ray sphere test

This commit is contained in:
Jorijn van der Graaf 2026-02-11 04:28:54 +01:00
commit 2daa51680a
3 changed files with 29 additions and 7 deletions

View file

@ -54,4 +54,25 @@ namespace Crafter {
return inverse_determinant * Vector<T, 3, 0>::Dot(edge2, q);
}
export template<typename T>
constexpr T IntersectionTestRaySphere(Vector<T, 3, 0> position, T radius, Vector<T, 3, 0> rayOrigin, Vector<T, 3, 0> rayDir) {
T a = Vector<T, 3, 0>::Dot(rayDir, rayDir);
T b = Vector<T, 3, 0>::Dot(rayDir, (T(2) * (rayOrigin - position)));
T c = Vector<T, 3, 0>::Dot(position, position) + Vector<T, 3, 0>::Dot(rayOrigin, rayOrigin) - T(2) * Vector<T, 3, 0>::Dot(rayOrigin, position) - radius * radius;
T d = b * b + (T(-4)) * a * c;
if (d < 0) {
return std::numeric_limits<T>::max();
}
d = std::sqrt(d);
float t = (T(-0.5)) * (b + d) / a;
if (t > T(0)) {
return t;
} else {
return std::numeric_limits<T>::max();
}
}
}

View file

@ -347,4 +347,10 @@ struct std::formatter<Crafter::Vector<T, 4, Aligment>> : std::formatter<std::str
obj.x, obj.y, obj.z, obj.w
), ctx);
}
};
};
template <typename T, std::uint32_t Len, std::uint32_t Aligment, typename BT>
constexpr Crafter::Vector<T, Len, Aligment> operator*(BT b, const Crafter::Vector<T, Len, Aligment>& v) {
return v * b;
}

View file

@ -4,10 +4,5 @@ import std;
using namespace Crafter;
int main() {
Vector<float, 3, 0> test(1,2,3);
Vector<float, 3, 0> test2(1,2,3);
Vector<float, 3, 0> test3(1,2,3);
Vector<float, 3, 0> test4(1,2,3);
Vector<float, 3, 0> test5(1,2,3);
std::cout << IntersectionTestRayTriangle(test, test2, test3, test4, test5) << std::endl;
std::cout << IntersectionTestRaySphere<float>({0,0,0}, 10, {0,0,-100}, {0,1,0}) << std::endl;
}