关于javascript:如何将多个纹理发送到WebGL中的片段着色器?

How to send multiple textures to a fragment shader in WebGL?

因此,在代码的JavaScript部分中,以下代码段实际上将像素数组发送到顶点和片段着色器-但当我到达这些着色器时,我仅使用1个纹理-无论如何,我可以发送两个 一次纹理? 如果是这样,我将如何在编码器的GLSL端"捕获"它们两者?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
        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);

您可以通过声明多个采样器制服来引用GLSL中的多个纹理

1
2
3
4
5
6
7
uniform sampler2D u_myFirstTexture;
uniform sampler2D u_mySecondTexture;

...

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

您可以通过调用gl.uniform1i来指定这两个采样器使用的纹理单位

1
2
3
4
5
6
7
8
9
10
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);

然后使用gl.activeTexturegl.bindTexture设置纹理单位

1
2
3
4
5
6
7
8
9
// 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);
...