146 lines · 5.9 KB · RustRaw
//! A picture made from nothing: a generated landscape (a sky, a sun, hills)//! as a PNG, so a synthetic photo has bytes to show without one real pixel in//! the tree. The workspace carries no image encoder on purpose, and a PNG//! needs none worth the name: a header, the rows through DEFLATE, two//! checksums.use super::SeededRandom;type Rgb = [u8; 3];/// What one picture is of — drawn once from the seed, rendered at any size,/// so a photo's small preview is the same scene as the photo.pub struct Scene { sky_top: Rgb, sky_low: Rgb, sun: Rgb, /// Centre and radius, as fractions of the width and height. sun_at: (f64, f64, f64), /// Back to front: where the ridge sits, how tall its waves are, how many /// there are across the picture, where they start, and its colour. hills: Vec<(f64, f64, f64, f64, Rgb)>,}impl Scene { pub fn draw(rng: &SeededRandom) -> Scene { const SKIES: [(Rgb, Rgb); 6] = [ ([54, 120, 201], [186, 219, 242]), ([24, 40, 92], [230, 132, 92]), ([120, 134, 150], [208, 212, 216]), ([250, 176, 94], [252, 226, 170]), ([32, 90, 150], [140, 200, 220]), ([70, 58, 110], [240, 160, 150]), ]; const GROUNDS: [Rgb; 6] = [[52, 110, 70], [96, 122, 60], [150, 128, 84], [40, 80, 96], [118, 92, 70], [70, 96, 120]]; let (sky_top, sky_low) = *rng.pick(&SKIES); let ground = *rng.pick(&GROUNDS); let ridges = rng.between(2, 4) as usize; let hills = (0..ridges) .map(|n| { // Each ridge nearer, lower in the frame and darker than the last. let shade = |c: u8| (f64::from(c) * (1.15 - 0.2 * n as f64)).clamp(0.0, 255.0) as u8; ( 0.48 + 0.14 * n as f64 + rng.between(0, 6) as f64 / 100.0, rng.between(3, 9) as f64 / 100.0, rng.between(1, 4) as f64 + rng.between(0, 9) as f64 / 10.0, rng.between(0, 628) as f64 / 100.0, [shade(ground[0]), shade(ground[1]), shade(ground[2])], ) }) .collect(); Scene { sky_top, sky_low, sun: [255, rng.between(210, 250) as u8, rng.between(150, 230) as u8], sun_at: (rng.between(12, 88) as f64 / 100.0, rng.between(10, 38) as f64 / 100.0, rng.between(4, 9) as f64 / 100.0), hills, } } fn pixel(&self, x: f64, y: f64, aspect: f64) -> Rgb { for (level, height, waves, phase, colour) in self.hills.iter().rev() { let ridge = level + height * (x * waves * std::f64::consts::TAU + phase).sin(); if y >= ridge { return *colour; } } let (cx, cy, radius) = self.sun_at; if ((x - cx) * aspect).powi(2) + (y - cy).powi(2) <= radius.powi(2) { return self.sun; } // The sky runs from its top colour to its low one at the first ridge. let t = (y / 0.5).clamp(0.0, 1.0); let mix = |a: u8, b: u8| (f64::from(a) + (f64::from(b) - f64::from(a)) * t) as u8; [mix(self.sky_top[0], self.sky_low[0]), mix(self.sky_top[1], self.sky_low[1]), mix(self.sky_top[2], self.sky_low[2])] } /// The scene as a PNG `width` by `height` pixels. pub fn png(&self, width: u32, height: u32) -> Vec<u8> { let aspect = f64::from(width) / f64::from(height); let mut rows = Vec::with_capacity((width as usize * 3 + 1) * height as usize); for y in 0..height { rows.push(0); // filter: none for x in 0..width { rows.extend(self.pixel( (f64::from(x) + 0.5) / f64::from(width), (f64::from(y) + 0.5) / f64::from(height), aspect, )); } } let mut header = Vec::with_capacity(13); header.extend(width.to_be_bytes()); header.extend(height.to_be_bytes()); header.extend([8, 2, 0, 0, 0]); // 8 bits a channel, RGB, no interlace let mut out = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]; chunk(&mut out, b"IHDR", &header); chunk(&mut out, b"IDAT", &miniz_oxide::deflate::compress_to_vec_zlib(&rows, 6)); chunk(&mut out, b"IEND", &[]); out }}fn chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) { out.extend((data.len() as u32).to_be_bytes()); let from = out.len(); out.extend(kind); out.extend(data); let sum = crc32(&out[from..]); out.extend(sum.to_be_bytes());}/// The PNG checksum (CRC-32, the reflected 0xEDB88320 polynomial), a bit at a/// time: a few hundred kilobytes a household, so no table.fn crc32(bytes: &[u8]) -> u32 { let mut crc = u32::MAX; for byte in bytes { crc ^= u32::from(*byte); for _ in 0..8 { crc = if crc & 1 == 1 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 }; } } !crc}#[cfg(test)]mod tests { use super::*; #[test] fn the_checksum_is_the_one_png_readers_check() { // The CRC-32 check value every implementation is tested against. assert_eq!(crc32(b"123456789"), 0xCBF4_3926); } #[test] fn a_scene_is_a_png_whose_rows_inflate_to_its_pixels() { let png = Scene::draw(&SeededRandom::new(3)).png(32, 24); assert_eq!(&png[..8], &[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]); assert_eq!(&png[12..16], b"IHDR"); assert_eq!(&png[16..24], &[0, 0, 0, 32, 0, 0, 0, 24]); let data = png.windows(4).position(|w| w == b"IDAT").expect("pixel data") + 4; let length = u32::from_be_bytes(png[data - 8..data - 4].try_into().expect("a length")) as usize; let rows = miniz_oxide::inflate::decompress_to_vec_zlib(&png[data..data + length]).expect("the rows inflate"); assert_eq!(rows.len(), (32 * 3 + 1) * 24); assert_eq!(&png[png.len() - 8..png.len() - 4], b"IEND"); }}