Search code examples
c#openglglslopentkcoordinate-transformation

Projection is not working when cutting particular area from top and bottom of openGL control


With the help of this link i can apply projection on my texture. Now I want to cut/remove equal area from top and bottom of my glcontrol and then need to apply same projection on remain area. I have tried like below. But as shown in the image top and bottom curve is missing on projection. How can I bring it back in remain area?

precision highp float;
uniform sampler2D sTexture;
varying vec2 vTexCoord;
void main()
{
    float img_h_px  = 432.0; // height of the image in pixel
    float area_h_px = 39.0;  // area height in pixel

    float w = area_h_px/img_h_px;
    if (vTexCoord.y < w || vTexCoord.y > (1.0-w)){
        gl_FragColor= vec4(1.0,0.0,1.0,1.0);
    }
    else
    {
        vec2  pos     = vTexCoord.xy * 2.0 - 1.0;
        float b       = 0.5;
        float v_scale = (1.0 + b) / (1.0 + b * sqrt(1.0 - pos.x*pos.x));

        float u = asin( pos.x ) / 3.1415 + 0.5;
        float v = (pos.y * v_scale) * 0.5 + 0.5;
        if ( v < 0.0 || v > 1.0 )
            discard;

        vec3 texColor = texture2D( u_texture, vec2(u, v) ).rgb;
        gl_FragColor  = vec4( texColor.rgb, 1.0 );
    }    
}


Solution

  • The size of bottom and top area (sum of bottom and top area), relative to the size of the control is 2.0*area_h_px/img_h_px = 2.0*w. The ration (h_ratio) of the control size and the "visible" area is:

    float w = area_h_px/img_h_px;
    float h_ratio = 1.0 - 2.0*w;
    

    You've to scale the y coordinate for the texture lookup by the ration of the "visible" area and the control size, this is reciprocal of h_ratio (1.0/h_ratio):

    float v = (pos.y * v_scale / h_ratio) * 0.5 + 0.5;
    

    Final shader:

    precision highp float;
    uniform sampler2D sTexture;
    varying vec2 vTexCoord;
    
    void main()
    {
        float img_h_px  = 432.0; // height of the image in pixel
        float area_h_px = 39.0;  // area height in pixel
        float w = area_h_px/img_h_px;
        float h_ratio = 1.0 - 2.0*w;
    
        vec2  pos     = vTexCoord.xy * 2.0 - 1.0;
        float b       = 0.5;
        float v_scale = (1.0 + b) / (1.0 + b * sqrt(1.0 - pos.x*pos.x));
    
        float u = asin(pos.x) / 3.1415 + 0.5;
        float v = (pos.y * v_scale / h_ratio) * 0.5 + 0.5;
    
        vec3 texColor = texture2D(sTexture, vec2(u, v)).rgb;
    
        vec4 color = vec4(texColor.rgb, 1.0);
        if (vTexCoord.y < w || vTexCoord.y > (1.0-w))
            color = vec4(1.0, 0.0, 1.0, 1.0);
        else if (v < 0.0 || v > 1.0)
            discard;
    
        gl_FragColor = color; 
    }
    

    If you want to tint the entire area in purple, then you've to set color, instead of discarding the fragments:

    if (v < 0.0 || v > 1.0)
        color = vec4(1.0, 0.0, 1.0, 1.0);