sphere()
Shape / 3D PrimitivesDescription
Draws a sphere. Use sphereDetail() to control tessellation. Must be in P3D mode.
Syntax
void sphere(float r)
Parameters
| Name | Type | Description |
|---|---|---|
| r | float | radius of the sphere |
Returns
voidRelated
Under the Hood
From Processing.h:
void sphere(float r);
inline void PGraphics::sphere(float r) { if(PApplet::g_papplet) PApplet::g_papplet->sphere(r); }
Under the Hood
From Processing.cpp:
void PApplet::sphere(float r){
int stacks=sphereRes, slices=sphereRes;
if(doFill){
// Use Phong (per-pixel) shading when lighting is on for smooth highlights
bool usePhong = lightsEnabled;
if (usePhong) {
initPhongShader();
if (phongProg) {
glUseProgram(phongProg);
GLint loc = glGetUniformLocation(phongProg, "uNumLights");
if (loc >= 0) glUniform1i(loc, lightIndex);
GLint locC = glGetUniformLocation(phongProg, "uLightConc");
if (locC >= 0) glUniform1fv(locC, 8, lightConcentration);
GLint locK = glGetUniformLocation(phongProg, "uLightCutCos");
if (locK >= 0) glUniform1fv(locK, 8, lightCutoffCos);
} else usePhong = false;
}
applyFill();
for(int i=0;i<stacks;i++){
float a0=PI*i/stacks-HALF_PI, a1=PI*(i+1)/stacks-HALF_PI;
glBegin(GL_QUAD_STRIP);
for(int j=0;j<=slices;j++){
float b=TWO_PI*j/slices;
float x1=std::cos(a1)*std::cos(b),y1=std::sin(a1),z1=std::cos(a1)*std::sin(b);
float x0=std::cos(a0)*std::cos(b),y0=std::sin(a0),z0=std::cos(a0)*std::sin(b);
glNormal3f(x1,y1,z1); glVertex3f(r*x1,r*y1,r*z1);
glNormal3f(x0,y0,z0); glVertex3f(r*x0,r*y0,r*z0);
}
glEnd();
}
if (usePhong) glUseProgram(0);
}
if(doStroke){
applyStroke(); glLineWidth(strokeW);
// Draw sphere as a wireframe of triangles -- matches Processing Java's
// sphere appearance with diagonal lines across each quad cell.
auto sv = [&](float lat, float lng) {
glVertex3f(r*std::cos(lat)*std::cos(lng),
r*std::sin(lat),
r*std::cos(lat)*std::sin(lng));
};
glBegin(GL_LINES);
for(int i=0;i<stacks;i++){
float lat0=PI*(-0.5f+(float)i/stacks);
float lat1=PI*(-0.5f+(float)(i+1)/stacks);
for(int j=0;j<slices;j++){
float lng0=TWO_PI*(float)j/slices;
float lng1=TWO_PI*(float)(j+1)/slices;
// Four edges of the quad + one diagonal (like Processing Java)
// Bottom edge (latitude ring)
sv(lat0,lng0); sv(lat0,lng1);
// Left edge (longitude line)
sv(lat0,lng0); sv(lat1,lng0);
// Diagonal (gives the characteristic triangulated look)
sv(lat0,lng1); sv(lat1,lng0);
}
}
// Top latitude ring
{
float lat1=PI*(-0.5f+(float)stacks/stacks);
for(int j=0;j<slices;j++){
float lng0=TWO_PI*(float)j/slices;
float lng1=TWO_PI*(float)(j+1)/slices;
sv(lat1,lng0); sv(lat1,lng1);
}
}
glEnd();
restoreLighting();
}
}