我在我的WebGL程序中使用了三个纹理,并且我得到了条纹/重叠效果。
我绑定的第一个纹理是正常的,但顺序纹理会产生效果。
这是我的顶点数据格式(x,y,z,s,t,textureIndex,textureName)
-5.0 0.0 -5.0 0.0 0.0 1 WL01
-5.0 0.0 5.0 0.0 1.0 1 WL01
5.0 0.0 5.0 1.0 1.0 1 WL01
-5.0 0.0 -5.0 0.0 0.0 1 WL01
5.0 0.0 -5.0 1.0 0.0 1 WL01
5.0 0.0 5.0 1.0 1.0 1 WL01
-1.0 1.0 -4.0 0.0 1.0 2 WL02
-1.0 0.0 -4.0 0.0 0.0 2 WL02
-0.0 0.0 -4.0 1.0 0.0 2 WL02
-1.0 1.0 -4.0 0.0 1.0 2 WL02
-0.0 1.0 -4.0 1.0 1.0 2 WL02
-0.0 0.0 -4.0 1.0 0.0 2 WL02
2.0 1.0 -4.0 1.0 1.0 0 WL00
2.0 0.0 -4.0 1.0 0.0 0 WL00
0.5 0.0 -4.0 0.0 0.0 0 WL00
2.0 1.0 -4.0 1.0 1.0 0 WL00
0.5 1.0 -4.0 0.0 1.0 0 WL00
0.5 0.0 -4.0 0.0 0.0 0 WL00
以下是我如何逐个初始化每个纹理:
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.image);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.bindTexture(gl.TEXTURE_2D, null);
缓冲区初始化:
levelVertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, levelVertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data), gl.STATIC_DRAW);
levelVertexBuffer.vertexCount = 18;
textureIndexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, textureIndexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Uint8Array(texIndexBuffData), gl.STATIC_DRAW);
在主循环中,我正在做:
...
for( var i = 0; i < level.textures.length; i++ ) {
gl.activeTexture(gl.TEXTURE0 + i);
gl.bindTexture(gl.TEXTURE_2D, level.textures[i]);
}
...
gl.uniform1i(shaderProgram.texturesUniform0, 0);
gl.uniform1i(shaderProgram.texturesUniform1, 1);
gl.uniform1i(shaderProgram.texturesUniform2, 2);
顶点着色器:
<script id="shader-vs" type="x-shader/x-vertex">
attribute vec3 aVertexPosition;
attribute vec2 aTextureCoord;
attribute float aTextureIndex;
uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;
varying vec2 vTextureCoord;
varying float vTextureIndex;
void main(void) {
gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
vTextureCoord = aTextureCoord;
vTextureIndex = aTextureIndex;
}
</script>
片段着色器:
<script id="shader-fs" type="x-shader/x-fragment">
precision mediump float;
varying float vTextureIndex;
varying vec2 vTextureCoord;
uniform sampler2D u_texture0;
uniform sampler2D u_texture1;
uniform sampler2D u_texture2;
vec4 getSampleFromArray(int index, vec2 uv) {
vec4 color;
if (index == 0) {
color = texture2D(u_texture0, uv);
} else if ( index == 1 ) {
color = texture2D(u_texture1, uv);
} else if ( index == 2 ) {
color = texture2D(u_texture2, uv);
}
return color;
}
void main() {
gl_FragColor = getSampleFromArray(int(vTextureIndex), vec2(vTextureCoord.s, vTextureCoord.t));
}
</script>
答案 0 :(得分:1)
我看到的可能性是你的变化vTextureIndex
的插值不佳。尝试将其舍入到最近而不是向下:int(vTextureIndex + 0.5)
。
是的,你会认为没有必要这样做,但GPU会在允许的地方使用粗略的足够好的近似值。