Modern OpenGL : Draw a sphere and cylinder

前端 未结 2 901
-上瘾入骨i
-上瘾入骨i 2021-02-06 19:24

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 th

相关标签:
2条回答
  • 2021-02-06 19:59

    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.

    0 讨论(0)
  • 2021-02-06 20:02

    For cylinders, it is convenient to work in cylindrical coordinates: (angle, radius, height). You will compute two polygons (constant angle increment, fixed radius, two height values) and create: two sets of triangles for the basis and a set of rectangles (split in two) for the lateral surface.

    For spheres, you will use spherical coordinates: (inclination, elevation, radius). By varying the two angles (one at a time), you will describe parallels and meridians on the sphere. These define a meshing, such that every tile is a quadrilateral (except at the poles); split along a diagonal to get triangles.

    0 讨论(0)
提交回复
热议问题