Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Blending with a Compute Shader, Possible?

Discussion in 'Shaders' started by MadWatch, Jun 9, 2020.

  1. MadWatch

    MadWatch

    Joined:
    May 26, 2016
    Posts:
    112
    Hello Everyone

    I'm a noob when it comes to compute shaders, so I don't really know how to do what I want to do.

    I want to write a texture with a compute shader. For each pixels of the texture I need to have N threads to compute a value, and then I need to combine the N values from the N threads to get the final color of the pixel.

    A naive implementation would look something like this:
    Code (CSharp):
    1. RWTexture2D<float4> output;
    2.  
    3. void DoStuff(uint3 dispatchThreadId : SV_DispatchThreadID)
    4. {
    5.   float4 result;
    6.  
    7.   ... Compute result here ...
    8.  
    9.   output[uint2(dispatchThreadId.x, dispatchThreadId.y)] += result; // Notice the +
    10. }
    So this is kind of a blend add of my N results into a single pixel. For this to work, I would need a kind of atomic add for my += operation. But it doesn't look like atomic operations are possible on texture (if it is then I didn't find how to do it).

    Also, most of my theads are going to return before they compute anything. Only a few of them are going to contribute to the final result. So allocating a huge buffer that is N times the size of my texture would be a waste of GPU RAM. Most of it just won't be used. I would like to find a better way if at all possible.

    How would you do it?

    Thanks.