Drawing Sphere in OpenGL without using gluSphere()

2019-01-03 12:02发布

Are there any tutorials out there that explain how I can draw a sphere in OpenGL without having to use gluSphere()?

Many of the 3D tutorials for OpenGL are just on cubes. I have searched but most of the solutions to drawing a sphere are to use gluSphere(). There is also a site that has the code to drawing a sphere at this site but it doesn't explain the math behind drawing the sphere. I have also other versions of how to draw the sphere in polygon instead of quads in that link. But again, I don't understand how the spheres are drawn with the code. I want to be able to visualize so that I could modify the sphere if I need to.

8条回答
不美不萌又怎样
2楼-- · 2019-01-03 12:40

If you wanted to be sly like a fox you could half-inch the code from GLU. Check out the MesaGL source code (http://cgit.freedesktop.org/mesa/mesa/).

查看更多
等我变得足够好
3楼-- · 2019-01-03 12:50

I'll further explain a popular way of generating a sphere using latitude and longitude (another way, icospheres, was already explained in the most popular answer at the time of this writing.)

A sphere can be expressed by the following parametric equation:

F(u, v) = [ cos(u)*sin(v)*r, cos(v)*r, sin(u)*sin(v)*r ]

Where:

  • r is the radius;
  • u is the longitude, ranging from 0 to 2π; and
  • v is the latitude, ranging from 0 to π.

Generating the sphere then involves evaluating the parametric function at fixed intervals.

For example, to generate 16 lines of longitude, there will be 17 grid lines along the u axis, with a step of π/8 (2π/16) (the 17th line wraps around).

The following pseudocode generates a triangle mesh by evaluating a parametric function at regular intervals (this works for any parametric surface function, not just spheres).

In the pseudocode below, UResolution is the number of grid points along the U axis (here, lines of longitude), and VResolution is the number of grid points along the V axis (here, lines of latitude)

var startU=0
var startV=0
var endU=PI*2
var endV=PI
var stepU=(endU-startU)/UResolution // step size between U-points on the grid
var stepV=(endV-startV)/VResolution // step size between V-points on the grid
for(var i=0;i<UResolution;i++){ // U-points
 for(var j=0;j<VResolution;j++){ // V-points
 var u=i*stepU+startU
 var v=j*stepV+startV
 var un=(i+1==UResolution) ? EndU : (i+1)*stepU+startU
 var vn=(j+1==VResolution) ? EndV : (j+1)*stepV+startV
 // Find the four points of the grid
 // square by evaluating the parametric
 // surface function
 var p0=F(u, v)
 var p1=F(u, vn)
 var p2=F(un, v)
 var p3=F(un, vn)
 // NOTE: For spheres, the normal is just the normalized
 // version of each vertex point; this generally won't be the case for
 // other parametric surfaces.
 // Output the first triangle of this grid square
 triangle(p0, p2, p1)
 // Output the other triangle of this grid square
 triangle(p3, p1, p2)
 }
}
查看更多
登录 后发表回答