calculating vertex normal in opengl c++ ( gouraud shading) -


i started learning c++ , opengl. i'm trying calculate vertex normal in opengl.

i know there function glnormal3f. however, not allowed use function. rather have calculate vertex normal codes , obj file. trying is, first calculate surface normals , calculate vertex normal.

i declared operators such +,-,* , , other functions innerproduct, crossproduct.

void calcul_color(){ vector kd; vector ks; kd=vector(0.8, 0.8, 0.8); ks=vector(1.0, 0.0, 0.0); double inner =  kd.innerproduct(ks);  int i, j; for(i=0;i<cube.vertex.size();i++) {     vector n = cube.vertex_normal[i];     vector l = vector(100,100,0) - cube.vertex[i];     vector v = vector(0,0,1) - cube.vertex[i];     float xl = n.innerproduct(l)/n.magnitude();     vector x = (n * (1.0/ n.magnitude())) * xl;     vector r = x - (l-x);      vector color = kd * (n.innerproduct(l)) + ks * pow((v.innerproduct(r)),10);     cube.vertex_color[i] = color; }     for(i=0;i<cube.face.size();i++)     {         face cur_face = cube.face[i];  glcolor3f(cube.vertex_color[cur_face.id1].x,cube.vertex_color[cur_face.id1].y,cube.vertex_color[cur_face.id1].z);             glvertex3f(cube.vertex[cur_face.id1].x,cube.vertex[cur_face.id1].y,cube.vertex[cur_face.id1].z);             glcolor3f(cube.vertex_color[cur_face.id2].x,cube.vertex_color[cur_face.id2].y,cube.vertex_color[cur_face.id2].z);             glvertex3f(cube.vertex[cur_face.id2].x,cube.vertex[cur_face.id2].y,cube.vertex[cur_face.id2].z);             glcolor3f(cube.vertex_color[cur_face.id3].x,cube.vertex_color[cur_face.id3].y,cube.vertex_color[cur_face.id3].z);             glvertex3f(cube.vertex[cur_face.id3].x,cube.vertex[cur_face.id3].y,cube.vertex[cur_face.id3].z);     } 

the way compute vertex normals this:

  • initialize every vertex normal (0,0,0)
  • for every face compute face normal fn, normalize it
  • for every vertex of face add fn vertex normal
  • after loop normalize every vertex normal

this loop nice o(n). 1 thing pay attention here if vertices shared, normals smooth out on sphere. if vertices not shared, hard faces want on cube. duplicating such vertices should done before.

if question on how go normal color, dependent on lighting equation! easiest 1 do: color = dot(normal,globallightdir)*globallightcolor way color = texturecubemap(normal). there endless possibilities!


Comments