Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create multiple stop gradient fragment shader?

I'm trying to create an OpenGL ES 2.0 fragment shader that outputs multiple stop gradient along one axis. It should interpolate between multiple colors at points defined in percents.

I've achieved this by using ifs the fragment shader, like this:

float y = gl_FragCoord.y;
float step1 = resolution.y * 0.20;
float step2 = resolution.y * 0.50;

if (y < step1) {
    color = white;
} else if (y < step2) {
    float x = smoothstep(step1, step2, y);
    color = mix(white, red, x);
} else {
    float x = smoothstep(step2, resolution.y, y);
    color = mix(red, green, x);
}

They say that branching in fragment shader can kill performance. Is there some clever trickery that can be used to interpolate between many values without using ifs? Is it actually worth it (this is highly subjective, I know, but as rule of thumb)?

To illustrate my problem, full source (still short though) in this GLSL Sandbox link: http://glsl.heroku.com/e#8035.0

like image 324
murgo Avatar asked Apr 10 '13 19:04

murgo


People also ask

How many times does fragment shader run?

Unless you have early depth testing enabled, a fragment is only discarded after you run the fragment shader. In this case, the frag shader would run once for every fragment in both quads, so 20000 times.

How does a vertex shader pass data to a fragment shader?

A vertex shader receives its input data from a vertex attribute. But how does a fragment shader gets its data? Data is passed from shader to shader by using the in and out keywords. You create an output shader variable by using the out keyword.

What is a fragment shader OpenGL?

A Fragment Shader is the Shader stage that will process a Fragment generated by the Rasterization into a set of colors and a single depth value. The fragment shader is the OpenGL pipeline stage after a primitive is rasterized. For each sample of the pixels covered by a primitive, a "fragment" is generated.

What do fragment shaders do?

Fragment shaders Fragment (or texture) shaders define RGBA (red, green, blue, alpha) colors for each pixel being processed — a single fragment shader is called once per pixel. The purpose of the fragment shader is to set up the gl_FragColor variable. gl_FragColor is a built-in GLSL variable like gl_Position .


1 Answers

If you want to eliminate branches you can do following (taken from Heroku);

color = mix(white, red, smoothstep(step1, step2, y));
color = mix(color, blue, smoothstep(step2, step3, y));
color = mix(color, green, smoothstep(step3, resolution.y, y));

But I'm not sure at all whether this is any faster than if/elses or not.

like image 134
harism Avatar answered Sep 27 '22 20:09

harism