terminateRayEXT Behavior in GLSL Any-Hit Shaders

The terminateRayEXT function in GLSL ray tracing shaders immediately halts the traversal of the current ray and accepts the current hit. When invoked within an any-hit shader, it causes the current shader invocation to stop execution instantly, skips any remaining primitive or acceleration structure intersections along the ray, and proceeds directly to resolving the accepted hit. This mechanism provides programmable, early-out termination for rays where finding a single valid hit is sufficient.

Immediate Invocation Termination

When terminateRayEXT() is called, the execution flow within the calling any-hit shader invocation halts at that exact point. Any instructions placed after the call within the shader body are discarded and will not execute. In SPIR-V, this maps directly to OpTerminateRayKHR, which acts as a terminating instruction for the current execution thread.

Traversal Halting and Hit Acceptance

Beyond stopping the local shader invocation, terminateRayEXT() affects the broader ray tracing pipeline:

  • Hit Confirmation: The intersection being evaluated is officially accepted as a confirmed hit.
  • Aborted Traversal: The traversal engine stops testing further bounding boxes and primitives for that ray. No additional intersection shaders or any-hit shaders will be launched for the remainder of the ray's query.

Interaction with Ignore Intersection

Calling ignoreIntersectionEXT() explicitly rejects a hit and continues ray traversal. If both functions exist in branching logic, they are mutually exclusive based on path execution. However, calling terminateRayEXT() implicitly accepts the hit; it should not be paired with ignoreIntersectionEXT() in the same execution path, as doing so creates contradictory pipeline instructions.

Downstream Pipeline Execution

Once traversal is terminated via terminateRayEXT(), the pipeline moves to the completion phase:

  • If ray traversal terminates and the accepted hit is the closest (or the only required) hit, the corresponding closest-hit shader executes, provided one is defined.
  • If the ray was dispatched with flags that suppress closest-hit shaders (such as gl_RayFlagsSkipClosestHitShaderEXT), execution control returns directly to the ray generation shader or the caller of traceRayEXT.

Typical Use Case: Alpha-Tested Occlusion

The primary application of terminateRayEXT() in an any-hit shader is evaluating transparent or cut-out geometry during shadow (occlusion) ray passes. The shader samples a texture to evaluate alpha transparency; if the fragment is transparent, it calls ignoreIntersectionEXT() to keep traversing. If the fragment is fully opaque, it calls terminateRayEXT() to instantly confirm occlusion and stop traversing, avoiding unnecessary intersection tests for the rest of the scene.