# 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 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.

## 1 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.

• Very nice. You solved my problem. I think it's better now : i.imgur.com/4RRaDx0.png
– Aldo
Jan 13, 2014 at 19:08
• I know this is kinda late but you should use triplanar mapping for terrain texturing Apr 14, 2021 at 2:22