1

我正在尝试在 WebGl 和 JavaScript 中制作一个简单的应用程序,并且在闲暇我在互联网上找到的一些教程时,我在创建一些基本着色器时遇到了一个奇怪的问题。创建着色器程序的函数如下所示:

 this.CreateShaderProgram = function(vertexShader, fragmentShader)
  {
    var tmp = this.gl.createProgram();

    var tempVert = this.gl.createShader(this.gl.VERTEX_SHADER);     
    this.gl.shaderSource(tempVert, vertexShader);
    this.gl.compileShader(tempVert);
    if(!this.gl.getShaderParameter(tempVert, this.gl.COMPILE_STATUS)) {
          this.Log("invalid shader : " + vertexShader);
          return null;
    };

    var tempFrag = this.gl.createShader(this.gl.FRAGMENT_SHADER); 
    this.gl.shaderSource(tempFrag, fragmentShader);
    this.gl.compileShader(tempFrag);    
    if(!this.gl.getShaderParameter(tempFrag, this.gl.COMPILE_STATUS)) {
          this.Log("invalid shader : " + fragmentShader);
          return null;
    };

    this.gl.attachShader(tmp, tempVert);
    this.gl.attachShader(tmp, tempFrag);

    return tmp;
  }

2个着色器看起来像:

  attribute vec3 aVertexPosition;
  uniform mat4 uMVMatrix;
  uniform mat4 uPMatrix;
  void main(void) {
         gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
  }
  --------------------------------------------  

  #ifdef GL_ES  precision highp float;
  #endif
  void main(void) { 
  gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);  };

奇怪的是,第一个顶点着色器编译成功,但对于片段着色器,它在“this.gl.compileShader(tempFrag);”上崩溃 线,我不知道为什么。

4

2 回答 2

4

This snippet from your code:

#ifdef GL_ES  precision highp float;
#endif

Should be on separate lines:

#ifdef GL_ES
precision highp float;
#endif

This is because the shading language uses a preprocessor, much like the C Preprocessor. lines that start with # are preprocessor directives, that span the entire line. Whereas the precision statement is not; it is just a normal statement in GLSL. Putting them on the same line confuses the preprocessor, because it considers the precision statement as part of its directive.

Zecc's advice to use getShaderInfoLog is also invaluable for debugging these kinds of problems.

于 2010-11-28T14:16:12.943 回答
4

如果你不知道为什么它没有编译,那么改变你的代码是这样的:

this.gl.compileShader(tempFrag);    
if(!this.gl.getShaderParameter(tempFrag, this.gl.COMPILE_STATUS)) {
      this.Log("invalid shader : " + this.gl.getShaderInfoLog(tempFrag));
      return null;
};

这应该为您提供有关问题的更多信息(可能使用#ifdef

于 2010-11-28T14:08:02.040 回答