简体   繁体   中英

Color a set of fragments in fragment shader

My goal is to color a set of fragments determined by the interpolation between two points. Below the code I've written, It didn't work...

I also added some comments, Probably there are some mistakes I made or something that I misunderstood.

Thank you for your help.

#ifdef GL_ES
precision highp float;
#endif

uniform vec2 u_resolution;

void main(){
    vec2 position = gl_FragCoord.xy / u_resolution;
    vec4 color = vec4(0.97, 0.1, 0.53, 1.0);
    
    // center (hopefully)
    vec2 P1 = vec2(0.0,0.0);
    // top right
    vec2 P2 = vec2(1.0,1.0);
    
    // generate 100 points between P1...P2
    for(float i = 0.0; i < 1.0; i+=0.01) {
        float lerpX = mix(P1.x, P2.x, i);
        float lerpY = mix(P1.y, P2.y, i);
        vec2 interpolatedPoint = vec2(lerpX, lerpY);

        // check if current fragment is one of the
        // interpolated points and color it
        if (position.x == interpolatedPoint.x) {
            gl_FragColor = color;
        } else {
            discard;
        }
    }
}

position.x == interpolatedPoint.x is a floating point comparison and is almost never evaluated as true. Your code discards all fragments. Implement a floating point comparison. Calculate the absolute value of the difference between the two values and compare it with an epsilon:

if (distance(position, interpolatedPoint) <= 0.01) {
    gl_FragColor = color;
}

WORKING SOLUTION

#ifdef GL_ES
precision highp float;
#endif

uniform vec2 u_resolution;

void main(){
    vec2 position = gl_FragCoord.xy / u_resolution;
    vec4 color = vec4(0.97, 0.1, 0.53, 1.0);
    
    // center (hopefully)
    vec2 P1 = vec2(0.0,0.0);
    // top right
    vec2 P2 = vec2(1.0,1.0);
    
    // generate 100 points between P1...P2
    for(float i = 0.0; i < 1.0; i+=0.01) {
        float lerpX = mix(P1.x, P2.x, i);
        float lerpY = mix(P1.y, P2.y, i);
        vec2 interpolatedPoint = vec2(lerpX, lerpY);

        // check if current fragment is one of the
        // interpolated points and color it
        if (distance(position, interpolatedPoint) <= 0.01) {
            gl_FragColor = color;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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