summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 0c812202445f160920868a39b1d543cf43b533ef (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
68
69
70
71
72
73
74
75
76
77
use std::fs::File;
use std::io::Write;

const IMG_WIDTH: usize = 256;
const IMG_HEIGHT: usize = 256;

#[derive(Debug, Copy, Clone)]
struct Pixel {
    r: u8,
    g: u8,
    b: u8,
}

impl Default for Pixel {
    fn default() -> Self {
        Pixel { r:0, g:0, b:0 }
    }
}

struct View<'a> {
    data: &'a[[Pixel; IMG_WIDTH]; IMG_HEIGHT],
    viewer: fn(&[[Pixel; IMG_WIDTH]; IMG_HEIGHT]) -> Result<String, std::io::Error>,
}

impl<'a> View<'a> {
    fn display(&self) {
        let result = (self.viewer)(self.data);
        match result {
            Ok(success_msg) => {
                println!("{}", success_msg);
            },
            Err(error_msg) => {
                eprintln!("{}", error_msg);
            }
        }
    }
}

fn ppm_exporter(data: &[[Pixel; IMG_WIDTH]; IMG_HEIGHT]) -> Result<String, std::io::Error> {
    let file_name = "output.ppm";
    let mut file = File::create(file_name)?;
    // header
    let mut txt_data = String::from("P3\n");
    txt_data.push_str(format!("{} {}\n255\n", IMG_WIDTH, IMG_HEIGHT).as_str());
    // data point
    data.iter().for_each(|row| {
        row.iter().for_each(|&pixel| {
            txt_data.push_str(&format!("{} {} {}\n", pixel.r, pixel.g, pixel.b));
        })
    });
    file.write_all(txt_data.as_bytes())?;
    Ok(format!("Output rendered to file {}", file_name))
}

fn main() {
    let mut data = [[Pixel::default(); IMG_WIDTH]; IMG_HEIGHT];

    (0..IMG_HEIGHT).for_each(|j| {
        (0..IMG_WIDTH).for_each(|i| {
            let r = i as f32 / IMG_WIDTH as f32;
            let g = j as f32 / IMG_HEIGHT as f32;
            let b = 0.0f32;

            let ir = (255.999 * r) as u8;
            let ig = (255.999 * g) as u8;
            let ib = (255.999 * b) as u8;

            data[i][j] = Pixel { r: ir, g: ig, b: ib};
        })
    });

    let view = View {
        data: &data,
        viewer: ppm_exporter,
    };
    view.display();
}