简体   繁体   English

纵横比拉伸的OpenGL 2D投影

[英]OpenGL 2D projection stretched by aspect ratio

I am currently trying to convert the drawing methods for my 2D java game to OpenGL by using JOGL, because native java seems rather slow for drawing high-res images in rapid succession. 我目前正在尝试使用JOGL将我的2D Java游戏的绘制方法转换为OpenGL,因为原生Java对于快速连续绘制高分辨率图像来说似乎很慢。 Now i want to use a 16:9 aspect ratio, but the problem is that my image is stretched to the sides. 现在我想使用16:9的宽高比,但是问题是我的图像被拉伸到了侧面。 Currently i am only drawing a white rotating quad for testing this: 目前我只画一个白色的旋转四边形来测试:

public void resize(GLAutoDrawable d, int width, int height) {

    GL2 gl = d.getGL().getGL2(); // get the OpenGL 2 graphics context
    gl.glViewport(0, 0, width, height);
    gl.glMatrixMode(GL2.GL_PROJECTION);
    gl.glOrtho(-1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f);

}

public void display(GLAutoDrawable d) {

    GL2 gl = d.getGL().getGL2();  // get the OpenGL 2 graphics context
    gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    gl.glClear(GL.GL_COLOR_BUFFER_BIT);

    gl.glMatrixMode(GL2.GL_MODELVIEW);
    gl.glLoadIdentity();
    gl.glColor3f(1.0f,1.0f,1.0f);

    degree += 0.1f;

    gl.glRotatef(degree, 0.0f, 0.0f, 1.0f);

    gl.glBegin(GL2.GL_QUADS);
    gl.glVertex2f(-0.25f, 0.25f);
    gl.glVertex2f(0.25f, 0.25f);
    gl.glVertex2f(0.25f, -0.25f);
    gl.glVertex2f(-0.25f, -0.25f);
    gl.glEnd();

    gl.glRotatef(-degree, 0.0f, 0.0f, 1.0f);

    gl.glFlush();
}

I know that you can somehow adress this problem by using glOrtho() and I tried many different values for this now, but none of them achieved a unstretched image. 我知道您可以通过使用glOrtho()以某种方式解决此问题,并且我现在为此尝试了许多不同的值,但没有一个获得未拉伸的图像。 How do I have to use this? 我该如何使用呢? Or is there another simple solution for this? 还是为此提供另一种简单的解决方案?

The projection matrix transforms all vertex data from the eye coordinates to the clip coordinates. 投影矩阵将所有顶点数据从眼睛坐标转换为剪辑坐标。

Then, these clip coordinates are also transformed to the normalized device coordinates (NDC) by dividing with w component of the clip coordinates. 然后,通过将片段坐标的w分量除以将这些片段坐标也转换为归一化设备坐标(NDC)。 The normalized device coordinates is in range (-1, -1, -1) to (1, 1, 1) . 归一化的设备坐标在(-1, -1, -1)(1, 1, 1) (-1, -1, -1)范围内。

With the orthographic projection, the eye space coordinates are linearly mapped to the NDC. 通过正交投影,眼睛空间坐标线性映射到NDC。

If the viewport is rectangular this has to be considered by mapping the coordinates. 如果视口是矩形的,则必须通过映射坐标来考虑。

float aspect = (float)width/height;
gl.glOrtho(-aspect, aspect, -1.0f, 1.0f, -1.0f, 1.0f);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM