summaryrefslogtreecommitdiff
path: root/src/renderer.rs
blob: 72ecf4e6de59bced72daea5da148277c102ca0a5 (plain)
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
use crate::calculus::calculus::{Point3, Ray, Vec3};
use crate::global::{Color, DisplayBuffer, Pixel, CAMERA_CENTER, FOCAL_LENGTH, IMG_HEIGHT, IMG_WIDTH, VIEWPORT_HEIGHT, VIEWPORT_WIDTH};
use crate::interval::Interval;
use crate::object::{HitRecord, Hittable, HittableList, Sphere};

fn ray_color(ray: &Ray, world: &HittableList) -> Color {
    let mut rec = HitRecord::default();
    let ray_t = Interval::new(0.0, f32::INFINITY);
    if world.hit(ray, ray_t, &mut rec) {
        let color = Color::new(1.0, 1.0, 1.0)
            .add(&Color::new(
                rec.normal.x,
                rec.normal.y,
                rec.normal.z)
            )
            .mul_scalar(0.5);
        return color;
    }

    let unit_direction = ray.direction.unit();
    let a = 0.5 * (unit_direction.y + 1.0);
    let color1 = Color::new(1.0, 1.0, 1.0).mul_scalar(1.0 - a);
    let color2 = Color::new(0.5, 0.7, 1.0).mul_scalar(a);
    color1.add(&color2)
}

pub fn render(display_buffer: &mut DisplayBuffer) {
    let viewport_hor_vector = Vec3{ x: VIEWPORT_WIDTH, y: 0.0, z: 0.0 };
    let viewport_ver_vector = Vec3 { x: 0.0, y: -1f32 * VIEWPORT_HEIGHT, z: 0.0 };

    let delta_pixel_u = viewport_hor_vector.scalar_mul(1.0 / IMG_WIDTH as f32);
    let delta_pixel_v = viewport_ver_vector.scalar_mul(1.0 / IMG_HEIGHT as f32);

    let viewport_upper_left = CAMERA_CENTER
        .sub(&Vec3 { x: 0f32, y: 0f32, z: FOCAL_LENGTH})
        .sub(&viewport_hor_vector.scalar_mul(0.5))
        .sub(&viewport_ver_vector.scalar_mul(0.5));
    let pixel_upper_left = viewport_upper_left.add(
        &delta_pixel_u.add(&delta_pixel_u).scalar_mul(0.5)
    );

    let mut world = HittableList::new();

    world.push(
        Sphere::new(Point3::new(0.0, 0.0, -1.0), 0.5)
    );

    world.push(
        Sphere::new(Point3::new(0.0, -100.5, -1.0), 100.0)
    );


    (0..IMG_HEIGHT).for_each(|j| {
        (0..IMG_WIDTH).for_each(|i| {
            let pixel_center = pixel_upper_left
                .add(&delta_pixel_u.scalar_mul(i as f32))
                .add(&delta_pixel_v.scalar_mul(j as f32));
            let ray_direction = pixel_center.sub(&CAMERA_CENTER);
            let ray = Ray {
                origin: &CAMERA_CENTER,
                direction: &ray_direction,
            };
            let color = ray_color(&ray, &world);
            display_buffer[j][i] = Pixel::from_color(&color);
        })
    })
}