Draw a sphere: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (J: torgb better fits than tograyscale - the gray of that image is because we're only using one channel of intensity and using it for all three colors - but the conversion routine does support all three...)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(150 intermediate revisions by 54 users not shown)
Line 1:
{{task}} {{requires|Graphics}}
{{requires|Graphics}}
[[Category:3D]]
The task is to draw a sphere.
 
;Task:
The sphere can be represented graphically, or in ascii art,
Draw a sphere.
depending on the language capabilities.
 
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
 
Either static or rotational projection is acceptable for this task.
 
 
;Related tasks:
* [[Draw_a_cuboid|draw a cuboid]]
* [[Draw_a_rotating_cube|draw a rotating cube]]
* [[Write_language_name_in_3D_ASCII|write language name in 3D ASCII]]
* [[Death_Star|draw a Deathstar]]
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V shades = [‘.’, ‘:’, ‘!’, ‘*’, ‘o’, ‘e’, ‘&’, ‘#’, ‘%’, ‘@’]
 
F dotp(v1, v2)
V d = dot(v1, v2)
R I d < 0 {-d} E 0.0
 
F draw_sphere(r, k, ambient, light)
L(i) Int(floor(-r)) .< Int(ceil(r) + 1)
V x = i + 0.5
V line = ‘’
 
L(j) Int(floor(-2 * r)) .< Int(ceil(2 * r) + 1)
V y = j / 2 + 0.5
I x * x + y * y <= r * r
V vec = normalize((x, y, sqrt(r * r - x * x - y * y)))
V b = dotp(light, vec) ^ k + ambient
V intensity = Int((1 - b) * (:shades.len - 1))
line ‘’= I intensity C 0 .< :shades.len {:shades[intensity]} E :shades[0]
E
line ‘’= ‘ ’
 
print(line)
 
V light = normalize((30.0, 30.0, -50.0))
draw_sphere(20, 4, 0.1, light)
draw_sphere(10, 2, 0.4, light)</syntaxhighlight>
 
{{out}}
<pre>
&&&&&&&&&&#######
&eeeeeeeeeeeeeeee&&&&&&#######%
&eoooo*******oooooooeeeee&&&&&########%
eoo****!!!!!!!!******oooooeeee&&&&&########%%
eoo**!!!!::::::::!!!!!*****ooooeeee&&&&&########%%%
eo**!!::::::...:::::::!!!!!***ooooeeee&&&&&########%%%%
eo*!!:::.............:::::!!!!***ooooeeee&&&&&########%%%%%
eo*!!:::.................::::!!!!***ooooeeee&&&&#########%%%%%%
eo*!!::....................::::!!!****oooeeee&&&&&#########%%%%%%
&o**!::......................::::!!!****oooeeee&&&&&##########%%%%%%%
&o**!::.......................::::!!!****oooeeee&&&&&##########%%%%%%%%
&oo*!!::.......................:::!!!!***ooooeeee&&&&&##########%%%%%%%%%
&eo*!!::.......................::::!!!****ooooeeee&&&&&##########%%%%%%%%%%
eo**!!::......................::::!!!!***ooooeeeee&&&&&##########%%%%%%%%%%
&eo**!!:::...................:::::!!!!****ooooeeee&&&&&###########%%%%%%%%%%%
eeo**!!::::................:::::!!!!!****ooooeeee&&&&&&###########%%%%%%%%%%%
&eeo***!!:::::...........::::::!!!!!****oooooeeee&&&&&&###########%%%%%%%%%%%%%
&eeoo**!!!!::::::::::::::::::!!!!!*****ooooeeeee&&&&&&############%%%%%%%%%%%%%
&eeooo***!!!!::::::::::::!!!!!!!*****oooooeeeee&&&&&&############%%%%%%%%%%%%%%
&&eeooo***!!!!!!!!!!!!!!!!!!!******oooooeeeeee&&&&&&############%%%%%%%%%%%%%%%
&&eeeooo******!!!!!!!!!!********ooooooeeeeee&&&&&&&############%%%%%%%%%%%%%%%%
#&&eeeooooo******************oooooooeeeeee&&&&&&&#############%%%%%%%%%%%%%%%%%
#&&&eeeeoooooooo******oooooooooooeeeeeee&&&&&&&&#############%%%%%%%%%%%%%%%%%%
##&&&&eeeeeooooooooooooooooooeeeeeeee&&&&&&&&&##############%%%%%%%%%%%%%%%%%%%
##&&&&&eeeeeeeeeeeeeeeeeeeeeeeeee&&&&&&&&&################%%%%%%%%%%%%%%%%%%%
####&&&&&&eeeeeeeeeeeeeeeeeee&&&&&&&&&&&################%%%%%%%%%%%%%%%%%%%%%
#####&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&#################%%%%%%%%%%%%%%%%%%%%%%
%#######&&&&&&&&&&&&&&&&&&&&&&&&###################%%%%%%%%%%%%%%%%%%%%%%%%
%###########&&&&&&&&&&&&&#######################%%%%%%%%%%%%%%%%%%%%%%%%%
%############################################%%%%%%%%%%%%%%%%%%%%%%%%%%
%%#######################################%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%#################################%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%#########################%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%#############%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%
::...:::!!!*o
..............::!!*oo
..................::!!**ooe
.....................::!!**ooee
.......................::!!**ooee
........................::!!**oooee
.........................::!!**oooeee
:........................::!!!**oooeeee
........................::!!!**ooooeeee
:......................::!!!***oooeeeee
:....................:::!!!***oooeeeeee
!:.................:::!!!****oooeeeeeee
*!:::...........::::!!!!***ooooeeeeeeee
*!!!:::::::::::!!!!!****oooooeeeeeeee
o**!!!!!!!!!!!!!*****oooooeeeeeeeee
oo**************ooooooeeeeeeeeeee
eoooooooooooooooooeeeeeeeeeeeee
eeeooooooooeeeeeeeeeeeeeeee
eeeeeeeeeeeeeeeeeeeee
eeeeeeeeeeeee
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">INT ARRAY SinTab=[
0 4 9 13 18 22 27 31 36 40 44 49 53 58 62 66 71 75 79 83
88 92 96 100 104 108 112 116 120 124 128 132 136 139 143
147 150 154 158 161 165 168 171 175 178 181 184 187 190
193 196 199 202 204 207 210 212 215 217 219 222 224 226
228 230 232 234 236 237 239 241 242 243 245 246 247 248
249 250 251 252 253 254 254 255 255 255 256 256 256 256]
 
INT FUNC Sin(INT a)
WHILE a<0 DO a==+360 OD
WHILE a>360 DO a==-360 OD
IF a<=90 THEN
RETURN (SinTab(a))
ELSEIF a<=180 THEN
RETURN (SinTab(180-a))
ELSEIF a<=270 THEN
RETURN (-SinTab(a-180))
ELSE
RETURN (-SinTab(360-a))
FI
RETURN (0)
 
INT FUNC Cos(INT a)
RETURN (Sin(a-90))
 
PROC Ellipse(INT x0,y0,rx,ry)
INT i
CARD x
BYTE y
 
x=x0+rx*Sin(0)/256
y=y0+ry*Cos(0)/256
Plot(x,y)
FOR i=5 TO 360 STEP 5
DO
x=x0+rx*Sin(i)/256
y=y0+ry*Cos(i)/256
DrawTo(x,y)
OD
RETURN
 
PROC Main()
BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6
INT cx=[160],cy=[96],r=[90],r2
BYTE i
Graphics(8+16)
COLOR1=$0C
COLOR2=$02
Color=1
 
Ellipse(cx,cy,r,r)
FOR i=10 TO 90 STEP 10
DO
r2=r*Cos(i)/256
Ellipse(cx,cy,r,r2)
Ellipse(cx,cy,r2,r)
OD
 
DO UNTIL CH#$FF OD
CH=$FF
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Draw_a_sphere.png Screenshot from Atari 8-bit computer]
 
=={{header|Ada}}==
Line 13 ⟶ 185:
Uses the Cairo component of GtkAda to create and save as png
[[File:SphereAda.png|thumb|right]]
<langsyntaxhighlight Adalang="ada">with Glib; use Glib;
with Cairo; use Cairo;
with Cairo.Png; use Cairo.Png;
Line 42 ⟶ 214:
Status_Out := Write_To_Png (Surface, "SphereAda.png");
pragma Assert (Status_Out = Cairo_Status_Success);
end Sphere;</langsyntaxhighlight>
 
{{libheader|Display}}
This uses a very loose binding to SDL as found in any GPS installation. For it to work, you must choose New Project From Templte|Empty Game
 
<syntaxhighlight lang="ada">
<lang Ada>
with Display; use Display;
with Display.Basic; use Display.Basic;
Line 60 ⟶ 232:
null;
end Main;
</syntaxhighlight>
</lang>
 
=={{header|ALGOL W}}==
{{Trans|AWK}} with some changes inspired by other samples.
<syntaxhighlight lang="algolw">begin
% draw a sphere %
% returns the next integer larger than x or x if x is an integer %
integer procedure ceil( real value x ) ;
begin
integer tmp;
tmp := truncate( x );
if tmp not = x then tmp + 1 else tmp
end ciel ;
% returns the absolute value of the dot product of x and y or 0 if it is not negative %
real procedure dot( real array x, y ( * ) ) ;
begin
real tmp;
tmp := x( 1 ) * y( 1 ) + x( 2 ) * y( 2 ) + x( 3 ) * y( 3 );
if tmp < 0 then - tmp else 0
end dot ;
% normalises the vector v %
procedure normalize( real array v ( * ) ) ;
begin
real tmp;
tmp := sqrt( v( 1 ) * v( 1 ) + v( 2 ) * v( 2 ) + v( 3 ) * v( 3 ) );
for i := 1 until 3 do v( i ) := v( i ) / tmp
end normalize ;
% draws a sphere using ASCII art %
procedure drawSphere( real value radius
; integer value k
; real value ambient
; real array light ( * )
; string(10) value shades
) ;
begin
real array vec ( 1 :: 3 );
integer intensity, maxShades;
real diameter, r2;
maxShades := 9;
diameter := 2 * radius;
r2 := radius * radius;
for i := entier( - radius ) until ceil( radius ) do begin
real x, x2;
integer linePos;
string(256) line;
linePos := 0;
x := i + 0.5;
x2 := x * x;
line := "";
for j := entier( - diameter ) until ceil( diameter ) do begin
real y, y2;
y := j / 2 + 0.5;
y2 := y * y;
if x2 + y2 <= r2 then begin
real b, dp;
vec( 1 ) := x;
vec( 2 ) := y;
vec( 3 ) := sqrt( r2 - x2 - y2 );
normalize( vec );
dp := dot( light, vec );
b := dp;
for p := 2 until k do b := b * dp;
b := b + ambient;
intensity := round( ( 1 - b ) * maxShades );
if intensity < 0 then intensity := 0;
if intensity > maxShades then intensity := maxShades;
line( linePos // 1 ) := shades( intensity // 1 );
end
else line( linePos // 1 ) := " "
;
if linePos < 255 then linePos := linePos + 1
end for_j ;
write( s_w := 0, line( 0 // 1 ) );
for c := 1 until if linePos > 255 then 255 else linePos - 1 do writeon( s_w := 0, line( c // 1 ) )
end for_i
end drawSphere ;
% test drawSphere %
begin
real array light ( 1 :: 3 );
integer maxShades;
light( 1 ) := 30;
light( 2 ) := 30;
light( 3 ) := -59;
normalize( light );
drawSphere( 20, 4, 0.1, light, ".:!*oe#%&@" );
drawSphere( 10, 2, 0.4, light, ".:!*oe#%&@" )
end test
end.</syntaxhighlight>
{{out}}
<pre>
%%%%%%%%%%%%%&&&&
%%#################%%%%%%%&&&&&
%##eeeeeooooooeeeeeee######%%%%%%&&&&&&
##eeooooo*******oooooooeeeee####%%%%%%&&&&&&&
##eooo*****!!!!!!!******oooooeeee####%%%%%%&&&&&&&&
#eeoo**!!!!!!!:::!!!!!!!*****ooooeeee####%%%%%&&&&&&&&&
#eoo**!!!:::::::::::::::!!!!****ooooeeee####%%%%%%&&&&&&&&&
#eeo**!!!::::.........::::::!!!!***ooooeeee####%%%%%%&&&&&&&&&&
#eoo*!!!:::..............:::::!!!!***ooooeee#####%%%%%&&&&&&&&&&&
%#eo**!!:::..................::::!!!****oooeeee####%%%%%%&&&&&&&&&&&&
%#eo**!!:::...................::::!!!!***oooeeee####%%%%%%&&&&&&&&&&&&&
%#eo**!!:::....................::::!!!!***oooeeee####%%%%%%&&&&&&&&&&&&&&
%#eoo**!!::.....................::::!!!****oooeeee####%%%%%%&&&&&&&&&&&&&&&
#eeo**!!:::....................::::!!!!***ooooeeee####%%%%%%&&&&&&&&&&&&&&&
%#eoo**!!::::..................::::!!!!****oooeeee#####%%%%%%&&&&&&&&&&&&&&&&
##eoo**!!!::::...............:::::!!!!****ooooeeee####%%%%%%%&&&&&&&&&&&&&&&&
%##eoo***!!!:::::..........::::::!!!!!****ooooeeee#####%%%%%%%&&&&&&&&&&&&&&&&&
%##eeoo**!!!!::::::::::::::::::!!!!!*****ooooeeee#####%%%%%%%&&&&&&&&&&&&&&&&&&
%##eeooo***!!!!!::::::::::::!!!!!!*****ooooeeeee#####%%%%%%%&&&&&&&&&&&&&&&&&&&
%##eeeooo****!!!!!!!!!!!!!!!!!!******oooooeeeee#####%%%%%%%&&&&&&&&&&&&&&&&&&&&
%%##eeeooo******!!!!!!!!!!!********oooooeeeee######%%%%%%%&&&&&&&&&&&&&&&&&&&&&
%%###eeeooooo******************oooooooeeeeee######%%%%%%%&&&&&&&&&&&&&&&&&&&&&&
&%%###eeeeooooooo*********oooooooooeeeeee#######%%%%%%%%&&&&&&&&&&&&&&&&&&&&&&&
&%%%####eeeeeooooooooooooooooooeeeeeeee#######%%%%%%%%%&&&&&&&&&&&&&&&&&&&&&&&&
&%%%%####eeeeeeeeeeeeeeeeeeeeeeeeee########%%%%%%%%%&&&&&&&&&&&&&&&&&&&&&&&&&
&&%%%%#######eeeeeeeeeeeeeeeee##########%%%%%%%%%%&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&%%%%%%############################%%%%%%%%%%%&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&%%%%%%%#####################%%%%%%%%%%%%%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&%%%%%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&
 
 
!!::::!!!**oo
:...........:::!!**oe
:.................::!!*ooee
:....................::!!**ooee
......................::!!**ooeee
........................::!!**ooeee
:........................::!!**ooeeee
!........................::!!!**ooeeeee
:.......................:::!!**oooeeeee
:......................:::!!***ooeeeeee
!:....................:::!!***oooeeeeee
*!:.................:::!!!***oooeeeeeee
o*!:::..........:::::!!!***ooooeeeeeeee
o*!!!:::::::::::!!!!!***ooooeeeeeeeee
o***!!!!!!!!!!!!*****ooooeeeeeeeeee
eoo*************ooooooeeeeeeeeeee
eeoooooooooooooooeeeeeeeeeeeeee
eeeeeeeeeeeeeeeeeeeeeeeeeee
eeeeeeeeeeeeeeeeeeeee
eeeeeeeeeeeee
</pre>
 
=={{header|Arendelle}}==
Line 71 ⟶ 395:
] [ #i , l ] d
]</pre>
 
=={{header|ATS}}==
<syntaxhighlight lang="text">
(*
** Solution to Draw_a_sphere.dats
*)
 
(* ****** ****** *)
//
#include
"share/atspre_define.hats" // defines some names
#include
"share/atspre_staload.hats" // for targeting C
#include
"share/HATS/atspre_staload_libats_ML.hats" // for ...
#include
"share/HATS/atslib_staload_libats_libc.hats" // for libc
//
(* ****** ****** *)
 
extern
fun
Draw_a_sphere
(
R: double, k: double, ambient: double
) : void // end of [Draw_a_sphere]
 
(* ****** ****** *)
 
implement
Draw_a_sphere
(
R: double, k: double, ambient: double
) = let
fun normalize(v0: double, v1: double, v2: double): (double, double, double) = let
val len = sqrt(v0*v0+v1*v1+v2*v2)
in
(v0/len, v1/len, v2/len)
end // end of [normalize]
fun dot(v0: double, v1: double, v2: double, x0: double, x1: double, x2: double): double = let
val d = v0*x0+v1*x1+v2*x2
val sgn = gcompare_val_val<double> (d, 0.0)
in
if sgn < 0 then ~d else 0.0
end // end of [dot]
fun print_char(i: int): void =
if i = 0 then print!(".") else
if i = 1 then print!(":") else
if i = 2 then print!("!") else
if i = 3 then print!("*") else
if i = 4 then print!("o") else
if i = 5 then print!("e") else
if i = 6 then print!("&") else
if i = 7 then print!("#") else
if i = 8 then print!("%") else
if i = 9 then print!("@") else print!(" ")
val i_start = floor(~R)
val i_end = ceil(R)
val j_start = floor(~2 * R)
val j_end = ceil(2 * R)
val (l0, l1, l2) = normalize(30.0, 30.0, ~50.0)
fun loopj(j: int, j_end: int, x: double): void = let
val y = j / 2.0 + 0.5;
val sgn = gcompare_val_val<double> (x*x + y*y, R*R)
val (v0, v1, v2) = normalize(x, y, sqrt(R*R - x*x - y*y))
val b = pow(dot(l0, l1, l2, v0, v1, v2), k) + ambient
val intensity = 9.0 - 9.0*b
val sgn2 = gcompare_val_val<double> (intensity, 0.0)
val sgn3 = gcompare_val_val<double> (intensity, 9.0)
in
( if sgn > 0 then print_char(10) else
if sgn2 < 0 then print_char(0) else
if sgn3 >= 0 then print_char(8) else
print_char(g0float2int(intensity));
if j < j_end then loopj(j+1, j_end, x)
)
end // end of [loopj]
fun loopi(i: int, i_end: int, j: int, j_end: int): void = let
val x = i + 0.5
val () = loopj(j, j_end, x)
val () = println!()
in
if i < i_end then loopi(i+1, i_end, j, j_end)
end // end of [loopi]
in
loopi(g0float2int(i_start), g0float2int(i_end), g0float2int(j_start), g0float2int(j_end))
end
 
(* ****** ****** *)
 
implement
main0() = () where
{
val () = DrawSphere(20.0, 4.0, .1)
val () = DrawSphere(10.0, 2.0, .4)
} (* end of [main0] *)
 
(* ****** ****** *)
</syntaxhighlight>
 
=={{header|AutoHotkey}}==
{{libheader|GDIP}}
<langsyntaxhighlight lang="ahk">#NoEnv
SetBatchLines, -1
#SingleInstance, Force
Line 130 ⟶ 559:
; gdi+ may now be shutdown on exiting the program
Gdip_Shutdown(pToken)
ExitApp</langsyntaxhighlight>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f DRAW_A_SPHERE.AWK
# converted from VBSCRIPT
BEGIN {
draw_sphere(20,4,0.1)
draw_sphere(10,2,0.4)
exit(0)
}
function draw_sphere(radius,k,ambient, b,i,intensity,j,leng_shades,light,line,shades,vec,x,y) {
leng_shades = split0(".:!*oe&#%@",shades,"")
split("30,30,-50",light,",")
normalize(light)
for (i=int(-radius); i<=ceil(radius); i++) {
x = i + 0.5
line = ""
for (j=int(-2*radius); j<=ceil(2*radius); j++) {
y = j / 2 + 0.5
if (x*x + y*y <= radius*radius) {
vec[1] = x
vec[2] = y
vec[3] = sqrt(radius*radius - x*x - y*y)
normalize(vec)
b = dot(light,vec) ^ k + ambient
intensity = int((1-b) * leng_shades)
if (intensity < 0) {
intensity = 0
}
if (intensity >= leng_shades) {
intensity = leng_shades
}
line = line shades[intensity]
}
else {
line = line " "
}
}
printf("%s\n",line)
}
}
function ceil(x, tmp) {
tmp = int(x)
return (tmp != x) ? tmp+1 : tmp
}
function dot(x,y, tmp) {
tmp = x[1]*y[1] + x[2]*y[2] + x[3]*y[3]
return (tmp < 0) ? -tmp : 0
}
function normalize(v, tmp) {
tmp = sqrt(v[1]*v[1] + v[2]*v[2] + v[3]*v[3])
v[1] /= tmp
v[2] /= tmp
v[3] /= tmp
}
function split0(str,array,fs, arr,i,n) { # same as split except indices start at zero
n = split(str,arr,fs)
for (i=1; i<=n; i++) {
array[i-1] = arr[i]
}
return(n)
}
</syntaxhighlight>
{{out}}
<pre>
############%%%%%
#&&&eeeeeeeee&&&&&&#####%%%%%%%
&eeeoooooooooooooeeeee&&&&#####%%%%%%%%
&eoo***************oooooeeee&&&&####%%%%%%%%%
&eo***!!!!!:::!!!!!!!****ooooeee&&&&#####%%%%%%%%%%
eoo*!!!::::::::::::::!!!!****oooeeee&&&#####%%%%%%%%%%%
eo**!!:::............::::!!!!***oooeeee&&&#####%%%%%%%%%%%%
&eo*!!::.................:::!!!!***oooeee&&&&#####%%%%%%%%%%%%%
eo*!!::...................::::!!!***oooeeee&&&#####%%%%%%%%%%%%%%
#eo*!!::.....................:::!!!***oooeeee&&&&####%%%%%%%%%%%%%%%@
&eo*!!::......................:::!!!***oooeeee&&&&#####%%%%%%%%%%%%%%%@
&eo*!!::......................::::!!!***oooeeee&&&&#####%%%%%%%%%%%%%%%@@
#eo**!!::......................:::!!!****oooeee&&&&#####%%%%%%%%%%%%%%%%%@@
&eo**!:::....................::::!!!!***oooeeee&&&&#####%%%%%%%%%%%%%%%%%@@
&eoo**!!::...................::::!!!!***ooooeee&&&&######%%%%%%%%%%%%%%%%%@@@
&eoo**!!:::................::::!!!!****ooooeee&&&&&#####%%%%%%%%%%%%%%%%%%@@@
#&eoo**!!!::::...........:::::!!!!!****oooeeee&&&&&######%%%%%%%%%%%%%%%%%%@@@@
#&eeoo**!!!!::::::::::::::::!!!!!****ooooeeee&&&&&######%%%%%%%%%%%%%%%%%%%@@@@
#&eeooo***!!!!!::::::::!!!!!!!*****ooooeeeee&&&&&######%%%%%%%%%%%%%%%%%%%@@@@@
#&&eeooo****!!!!!!!!!!!!!!!******oooooeeee&&&&&#######%%%%%%%%%%%%%%%%%%%%@@@@@
##&&eeoooo********************oooooeeeee&&&&&&######%%%%%%%%%%%%%%%%%%%%%%@@@@@
##&&&eeeoooooo***********oooooooeeeeee&&&&&&#######%%%%%%%%%%%%%%%%%%%%%%@@@@@@
%##&&&eeeeeooooooooooooooooooeeeeeee&&&&&&#######%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@
%%###&&&&eeeeeeeeeeoeeeeeeeeeeee&&&&&&&&########%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@
%%###&&&&&&eeeeeeeeeeeeeeee&&&&&&&&&#########%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@
%%%#####&&&&&&&&&&&&&&&&&&&&&&&&##########%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@
%%%%#######&&&&&&&&&&&&&&&############%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@
%%%%%%#############################%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@
%%%%%%%%######################%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@
%%%%%%%%%%%%%%%#####%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@@@@
@%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@@@@@
@@@@%%%%%%%%%%%%@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@
 
::..::::!!**o
.............::!!**oe
..................::!!*ooee
.....................::!!*ooeee
.......................:!!**ooeee
........................:!!**ooeeee
........................::!!**ooeeee&
:........................::!!**ooeeee&&
........................::!!**oooeeee&&
:......................::!!***ooeeeee&&
:....................::!!!***ooeeeee&&&
!::................:::!!***oooeeeeee&&&
*!!::..........::::!!!****oooeeeeee&&&&
**!!::::::::::!!!!!***ooooeeeeee&&&&&
o***!!!!!!!!!!*****ooooeeeeeee&&&&&
eooo*********ooooooeeeeeeee&&&&&&
eeeoooooooooooeeeeeeeeee&&&&&&&
eeeeeeeeeeeeeeeeeee&&&&&&&&
&eeeeeeeeee&&&&&&&&&&
&&&&&&&&&&&&&
 
</pre>
 
=={{header|BASIC}}==
 
==={{header|BASIC256}}===
This is based, but not exactly, on the [http://rosettacode.org/wiki/Draw_a_sphere#Tcl Tcl] implementation.
Thus, the output is almost the same to the output of Tcl implementation below.
<syntaxhighlight lang="basic256">clg
color white
rect 0,0,graphwidth, graphheight
for n = 1 to 100
color rgb(2*n,2*n,2*n)
circle 150-2*n/3,150-n/2,150-n
next n</syntaxhighlight>
 
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
Using Direct3D.
<langsyntaxhighlight lang="bbcbasic"> MODE 8
INSTALL @lib$+"D3DLIB"
D3DTS_VIEW = 2
Line 254 ⟶ 822:
SYS "FreeLibrary", d3dx%
END
</syntaxhighlight>
</lang>
{{out}}
[[File:Sphere_BBC.jpeg]]
Line 262 ⟶ 830:
Some simple 3D objects are built into DarkBASIC. Creating a sphere only takes 1 line:
 
<syntaxhighlight lang ="darkbasic">MAKE OBJECT SPHERE 1,1</langsyntaxhighlight>
 
==={{header|FreeBASIC}}===
<langsyntaxhighlight FreeBASIClang="freebasic">' "\" = a integer division (CPU)
' "/" = a floating point division (FPU)
' the compiler takes care of the conversion between floating point and integer
Line 273 ⟶ 841:
' Sphere using XPL0 code from rosetacode sphere page
' Altered freebasic version to compile in default mode
' version 17-06-2015
' compile with: fbc -s console or fbc -s gui
#Define W 640
#Define H 480
Line 307 ⟶ 876:
Locate 50,2
Color(RGB(255,255,255),RGB(0,0,0)) ' foreground color is changed
' empty keyboard buffer
Print "Enter any key to exit "
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{works with|FreeBASIC}}
needs #Lang "fblite", #Lang "qb" or #Lang "deprecated" to compile.
<langsyntaxhighlight FreeBASIClang="freebasic">'Sphere for FreeBASIC May 2015
'spherefb4.bas
'Sphere using XPL0 code from rosetacode sphere page
Line 347 ⟶ 918:
Print "Enter any key to exit "
sleep
END</langsyntaxhighlight>
 
==={{header|Liberty BASIC}}===
<syntaxhighlight lang="lb">
<lang lb>
WindowWidth =420
WindowHeight =460
Line 377 ⟶ 948:
close #w
end
</syntaxhighlight>
</lang>
 
==={{header|Locomotive Basic}}===
Translated from ERRE version, this will print a 39x20 text sphere onscreen.
The variables in line 80 can be used to adjust size (r), spotlight (k), reflective light (ambient).
<syntaxhighlight lang="locobasic">
10 MODE 2:s$=".:!*oe&#%@"
20 DIM v(2),vec(2)
30 v(0)=30:v(1)=30:v(2)=-50
40 lung=SQR(v(0)*v(0)+v(1)*v(1)+v(2)*v(2))
50 v(0)=v(0)/lung
60 v(1)=v(1)/lung
70 v(2)=v(2)/lung
80 r=10:k=2:ambient=0.4
90 FOR i=INT(-r) TO INT(r)
100 x=i+0.5
110 FOR j=INT(-2*r) TO INT(2*r)
120 y=j/2+0.5
130 IF (x*x+y*y<=r*r) THEN GOSUB 1000 ELSE PRINT" ";
140 NEXT j
150 PRINT
160 NEXT i
170 END
1000 vec(0)=x
1010 vec(1)=y
1020 vec(2)=SQR(r*r-x*x-y*y)
1030 GOSUB 2000
1040 GOSUB 3000
1050 b=d^k+ambient
1060 intensity%=(1-b)*(LEN(s$)-1)
1070 IF (intensity%<0) THEN intensity%=0
1080 IF (intensity%>LEN(s$)-1) THEN intensity%=LEN(s$)-2
1090 PRINT MID$(s$,intensity%+1,1);
1100 RETURN
2000 lung=SQR(vec(0)*vec(0)+vec(1)*vec(1)+vec(2)*vec(2))
2010 vec(0)=vec(0)/lung
2020 vec(1)=vec(1)/lung
2030 vec(2)=vec(2)/lung
2040 RETURN
3000 d=v(0)*vec(0)+v(1)*vec(1)+v(2)*vec(2)
3010 IF d<0 THEN d=-d ELSE d=0
3020 RETURN
</syntaxhighlight>
 
==={{header|PureBasic}}===
3D Sphere animation.
<langsyntaxhighlight PureBasiclang="purebasic">; Original by Comtois @ 28/03/06
;
; Updated/Formated by Fluid Byte @ March.24,2009
Line 631 ⟶ 1,244:
SetMeshData(0,#PB_Mesh_Face,*IBuffer,Length)
EndProcedure</langsyntaxhighlight>
[[image:PB_Animated_sphere.png]]
 
===[[QBasic]]===
 
<langsyntaxhighlight QBASIClang="qbasic">SCREEN 13 ' enter high-color graphic mode
 
' sets palette colors B/N
Line 654 ⟶ 1,267:
' wait until keypress
DO: LOOP WHILE INKEY$ = ""
END</langsyntaxhighlight>
 
==={{header|Run BASIC}}===
<langsyntaxhighlight lang="runbasic">'Run BASIC White Sphere, Black background
'runbasic.com
graphic #win, 300, 300
Line 674 ⟶ 1,287:
next X
next Y
render #win</langsyntaxhighlight>
 
<langsyntaxhighlight Runbasiclang="runbasic">'This is a simple Circle
graphic #g, 300, 300 'create a graphic object
#g place(100,100) 'place the drawing pen at 100,100
#g circle(75) 'make a circle with radius 75
render #g 'show it</langsyntaxhighlight>
 
==={{header|Sinclair ZX81 BASIC}}===
Works with 1k of RAM. A screenshot of the output is [http://www.edmundgriffiths.com/zx81sphere.jpg here].
<syntaxhighlight lang="basic">10 LET I=21
20 LET J=2
30 FOR K=-PI TO PI STEP 0.07
40 PLOT 21+I*SIN K,22+21*COS K
50 PLOT 21+21*SIN K,22+(I-1)*COS K
60 NEXT K
70 LET I=I-J
80 LET J=J+1
90 IF I>0 THEN GOTO 30</syntaxhighlight>
 
=={{header|Batch File}}==
{{trans|C}}
Since Batch Files do not support floating point, the input parameters for drawing the sphere are limited to integers only. The ''k'' parameter has been hardcoded to 2. The <code>ambient</code> variable for this code is scaled up 10 times of its value in C implementation. For example, <code>ambient = 0.1</code> in C code corresponds to <code>ambient = 1</code> here.
Lastly, the variables used in calculations are scaled up 100 times of the actual values in C implementation, and then scaled down 100 times back for determination of shades.
<syntaxhighlight lang="dos">:: Draw a Sphere Task from Rosetta Code
:: Batch File Implementation
@echo off
rem -------------- define arithmetic "functions"
rem more info: https://www.dostips.com/forum/viewtopic.php?f=3&t=6744
 
rem integer sqrt arithmetic function by Aacini, penpen and einstein1969
rem source: https://www.dostips.com/forum/viewtopic.php?f=3&t=5819&start=30#p44016
set "sqrt(N)=( M=(N),j=M/(11*1024)+40, j=(M/j+j)>>1, j=(M/j+j)>>1, j=(M/j+j)>>1, j=(M/j+j)>>1, j=(M/j+j)>>1, j+=(M-j*j)>>31 )"
 
rem -------------- define batch file macros with parameters appended
rem more info: https://www.dostips.com/forum/viewtopic.php?f=3&t=2518
setlocal disabledelayedexpansion % == required for macro ==%
(set \n=^^^
%== this creates escaped line feed for macro ==%
)
 
rem normalize macro
rem argument: v
set normalize=for %%# in (1 2) do if %%#==2 ( %\n%
for /f "tokens=1" %%a in ("!args!") do set "v=%%a" %\n%
set /a "length_sqrd=!v![0]*!v![0]+!v![1]*!v![1]+!v![2]*!v![2]" %\n%
set /a "length=%sqrt(N):N=!length_sqrd!%" %== sqrt(N) applied ==% %\n%
set /a "!v![0]*=100", "!v![1]*=100", "!v![2]*=100" %== normalized elements mult. by 100 ==% %\n%
set /a "!v![0]/=length", "!v![1]/=length", "!v![2]/=length" %\n%
) else set args=
 
rem dot macro
rem arguments: s t outputvar
set dot=for %%# in (1 2) do if %%#==2 ( %\n%
for /f "tokens=1,2,3" %%a in ("!args!") do ( %\n%
set "s=%%a" %\n%
set "t=%%b" %\n%
set "outputvar=%%c" %\n%
) %\n%
set /a "d=!s![0]*!t![0]+!s![1]*!t![1]+!s![2]*!t![2]" %\n%
if !d! lss 0 (set /a "!outputvar!=-d") else (set "!outputvar!=0") %\n%
) else set args=
 
rem -------------- define pseudo-arrays
set "shades[0]=."
set "shades[1]=:"
set "shades[2]=!"
set "shades[3]=*"
set "shades[4]=o"
set "shades[5]=e"
set "shades[6]=&"
set "shades[7]=#"
set "shades[8]=%%"
set "shades[9]=@"
set "num_shades=9" %== start at 0 ==%
set "light[0]=30" & set "light[1]=30" & set "light[2]=-50"
 
rem -------------- main thing: execute drawSphere
setlocal enabledelayedexpansion
%normalize% light %== normalize macro applied ==%
call :drawSphere 20 1
exit /b 0
 
rem -------------- the function to draw the sphere
rem arguments: R ambient
:drawSphere
rem initialize variables from arguments
set /a "R=%1", "negR=-R", "twiceR=R*2", "twiceNegR=negR*2"
set /a "sqrdR=R*R*100*100" %== R*R is mult. by 100*100 ==%
set "k=2" %== k is hardcoded to 2 ==%
set "ambient=%2"
rem start draw line-by-line
for /l %%i in (%negR%, 1, %R%) do (
set /a "x=100*%%i+(100/2)" %== x is mult. by 100 ==%
set "line="
for /l %%j in (%twiceNegR%, 1, %twiceR%) do (
set /a "y=(100/2)*%%j+(100/2)" %== y is mult. by 100 ==%
set /a "pythag = x*x + y*y"
if !pythag! lss !sqrdR! (
set /a "vec[0]=x"
set /a "vec[1]=y"
set /a "vec[2]=sqrdR-pythag"
set /a "vec[2]=%sqrt(N):N=!vec[2]!%" %== sqrt(N) applied ==%
%normalize% vec %== normalize macro applied ==%
%dot% light vec dot_out %== dot macro applied ==%
rem since both light and vec are normalized to 100,
rem then dot_out is scaled up by 100*100 now.
set /a "dot_out/=100" %== scale-down to 100*[actual] to prevent overflow before exponentiation ==%
set "scaleup=1" %== after exponentiation, b would be scaleup*[actual] ==%
set "b=1"
for /l %%? in (1,1,%k%) do set /a "b*=dot_out","scaleup*=100" %== exponentiation ==%
set /a "b+=ambient*scaleup/10" %== add ambient/10 to b ==%
set /a "b/=scaleup/100" %== scale-down to 100*[actual] ==%
set /a "intensity=(100-b)*num_shades"
set /a "intensity/=100" %== final scale-down ==%
if !intensity! lss 0 set "intensity=0"
if !intensity! gtr %num_shades% set "intensity=%num_shades%"
for %%c in (!intensity!) do set "line=!line!!shades[%%c]!"
) else (
set "line=!line! "
)
)
echo(!line!
)
goto :EOF</syntaxhighlight>
{{Out}}
<pre> eeeeeeeeee&&&&&##
eoooo*****ooooooooeeeee&&&&###%
oo******!!!!!********oooooeeee&&&&###%%
o**!!!!!!!!!!!!!!!!!!*****oooooeeee&&&&###%%%
o**!!!!:::::::::::!!!!!!!!!****oooooeee&&&&&###%%%%
o*!!!:::::::::::::::::::!!!!!!*****ooooeeee&&&&####%%%%
o*!!!:::::........:::::::::!!!!!!*****oooeeee&&&&&####%%%%@
o*!!!::::.............::::::::!!!!!!****ooooeeee&&&&####%%%%%@@
**!!::::.................::::::!!!!!!*****ooooeeee&&&&####%%%%%%@
e*!!!::::..................:::::::!!!!!!****ooooeeee&&&&#####%%%%%@@@
o*!!!:::....................::::::!!!!!!!****ooooeeee&&&&&####%%%%%%@@@
e**!!::::....................::::::!!!!!!*****ooooeeee&&&&#####%%%%%%@@@@
e**!!!::::..................::::::::!!!!!!****ooooeeeee&&&&#####%%%%%%%@@@@
o**!!:::::..................:::::::!!!!!!*****ooooeeeee&&&&#####%%%%%%%@@@@
eo*!!!::::::...............::::::::!!!!!!*****ooooeeeee&&&&&#####%%%%%%%@@@@@
o**!!!!:::::::.........::::::::::!!!!!!!*****oooooeeee&&&&&&####%%%%%%%%@@@@@
eo**!!!!!:::::::::::::::::::::::!!!!!!!!*****oooooeeeee&&&&&#####%%%%%%%%@@@@@@
eoo**!!!!!::::::::::::::::::::!!!!!!!!******oooooeeeee&&&&&######%%%%%%%@@@@@@@
eoo***!!!!!:::::::::::::::::!!!!!!!!*******ooooeeeeee&&&&&######%%%%%%%%@@@@@@@
eoo****!!!!!!!!!!:::!:!!!!!!!!!!!!*******oooooeeeeee&&&&&######%%%%%%%%@@@@@@@@
eeoo****!!!!!!!!!!!!!!!!!!!!!!!!********oooooeeeeee&&&&&&#####%%%%%%%%%@@@@@@@@
&eeoo******!!!!!!!!!!!!!!!!!*********ooooooeeeeee&&&&&&######%%%%%%%%%@@@@@@@@@
&eeeooo********!*!!!!!************oooooooeeeeeee&&&&&&######%%%%%%%%%@@@@@@@@@@
#&eeeooooo********************ooooooooeeeeeeee&&&&&&#######%%%%%%%%%@@@@@@@@@@@
&&eeeeoooooooo*********oooooooooooeeeeeeee&&&&&&&&######%%%%%%%%%%@@@@@@@@@@@
#&&&eeeeeooooooooooooooooooooooeeeeeeeee&&&&&&&&#######%%%%%%%%%%@@@@@@@@@@@@
#&&&&eeeeeeeeoooooooooeeeeeeeeeeeeee&&&&&&&&########%%%%%%%%%%@@@@@@@@@@@@@
%##&&&&&eeeeeeeeeeeeeeeeeeeeeeee&&&&&&&&&&########%%%%%%%%%%%@@@@@@@@@@@@@@
%###&&&&&&&&eeeeeeeeeeeee&&&&&&&&&&&&&########%%%%%%%%%%%%@@@@@@@@@@@@@@@
%%####&&&&&&&&&&&&&&&&&&&&&&&&&&###########%%%%%%%%%%%%%@@@@@@@@@@@@@@@
%%%#######&&&&&&&&&&&&&&&&#############%%%%%%%%%%%%%%@@@@@@@@@@@@@@@@
%%%##############################%%%%%%%%%%%%%%%@@@@@@@@@@@@@@@@@
%%%%%%%####################%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@@@@@@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@@@@@@
@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@@@@@@@@
@@%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@%%%%%%%%%%%@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@</pre>
 
=={{header|Befunge}}==
{{trans|C}}
<lang befunge>"o",@</lang>
While based on the C implementation, the algorithm has been considerably simplified to try and avoid floating point (which Befunge doesn't support) and minimise the need for sqrt calculations (which we approximate using the Babylonian method).
{{out}}
<pre>o</pre>
 
The first four values on the stack define the radius (45* = 20) and the light vector (65*65*"2" = 30;30;50). The ''k'' parameter has been hardcoded to 2, and the ambient light is approximated by adjusting the shade characters (defined on the last line).
 
Also note that the z-coordinate of the light vector is negated at runtime to more closely match the C defaults. This is preferable to making the initial constant negative since negative data values aren't supported across all Befunge implementations.
 
<syntaxhighlight lang="befunge">45*65*65*"2"30p20p10p::00p2*40p4*5vv<
>60p140g->:::*00g50g*60g40g-:*-\-v0>1
^_@#`\g0<|`\g04:+1, <*84$$_v#`\0:<>p^
>v>g2+:5^$>g:*++*/7g^>*:9$#<"~"/:"~"v
g:^06,+55<^03*<v09p07%"~"p09/"~"p08%<
^>#0 *#12#<0g:^>+::"~~"90g*80g+*70gv|
g-10g*+:9**00gv|!*`\2\`-20::/2-\/\+<>
%#&eo*!:..^g05<>$030g-*9/\20g*+60g40^</syntaxhighlight>
 
{{out}}
<pre> eeeeeeeeeee&&&&&#
eooo********oooooooeeee&&&&###%
oo****!!!!!!!!********ooooeeeee&&&###%%
o**!!!!!!!!!!!!!!!!!!!*****oooooeeee&&&####%%
o*!!!!:::::::::::::::!!!!!!*****ooooeeee&&&&####%%%
**!!:::::::....::::::::::!!!!!!****ooooeeeee&&&####%%%%
**!!::::.............::::::::!!!!!****ooooeeee&&&&####%%%%%
o*!!::::.................::::::!!!!!!****ooooeeee&&&&####%%%%%%
*!!::::....................::::::!!!!!****ooooeeeee&&&&####%%%%%%
e*!!:::......................::::::!!!!!*****ooooeeee&&&&####%%%%%%%%
o*!!:::.......................::::::!!!!!*****ooooeeee&&&&#####%%%%%%%%
o*!!::::.......................::::::!!!!!****oooooeeee&&&&#####%%%%%%%%%
e**!!:::.......................::::::!!!!!*****ooooeeeee&&&&#####%%%%%%%%%%
o*!!!:::......................:::::::!!!!!*****ooooeeeee&&&&#####%%%%%%%%%%
o**!!!::::...................::::::::!!!!!*****oooooeeee&&&&&#####%%%%%%%%%%%
o**!!!:::::................::::::::!!!!!!*****oooooeeeee&&&&#####%%%%%%%%%%%%
eo**!!!:::::::............:::::::::!!!!!!*****oooooeeeee&&&&&#####%%%%%%%%%%%%%
eo***!!!:::::::::::::::::::::::::!!!!!!******oooooeeeee&&&&&#####%%%%%%%%%%%%%%
eoo**!!!!!::::::::::::::::::::!!!!!!!!******oooooeeeee&&&&&######%%%%%%%%%%%%%%
eoo***!!!!!!:::::::::::::::!!!!!!!!!******ooooooeeeee&&&&&######%%%%%%%%%%%%%%%
eeoo****!!!!!!!!!!!!!!!!!!!!!!!!!*******ooooooeeeeee&&&&&######%%%%%%%%%%%%%%%%
&eooo*****!!!!!!!!!!!!!!!!!!!!********ooooooeeeeee&&&&&&######%%%%%%%%%%%%%%%%%
&eeoooo*******!!!!!!!!!!***********oooooooeeeeeee&&&&&&######%%%%%%%%%%%%%%%%%#
&&eeeoooo***********************ooooooooeeeeeee&&&&&&#######%%%%%%%%%%%%%%%%%%#
&&eeeooooooo**************ooooooooooeeeeeeee&&&&&&#######%%%%%%%%%%%%%%%%%%%#
#&&eeeeeoooooooooooooooooooooooooeeeeeeee&&&&&&&########%%%%%%%%%%%%%%%%%%%##
#&&&eeeeeeeooooooooooooooooeeeeeeeeee&&&&&&&&########%%%%%%%%%%%%%%%%%%%%##
%##&&&&eeeeeeeeeeeeeeeeeeeeeeeeee&&&&&&&&&&########%%%%%%%%%%%%%%%%%%%%%##&
%###&&&&&&eeeeeeeeeeeeeeeeee&&&&&&&&&&&#########%%%%%%%%%%%%%%%%%%%%%%##&
%####&&&&&&&&&&&&&&&&&&&&&&&&&&&&&##########%%%%%%%%%%%%%%%%%%%%%%%%##&
%%######&&&&&&&&&&&&&&&&&&&&############%%%%%%%%%%%%%%%%%%%%%%%%%%##e
%%%################################%%%%%%%%%%%%%%%%%%%%%%%%%%%##&
%%%%%########################%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%###&
%%%%%%%%%###########%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%###&
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%###&
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%##&&
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%###&
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%####&
%%%%%%%%%%%%%%%%%%%%%%%%%%####&
%%%%%%%%%%%%##### </pre>
 
=={{header|Brlcad}}==
 
<langsyntaxhighlight lang="brlcad">opendb balls.g y # Create a database to hold our shapes
units cm # Set the unit of measure
in ball.s sph 0 0 0 3 # Create a sphere of radius 3 cm named ball.s with its centre at 0,0,0 </langsyntaxhighlight>
 
=={{header|C}}==
The lighting calculation is somewhere between crude and bogus, but hey, I'm shading it with ASCII characters, don't expect too much.
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 752 ⟶ 1,579:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre> #############%%%%
Line 818 ⟶ 1,645:
===Fun with 3D noise texture===
[[file:sphere-perlin.png]]
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <math.h>
Line 825 ⟶ 1,652:
int g[] = { -1, 1, -1, 1 };
/* Perlin-like noise */
static inline void
hashed(int *data, int *out, int len) {
# define ror(a, d) ((a << (d)) | (a >> (32 - d)))
Line 979 ⟶ 1,806:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
{{trans|C}}
<langsyntaxhighlight lang="java">using System;
 
namespace Sphere {
Line 1,033 ⟶ 1,860:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
{{libheader|Qt}}
<syntaxhighlight lang="cpp">// Based on https://www.cairographics.org/samples/gradient/
 
#include <QImage>
#include <QPainter>
 
int main() {
const QColor black(0, 0, 0);
const QColor white(255, 255, 255);
 
const int size = 300;
const double diameter = 0.6 * size;
 
QImage image(size, size, QImage::Format_RGB32);
QPainter painter(&image);
painter.setRenderHint(QPainter::Antialiasing);
 
QLinearGradient linearGradient(0, 0, 0, size);
linearGradient.setColorAt(0, white);
linearGradient.setColorAt(1, black);
 
QBrush brush(linearGradient);
painter.fillRect(QRect(0, 0, size, size), brush);
 
QPointF point1(0.4 * size, 0.4 * size);
QPointF point2(0.45 * size, 0.4 * size);
QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);
radialGradient.setColorAt(0, white);
radialGradient.setColorAt(1, black);
 
QBrush brush2(radialGradient);
painter.setPen(Qt::NoPen);
painter.setBrush(brush2);
painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));
 
image.save("sphere.png");
return 0;
}</syntaxhighlight>
 
{{out}}
[[Media:Draw a sphere cpp.png]]
 
=={{header|Clojure}}==
{{libheader|quil}}
<langsyntaxhighlight lang="clojure">
(use 'quil.core)
 
Line 1,058 ⟶ 1,928:
:draw draw
:renderer :opengl)
</syntaxhighlight>
</lang>
 
{{out}}
[http://i.imgur.com/fkzH5wM.png]
 
=={{header|Common Lisp}}==
{{libheader|cl-cairo2}}
 
Saved as a png file and rendered in a X-Window. Unfortunately the file upload isn't working anymore for like four years so I cannot show my results directly.
 
<syntaxhighlight lang="lisp">;; * Loading the cairo bindings
(eval-when (:compile-toplevel :load-toplevel)
(ql:quickload '("cl-cairo2" "cl-cairo2-xlib")))
 
;; * The package definition
(defpackage :sphere
(:use :common-lisp :cl-cairo2))
(in-package :sphere)
 
(defparameter *context* nil)
(defparameter *size* 400)
(defparameter *middle* (/ *size* 2))
 
;; Opening a display and draw a sphere
(let ((width *size*)
(height *size*))
;; Draw to a X-Window
(setf *context*
(create-xlib-image-context width height :window-name "Sphere"))
;; Clear the whole canvas with gray
(rectangle 0 0 width height)
(set-source-rgb 127 127 127)
(fill-path)
;; Draw a the sphere as circa with a radial pattern
(with-patterns ((pat (create-radial-pattern (* 0.9 *middle*) (* 0.8 *middle*) (* 0.2 *middle*)
(* 0.8 *middle*) (* 0.8 *middle*) *middle*)))
(pattern-add-color-stop-rgba pat 0 1 1 1 1)
(pattern-add-color-stop-rgba pat 1 0 0 0 1)
(set-source pat)
(arc *middle* *middle* 180 0 (* 2 pi))
(fill-path))
;; Draw to a png file
(with-png-file ("sphere.png" :rgb24 width height)
;; Clear the whole canvas with gray
(rectangle 0 0 width height)
(set-source-rgb 127 127 127)
(fill-path)
;; Draw a the sphere as circa with a radial pattern
(with-patterns ((pat (create-radial-pattern (* 0.9 *middle*) (* 0.8 *middle*) (* 0.2 *middle*)
(* 0.8 *middle*) (* 0.8 *middle*) *middle*)))
(pattern-add-color-stop-rgba pat 0 1 1 1 1)
(pattern-add-color-stop-rgba pat 1 0 0 0 1)
(set-source pat)
(arc *middle* *middle* 180 0 (* 2 pi))
(fill-path))))</syntaxhighlight>
 
=={{header|ContextFree}}==
<syntaxhighlight lang="contextfree">
startshape SPHERE
 
shape SPHERE {
CIRCLE[]
SPHERE[x 0.1% y 0.1%s 0.99 0.99 b 0.05]
}
</syntaxhighlight>
 
=={{header|Craft Basic}}==
<syntaxhighlight lang="basic">let j = 2
 
for i = 221 to 0 step j * -1
 
for k = -3.14 to 3.14 step .01
 
dot 221 + i * sin(k), 222 + 221 * cos(k)
dot 221 + 221 * sin(k), 222 + (i - 1) * cos(k)
 
wait
 
next k
 
let j = j + 1
 
next i</syntaxhighlight>
 
=={{header|D}}==
{{trans|C}}
<langsyntaxhighlight lang="d">import std.stdio, std.math, std.algorithm, std.numeric;
 
alias V3 = double[3];
Line 1,104 ⟶ 2,053:
drawSphere(20, 4, 0.1);
drawSphere(10, 2, 0.4);
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
Line 1,113 ⟶ 2,062:
'''Steps:''' Run the CMD Windows shell. Then follow this path to setup the new width: '''Main Menu-> Properties -> Layout -> Window Size -> Width'''.
 
<syntaxhighlight lang="delphi">
<lang Delphi>
program DrawASphere;
 
Line 1,184 ⟶ 2,133:
Readln;
end.
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,252 ⟶ 2,201:
[[image:DWScript-sphere.pbm.png|thumb|right|PBM output magnified 5 times]]
{{trans|C}} but adapted to spit out a [[wp:Netpbm_format|PGM]] image
<langsyntaxhighlight lang="delphi">
type
TFloat3 = array[0..2] of Float;
Line 1,308 ⟶ 2,257:
normalize(light);
drawSphere(19, 4, 0.1);
</syntaxhighlight>
</lang>
 
=={{header|Emacs Lisp}}==
{{trans|Go}}
<syntaxhighlight lang="lisp">; Draw a sphere
 
(defun normalize (v)
"Normalize a vector."
(setq invlen (/ 1.0 (sqrt (dot v v))))
(mapcar (lambda (x) (* invlen x)) v))
 
(defun dot (v1 v2)
"Dot product of two vectors."
(+ (* (car v1) (car v2))
(* (cadr v1) (cadr v2))
(* (caddr v1) (caddr v2))))
 
(defun make-array (size)
"Create an empty array with size*size elements."
(setq m-array (make-vector size nil))
(dotimes (i size)
(setf (aref m-array i) (make-vector size 0)))
m-array)
 
(defun pic-lines (arr size)
"Turn array into a string."
(setq all "")
(dotimes (y size)
(setq line "")
(dotimes (x size)
(setq line (concat line (format "%i \n" (elt (elt arr y) x)))))
(setq all (concat all line "\n")))
all)
 
(defun pic-show (arr size)
"Convert size*size array to grayscale PBM image and show it."
(insert-image (create-image (concat (format "P2
%i %i 255\n" size size) (pic-lines arr size)) 'pbm t)))
 
(defun sphere (size k amb dir)
"Draw a sphere."
(let ((arr (make-array size))
(ndir (normalize dir))
(r (/ size 2)))
(dotimes (yp size)
(dotimes (xp size)
(setq x (- xp r))
(setq y (- yp r))
(setq z (- (* r r) (* x x) (* y y)))
(if (>= z 0)
(let* ((vec (normalize (list x y (sqrt z))))
(s (max 0 (dot vec ndir)))
(lum (max 0 (min 255 (* 255 (+ amb (expt s k))
(/ (1+ amb)))))))
(setf (elt (elt arr yp) xp) lum)))))
(pic-show arr size)))
 
(sphere 200 1.5 0.2 '(-30 -30 50))</syntaxhighlight>
 
=={{header|ERRE}}==
Using ASCII art: output is written to 'SPHERE.PRN' sequential file.
<langsyntaxhighlight ERRElang="erre">PROGRAM SPHERE
 
CONST SHADES$=".:!*oe&#%@"
Line 1,366 ⟶ 2,372:
CLOSE(1)
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre> !::::::!!!**o
Line 1,432 ⟶ 2,438:
</pre>
 
=={{header|Evaldraw}}==
 
Draw a sphere. We dont need to wrap the main () function with braces if we have no functions.
 
[[File:Evaldraw draw sphere.png|thumb|alt=A red sphere on a black background.|A red sphere, 5 units in front of camera.]]
 
<syntaxhighlight lang="C">
()
cls(0);
clz(1e32);
setcam(0,0,-5,0,0);
setcol(128,64,64);
drawsph(0,0,0,1);
</syntaxhighlight>
 
=={{header|Factor}}==
{{libheader|raylib}}
{{works with|Factor|0.99 2020-03-02}}
<syntaxhighlight lang="factor">USING: classes.struct kernel raylib.ffi ;
640 480 "sphere" init-window
S{ Camera3D
{ position S{ Vector3 f 4.5 4.5 4.5 } }
{ target S{ Vector3 f 0 0 0 } }
{ up S{ Vector3 f 0 1 0 } }
{ fovy 45.0 }
{ type 0 }
}
60 set-target-fps
[ window-should-close ] [
begin-drawing
BLACK clear-background dup
begin-mode-3d
S{ Vector3 f 0 0 0 } 2 20 20 LIME draw-sphere-wires
end-mode-3d
end-drawing
] until drop close-window</syntaxhighlight>
{{out}}
[https://i.imgur.com/FXHkZm6.png]
 
=={{header|Forth}}==
 
{{works with|gforth|0.7.3}}
Inspired by C version but simplified.
Traditionaly, Forth use Fixed-Point Arithmetic (here with a 1000 scale). Integer square root function is hand coded.
 
===ASCII output===
<syntaxhighlight lang="forth">: 3dup 2 pick 2 pick 2 pick ;
 
: sqrt ( u -- sqrt ) ( Babylonian method )
dup 2/ ( first square root guess is half )
dup 0= if drop exit then ( sqrt[0]=0, sqrt[1]=1 )
begin dup >r 2dup / r> + 2/ ( stack: square old-guess new-guess )
2dup > while ( as long as guess is decreasing )
nip repeat ( forget old-guess and repeat )
drop nip ;
 
: normalize ( x1 y1 z1 -- x1' y1' z1' ) ( normalise down to 1000 )
3dup dup * rot dup * rot dup * + + sqrt 1000 / >r ( length )
r@ / rot r@ / rot r> / rot ;
 
: r2-y2-x2 ( x y r -- z2 ) dup * swap dup * - swap dup * - ;
 
: shade ( u -- c ) C" @#&eo%*!:. " + c@ ;
 
: map-to-shade ( u -- u ) 0 shade * 1000 / 1 max 0 shade min ;
 
: dot-light ( x y z -- i ) ( hard coded light vector z, y, x )
-770 * rot 461 * rot 461 * + +
0 min 1000 / ;
 
: intensity ( x y z -- u ) dot-light dup * 1000 / map-to-shade ;
 
: pixel ( x y r -- c )
3dup r2-y2-x2 dup 0> if ( if in disk )
sqrt nip normalize intensity shade ( z=sqrt[r2-x2-y2] )
else 2drop 2drop bl ( else blank )
then ;
 
: draw ( r -- ) ( r x1000 )
1000 * dup dup negate do
cr
dup dup negate do
dup I 500 + J 500 + rot pixel emit
500 +loop
1000 +loop drop ;
 
20 draw
10 draw</syntaxhighlight>
 
{{out}}
<pre> eeooooeeeeee&&&##
o%%%%******%%%%%%ooooeee&&&##@@
o%**!!!!!!!!!!!!*****%%%%oooeee&&&##@@@
%*!!!:::::::::::::!!!!!****%%%oooeee&&&##@@@@
%*!!:::............:::::!!!!****%%%oooeee&&###@@@@@
%*!::...... ........::::!!!!***%%%oooeee&&&##@@@@@@
%!!::... .....::::!!!!***%%%oooeee&&&##@@@@@@@
%*!::... .....::::!!!****%%%oooee&&&###@@@@@@@@
*!::... .....:::!!!!***%%%oooeee&&&###@@@@@@@@
o*!::.. .....::::!!!***%%%oooeee&&&###@@@@@@@@@@
o*!::.. .....::::!!!***%%%oooeee&&&####@@@@@@@@@@
o*!::... ....::::!!!!***%%%oooeee&&&&###@@@@@@@@@@@
o*!!::.. .....::::!!!****%%%oooeee&&&####@@@@@@@@@@@@
%*!::... .....::::!!!!***%%%%oooeee&&&####@@@@@@@@@@@@
o%*!::.... .....::::!!!!****%%%oooeeee&&&###@@@@@@@@@@@@@@
%**!:::.... ......::::!!!!****%%%ooooeee&&&####@@@@@@@@@@@@@@
e%**!!::..... .......:::::!!!!****%%%ooooeee&&&&####@@@@@@@@@@@@@@@
o%**!!::::.....................:::::!!!!*****%%%ooooeee&&&&####@@@@@@@@@@@@@@@@
o%%**!!:::::...............:::::::!!!!!****%%%%ooooeeee&&&####@@@@@@@@@@@@@@@@@
eo%***!!!:::::::......:::::::::!!!!!!****%%%%%ooooeee&&&&####@@@@@@@@@@@@@@@@@@
eo%%***!!!!:::::::::::::::::!!!!!!******%%%%ooooeeee&&&&####@@@@@@@@@@@@@@@@@@@
eeo%%****!!!!!!!!::::!!!!!!!!!!******%%%%%oooooeeee&&&&####@@@@@@@@@@@@@@@@@@@@
&eoo%%%*****!!!!!!!!!!!!!!!********%%%%%oooooeeee&&&&&####@@@@@@@@@@@@@@@@@@@@@
#&eooo%%%%*********************%%%%%%ooooooeeee&&&&&#####@@@@@@@@@@@@@@@@@@@@@@
&&eeooo%%%%%%************%%%%%%%%ooooooeeeee&&&&&#####@@@@@@@@@@@@@@@@@@@@@@@
#&&eeeoooo%%%%%%%%%%%%%%%%%%%oooooooeeeeee&&&&&#####@@@@@@@@@@@@@@@@@@@@@@@@@
##&&eeeeoooooooooooooooooooooooeeeeeee&&&&&&#####@@@@@@@@@@@@@@@@@@@@@@@@@@
@##&&&eeeeeeooooooooooooooeeeeeeeee&&&&&&######@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@##&&&&&eeeeeeeeeeeeeeeeeeee&&&&&&&&#######@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@###&&&&&&&&&&&&&&&&&&&&&&&&&&########@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@######&&&&&&&&&&&&&&&##########@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@#######################@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@########@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@
o%%%%%%ooe&#@
*!::...:::!!*%%oe&&#@
*:. ..::!!*%ooe&#@@@
*: ..:!!*%ooe&#@@@@
!. ..::!*%%oe&&#@@@@
!. ..::!*%%oee&#@@@@@
!: ..:!!*%%oe&&#@@@@@@
%!. ..:!!**%ooe&&#@@@@@@@
%!:. ..::!!**%ooe&&##@@@@@@@
%!::.. ...:::!!*%%ooee&##@@@@@@@@
o*!!::.......:::!!!**%%oee&&##@@@@@@@@@
eo%*!!!!:::!!!!!**%%%ooee&&##@@@@@@@@@@
#eo%%**********%%%ooeee&&##@@@@@@@@@@@@
#&eooo%%%%%%ooooeee&&&###@@@@@@@@@@@@
##&&eeeeeeeeee&&&&###@@@@@@@@@@@@@@
@@##&&&&&&&&#####@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@ ok</pre>
 
===PGM output===
The same program as the ASCII one is translated to produce a PGM portable pixmap image file.
<syntaxhighlight lang="forth">: 3dup 2 pick 2 pick 2 pick ;
 
: sqrt ( u -- sqrt ) ( Babylonian method )
dup 2/ ( first square root guess is half )
dup 0= if drop exit then ( sqrt[0]=0, sqrt[1]=1 )
begin dup >r 2dup / r> + 2/ ( stack: square old-guess new-guess )
2dup > while ( as long as guess is decreasing )
nip repeat ( forget old-guess and repeat )
drop nip ;
 
: normalize ( x1 y1 z1 -- x1' y1' z1' ) ( normalise down to 1000 )
3dup dup * rot dup * rot dup * + + sqrt 1000 / >r ( length )
r@ / rot r@ / rot r> / rot ;
 
: r2-y2-x2 ( x y r -- z2 ) dup * swap dup * - swap dup * - ;
 
0 value fileidstore
: image-open ( r -- )
outfile-id to fileidstore
s" sphere.pgm" w/o create-file throw to outfile-id
s\" P2\n" type 2* dup . .
s\" \n255" type ;
: image-close outfile-id close-file throw fileidstore to outfile-id ;
 
: map-to-shade 255 * 1000 / 1 max 255 min ;
 
: dot-light ( x y z -- i ) ( hard coded light vector z, y, x )
-770 * rot 461 * rot 461 * + +
0 min 1000 / ;
 
: intensity ( x y z -- u ) dot-light dup * 1000 / map-to-shade ;
 
: pixel ( x y r -- c )
3dup r2-y2-x2 dup 0> if ( if in disk )
sqrt nip normalize intensity ( z=sqrt[r2-x2-y2] )
else 2drop 2drop 255 ( else blank )
then ;
 
: draw ( r -- ) ( r x1000 )
dup image-open
1000 * dup dup negate do
cr
dup dup negate do
dup I 500 + J 500 + rot pixel .
1000 +loop
1000 +loop drop image-close ;
 
200 draw</syntaxhighlight>
 
=={{header|Frink}}==
This program not only draws a sphere and renders it onscreen projected on the x,y, and z axes but also outputs a <CODE>.stl</CODE> file for 3-D printing or display in a 3-D modeling package like MeshLab! Frink has [https://frinklang.org/3d/frink/graphics/package-summary.html built-in routines for 3-D modeling] and can emit STL files or Wavefront OBJ files natively! Frink will let you print a sphere that you can hold in your hand!
<syntaxhighlight lang="frink">res = 254 / in
v = callJava["frink.graphics.VoxelArray", "makeSphere", [1/2 inch res]]
 
v.projectX[undef].show["X"]
v.projectY[undef].show["Y"]
v.projectZ[undef].show["Z"]
 
filename = "sphere.stl"
print["Writing $filename..."]
w = new Writer[filename]
w.println[v.toSTLFormat["sphere", 1/(res mm)]]
w.close[]
println["done."]</syntaxhighlight>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
_window = 1
begin enum output 1
_sphereImageView
end enum
 
void local fn BuildWindow
CGRect r = fn CGRectMake( 0, 0, 400, 400 )
window _window, @"Rosetta Code Sphere", r, NSWindowStyleMaskTitled + NSWindowStyleMaskClosable
r = fn CGRectMake( 20, 20, 360, 360 )
imageview _sphereImageView, YES, , r, NSImageScaleAxesIndependently, NSImageAlignCenter, NSImageFrameNone, _window
end fn
 
local fn SphereImageWithCIFilter( imageDimension as NSUInteger, sphereColor as ColorRef, backgroundColor as ColorRef, radiusBlur as float, radiusSphere as float ) as ImageRef
CIVectorRef civ = fn CIVectorWithXY( imageDimension/2, imageDimension/2 )
CIFilterRef filter = fn CIFilterWithName( @"CIRadialGradient" )
CIFilterSetDefaults( filter )
ObjectSetValueForKey( filter, civ, @"inputCenter" )
ObjectSetValueForKey( filter, fn NumberWithFloat( radiusBlur ), @"inputRadius0" )
ObjectSetValueForKey( filter, fn NumberWithFloat( radiusSphere ), @"inputRadius1" )
ObjectSetValueForKey( filter, fn CIColorWithCGColor( fn ColorCGColor( sphereColor ) ), @"inputColor0" )
ObjectSetValueForKey( filter, fn CIColorWithCGColor( fn ColorCGColor( backgroundColor ) ), @"inputColor1" )
ImageRef resultImage = fn ImageWithSize( fn CGSizeMake( imageDimension, imageDimension ) )
ImageLockFocus( resultImage )
CIImageDrawAtPoint( fn CIFilterOutputImage( filter ), CGPointZero, fn CGRectMake( 0, 0, imageDimension, imageDimension ), NSCompositeDestinationAtop, 1.0 )
ImageUnlockFocus( resultImage )
end fn = resultImage
 
local fn BuildSphere
ImageRef sphereImage = fn SphereImageWithCIFilter( 340, fn ColorWithRGB( 0.988, 0.335, 0.176, 1.0 ), fn ColorBlack, 0.0, 125.0 )
ImageViewSetImage( _sphereImageView, sphereImage )
end fn
 
fn BuildWindow
fn BuildSphere
 
HandleEvents
</syntaxhighlight>
{{output}}
[[File:Rosetta Code Sphere.png]]
 
=={{header|Go}}==
Line 1,437 ⟶ 2,709:
{{trans|C}}
Using image library rather than ASCII art.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,504 ⟶ 2,776:
fmt.Println(err)
}
}</langsyntaxhighlight>
 
=={{header|HTML}}==
 
See [[Draw_a_sphere#Javascript]]
 
=={{header|Haskell}}==
[[File:Sphere_Haskell.png|thumb|right]]
<langsyntaxhighlight lang="haskell">import Graphics.Rendering.OpenGL.GL
import Graphics.UI.GLUT.Objects
import Graphics.UI.GLUT
Line 1,559 ⟶ 2,827:
setMaterial
displayCallback $= display
mainLoop</langsyntaxhighlight>
 
=== ASCII art ===
{{trans|Python}}
 
<syntaxhighlight lang="haskell">import Data.List (genericLength)
 
shades = ".:!*oe%#&@"
n = genericLength shades
dot a b = sum $ zipWith (*) a b
normalize x = (/ sqrt (x `dot` x)) <$> x
 
sphere r k amb light = unlines $
[ [ if x*x + y*y <= r*r
then let vec = normalize [x, y, sqrt (r*r-x*x-y*y)]
b = (light `dot` vec) ** k + amb
intensity = (1 - b)*(n - 1)
in shades !! round ((0 `max` intensity) `min` n)
else ' '
| y <- map (/2.12) [- 2*r - 0.5 .. 2*r + 0.5] ]
| x <- [ - r - 0.5 .. r + 0.5] ]</syntaxhighlight>
 
<pre>λ> putStrLn $ sphere 10 4 0.1 (normalize [30,30,-50])
#%%%%%%%####&&
eoo*****oooee%%%###&&&
eo*!!::::!!!**ooee%%%###&&&&
e*!::......::!!**ooee%%####&&&&&
%o!::.........::!!**ooee%%###&&&&&&&
eo!::..........::!!**ooee%%###&&&&&&&&
%o*!:..........::!!**ooee%%%###&&&&&&&&&
#eo*!::.......:::!!**ooeee%%####&&&&&&&&&&
%eo*!!:::::::::!!***ooeee%%####&&&&&&&&&&&
%eeo**!!!!!!!!****ooeee%%%####&&&&&&&&&&&&
#%eeooo*******ooooeee%%%%####&&&&&&&&&&&&&
##%%eeeoooooooeeeee%%%%####&&&&&&&&&&&&&&&
&###%%%%eeeeee%%%%%%######&&&&&&&&&&&&&&&#
&&####%%%%%%%%########&&&&&&&&&&&&&&&&&&
&&&##############&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&#
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&#
 
</pre>
 
==Icon and {{header|Unicon}}==
Unicon provides a built-in interface to openGL including some higher level abstractions (for more information see [[Icon%2BUnicon/Intro#Graphics.2C_Network_Messaging.2C_etc.|Unicon Technical References, 3D Graphics]]). The example below draws a blue sphere on a black background and waits for input to quit.[[File:Sphere_unicon.PNG|thumb|Unicon Sphere]]
 
<langsyntaxhighlight Uniconlang="unicon">procedure main()
W := open("Demo", "gl", "size=400,400", "bg=black") | stop("can't open window!")
WAttrib(W, "slices=40", "rings=40", "light0=on, ambient white; diffuse gold; specular gold; position 5, 0, 0" )
Line 1,570 ⟶ 2,884:
DrawSphere(W, 0, 0, -5, 1)
Event(W)
end</langsyntaxhighlight>
 
<div style="border: 1px solid #000000; overflow: auto; width: 100%"></div>
=={{header|J}}==
 
=={{header|J}}==
===Demo Solution===
[[File:J-sphere.png|thumb|J Sphere]]
 
Line 1,588 ⟶ 2,902:
But bringing up the example with a line of code is trivial enough:
 
<langsyntaxhighlight lang="j">load '~system/examples/graphics/opengl/simple/sphere.ijs'</langsyntaxhighlight>
 
(Note that this example has been removed from recent versions of J, but still works for J version 5 and version 6.)
<div style="border: 1px solid #000000; overflow: auto; width: 100%"></div>
 
Line 1,595 ⟶ 2,911:
Here's a version using raytracing computed in J. luminosity is an array of luminosity values with theoretical maximum 1 and minimum 0, and viewmat is used to display this.
 
<langsyntaxhighlight lang="j">'R k ambient' =. 10 2 0.4
light =. (% +/&.:*:) 30 30 _50
pts =. (0&*^:(0={:))@:(,,(0>.(*:R)-+)&.*:)"0/~ i:15j200
Line 1,602 ⟶ 2,918:
load 'viewmat'
torgb =. 256 #. [: <. 255 255 255 *"1 0 ]
'rgb' viewmat torgb luminosity</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|C}}
<langsyntaxhighlight lang="java">public class Sphere{
static char[] shades = {'.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'};
 
Line 1,648 ⟶ 2,964:
drawSphere(10, 2, .4);
}
}</langsyntaxhighlight>
{{out}}
<pre> &&&&&&&&&&#######
Line 1,712 ⟶ 3,028:
eeeeeeeeeeeee
</pre>
 
=={{header|JavaScript}}==
 
Line 1,718 ⟶ 3,035:
This Javascript entry uses an HTML wrapper to offer easy running and some interactivity. It is made as such, though, that the entire HTML wrapper can be removed (except for a canvas with id <code>c</code>) and still work. If you remove the HTML, call the <code>draw_sphere</code> function to draw the thing.
 
<langsyntaxhighlight lang="javascript"><!DOCTYPE html>
<html>
<head>
Line 1,779 ⟶ 3,096:
<canvas id="c">Unsupportive browser...</canvas><br>
</body>
</html></langsyntaxhighlight>
 
=={{header|jq}}==
{{works with|jq|1.4}}
The approach adopted here is to generate an SVG file, which may then be viewed, for example, in a web browser.
<langsyntaxhighlight lang="jq">def svg:
"<svg width='100%' height='100%' version='1.1'
xmlns='http://www.w3.org/2000/svg'
Line 1,802 ⟶ 3,119:
 
def sphere(cx; cy; r; gradientId):
"<circle fill='url(#\(gradientId))' cx='\(cx)' cy='\(cy)' r='\(r)' />" ;</langsyntaxhighlight>
 
'''Example:'''
<langsyntaxhighlight lang="jq">def draw_sphere:
svg,
"<title>Teal sphere</title>",
Line 1,813 ⟶ 3,130:
"</svg>" ;
draw_sphere</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -r -n -f spheres.jq > spheres.svg</langsyntaxhighlight>
 
One way to view the output as an image is to point your browser to the generated SVG.
 
=={{header|Julia}}==
===ASCII Text===
{{trans|C}}
<syntaxhighlight lang="julia">function draw_sphere(r, k, ambient, light)
shades = ('.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@')
for i in floor(Int, -r):ceil(Int, r)
x = i + 0.5
line = IOBuffer()
for j in floor(Int, -2r):ceil(2r)
y = j / 2 + 0.5
if x ^ 2 + y ^ 2 ≤ r ^ 2
v = normalize([x, y, sqrt(r ^ 2 - x ^ 2 - y ^ 2)])
b = dot(light, v) ^ k + ambient
intensity = ceil(Int, (1 - b) * (length(shades) - 1))
if intensity < 1
intensity = 1 end
if intensity > length(shades)
intensity = length(shades) end
print(shades[intensity])
else
print(' ')
end
end
println()
end
end
 
light = normalize([30, 30, -50])
draw_sphere(20, 4, 0.1, light)
draw_sphere(10, 2, 0.4, light)
</syntaxhighlight>
===Graphical===
<syntaxhighlight lang="julia"># run from REPL
 
using Makie
 
φ = 0:π/100:2π
 
θ = 0:π/200:π
 
x = [cos(θ) * sin(φ) for θ in θ, φ in φ]
y = [sin(θ)*sin(φ) for θ in θ, φ in φ]
z = [cos(φ) for θ in θ, φ in φ]
 
surface(x, y, z, backgroundcolor = :black, show_axis = false)
</syntaxhighlight>
 
=={{header|Kotlin}}==
{{trans|C}}
<syntaxhighlight lang="scala">// version 1.0.6
 
const val shades = ".:!*oe&#%@"
val light = doubleArrayOf(30.0, 30.0, -50.0)
 
fun normalize(v: DoubleArray) {
val len = Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2])
v[0] /= len; v[1] /= len; v[2] /= len
}
 
fun dot(x: DoubleArray, y: DoubleArray): Double {
val d = x[0] * y[0] + x[1] * y[1] + x[2] * y[2]
return if (d < 0.0) -d else 0.0
}
 
fun drawSphere(r: Double, k: Double, ambient: Double) {
val vec = DoubleArray(3)
var intensity: Int
var b : Double
var x: Double
var y: Double
for (i in Math.floor(-r).toInt() .. Math.ceil(r).toInt()) {
x = i + 0.5
for (j in Math.floor(-2.0 * r).toInt() .. Math.ceil(2.0 * r).toInt()) {
y = j / 2.0 + 0.5
if (x * x + y * y <= r * r) {
vec[0] = x
vec[1] = y
vec[2] = Math.sqrt(r * r - x * x - y * y)
normalize(vec)
b = Math.pow(dot(light, vec), k) + ambient
intensity = ((1.0 - b) * (shades.length - 1)).toInt()
if (intensity < 0) intensity = 0
if (intensity >= shades.length - 1) intensity = shades.length - 2
print(shades[intensity])
}
else print(' ')
}
println()
}
}
 
fun main(args: Array<String>) {
normalize(light)
drawSphere(20.0, 4.0, 0.1)
drawSphere(10.0, 2.0, 0.4)
}</syntaxhighlight>
 
{{out}}
<pre>
&&&&&&&&&&#######
&eeeeeeeeeeeeeeee&&&&&&#######%
&eoooo*******oooooooeeeee&&&&&########%
eoo****!!!!!!!!******oooooeeee&&&&&########%%
eoo**!!!!::::::::!!!!!*****ooooeeee&&&&&########%%%
eo**!!::::::...:::::::!!!!!***ooooeeee&&&&&########%%%%
eo*!!:::.............:::::!!!!***ooooeeee&&&&&########%%%%%
eo*!!:::.................::::!!!!***ooooeeee&&&&#########%%%%%%
eo*!!::....................::::!!!****oooeeee&&&&&#########%%%%%%
&o**!::......................::::!!!****oooeeee&&&&&##########%%%%%%%
&o**!::.......................::::!!!****oooeeee&&&&&##########%%%%%%%%
&oo*!!::.......................:::!!!!***ooooeeee&&&&&##########%%%%%%%%%
&eo*!!::.......................::::!!!****ooooeeee&&&&&##########%%%%%%%%%%
eo**!!::......................::::!!!!***ooooeeeee&&&&&##########%%%%%%%%%%
&eo**!!:::...................:::::!!!!****ooooeeee&&&&&###########%%%%%%%%%%%
eeo**!!::::................:::::!!!!!****ooooeeee&&&&&&###########%%%%%%%%%%%
&eeo***!!:::::...........::::::!!!!!****oooooeeee&&&&&&###########%%%%%%%%%%%%%
&eeoo**!!!!::::::::::::::::::!!!!!*****ooooeeeee&&&&&&############%%%%%%%%%%%%%
&eeooo***!!!!::::::::::::!!!!!!!*****oooooeeeee&&&&&&############%%%%%%%%%%%%%%
&&eeooo***!!!!!!!!!!!!!!!!!!!******oooooeeeeee&&&&&&############%%%%%%%%%%%%%%%
&&eeeooo******!!!!!!!!!!********ooooooeeeeee&&&&&&&############%%%%%%%%%%%%%%%%
#&&eeeooooo******************oooooooeeeeee&&&&&&&#############%%%%%%%%%%%%%%%%%
#&&&eeeeoooooooo******oooooooooooeeeeeee&&&&&&&&#############%%%%%%%%%%%%%%%%%%
##&&&&eeeeeooooooooooooooooooeeeeeeee&&&&&&&&&##############%%%%%%%%%%%%%%%%%%%
##&&&&&eeeeeeeeeeeeeeeeeeeeeeeeee&&&&&&&&&################%%%%%%%%%%%%%%%%%%%
####&&&&&&eeeeeeeeeeeeeeeeeee&&&&&&&&&&&################%%%%%%%%%%%%%%%%%%%%%
#####&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&#################%%%%%%%%%%%%%%%%%%%%%%
%#######&&&&&&&&&&&&&&&&&&&&&&&&###################%%%%%%%%%%%%%%%%%%%%%%%%
%###########&&&&&&&&&&&&&#######################%%%%%%%%%%%%%%%%%%%%%%%%%
%############################################%%%%%%%%%%%%%%%%%%%%%%%%%%
%%#######################################%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%#################################%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%#########################%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%#############%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%
 
::...:::!!!*o
..............::!!*oo
..................::!!**ooe
.....................::!!**ooee
.......................::!!**ooee
........................::!!**oooee
.........................::!!**oooeee
:........................::!!!**oooeeee
........................::!!!**ooooeeee
:......................::!!!***oooeeeee
:....................:::!!!***oooeeeeee
!:.................:::!!!****oooeeeeeee
*!:::...........::::!!!!***ooooeeeeeeee
*!!!:::::::::::!!!!!****oooooeeeeeeee
o**!!!!!!!!!!!!!*****oooooeeeeeeeee
oo**************ooooooeeeeeeeeeee
eoooooooooooooooooeeeeeeeeeeeee
eeeooooooooeeeeeeeeeeeeeeee
eeeeeeeeeeeeeeeeeeeee
eeeeeeeeeeeee
</pre>
 
=={{header|Lingo}}==
<syntaxhighlight lang="lingo">----------------------------------------
-- Draw a circle
-- @param {image} img
-- @param {integer} x
-- @param {integer} y
-- @param {integer} r
-- @param {integer} lineSize
-- @param {color} drawColor
----------------------------------------
on circle (img, x, y, r, lineSize, drawColor)
props = [:]
props[#shapeType] = #oval
props[#lineSize] = lineSize
props[#color] = drawColor
img.draw(x-r, y-r, x+r, y+r, props)
end</syntaxhighlight>
 
=={{header|Logo}}==
Line 1,825 ⟶ 3,321:
{{works with|MSWlogo}}
 
<langsyntaxhighlight lang="logo">to sphere :r
cs perspective ht ;making the room ready to use
repeat 180 [polystart circle :r polyend down 1]
polyview
end</langsyntaxhighlight>
 
=={{header|Lua}}==
{{trans|C}}
{{works with|Lua|5.1.4}}
<langsyntaxhighlight Lualang="lua">require ("math")
 
shades = {'.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'}
Line 1,870 ⟶ 3,366:
 
draw_sphere (20, 4, 0.1)
draw_sphere (10, 2, 0.4)</langsyntaxhighlight>
{{out}}
<pre> &&&&&&&&&&&&#####
Line 1,934 ⟶ 3,430:
eeeeeeeeeeeee
</pre>
 
=={{header|MathematicaM2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
Er$="Pset is a new statement"
If Version<9.4 Then Error Er$
If Version=9.4 then If revision<26 then Error Er$
Form 60, 40
Cls 0 ' Black
Gradient 0,1
Pen 14 ' Yellow
Set Fast !
Refresh 500
Module Sphere (R as long, X0 as long, Y0 as long, fun){
R2 = R * R
Def Long X, Y, D2
Let Scale=twipsx/R*13.5
For Y = -R To R step twipsx {
Move X0-R, Y+Y0
For X = -R To R step twipsy {
D2 = X **2 + Y **2
IF R2>D2 THEN Pset Fun(Max.Data(Min.Data((Sqrt(R2 - D2) - ( X + Y) / 2 )*Scale ,255),0))
Step twipsx
}
}
}
Blue=lambda (c)->{
c1=c/4+192
=Color(c,c,c1)
}
Blue1=lambda (c)->{
c1=c/4+Random(150,192)
=Color(c,c,c1)
}
Mystery=lambda m=1 (c)->{
c1=c/4+m
m+=10
if m>192 then m=1
=Color(c,c,c1)
}
Mystery2=lambda m=1, p=true (c)->{
c1=c/4+m
if p then m+=10
Else m=-10
if m>192 then m-=10 : p=false
If m<0 then m+=10: p=true
=Color(c,c,c1)
}
Buffer Alfa as byte*8
Trans =lambda Alfa (c) -> {
Return Alfa, 0:=-point as long
Return Alfa, 4:=-color(c,c, c/4+192) as long
for i=0 to 2: Return Alfa, i:=(Eval(Alfa, i)+Eval(Alfa, i+4))/2: Next i
=-Eval(Alfa, 0 as long)
}
Sphere 2400, 9000,7000, Blue
Sphere 800, 6000, 7000, Blue1
Sphere 1200, 5000,5000, Mystery
Sphere 1200, 10000,6000, Mystery2
Sphere 1200, 8000,5000, trans
}
Checkit
</syntaxhighlight>
 
[[https://2.bp.blogspot.com/-ZWy2xDxXbzg/W98lAuNSY9I/AAAAAAAAHZ0/DFYluvWtz_cwwAUKfblujnW6mTC5XVs1QCLcBGAs/s1600/sphere.png]image]
 
=={{header|Maple}}==
[[File:Sphere_Maple.png|thumb]]
<syntaxhighlight lang="maple">plots[display](plottools[sphere](), axes = none, style = surface);</syntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Mathematica has many 3D drawing capabilities. To create a sphere with radius one centered at (0,0,0):
<langsyntaxhighlight Mathematicalang="mathematica">Graphics3D[Sphere[{0,0,0},1]]</langsyntaxhighlight>
 
=={{header|MATLAB}}==
To create the unit sphere:
<syntaxhighlight lang="matlab">figure; sphere</syntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">/* Two solutions */
plot3d(1, [theta, 0, %pi], [phi, 0, 2 * %pi],
[transform_xy, spherical_to_xyz], [grid, 30, 60],
Line 1,950 ⟶ 3,519:
sin(phi)*sin(theta),
cos(theta),
theta, 0, %pi, phi, 0, 2 * %pi))$</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|C}}
<langsyntaxhighlight lang="nim">import math
 
type Point = tuple[x,y,z: float]
Line 1,969 ⟶ 3,538:
let light = normalize(30.0, 30.0, -50.0)
 
proc drawSphere(r,: int; k, ambient: float) =
for i in -r .. r:
let x = i.float + 0.5
Line 1,984 ⟶ 3,553:
 
drawSphere 20, 4.0, 0.1
drawSphere 10, 2.0, 0.4</langsyntaxhighlight>
{{out}}
<pre> &&&&&&&&&&#######
Line 2,047 ⟶ 3,616:
eeeeeeeeeeeeeeeeeeeee
eeeeeeeeeeeee</pre>
 
=={{header|Ol}}==
{{libheader|OpenGL}}
<syntaxhighlight lang="scheme">
(import (lib gl))
(import (OpenGL version-1-0))
 
; init
(glClearColor 0.3 0.3 0.3 1)
(glPolygonMode GL_FRONT_AND_BACK GL_FILL)
 
(define quadric (gluNewQuadric))
 
; draw loop
(gl:set-renderer (lambda (mouse)
(glClear GL_COLOR_BUFFER_BIT)
 
(glColor3f 0.7 0.7 0.7)
(gluSphere quadric 0.4 32 10)
))
</syntaxhighlight>
 
=={{header|Openscad}}==
Drawing a sphere is easy in openscad:
 
<langsyntaxhighlight lang="openscad">// This will produce a sphere of radius 5
sphere(5);</langsyntaxhighlight>
 
[[Category:Geometric Primitives]]
 
=={{header|OxygenBasic}}==
Using an OpenGl-based console
<syntaxhighlight lang="text">
% Title "Sphere"
'% Animated
% PlaceCentral
uses ConsoleG
 
sub main
========
cls 0.0, 0.2, 0.7
shading
scale 10
pushstate
GoldMaterial.act
go sphere
popstate
end sub
 
EndScript
</syntaxhighlight>
 
=={{header|Pascal}}==
{{works with|Free_Pascal}}
After changing "{$APPTYPE CONSOLE}" to "{$mode delphi}" or "{$mode objfpc}" the Delphi example works with FreePascal.
 
 
=={{header|Perl}}==
{{trans|Perl 6Raku}}
 
This produces a PGM image which can't be uploaded on rosettacode at the moment. It looks similar as the Perl 6Raku solution, though.
 
<langsyntaxhighlight lang="perl">use strict;
use warnings;
 
Line 2,116 ⟶ 3,727:
},
q{""} => sub { sprintf "Vector:[%s]", join ' ', @{shift()} };
}</langsyntaxhighlight>
 
=={{header|Perl 6Phix}}==
{{translibheader|CPhix/pGUI}}
{{libheader|Phix/online}}
 
{{trans|Go}} (Go gets credit for the dot/normalize/drawSphere routines, but this draws on screen rather than to png file)
The C code is modified to output a .pgm file.
Sphere will resize to match the window.
 
You can run this online [http://phix.x10.mx/p2js/drawsphere.htm here]. Note fullscreen redraw can be quite slow.
[[File:Sphere-perl6.png|thumb]]
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang perl6>my $x = my $y = 255;
<span style="color: #000080;font-style:italic;">--
$x +|= 1; # must be odd
-- demo\rosetta\Draw_a_sphere.exw
 
-- ==============================
my @light = normalize([ 3, 2, -5 ]);
--</span>
 
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
my $depth = 255;
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
 
sub MAIN ($outfile = 'sphere-perl6.pgm') {
<span style="color: #008080;">constant</span> <span style="color: #000000;">title</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"Draw a sphere"</span>
my $out = open( $outfile, :w, :bin ) or die "$!\n";
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">canvas</span>
$out.say("P5\n$x $y\n$depth"); # .pgm header
<span style="color: #004080;">cdCanvas</span> <span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cdcanvas</span>
$out.write( Blob.new(draw_sphere( ($x-1)/2, .9, .2) ) );
$out.close;
<span style="color: #008080;">function</span> <span style="color: #000000;">dot</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">)</span>
}
<span style="color: #008080;">return</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">))</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
sub normalize (@vec) { return @vec »/» ([+] @vec Z* @vec).sqrt }
 
<span style="color: #008080;">function</span> <span style="color: #000000;">normalize</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">v</span><span style="color: #0000FF;">)</span>
sub dot (@x, @y) { return -([+] @x Z* @y) max 0 }
<span style="color: #004080;">atom</span> <span style="color: #000000;">len</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dot</span><span style="color: #0000FF;">(</span><span style="color: #000000;">v</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">v</span><span style="color: #0000FF;">))</span>
 
<span style="color: #008080;">return</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">len</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">?{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">}:</span><span style="color: #7060A8;">sq_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">v</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">/</span><span style="color: #000000;">len</span><span style="color: #0000FF;">))</span>
sub draw_sphere ( $rad, $k, $ambient ) {
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
my @pixels;
my $r2 = $rad * $rad;
<span style="color: #008080;">procedure</span> <span style="color: #000000;">drawSphere</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">width</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">height</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">amb</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">direction</span><span style="color: #0000FF;">)</span>
my @range = -$rad .. $rad;
<span style="color: #004080;">atom</span> <span style="color: #000000;">t0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">t0</span><span style="color: #0000FF;">,</span>
for @range X @range -> $x, $y {
<span style="color: #000000;">lmul</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">255</span><span style="color: #0000FF;">/(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">+</span><span style="color: #000000;">amb</span><span style="color: #0000FF;">)</span>
if (my $x2 = $x * $x) + (my $y2 = $y * $y) < $r2 {
<span style="color: #004080;">integer</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">((</span><span style="color: #7060A8;">min</span><span style="color: #0000FF;">(</span><span style="color: #000000;">width</span><span style="color: #0000FF;">,</span><span style="color: #000000;">height</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">20</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">),</span>
my @vector = normalize([$x, $y, ($r2 - $x2 - $y2).sqrt]);
<span style="color: #000000;">cx</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">width</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">),</span>
my $intensity = dot(@light, @vector) ** $k + $ambient;
<span style="color: #000000;">cy</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">height</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
my $pixel = (0 max ($intensity * $depth).Int) min $depth;
<span style="color: #008080;">for</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">=-</span><span style="color: #000000;">r</span> <span style="color: #008080;">to</span> <span style="color: #000000;">r</span> <span style="color: #008080;">do</span>
@pixels.push($pixel);
<span style="color: #008080;">if</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()></span><span style="color: #000000;">t1</span> <span style="color: #008080;">then</span>
}
<span style="color: #000080;font-style:italic;">-- Let the user know we aren't completely dead just yet</span>
else {
<span style="color: #7060A8;">IupSetStrAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s - drawing (%d%%)"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">title</span><span style="color: #0000FF;">,</span><span style="color: #000000;">100</span><span style="color: #0000FF;">*(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">r</span><span style="color: #0000FF;">)/(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">r</span><span style="color: #0000FF;">)})</span>
@pixels.push(0);
<span style="color: #000000;">t1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()+</span><span style="color: #000000;">1</span>
}
<span style="color: #000080;font-style:italic;">-- (as per DeathStar.exw, prevent "(Not Responding)" nonsense)</span>
}
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
return @pixels;
<span style="color: #008080;">if</span> <span style="color: #7060A8;">IupLoopStep</span><span style="color: #0000FF;">()=</span><span style="color: #004600;">IUP_CLOSE</span> <span style="color: #008080;">then</span>
}</lang>
<span style="color: #7060A8;">IupExitLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">exit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">=-</span><span style="color: #000000;">r</span> <span style="color: #008080;">to</span> <span style="color: #000000;">r</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">z</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">*</span><span style="color: #000000;">r</span><span style="color: #0000FF;">-(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">*</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">y</span><span style="color: #0000FF;">*</span><span style="color: #000000;">y</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">z</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">dot</span><span style="color: #0000FF;">(</span><span style="color: #000000;">direction</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">normalize</span><span style="color: #0000FF;">({</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">)})),</span>
<span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">?</span><span style="color: #000000;">0</span><span style="color: #0000FF;">:</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">k</span><span style="color: #0000FF;">))</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">lum</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">#FF</span><span style="color: #0000FF;">,</span><span style="color: #000000;">lmul</span><span style="color: #0000FF;">*(</span><span style="color: #000000;">l</span><span style="color: #0000FF;">+</span><span style="color: #000000;">amb</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">cdCanvasPixel</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">cx</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">cy</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">lum</span><span style="color: #0000FF;">*</span><span style="color: #000000;">#10101</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">t1</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">t0</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupSetStrAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">title</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">redraw_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*ih*/</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000080;font-style:italic;">/*posx*/</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">/*posy*/</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">width</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">height</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupGetIntInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"DRAWSIZE"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">cdCanvasActivate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">cdCanvasClear</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">drawSphere</span><span style="color: #0000FF;">(</span><span style="color: #000000;">width</span><span style="color: #0000FF;">,</span><span style="color: #000000;">height</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1.5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0.2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">normalize</span><span style="color: #0000FF;">({-</span><span style="color: #000000;">30</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">30</span><span style="color: #0000FF;">,</span><span style="color: #000000;">50</span><span style="color: #0000FF;">}))</span>
<span style="color: #7060A8;">cdCanvasFlush</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">map_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000000;">ih</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">cdcanvas</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">cdCreateCanvas</span><span style="color: #0000FF;">(</span><span style="color: #004600;">CD_IUP</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ih</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">cddbuffer</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">cdCreateCanvas</span><span style="color: #0000FF;">(</span><span style="color: #004600;">CD_DBUFFER</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cdcanvas</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">cdCanvasSetBackground</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CD_BLACK</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">canvas</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupCanvas</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"RASTERSIZE=340x340"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetCallbacks</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"MAP_CB"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"map_cb"</span><span style="color: #0000FF;">),</span>
<span style="color: #008000;">"ACTION"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"redraw_cb"</span><span style="color: #0000FF;">)})</span>
<span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span><span style="color: #008000;">`TITLE="%s"`</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">title</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"RASTERSIZE"</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">NULL</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- release the minimum limitation</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
 
=={{header|PicoLisp}}==
{{libheader|GLUT}}
This is for the 64-bit version.
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/openGl.l")
 
(glutInit)
Line 2,188 ⟶ 3,852:
# Exit upon mouse click
(mouseFunc '((Btn State X Y) (bye)))
(glutMainLoop)</langsyntaxhighlight>
 
{{trans|C}}
 
<langsyntaxhighlight PicoLisplang="picolisp">(scl 24)
 
(setq *Shades
Line 2,251 ⟶ 3,915:
(setq *Light (normalize *Light))
(drawSphere 20.0 4 0.1)
(drawSphere 10.0 2 0.4)</langsyntaxhighlight>
{{out}}
<pre> ##############%%%
Line 2,321 ⟶ 3,985:
=={{header|PostScript}}==
Gradient filled circle:
<langsyntaxhighlight PostScriptlang="postscript">%!PS-Adobe-3.0
%%BoundingBox 0 0 300 300
 
Line 2,344 ⟶ 4,008:
showpage
%%EOF
</syntaxhighlight>
</lang>
 
=={{header|POV-Ray}}==
Line 2,350 ⟶ 4,014:
This is what POVray was made for. An example with a sky, surface and transparency:
 
<syntaxhighlight lang="povray">
<lang POVray>
camera { location <0.0 , .8 ,-3.0> look_at 0}
Line 2,366 ⟶ 4,030:
interior { ior 1.5}
}
</syntaxhighlight>
</lang>
 
Yields this:
Line 2,375 ⟶ 4,039:
3D rendering is built into Processing.
 
<langsyntaxhighlight Processinglang="java">void setup() {
size(500, 500, P3D);
background(200);
}
 
void draw() {
background(192);
translate(width/2, height/2);
// optional color and lighting style
stroke(200);
translatefill(250,250255);
lights();
// draw sphere(100);
sphere(200);
}</lang>
}</syntaxhighlight>
A sphere build from triangles (to for instance allow distortion)
<syntaxhighlight lang="java">float rotX, rotY;
 
PVector[][] sphere;
int detail = 50;
 
void setup() {
size(600, 600, P3D);
background(50, 50, 200);
fill(255, 0, 200);
stroke(0, 40);
sphere = new PVector[detail+1][detail+1];
}
 
void draw() {
pointLight(255, 255, 255, -width, -height, 2*height);
translate(width/2, height/2);
rotateX(rotX);
rotateY(rotY);
float r = 200;
for (int i = 0; i <= detail; i++) {
float rows = map(i, 0, detail, 0, PI);
for (int j = 0; j <= detail; j++) {
float columns = map(j, 0, detail, 0, TWO_PI);
float x = r * sin(rows) * cos(columns);
float y = r * sin(rows) * sin(columns);
float z = r * cos(rows);
sphere[i][j] = new PVector(x, y, z);
}
}
for (int i = 0; i < detail; i++) {
beginShape(TRIANGLE_STRIP);
for (int j = 0; j <= detail; j++) {
PVector v1 = sphere[i][j];
vertex(v1.x, v1.y, v1.z);
PVector v2 = sphere[i+1][j];
vertex(v2.x, v2.y, v2.z);
}
endShape();
}
}
 
void mouseDragged() {
rotY -= (mouseX - pmouseX) * 0.01;
rotX -= (mouseY - pmouseY) * 0.01;
}</syntaxhighlight>
 
=={{header|Python}}==
===Ascii-Art===
{{trans|C}}
<langsyntaxhighlight lang="python">import math
 
shades = ('.',':','!','*','o','e','&','#','%','@')
Line 2,421 ⟶ 4,133:
light = normalize((30,30,-50))
draw_sphere(20,4,0.1, light)
draw_sphere(10,2,0.4, light)</langsyntaxhighlight>
{{out}}
<pre> &&&&&&&&&&######
Line 2,491 ⟶ 4,203:
This code contains unnecessary functions which are part of a 3D graphics library I wrote. <br>
Uses Pygame and Python 3.2.2
<langsyntaxhighlight lang="python">
import pygame
from pygame.locals import *
Line 2,498 ⟶ 4,210:
import random
import math
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang="python">
class Tricubic:
def __init__(self,pts):
Line 3,271 ⟶ 4,983:
if event.type == KEYDOWN:
pass
</syntaxhighlight>
</lang>
 
==={{libheader|VPython}}===
{{works with|Python|2.7.5}}
'''Short version''':
<langsyntaxhighlight lang="python">from visual import *
scene.title = "VPython: Draw a sphere"
sphere() # using defaults, see http://www.vpython.org/contents/docs/defaults.html </langsyntaxhighlight>
 
'''Regular version''', with some window-dressing:
<langsyntaxhighlight lang="python">
from __future__ import print_function, division
from visual import *
Line 3,304 ⟶ 5,016:
rate(100)
pass # no animation in this demo
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
Line 3,312 ⟶ 5,024:
Using the Typed Racket language with the plot library:
 
<langsyntaxhighlight lang="racket">
#lang typed/racket
 
(require plot/typed)
(plot3d (polar3d (λ (θ ρ) 1)) #:altitude 25)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
 
===Pure Raku===
{{trans|C}}
 
The C code is modified to output a .pgm file.
{{works with|Rakudo|2018.10}}
 
[[File:Sphere-perl6.png|thumb]]
<syntaxhighlight lang="raku" line>my $width = my $height = 255; # must be odd
 
my @light = normalize([ 3, 2, -5 ]);
 
my $depth = 255;
 
sub MAIN ($outfile = 'sphere-perl6.pgm') {
spurt $outfile, "P5\n$width $height\n$depth\n"; # .pgm header
my $out = open( $outfile, :a, :bin ) orelse .die;
$out.write( Blob.new(draw_sphere( ($width-1)/2, .9, .2) ) );
$out.close;
}
 
sub normalize (@vec) { @vec »/» ([+] @vec »*« @vec).sqrt }
 
sub dot (@x, @y) { -([+] @x »*« @y) max 0 }
 
sub draw_sphere ( $rad, $k, $ambient ) {
my @pixels[$height];
my $r2 = $rad * $rad;
my @range = -$rad .. $rad;
@range.hyper.map: -> $x {
my @row[$width];
@range.map: -> $y {
if (my $x2 = $x * $x) + (my $y2 = $y * $y) < $r2 {
my @vector = normalize([$x, $y, ($r2 - $x2 - $y2).sqrt]);
my $intensity = dot(@light, @vector) ** $k + $ambient;
my $pixel = (0 max ($intensity * $depth).Int) min $depth;
@row[$y+$rad] = $pixel;
}
else {
@row[$y+$rad] = 0;
}
}
@pixels[$x+$rad] = @row;
}
flat |@pixels.map: *.list;
}</syntaxhighlight>
 
===Cairo graphics library===
<syntaxhighlight lang="raku" line>use Cairo;
 
given Cairo::Image.create(Cairo::FORMAT_ARGB32, 256, 256) {
given Cairo::Context.new($_) {
 
my Cairo::Pattern::Solid $bg .= create(.5,.5,.5);
.rectangle(0, 0, 256, 256);
.pattern($bg);
.fill;
$bg.destroy;
 
my Cairo::Pattern::Gradient::Radial $shadow .=
create(105.2, 102.4, 15.6, 102.4, 102.4, 128.0);
$shadow.add_color_stop_rgba(0, .3, .3, .3, .3);
$shadow.add_color_stop_rgba(1, .1, .1, .1, .02);
.pattern($shadow);
.arc(136.0, 134.0, 110, 0, 2 * pi);
.fill;
$shadow.destroy;
 
my Cairo::Pattern::Gradient::Radial $sphere .=
create(115.2, 102.4, 25.6, 102.4, 102.4, 128.0);
$sphere.add_color_stop_rgba(0, 1, 1, .698, 1);
$sphere.add_color_stop_rgba(1, .923, .669, .144, 1);
.pattern($sphere);
.arc(128.0, 128.0, 110, 0, 2 * pi);
.fill;
$sphere.destroy;
};
.write_png('sphere2-perl6.png');
}</syntaxhighlight>
See [https://github.com/thundergnat/rc/blob/master/img/sphere2-perl6.png sphere2-perl6.png] (offsite .png image)
 
=={{header|REXX}}==
This program is modeled after the &nbsp; '''C''' &nbsp; version.
 
<br>The REXX language doesn't have a &nbsp; '''SQRT''' &nbsp; function, so a version is included here.
The REXX language doesn't have a &nbsp; '''SQRT''' &nbsp; function, so a version is included here.
<br>Same with the &nbsp; '''CEIL'''ing &nbsp; and &nbsp; '''FLOOR''' &nbsp; functions.
<br><br>Programming note: &nbsp; the output will appear slightly different when executed on an EBCDIC machine &nbsp; (due to different dithering characters).
<lang rexx>/*REXX program expresses a lighted sphere with simple chars for shading.*/
call drawSphere 19, 4, 2/10 /*draw a sphere with radius 19. */
call drawSphere 10, 2, 4/10 /*draw a sphere with radius ten. */
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────DRAWSPHERE subroutine───────────────*/
drawSphere: procedure; parse arg r, k, ambient /*get the arguments*/
if 1=='f1'x then shading='.:!*oe&#%@' /*EBCDIC dithering.*/
else shading='·:!°oe@░▒▓' /*ASCII " */
lightSource = '30 30 -50' /*the light source.*/
parse value norm(lightSource) with s1 s2 s3 /*normalize light S*/
sLen=length(shading); sLen1=sLen-1; rr=r*r /*handy-dandy vars.*/
 
Programming note: &nbsp; the output will appear slightly different when executed on an EBCDIC machine &nbsp; (due to different dithering characters).
do i=floor(-r) to ceil(r) ; x= i+.5; xx=x**2; aLine=
<syntaxhighlight lang="rexx">/*REXX program expresses a lighted sphere with simple characters used for shading. */
do j=floor(-2*r) to ceil(2*r); y=j/2+.5; yy=y**2
call drawSphere 19, if xx+yy<=rr4, then do 2/10, '30 30 -50' /*draw a sphere with a radius of 19. /*within the phere?*/
call drawSphere 10, 2, 4/10, '30 30 -50' /* " " parse value norm(x" y sqrt(rr-xx-yy)) with " " " " v1 v2ten. v3*/
exit dot=s1*v1 + s2*v2 + s3*v3 /*dotstick a fork in it, we're productall ofdone. Vs*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
if dot>0 then dot=0 /*if pos, make it 0*/
ceil: procedure; parse arg x; _= trunc(x); b=abs(dot)**k + ambient return _ /*calc.+(x>0) brightness.*/ (x\=_)
floor: procedure; parse arg x; _= trunc(x); if b return _ -(x<=0) then* brite(x\=sLenm1_)
norm: parse arg $a $b $c; _= sqrt($a**2 + $b**2 + $c**2); return $a/_ else brite=trunc( max( (1-$b)/_ * sLen1, 0) )$c/_
/*──────────────────────────────────────────────────────────────────────────────────────*/
aLine=aLine || substr(shading,brite+1,1) /*build.*/
drawSphere: procedure; parse arg r, k, ambient, lightSource /*obtain the four arguments*/
end
if 8=='f8'x then else aLineshading=aLine' ' ".:!*oe&#%@" /*append aEBCDIC blank.dithering chars. */
else shading= "·:!°oe@░▒▓" /* ASCII " " */
end /*j*/
say strip(aLine,'trailing') parse value norm(lightSource) with s1 s2 s3 /*shownormalize alight linesource. of it*/
end /*i*/ shadeLen= length(shading) - 1; rr= r**2; r2= r+r /*handy─dandy [↑]variables. show sphere*/
 
return
do i=floor(-r ) to ceil(r ); x= i + .5; xx= x**2; $=
/*─────────────────────────────────────subroutines────────────────────────────*/
ceil: procedure; parse arg x; _ do j=truncfloor(x-r2) to ceil(r2); returny= j * .5 _ + (x>0).5; yy= y**2; (x\ z=_) xx+yy
if z<=rr then do /*is point within sphere ? */
floor: procedure; parse arg x; _=trunc(x); return _ - (x<0) * (x\=_)
norm: parse argvalue _1 _2norm(x _3; y _=sqrt(_1**2+_2**2+_3**2rr - xx - yy); ) with v1 return _1/_v2 _2/_ _3/_v3
dot= min(0, s1*v1 + s2*v2 + s3*v3) /*the dot product of above.*/
/*─────────────────────────────────────SQRT subroutine────────────────────────*/
b= -dot**k + ambient /*calculate the brightness.*/
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); p=d+d%4+2; m.=11
if b<=0 then brite= shadeLen
numeric digits m.;numeric form;parse value format(x,2,1,,0) 'E0' with g 'E' _ .
g=g*.5'E'_%2; do j=0 while p>9; m.j=p; p else brite=p%2+ max(0, (1;-b) * endshadeLen) % 1
do k=j+5 to 0 by -1; if m.k>11 then numeric digits m.k; g $=.5* $ || substr(gshading, brite +x/g); end1, 1)
end /* [↑] build display line.*/
numeric digits d; return g/1</lang>
else $= $' ' /*append a blank to line. */
{{out}} when executed on an ASCII machine:
end /*j*/ /*[↓] strip trailing blanks*/
<pre style="height:105ex">
say strip($, 'T') /*show a line of the sphere*/
end /*i*/ /* [↑] display the sphere.*/
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; parse arg x; if x=0 then return 0; d= digits(); numeric digits; h= d+6
numeric form; m.=9; parse value format(x,2,1,,0) 'E0' with g "E" _ .; g= g*.5'e'_%2
do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input and executed on an '''ASCII''' machine:}}
(Shown at &nbsp; <big>'''<sup>1</sup>/<sub>2</sub>'''</big> &nbsp; size.)
 
<pre style="font-size:50%">
eeeeeeeeee@@@@@@@
eoooooooooooooooeeeee@@@@@@@░
Line 3,429 ⟶ 5,225:
Shoes comes with this sample program.
[[File:sphere.shoes.png|thumb|right]]
<langsyntaxhighlight lang="ruby">Shoes.app :width => 500, :height => 500, :resizable => false do
image 400, 470, :top => 30, :left => 50 do
nostroke
Line 3,456 ⟶ 5,252:
end
end
end</langsyntaxhighlight>
 
=={{header|Rust}}==
{{trans|Go}}
<syntaxhighlight lang="rust">// [dependencies]
// image = "0.23"
 
use image::{GrayImage, Luma};
 
type Vector = [f64; 3];
 
fn normalize(v: &mut Vector) {
let inv_len = 1.0/dot_product(v, v).sqrt();
v[0] *= inv_len;
v[1] *= inv_len;
v[2] *= inv_len;
}
 
fn dot_product(v1: &Vector, v2: &Vector) -> f64 {
v1.iter().zip(v2.iter()).map(|(x, y)| *x * *y).sum()
}
 
fn draw_sphere(radius: u32, k: f64, ambient: f64, dir: &Vector) -> GrayImage {
let width = radius * 4;
let height = radius * 3;
let mut image = GrayImage::new(width, height);
let mut vec = [0.0; 3];
let diameter = radius * 2;
let r = radius as f64;
let xoffset = (width - diameter)/2;
let yoffset = (height - diameter)/2;
for i in 0..diameter {
let x = i as f64 - r;
for j in 0..diameter {
let y = j as f64 - r;
let z = r * r - x * x - y * y;
if z >= 0.0 {
vec[0] = x;
vec[1] = y;
vec[2] = z.sqrt();
normalize(&mut vec);
let mut s = dot_product(&dir, &vec);
if s < 0.0 {
s = 0.0;
}
let mut lum = 255.0 * (s.powf(k) + ambient)/(1.0 + ambient);
if lum < 0.0 {
lum = 0.0;
} else if lum > 255.0 {
lum = 255.0;
}
image.put_pixel(i + xoffset, j + yoffset, Luma([lum as u8]));
}
}
}
image
}
 
fn main() {
let mut dir = [-30.0, -30.0, 50.0];
normalize(&mut dir);
match draw_sphere(200, 1.5, 0.2, &dir).save("sphere.png") {
Ok(()) => {}
Err(error) => eprintln!("{}", error),
}
}</syntaxhighlight>
 
{{out}}
[[Media:Draw a sphere rust.png]]
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">object Sphere extends App {
private val (shades, light) = (Seq('.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'), Array(30d, 30d, -50d))
 
private def drawSphere(r: Double, k: Double, ambient: Double): Unit = {
def dot(x: Array[Double], y: Array[Double]) = {
val d = x.head * y.head + x(1) * y(1) + x.last * y.last
if (d < 0) -d else 0D
}
 
for (i <- math.floor(-r).toInt to math.ceil(r).toInt; x = i + .5)
println(
(for (j <- math.floor(-2 * r).toInt to math.ceil(2 * r).toInt; y = j / 2.0 + .5)
yield if (x * x + y * y <= r * r) {
 
def intensity(vec: Array[Double]) = {
val b = math.pow(dot(light, vec), k) + ambient
if (b <= 0) shades.length - 2
else math.max((1 - b) * (shades.length - 1), 0).toInt
}
 
shades(intensity(normalize(Array(x, y, scala.math.sqrt(r * r - x * x - y * y)))))
} else ' ').mkString)
}
 
private def normalize(v: Array[Double]): Array[Double] = {
val len = math.sqrt(v.head * v.head + v(1) * v(1) + v.last * v.last)
v.map(_ / len)
}
 
normalize(light).copyToArray(light)
drawSphere(20, 4, .1)
drawSphere(10, 2, .4)
 
}</syntaxhighlight>
{{Out}}See it in running in your browser by [https://scalafiddle.io/sf/uSm8bJ9/0 ScalaFiddle (JavaScript)] or by [https://scastie.scala-lang.org/TtVHUp3aS0eDEB6YCW4gKg Scastie (JVM)].
 
=={{header|Sidef}}==
{{trans|Raku}}
Produces a PGM image.
<syntaxhighlight lang="ruby">func normalize (vec) { vec »/» (vec »*« vec -> sum.sqrt) }
func dot (x, y) { -(x »*« y -> sum) `max` 0 }
 
var x = var y = 255
x += 1 if x.is_even # must be odd
 
var light = normalize([ 3, 2, -5 ])
var depth = 255
 
func draw_sphere(rad, k, ambient) {
var pixels = []
var r2 = (rad * rad)
var range = (-rad .. rad)
for x,y in (range ~X range) {
if ((var x2 = x*x) + (var y2 = y*y) < r2) {
var vector = normalize([x, y, (r2 - x2 - y2).sqrt])
var intensity = (dot(light, vector)**k + ambient)
var pixel = (0 `max` (intensity*depth -> int) `min` depth)
pixels << pixel
}
else {
pixels << 0
}
}
return pixels
}
 
var outfile = %f'sphere-sidef.pgm'
var out = outfile.open('>:raw')
 
out.say("P5\n#{x} #{y}\n#{depth}") # .pgm header
out.print(draw_sphere((x-1)/2, .9, .2).map{.chr}.join)
out.close</syntaxhighlight>
 
=={{header|Smalltalk}}==
Line 3,464 ⟶ 5,402:
{{works with|Smalltalk/X}}
although there is a Point3 class in some loadable library, here is some self contained code, defining a local anon Point3D class.
<syntaxhighlight lang="smalltalk">
<lang Smalltalk>
Point3D :=
Point subclass:#Point3D
Line 3,528 ⟶ 5,466:
 
main value.
</syntaxhighlight>
</lang>
[[file:sphere-smalltalk.png]]
 
Line 3,534 ⟶ 5,472:
Not quite a sphere.
[[file:sphere-ish.svg]]
 
=={{header|Swift}}==
In Playground for example:
<syntaxhighlight lang="swift">
class Sphere: UIView{
override func drawRect(rect: CGRect)
{
let context = UIGraphicsGetCurrentContext()
let locations: [CGFloat] = [0.0, 1.0]
let colors = [UIColor.whiteColor().CGColor,
UIColor.blueColor().CGColor]
let colorspace = CGColorSpaceCreateDeviceRGB()
let gradient = CGGradientCreateWithColors(colorspace,
colors, locations)
var startPoint = CGPoint()
var endPoint = CGPoint()
startPoint.x = self.center.x - (self.frame.width * 0.1)
startPoint.y = self.center.y - (self.frame.width * 0.15)
endPoint.x = self.center.x
endPoint.y = self.center.y
let startRadius: CGFloat = 0
let endRadius: CGFloat = self.frame.width * 0.38
CGContextDrawRadialGradient (context, gradient, startPoint,
startRadius, endPoint, endRadius,
0)
}
}
 
var s = Sphere(frame: CGRectMake(0, 0, 200, 200))
</syntaxhighlight>
 
In SwiftUI:
<syntaxhighlight lang="swift">
struct ContentView: View {
 
var body: some View {
 
let gradient = RadialGradient(gradient: Gradient(colors:[.white, .black]),
center: .init(x: 0.4, y: 0.4), startRadius: 10, endRadius: 100)
return Circle()
.fill(gradient)
.frame(width: 200, height: 200)
 
}
}
</syntaxhighlight>
 
=={{header|Tcl}}==
Line 3,539 ⟶ 5,530:
Assuming the task is to draw a <i>likeness</i> of a sphere, this would usually do:
 
<langsyntaxhighlight Tcllang="tcl">proc grey {n} {format "#%2.2x%2.2x%2.2x" $n $n $n}
 
pack [canvas .c -height 400 -width 640 -background white]
Line 3,546 ⟶ 5,537:
set h [grey $i]
.c create arc [expr {100+$i/5}] [expr {50+$i/5}] [expr {400-$i/1.5}] [expr {350-$i/1.5}] \
-start 0 -extent 359 -fill $h -outline $h}
}</langsyntaxhighlight>
Results in this image:
 
[[image:Tcl-spheroid.gif]]
 
=={{header|TeXLaTeX}}==
 
{{libheader|PGF}}
The PGF <code>shadings</code> library includes a "ball" for a 3-D style highlight. For example with [[LaTeX]],
 
<langsyntaxhighlight TeXlang="latex">\documentclass{articleminimal}
\usepackage{tikz}
\usetikzlibrary{shadings}
\begin{document}
\begin{tikzpicture}
\shade[ball color=black] (0,0) circle (4);
\end{tikzpicture}
\end{document}</langsyntaxhighlight>
 
=={{header|Turing}}==
Translated and optimized from the Algol W solution and others posted here.
 
<syntaxhighlight lang="turing">% Draw a sphere in ASCII art in Turing
% Light intensity to character map
const shades := '.:!*oe&#%@'
const maxShades := length (shades)
 
% Absolute dot product of x and y
function dot (x, y : array 1 .. 3 of real) : real
result abs (x(1) * y(1) + x(2) * y(2) + x(3) * y(3))
end dot
 
% Vector normalization
procedure normalize (var v : array 1 .. 3 of real)
const norm := sqrt (v(1)**2 + v(2)**2 + v(3)**2)
for i : 1 .. 3
v(i) := v(i) / norm
end for
end normalize
 
% Draws a sphere using ASCII art
procedure drawSphere (radius : real, k : int, lightsource : array 1 .. 3 of real, brightness : real)
const diameter := 2.0 * radius
for i : floor (-radius) .. ceil (radius)
var x := i + 0.5
for j : floor (-diameter) .. ceil (diameter)
var y := j / 2 + 0.5
 
if x**2 + y**2 <= radius**2 then
var vec : array 1 .. 3 of real
vec(1) := x; vec(2) := y; vec(3) := sqrt (radius**2 - x**2 - y**2)
normalize (vec)
 
const b := dot (lightsource, vec) ** k + brightness
var intensity := round ((1 - b) * maxShades)
 
if intensity < 1 then
intensity := 1
elsif intensity > maxShades then
intensity := maxShades
end if
 
put shades (intensity) ..
else
put ' ' ..
end if
end for
put ""
end for
end drawSphere
 
% Light source
var lightsource : array 1 .. 3 of real := init (30, 30, -59)
normalize (lightsource)
const brightness := 0.1
 
% Draw some spheres
drawSphere (20, 4, lightsource, brightness)
drawSphere (15, 10, lightsource, brightness)</syntaxhighlight>
 
{{Out}}
<pre>
###############%%
#&&&eeeeeeeeee&&&&&&#######%%%%
&&eeeoooooooooooooeeeee&&&&&######%%%%%
&eeooo**************oooooeeee&&&&&#####%%%%%%
&eoo***!!!!!!!!!!!!!!!*****ooooeee&&&&&#####%%%%%%%
&eo**!!!:::::::::::::::!!!!****oooeeee&&&&######%%%%%%%
&eo**!!:::.............::::!!!!***ooooeee&&&&######%%%%%%%%
&eo**!!::..................::::!!!***ooooeee&&&&######%%%%%%%%%
&oo*!!::.....................::::!!!***oooeeee&&&&#####%%%%%%%%%%
#eo**!::........................:::!!!!***oooeee&&&&######%%%%%%%%%%%
&eo**!::.........................::::!!!***oooeeee&&&&#####%%%%%%%%%%%%
&eoo*!!::.........................::::!!!***oooeeee&&&&######%%%%%%%%%%%%
#&eo*!!::..........................:::!!!!***oooeeee&&&&######%%%%%%%%%%%%%
&eo**!!::.........................::::!!!***ooooeee&&&&&######%%%%%%%%%%%%%
&eeo**!!::.........................:::!!!****oooeeee&&&&#######%%%%%%%%%%%%%%
&eeo**!!::.......................::::!!!!***ooooeee&&&&&######%%%%%%%%%%%%%%%
#&eeo**!!:::.....................::::!!!****ooooeeee&&&&#######%%%%%%%%%%%%%%%%
#&eeoo**!!::::................:::::!!!!****ooooeeee&&&&&######%%%%%%%%%%%%%%%%%
#&eeoo***!!!:::::.........:::::::!!!!****oooooeeee&&&&&#######%%%%%%%%%%%%%%%%%
#&&eeoo***!!!!::::::::::::::::!!!!!*****ooooeeeee&&&&&#######%%%%%%%%%%%%%%%%%%
#&&eeeoo****!!!!!!!:::::!!!!!!!!******ooooeeeee&&&&&&#######%%%%%%%%%%%%%%%%%%%
##&&eeeooo*****!!!!!!!!!!!!!*******oooooeeeeee&&&&&########%%%%%%%%%%%%%%%%%%%%
###&&eeeooooo*******************ooooooeeeeee&&&&&&########%%%%%%%%%%%%%%%%%%%%%
%##&&&&eeeeooooooo********oooooooooeeeeee&&&&&&&#########%%%%%%%%%%%%%%%%%%%%%%
####&&&&eeeeeoooooooooooooooooeeeeeeee&&&&&&&#########%%%%%%%%%%%%%%%%%%%%%%%
%####&&&&&eeeeeeeeeeeeeeeeeeeeeeee&&&&&&&&##########%%%%%%%%%%%%%%%%%%%%%%%%%
%#####&&&&&&&&eeeeeeeeeeeeee&&&&&&&&&&&##########%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%######&&&&&&&&&&&&&&&&&&&&&&&&&&############%%%%%%%%%%%%%%%%%%%%%%%%%%%#
%%%%########&&&&&&&&&&&&&&&&&###############%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%##################################%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
%%%%%%%############################%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
%%%%%%%%%%#################%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%
%%%%########%%%%%%%%%%%%%%%
%####&&&&&&&&#######%%%%%%%%%%%%%
%###&&eeeeooeeeee&&&#####%%%%%%%%%%%%%%
%##&eeoo********oooee&&&####%%%%%%%%%%%%%%%
%##&eo**!!::::::!!!**ooee&&#####%%%%%%%%%%%%%%%
%#&eo**!:.........::!**ooee&&####%%%%%%%%%%%%%%%%
##&eo*!:............:!!*ooee&&&####%%%%%%%%%%%%%%%%
%%#&eo*!:.............:!!**oee&&&####%%%%%%%%%%%%%%%%%%
%#&&eo*!:............::!!*ooee&&#####%%%%%%%%%%%%%%%%%%
%##&eoo*!:...........::!!**oee&&&####%%%%%%%%%%%%%%%%%%%%
%%##&eeo*!!:........:::!!*ooeee&&#####%%%%%%%%%%%%%%%%%%%%%
%%##&&eoo*!!::::::::!!!**ooee&&&#####%%%%%%%%%%%%%%%%%%%%%%
%%###&eeoo***!!!!!!***oooeee&&&#####%%%%%%%%%%%%%%%%%%%%%%%
%%%##&&&eeooooo**oooooeeee&&&######%%%%%%%%%%%%%%%%%%%%%%%%
%%%####&&&eeeeeeeeeeeee&&&&######%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%#####&&&&&&&&&&&&&&&#######%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%########&&&&###########%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%################%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%#####%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%
</pre>
 
=={{header|VBScript}}==
{{trans|C}}
<syntaxhighlight lang="vb">shades = Array(".", ":", "!", "*", "o", "e", "&", "#", "%", "@")
light = Array(30, 30, -50)
 
Sub Normalize(v)
length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))
v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length
End Sub
 
Function Dot(x, y)
d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)
If d < 0 Then Dot = -d Else Dot = 0 End If
End Function
 
'floor function is the Int function
'ceil function implementation
Function Ceil(x)
Ceil = Int(x)
If Ceil <> x Then Ceil = Ceil + 1 End if
End Function
 
Sub DrawSphere(R, k, ambient)
Dim i, j, intensity, inten, b, x, y
Dim vec(3)
For i = Int(-R) to Ceil(R)
x = i + 0.5
line = ""
For j = Int(-2*R) to Ceil(2*R)
y = j / 2 + 0.5
If x * x + y * y <= R*R Then
vec(0) = x
vec(1) = y
vec(2) = Sqr(R * R - x * x - y * y)
Normalize vec
b = dot(light, vec)^k + ambient
intensity = Int((1 - b) * UBound(shades))
If intensity < 0 Then intensity = 0 End If
If intensity >= UBound(shades) Then
intensity = UBound(shades)
End If
line = line & shades(intensity)
Else
line = line & " "
End If
Next
WScript.StdOut.WriteLine line
Next
End Sub
 
Normalize light
DrawSphere 20, 4, 0.1
DrawSphere 10,2,0.4</syntaxhighlight>
{{Out}}
<pre> &&&&&&&&&&#######
&eeeeeeeeeeeeeeee&&&&&&#######%
&eoooo*******oooooooeeeee&&&&&########%
eoo****!!!!!!!!******oooooeeee&&&&&########%%
eoo**!!!!::::::::!!!!!*****ooooeeee&&&&&########%%%
eo**!!::::::...:::::::!!!!!***ooooeeee&&&&&########%%%%
eo*!!:::.............:::::!!!!***ooooeeee&&&&&########%%%%%
eo*!!:::.................::::!!!!***ooooeeee&&&&#########%%%%%%
eo*!!::....................::::!!!****oooeeee&&&&&#########%%%%%%
&o**!::......................::::!!!****oooeeee&&&&&##########%%%%%%%
&o**!::.......................::::!!!****oooeeee&&&&&##########%%%%%%%%
&oo*!!::.......................:::!!!!***ooooeeee&&&&&##########%%%%%%%%%
&eo*!!::.......................::::!!!****ooooeeee&&&&&##########%%%%%%%%%%
eo**!!::......................::::!!!!***ooooeeeee&&&&&##########%%%%%%%%%%
&eo**!!:::...................:::::!!!!****ooooeeee&&&&&###########%%%%%%%%%%%
eeo**!!::::................:::::!!!!!****ooooeeee&&&&&&###########%%%%%%%%%%%
&eeo***!!:::::...........::::::!!!!!****oooooeeee&&&&&&###########%%%%%%%%%%%%%
&eeoo**!!!!::::::::::::::::::!!!!!*****ooooeeeee&&&&&&############%%%%%%%%%%%%%
&eeooo***!!!!::::::::::::!!!!!!!*****oooooeeeee&&&&&&############%%%%%%%%%%%%%%
&&eeooo***!!!!!!!!!!!!!!!!!!!******oooooeeeeee&&&&&&############%%%%%%%%%%%%%%%
&&eeeooo******!!!!!!!!!!********ooooooeeeeee&&&&&&&############%%%%%%%%%%%%%%%%
#&&eeeooooo******************oooooooeeeeee&&&&&&&#############%%%%%%%%%%%%%%%%%
#&&&eeeeoooooooo******oooooooooooeeeeeee&&&&&&&&#############%%%%%%%%%%%%%%%%%%
##&&&&eeeeeooooooooooooooooooeeeeeeee&&&&&&&&&##############%%%%%%%%%%%%%%%%%%%
##&&&&&eeeeeeeeeeeeeeeeeeeeeeeeee&&&&&&&&&################%%%%%%%%%%%%%%%%%%%
####&&&&&&eeeeeeeeeeeeeeeeeee&&&&&&&&&&&################%%%%%%%%%%%%%%%%%%%%%
#####&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&#################%%%%%%%%%%%%%%%%%%%%%%
%#######&&&&&&&&&&&&&&&&&&&&&&&&###################%%%%%%%%%%%%%%%%%%%%%%%%
%###########&&&&&&&&&&&&&#######################%%%%%%%%%%%%%%%%%%%%%%%%%
%############################################%%%%%%%%%%%%%%%%%%%%%%%%%%
%%#######################################%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%#################################%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%#########################%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%#############%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%
 
::...:::!!!*o
..............::!!*oo
..................::!!**ooe
.....................::!!**ooee
.......................::!!**ooee
........................::!!**oooee
.........................::!!**oooeee
:........................::!!!**oooeeee
........................::!!!**ooooeeee
:......................::!!!***oooeeeee
:....................:::!!!***oooeeeeee
!:.................:::!!!****oooeeeeeee
*!:::...........::::!!!!***ooooeeeeeeee
*!!!:::::::::::!!!!!****oooooeeeeeeee
o**!!!!!!!!!!!!!*****oooooeeeeeeeee
oo**************ooooooeeeeeeeeeee
eoooooooooooooooooeeeeeeeeeeeee
eeeooooooooeeeeeeeeeeeeeeee
eeeeeeeeeeeeeeeeeeeee
eeeeeeeeeeeee</pre>
 
=={{header|V (Vlang)}}==
Graphical
<syntaxhighlight lang="Zig">
import gg
import gx
 
const (
win_width = 600
win_height = 600
)
 
struct App {
mut:
gg &gg.Context = unsafe {nil}
}
 
fn main() {
mut app := &App{
gg: 0
}
app.gg = gg.new_context(
bg_color: gx.white
width: win_width
height: win_height
create_window: true
window_title: 'Circle'
frame_fn: frame
user_data: app
)
app.gg.run()
}
 
fn frame(app &App) {
app.gg.begin()
app.draw()
app.gg.end()
}
 
fn (app &App) draw() {
app.gg.draw_circle_filled(300, 300, 150, gx.red)
}
</syntaxhighlight>
 
=={{header|Wren}}==
{{trans|C}}
<syntaxhighlight lang="wren">var shades = ".:!*oe&#\%@"
var light = [30, 30, -50]
 
var normalize = Fn.new { |v|
var len = (v[0]*v[0] + v[1]*v[1] + v[2]*v[2]).sqrt
for (i in 0..2) v[i] = v[i] / len
}
 
var dot = Fn.new { |x, y|
var d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
return (d < 0) ? -d : 0
}
 
var drawSphere = Fn.new { |r, k, ambient|
var vec = [0] * 3
for (i in (-r).floor..r.ceil) {
var x = i + 0.5
for (j in (-2*r).floor..(2*r).ceil) {
var y = j/2 + 0.5
if (x*x + y*y <= r*r) {
var vec = [x, y, (r*r - x*x - y*y).sqrt]
normalize.call(vec)
var b = dot.call(light, vec).pow(k) + ambient
var intensity = ((1 - b) * (shades.count - 1)).truncate
if (intensity < 0) intensity = 0
if (intensity >= shades.count - 1) intensity = shades.count - 2
System.write(shades[intensity])
} else {
System.write(" ")
}
}
System.print()
}
}
 
normalize.call(light)
drawSphere.call(20, 4, 0.1)
drawSphere.call(10, 2, 0.4)</syntaxhighlight>
 
{{out}}
<pre>
&&&&&&&&&&#######
&eeeeeeeeeeeeeeee&&&&&&#######%
&eoooo*******oooooooeeeee&&&&&########%
eoo****!!!!!!!!******oooooeeee&&&&&########%%
eoo**!!!!::::::::!!!!!*****ooooeeee&&&&&########%%%
eo**!!::::::...:::::::!!!!!***ooooeeee&&&&&########%%%%
eo*!!:::.............:::::!!!!***ooooeeee&&&&&########%%%%%
eo*!!:::.................::::!!!!***ooooeeee&&&&#########%%%%%%
eo*!!::....................::::!!!****oooeeee&&&&&#########%%%%%%
&o**!::......................::::!!!****oooeeee&&&&&##########%%%%%%%
&o**!::.......................::::!!!****oooeeee&&&&&##########%%%%%%%%
&oo*!!::.......................:::!!!!***ooooeeee&&&&&##########%%%%%%%%%
&eo*!!::.......................::::!!!****ooooeeee&&&&&##########%%%%%%%%%%
eo**!!::......................::::!!!!***ooooeeeee&&&&&##########%%%%%%%%%%
&eo**!!:::...................:::::!!!!****ooooeeee&&&&&###########%%%%%%%%%%%
eeo**!!::::................:::::!!!!!****ooooeeee&&&&&&###########%%%%%%%%%%%
&eeo***!!:::::...........::::::!!!!!****oooooeeee&&&&&&###########%%%%%%%%%%%%%
&eeoo**!!!!::::::::::::::::::!!!!!*****ooooeeeee&&&&&&############%%%%%%%%%%%%%
&eeooo***!!!!::::::::::::!!!!!!!*****oooooeeeee&&&&&&############%%%%%%%%%%%%%%
&&eeooo***!!!!!!!!!!!!!!!!!!!******oooooeeeeee&&&&&&############%%%%%%%%%%%%%%%
&&eeeooo******!!!!!!!!!!********ooooooeeeeee&&&&&&&############%%%%%%%%%%%%%%%%
#&&eeeooooo******************oooooooeeeeee&&&&&&&#############%%%%%%%%%%%%%%%%%
#&&&eeeeoooooooo******oooooooooooeeeeeee&&&&&&&&#############%%%%%%%%%%%%%%%%%%
##&&&&eeeeeooooooooooooooooooeeeeeeee&&&&&&&&&##############%%%%%%%%%%%%%%%%%%%
##&&&&&eeeeeeeeeeeeeeeeeeeeeeeeee&&&&&&&&&################%%%%%%%%%%%%%%%%%%%
####&&&&&&eeeeeeeeeeeeeeeeeee&&&&&&&&&&&################%%%%%%%%%%%%%%%%%%%%%
#####&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&#################%%%%%%%%%%%%%%%%%%%%%%
%#######&&&&&&&&&&&&&&&&&&&&&&&&###################%%%%%%%%%%%%%%%%%%%%%%%%
%###########&&&&&&&&&&&&&#######################%%%%%%%%%%%%%%%%%%%%%%%%%
%############################################%%%%%%%%%%%%%%%%%%%%%%%%%%
%%#######################################%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%#################################%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%#########################%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%#############%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%
::...:::!!!*o
..............::!!*oo
..................::!!**ooe
.....................::!!**ooee
.......................::!!**ooee
........................::!!**oooee
.........................::!!**oooeee
:........................::!!!**oooeeee
........................::!!!**ooooeeee
:......................::!!!***oooeeeee
:....................:::!!!***oooeeeeee
!:.................:::!!!****oooeeeeeee
*!:::...........::::!!!!***ooooeeeeeeee
*!!!:::::::::::!!!!!****oooooeeeeeeee
o**!!!!!!!!!!!!!*****oooooeeeeeeeee
oo**************ooooooeeeeeeeeeee
eoooooooooooooooooeeeeeeeeeeeee
eeeooooooooeeeeeeeeeeeeeeee
eeeeeeeeeeeeeeeeeeeee
eeeeeeeeeeeee
</pre>
 
=={{header|XPL0}}==
[[File:SphereXPL0.png|right]]
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
def R=100, R2=R*R; \radius, in pixels; radius squared
def X0=640/2, Y0=480/2; \coordinates of center of screen
Line 3,585 ⟶ 5,978:
repeat until KeyHit; \wait for keystroke
SetVid($03); \restore normal text mode
]</langsyntaxhighlight>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">ancho = 640 : alto = 480
open window 640,480
backcolor 16,16,16
clear window
sphera()
 
sub sphera()
local n
for n = 1 to 100
color 2*n, 2*n, 2*n
fill circle ancho/2-2*n/3, alto/2-n/2, 150-n
next n
end sub</syntaxhighlight>
 
=={{header|Zig}}==
{{trans|Factor}}
{{libheader|raylib}}
<syntaxhighlight lang="zig">
const std = @import("std");
const c = @cImport({
@cInclude("raylib.h");
});
 
pub fn main() !void {
c.SetConfigFlags(c.FLAG_WINDOW_RESIZABLE | c.FLAG_VSYNC_HINT);
c.InitWindow(600, 480, "Draw a Sphere");
defer c.CloseWindow();
 
const camera = c.Camera3D{
.position = .{ .x = 4.5, .y = 4.5, .z = 4.5 },
.target = .{ .x = 0, .y = 0, .z = 0 },
.up = .{ .x = 0, .y = 1, .z = 0 },
.fovy = 45.0,
.projection = c.CAMERA_PERSPECTIVE,
};
 
c.SetTargetFPS(60);
 
while (!c.WindowShouldClose()) {
c.BeginDrawing();
defer c.EndDrawing();
 
c.ClearBackground(c.BLACK);
 
{
c.BeginMode3D(camera);
defer c.EndMode3D();
 
c.DrawSphereWires(.{ .x = 0, .y = 0, .z = 0 }, 2, 20, 20, c.LIME);
}
}
}
</syntaxhighlight>
 
=={{header|zkl}}==
Uses the PPM class from http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#zkl
{{trans|XPL0}}
[[File:Sphere.zkl.jpg|200px|thumb|right]]
<lang zkl>img:=PPM(640,480);
<syntaxhighlight lang="zkl">img:=PPM(640,480);
R:=100; R2:=R*R; //radius, in pixels; radius squared
X0:=640/2; Y0:=480/2; //coordinates of center of screen
Line 3,604 ⟶ 6,054:
}
}
img.write(File("foo.ppm","wb"));</langsyntaxhighlight>
{{out}}See the XPL0 image or http://home.comcast.net/~zenkinetic/Images/sphere.jpg
The radius of 100 is the max before the color calculation overflows 24 bits so for a radius (R) of, say 200, use
<langsyntaxhighlight lang="zkl">img[X+X0,Y+Y0]=C*140+C;</langsyntaxhighlight>
Perhaps a more useful solution is to use GnuPlot (I grabbed the code from (http://ayapin-film.sakura.ne.jp/Gnuplot/):
[[File:GnuplotSphere.zkl.png|250px|thumb|right]]
<lang zkl>cmd:=0'|
<syntaxhighlight lang="zkl">#<<<
cmd:=0'|
set term wxt
set parametric
Line 3,630 ⟶ 6,081:
gnuplot:=System.popen("gnuplot","w");
gnuplot.write(cmd); gnuplot.flush();
ask("Hit return to finish"); gnuplot.close();</langsyntaxhighlight>
Where "term wxt" is X11 on my Linux box. A window pops up and stays until the pipe is closed.
 
{{out}}
=={{header|ZX Spectrum Basic}}==
http://home.comcast.net/~zenkinetic/Images/gnuplotSphere.png
<syntaxhighlight lang="zxbasic">1 REM fast
50 REM spheer with hidden lines and rotation
100 CLS
110 PRINT "sphere with lenght&wide-circles"
120 PRINT "_______________________________"''
200 INPUT "rotate x-as:";a
210 INPUT "rotate y-as:";b
220 INPUT "rotate z-as:";c
225 INPUT "distance lines(10-45):";d
230 LET u=128: LET v=87: LET r=87: LET bm=PI/180: LET h=.5
240 LET s1=SIN (a*bm): LET s2=SIN (b*bm): LET s3=SIN (c*bm)
250 LET c1=COS (a*bm): LET c2=COS (b*bm): LET c3=COS (c*bm)
260 REM calc rotate matrix
270 LET ax=c2*c3: LET ay=-c2*s3: LET az=s2
280 LET bx=c1*s3+s1*s2*c3
290 LET by=c1*c3-s1*s2*s3: LET bz=-s1*c2
300 LET cx=s1*s3-c1*s2*c3
310 LET cy=s1*c3+c1*s2*s3: LET cz=c1*c2
400 REM draw outer
410 CLS : CIRCLE u,v,r
500 REM draw lenght-circle
510 FOR l=0 TO 180-d STEP d
515 LET f1=0
520 FOR p=0 TO 360 STEP 5
530 GO SUB 1000: REM xx,yy,zz calc
540 IF yy>0 THEN LET f2=0: LET f1=0: GO TO 580
550 LET xb=INT (u+xx+h): LET yb=INT (v+zz+h): LET f2=1
560 IF f1=0 THEN LET x1=xb: LET y1=yb: LET f1=1: GO TO 580
570 PLOT x1,y1: DRAW xb-x1,yb-y1: LET x1=xb: LET y1=yb: LET f1=f2
580 NEXT p
590 NEXT l
600 REM draw wide-circle
610 FOR p=-90+d TO 90-d STEP d
615 LET f1=0
620 FOR l=0 TO 360 STEP 5
630 GO SUB 1000: REM xx,yy,zz
640 IF yy>0 THEN LET f2=0: LET f1=0: GO TO 680
650 LET xb=INT (u+xx+h): LET yb=INT (v+zz+h): LET f2=1
660 IF f1=0 THEN LET x1=xb: LET y1=yb: LET f1=1: GO TO 680
670 PLOT x1,y1: DRAW xb-x1,yb-y1: LET x1=xb: LET y1=yb: LET f1=f2
680 NEXT l
690 NEXT p
700 PRINT #0;"...press any key...": PAUSE 0: RUN
999 REM sfere-coordinates>>>Cartesis Coordinate
1000 LET x=r*COS (p*bm)*COS (l*bm)
1010 LET y=r*COS (p*bm)*SIN (l*bm)
1020 LET z=r*SIN (p*bm)
1030 REM p(x,y,z) rotate to p(xx,yy,zz)
1040 LET xx=ax*x+ay*y+az*z
1050 LET yy=bx*x+by*y+bz*z
1060 LET zz=cx*x+cy*y+cz*z
1070 RETURN</syntaxhighlight>
 
[[Category:Geometry]]
9,488

edits