sphere box test

This commit is contained in:
Jorijn van der Graaf 2026-03-07 20:20:06 +01:00
commit b1f9f44bbe

View file

@ -197,17 +197,41 @@ namespace Crafter {
constexpr bool IntersectionTestSphereOrientatedBox(Vector<T, 3, 0> spherePos, T sphereRadius, Vector<T, 3, 0> boxSize, MatrixRowMajor<T, 4, 3, 1> boxMat) {
Vector<T, 3, 0> d = spherePos - Vector<T, 3, 0>(boxMat.m[0][3], boxMat.m[1][3], boxMat.m[2][3]);
T distSq = 0.0f;
T distSq = T(0);
for (std::uint32_t i = 0; i < 3; ++i)
{
Vector<T, 3, 0> axis(boxMat.m[0][i], boxMat.m[1][i], boxMat.m[2][i]);
T dist = Vector<T, 3, 0>::Dot(d, axis);
T excess = std::fabs(dist) - boxSize.v[i];
excess = std::max(excess, 0.0f);
excess = std::max(excess, T(0));
distSq += excess * excess;
}
// Check sphere axes (world axes)
for (std::uint32_t i = 0; i < 3; ++i) {
Vector<T, 3, 0> axis = Vector<T, 3, 0>(0,0,0);
axis.v[i] = T(1);
T dist = Vector<T, 3, 0>::Dot(d, axis);
T excess = std::abs(dist) - sphereRadius;
excess = std::max(excess, T(0));
distSq += excess * excess;
}
// Check cross product axes
for (std::uint32_t i = 0; i < 3; ++i) {
for (std::uint32_t j = 0; j < 3; ++j) {
Vector<T, 3, 0> boxAxis(boxMat.m[0][i], boxMat.m[1][i], boxMat.m[2][i]);
Vector<T, 3, 0> sphereAxis = Vector<T, 3, 0>::Zero();
sphereAxis.v[j] = T(1);
Vector<T, 3, 0> axis = Vector<T, 3, 0>::Cross(boxAxis, sphereAxis);
T dist = Vector<T, 3, 0>::Dot(d, axis);
T excess = std::abs(dist) - (boxSize.v[(i+1)%3] * sphereRadius + boxSize.v[(i+2)%3] * sphereRadius);
excess = std::max(excess, T(0));
distSq += excess * excess;
}
}
return distSq <= sphereRadius * sphereRadius;
}
}