Search Unity

Question Trouble converting float2 to index in Compute Shader

Discussion in 'Shaders' started by UserNobody, Apr 3, 2021.

  1. UserNobody

    UserNobody

    Joined:
    Oct 3, 2019
    Posts:
    144
    Hello, I'm having trouble converting float2 to a one dimensional index value.

    I want to use an input color array instead of a source texture, so I fetched source texture pixels and have stored them in the color array. I then sent an input buffer containing those colors to a Compute Shader, which I then want to use for sampling.

    However, for some reason when I try to sample a color from an array I get a really strange result:



    Although, if I use a source image instead, I get a desired result:



    Below is the Compute Shader code I use.

    Code (CSharp):
    1. Texture2D<float4> source; //A source texture.
    2.  
    3. StructuredBuffer<float4>   input; //An array of colors that contain source image pixels.
    4. RWStructuredBuffer<float4> output; //An output color array.
    5.  
    6. int width; //Result image width.
    7. int height; //Result image height.
    8.  
    9. Buffer<float> sc; //Pre-computed sin and cos values.
    10.  
    11. [numthreads(1, 1, 1)]
    12. void Rotate(uint3 id : SV_DispatchThreadID)
    13. {
    14.     int w = width;
    15.     int h = height;
    16.  
    17.     float2x2 r2 = float2x2(sc[1], -sc[0], sc[0], sc[1]);
    18.  
    19.     float2 center = float2(w, h) / 2;
    20.     float2 pos = mul(r2, id - center) + center;
    21.  
    22.     if (min(pos.x, pos.y) < 0 || max(pos.x - w, pos.y - h) >= 0 || id.x >= width || id.y >= height)
    23.     {
    24.         output[id.x + id.y * w] = float4(0, 0, 0, 0);
    25.     }
    26.     else
    27.     {
    28.         output[id.x + id.y * w] = source[pos.xy]; //Works
    29.         output[id.x + id.y * w] = input[pos.x + pos.y * w]; //Doesn't work
    30.     }
    31. }
    Can someone please help me? I'm not sure what am I doing wrong here... :/
     
    Last edited: Apr 3, 2021