2
votes

I'm new to OpenGL, and trying to figure out my fragment shader. I have a rectangle drawn in my window, and I'd like to color the top half of it a different color (say blue), without hard-coding the height of the pixels.

With a window height of 1000, in my fragment shader, I have:

void main(){
if((gl_FragCoord.y) > 500)
{
    color = vec3(.3, .3, 1);
}
else
{
    color = fragmentColor;
}

Which colors the top half of the rectangle blue. But what if I'd like to get the window height from inside my fragment shader instead of just using 500 pixels? I initialized uniform vec2 windowSize, and am trying to use glUniform1i() to place the window height in this variable, but I don't know how.

1
You need to use glUniform2f to set the windowSize because it's a vec2. - rwols
How could I make the call in my fragment shader? Is it glUniform2f(windowSize, ?, ?)? How should I pass in the other two arguments? - 3PA
You first obtain a "handle" to the uniform variable via glGetUniformLocation, and then use that "handle" as the first argument for glUniform2f. The second and third arguments for glUniform2f can be whatever you want. - rwols
@3PA: You don't make the call in the fragment shader. The fragment shader is executed long after any chance to set uniforms has passed. You make the call of glUniform in the hosts programs display/drawing routine. - datenwolf

1 Answers

1
votes

The situation you describe just begs for an out float variable in the vertex shader that is set to the current Y coordinate of the rectangle, which, along with the X coordinate and whatever else vertex attributes you have, is passed to your shader by OpenGL.

When it arrives at the fragment shader (the type being in float), it gets interpolated, most probably in [–1; 1] bounds. So, to paint the upper half blue, you just need to check if that variable is positive.

N.B.: if you use GLSL prior to 3.x, out float VARIABLE_NAME and in float VARIABLE_NAME must both be varying float VARIABLE_NAME.