代码之家  ›  专栏  ›  技术社区  ›  Colin Dumitru Cihan Biyikoglu

WebGL着色器创建问题

  •  1
  • Colin Dumitru Cihan Biyikoglu  · 技术社区  · 15 年前

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

     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;
      }
    

    两个阴影看起来像:

      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);”行上崩溃,我不知道原因。

    2 回复  |  直到 15 年前
        1
  •  4
  •   Stéphan Kochen    15 年前

    此代码片段:

    #ifdef GL_ES  precision highp float;
    #endif
    

    应该在单独的行上:

    #ifdef GL_ES
    precision highp float;
    #endif
    

    这是因为着色语言使用一个预处理器,很像 C Preprocessor . 以开头的行 # 是跨整行的预处理器指令。鉴于 precision 语句不是;它只是GLSL中的一个普通语句。将它们放在同一行会混淆预处理器,因为它将precision语句视为其指令的一部分。

    Zecc的使用建议 getShaderInfoLog 对于调试这类问题也是非常宝贵的。

        2
  •  4
  •   Zecc    15 年前

    如果您不知道为什么不编译,请更改代码如下:

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

    这将为您提供更多关于错误的信息(可能使用 #ifdef )