-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdemo6.rs
58 lines (52 loc) · 2.08 KB
/
demo6.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Copyright 2022 Lukasz Janyst <[email protected]>
// Licensed under the MIT license, see the LICENSE file for details.
use ray_tracer::{color, intersect, point, sphere_unit, Canvas, Ray};
use ray_tracer::{point_light, Intersections, Material};
use std::io::{self, Write};
use std::time::Instant;
pub fn demo6() {
print!("Rendering demo6... ");
io::stdout().flush().unwrap();
let now = Instant::now();
let ray_origin = point(0.0, 0.0, -5.0);
let canvas_dim = (7.0_f64, 7.0_f64);
let mut canvas = Canvas::new(500, 500);
let mut m = Material::new();
m.color = color(1.0, 0.2, 1.0);
let mut sphere = sphere_unit();
sphere.set_material(&m);
let light = point_light(point(-10.0, 10.0, -10.0), color(1.0, 1.0, 1.0));
let offset = (canvas_dim.0 / 2.0, canvas_dim.1 / 2.0);
let cz = 10.0_f64;
for i in 0..canvas.width() {
let cx = (i as f64 / canvas.width() as f64) * canvas_dim.0 - offset.0;
for j in 0..canvas.height() {
let cy = -((j as f64 / canvas.width() as f64) * canvas_dim.1 - offset.1);
let ray_target = point(cx, cy, cz);
let ray_direction = (ray_target - ray_origin).normalized();
let ray = Ray::new(ray_origin, ray_direction);
let xs = Intersections::from_vector(intersect(sphere.as_ref(), &ray));
let hit = xs.hit();
if let Some(hit) = hit {
let point = ray.position(hit.t());
let normalv = hit.shape().normal_at(point);
let eyev = -ray.direction();
let c = hit.shape().material().lighting(
sphere.as_ref(),
&light,
&point,
&eyev,
&normalv,
false,
);
canvas.set(i, j, &c);
} else {
canvas.set(i, j, &color(0.0, 0.0, 0.0));
}
}
}
let elapsed = now.elapsed();
let fname = "demo6.ppm";
canvas.save(fname).unwrap();
println!("done. Elapsed {:.2?}. Saved {}.", elapsed, fname);
}