【发布时间】:2016-10-10 17:23:45
【问题描述】:
我在顶点着色器“uIsTeapot”中有变量。
uniform float uIsTeapot;
顶点着色器可以很好地使用它,但片段着色器看不到它。如果我使用
if (uIsTeapot == 0.0)
然后发生错误
"uIsTeapot": undeclared identifier
但我在顶点着色器中定义了它。如果我将两个着色器中的 uIsTeapot 定义为统一,那么程序会说“无法初始化着色器”,因为程序没有通过验证
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert("Could not initialise shaders");
}
编辑: 我将 mediump 添加到变量中,现在程序编译没有错误,但结果是屏幕上的一个对象,但我绘制了两个对象。
顶点着色器
attribute vec3 aVertexPosition;
attribute vec3 aVertexNormal;
attribute vec2 aTextureCoord;
attribute vec4 aVertexColor;
uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;
uniform mat3 uNMatrix;
uniform vec3 uAmbientColor;
uniform vec3 uPointLightingLocation;
uniform vec3 uPointLightingColor;
uniform mediump float uIsTeapot;
//varying float vIsTeapot;
varying vec2 vTextureCoord;
varying vec3 vLightWeighting;
varying vec4 vColor;
void main(void) {
if (uIsTeapot == 1.0) {
vec4 mvPosition = uMVMatrix * vec4(aVertexPosition, 1.0);
gl_Position = uPMatrix * mvPosition;
vec3 lightDirection = normalize(uPointLightingLocation - mvPosition.xyz);
vec3 transformedNormal = uNMatrix * aVertexNormal;
float directionalLightWeighting = max(dot(transformedNormal, lightDirection), 0.0);
directionalLightWeighting = 100.0;
vLightWeighting = uAmbientColor + uPointLightingColor * directionalLightWeighting;
vTextureCoord = aTextureCoord;
}
if (uIsTeapot == 0.0) {
gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
vColor = aVertexColor;
} }
片段着色器
precision mediump float;
varying vec2 vTextureCoord;
varying vec3 vLightWeighting;
varying vec4 vColor;
uniform sampler2D uSampler;
uniform mediump float uIsTeapot;
//varying float vIsTeapot;
void main(void) {
if (uIsTeapot == 1.0) {
vec4 textureColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));
gl_FragColor = vec4(textureColor.rgb * vLightWeighting, textureColor.a);
} else {
gl_FragColor = vColor;
}
}
【问题讨论】:
-
“程序无法正常工作”信息不足。你得到什么错误信息? Are you printing out the shader info log and program info log when the shaders fail to compile or link?
-
我添加了发生错误的信息
-
您的代码应该是
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { alert(gl.getProgramInfoLog(shaderProgram)); },并且在编译着色器时您还应该有类似代码,除非您调用gl.getShaderInfoLog(shader)和gl.getShaderParameter(shader, gl.COMPILE_STATUS)
标签: opengl-es webgl shader fragment-shader vertex-shader