GLSL Shader will not render color from uniform var

2020-03-26 03:39发布

问题:

I am currently building an app for Android, but have run into some problems with a shader that refuses to render.

Consider the following fragment shader:

uniform vec4 color;
void main(){
    gl_FragColor = vec4(1.0);
}

This shader works fine for drawing an object in a solid color (white in this case). The uniform vector color is optimized away, and cannot be found with glGetUniformLocation() (returns -1).

Trying to get the color from the uniform variable can be done like so:

uniform vec4 color;
void main(){
    gl_FragColor = color;
}

However, when I use this, nothing renders. The shader is created successfully and glGetUniformLocation() returns a valid value (0) for color. But nothing shows on screen, not even black. The only change made is replacing vec4(1.0) with color. This code has the same result:

uniform vec4 color;
void main(){
    gl_FragColor = vec4(1.0)+color;
}

The strange thing is that when I tried the shader in a different project, it works as it should, so the problem must be something I do elsewhere in the code.
This is my drawing method (keep in mind that it works when the color-variable is not in the shader):

GLES20.glUseProgram(colorshader);
GLES20.glUniform4f(colorIndex, 1, 1, 1, 1); //colorIndex is the result of glGetUniformLocation() called with the correct shader index and variable name.

Matrix.multiplyMM(mvpMatrix, 0, vpMatrix, 0, matrix, 0);
GLES20.glUniformMatrix4fv(matrixindex, 1, false, mvpMatrix, 0);

GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, vertices);
GLES20Fix.glVertexAttribPointer(Shader.ATTRIBUTE_VERTEX, 3, GLES20.GL_FLOAT, false, 12, 0);

GLES20.glLineWidth(width);
GLES20.GL_UNSIGNED_SHORT, 0);
GLES20.glDrawArrays(GLES20.GL_LINES, 0, count);

I have absolutely no idea what might be causing this odd behaviour, if anyone have any ideas or possible solutions, please help me.

Update:
It seems that using any uniform variable that is not a sampler causes this behaviour in this (and only this) shader.

Update 2 Using glGetError() return error code 502: GL_INVALID_OPERATION.

回答1:

Ok, so I finally figured it out after a load of testing.
In my code, I was using multiple shaders, but I had accidentally only got the mvpMatrix-uniform for one shader and was using that one for every shader, which funnily enough worked for all shaders I had before creating this one (it got id 0 for all the earlier shaders).
However with this shader it seems that my new vec4 got id 0, which caused the code to wrongly assign my vector data to the mvp-matrix. getting new ids for each shader made the program work.



回答2:

color is uninitialized, and most likely the shader aborts.