Question

i have a shape with the following vertexes and faces:

static Vec3f cubeVerts[24] = {
{ -0.5,  0.5, -0.5 },   /* backside */
{ -0.5, -0.5, -0.5 },   
{ -0.3,  4.0, -0.5 },
{ -0.3,  3.0, -0.5 },
{ -0.1,  5.5, -0.5 },
{ -0.1,  4.5, -0.5 },
{  0.1,  5.5, -0.5 },
{  0.1,  4.5, -0.5 },
{  0.3,  4.0, -0.5 },           
{  0.3,  3.0, -0.5 },
{  0.5,  0.5, -0.5 },   
{  0.5, -0.5, -0.5 },   

{ -0.5,  0.5,  0.5 },   /* frontside */
{ -0.5, -0.5,  0.5 },   
{ -0.3,  4.0,  0.5 },
{ -0.3,  3.0,  0.5 },
{ -0.1,  5.5,  0.5 },
{ -0.1,  4.5,  0.5 },
{  0.1,  5.5,  0.5 },
{  0.1,  4.5,  0.5 },
{  0.3,  4.0,  0.5 },           
{  0.3,  3.0,  0.5 },
{  0.5,  0.5,  0.5 },   
{  0.5, -0.5,  0.5 }
};

static GLuint cubeFaces[] = {
0, 1, 3, 2,     /*backfaces*/
2, 3, 5, 4,
4, 5, 7, 6, 
6, 7, 9, 8, 
8, 9, 11, 10,

12, 13, 15, 14, /*frontfaces*/
14, 15, 17, 16,
16, 17, 19, 18,
18, 19, 21, 20,
20, 21, 23, 22,

0, 2, 14, 12,   /*topfaces*/
2, 4, 16, 14,
4, 6, 18, 16, 
6, 8, 20, 18,
8, 10, 22, 20,

1, 3, 15, 13,   /*bottomfaces*/
3, 5, 17, 15,
5, 7, 19, 17,
7, 9, 21, 19,
9, 11, 23, 21,

0, 1, 13, 12,   /*sidefaces*/
10, 11, 23, 22
};

and i want to get its normal like this:

static Vec3f cubeNorms[] = {
{ 0, 1, 0 },
{ 0, 1, 0 },
{ 0, 1, 0 },
{ 0, 1, 0 }
};

Can someone tell me how to calculate its normal and putting it inside an array so i can use all these together like this, i know something is wrong with my normal, because lighting on my shape is not right and i am also not sure if its the right way of setting up the normal, just one example is fine, ive been reading heaps of normal calculations and still can't figure out how to do it.

static void drawCube()
{
//vertexes
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, cubeVerts);
//norms
glEnableClientState(GL_NORMAL_ARRAY);
glNormalPointer(GL_FLOAT, 0, cubeNorms);
//faces
glDrawElements(GL_QUADS, 22 * 4, GL_UNSIGNED_INT, cubeFaces);
}
Was it helpful?

Solution

I'm going to assume your faces are counter-clockwise front-facing - I don't know if that's the case - and the quads are, of course, convex and planar.

For a face, take vertices {0, 1, 2}. I don't know the Vec3f specification (or if it's a class or C struct), but we can find the normal for all vertices in the quad with:

Vec3f va = v0 - v1; // quad vertex 1 -> 0
Vec3f vb = v2 - v1; // quad vertex 1 -> 2
Vec3f norm = cross(vb, va); // cross product.

float norm_len = sqrt(dot(norm, norm));
norm /= norm_len; // divide each component of norm by norm_len.

That gives you a unit normal for that face. If vertices are shared, and you want to give the model the perception of curvature using lighting, you'll have to decide what value of the normal should be 'agreed' upon. Perhaps the best starting point is to simply take an average of the face normals at that vertex - and rescale the result to unit length as required.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top