请问有人可以解释一下三角网格的索引是如何生成的吗?
该程序为球体对象生成了顶点数组,并生成了用于使用glDrawElements方法绘制的索引。
我不明白这些索引与堆栈和切片有什么关系。
我是OpenGL的新手,花了很多时间试图理解这段代码的工作原理。
提前感谢您的帮助。:)
int stacks = 40, slices = 40; // stacks = no. of Latitude lines,
// slices = no. of Longitude lines
double deltaLong = PI * 2 / slices;
double deltaLat = PI / stacks;
// Generate vertices coordinates, normal values, and texture coordinates
numVertices = (slices + 1) * (stacks - 1) + 2;
vertices = new float[numVertices * 3];
normals = new float[numVertices * 3];
textures = new float[numVertices * 2];
// North pole point
normals[0] = 0; normals[1] = 0; normals[2] = 1;
vertices[0] = 0; vertices[1] = 0; vertices[2] = radius;
textures[0] = 0.5f; textures[1] = 1.0f;
k = 1;
// vertices on the main body
for (i = 1; i < stacks; i++) {
for (j = 0; j <= slices; j++) {
normals[3 * k] = sin(deltaLat * i) * cos(deltaLong * j);
normals[3 * k + 1] = sin(deltaLat * i) * sin(deltaLong * j);
normals[3 * k + 2] = cos(deltaLat * i);
vertices[3 * k] = radius * normals[3 * k];
vertices[3 * k + 1] = radius * normals[3 * k + 1];
vertices[3 * k + 2] = radius * normals[3 * k + 2];
textures[2 * k] = (float) j / slices;
textures[2 * k + 1] = 1 - (float) i / stacks;
k++;
}
}
// South pole point
normals[3 * k] = 0;normals[3 * k + 1] = 0;normals[3 * k + 2] = -1;
vertices[3 * k] = 0;vertices[3 * k + 1] = 0;vertices[3 * k + 2] = -radius;
textures[2 * k] = 0.5f; textures[2 * k + 1] = 0.0f; k++;
//The above code is to generate vertices array and I think I understand how it works.
//**********************************
// Below is what I don't understand
int numIndices = (stacks - 1) * slices * 6; //why multiply by 6?
int[] indices = new int[numIndices];
int k = 0;
//add indices in North Pole region (no. of elements is slices * 3)
// WHY 3 times thenumber of slices?
for (int j = 1; j<= slices; j++){
indices[k++] = 0;
indices[k++] = j;
indices[k++] = j+1;
}
//add indices in South Pole Region (no. of element is slices * 3)
int temp = numVertices - 1;
for (int j = temp-1; j > temp - slices - 1; j--){
indices [k++] = temp;
indices [k++] = j;
indices [k++] = j - 1;
}
// add body (no. of element is (stacks - 2) * slices * 6
for (i = 1; i < stacks - 1; i++) {
for (j = 1; j <= slices; j++) {
// each quad gives two triangles
// triangle one
indices[k++] = (i - 1) * slices + j;
indices[k++] = i * slices + j;
indices[k++] = i * slices + j + 1;
// triangle two
indices[k++] = (i - 1) * slices + j;
indices[k++] = i * slices + j + 1;
indices[k++] = (i - 1) * slices + j + 1;
}
}
我终于理解了我展示的球体代码中的索引如何工作,并且找到了如何制作上面图片中显示的圆柱体。