简体   繁体   English

OpenGL. 顶点乘以投影矩阵

[英]OpenGL. Multiplying a vertex by a projection matrix

I'm trying to draw a model and this is what I ran into, the code below works like 2d, although there should be a perspective我正在尝试绘制一个 model,这就是我遇到的情况,下面的代码像 2d 一样工作,尽管应该有一个透视图

Code # 1
mat4 Proj = glFrustum(left, right, bottom, top, zNear, zFar);
mat4 View = gluLookAt(position, direction, up);
mat4 World = mat4(1);
glBegin(GL_TRIANGLES);
for (auto& t : mesh)
{
    norm = Proj * View * World * vec4(t.norm, 0);
    dot1 = Proj * View * World * vec4(t.dot1, 1);
    dot2 = Proj * View * World * vec4(t.dot2, 1);
    dot3 = Proj * View * World * vec4(t.dot3, 1);
 
    glNormal3f(norm);
    glVertex3f(dot1.x, dot1.y, dot1.z);
    glVertex3f(dot2.x, dot2.y, dot3.z);
    glVertex3f(dot3.x, dot3.y, dot3.z);
}
glEnd();

And so the perspective appears:所以透视图出现了:

Code # 2
mat4 Proj = glFrustum(left, right, bottom, top, zNear, zFar);
mat4 View = gluLookAt(position, direction, up);
mat4 World = mat4(1);
glMatrixMode(GL_PROJECTION);
glLoadMatrix(Proj);
glBegin(GL_TRIANGLES);
for (auto& t : mesh)
{
    norm = View * World * vec4(t.norm, 0);
    dot1 = View * World * vec4(t.dot1, 1);
    dot2 = View * World * vec4(t.dot2, 1);
    dot3 = View * World * vec4(t.dot3, 1);
 
    glNormal3f(norm);
    glVertex3f(dot1.x, dot1.y, dot1.z);
    glVertex3f(dot2.x, dot2.y, dot3.z);
    glVertex3f(dot3.x, dot3.y, dot3.z);
}
glEnd();

From which the question arose: why code 2 and code 3 get the same result, but code 1 and code 2 are different?由此产生的问题是:为什么代码2和代码3得到相同的结果,而代码1和代码2却不同?

Code # 3
mat4 Proj = glFrustum(left, right, bottom, top, zNear, zFar);
mat4 View = gluLookAt(position, direction, up);
mat4 World = mat4(1);
glMatrixMode(GL_PROJECTION);
glLoadMatrix(Proj);
*glMatrixMode(GL_MODELVIEW);
glLoadMatrix(View);*
glBegin(GL_TRIANGLES);
for (auto& t : mesh)
{
    norm = World * vec4(t.norm, 0);
    dot1 = World * vec4(t.dot1, 1);
    dot2 = World * vec4(t.dot2, 1);
    dot3 = World * vec4(t.dot3, 1);
 
    glNormal3f(norm);
    glVertex3f(dot1.x, dot1.y, dot1.z);
    glVertex3f(dot2.x, dot2.y, dot3.z);
    glVertex3f(dot3.x, dot3.y, dot3.z);
}
glEnd();

Tell me what am I doing wrong?告诉我我做错了什么? How can I calculate the vertex multiplied by the projection matrix correctly?如何正确计算顶点乘以投影矩阵?

The transformation with the projection matrix generates Homogeneous coordinates .与投影矩阵的变换生成齐次坐标 A Homogeneous coordinate has 4 components, but you just pass 3 components to the vertex coordinate.齐次坐标有 4 个分量,但您只需将 3 个分量传递给顶点坐标。 Use all 4 components to specify the vertex coordinate.使用所有 4 个组件来指定顶点坐标。 eg:例如:

glVertex3f(dot1.x, dot1.y, dot1.z);

glVertex4f(dot1.x, dot1.y, dot1.z, dot1.w);

or或者

glVertex4fv(glm::value_ptr(dot1));

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

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