From 47911edec357ac67c10f382e0842972b0cb56572 Mon Sep 17 00:00:00 2001 From: josh Date: Sun, 3 Jun 2007 03:23:32 +0000 Subject: [PATCH] stl: computing normals in the stl module by cross product now git-svn-id: svn://anubis/misc/stl@7 bd8a9e45-a331-0410-811e-c64571078777 --- stl-viewer.c | 11 +++++++++-- stl.c | 30 ++++++++++++++++++++++++++++++ stl.h | 1 + 3 files changed, 40 insertions(+), 2 deletions(-) diff --git a/stl-viewer.c b/stl-viewer.c index 2bc7b51..9fe0cc6 100644 --- a/stl-viewer.c +++ b/stl-viewer.c @@ -101,13 +101,14 @@ GLuint buildDL(void) unsigned int i; int dfltClrAct = 1; GLfloat color[4]; + float normal[3]; color[3] = 0.0f; GLuint dl = glGenLists(1); glNewList(dl, GL_COMPILE); - glBegin(GL_TRIANGLES); glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, default_color); for (i = 0; i < n_faces; i++) { +#if 0 if (stl_attr_color_valid(stl_face(stl, i).attribute)) { color[0] = stl_attr_color_r(stl_face(stl, i).attribute) / (float) 255; @@ -119,7 +120,13 @@ GLuint buildDL(void) else if (!dfltClrAct) glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, default_color); - glNormal3fv(stl_face(stl, i).normal); +#endif + stl_get_face_normal(stl, i, normal); + printf("normal: %f, %f, %f\n", + normal[0], + normal[1], + normal[2]); + glNormal3fv(normal); int j; for (j = 0; j < 3; j++) glVertex3fv(stl_face(stl, i).vertices[j]); diff --git a/stl.c b/stl.c index ef41827..1377a8d 100644 --- a/stl.c +++ b/stl.c @@ -2,6 +2,7 @@ #include /* struct stat */ #include /* malloc() */ #include /* fprintf() */ +#include /* sqrt() */ #include "stl.h" /* load a STL file and return a pointer to the stl_t struct */ @@ -37,3 +38,32 @@ stl_t * stl_load(const char * filename) } return stl; } + +/* fill vector pointed to by normal with the normal of the face */ +void stl_get_face_normal(stl_t * stl, int face, float * normal) +{ + float e1[3]; + float e2[3]; + int i; + for (i = 0; i < 3; i++) + { + e1[i] = stl_face(stl, face).vertices[1][i] - + stl_face(stl, face).vertices[0][i]; + e2[i] = stl_face(stl, face).vertices[2][i] - + stl_face(stl, face).vertices[1][i]; + } + + /* take the cross product of the first two edges */ + normal[0] = e1[1] * e2[2] - e1[2] * e2[1]; + normal[1] = e1[2] * e2[0] - e1[0] * e2[2]; + normal[2] = e1[0] * e2[1] - e1[1] * e2[0]; + + /* then normalize */ + double l; + l = sqrt(normal[0] * normal[0] + + normal[1] * normal[1] + + normal[2] * normal[2]); + normal[0] /= l; + normal[1] /= l; + normal[2] /= l; +} diff --git a/stl.h b/stl.h index 0c93291..23adcb8 100644 --- a/stl.h +++ b/stl.h @@ -37,6 +37,7 @@ typedef struct stl_s /* functions */ stl_t * stl_load(const char * filename); +void stl_get_face_normal(stl_t * stl, int face, float * normal); #ifdef __cplusplus