【问题标题】:Drawing the top and bottom of a cylinder绘制圆柱体的顶部和底部
【发布时间】:2020-03-31 15:51:51
【问题描述】:

我正在尝试创建一个可以在程序上创建棱镜(如果精度足够高,则为圆柱体)但仅显示 3d 模型的侧面(而不是顶部和底部)的类。这是使用openGL和c++。不追求效率,只是修改了以前的类,使一个球体。

#define numSlices 2
Prism::Prism() {
    init(3);
}

Prism::Prism(int prec) {
    init(prec);
}

float Prism::toRadians(float degrees) { return (degrees * 2.0f * 3.14159f) / 360.0f; }

void Prism::init(int prec) {
    prec = (prec < 3) ? 3 : prec;

    numVertices = (prec + 1) * (numSlices+1);
    numIndices = prec * numSlices * 6;
    for (int i = 0; i < numVertices; i++) { vertices.push_back(glm::vec3()); }
    for (int i = 0; i < numVertices; i++) { texCoords.push_back(glm::vec2()); }
    for (int i = 0; i < numVertices; i++) { normals.push_back(glm::vec3()); }
    for (int i = 0; i < numVertices; i++) { tangents.push_back(glm::vec3()); }
    for (int i = 0; i < numIndices; i++) { indices.push_back(0); }

    // calculate triangle vertices
    for (int i = 0; i <= numSlices; i++) {
        for (int j = 0; j <= prec; j++) {
            float y = i;
            float x = -(float)cos(toRadians(j * 360.0f / (float)prec));
            float z = (float)sin(toRadians(j * 360.0f / (float)prec));
            vertices[i * (prec + 1) + j] = glm::vec3(x, y, z);
            texCoords[i * (prec + 1) + j] = glm::vec2(((float)j / prec), ((float)i / numSlices));

        }
    }

    // calculate triangle indices 
    for (int i = 0; i < numSlices; i++) {
        for (int j = 0; j < prec; j++) {
            indices[6 * (i * prec + j) + 0] = i * (prec + 1) + j;
            indices[6 * (i * prec + j) + 1] = i * (prec + 1) + j + 1;
            indices[6 * (i * prec + j) + 2] = (i + 1) * (prec + 1) + j;
            indices[6 * (i * prec + j) + 3] = i * (prec + 1) + j + 1;
            indices[6 * (i * prec + j) + 4] = (i + 1) * (prec + 1) + j + 1;
            indices[6 * (i * prec + j) + 5] = (i + 1) * (prec + 1) + j;
        }
    }

}

非常感谢任何与已编写代码密切相关的提示或解决方案。

【问题讨论】:

  • OT:您可以调用vertices.resize(numVertices) 一次性调整顶点大小。
  • 嗯,谢谢你:)

标签: c++ 3d-modelling


【解决方案1】:

要渲染圆柱体的顶部和底部,您可以创建一个“三角形扇形”,从圆柱体顶部/底部中心的顶点开始,并为每一边创建一个三角形。

调整你的代码:(未经测试,我可能对缠绕顺序犯了错误)

int bottom_center = vertices.length(); vertices.push_back(glm::vec3(0,0,0));
int top_center = vertices.length(); vertices.push_back(glm::vec3(0,numSlices,0));

// Bottom
for (int j = 0; j < prec; j++) {
  int base = 0;
  indices.push_back(bottom_center);
  indices.push_back(base+j);
  indices.push_back(base+j+1);
}

// Top
for (int j = 0; j < prec; j++) {
  int base = numSlices * (prec+1);
  indices.push_back(top_center);
  indices.push_back(base+j);
  indices.push_back(base+j+1);
}

请参阅http://www.songho.ca/opengl/gl_cylinder.html 了解更完善的示例。

【讨论】:

    猜你喜欢
    • 2013-11-22
    • 2018-10-14
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-19
    相关资源
    最近更新 更多