Draw a sphere: Difference between revisions
Content added Content deleted
(Added D version) |
(Improved formatting D code) |
||
Line 157: | Line 157: | ||
{{trans|C}} |
{{trans|C}} |
||
<lang d>import std.stdio, std.math, std.algorithm, std.numeric; |
<lang d>import std.stdio, std.math, std.algorithm, std.numeric; |
||
⚫ | |||
double[3] light = [30, 30, -50]; |
double[3] light = [30, 30, -50]; |
||
void normalize(ref double[3] v) { |
void normalize(ref double[3] v) { |
||
double len = sqrt(dotProduct(v[], v[])); |
double len = sqrt(dotProduct(v[], v[])); |
||
v[0] /= len; v[1] /= len; v[2] /= len; |
v[0] /= len; v[1] /= len; v[2] /= len; |
||
} |
} |
||
double dot(const ref double[3] x, const ref double[3] y) { |
double dot(const ref double[3] x, const ref double[3] y) { |
||
double d = dotProduct(x[], y[]); |
double d = dotProduct(x[], y[]); |
||
return d < 0 ? -d : 0; |
return d < 0 ? -d : 0; |
||
} |
} |
||
void |
void drawSphere(double R, double k, double ambient) { |
||
⚫ | |||
double[3] vec; |
|||
foreach (int i; cast(int)floor(-R) .. cast(int)ceil(R) + 1) { |
foreach (int i; cast(int)floor(-R) .. cast(int)ceil(R) + 1) { |
||
const double x = i + 0.5; |
const double x = i + 0.5; |
||
foreach (int j; cast(int)floor(-2 |
foreach (int j; cast(int)floor(-2*R)..cast(int)ceil(2*R)+1){ |
||
const double y = j / 2. + 0.5; |
const double y = j / 2. + 0.5; |
||
if (x |
if (x ^^ 2 + y ^^ 2 <= R ^^ 2) { |
||
vec = [x, y, |
double[3] vec = [x, y, (R^^2 - x^^2 - y^^2) ^^ 0.5]; |
||
vec.normalize(); |
vec.normalize(); |
||
const double b = dot(light, vec) ^^ k + ambient; |
const double b = dot(light, vec) ^^ k + ambient; |
||
int intensity = cast(int)((1 |
int intensity = cast(int)((1-b) * (shades.length-1)); |
||
intensity = min(shades.length-1, max(intensity, 0)); |
intensity = min(shades.length-1, max(intensity, 0)); |
||
putchar(shades[intensity]); |
putchar(shades[intensity]); |
||
Line 191: | Line 189: | ||
} |
} |
||
} |
} |
||
void main() { |
void main() { |
||
normalize(light); |
normalize(light); |
||
drawSphere(20, 4, 0.1); |
|||
drawSphere(10, 2, 0.4); |
|||
}</lang> |
}</lang> |
||