所以我目前有一个可以动态更改的三角形网格(用贝塞尔曲线制成)。我面临的问题是试图根据相机所在的位置确定要实际渲染的三角形。相机总是看向原点(0,0,0),所以我找到了每个三角形的法线,并用我的相机矢量取它的点积。然后,根据结果,确定三角形是否应该“可见”。
以下是我用于计算的代码:
void bezier_plane()
{
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 20; j++) {
grid[i][j].x = 0;
grid[i][j].y = 0;
grid[i][j].z = 0;
}
}
//Creates the grid using bezier calculation
CalcBezier();
for (int i = 0; i < 19; i++) {
for (int j = 0; j < 19; j++) {
Vector p1, p2, p3, normal;
p1.x = grid[i+1][j+1].x - grid[i][j].x; p1.y = grid[i+1][j+1].y - grid[i][j].y; p1.z = grid[i+1][j+1].z - grid[i][j].z;
p2.x = grid[i+1][j].x - grid[i][j].x; p1.y = grid[i+1][j].y - grid[i][j].y; p1.z = grid[i+1][j].z - grid[i][j].z;
normal = CalcNormal(p2, p1);
double first = dotproduct(normal, Camera);
p3.x = grid[i][j+1].x - grid[i][j].x; p3.y = grid[i][j+1].y - grid[i][j].y; p3.z = grid[i][j+1].z - grid[i][j].z;
normal = CalcNormal(p1, p3);
double second = dotproduct(normal, Camera);
if (first < 0 && second < 0) {
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glColor3f(0, 1, 0);
glBegin(GL_TRIANGLE_STRIP);
glVertex3f(grid[i][j].x, grid[i][j].y, grid[i][j].z);
glVertex3f(grid[i][j+1].x, grid[i][j+1].y, grid[i][j+1].z);
glVertex3f(grid[i+1][j].x, grid[i+1][j].y, grid[i+1][j].z);
glVertex3f(grid[i+1][j+1].x, grid[i+1][j+1].y, grid[i+1][j+1].z);
glEnd();
} else if (first < 0 && second > 0) {
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glColor3f(0, 1, 0);
glBegin(GL_TRIANGLE_STRIP);
glVertex3f(grid[i][j].x, grid[i][j].y, grid[i][j].z);
glVertex3f(grid[i+1][j].x, grid[i+1][j].y, grid[i+1][j].z);
glVertex3f(grid[i+1][j+1].x, grid[i+1][j+1].y, grid[i+1][j+1].z);
glEnd();
} else if (first > 0 && second < 0) {
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glColor3f(0, 1, 0);
glBegin(GL_TRIANGLE_STRIP);
glVertex3f(grid[i][j].x, grid[i][j].y, grid[i][j].z);
glVertex3f(grid[i][j+1].x, grid[i][j+1].y, grid[i][j+1].z);
glVertex3f(grid[i+1][j+1].x, grid[i+1][j+1].y, grid[i+1][j+1].z);
glEnd();
}
}
}
}
这是 CalcNormal:
Vector CalcNormal(Vector p1, Vector p2)
{
Vector normal;
normal.x = (p1.y * p2.z) - (p1.z * p2.y);
normal.y = (p1.z * p2.x) - (p1.x * p2.z);
normal.z = (p1.x * p2. y) - (p1.y * p2.x);
return normal;
}
double dotproduct(Vector normal, Vector Camera)
{
return (normal.x * Camera.x + normal.y * Camera.y + normal.z + Camera.z);
}
现在,我的代码给出了这个结果。不应显示红色圈出的部分(我相信,后面的三角形)。