Recently I am trying to improve my existing 3D engine, so I have decided to change from immediate mode to Vertex Array. But I am facing some problem with how to assign the normal to the correct indice of the mesh. I use google to search for the answer but was not able to get a completed tutorial on it, they just show you the spec of glDrawElements or the manual of using it but without an effective example.
Below is a cube with 12 vertices, 6 face with 6 normal for each face.
Vertices
8
0 0.026 0
10 0.026 0
10 10.026 0
0 10.026 0
0 0.026 -2
10 0.026 -2
10 10.026 -2
0 10.026 -2
Face // 1 base index.
6
2 6 5 1
3 7 6 2
4 8 7 3
1 5 8 4
4 1 2 3
8 5 6 7
Normal
6
0 1 0
-1 0 0
0 -1 0
1 0 0
0 0 1
0 0 -1
The snippet code for rendering this cube is as follow.
internal void RenderVertexArray()
{
// Collect Element Indice
// 6 face
int FaceNum=FaceList.Count;
ArrayIndex=null;
ArrayIndex = new int[FaceNum*4];
count=0;
int norCount=0;
for(i=0;i<FaceNum;i++)
{
Face3d pObj=FaceList[i] as Face3d;
ArrayIndex[count++]=pObj.Index[0];
ArrayIndex[count++]=pObj.Index[1];
ArrayIndex[count++]=pObj.Index[2];
ArrayIndex[count++]=pObj.Index[3];
}
pNorList=null;
int numVertex=4;
int xyz=3;
// Each normal with 3 component x,y,z and each face
// have 4 vertices so sum up to be 72.
pNorList=new double[bilFace*numVertex*xyz];
// Collect Normal
int c=0;
// Collect Normal
int c=0;
for(i=0;i<FaceNum;i++)
{
Face3d pFace=FaceList[i] as Face3d;
Point3D vert=pFace.GetNormal();
for(j=0;j<pFace.Index.Length;j++)
{
pNorList[c++]=vert.X;
pNorList[c++]=vert.Y;
pNorList[c++]=vert.Z;
}
}
Point3D testtem=new Point3D(0,0,0);
int test=Marshal.SizeOf(testtem);
Gl.glEnableClientState(Gl.GL_NORMAL_ARRAY);
Gl.glEnableClientState(Gl.GL_VERTEX_ARRAY);
Gl.glVertexPointer(3, Gl.GL_DOUBLE, test,ref VertexList[0].x);
Gl.glNormalPointer(Gl.GL_DOUBLE,0,pNorList);
Gl.glDrawElements(Gl.GL_QUADS, ArrayIndex.Length, Gl.GL_UNSIGNED_INT, mesh.ArrayIndex);
Gl.glDisableClientState(Gl.GL_VERTEX_ARRAY);
Gl.glDisableClientState(Gl.GL_NORMAL_ARRAY);
}
I am able to display the cube in wireframe mode, but when I render it in shading mode the cube doens’t looks what it suppose to be( the normal direction is wrong). Can anyone point out where I am wrong. Thanks in advance.