简体   繁体   English

如何使着色器淡出一种颜色?

[英]How to make a shader fade to a color?

This is the current shader I am using. 这是我正在使用的当前着色器。 It fades the object by slowly reducing the opacity. 它通过缓慢降低不透明度来淡化对象。 I want to fade to purple. 我想淡出紫色。 How can this be done? 如何才能做到这一点?

shader.frag: shader.frag:

uniform sampler2D texture;
uniform float opacity;

void main()
{
    vec4 pixel = texture2D(texture, gl_TexCoord[0].xy);
    gl_FragColor = pixel * vec4(1.0, 1.0, 1.0, opacity);
}

shader.vert: shader.vert:

void main()
{
    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
    gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;
    gl_FrontColor = gl_Color;
}

application of shader in main function: 着色器在主要功能中的应用:

sf::Shader shader;
if (!shader.loadFromFile("shader.vert", "shader.frag"))
    return EXIT_FAILURE;

float opacity = 1.0; //transparency of shader
shader.setParameter("texture", sf::Shader::CurrentTexture); //shader.vert
shader.setParameter("opacity", opacity);                    //shader.frag

//////////////////////////// ////////////////////////////

//Delete Text Display
    counter1 = 0;
    for (iter8 = textDisplayArray.begin(); iter8 != textDisplayArray.end(); iter8++)
    {
        if (textDisplayArray[counter1].destroy == true)
        {
            //shader
            opacity -= 0.1;         
            if (opacity <= 0)
            {
                textDisplayArray.erase(iter8);
                opacity = 1;
            }
            shader.setParameter("opacity", opacity);
        }

The RGB value for purple is vec3( 1.0, 0.0, 1.0 ) (maximum red, minimal green and maximum blue). 紫色的RGB值是vec3( 1.0, 0.0, 1.0 ) (最大红色,最小绿色和最大蓝色)。 You have to interpolate between your frgment color and the color value of purpel, similar as you do it with opacity . 您必须在您的frgment颜色和purpel的颜色值之间进行插值,就像使用opacity Use mix for this. 使用mix mix(x, y, a) performs a linear interpolation between x and y using a to weight between them. mix(x, y, a)执行之间的线性插值xy使用a在它们之间的重量。 The return value is computed as x×(1−a)+y×ax×(1−a)+y×a . 返回值计算为x×(1-a)+ y×ax×(1-a)+ y×a

uniform sampler2D texture;
uniform float opacity;
uniform float purpleFac;

void main()
{
    vec4 pixel = texture2D(texture, gl_TexCoord[0].xy);
    vec3 mixedCol = mix( vec3( 1.0, 0.0, 1.0 ), pixel.rgb, purpleFac );
    gl_FragColor = vec4( mixedCol , opacity );
}

Note you have to set uniform purpleFac similar as you do it with opacity . 请注意,您必须设置与opacity相似的均匀purpleFac purpleFac shoud be in range [0.0, 1.0]. purpleFac应该在[ purpleFac ]的范围内。 If purpleFac is 1.0 your fragment is colord purple and if it is 0.0 your fragment colol is the color of the texture only. 如果purpleFac1.0您的片段为purpleFac purple,如果为0.0 ,则片段colol仅为纹理的颜色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM