Jump to content

Draw a sphere: Difference between revisions

Improved formatting D code
(Added D version)
(Improved formatting D code)
Line 157:
{{trans|C}}
<lang d>import std.stdio, std.math, std.algorithm, std.numeric;
 
enum shades = ".:!*oe&#%@";
double[3] light = [30, 30, -50];
 
void normalize(ref double[3] v) {
double len = sqrt(dotProduct(v[], v[]));
v[0] /= len; v[1] /= len; v[2] /= len;
}
 
double dot(const ref double[3] x, const ref double[3] y) {
double d = dotProduct(x[], y[]);
return d < 0 ? -d : 0;
}
 
void draw_spheredrawSphere(double R, double k, double ambient) {
enum shades = ".:!*oe&#%@";
double[3] vec;
foreach (int i; cast(int)floor(-R) .. cast(int)ceil(R) + 1) {
const double x = i + 0.5;
foreach (int j; cast(int)floor(-2 * R) .. cast(int)ceil(2 * R) + 1) {
const double y = j / 2. + 0.5;
if (x *^^ x2 + y *^^ y2 <= R *^^ R2) {
double[3] vec = [x, y, sqrt(R * R^^2 - x ^^ 2 - y ^^ 2) ^^ 0.5];
vec.normalize();
const double b = dot(light, vec) ^^ k + ambient;
int intensity = cast(int)((1 - b) * (shades.length - 1));
intensity = min(shades.length-1, max(intensity, 0));
putchar(shades[intensity]);
Line 191 ⟶ 189:
}
}
 
void main() {
normalize(light);
draw_spheredrawSphere(20, 4, 0.1);
draw_spheredrawSphere(10, 2, 0.4);
}</lang>
 
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.