Search Unity

Compute shader to uniform/global shader variables (buffers? no idea how do you use them??)

Discussion in 'Shaders' started by AverageCG, Dec 8, 2019.

  1. AverageCG

    AverageCG

    Joined:
    Nov 13, 2017
    Posts:
    19
    Hey all,

    Tl;dr : I'm having trouble figuring out how to pass data from compute shader to global shader variable / buffers (and also what are buffers exactly and how to use them etc.)

    edit: As a simplified example, how would i go about it if i wanted to compute a single value from let's say summing up all the pixel values in a texture and make the result accessible to all shaders or even just all materials using a certain shader?

    I'm working on a study project where i need to render an image, do some computation on each pixel and store the result in a global shader variable that in the end should probably update at least every few frames. Currently I am doing all those calculations on the CPU in a simple c# script where i read from the render texture and pass data via Shader.setglobal- float, -vector, -vectorarray() however this has a tremendous overhead and everything seems to say that i'll need compute shaders to do this more efficiently and prevent having to pass data between CPU and GPU.

    Am I understanding this correctly? For the entire frame and all the computations (multiple render textures have to be dealt with) The profiler shows that Gfx.readbackimage takes about 68ms (about 1ms each [very small] texture) and gc.alloc about 19ms.

    Now i'm still fairly ignorant when it comes to the gritty detail of CG and especially new to compute shaders. I've tried looking into compute shaders and cbuffers but i couldn't really find any tutorials or clear documentation on how one could get the results of some compute operation into shader variables. My idea currently is have the rendertextures be directly handled by a shader that then sets global shader variables or buffers(?) however the use of structured buffers / constant buffers (or what have we) is also simply obscure to me. How do i initialize them how do i "structure" them ?

    Most compute shader stuff I found simply deals with rendertextures and outputs another texture or something along those lines that is then assigned to a material. How would i go about computing multiple variables like array's of floats float4's or anything really and make them accessible to all shaders/ materials?

    Sorry for my rambling/ i'm a little confused on the whole topic :oops: appreciate any pointers and thanks for your time :)
     
    Last edited: Dec 8, 2019