How to create multiple stop gradient fragment shader?

老子叫甜甜 提交于 2019-12-04 11:22:03

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/15935117/how-to-create-multiple-stop-gradient-fragment-shader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!