Transform Feedback: Only write into buffer when condition is met

I try to implement a ray-triangle-intersection test in the geometry shader and get the intersection data back to my application with a transform feedback buffer.

Now I have the following problem:

Let’s say I have a 3d-object consisting of 10’000 triangles. The geometry shader performs an intersection test with a ray that is given as a uniform variable for each of these triangles. It then writes the result of the intersection calculation again FOR EACH triangle in the transform feedback buffer. So the buffer is filled with the intersection data for 10’0000 triangles, of which 9999 triangles dont get hit by the ray. I would very much like to tell the shader to only write values in the buffer if there is an intersection.

Is there a way to tell the shader NOT to write into the feedback buffer under certain conditions? Of course I could let it write 0 for every triangle that has no intersection and then search the buffer for values that are not 0, but that seems a big waist to me.

What you’re looking for is selective emission using transform feedback and a geometry shader.

That is, only call EmitStreamVertex() for executions where you’ve got a hit.

For more details, see: