有人可以告诉我我弄乱了代码的哪一部分?
在glDrawElements中,我只喜欢1/3 of the sphere with "indices.size() / 3",这是大多数教程的进行方式,但是当我尝试indices.size()时,出现了分割错误,但没有任何显示。

vector<GLfloat> vertices, normals, texCoords;
vector<GLushort> indices;

void setupSphere(double r, int slice, int stack)
{
    vertices.resize(slice * stack * 3);
    normals.resize(slice * stack * 3);
    texCoords.resize(slice * stack * 2);

    float x, y, z, xz;
    float nx, ny, nz, lengthInv = 1.0f / r;
    float s, t;

    float sliceAngle, stackAngle;

    vector<GLfloat>::iterator itV = vertices.begin();
    vector<GLfloat>::iterator itN = normals.begin();
    vector<GLfloat>::iterator itT = texCoords.begin();

    for (int i = 0; i < stack; i++)
    {
        stackAngle = M_PI_2 - M_PI * i / stack;
        xz = r * cosf(stackAngle);
        y = r * sinf(stackAngle);

        for (int j = 0; j < slice; j++)
        {
            sliceAngle = 2 * M_PI * j / slice;

            x = xz * sinf(sliceAngle);
            z = xz * cosf(sliceAngle);
            *itV++ = x;
            *itV++ = y;
            *itV++ = z;

            nx = x * lengthInv;
            ny = y * lengthInv;
            nz = z * lengthInv;
            *itN++ = nx;
            *itN++ = ny;
            *itN++ = nz;

            s = (float)j / slice;
            t = (float)i / stack;
            *itT++ = s;
            *itT++ = t;
        }
    }

    int first, second;
    for (int i = 0; i < stack; i++)
    {
        for (int j = 0; j < slice; j++)
        {
            first = i * slice + j;
            second = first + slice + 1;

            indices.push_back(first);
            indices.push_back(second);
            indices.push_back(first + 1);

            indices.push_back(first + 1);
            indices.push_back(second);
            indices.push_back(second + 1);
        }
    }
}

void drawSphere()
{
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_NORMAL_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    glVertexPointer(3, GL_FLOAT, 0, &vertices[0]);
    glNormalPointer(GL_FLOAT, 0, &normals[0]);
    glTexCoordPointer(2, GL_FLOAT, 0, &texCoords[0]);

    glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_SHORT, &indices[0]);
}

最佳答案

正确的确实是indices.size() / 3,因为您必须传递三角形的数量,而不是索引的数量。
正确的确实是indices.size(),因为您必须传递要传递的数组中元素的数量。我不知道您看到的教程为什么使用/ 3变体。
对于缺少球体部分的问题,我对所提供信息的最佳猜测是,您有65535个以上的顶点,因此索引会围绕该值,因为您使用的是GL_UNSIGNED_SHORT
尝试从vector<GLushort> indices;更改为vector<GLuint> indices;,并在GL_UNSIGNED_INT中使用glDrawElements()
或者,降低slicestack的值,以便slice * stack * 3 <= 65535

关于c++ - 用OpenGL绘制球体,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/64256401/

10-11 22:01