透视投影反转 x 轴(glm::perspective)

Perspective projection inverting x axis (glm::perspective)

当我在 OpenGL 中使用透视投影时,我的 X 轴反转,如下图所示。下面的代码可能无效,因为我对其进行了很多更改以使其不那么晦涩。它可能不起作用,所以请记住这一点。这是代码和顶点:

 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

这是顶点着色器:

#version 330 core

layout(location = 0) in vec4 position;

uniform mat4 u_MVP;

void main(){
  gl_Position = u_MVP * position;
}

这是输出。如您所见,它与提供的顶点不匹配。

如果您需要完整的代码,或者您希望我提供原始版本,请告诉我。谢谢!

更新:我试过负 Z 轴,但没有用。代码如下:

  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
  );

x 轴不会因为投影矩阵而反转,但会因为视图矩阵而反转。

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));

视图 space 是一个 Right-handed 系统,其中 X 轴指向右侧,Y 轴指向上方。 Z 轴指向视图外(请注意,在右手系统中,Z 轴是 X 轴和 Y 轴的叉积)。

所以你从后面看三角形。

更改模型矩阵和视图矩阵。沿负 Z 轴移动三角形。定义指向负 z 方向的视线:

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));

到近平面和远平面的距离必须为正值,角度单位为 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);