use std::{ fmt::Write as FmtWriter, fs::File, io::{self, BufWriter, Write}, num, path::Path, }; use maths::vec3::Colour; use numtoa::NumToA; use thiserror::Error; pub struct PPM { pub width: usize, pub height: usize, pub buffer: Vec, } impl PPM { pub fn new(width: usize, height: usize) -> Result { if width == 0 || height == 0 { // TODO: Return why (e.g. too big, too small etc) return Err(PPMError::InvalidDimension()); } let buffer = Vec::with_capacity(width * height); Ok(Self { width, height, buffer, }) } pub fn write_to_file(&self, path: &Path) -> Result<(), PPMError> { let mut file = File::create(path)?; file.write_all(format!("P3\n{} {}\n255\n", self.width, self.height).as_bytes())?; // Each 'pixel' takes 13 bytes // up to 4 per RGB * 3 // 1 extra for space on the end let mut mem = String::with_capacity(13 * (self.width * self.height)); let mut numbuf = [0u8; 4]; for colour in self.buffer.iter() { colour.write_as_u8(&mut mem, &mut numbuf); // write!(writer, "{} {} {} ", colour.red, colour.green, colour.blue)?; } file.write_all(mem.as_bytes())?; Ok(()) } } #[derive(Error, Debug)] pub enum PPMError { #[error("failed to write to file")] IoFailure(#[from] io::Error), #[error("invalid width/height")] InvalidDimension(), } #[cfg(test)] mod tests { use super::*; #[test] pub fn write_white() { let mut ppm = PPM::new(10, 10).unwrap(); for _ in 0..(ppm.height * ppm.width) { ppm.buffer.push(Colour::new(255.0, 255.0, 255.0)); } ppm.write_to_file(Path::new("/tmp/white.ppm")).unwrap(); } #[test] pub fn rainbow() { let mut ppm = PPM::new(100, 100).unwrap(); for width in 0..ppm.width { for height in 0..ppm.height { let r = height as f64 / (ppm.height - 1) as f64; let g = width as f64 / (ppm.width - 1) as f64; let b = 0.0; ppm.buffer.push(Colour::new(r, g, b)); } } ppm.write_to_file(Path::new("/tmp/rainbow.ppm")).unwrap(); } }