Skip to main content
gamedev.net
🔒 Locked

Problem with computing face normals

Started by colinisinhere Oct 8, 2004 at 6:28 PM 2 replies 800+ views
Original Post
colinisinhere
colinisinhere
I wrote a function for my mesh class to compute all of the face normals, here is the code:

void CMesh::computeNormals() {
		vector3df vect1, vect2, vect3, nVect1, nVect2;
		for(int i = 0; i < numGroups; i++) { //! Loop for every group (Rhymage!!!)
			for(int j = 0; j < groups.numTriangles; j++) {
				vect1 = groups.vertices[groups.triangles[j].indices[0]].pos;
				vect2 = groups.vertices[groups.triangles[j].indices[1]].pos;
				vect3 = groups.vertices[groups.triangles[j].indices[2]].pos;
				
				nVect1 = vect1 - vect3;
				nVect2 = vect3 - vect2;

				groups.triangles[j].normal = nVect1.crossProduct(nVect2);
				groups.triangles[j].normal.normalize();
			}
		}
	}


And here are the functions of vector3df:

float getLength() const { return sqrt(x*x + y*y + z*z); }

//! Returns the cross product of 2 vectors
vector3d<type> crossProduct(const vector3d<type>& p) const {
	return vector3d<type>(y * p.z - z * p.y, z * p.x - x * p.z, x * p.y - y * p.x);
}

//! Normalizes the vector
vector3d<type>& normalize() {
	type inv = (type)1.0 / (type)getLength();
	x *= inv;
	y *= inv;
	z *= inv;
	return *this;
}


But, when I render my object, all I get is a solid black model! (yes, GL_LIGHTING is enables, and I have a light at a good position, and I am rending the mesh with glNormal3f()) Any ideas why it is not computing them correctly?
Hybrid
Hybrid
Not being stupid here, but have you printed out the normals you get? Do they look like normalised normals? If so, then even with a dodgy light and lighting enabled you should at least get some shading even if you messed up the normal calculations, so the problem may be elsewhere perhaps...
Zakwayda
Zakwayda
Couple of ideas. First of all, the order you do the cross product and the handedness of your coordinate system can result in the normals pointing the wrong way. Try reversing the order of the cross product and see what happens.

Also, try drawing the normals, like this (psuedocode):
for (each triangle){    float normallength = 8.0f; // Adjust to your scale    Vector3 v1 = // first vert in triangle    Vector3 v2 = // second vert    Vector3 v3 = // third vert    Vector3 p1 = (v1 + v2 + v3) / 3.0f;    Vector3 p2 = p1 + trianglenormal * normallength;    DrawLine(p1, p2); // Appropriate OpenGL code goes here}


This should draw a line from the center of each tri in the direction of the normal. It's a helpful debugging function to have as part of your mesh class.
colinisinhere
colinisinhere
Thank you! That was the problem. Be prepared, I might be posting a question about vertex normal in awhile :P

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.