0

I'm still a beginner in OpenGL. I'm trying to draw a perfect square on the screen size 1280 by 720 using shaders.

I'm using OpenGL core profile, version 3.3. I was stuck with this when I tried to draw a square in 1280 by 720

enter image description here

After some time of searching, I realized that the size is distort by the viewport size, after changing the viewport size to 720 by 720, I got this.

This is in a viewport with size of 720 by 720

In the legacy OpenGL, they have a solution to fix this, but now it's deprecated in the Core profile.

Issue: How can I draw a perfect square in 1280 x 720 screensize, using only core profile, OpenGL 3.3?

Community
  • 1
  • 1
kimnod
  • 181
  • 1
  • 9
  • 2
    You need to do exactly the same thing. Apply an orthographic projection transform. In your case, just in a shader. – Nico Schertler Sep 06 '15 at 09:11
  • @NicoSchertler Does the shader has such function? or I have to calculate myself? – kimnod Sep 06 '15 at 10:35
  • The shader does not have an internal solution for this, buy you can use an external library, such as glm. http://glm.g-truc.net/0.9.7/index.html – Tal Darom Sep 06 '15 at 12:36
  • For orthographic projection create your matrix from the description of the compatibility mode: https://www.opengl.org/sdk/docs/man2/xhtml/glOrtho.xml – Josef Meixner Sep 06 '15 at 16:06

2 Answers2

1

Applying a projection transformation is the most standard way of solving this. You can find details on how to do that in almost any tutorial that shows how to use OpenGL with shaders. In summary, you typically have a projection matrix as a uniform variable in your vertex shader, and apply it to the input positions:

uniform mat4 ProjMat;
in vec4 InPosition;
...
    gl_Position = ProjMat * InPosition;

In your C++ code, you calculate the matrix to apply the necessary scaling, and set it using glUniformMatrix4fv().

Another option is that you keep the viewport square. While the viewport is often set to match the size of the window, this does not have to be the case. For example, the viewport can extend beyond the size of the window.

To use this approach, you would have something like this in the code where you set the viewport in response to window (re-)size events. With w and h the width and height of the window:

if (w > h) {
    glViewport(0, (h - w) / 2, w, w);
} else {
    glViewport((w - h) / 2, 0, h, h);
}

This takes the larger of the two window dimensions as the viewport size, and extends the viewport beyond the window in the other dimension to produce a square viewport.

Reto Koradi
  • 53,228
  • 8
  • 93
  • 133
0

Scale everything by (2.0/width, 2.0/height). If you have a camera matrix, just multiply it with this scaling.

Using that transform, you can input positions as pixels with the origin at the middle of the screen.

Joonazan
  • 1,408
  • 10
  • 18