# Drawing a sphere to buffer array

This topic is 2124 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hey guys

I've got a problem. What I've got is the transformed center and the transformed radius of the sphere.

Now I've got to figure out  how to compute pixel coordinates (x and y) for that sphere to draw.

e.g. something like framebuffer[index] = x + y * width;

I've been trying to loop phi and theta like this:

   for(float phi = 0.0f; phi < 2*M_PI; phi += M_PI / 10.0f)
{
for(float theta = 0.0f; theta < M_PI; theta += M_PI / 10.0f)
{
float x = Screen_Radius * cos(phi) * sin(theta) + Screen_X;
float y = Screen_Radius * sin(phi) * sin(theta) + Screen_Y;
float z = Screen_Radius * cos(theta) + Screen_Z;

float xPixel = x * Width;
float yPixel = y * Height;

const unsigned int index = xPixel + yPixel * Width;


but I don't think that will work, since I don't want to generate seperate vertices but the actual pixel coordinates of where the pixel should be filled or not. The above only gives me garbage. Any ideas ?

I've also tried something which gave me results but I'm not sure if it's correct, looping like this:

for(int y = centerY - R); y <= centerY + R; y++)
{
for(int x = centerX - R; x <= centerX + R; x++)
{
// but how to calculate z for each pixel now ?
}
}

Edited by lipsryme

##### Share on other sites
Hi,

assuming orthographic/parallel projection, the projection of a sphere is a circle with

So instead of constructing all covered pixels by first constructing the sphere using an explicit formula
like you do in your first snippet, you can also do the following:
Test for every pixel, if it is covered by the circle.

It looks like you already do this in your second approach. Even with the optimization of testing
only points inside the bounding rectangle.

An easy way for testing each pixel if it's covered by the circle exploits the observation that the distance
of a covered point from the center of circle is less than or equal to the radius of the circle.

The same observation is true for spheres.

So if you write down the equation for this observation, plug in the x and y coordinates that you already have,
its easy to get the z coordinate.

I noticed you are a student at the games-academy, so if it's homework, make sure you solve the correct problem.
If the exercise states you should do raycasting the approach described above is wrong.

##### Share on other sites

Well no it's actually a perspective projection that I'm doing...

And I don't get it.

What you're saying is that a point on the sphere is <= (x - centerX) ? How does this get me the Z coordinate ?

Atm I'm going through the loop (2. example) and I cut the rectangle like this:

if (dx*dx + dy*dy > R_2)
continue;


is that what you were getting at ? I stil don't see how this gets me z...

The purpose of this is doing some kind of zbuffering for every pixel.

Edited by lipsryme

• 18
• 29
• 11
• 21
• 16