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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
|
use std::{borrow::Borrow, sync::RwLock, time::Duration};
use rayon::prelude::*;
use synchronoise::SignalEvent;
use crate::{
camera::Camera,
config::RenderData,
error::TracerError,
geometry::Hittable,
image::{Image, SubImage},
ray::Ray,
util::random_double,
vec3::{Color, Vec3},
};
fn ray_color(scene: &dyn Hittable, ray: &Ray, depth: usize) -> Vec3 {
if depth == 0 {
return Vec3::default();
}
if let Some(rec) = scene.hit(ray, 0.001, std::f64::INFINITY) {
if let Some((scattered, attenuation)) = rec.material.scatter(ray, &rec) {
return attenuation * ray_color(scene, &scattered, depth - 1);
}
return Color::default();
}
// Sky
let first_color = Vec3::new(1.0, 1.0, 1.0);
let second_color = Vec3::new(0.5, 0.7, 1.0);
let unit_direction = ray.direction().unit_vector();
let t = 0.5 * (unit_direction.y() + 1.0);
(1.0 - t) * first_color + t * second_color
}
pub fn raytrace_scaled(
buffer: &RwLock<Vec<u32>>,
cancel_event: Option<&SignalEvent>,
scene: &dyn Hittable,
camera: Camera,
image: &SubImage,
data: &RenderData,
scale: (usize, usize),
) -> Result<(), TracerError> {
let (scale_width, scale_height) = scale;
let scaled_width = image.width / scale_width;
let scaled_height = image.height / scale_height;
let mut colors: Vec<Vec3> = vec![Vec3::default(); scaled_height * scaled_width];
for row in 0..scaled_height {
for column in 0..scaled_width {
let u: f64 = ((image.x + column * scale_width) as f64 + random_double())
/ (image.screen_width - 1) as f64;
for _ in 0..data.samples {
let v: f64 = ((image.y + row * scale_height) as f64 + random_double())
/ (image.screen_height - 1) as f64;
colors[row * scaled_width + column].add(ray_color(
scene,
&camera.get_ray(u, v),
data.max_depth,
));
}
}
if do_cancel(cancel_event) {
return Ok(());
}
}
(!do_cancel(cancel_event))
.then_some(|| ())
.ok_or(TracerError::CancelEvent)
.and_then(|_| {
buffer
.write()
.map_err(|e| TracerError::FailedToAcquireLock(e.to_string()))
})
.map(|mut buf| {
let offset = image.y * image.screen_width + image.x;
for scaled_row in 0..scaled_height {
for scaled_col in 0..scaled_width {
let color = colors[scaled_row * scaled_width + scaled_col]
.scale_sqrt(data.samples)
.as_color();
let row = scaled_row * scale_height;
let col = scaled_col * scale_width;
for scale_h in 0..scale_height {
for scale_w in 0..scale_width {
buf[offset + (row + scale_h) * image.screen_width + col + scale_w] =
color;
}
}
}
}
})
}
pub fn raytrace(
buffer: &RwLock<Vec<u32>>,
cancel_event: Option<&SignalEvent>,
scene: &dyn Hittable,
camera: Camera,
image: &SubImage,
data: &RenderData,
) -> Result<(), TracerError> {
let mut colors: Vec<Vec3> = vec![Vec3::default(); image.height * image.width];
for row in 0..image.height {
for column in 0..image.width {
let u: f64 =
((image.x + column) as f64 + random_double()) / (image.screen_width - 1) as f64;
for _ in 0..data.samples {
let v: f64 =
((image.y + row) as f64 + random_double()) / (image.screen_height - 1) as f64;
colors[row * image.width + column].add(ray_color(
scene,
&camera.get_ray(u, v),
data.max_depth,
));
}
}
if do_cancel(cancel_event) {
return Ok(());
}
}
(!do_cancel(cancel_event))
.then_some(|| ())
.ok_or(TracerError::CancelEvent)
.and_then(|_| {
buffer
.write()
.map_err(|e| TracerError::FailedToAcquireLock(e.to_string()))
})
.map(|mut buf| {
let offset = image.y * image.screen_width + image.x;
for row in 0..image.height {
for col in 0..image.width {
let color = colors[row * image.width + col]
.scale_sqrt(data.samples)
.as_color();
buf[offset + row * image.screen_width + col] = color;
}
}
})
}
fn do_cancel(cancel_event: Option<&SignalEvent>) -> bool {
match cancel_event {
Some(event) => event.wait_timeout(Duration::from_secs(0)),
None => false,
}
}
fn get_highest_divdable(value: usize, mut div: usize) -> usize {
// Feels like there could possibly be some other nicer trick to this.
while (value % div) != 0 {
div -= 1;
}
div
}
pub fn render(
buffer: &RwLock<Vec<u32>>,
camera: &RwLock<Camera>,
image: &Image,
scene: &dyn Hittable,
data: &RenderData,
cancel_event: Option<&SignalEvent>,
scale: Option<usize>,
) -> Result<(), TracerError> {
if do_cancel(cancel_event) {
return Ok(());
}
let width_step = image.width / data.num_threads_width;
let height_step = image.height / data.num_threads_height;
let scaled_width = scale.map_or(1, |s| get_highest_divdable(width_step, s));
let scaled_height = scale.map_or(1, |s| get_highest_divdable(height_step, s));
(!do_cancel(cancel_event))
.then_some(|| ())
.ok_or(TracerError::CancelEvent)
.and_then(|_| {
camera
.read()
.map_err(|e| TracerError::FailedToAcquireLock(e.to_string()))
// We make a clone of it as it's not very important to
// have the latest camera angle etc. Better to keep
// the lock to a minimum.
.map(|cam| cam.clone())
})
.map(|cam| {
let images = (0..data.num_threads_width)
.flat_map(|ws| {
(0..data.num_threads_height)
.map(|hs| SubImage {
x: width_step * ws,
y: height_step * hs,
screen_width: image.width,
screen_height: image.height,
// Neccesary in case the threads width is not
// evenly divisible by the image width.
width: if ws == data.num_threads_width - 1 {
image.width - width_step * ws
} else {
width_step
},
// Neccesary in case the threads height is not
// evenly divisible by the image height.
height: if hs == data.num_threads_height - 1 {
image.height - height_step * hs
} else {
height_step
},
})
.collect::<Vec<SubImage>>()
})
.collect::<Vec<SubImage>>();
(cam, images)
})
.and_then(|(cam, sub_images)| {
sub_images
.into_par_iter()
.map(|image| {
scale.map_or_else(
|| {
raytrace(
buffer,
cancel_event,
(*scene).borrow(),
cam.clone(),
&image,
data,
)
},
|_| {
raytrace_scaled(
buffer,
cancel_event,
(*scene).borrow(),
cam.clone(),
&image,
data,
(scaled_width, scaled_height),
)
},
)
})
.collect::<Result<(), TracerError>>()
})
}
|