Search code examples
glslshaderwebglshadertoy

GLSL Shadertoy, how to storage variables data?


How to use variable in GLSL on https://www.shadertoy.com/new for all call?

Variables float buffer; or vec2 buffer2[1024]; cleaned for each mainImage() call.

Yes, i can save data to video buffer fragColor = data; and get it vec3 buf = texture(iChannel0, fragCoord / iResolution.xy).rgb; but it is so hard.

How to save data to normal variables and use it?


Solution

  • Shadertoy doesn't support storage for variables. That's kind of the whole point. Shadertoy is a fun puzzle of "how do I make pretty pictures with nothing but a function that takes only a pixel position and time as input". It is not remotely about best practices or flexible programming with variables. The fact that it's hard is also the point as in "OMG! You managed to do that with no variables! Amazing!!"

    To store anything in shadertoy across frames you have to write to a texture. You choose locations in the texture for each thing you want to store and then write the appropriate shader code to read

    vec4 values = textureFetch(texture, pixelCoordOfVariable, 0);
    

    And write

    if (int(gl_FragCoord.x) == pixelCoordOfVariable.x &&
        int(gl_FragCoord.y) == pixelCoordOfVariable.y) {
      fragColor = valueToStore;
    }
    

    Performant and flexible WebGL apps generally do not use the techniques on shadertoy.

    If you look at this shadertoy shader and click on the "common" tab you'll see constants where they define which pixels to store variables in. You can then look for the usages of those constants in the code.