Webgl's getAttribLocation oddly returns -1

2020-06-03 02:28发布

I have managed to isolate the problem in this code:

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 is alright, it is 0. But textureLocation is -1, what am I missing?

标签: webgl
1条回答
仙女界的扛把子
2楼-- · 2020-06-03 02:52

You're trying to get the location for an attribute that you declare but never use. Your vertex shader code is (expanded for clarity):

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

During the compilation of your shader "uv" will be identified as an unused parameter and be stripped out. Even if you assign it to a varying in this shader but don't ever use it in the fragment shader, it may still be stripped out because it's been identified as not contributing to the final fragment.

查看更多
登录 后发表回答