How to bind an array of textures to a WebGL shader uniform?

前提是你 提交于 2019-11-29 07:03:49

You have to index sampler arrays with constant values so you can do something like this

precision mediump float;
varying float v_textureIndex;
uniform sampler2D u_textures[4];

vec4 getSampleFromArray(sampler2D textures[4], int ndx, vec2 uv) {
    vec4 color;
    if (ndx == 0) {
      color = texture2D(u_textures[0], uv);
    } else if (ndx == 1) {
      color = texture2D(u_textures[1], uv);
    } else if (ndx == 2) {
      color = texture2D(u_textures[2], uv);
    } else /* if (ndx == 3) */ {
      color = texture2D(u_textures[3], uv);
    }
    return color;
}

void main() {
    gl_FragColor = getSampleFromArray(u_textures, int(v_textureIndex), vec2(0.5, 0.5));
}

You also need to tell it which texture units to use

var textureLoc = gl.getUniformLocation(program, "u_textures[0]");
// Tell the shader to use texture units 0 to 3
gl.uniform1iv(textureLoc, [0, 1, 2, 3]);

The sample above uses a constant texture coord just to keep it simple but of course you can use any texture coordinates.

Here's a sample:

http://jsfiddle.net/greggman/dQuxT/

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!