Skip to content

Instantly share code, notes, and snippets.

@marmakoide
Created November 15, 2022 10:14
Show Gist options
  • Save marmakoide/421b7e90083214ce9f334637df0717e7 to your computer and use it in GitHub Desktop.
Save marmakoide/421b7e90083214ce9f334637df0717e7 to your computer and use it in GitHub Desktop.
Check if an axis aligned bounding box intersects the triangle [ABC]. Box extents are half the size of the box
def aabox_triangle_3d_intersecting(box_center, box_extents, ABC):
# Algorithm described in "Fast 3D Triangle-Box Overlap Testing" by Tomas Akenine-Moller
ABC = ABC - box_center
UVW = numpy.roll(ABC, -1, axis = 0) - ABC
# Check along triangle edges
for K in UVW:
P = numpy.dot(ABC, numpy.array([0, -K[2], K[1]]))
if max(-numpy.amax(P), numpy.amin(P)) > box_extents[1] * numpy.fabs(K[2]) + box_extents[2] * numpy.fabs(K[1]):
return False
for K in UVW:
P = numpy.dot(ABC, numpy.array([K[2], 0, -K[0]]))
if max(-numpy.amax(P), numpy.amin(P)) > box_extents[0] * numpy.fabs(K[2]) + box_extents[2] * numpy.fabs(K[0]):
return False
for K in UVW:
P = numpy.dot(ABC, numpy.array([-K[1], K[0], 0]))
if max(-numpy.amax(P), numpy.amin(P)) > box_extents[1] * numpy.fabs(K[0]) + box_extents[0] * numpy.fabs(K[1]):
return False
# Check along cube faces
if numpy.any(numpy.amin(ABC, axis = 0) > box_extents):
return False
if numpy.any(numpy.amax(ABC, axis = 0) < -box_extents):
return False
# Check distance to the A, B, C plane
N = numpy.cross(UVW[0], UVW[1])
if numpy.fabs(numpy.dot(N, ABC[0])) > numpy.dot(box_extents, numpy.fabs(N)):
return False
# Job done
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment