简体   繁体   中英

Perspective projection not working in OpenGL

I'was displaying a cube in opengl. Here is my file for vertex shader

#version 330

layout(location = 0) in vec4 position;
layout(location = 1) in vec4 color;

smooth out vec4 theColor;

uniform vec3 offset;
uniform mat4 perspectiveMatrix;

void main()
{
    vec4 cameraPos = position + vec4(offset.x, offset.y, offset.z, 0.0);

    //gl_Position = perspectiveMatrix * cameraPos;
    gl_Position.xy = cameraPos.xy;
    gl_Position.z = cameraPos.z*2.0f + 3.0f;
    gl_Position.w = -cameraPos.z;

    float tmp = gl_Position.z / gl_Position.w;
    theColor = color;

}

RET

The result is weird.It seems that the five faces other than the front face are showed, which should all be disappeared.The back face is now in front of the front face.Here is the two triangles for the front face:

0.25f,  0.25f, -1.0f, 1.0f,
0.25f, -0.25f, -1.0f, 1.0f,
-0.25f,  0.25f, -1.0f, 1.0f,

 0.25f, -0.25f, -1.0f, 1.0f,
-0.25f, -0.25f, -1.0f, 1.0f,
-0.25f,  0.25f, -1.0f, 1.0f,

the data for the back face:

0.25f,  0.25f, -3.0f, 1.0f,
-0.25f,  0.25f, -3.0f, 1.0f,
0.25f, -0.25f, -3.0f, 1.0f,

0.25f, -0.25f, -3.0f, 1.0f,
-0.25f,  0.25f, -3.0f, 1.0f,
-0.25f, -0.25f, -3.0f, 1.0f,

I choose -1.0f and 3.0f for the near and far plane respectively,so (n + f) / (f - n) = 2.0f and (2 * n * f) / (f - n) = 3.0f.Why the result is such weird?

After some test,I get the correct image.

RET

I know what did I do wrong now.

First, the window I created didn't have a depth buffer and I did't enable the depth test.As the data of the five faces other than the front face was loaded after the front face, they were all be drawn.

Second, (n + f) / (f - n) and (2 * n * f) / (f - n) should change to (n + f) / (f - n) and (2 * n * f) / (f - n) .

Why the negations? OpenGL wants to present to the programmer a  
right-handed coordinate system before projection and left-handed 
coordinate system after projection.

That's the information I found.The larger z values will finally become smaller z value in the window space, which is exactly the depth value. And as the default value for glDepthFunc is GL_LESS, the front face will show before the other faces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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