Webgl的getAttribLocation奇怪地返回-1

时间:2012-01-25 18:39:10

标签: webgl

我已设法隔离此代码中的问题:

var gl;
_main_web = function() {
    gl = document.getElementById("canvas").getContext("experimental-webgl");

    gl = WebGLDebugUtils.makeDebugContext(gl,
    function (err, funcName, args) {
        throw(WebGLDebugUtils.glEnumToString(err) + " was caused by call to " + funcName);
    }
    );

    vert_shader = gl.createShader(gl.VERTEX_SHADER);
    gl.shaderSource(vert_shader,"attribute vec4 vertex;attribute vec2 uv; void main(void) {gl_Position = vertex;}\n");
    gl.compileShader(vert_shader);
    if( !gl.getShaderParameter(vert_shader,gl.COMPILE_STATUS ) ) {
        throw 0;
    }
    frag_shader = gl.createShader(gl.FRAGMENT_SHADER);
    gl.shaderSource(frag_shader,"void main(void) { gl_FragColor = vec4(1.0,1.0,1.0,1.0); } \n");
    gl.compileShader(frag_shader);
    if( !gl.getShaderParameter(frag_shader,gl.COMPILE_STATUS) ) {
        throw 1;
    }
    program = gl.createProgram();
    gl.attachShader(program,vert_shader);
    gl.attachShader(program,frag_shader);
    gl.linkProgram(program);
    if( !gl.getProgramParameter(program,gl.LINK_STATUS) ) {
        throw 2;
    }

    vertexLocation = gl.getAttribLocation(program,"vertex");
    textureLocation = gl.getAttribLocation(program,"uv");
}

vertexLocation没关系,它是0.但是textureLocation是-1,我错过了什么?

1 个答案:

答案 0 :(得分:39)

您正在尝试获取您声明但从不使用的属性的位置。您的顶点着色器代码是(为了清晰起见而展开):

attribute vec4 vertex;
attribute vec2 uv;
void main(void) {
    gl_Position = vertex;
}

在着色器的编译过程中,“uv”将被识别为未使用的参数并被剥离。即使您在此着色器中将其分配给变量但不在片段着色器中使用它,它仍可能被剥离,因为它已被识别为对最终片段没有贡献。