如何在片段着色器中叠加线性渐变上的径向渐变?

时间:2015-08-13 15:46:20

标签: android ios opengl-es-2.0 fragment-shader

我被片段着色器困住了。我设法从上到下显示线性渐变(cp。左图)。目标是将径向白色渐变覆盖到此线性渐变(如左图中的黑色虚线=>右图显示目标)。

我知道我必须以某种方式将x和y坐标结合起来,但到目前为止所有的试验都失败了 - 我认为我的数学太糟糕了: - /我也没想出如何混合蓝色颜色以达到白色阴影。

有人可以帮我提示吗?

enter image description here

这是当前着色器,它将左图像作为结果(取决于颜色制服):

// Precision
precision highp float;
// Uniforms
uniform vec2 uResolution;
// Colors
uniform vec3 uColor1;
uniform vec3 uColor2;

void main(void) {
    vec2 position = gl_FragCoord.xy/uResolution;
    vec3 color = vec3(uColor2.x+(uColor1.x-uColor2.x)*position.y, uColor2.y+(uColor1.y-uColor2.y)*position.y, uColor2.z+(uColor1.z-uColor2.z)*position.y);
    gl_FragColor = vec4(color.x, color.y, color.z, 1.);
}

1 个答案:

答案 0 :(得分:3)

以下是一些可以满足您需求的代码:

// Precision
precision highp float;
// Uniforms
uniform vec2 uResolution;
// Colors
uniform vec3 uColor1;
uniform vec3 uColor2;

// parameters of the radial gradient
uniform vec2  uRadialFxCenter; // this should be in [0-1], so normalized screen coords
uniform float uRadialFxRadius; // this should be in [0-1], so normalized screen coords
uniform vec3 uRadialFxColor;    // should be white
uniform float uRadialFxOpacity; // between [0-1]

void main(void) {
    vec2 position = gl_FragCoord.xy/uResolution;
    vec3 color = vec3(uColor2.x+(uColor1.x-uColor2.x)*position.y, 
                      uColor2.y+(uColor1.y-uColor2.y)*position.y, 
                      uColor2.z+(uColor1.z-uColor2.z)*position.y);

    // compute radial fx opacity => alpha
    vec2 posToRadialFxCenter = uRadialFxCenter - position;
    float distToCenterNormalized = min((length(posToRadialFxCenter)/uRadialFxRadius), 1.0);
    float alpha = (1.0-distToCenterNormalized) * uRadialFxOpacity;

    // alpha blending radialFxColor / color 
    color = color * (1.0-alpha) + uRadialFxColor * alpha;

    //
    gl_FragColor = vec4(color.x, color.y, color.z, 1.);
}

您还可以控制"斜率"通过添加这样的东西,径向梯度消失:

distToCenterNormalized = pow(distToCenterNormalized, slope);