我想使用GL_TRIANGLES在OpenGL中渲染一個球體。 這裏是我用下面的代碼得到的圖像.. Bad Sphere連接球體頂點OpenGL
這應該是一個單位球體。
我都來源於基本近似球體的頂點從 wikipedia.
這裏是我創建渲染單元球.. 請讓我知道代碼哪裏我錯了
void createGreenSphere(mat4 modelView){
std::vector<Vertex> v;
int numSphereSlices = 12;
int numSphereSegments = 12;
float theta = 0;
float phi = 0;
float phiDelt = (2*PI)/numSphereSegments;
float thetaDelt = PI/numSphereSlices;
float* vertices = new float[numSphereSlices*numSphereSegments*4];
float* normals = new float[numSphereSlices*numSphereSegments*4];
float* colors = new float[numSphereSlices*numSphereSegments*3];
int colorCnt = 0;
int vertCnt = 0;
for(int heightCnt = 0; heightCnt < numSphereSlices; heightCnt++){
theta += thetaDelt;
phi = 0;
for(int widthCnt = 0; widthCnt < numSphereSegments; widthCnt++){
phi += phiDelt;
vertices[vertCnt] = sin(theta)*cos(phi);
normals[vertCnt] = vertices[vertCnt];
vertCnt++;
vertices[vertCnt] = sin(theta)*sin(phi);
normals[vertCnt] = vertices[vertCnt];
vertCnt++;
vertices[vertCnt] = cos(theta);
normals[vertCnt] = vertices[vertCnt];
vertCnt++;
vertices[vertCnt] = 1.0;
normals[vertCnt] = vertices[vertCnt];
vertCnt++;
colors[colorCnt] = 0.0;
colorCnt++;
colors[colorCnt] = 1.0;
colorCnt++;
colors[colorCnt] = 0.0;
colorCnt++;
}
}
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, vertCnt-1 * sizeof(float), vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, cbo);
glBufferData(GL_ARRAY_BUFFER, colorCnt-1 * sizeof(float), colors, GL_STREAM_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, nbo);
glBufferData(GL_ARRAY_BUFFER, vertCnt-1 * sizeof(float), normals, GL_STATIC_DRAW);
unsigned short* indices = new unsigned short[numSphereSlices*numSphereSegments*6];
int indexCnt = 0;
for (int i=0;i<numSphereSlices;i++){
for(int j=0;j<numSphereSegments;j++){
indices[indexCnt] = j + numSphereSegments*i;
indexCnt++;
indices[indexCnt] = j+1 + numSphereSegments*i;
indexCnt++;
indices[indexCnt] = numSphereSegments+j + numSphereSegments*i;
indexCnt++;
indices[indexCnt] = numSphereSegments+j+1 + numSphereSegments*i;
indexCnt++;
indices[indexCnt] = numSphereSegments+j + numSphereSegments*i;
indexCnt++;
indices[indexCnt] = j+1 + numSphereSegments*i;
indexCnt++;
}
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, (numSphereSlices*numSphereSegments*6) * sizeof(unsigned short), indices, GL_STATIC_DRAW);
delete [] indices;
glUniformMatrix4fv(u_modelMatrixLocation, 1, GL_FALSE, &modelView[0][0]);
glDrawElements(GL_TRIANGLES, numSphereSlices*numSphereSegments, GL_UNSIGNED_SHORT, 0);
glDisableVertexAttribArray(positionLocation);
glDisableVertexAttribArray(colorLocation);
glDisableVertexAttribArray(normalLocation);
}
我不確定問題出在創建頂點還是鏈接索引上。
一切看起來都很好。我猜你的視圖矩陣有問題。首先,嘗試使用您現在使用的視圖矩陣的轉置。 –
我不相信這是問題,我正在製作其他形狀,例如立方體。 – Kyle