WebGL: glsl attributes issue, getProgramParameter returns wrong number of attributes

こ雲淡風輕ζ 提交于 2019-12-10 18:19:57

问题


I'm making a simple WebGL demo. I have a simple vertex shader that takes two attributes and some uniforms. Here is the code:

attribute vec3 v_position;
attribute vec3 v_normal;

uniform mat4   mvMatrix;
uniform mat4   pMatrix;
uniform mat3   normalMatrix;
uniform vec3   lightPosition;



// Color to fragment program
varying vec3 transformedNormal;
varying vec3 lightDir;

void main(void) 
{ 
  // Get surface normal in eye coordinates
  transformedNormal = normalMatrix * v_normal;

  // Get vertex position in eye coordinates
  vec4 position4 = mvMatrix * vec4(v_position.xyz,1.0);
  vec3 position3 = position4.xyz / position4.w;

      // Get vector to light source
  lightDir = normalize(lightPosition - position3);


  // Don't forget to transform the geometry!
  gl_Position = pMatrix * mvMatrix * vec4(v_position.xyz,1.0);
}

For some reason when I call

gl.getProgramParameter(shaderProgram, gl.ACTIVE_ATTRIBUTES);

I get a count of 1 when I should be getting 2;

I'm not sure what is wrong here. If you need it this is the fragment shader that goes with it:

#ifdef GL_ES
precision highp float;
#endif 

uniform vec4    ambientColor;
uniform vec4    diffuseColor;   
uniform vec4    specularColor;

varying  vec3 transformedNormal;
varying  vec3 lightDir;


void main(void)
{ 
  // Dot product gives us diffuse intensity
  float diff = max(0.0, dot(normalize(transformedNormal), normalize(lightDir)));

  // Multiply intensity by diffuse color, force alpha to 1.0
  vec4 out_color = diff * diffuseColor;

  // Add in ambient light
  out_color += ambientColor;


      // Specular Light
  vec3 vReflection = normalize(reflect(-normalize(lightDir), normalize(transformedNormal)));
  float spec = max(0.0, dot(normalize(transformedNormal), vReflection));
  if(diff != 0.0) {
    float fSpec = pow(spec, 128.0);
    out_color.rgb += vec3(fSpec, fSpec, fSpec);
  }


  gl_FragColor = vec4(1.0,0.0,0.0, 1.0);

}

回答1:


This is due to the smartness of your GLSL compiler, I think. In your fragment shader you assign a constant color to gl_FragColor in the last line. Therefore all your nice computations, and all the varyings get optimized away. So as transformedNormal has been optimized away, you also don't need to compute its value in the vertex shader. So your v_normal attribute is also optimized away (isn't it nice how smart your GLSL compiler is, to reduce both shaders to a single line). That's the reason it's called ACTIVE_ATTRIBUTES and not just ATTRIBUTES or DECLARED_ATTRIBUTES (those constants don't exist, I made them up).

Try to assign out_color to gl_FragColor and nothing should get optimized away.



来源:https://stackoverflow.com/questions/7325038/webgl-glsl-attributes-issue-getprogramparameter-returns-wrong-number-of-attrib

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