use std::io::Write; use std::net::TcpStream; use crate::display::{Display, Pixel}; use crate::vec3::Color; pub struct Pixelflut { socket: TcpStream, x: usize, y: usize, width: usize, height: usize, data: Vec, } impl Pixelflut { pub fn new(addr: &str, x: usize, y: usize, width: usize, height: usize) -> Self { let data = vec![ Pixel { color: Color { x: 0.0, y: 0.0, z: 0.0 }, sample_count: 0 }; width * height ]; let mut ret = Self { socket: TcpStream::connect(addr).expect("Could not connect to Pixelflut!"), x, y, width, height, data, }; ret.maybe_update(); ret } } impl Display for Pixelflut { fn add_sample(&mut self, x: usize, y: usize, color: crate::vec3::Color) { self.data .get_mut((y * self.width) + x) .unwrap() .update(color); } fn maybe_write(&self, _: &mut impl std::io::prelude::Write) {} fn maybe_update(&mut self) { for y in 0..self.height { for x in 0..self.width { let pixel = self.data.get((y * self.width) + x).unwrap(); let scale = 1.0 / pixel.sample_count as f64; let r = (pixel.color.x * scale).sqrt(); let g = (pixel.color.y * scale).sqrt(); let b = (pixel.color.z * scale).sqrt(); self.socket .write( format!( "PX {} {} {:02x}{:02x}{:02x}\n", self.x + x, self.y + self.height - y, (256.0 * r.clamp(0.0, 0.999)) as u32, (256.0 * g.clamp(0.0, 0.999)) as u32, (256.0 * b.clamp(0.0, 0.999)) as u32 ) .as_bytes(), ) .unwrap(); } } } }