rustic-zen 0.3.0

Photon-Garden raytracer for creating artistic renderings
Documentation
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! Image contains the full colour depth framebuffer, and provides functions to export it.

use crate::{geom::Point, ray::RayResult};

use std::mem::swap;

use super::{ExportImage, RenderImage};

/// Represents an image while ray rendering is happening
///
/// This struct uses floats to represent each pixel of the image so normalisation
/// can happen after rendering finishes.
///
/// Image is created and populated by the renderer. Only export functions are exposed.
pub struct Image {
    width: usize,
    height: usize,
    pixels: Vec<(f32, f32, f32)>,
    lightpower: f32,
}

impl Image {
    /// Create new image with the given width and hieght;
    pub fn new(width: usize, height: usize) -> Self {
        let len = width * height;
        let pixels: Vec<(f32, f32, f32)> = vec![(0.0, 0.0, 0.0); len];
        Image {
            width,
            height,
            pixels,
            lightpower: 0.0,
        }
    }

    #[inline(always)]
    fn plot(&self, colour: (f32, f32, f32), pixel: usize, intensity: f32) {
        if pixel >= self.pixels.len() {
            return;
        };

        unsafe {
            // This is using statistical safety. A tyical image has over 8 million data points in it,
            // while even a high end CPU will likely only have 64 threads. Safety while not guarenteed
            // is provided "good enough" by the diminishinly small change of a read before write error
            // occuring in this large dataset, and the miniscule values the pixels are updated with by
            // each ray.
            //
            // NB: This is not actually safe. Small data errors will occur. We however don't consider
            // them significant.
            let s = (self as *const Self) as *mut Self;
            (*s).pixels[pixel].0 += colour.0 * intensity;
            (*s).pixels[pixel].1 += colour.1 * intensity;
            (*s).pixels[pixel].2 += colour.2 * intensity;
        }
    }

    #[inline(always)]
    fn inner_draw_line(&self, ray: &RayResult) {
        /*
         * Modified version of Xiaolin Wu's antialiased line algorithm:
         * http://en.wikipedia.org/wiki/Xiaolin_Wu%27s_line_algorithm
         *
         * Brightness compensation:
         *   The total brightness of the line should be proportional to its
         *   length, but with Wu's algorithm it's proportional to dx.
         *   We scale the brightness of each pixel to compensate.
         */

        let bounds =
            Self::check_bounds(ray.origin, ray.termination, self.width - 1, self.height + 2);
        if bounds.is_none() {
            return;
        }

        let colour = ray.color();

        let (p0, p1) = bounds.unwrap();

        let mut hx: i64 = 1;
        let mut hy: i64 = self.width as i64;

        let mut x0 = p0.x;
        let mut y0 = p0.y;
        let mut x1 = p1.x;
        let mut y1 = p1.y;

        let dx = (x1 - x0).abs();
        let dy = (y1 - y0).abs();

        // Axis swap. The virtual 'x' is always the major axis.
        if dy > dx {
            swap(&mut x0, &mut y0);
            swap(&mut x1, &mut y1);
            swap(&mut hx, &mut hy);
        }

        // We expect x0->x1 to be in the +X direction
        if x0 > x1 {
            swap(&mut x0, &mut x1);
            swap(&mut y0, &mut y1);
        }

        // calculate gradient
        let dx = x1 - x0;
        let dy = y1 - y0;
        let gradient = if dx == 0.0 { 1.0 } else { dy / dx };

        const SHIFT: f64 = 0.25;

        x0 -= SHIFT;
        x1 += SHIFT;
        y0 -= gradient * SHIFT;
        y1 += gradient * SHIFT;

        // Brightness Calculation
        let br = 128.0 * f64::sqrt(dx * dx + dy * dy) / dx;

        // TODO clipping here

        // Handle first endpoint
        let xend = x0.round();
        let yend = y0 + gradient * (xend - x0);
        let xpxl1: i64 = xend as i64;
        let ypxl1: i64 = yend.floor() as i64;

        let xgap = br * (1.0 - (x0 + 0.5) + xend); // 0 to br
        let ygap = yend - yend.floor(); // 0 to 1

        self.plot(
            colour,
            (xpxl1 * hx + ypxl1 * hy) as usize,
            (xgap * (1.0 - ygap)) as f32,
        );
        self.plot(
            colour,
            (xpxl1 * hx + (ypxl1 + 1) * hy) as usize,
            (xgap * ygap) as f32,
        );

        let mut intery = yend + gradient;

        //Handle Second endpoint
        let xend = x1.round();
        let yend = y1 + gradient * (xend - x1);
        let xpxl2: i64 = xend as i64;
        let ypxl2: i64 = yend.floor() as i64;

        let xgap = br * (1.0 - (x1 + 0.5) + xend); // 0 to br
        let ygap = yend - yend.floor(); // 0 to 1

        self.plot(
            colour,
            (xpxl2 * hx + ypxl2 * hy) as usize,
            (xgap * (1.0 - ygap)) as f32,
        );
        self.plot(
            colour,
            (xpxl2 * hx + (ypxl2 + 1) * hy) as usize,
            (xgap * ygap) as f32,
        );

        // Loop Over line
        for x in xpxl1 + 1..xpxl2 {
            let iy: i64 = intery.floor() as i64;
            let fy: f64 = intery - intery.floor(); // 0 to 1

            self.plot(
                colour,
                (x * hx + iy * hy) as usize,
                (br * (1.0 - fy)) as f32,
            );
            self.plot(colour, (x * hx + (iy + 1) * hy) as usize, (br * fy) as f32);

            intery += gradient;
        }
    }

    #[inline(always)]
    fn check_bounds(
        mut p0: Point,
        mut p1: Point,
        width: usize,
        height: usize,
    ) -> Option<(Point, Point)> {
        let width = (width) as f64;
        let height = (height) as f64;

        if (p0.x < 0.0 && p1.x < 0.0) ||  // if both are less than 0 the line is not in frame
           (p0.y < 0.0 && p1.y < 0.0) || // if both are less than 0 the line is not in frame
           (p0.x > width && p1.x > width) || // if both are greater than width the line is not in frame
           (p0.y > height && p1.y > height)
        // if both are greater than height the line is not in frame
        {
            return None;
        }

        if p0.x > p1.x {
            swap(&mut p0, &mut p1);
        }

        let d = (p1 - p0).normalized();

        if d.x == 0.0 {
            p0.y = p0.y.clamp(0.0, height);
            p1.y = p1.y.clamp(0.0, height);
        } else {
            if p0.x < 0.0 {
                p0 = p0 - (d * (p0.x / d.x));
            }
            if p1.x > width {
                p1 = p1 - d * ((p1.x - width) / d.x);
            }
            if p0.y < 0.0 {
                p0 = p0 - (d * (p0.y / d.y));
            } else {
                if p0.y > height {
                    p0 = p0 - d * ((p0.y - height) / d.y);
                }
            }
            if p1.y < 0.0 {
                p1 = p1 - (d * (p1.y / d.y));
            } else {
                if p1.y > height {
                    p1 = p1 - d * ((p1.y - height) / d.y);
                }
            }
        }
        Some((p0, p1))
    }
}

impl RenderImage for Image {
    fn draw_line(&self, ray: RayResult) {
        self.inner_draw_line(&ray);
    }

    fn prepare_render(&mut self, lightpower: f32) {
        self.lightpower = lightpower;
    }
}

impl ExportImage for Image {
    fn get_lightpower(&self) -> f32 {
        self.lightpower
    }

    fn get_size(&self) -> (usize, usize) {
        (self.width, self.height)
    }

    fn to_rgbaf32(&self) -> Vec<f32> {
        self.pixels
            .clone()
            .into_iter()
            .map(|x| [x.0, x.1, x.2, 1.0f32])
            .flatten()
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::Image;
    use crate::image::{ExportImage, RenderImage};
    use crate::prelude::Point;
    use crate::ray::RayResult;

    #[test]
    fn traced_ray_is_not_black() {
        let i = Image::new(100, 100);
        i.draw_line(RayResult::new((10.0, 10.0), (90.0, 90.0), 620.0)); //red
        i.draw_line(RayResult::new((20.0, 10.0), (90.0, 80.0), 520.0)); //green
        i.draw_line(RayResult::new((10.0, 20.0), (80.0, 90.0), 470.0)); //blue
        let mut r_count = 0.0;
        let mut g_count = 0.0;
        let mut b_count = 0.0;
        for (r, g, b) in i.pixels.iter() {
            r_count += r;
            g_count += g;
            b_count += b;
        }
        assert_ne!(r_count, 0.0);
        assert_ne!(g_count, 0.0);
        assert_ne!(b_count, 0.0);
    }

    #[test]
    fn empty_image_is_black() {
        let mut i = Image::new(1920, 1080);
        i.prepare_render(1.0);
        let v = i.to_rgba8(0, 1.0, 1.0);
        for i in v.chunks(4) {
            assert_eq!(i[0], 0u8);
            assert_eq!(i[1], 0u8);
            assert_eq!(i[2], 0u8);
            assert_eq!(i[3], 255u8);
        }
    }

    #[test]
    fn output_len_u8() {
        let i = Image::new(1920, 1080);
        let v = i.to_rgba8(0, 1.0, 1.0);
        assert_eq!(v.len(), 1920 * 1080 * 4);
    }

    #[test]
    fn output_len_f32() {
        let i = Image::new(1920, 1080);
        let v = i.to_rgbaf32();
        assert_eq!(v.len(), 1920 * 1080 * 4);
    }

    #[test]
    fn contigious_lines() {
        let i = Image::new(400, 400);
        i.draw_line(RayResult::new((10.0, 10.0), (100.0, 100.0), 0.0));
        i.draw_line(RayResult::new((100.0, 100.0), (200.0, 200.0), 0.0));
        i.draw_line(RayResult::new((200.0, 200.0), (300.0, 300.0), 0.0));
        i.draw_line(RayResult::new((300.0, 300.0), (390.0, 390.0), 0.0));

        for x in 0..10 {
            for y in 0..400 {
                let p = i.pixels[(y * 400) + x];
                assert_eq!(p.0, 0.0);
                assert_eq!(p.1, 0.0);
                assert_eq!(p.2, 0.0);
            }
        }

        for x in 10..=390 {
            for y in 0..400 {
                let p = i.pixels[(y * 400) + x];
                if x == y {
                    assert!(p.0 > 0.0);
                    assert!(p.1 > 0.0);
                    assert!(p.2 > 0.0);
                } else {
                    assert_eq!(p.0, 0.0);
                    assert_eq!(p.1, 0.0);
                    assert_eq!(p.2, 0.0);
                }
            }
        }

        for x in 391..400 {
            for y in 0..400 {
                let p = i.pixels[(y * 400) + x];
                assert_eq!(p.0, 0.0);
                assert_eq!(p.1, 0.0);
                assert_eq!(p.2, 0.0);
            }
        }
    }

    #[test]
    fn line_correct() {
        let i = Image::new(100, 100);
        i.draw_line(RayResult::new((0.0, 0.0), (100.0, 100.0), 0.0)); //green
        for x in 0..100 {
            for y in 0..100 {
                let p = i.pixels[(y * 100) + x];
                if x == y {
                    assert!(p.0 > 0.0);
                    assert!(p.1 > 0.0);
                    assert!(p.2 > 0.0);
                } else {
                    assert_eq!(p.0, 0.0);
                    assert_eq!(p.1, 0.0);
                    assert_eq!(p.2, 0.0);
                }
            }
        }
    }

    #[test]
    fn bounds_check_left1() {
        let p0 = Point::new(-10.0, 0.0);
        let p1 = Point::new(10.0, 20.0);

        let (p0, p1) = Image::check_bounds(p0, p1, 50, 50).unwrap();

        assert_eq!(p0, (0.0, 10.0).into());
        assert_eq!(p1, (10.0, 20.0).into());
    }

    #[test]
    fn bounds_check_left2() {
        let p1 = Point::new(-10.0, 0.0);
        let p0 = Point::new(10.0, 20.0);

        let (p0, p1) = Image::check_bounds(p0, p1, 50, 50).unwrap();

        assert_eq!(p0, (0.0, 10.0).into());
        assert_eq!(p1, (10.0, 20.0).into());
    }

    #[test]
    fn bounds_check_right1() {
        let p0 = Point::new(60.0, 0.0);
        let p1 = Point::new(40.0, 20.0);

        let (p0, p1) = Image::check_bounds(p0, p1, 50, 50).unwrap();

        assert_eq!(p1, (50.0, 10.0).into());
        assert_eq!(p0, (40.0, 20.0).into());
    }

    #[test]
    fn bounds_check_right2() {
        let p1 = Point::new(60.0, 0.0);
        let p0 = Point::new(40.0, 20.0);

        let (p0, p1) = Image::check_bounds(p0, p1, 50, 50).unwrap();

        assert_eq!(p1, (50.0, 10.0).into());
        assert_eq!(p0, (40.0, 20.0).into());
    }

    #[test]
    fn bounds_check_top1() {
        let p0 = Point::new(20.0, -10.0);
        let p1 = Point::new(40.0, 10.0);

        let (p0, p1) = Image::check_bounds(p0, p1, 50, 50).unwrap();

        assert_eq!(p0, (30.0, 0.0).into());
        assert_eq!(p1, (40.0, 10.0).into());
    }

    #[test]
    fn bounds_check_top2() {
        let p1 = Point::new(20.0, -10.0);
        let p0 = Point::new(40.0, 10.0);

        let (p0, p1) = Image::check_bounds(p0, p1, 50, 50).unwrap();

        assert_eq!(p0, (30.0, 0.0).into());
        assert_eq!(p1, (40.0, 10.0).into());
    }

    #[test]
    fn bounds_check_bottom1() {
        let p0 = Point::new(10.0, 60.0);
        let p1 = Point::new(40.0, 30.0);

        let (p0, p1) = Image::check_bounds(p0, p1, 50, 50).unwrap();

        assert_eq!(p0, (20.0, 50.0).into());
        assert_eq!(p1, (40.0, 30.0).into());
    }

    #[test]
    fn bounds_check_bottom2() {
        let p1 = Point::new(10.0, 60.0);
        let p0 = Point::new(40.0, 30.0);

        let (p0, p1) = Image::check_bounds(p0, p1, 50, 50).unwrap();

        assert_eq!(p0, (20.0, 50.0).into());
        assert_eq!(p1, (40.0, 30.0).into());
    }
}