Michael Sohnen
Michael Sohnen

Reputation: 980

GLSL map gl_FragCoord.xy to coordinates in orthographic projection

Hello I have an opengl Program that renders 2d polygons in an orthographic projection. At the start of the porgram, or when the window size changes, the function reshape is called. Here is the code for the reshape function:

    /* Call back when the windows is re-sized */
    void reshape(GLsizei width, GLsizei height) {
    // Compute aspect ratio of the new window
    if (height == 0) height = 1;                
    // To prevent divide by 0
    GLfloat aspect = (GLfloat)width / 
    (GLfloat)height;

    // Set the viewport to cover the new window
    glViewport(0, 0, width, height);

    // Set the aspect ratio of the clipping area to match the viewport
    glMatrixMode(GL_PROJECTION);  // To operate on the Projection matrix
    glLoadIdentity();             // Reset the projection matrix
    if (width >= height) {
    clipAreaXLeft = -1.0 * aspect;
    clipAreaXRight = 1.0 * aspect;
    clipAreaYBottom = -1.0;
    clipAreaYTop = 1.0;
    }
    else {
    clipAreaXLeft = -1.0;
    clipAreaXRight = 1.0;
    clipAreaYBottom = -1.0 / aspect;
    clipAreaYTop = 1.0 / aspect;
    }
    clipAreaXLeft *= 600;
    clipAreaYBottom *= 600;
    clipAreaXRight *= 600;
    clipAreaYTop *= 600;

   gluOrtho2D(clipAreaXLeft, clipAreaXRight, 
clipAreaYBottom, clipAreaYTop);
    glScissor(0, 0, width, height);
    glEnable(GL_SCISSOR_TEST);

    }

Here is some code for a GLSL fragment shader:

#version 420 core
out vec4 color
void main(){
vec2 orthoXY =... need help here, should 
convert window-space to ortho-space, 
maybe use projection matrix from fixed 
pipeline?
color=vec4{1,1,1,1}
}

Upvotes: 2

Views: 1547

Answers (1)

Rabbid76
Rabbid76

Reputation: 211077

If you want to transform gl_FragCoord to normalize device space, then I recommend to create uniform, which contains the size of the viewport:

uniform vec2 u_resolution; // with and height of the viewport

gl_FragCoord.xy contains the "window" coordinates of the fragment, gl_FragCoord.z contains the depth in the depth range, which is [0, 1], if you didn't change it by glDepthRange.

The normalized device space is a cube with a left, lower, front coordnate (-1, -1, -1) and a right, top, back coordinate of (1, 1, 1):

So the transformation is:

vec3 ndc = -1.0 + 2.0 * gl_FragCoord.xyz/vec3(u_resolution.xy, 1.0);

Or the following, if you want to transform the x and y component only:

vec2 ndc_xy = -1.0 + 2.0 * gl_FragCoord.xy/u_resolution.xy;

Upvotes: 2

Related Questions