Ray-mesh intersection queries
What it does
Three TBPs that wrap the AABB-tree-accelerated ray-versus-surface intersection in flavours that match the canonical use cases:
intersect_ray_first— closest hit (best-first traversal witht_bestpruning). For picking (which facet did the ray hit?).intersect_ray_all— every hit, sorted ascending byt. For visibility counting and inside / outside ray-cast tests.intersect_ray_any— early-exit "is there any hit withinmax_t?" For shadow rays and conservative inside-test rejection.
All three share one exact ray-facet test (issue #82) and the same AABB tree traversal pattern (the enumerate_children dispatcher used by §1.4 and §1.2). Both SAH BVH and octree tree kinds are supported transparently. Every hit is decided exactly, so a ray crosses the surface once per crossing: through a shared edge or vertex it hits one of the facets there, and on a closed surface the parity of the hit count is the state of the origin.
Picking: from an eye point in front of the dragon, 35 rays aimed at a grid over its box. 23 hit, and intersect_ray_first returns the first hit of each (gold) and the facet it picked (ember); the other 12 miss. The figure is drawn by docs/examples/src/fig_ref_ray_queries_picking.f90.
Pipeline
For each query:
- Tree traversal. Starting from the root, walk down to leaves whose AABB the ray pierces. The slab-test produces a
[t_near, t_far]interval per box; subtree pruning usest_nearfor ordering. The boxes are padded by 1e-9 of the ray's extent over the surface box (and, for the octree, by the facets' reach: an octree node holds the facets whose centroid it contains, which stick out of its box), so no crossing is lost to round-off at a box face. - Per-leaf facet sweep. For each owned facet, the exact test of
fossil_ray_query. The ray is the line through the originoand a far pointq = o + s·dbeyond the surface box (rounded once, the same for every facet). It crosses triangle ABC iff the three side testsorient3d(o, q, A, B),(o, q, B, C),(o, q, C, A)have one sign; a zero (the ray meets an edge's line) is settled by one symbolic perturbation of the ray, the same for every facet, so the two facets of an edge always see it on opposite sides. An axis-aligned ray takes the kernel ofline_crossingsinstead (the global perturbation of issue #69), so it agrees with the line queries and the cut cells. The crossing is ahead iffoandqlie on opposite sides of the facet's plane (orient3d, exact);titself is rounded, from the barycentric weights of the side tests. - Per-flavour assembly:
_first— keep the smallestt ≥ 0; prune any subtree whoset_near ≥ t_best._all— accumulate every hit witht ≥ 0; sort ascending._any— return on the first hit witht ∈ [0, max_t]; prune any subtree whoset_near > max_t.
A flat-O(N) fallback exists for surfaces without a built AABB tree; it operates on facet(:) directly. Standard surfaces from load_from_file always have a tree, so the fallback rarely fires.
One of those hits, seen through the per-facet Möller-Trumbore test facet%intersect_ray (the queries decide the hit exactly, as step 2 says, but the parameter is the same): t = 0.8543 and (u, v), the weights (0.340, 0.432, 0.228) of vertices 1, 2 and 3. Each weight is the area fraction of the sub-triangle opposite its vertex (shaded). The point at t along the ray and the barycentric point agree with hit%point within 1e-12.
API
Closest hit
call surface%intersect_ray_first(ray_origin, ray_direction, hit, has_hit, status, exclude)
class(surface_stl_object), intent(in) :: self
type(vector_R8P), intent(in) :: ray_origin
type(vector_R8P), intent(in) :: ray_direction ! need not be unit
type(ray_hit_t), intent(out) :: hit ! valid iff has_hit
logical, intent(out) :: has_hit
integer(I4P), intent(out), optional :: status ! RAY_STATUS_*
integer(I4P), intent(in), optional :: exclude ! facet to skip (issue #62)hit carries %facet_id, %t, %point (= ray_origin + t·ray_direction). Always check has_hit first — hit is undefined when has_hit = .false..
All hits
call surface%intersect_ray_all(ray_origin, ray_direction, hits, status, exclude)
type(ray_hit_t), allocatable, intent(out) :: hits(:)
integer(I4P), intent(in), optional :: exclude ! facet to skip (issue #82)hits is always allocated (zero-length if no hits found), sorted ascending by t (then by facet id), with one hit per crossing of the surface. exclude drops one facet, as for _first: the facet a ray is cast from.
The ray above, along +x from (−14, −1.5, 7.857), passes through the dragon five times: 10 hits from t = 6.629 to 22.151, entries and exits alternating (the program tells them by the sign of the facet normal's x component). The exit at t = 17.967 and the entry at t = 17.987 are 0.020 apart: a narrow gap between two parts of the body.
Any hit (shadow ray)
call surface%intersect_ray_any(ray_origin, ray_direction, max_t, found, status)
real(R8P), intent(in), optional :: max_t ! default MaxR8P
logical, intent(out) :: foundReturns immediately on the first hit with 0 ≤ t ≤ max_t. Default max_t accepts any forward hit. Pass the Euclidean distance to a target point (when direction is unit) to test occlusion of that target.
Above, each of the 6860 cells of the ground casts one shadow ray towards the light, with no max_t (the light is at infinity); 2267 are blocked. A blocked ray returns at its first hit, wherever it is in the tree.
Example
The cookbook casts one ray at the dragon. This program runs the three queries on the unit cube cube-01.stl, then the two cases where the surface's own edges matter:
use fossil, only : surface_stl_object, ray_hit_t, RAY_STATUS_OK
use fossil_facet_object, only : facet_object
use penf, only : I4P, R8P
use vecfor, only : vector_R8P, ex_R8P
implicit none
type(surface_stl_object) :: cube
type(ray_hit_t) :: hit
type(ray_hit_t), allocatable :: hits(:)
type(facet_object), pointer :: f
type(vector_R8P) :: origin
logical :: has_hit, blocked
integer(I4P) :: status, k, own
call cube%load_from_file(file_name='cube-01.stl', guess_format=.true.)
origin = vector_R8P(-1._R8P, 0.3_R8P, 0.6_R8P)
call cube%intersect_ray_first(ray_origin=origin, ray_direction=ex_R8P, hit=hit, has_hit=has_hit, status=status)
print '(A,L1,A,I0,A,F6.3,A,3F6.3)', 'first: ', has_hit, ', facet ', hit%facet_id, ', t ', hit%t, ', point ', &
hit%point%x, hit%point%y, hit%point%z
call cube%intersect_ray_first(ray_origin=origin, ray_direction=2._R8P * ex_R8P, hit=hit, has_hit=has_hit)
print '(A,F6.3)', 'first, direction 2 ex: t ', hit%t ! parametric: half the distance
call cube%intersect_ray_all(ray_origin=origin, ray_direction=ex_R8P, hits=hits)
do k = 1, size(hits)
f => cube%facet_at(hits(k)%facet_id)
print '(A,I0,A,I0,A,F6.3,A,A)', 'all: hit ', k, ', facet ', hits(k)%facet_id, ', t ', hits(k)%t, ', ', &
merge('enters', 'leaves', f%normal%dotproduct(ex_R8P) < 0._R8P)
enddo
do k = 1, 3 ! max_t = 0.5, 1, 1.5
call cube%intersect_ray_any(ray_origin=origin, ray_direction=ex_R8P, max_t=0.5_R8P * k, found=blocked)
print '(A,F4.1,A,L1)', 'any: within t <= ', 0.5_R8P * k, ': ', blocked
enddoorigin = vector_R8P(0._R8P, 0.3_R8P, 0.6_R8P) ! on the face x = 0
call cube%intersect_ray_first(ray_origin=origin, ray_direction=ex_R8P, hit=hit, has_hit=has_hit)
print '(A,I0,A,F6.3)', 'origin on the surface: first facet ', hit%facet_id, ', t ', hit%t
own = hit%facet_id
call cube%intersect_ray_first(ray_origin=origin, ray_direction=ex_R8P, hit=hit, has_hit=has_hit, exclude=own)
print '(A,I0,A,F6.3)', ' the same, that facet excluded: facet ', hit%facet_id, ', t ', hit%t
call cube%intersect_ray_all(ray_origin=origin, ray_direction=ex_R8P, hits=hits)
print '(A,I0,A,2F6.3)', ' all: ', size(hits), ' hits, t', hits(:)%t
call cube%intersect_ray_all(ray_origin=origin, ray_direction=ex_R8P, hits=hits, exclude=own)
print '(A,I0,A,F6.3)', ' all, that facet excluded: ', size(hits), ' hit, t', hits(1)%t
origin = vector_R8P(-1._R8P, 0.3_R8P, 0.3_R8P) ! through the edge of two facets
call cube%intersect_ray_all(ray_origin=origin, ray_direction=ex_R8P, hits=hits)
print '(A,I0,A,2I4)', 'through a shared edge: ', size(hits), ' hits, facets', hits(:)%facet_id
origin = vector_R8P(-1._R8P, 0.5_R8P, 0.5_R8P) ! through the vertex of four facets
call cube%intersect_ray_all(ray_origin=origin, ray_direction=ex_R8P, hits=hits)
print '(A,I0,A,2F6.3)', 'through the face centres: ', size(hits), ' hits, t', hits(:)%t$ ref_ray_queries
first: T, facet 44, t 1.000, point 0.000 0.300 0.600
first, direction 2 ex: t 0.500
all: hit 1, facet 44, t 1.000, enters
all: hit 2, facet 38, t 2.000, leaves
any: within t <= 0.5: F
any: within t <= 1.0: T
any: within t <= 1.5: T
origin on the surface: first facet 44, t 0.000
the same, that facet excluded: facet 38, t 1.000
all: 2 hits, t 0.000 1.000
all, that facet excluded: 1 hit, t 1.000
through a shared edge: 2 hits, facets 48 40
through the face centres: 2 hits, t 1.000 2.000_firstreturns the facet,tand the point. With the direction2 exthe same point hast = 0.5:tis parametric, not a length._allreturns the entry att = 1and the exit att = 2, sorted. Which is which is not in the record: the sign of the hit facet's normal against the direction tells it._anywithmax_t = 1finds the hit at exactlyt = 1: the bound is inclusive.- An origin on the surface is hit at
t = 0: hits att = 0are kept, by_first,_alland_anyalike. The crossing is at the origin, so it is a hit; whether the ray then enters or leaves depends on the direction. To leave the facet the ray starts from, pass it asexclude(to_firstor_all): the next hit is the far face att = 1. - A ray through a shared edge hits one of its two facets: 2 hits for 2 crossings. Through the face centres, where four facets meet at a vertex, it hits one of the four: 2 hits again (12 before issue #82). A parity count needs no merging: on a closed surface, an odd number of hits means the origin is inside, whatever edges and vertices the ray passes through, and a ray that only touches the surface at an edge or lies in a face plane counts 0 or 2. The
fossil_test_ray_crossingstest checks it on rays along the grid lines of a marching-cubes sphere, the diagonals of the cube's faces and aimed at mesh vertices: parity equalsis_point_insideon every one.
Known limitations
- Direction need not be unit.
tis the parametric position (origin + t·direction), not the Euclidean distance, whendirectionisn't unit. Normalize the direction yourself if you wanttto mean Euclidean distance. - Hits exactly at
t = 0(origin on the surface) are returned by_first,_alland_any, as the example shows. For a ray cast from a facet, pass that facet asexcludeto_firstor_all(no origin offset needed); a ray from a point on an edge or vertex still hits one of the other facets there att = 0. tis rounded, the hit decisions are exact: two crossings closer than round-off keep their order by facet id when theirtare equal.- Boundary-touching cases at
t = max_tare included by_any(the contract ist ≤ max_t, inclusive). - Two latent slab-test bugs in the underlying AABB ray test were fixed during the §2.5 implementation: a parallel-ray classifier that misread
EPS = 0.0as "negative directions are parallel," and a slab-interval accumulator that tookmaxof far-plane crossings instead ofmin. The pre-§2.5 ray-cast inside-test sign algorithm worked anyway — the bugs only inflated AABB-hit counts; the per- facet test downstream filtered correctly. The fix made the inside- test sign algorithm strictly faster and unblocked the new intersect_ray_* TBPs.
See also
facet%intersect_ray— the per-facet Möller-Trumbore test, with barycentrics. Useful against a single triangle; the surface queries use the exact test instead (issue #82).- SDF segmentation — the cone-of-rays SDF query uses
intersect_ray_firstfor every cone ray. ray_hit_t— the record type returned by the queries.- Constants —
RAY_STATUS_*.
References
- Möller & Trumbore, Fast, Minimum Storage Ray-Triangle Intersection, Journal of Graphics Tools 2(1), 1997.
facet%intersect_ray. - Woop, Benthin & Wald, Watertight Ray/Triangle Intersection, Journal of Computer Graphics Techniques 2(1), 2013. The side tests, made exact here with
orient3dand a symbolic perturbation. - Smits, Efficient Bounding Box Intersection, Ray Tracing News 15(1), 2002. The slab-based AABB ray test.
- Williams, Barrus, Morley & Shirley, An Efficient and Robust Ray-Box Intersection Algorithm, J. of Graphics Tools 10(1), 2005. Refinement of Smits' slab test that handles the parallel-ray case correctly (the formulation FOSSIL adopts after the §2.5 fix).