My InterlockedMin() call in a pixel shader returns... nonsense? [solved]

Hi,

I want to use a UAV in a Pixel Shader as a sort of manual depth-buffer, using atomic operations on a Compute Buffer.

I find that while InterlockedMin should work in Pixel Shaders, its behaviour is unpredictable.

The parameter that is meant to be the original value in memory before the operation does not seem to be correct. It seems as though there is a race condition, as if InterlockedMin() is not atomic at all.

I know this because the conditional based on the original value fails. Further, whatever is causing the behaviour in Unity, does it in the frame debugger as well - both Unity’s and RenderDoc! (see videos below)

Does anyone know what could cause this?

Things I have tried to resolve it:

  • RWByteAddressBuffer instead of RWStructuredBuffer
  • Different creation flags for ComputeBuffer
  • Using a RenderTexture instead of a ComputeBuffer
  • Using the globallycoherent prefix
  • Clearing the buffer in the pixel shader then syncing with a DeviceMemoryBarrier() call
  • Clearing the buffer in the pixel shader every other frame with a CPU set flag
  • Using a different atomic (InterlockedMax())
  • Using a different slot and/or binding calls

I have attached a simple example that demonstrates the problem.

Here is a video of the ‘Z’-fighting: https://vid.me/tUP8
And the behaviour in RenderDoc: https://vid.me/4Fir

3036854–227308–Atomics Bug Minimum Working Example.zip (49.7 KB)

If anyone else has this issue, it is a thread-safety bug spotted by richardurich on GameDev. The InterlockedMin() function works fine, but it is not safe to use the result in a conditional because there is no guarantee that the Interlocked call and the resulting writes due to the conditionals will occur in order.

You can use UNITY_FLATTEN to prevent the branch.

Interesting, thanks bgolus!