gpt4 book ai didi

c++ - 在 Open GL 中计算曲面的法线

转载 作者:太空狗 更新时间:2023-10-29 19:53:31 24 4
gpt4 key购买 nike

我正在尝试为我的地形生成器添加阴影/光照。但出于某种原因,即使在我计算了表面法线之后,我的输出看起来仍然是 block 状的。

set<pair<int,int> >::const_iterator it;

for ( it = mRandomPoints.begin(); it != mRandomPoints.end(); ++it )
{
for ( int i = 0; i < GetXSize(); ++i )
{
for ( int j = 0; j < GetZSize(); ++j )
{
float pd = sqrt(pow((*it).first - i,2) + pow((*it).second - j,2))*2 / mCircleSize;
if(fabs(pd) <= 1.0)
{
mMap[i][j][2] += mCircleHeight/2 + cos(pd*3.14)*mCircleHeight/2; ;
}

}
}
}

/*
The three points being considered to compute normals are
(i,j)
(i+1,j)
(i, j+1)
*/

for ( int i = 0; i < GetXSize() -1 ; ++i )
{
for ( int j = 0; j < GetZSize() - 1; ++j )
{
float b[] = {mMap[i+1][j][0]-mMap[i][j][0], mMap[i+1][j][1]-mMap[i][j][1], mMap[i+1][j][2]-mMap[i][j][2] };
float c[] = {mMap[i][j+1][0]-mMap[i][j][0], mMap[i][j+1][1]-mMap[i][j][1], mMap[i][j+1][2]-mMap[i][j][2] };
float a[] = {b[1]*c[2] - b[2]*c[1], b[2]*c[0]-b[0]*c[2], b[0]*c[1]-b[1]*c[0]};

float Vnorm = sqrt(pow(a[0],2) + pow(a[1],2) + pow(a[2],2));

mNormalMap[i][j][0] = a[0]/Vnorm;
mNormalMap[i][j][1] = a[1]/Vnorm;
mNormalMap[i][j][2] = a[2]/Vnorm;

}
}

然后在绘制时我使用以下内容

float*** normal = map->GetNormalMap();

for (int i = 0 ; i < map->GetXSize() - 1; ++i)
{
glBegin(GL_TRIANGLE_STRIP);

for (int j = 0; j < map->GetZSize() - 1; ++j)
{

glNormal3fv(normal[i][j]);


float color = 1 - (terrain[i][j][2]/height);
glColor3f(color,color, color);
glVertex3f(terrain[i][j][0], terrain[i][j][2], terrain[i][j][1]);
glVertex3f(terrain[i+1][j][0], terrain[i+1][j][2], terrain[i+1][j][1]);
glVertex3f(terrain[i][j+1][0], terrain[i][j+1][2], terrain[i][j+1][1]);
glVertex3f(terrain[i+1][j+1][0], terrain[i+1][j+1][2], terrain[i+1][j+1][1]);
}

glEnd();
}

编辑:初始化代码

glFrontFace(GL_CCW);
glCullFace(GL_FRONT); // glCullFace(GL_BACK);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_SMOOTH);
glEnable(GL_POLYGON_SMOOTH);
glMatrixMode(GL_PROJECTION);

我是否正确计算了法线?

最佳答案

除了 Bovinedragon 建议的内容,即 glShadeModel(GL_SMOOTH);,您可能应该使用逐顶点法线。这意味着每个 glVertex3f 之前都会有一个 glNormal3fv 调用,这将定义所有相邻面的平均法线。要获得它,您可以简单地将这些相邻的法 vector 相加并对结果进行归一化。

enter image description here

引用这个问题:Techniques to smooth face edges in OpenGL

关于c++ - 在 Open GL 中计算曲面的法线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13392995/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com