Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

opengl - How to correctly draw other texture in fragment shader?

How to correctly calculate uv coordinates for my sampler2D uniform?

E.g. i have main texture which has 1920x1080 resolution, i attached a shader to this texture, then passed other texture as sampler2D uniform which has 200x200 resolution.

Also, as i understand, i have to pass to a shader texture resolution and its normalized position. But i don't understand how to calculate uv coordinates for second texture.

uniform sampler2D u_render_texture;
uniform vec2 u_render_texture_pos;
uniform vec2 u_render_texture_size;

In main:

void main() {
   vec4 mainTextureCol = texture2D(u_texture, v_texCoord);
   vec4 renderTextureCol = texture2D(u_render_texture, what is here?);
   gl_FragColor = mainTextureCol + renderTextureCol;
}
question from:https://stackoverflow.com/questions/65641145/how-to-correctly-draw-other-texture-in-fragment-shader

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to scale the texture coordinates according to the ratio of the texture sizes. If the unit of u_render_texture_pos is pixels and since the texture coordinates are in the range [0.0, 1.0], the offset must also be scaled.
Skip the color you got from u_render_texture if one of the coordinates is not in the range [0.0, 1.0]:

uniform vec2 u_render_texture_pos;
uniform vec2 u_render_texture_size;
uniform vec2 u_texture_size;

void main()
{
    vec2 uv = v_texCoord * u_render_texture_size/u_texture_size 
              + u_render_texture_pos/u_texture_size; 

    vec4 mainTextureCol = texture2D(u_texture, v_texCoord);
    vec4 renderTextureCol = texture2D(u_render_texture, uv);

    vec4 finalColor = mainTextureCol;
    if (uv.x >= 0.0 && uv.x <= 1.0 && uv.y >= 0.0 && uv.y <= 1.0)
        finalColor += renderTextureCol;

    gl_FragColor = finalColor;
}

If you are using GLSL 1.30 or higher, you can use textureSize to determine the size of a texture:

vec2 texture_size = textureSize(u_texture, 0); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...