danielepanozzo / cg-old

43 stars 16 forks source link

drawing spheres #49

Closed jw3877 closed 7 years ago

jw3877 commented 7 years ago

What is the recommended way to draw spheres in OpenGL?

The GLUT library has built-in functions for drawing spheres. However, I don't think that I will be needing this library for anything else.

Is "Catmull–Clark subdivision" the only other alternative? You essentially start with a cube and end up with a sphere-like shape after repeated iterations?

Could you say a few words about how you would recommend drawing spheres?

danielepanozzo commented 7 years ago

You should threat them as every other object --- you need a 3d model of a sphere that is made of triangles, and you then render the triangles. To get the model, you can do it in two way:

  1. You can write an algorithm that procedurally creates it (it is very easy if you use spherical coordinates)
  2. You can create the sphere in another software (blender for example has it as a basic shape) and export it in obj or off format and then load it in your application. If you need to convert between different mesh formats you can use meshlab.
jw3877 commented 7 years ago

Useful link for procedurally generating spheres : https://gamedevdaily.io/four-ways-to-create-a-mesh-for-a-sphere-d7956b825db4#.jeoqp0li2

I used the first one, "Standard Sphere" which uses the spherical coordinates like you mentioned:

`void InitSphere() { int meridians = 5; int parallels = 5;

float r = 1.0f;

for(int j = 0; j < parallels; ++j)
{
    float theta = M_PI * (float)(j + 1) / (float)parallels;

    for(int i = 0; i < meridians; ++i)
    {
        float phi = 2.0f * M_PI * (float)i / (float)meridians;

        float x = r * sin(phi) * cos(theta);
        float y = r * sin(phi) * sin(theta);
        float z = r * cos(phi);

        std::cout << "(" << x << ", " << y << ", " << z << ")" << std::endl;
    }
}

}`

Does this code look correct? I get 25 coordinates from this example -- any tips on how to create the face ordering from these vertices?

(I have the blender sphere but would like to get this working in case I need to procedurally generate a sphere.)

danielepanozzo commented 7 years ago

The code is building up the sphere one "strip" at a time. You can think of every strip as a collection of quadrilaterals, and then split every quadrilateral into 2 triangles.