When I use a perspective projection in OpenGL, my X axis gets inverted as seen in the image below. The code below might not be valid because I changed it a lot in order to make it less obscure. It might not work, so just keep that in mind. Here is the code and vertices:
typedef struct{
float x;
float y;
float z;
} vertex_t;
glm::vec3 position = glm::vec3(0, 0, 0);
glm::vec3 look_at = glm::vec3(0, 0, 1);
glm::mat4 projectionMatrix = glm::perspective(45.0f, (float)800 / (float)600, 0.1f, 100.f);
glm::mat4 modelMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 5.0f));
glm::mat4 viewMatrix = glm::lookAt(
position,
look_at,
glm::vec3(0, 1, 0)
);
vertex_t data[3] = {
{-0.5, 0.5, -0.5f},
{ 0.5, 0.5, -0.5f},
{-0.5, -0.5, -0.5f},
};
unsigned int indices[3] = {
0, 1, 2
};
glm::mat4 mvp = projectionMatrix * viewMatrix * modelMatrix; //This is passed in as the uniform u_MVP later
This is the vertex shader:
#version 330 core
layout(location = 0) in vec4 position;
uniform mat4 u_MVP;
void main(){
gl_Position = u_MVP * position;
}
And this is the output. As you can see, it doesn't match the vertices provided.
If you need the entire code, or if you want me to provide the original version, please let me know. Thanks!
UPDATE: I've tried a negative Z axis, and it hasn't worked. Heres the code:
position = glm::vec3(0, 0, 0);
look_at = glm::vec3(0, 0, -1);
glm::mat4 projectionMatrix = glm::perspective(45.0f, (float)800 / (float)600, 0.1f, 100.f);
glm::mat4 modelMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, -5.0f));
viewMatrix = glm::lookAt(
position,
look_at,
glm::vec3(0, 1, 0) // Tilt/rotation (unclear) set y to -1 for upside down view
);
The x-axis doesn't get inverted because of the projection matrix, but it get's inverted because of the view matrix.
glm::vec3 position = glm::vec3(0, 0, 0); glm::vec3 look_at = glm::vec3(0, 0, 1); glm::mat4 viewMatrix = glm::lookAt(position, look_at, glm::vec3(0, 1, 0));
The view space is a Right-handed system, where the X-axis points to the right and the Y-axis points up. The Z-axis points out of the view (Note in a right hand system the Z-Axis is the cross product of the X-Axis and the Y-Axis).
Hence you look at the triangle from the back.
Change the model matrix and the view matrix. Shift the triangle along the negative Z axis. Define a line of sight pointing in the negative z-direction:
glm::mat4 modelMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, -5.0f));
glm::vec3 position = glm::vec3(0, 0, 0);
glm::vec3 look_at = glm::vec3(0, 0, -1);
glm::mat4 viewMatrix = glm::lookAt(position, look_at, glm::vec3(0, 1, 0));
The distances to the near and far plane have to be positive values and th unit of the angle for glm::perspective
is radiant:
0 < near < far
glm::mat4 projectionMatrix = glm::perspective(45.0f, (float)800 / (float)600, -0.1f, -100.f);
glm::mat4 projectionMatrix = glm::perspective(
glm::radians(45.0f), 800.0f/600.0f, 0.1f, 100.f);