天天看点

gl attribute和uniform的用法

gl attribute和uniform的用法

attribute

    attribute变量是只能在vertex shader中使用的变量。(它不能在fragment shader中声明attribute变量,也不能被fragment shader中使用)

    一般用attribute变量来表示一些顶点的数据,如:顶点坐标,法线,纹理坐标,顶点颜色等

    在application中,一般用函数glBindAttribLocation()来绑定每个attribute变量的位置,然后用函数glVertexAttribPointer()为每个attribute变量赋值。

    glsl里面定义属性

    Line 16:     attribute vec3 aVertexPosition;

    Line 22:         gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);

    javascript使用属性

        shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");

    Line 97:         gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);

    Line 153:         gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, triangleVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);

    Line 160:         gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, squareVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);

uniform

    uniform变量就像是C语言里面的常量(const ),它不能被shader程序修改。(shader只能用,不能改)

    如果uniform变量在vertex和fragment两者之间声明方式完全一样,则它可以在vertex和fragment共享使用。(相当于一个被vertex和fragment shader共享的全局变量)

    uniform变量一般用来表示:变换矩阵,材质,光照参数和颜色等信息。

    glsl里

    Line 18:     uniform mat4 uMVMatrix;

    javascript里

    Line 100:         shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");

    Line 109:         gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);

继续阅读