使用C ++和OpenGL我使用四边形,线条和点绘制了一个立方体。我现在正试图让我的代码更密集。为了达到这个目的,我想使用for循环。
我的立方体的顶点是二维数组,如下所示:
double vertices[8][3] = {
{ 1.0f, 1.0f, 1.0f}, //0
{ 1.0f, 1.0f,-1.0f}, //1
{ 1.0f,-1.0f,-1.0f}, //2
{-1.0f,-1.0f,-1.0f}, //3
{-1.0f,-1.0f, 1.0f}, //4
{-1.0f, 1.0f, 1.0f}, //5
{-1.0f, 1.0f,-1.0f}, //6
{ 1.0f,-1.0f, 1.0f} //7
};
目前我使用线条绘制多维数据集的代码是
void drawLines(){
glBegin(GL_LINES);
//Front Lines
//Left
glVertex3f(vertices[5][0],vertices[5][1],vertices[5][2]);
glVertex3f(vertices[4][0],vertices[4][1],vertices[4][2]);
//Top
glVertex3f(vertices[5][0],vertices[5][1],vertices[5][2]);
glVertex3f(vertices[0][0],vertices[0][1],vertices[0][2]);
//Bottom
glVertex3f(vertices[4][0],vertices[4][1],vertices[4][2]);
glVertex3f(vertices[7][0],vertices[7][1],vertices[7][2]);
//Right
glVertex3f(vertices[7][0],vertices[7][1],vertices[7][2]);
glVertex3f(vertices[0][0],vertices[0][1],vertices[0][2]);
//Middle Lines
//Top Left
glVertex3f(vertices[6][0],vertices[6][1],vertices[6][2]);
glVertex3f(vertices[5][0],vertices[5][1],vertices[5][2]);
//Top Right
glVertex3f(vertices[1][0],vertices[1][1],vertices[1][2]);
glVertex3f(vertices[0][0],vertices[0][1],vertices[0][2]);
//Bottom Left
glVertex3f(vertices[3][0],vertices[3][1],vertices[3][2]);
glVertex3f(vertices[4][0],vertices[4][1],vertices[4][2]);
//Bottom Right
glVertex3f(vertices[2][0],vertices[2][1],vertices[2][2]);
glVertex3f(vertices[7][0],vertices[7][1],vertices[7][2]);
//Back Lines
//Left
glVertex3f(vertices[6][0],vertices[6][1],vertices[6][2]);
glVertex3f(vertices[3][0],vertices[3][1],vertices[3][2]);
//Top
glVertex3f(vertices[6][0],vertices[6][1],vertices[6][2]);
glVertex3f(vertices[1][0],vertices[1][1],vertices[1][2]);
//Bottom
glVertex3f(vertices[3][0],vertices[3][1],vertices[3][2]);
glVertex3f(vertices[2][0],vertices[2][1],vertices[2][2]);
//Right
glVertex3f(vertices[2][0],vertices[2][1],vertices[2][2]);
glVertex3f(vertices[1][0],vertices[1][1],vertices[1][2]);
glEnd(); // Done Drawing Edges
}
为了压缩我的代码,我试图使用for循环获得相同的结果,目前我有这个:
glBegin(GL_LINES);
for ( int i=0; i<8; i+=1 ) {
for (int j=0; j<8; j+=1) {
glVertex3f(vertices[i][0],vertices[i][1],vertices[i][2]);
glVertex3f(vertices[j][0],vertices[j][1],vertices[j][2]);
}
}
glEnd();
我的问题是,是否有人能够给我指导以获得与原始代码相同的结果?
答案 0 :(得分:7)
为索引添加数组:
int[12][2] indices = {
{5,4},
{5,0},
{4,7},
{7,0},
{6,5},
{1,0},
{3,4},
{2,7},
{6,3},
{6,1},
{3,2},
{2,1}
}
并循环:
glBegin(GL_LINES);
for ( int i=0; i<12; i+=1 ) {
glVertex3f(vertices[indices[i][0]][0],vertices[indices[i][0]][1],vertices[indices[i][0]][2]);
glVertex3f(vertices[indices[i][1]][0],vertices[indices[i][1]][1],vertices[indices[i][1]][2]);
}
glEnd();
但是,建议您不要使用旧的(和已弃用的)openGL进行学习。相反,建议的方法是将顶点数据上传到VBO;创建一组着色器并改为使用glDrawArrays
或glDrawElements
。