Thursday, February 15, 2018

opengl - How can I calculate a terrain's normals?


Im trying to implement basic lighting in Opengl 3+ (a sun) with this tutorial :


http://www.mbsoftworks.sk/index.php?page=tutorials&series=1&tutorial=11


Im building a basic terrain and its working well. Now im trying to add normals, and I think its not working well :



Terrain


Terrain in wireframe


As you can see I dont think my normals are good.


This is how I get them :


for(x = 0; x < this.m_size.width - 1 ; x++)
{
for(y = 0; y < this.m_size.height - 1 ; y++)
{
immutable uint indice1 = y * this.m_size.width + x;
immutable uint indice2 = y * this.m_size.width + (x + 1);

immutable uint indice3 = (y + 1) * this.m_size.width + x;
immutable uint indice4 = (y + 1) * this.m_size.width + x;
immutable uint indice5 = y * this.m_size.width + (x + 1);
immutable uint indice6 = (y + 1) * this.m_size.width + (x + 1);

Vector3 v1 = vertexes[indice3] - vertexes[indice1];
Vector3 v2 = vertexes[indice2] - vertexes[indice1];
Vector3 normal = v1.cross(v2);
normal.normalize();


normals[indice1] = normal;

indices ~= [indice1,
indice2,
indice3,
indice4,
indice5,
indice6];
}
}


I use this basic shader : http://ogldev.atspace.co.uk/www/tutorial18/tutorial18.html or in the link I posted at the top.


Thanks.



Answer



By looking at your picture your problem seems that you need to smooth(average) your normals. That is when a vertex is shared by multiple triangles and yet has one normal you have two options to deal with this problem:



  • Smooth edges: You calculate the normal of each vertex for each adjacent triangle and then average them.

  • Hard edges: You duplicate each vertex, especially at the edges where the normal greatly varies between triangles. It practically has 3 different normals (though it's not actually) but then you have the effect of hard edges.


I provided the full code for smooth normals here. And more detailed explanation for this issue here.



No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...