Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DirectCompute atomic counter

In a compute shader (with Unity) I have a raycast finding intersections with mesh triangles. At some point I would like to return how many intersections are found.

I can clearly see how many intersections there are by marking the pixels, however if I simply increment a global int for every intersection in the compute shader (and return via a buffer), the number I get back makes no sense. I assume this is because I'm creating a race condition.

I see that opengl has "atomic counters" : https://www.opengl.org/wiki/Atomic_Counter, which seem like what I need in this situation. I have had no luck finding such a feature in either the Unity nor the DirectCompute documentation. Is there a good way to do this?

I could create an appendBuffer, but it seems silly as I literally need to return just a single int.

like image 606
Aaron Krajeski Avatar asked Feb 20 '15 21:02

Aaron Krajeski


1 Answers

HA! That was easy. I'll leave this here just in-case someone runs into the same problem. HLSL has a whole set of "interlocked" functions that prevent this sort of thing from happening:

https://msdn.microsoft.com/en-us/library/windows/desktop/ff476334(v=vs.85).aspx

In my case it was:

InterlockedAdd(collisionCount, 1);

To replace

collisionCount++;

And that's it!

like image 69
Aaron Krajeski Avatar answered Nov 09 '22 03:11

Aaron Krajeski