现代OpenGL:绘制一个球体和圆柱体 [英] Modern OpenGL : Draw a sphere and cylinder

查看:1308
本文介绍了现代OpenGL:绘制一个球体和圆柱体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



对于立方体,我们认为每个面都由两个三角形组成,然后适当地设置顶点和颜色缓冲区。然后将这些缓冲区发送到着色器代码。



我们如何类似地绘制球体和圆柱体?所有的在线教程都专注于绘制立方体。



为球体或圆柱体设置顶点缓冲区似乎并不重要;我无法像三维立方体那样从三角形构造它们。

绘制空间。



注意:此代码使用C ++和GLM数学库。

 < code $ //计算顶点
for(int i = 0; i <= Stacks; ++ i){

float V = i /(float)Stacks;
float phi = V * glm :: pi< float> ();

//循环切片
for(int j = 0; j< = Slices; ++ j){

float U = j /(float )切片;
float theta = U *(glm :: pi< float>()* 2);

//计算顶点位置
float x = cosf(theta)* sinf(phi);
float y = cosf(phi);
float z = sinf(theta)* sinf(phi);

//推回顶点数据
vertices.push_back(glm :: vec3(x,y,z)* Radius);



//计算指数位置
for(int i = 0; i< Slices * Stacks + Slices; ++ i){

indices.push_back(i);
indices.push_back(i + Slices + 1);
indices.push_back(i + Slices);

indices.push_back(i + Slices + 1);
indices.push_back(i);
indices.push_back(i + 1);
}

这个算法创建了所谓的UV Sphere。
'Slices'和'Stacks'是X轴和Y轴的细分数。


I've learned how to draw a cube using OpenGL from various tutorials.

For a cube, we consider each face to be composed of two triangles, and then appropriately set up the vertex and color buffers. These buffers are then sent to the shader code.

How do we similarly draw a sphere and cylinder? All tutorials online focus on drawing cubes.

Setting up vertex buffer for a sphere or cylinder doesn't seem trivial; I'm unable to "construct" them from triangles as we do for cubes.

解决方案

Here is some code that I use when drawing spheres.

Note: This code uses C++, with the GLM math library.

// Calc The Vertices
for (int i = 0; i <= Stacks; ++i){

    float V   = i / (float) Stacks;
    float phi = V * glm::pi <float> ();

    // Loop Through Slices
    for (int j = 0; j <= Slices; ++j){

        float U = j / (float) Slices;
        float theta = U * (glm::pi <float> () * 2);

        // Calc The Vertex Positions
        float x = cosf (theta) * sinf (phi);
        float y = cosf (phi);
        float z = sinf (theta) * sinf (phi);

        // Push Back Vertex Data
        vertices.push_back (glm::vec3 (x, y, z) * Radius);
    }
}

// Calc The Index Positions
for (int i = 0; i < Slices * Stacks + Slices; ++i){

    indices.push_back (i);
    indices.push_back (i + Slices + 1);
    indices.push_back (i + Slices);

    indices.push_back (i + Slices + 1);
    indices.push_back (i);
    indices.push_back (i + 1);
}

This algorithm creates what is called a UV Sphere. The 'Slices' and 'Stacks' are the number of subdivisions on the X and Y axis.

这篇关于现代OpenGL:绘制一个球体和圆柱体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆