How to send multiple textures to a fragment shader in WebGL?
Asked Answered
L

1

6

So in the javascript portion of my code, here is the snippet that actually sends an array of pixels to the vertex and fragment shaders- but I am only working with 1 texture when I get to those shaders- is there anyway that I can send two textures at a time? if so, how would I 'catch' both of them on the GLSL side of the codee?

        if (it > 0){

            gl.activeTexture(gl.TEXTURE1);

            gl.bindTexture(gl.TEXTURE_2D, texture);

            gl.activeTexture(gl.TEXTURE0);

            gl.bindFramebuffer(gl.FRAMEBUFFER, FBO2);}

        else{

            gl.activeTexture(gl.TEXTURE1);

            gl.bindTexture(gl.TEXTURE_2D, texture2);

            gl.activeTexture(gl.TEXTURE0);

            gl.bindFramebuffer(gl.FRAMEBUFFER, FBO);}

        gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
Lilialiliaceous answered 3/11, 2013 at 16:46 Comment(0)
L
11

You reference multiple textures in GLSL by declaring multiple sampler uniforms

uniform sampler2D u_myFirstTexture;
uniform sampler2D u_mySecondTexture;

...

vec4 colorFrom1stTexture = texture2D(u_myFirstTexture, someUVCoords); 
vec4 colorFrom2ndTexture = texture2D(u_mySecondTexture, someOtherUVCoords);

You can specific which texture units those 2 samplers use by calling gl.uniform1i as in

var location1 = gl.getUniformLocation(program, "u_myFirstTexture");
var location2 = gl.getUniformLocation(program, "u_mySecondTexture");

...

// tell u_myFirstTexture to use texture unit #7
gl.uniform1i(location1, 7);

// tell u_mySecondTexture to use texture unit #4
gl.uniform1i(location2, 4);  

And you setup texture units by using gl.activeTexture and gl.bindTexture

// setup texture unit #7
gl.activeTexture(gl.TEXTURE7);  // or gl.TEXTURE0 + 7
gl.bindTexture(gl.TEXTURE_2D, someTexture);
...

// setup texture unit #4
gl.activeTexture(gl.TEXTURE4);  // or gl.TEXTURE0 + 4
gl.bindTexture(gl.TEXTURE_2D, someOtherTexture);
...
Laband answered 4/11, 2013 at 0:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.