From 16993e823110c64cc33bc71fab00031188c7e220 Mon Sep 17 00:00:00 2001 From: bankosegger Date: Wed, 18 Nov 2026 17:38:34 +0100 Subject: [PATCH 1/5] feat: print a small random pixel-art sprite at the bottom of each slip A mirrored 8x4 cell sprite, 72 dots high on 80 mm paper, is printed centred below the quote and differs per copy. Co-Authored-By: Claude Sonnet 5.5 --- src/artwork.rs | 65 +++++++++++++++++++ src/main.rs | 1 + src/printer.rs | 173 +++++++++++++++++++++++++++++++++++++++---------- 3 files changed, 204 insertions(+), 35 deletions(-) create mode 100644 src/artwork.rs diff --git a/src/artwork.rs b/src/artwork.rs new file mode 100644 index 0000000..93f303b --- /dev/null +++ b/src/artwork.rs @@ -0,0 +1,65 @@ +//! A small random pixel-art sprite for the bottom of every printed slip. +//! +//! The sprite is a few chunky cells high and mirrored left to right, which +//! makes random bits read as a little creature or emblem instead of noise. + +pub const COLUMNS: usize = 8; +pub const ROWS: usize = 4; +const HALF: usize = COLUMNS / 2; +/// How many of the 16 cells of the left half may be filled: enough to read as +/// a shape, not so many that it turns into a block. +const FILLED: std::ops::RangeInclusive = 6..=11; + +pub type Sprite = [[bool; COLUMNS]; ROWS]; + +/// The sprite for `seed`; the same seed always gives the same sprite. +pub fn sprite(seed: u64) -> Sprite { + let mut state = seed; + loop { + let bits = next(&mut state) & 0xFFFF; + let row = |index: usize| (bits >> (index * HALF)) & 0xF; + if !FILLED.contains(&bits.count_ones()) || (0..ROWS).any(|index| row(index) == 0) { + continue; + } + return std::array::from_fn(|y| { + std::array::from_fn(|x| row(y) >> x.min(COLUMNS - 1 - x) & 1 == 1) + }); + } +} + +/// SplitMix64: a few lines, well mixed, and good enough for decoration. +fn next(state: &mut u64) -> u64 { + *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut mixed = *state; + mixed = (mixed ^ (mixed >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + mixed = (mixed ^ (mixed >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + mixed ^ (mixed >> 31) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sprites_are_mirrored_filled_in_every_row_and_not_a_block() { + for seed in 0..2000 { + let sprite = sprite(seed); + let filled = sprite.iter().flatten().filter(|cell| **cell).count(); + assert!((12..=22).contains(&filled), "seed {seed}: {filled} cells"); + for row in sprite { + assert!(row.iter().any(|cell| *cell), "seed {seed}: empty row"); + assert!( + (0..COLUMNS).all(|x| row[x] == row[COLUMNS - 1 - x]), + "seed {seed}: not mirrored" + ); + } + } + } + + #[test] + fn a_seed_gives_one_sprite_and_seeds_give_many() { + assert_eq!(sprite(7), sprite(7)); + let distinct: std::collections::HashSet = (0..1000).map(sprite).collect(); + assert!(distinct.len() > 200, "{} sprites", distinct.len()); + } +} diff --git a/src/main.rs b/src/main.rs index e07fc41..5fbe3f6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -20,6 +20,7 @@ use slint::{Rgb8Pixel, SharedPixelBuffer}; slint::include_modules!(); +mod artwork; mod camera; mod capture; mod diagnostics; diff --git a/src/printer.rs b/src/printer.rs index 8fc27d6..e0be07c 100644 --- a/src/printer.rs +++ b/src/printer.rs @@ -26,7 +26,8 @@ //! Each photo is captioned with the event name and place above it, and a //! keepsake line, the capture date and time and one of `QUOTES` below it. The //! captions are in German with the English directly underneath, the quotes in -//! English only. The timestamp is the system +//! English only, then a small random pixel-art sprite (see `artwork`) closes +//! the slip. The timestamp is the system //! clock in local time, so the booth's clock has to be right for it to mean //! anything. Text goes out in the printer's own code page (PC437), since it //! prints UTF-8 bytes as separate glyphs; see `code_page`. @@ -53,7 +54,10 @@ use opencv::{ prelude::*, }; -use crate::quotes::QUOTES; +use crate::{ + artwork::{self, COLUMNS, ROWS}, + quotes::QUOTES, +}; const DEFAULT_PRINTER: &str = "/dev/usb/lp0"; const DEFAULT_DOTS: usize = 576; @@ -213,7 +217,14 @@ impl Printer { let bitmap = render(frame, self.dots, self.gamma).map_err(|error| format!("render: {error}"))?; let stamp = Local::now().format(STAMP_FORMAT).to_string(); - self.send(&encode(&bitmap, &self.head, copies, &stamp, first_quote())) + self.send(&encode( + &bitmap, + &self.head, + copies, + &stamp, + first_quote(), + clock_seed(), + )) } /// Sends the job one write at a time, pacing them to the print head. @@ -350,25 +361,60 @@ fn encode( copies: usize, stamp: &str, first_quote: usize, + seed: u64, ) -> Vec> { let mut job = Vec::new(); for copy in 0..copies { + let sprite = sprite_strip(bitmap.width_bytes * 8, seed.wrapping_add(copy as u64)); job.push(header(head)); - for band in bitmap.data.chunks(BAND_ROWS * bitmap.width_bytes) { - let rows = band.len() / bitmap.width_bytes; - let mut write = vec![0x1B, b'@']; // ESC @: initialize - write.extend(head.commands()); - write.extend([0x1D, b'v', b'0', 0]); // GS v 0: raster image, normal density - write.extend((bitmap.width_bytes as u16).to_le_bytes()); - write.extend((rows as u16).to_le_bytes()); - write.extend(band); - job.push(write); - } - job.push(footer(head, stamp, "ES[(first_quote + copy) % QUOTES.len()])); + raster_bands(&mut job, bitmap, head); + job.push(footer( + head, + stamp, + "ES[(first_quote + copy) % QUOTES.len()], + )); + raster_bands(&mut job, &sprite, head); + job.push(finish(head)); } job } +/// Appends the bitmap as one write per band of `BAND_ROWS` rows. +fn raster_bands(job: &mut Vec>, bitmap: &Bitmap, head: &Head) { + for band in bitmap.data.chunks(BAND_ROWS * bitmap.width_bytes) { + let rows = band.len() / bitmap.width_bytes; + let mut write = vec![0x1B, b'@']; // ESC @: initialize + write.extend(head.commands()); + write.extend([0x1D, b'v', b'0', 0]); // GS v 0: raster image, normal density + write.extend((bitmap.width_bytes as u16).to_le_bytes()); + write.extend((rows as u16).to_le_bytes()); + write.extend(band); + job.push(write); + } +} + +/// The random sprite centred on a full-width strip, `ROWS` cells high, with +/// cells that grow with the paper width (18 dots on 80 mm, 12 on 58 mm). +fn sprite_strip(dots: usize, seed: u64) -> Bitmap { + let cell = (dots / 32).max(1); + let left = (dots - COLUMNS * cell) / 2; + let stride = dots / 8; + let sprite = artwork::sprite(seed); + let mut data = vec![0u8; stride * ROWS * cell]; + for y in 0..ROWS * cell { + for x in 0..COLUMNS * cell { + if sprite[y / cell][x / cell] { + let dot = left + x; + data[y * stride + dot / 8] |= 0x80 >> (dot % 8); + } + } + } + Bitmap { + width_bytes: stride, + data, + } +} + /// The German letters and the middle dot in the captions as single PC437 bytes, /// the code page the booth's printer starts in. Anything else non-ASCII would /// need a wider table or `ESC t`, so a test keeps the printed text within this @@ -390,7 +436,10 @@ fn code_page(character: char) -> Option { /// Appends one line of text, encoded for the printer. fn text_line(write: &mut Vec, line: &str) { - write.extend(line.chars().map(|character| code_page(character).unwrap_or(b'?'))); + write.extend( + line.chars() + .map(|character| code_page(character).unwrap_or(b'?')), + ); write.push(b'\n'); } @@ -425,6 +474,13 @@ fn first_quote() -> usize { % QUOTES.len() } +/// Seed for the sprites of one job, from the clock like the quote. +fn clock_seed() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |since| since.as_nanos() as u64) +} + fn footer(head: &Head, stamp: &str, quote: &[&str]) -> Vec { let mut write = centered(head); write.extend([0x1B, b'd', 1]); @@ -438,6 +494,14 @@ fn footer(head: &Head, stamp: &str, quote: &[&str]) -> Vec { for line in quote { text_line(&mut write, line); } + write.extend([0x1B, b'd', 1]); // a blank line between the quote and the sprite + write +} + +/// Feeds the slip past the cutter and cuts it. +fn finish(head: &Head) -> Vec { + let mut write = vec![0x1B, b'@']; // ESC @: initialize + write.extend(head.commands()); write.extend([0x1B, b'd', FEED_LINES]); // ESC d n: feed n lines write.extend([0x1D, b'V', 66, 3]); // GS V 66 n: feed and partial cut write @@ -490,8 +554,7 @@ mod tests { #[test] fn quotes_are_picked_from_the_list_and_vary() { - let picked: std::collections::BTreeSet = - (0..1000).map(|_| first_quote()).collect(); + let picked: std::collections::BTreeSet = (0..1000).map(|_| first_quote()).collect(); assert!(picked.last().is_some_and(|last| *last < QUOTES.len())); // Not all of them on a coarse clock, but a slip must not be predictable. assert!(picked.len() > 1, "{picked:?}"); @@ -556,11 +619,14 @@ mod tests { width_bytes: 1, data: vec![0; BAND_ROWS + 1], }; - let job = encode(&bitmap, &Head::from_values(Some("85"), Some("quality")), 1, STAMP, 0); + let head = Head::from_values(Some("85"), Some("quality")); + let job = encode(&bitmap, &head, 1, STAMP, 0, 0); for band in &job[1..3] { assert_eq!( &band[..12], - [0x1B, b'@', 0x12, b'~', 85, 0x1D, b's', 1, 0x1D, b'v', b'0', 0] + [ + 0x1B, b'@', 0x12, b'~', 85, 0x1D, b's', 1, 0x1D, b'v', b'0', 0 + ] ); } } @@ -596,10 +662,11 @@ mod tests { width_bytes: 2, data: vec![0xAA; 2 * (BAND_ROWS + 1)], }; - let job = encode(&bitmap, &Head::default(), 2, STAMP, 0); - // Per copy: the caption, a full band, the leftover row, then the footer. - assert_eq!(job.len(), 2 * 4); - for copy in job.chunks(4) { + let job = encode(&bitmap, &Head::default(), 2, STAMP, 0, 0); + // Per copy: the caption, a full band, the leftover row, the footer, the + // sprite and the cut. + assert_eq!(job.len(), 2 * 6); + for copy in job.chunks(6) { assert_eq!( ©[1][..10], [0x1B, b'@', 0x1D, b'v', b'0', 0, 2, 0, BAND_ROWS as u8, 0] @@ -607,13 +674,57 @@ mod tests { assert_eq!(copy[1].len(), 10 + 2 * BAND_ROWS); assert_eq!( copy[2], - [vec![0x1B, b'@', 0x1D, b'v', b'0', 0, 2, 0, 1, 0], vec![0xAA; 2]].concat() + [ + vec![0x1B, b'@', 0x1D, b'v', b'0', 0, 2, 0, 1, 0], + vec![0xAA; 2] + ] + .concat() ); } // Every write initializes first, so no dot data is read as commands. assert!(job.iter().all(|write| write.starts_with(&[0x1B, b'@']))); } + #[test] + fn closes_each_slip_with_a_centred_sprite_before_the_cut() { + for dots in [384, 576] { + let strip = sprite_strip(dots, 42); + let cell = dots / 32; + assert_eq!(strip.width_bytes, dots / 8); + assert_eq!(strip.data.len(), dots / 8 * ROWS * cell); + let lit = |row: usize, dot: usize| { + strip.data[row * strip.width_bytes + dot / 8] & (0x80 >> (dot % 8)) != 0 + }; + // Mirrored about the centre of the paper, nothing outside the sprite. + let margin = (dots - COLUMNS * cell) / 2; + for row in 0..ROWS * cell { + for dot in 0..dots { + assert_eq!( + lit(row, dot), + lit(row, dots - 1 - dot), + "{dots} {row} {dot}" + ); + if !(margin..dots - margin).contains(&dot) { + assert!(!lit(row, dot), "{dots} {row} {dot}"); + } + } + } + assert!(strip.data.iter().any(|byte| *byte != 0)); + } + // After the footer come the sprite bands (72 rows at 576 dots), then the cut. + let bitmap = Bitmap { + width_bytes: 72, + data: vec![0; 72], + }; + let job = encode(&bitmap, &Head::default(), 1, STAMP, 0, 5); + assert_eq!(job.len(), 6); // caption, photo, footer, 2 sprite bands, cut + assert!(job[3].starts_with(&[0x1B, b'@', 0x1D, b'v', b'0', 0, 72, 0, BAND_ROWS as u8, 0])); + assert!(job[5].ends_with(&[0x1D, b'V', 66, 3])); + // Copies get different sprites. + let two = encode(&bitmap, &Head::default(), 2, STAMP, 0, 5); + assert_ne!(two[3], two[9]); + } + #[test] fn captions_the_photo_and_cuts_once_per_copy() { let bitmap = Bitmap { @@ -621,16 +732,14 @@ mod tests { data: vec![0; 1], }; let last = QUOTES.len() - 1; - let job = encode(&bitmap, &Head::default(), 2, STAMP, last); + let job = encode(&bitmap, &Head::default(), 2, STAMP, last, 0); assert!(contains_line(&job[0], EVENT_TITLE) && contains_line(&job[0], EVENT_PLACE)); assert!(contains_line(&job[2], KEEPSAKE_DE) && contains_line(&job[2], KEEPSAKE_EN)); assert!(contains_line(&job[2], STAMP)); // Consecutive copies get consecutive quotes, wrapping round the list. assert!(QUOTES[last].iter().all(|line| contains_line(&job[2], line))); - assert!(QUOTES[0].iter().all(|line| contains_line(&job[5], line))); - assert!( - job[2].ends_with(&footer(&Head::default(), STAMP, QUOTES[last])[1..]) - ); + assert!(QUOTES[0].iter().all(|line| contains_line(&job[7], line))); + assert!(job[2].ends_with(&footer(&Head::default(), STAMP, QUOTES[last])[1..])); // The real stamp is as wide as the one used here. let now = Local::now().format(STAMP_FORMAT).to_string(); assert!(now.is_ascii() && now.len() == STAMP.len(), "{now}"); @@ -641,9 +750,3 @@ mod tests { assert_eq!(cuts, 2); } } - - - - - - -- 2.49.1 From 67aa0e64c1011784b5222cf250538f840562b80d Mon Sep 17 00:00:00 2001 From: bankosegger Date: Wed, 18 Nov 2026 17:43:06 +0100 Subject: [PATCH 2/5] feat: replace the sprite with a full-width pixel strip that thins out The strip is four lines of 12-dot pixels across the paper: the first line is solid and each line below it has fewer pixels in random places. Co-Authored-By: Claude Sonnet 5.5 --- src/artwork.rs | 90 +++++++++++++++++++++++++++++++------------------- src/printer.rs | 75 +++++++++++++++++++++-------------------- 2 files changed, 95 insertions(+), 70 deletions(-) diff --git a/src/artwork.rs b/src/artwork.rs index 93f303b..3caac17 100644 --- a/src/artwork.rs +++ b/src/artwork.rs @@ -1,30 +1,36 @@ -//! A small random pixel-art sprite for the bottom of every printed slip. +//! A strip of random pixel art for the bottom of every printed slip. //! -//! The sprite is a few chunky cells high and mirrored left to right, which -//! makes random bits read as a little creature or emblem instead of noise. +//! The first line is solid; every line below it has fewer pixels, so the +//! strip dissolves towards the bottom edge of the slip. -pub const COLUMNS: usize = 8; +/// Lines of pixels in the strip. pub const ROWS: usize = 4; -const HALF: usize = COLUMNS / 2; -/// How many of the 16 cells of the left half may be filled: enough to read as -/// a shape, not so many that it turns into a block. -const FILLED: std::ops::RangeInclusive = 6..=11; +/// Pixels across the paper that the strip aims for; the printer picks the +/// pixel size that comes closest (12 dots on 80 mm paper, 8 on 58 mm). +pub const CELLS_ACROSS: usize = 48; +/// Percent of the pixels that are set in each line, from the solid one down. +const DENSITY: [usize; ROWS] = [100, 65, 35, 12]; -pub type Sprite = [[bool; COLUMNS]; ROWS]; - -/// The sprite for `seed`; the same seed always gives the same sprite. -pub fn sprite(seed: u64) -> Sprite { +/// The pixels of each line for `seed`; the same seed always gives the same +/// strip. Every line has exactly `columns * DENSITY / 100` pixels set, in +/// random places. +pub fn pattern(seed: u64, columns: usize) -> [Vec; ROWS] { let mut state = seed; - loop { - let bits = next(&mut state) & 0xFFFF; - let row = |index: usize| (bits >> (index * HALF)) & 0xF; - if !FILLED.contains(&bits.count_ones()) || (0..ROWS).any(|index| row(index) == 0) { - continue; + std::array::from_fn(|row| { + let filled = columns * DENSITY[row] / 100; + // Partial Fisher-Yates shuffle: the first `filled` entries are a + // uniform random choice of columns. + let mut order: Vec = (0..columns).collect(); + for index in 0..filled { + let other = index + (next(&mut state) % (columns - index) as u64) as usize; + order.swap(index, other); } - return std::array::from_fn(|y| { - std::array::from_fn(|x| row(y) >> x.min(COLUMNS - 1 - x) & 1 == 1) - }); - } + let mut line = vec![false; columns]; + for &column in &order[..filled] { + line[column] = true; + } + line + }) } /// SplitMix64: a few lines, well mixed, and good enough for decoration. @@ -41,25 +47,41 @@ mod tests { use super::*; #[test] - fn sprites_are_mirrored_filled_in_every_row_and_not_a_block() { - for seed in 0..2000 { - let sprite = sprite(seed); - let filled = sprite.iter().flatten().filter(|cell| **cell).count(); - assert!((12..=22).contains(&filled), "seed {seed}: {filled} cells"); - for row in sprite { - assert!(row.iter().any(|cell| *cell), "seed {seed}: empty row"); + fn the_first_line_is_solid_and_each_line_is_sparser() { + for columns in [8, 16, 48, 50] { + for seed in 0..200 { + let lines = pattern(seed, columns); + let counts: Vec = lines + .iter() + .map(|line| line.iter().filter(|cell| **cell).count()) + .collect(); + assert_eq!(counts[0], columns, "{columns} columns, seed {seed}"); assert!( - (0..COLUMNS).all(|x| row[x] == row[COLUMNS - 1 - x]), - "seed {seed}: not mirrored" + counts.windows(2).all(|pair| pair[0] > pair[1]), + "{columns} columns, seed {seed}: {counts:?}" ); + assert!(lines.iter().all(|line| line.len() == columns)); } } } #[test] - fn a_seed_gives_one_sprite_and_seeds_give_many() { - assert_eq!(sprite(7), sprite(7)); - let distinct: std::collections::HashSet = (0..1000).map(sprite).collect(); - assert!(distinct.len() > 200, "{} sprites", distinct.len()); + fn a_seed_gives_one_pattern_and_seeds_give_many() { + assert_eq!(pattern(7, 48), pattern(7, 48)); + let distinct: std::collections::HashSet<_> = + (0..1000).map(|seed| pattern(seed, 48)).collect(); + assert_eq!(distinct.len(), 1000); + } + + #[test] + fn sparse_pixels_land_everywhere_across_the_strip() { + // Not clumped on one side: over many seeds each column gets used. + let mut seen = [false; 48]; + for seed in 0..200 { + for (column, set) in pattern(seed, 48)[3].iter().enumerate() { + seen[column] |= *set; + } + } + assert!(seen.iter().all(|used| *used)); } } diff --git a/src/printer.rs b/src/printer.rs index e0be07c..aae1621 100644 --- a/src/printer.rs +++ b/src/printer.rs @@ -26,7 +26,7 @@ //! Each photo is captioned with the event name and place above it, and a //! keepsake line, the capture date and time and one of `QUOTES` below it. The //! captions are in German with the English directly underneath, the quotes in -//! English only, then a small random pixel-art sprite (see `artwork`) closes +//! English only, then a strip of random pixel art (see `artwork`) closes //! the slip. The timestamp is the system //! clock in local time, so the booth's clock has to be right for it to mean //! anything. Text goes out in the printer's own code page (PC437), since it @@ -55,7 +55,7 @@ use opencv::{ }; use crate::{ - artwork::{self, COLUMNS, ROWS}, + artwork::{self, CELLS_ACROSS, ROWS}, quotes::QUOTES, }; @@ -365,7 +365,7 @@ fn encode( ) -> Vec> { let mut job = Vec::new(); for copy in 0..copies { - let sprite = sprite_strip(bitmap.width_bytes * 8, seed.wrapping_add(copy as u64)); + let strip = pixel_strip(bitmap.width_bytes * 8, seed.wrapping_add(copy as u64)); job.push(header(head)); raster_bands(&mut job, bitmap, head); job.push(footer( @@ -373,7 +373,7 @@ fn encode( stamp, "ES[(first_quote + copy) % QUOTES.len()], )); - raster_bands(&mut job, &sprite, head); + raster_bands(&mut job, &strip, head); job.push(finish(head)); } job @@ -393,17 +393,18 @@ fn raster_bands(job: &mut Vec>, bitmap: &Bitmap, head: &Head) { } } -/// The random sprite centred on a full-width strip, `ROWS` cells high, with -/// cells that grow with the paper width (18 dots on 80 mm, 12 on 58 mm). -fn sprite_strip(dots: usize, seed: u64) -> Bitmap { - let cell = (dots / 32).max(1); - let left = (dots - COLUMNS * cell) / 2; +/// The random pixel strip across the whole paper, `ROWS` lines of pixels that +/// get sparser downwards. Pixels are 12 dots on 80 mm paper and 8 on 58 mm. +fn pixel_strip(dots: usize, seed: u64) -> Bitmap { + let cell = (dots / CELLS_ACROSS).max(1); + let columns = dots / cell; + let left = (dots - columns * cell) / 2; let stride = dots / 8; - let sprite = artwork::sprite(seed); + let lines = artwork::pattern(seed, columns); let mut data = vec![0u8; stride * ROWS * cell]; for y in 0..ROWS * cell { - for x in 0..COLUMNS * cell { - if sprite[y / cell][x / cell] { + for x in 0..columns * cell { + if lines[y / cell][x / cell] { let dot = left + x; data[y * stride + dot / 8] |= 0x80 >> (dot % 8); } @@ -474,7 +475,7 @@ fn first_quote() -> usize { % QUOTES.len() } -/// Seed for the sprites of one job, from the clock like the quote. +/// Seed for the pixel strips of one job, from the clock like the quote. fn clock_seed() -> u64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) @@ -494,7 +495,7 @@ fn footer(head: &Head, stamp: &str, quote: &[&str]) -> Vec { for line in quote { text_line(&mut write, line); } - write.extend([0x1B, b'd', 1]); // a blank line between the quote and the sprite + write.extend([0x1B, b'd', 1]); // a blank line between the quote and the pixel strip write } @@ -664,7 +665,7 @@ mod tests { }; let job = encode(&bitmap, &Head::default(), 2, STAMP, 0, 0); // Per copy: the caption, a full band, the leftover row, the footer, the - // sprite and the cut. + // pixel strip and the cut. assert_eq!(job.len(), 2 * 6); for copy in job.chunks(6) { assert_eq!( @@ -686,43 +687,45 @@ mod tests { } #[test] - fn closes_each_slip_with_a_centred_sprite_before_the_cut() { + fn closes_each_slip_with_a_fading_pixel_strip_before_the_cut() { for dots in [384, 576] { - let strip = sprite_strip(dots, 42); - let cell = dots / 32; + let strip = pixel_strip(dots, 42); + let cell = dots / CELLS_ACROSS; assert_eq!(strip.width_bytes, dots / 8); assert_eq!(strip.data.len(), dots / 8 * ROWS * cell); let lit = |row: usize, dot: usize| { strip.data[row * strip.width_bytes + dot / 8] & (0x80 >> (dot % 8)) != 0 }; - // Mirrored about the centre of the paper, nothing outside the sprite. - let margin = (dots - COLUMNS * cell) / 2; - for row in 0..ROWS * cell { - for dot in 0..dots { - assert_eq!( - lit(row, dot), - lit(row, dots - 1 - dot), - "{dots} {row} {dot}" - ); - if !(margin..dots - margin).contains(&dot) { - assert!(!lit(row, dot), "{dots} {row} {dot}"); + // The first line of pixels spans the paper; later ones thin out. + let counts: Vec = (0..ROWS) + .map(|line| (0..dots).filter(|dot| lit(line * cell, *dot)).count()) + .collect(); + assert_eq!(counts[0], dots); + assert!( + counts.windows(2).all(|pair| pair[0] > pair[1]), + "{counts:?}" + ); + // Pixels are solid squares: every dot row of a line is the same. + for line in 0..ROWS { + for dot_row in 1..cell { + for dot in 0..dots { + assert_eq!(lit(line * cell, dot), lit(line * cell + dot_row, dot)); } } } - assert!(strip.data.iter().any(|byte| *byte != 0)); } - // After the footer come the sprite bands (72 rows at 576 dots), then the cut. + // After the footer comes the strip (48 rows at 576 dots), then the cut. let bitmap = Bitmap { width_bytes: 72, data: vec![0; 72], }; let job = encode(&bitmap, &Head::default(), 1, STAMP, 0, 5); - assert_eq!(job.len(), 6); // caption, photo, footer, 2 sprite bands, cut - assert!(job[3].starts_with(&[0x1B, b'@', 0x1D, b'v', b'0', 0, 72, 0, BAND_ROWS as u8, 0])); - assert!(job[5].ends_with(&[0x1D, b'V', 66, 3])); - // Copies get different sprites. + assert_eq!(job.len(), 5); // caption, photo, footer, strip, cut + assert!(job[3].starts_with(&[0x1B, b'@', 0x1D, b'v', b'0', 0, 72, 0, 48, 0])); + assert!(job[4].ends_with(&[0x1D, b'V', 66, 3])); + // Copies get different strips. let two = encode(&bitmap, &Head::default(), 2, STAMP, 0, 5); - assert_ne!(two[3], two[9]); + assert_ne!(two[3], two[8]); } #[test] -- 2.49.1 From 4a3149bab300d61dc7382e5a7d38af5a03b9a996 Mon Sep 17 00:00:00 2001 From: bankosegger Date: Wed, 18 Nov 2026 17:44:46 +0100 Subject: [PATCH 3/5] feat: frame the photo with pixel strips above and below The solid line of each strip sits next to the photo and the pixels thin out away from it; the strip at the bottom of the slip is gone. Co-Authored-By: Claude Sonnet 5.5 --- src/printer.rs | 128 +++++++++++++++++++++++++++++-------------------- 1 file changed, 77 insertions(+), 51 deletions(-) diff --git a/src/printer.rs b/src/printer.rs index aae1621..5ac9219 100644 --- a/src/printer.rs +++ b/src/printer.rs @@ -26,9 +26,9 @@ //! Each photo is captioned with the event name and place above it, and a //! keepsake line, the capture date and time and one of `QUOTES` below it. The //! captions are in German with the English directly underneath, the quotes in -//! English only, then a strip of random pixel art (see `artwork`) closes -//! the slip. The timestamp is the system -//! clock in local time, so the booth's clock has to be right for it to mean +//! English only. A strip of random pixel art (see `artwork`) frames the photo +//! above and below, solid next to it and thinning out away from it. The +//! timestamp is the system clock in local time, so the booth's clock has to be right for it to mean //! anything. Text goes out in the printer's own code page (PC437), since it //! prints UTF-8 bytes as separate glyphs; see `code_page`. //! @@ -365,15 +365,22 @@ fn encode( ) -> Vec> { let mut job = Vec::new(); for copy in 0..copies { - let strip = pixel_strip(bitmap.width_bytes * 8, seed.wrapping_add(copy as u64)); + // Two different strips frame the photo, each solid next to it. + let dots = bitmap.width_bytes * 8; + let seed = seed.wrapping_add(2 * copy as u64); job.push(header(head)); + raster_bands(&mut job, &pixel_strip(dots, seed, true), head); raster_bands(&mut job, bitmap, head); + raster_bands( + &mut job, + &pixel_strip(dots, seed.wrapping_add(1), false), + head, + ); job.push(footer( head, stamp, "ES[(first_quote + copy) % QUOTES.len()], )); - raster_bands(&mut job, &strip, head); job.push(finish(head)); } job @@ -393,9 +400,11 @@ fn raster_bands(job: &mut Vec>, bitmap: &Bitmap, head: &Head) { } } -/// The random pixel strip across the whole paper, `ROWS` lines of pixels that -/// get sparser downwards. Pixels are 12 dots on 80 mm paper and 8 on 58 mm. -fn pixel_strip(dots: usize, seed: u64) -> Bitmap { +/// The random pixel strip across the whole paper: `ROWS` lines of pixels that +/// get sparser downwards, or upwards when `solid_last`, so that the solid line +/// can sit next to the photo on either side. Pixels are 12 dots on 80 mm paper +/// and 8 on 58 mm. +fn pixel_strip(dots: usize, seed: u64, solid_last: bool) -> Bitmap { let cell = (dots / CELLS_ACROSS).max(1); let columns = dots / cell; let left = (dots - columns * cell) / 2; @@ -404,7 +413,12 @@ fn pixel_strip(dots: usize, seed: u64) -> Bitmap { let mut data = vec![0u8; stride * ROWS * cell]; for y in 0..ROWS * cell { for x in 0..columns * cell { - if lines[y / cell][x / cell] { + let line = if solid_last { + ROWS - 1 - y / cell + } else { + y / cell + }; + if lines[line][x / cell] { let dot = left + x; data[y * stride + dot / 8] |= 0x80 >> (dot % 8); } @@ -495,7 +509,6 @@ fn footer(head: &Head, stamp: &str, quote: &[&str]) -> Vec { for line in quote { text_line(&mut write, line); } - write.extend([0x1B, b'd', 1]); // a blank line between the quote and the pixel strip write } @@ -622,7 +635,8 @@ mod tests { }; let head = Head::from_values(Some("85"), Some("quality")); let job = encode(&bitmap, &head, 1, STAMP, 0, 0); - for band in &job[1..3] { + // Strip, the two photo bands and the other strip. + for band in &job[1..5] { assert_eq!( &band[..12], [ @@ -664,17 +678,17 @@ mod tests { data: vec![0xAA; 2 * (BAND_ROWS + 1)], }; let job = encode(&bitmap, &Head::default(), 2, STAMP, 0, 0); - // Per copy: the caption, a full band, the leftover row, the footer, the - // pixel strip and the cut. - assert_eq!(job.len(), 2 * 6); - for copy in job.chunks(6) { + // Per copy: the caption, a pixel strip, the photo's full band and + // leftover row, a pixel strip, the footer and the cut. + assert_eq!(job.len(), 2 * 7); + for copy in job.chunks(7) { assert_eq!( - ©[1][..10], + ©[2][..10], [0x1B, b'@', 0x1D, b'v', b'0', 0, 2, 0, BAND_ROWS as u8, 0] ); - assert_eq!(copy[1].len(), 10 + 2 * BAND_ROWS); + assert_eq!(copy[2].len(), 10 + 2 * BAND_ROWS); assert_eq!( - copy[2], + copy[3], [ vec![0x1B, b'@', 0x1D, b'v', b'0', 0, 2, 0, 1, 0], vec![0xAA; 2] @@ -687,45 +701,57 @@ mod tests { } #[test] - fn closes_each_slip_with_a_fading_pixel_strip_before_the_cut() { + fn frames_the_photo_with_pixel_strips_that_thin_out_away_from_it() { for dots in [384, 576] { - let strip = pixel_strip(dots, 42); let cell = dots / CELLS_ACROSS; - assert_eq!(strip.width_bytes, dots / 8); - assert_eq!(strip.data.len(), dots / 8 * ROWS * cell); - let lit = |row: usize, dot: usize| { - strip.data[row * strip.width_bytes + dot / 8] & (0x80 >> (dot % 8)) != 0 - }; - // The first line of pixels spans the paper; later ones thin out. - let counts: Vec = (0..ROWS) - .map(|line| (0..dots).filter(|dot| lit(line * cell, *dot)).count()) - .collect(); - assert_eq!(counts[0], dots); - assert!( - counts.windows(2).all(|pair| pair[0] > pair[1]), - "{counts:?}" - ); - // Pixels are solid squares: every dot row of a line is the same. - for line in 0..ROWS { - for dot_row in 1..cell { - for dot in 0..dots { - assert_eq!(lit(line * cell, dot), lit(line * cell + dot_row, dot)); + for solid_last in [false, true] { + let strip = pixel_strip(dots, 42, solid_last); + assert_eq!(strip.width_bytes, dots / 8); + assert_eq!(strip.data.len(), dots / 8 * ROWS * cell); + let lit = |row: usize, dot: usize| { + strip.data[row * strip.width_bytes + dot / 8] & (0x80 >> (dot % 8)) != 0 + }; + // Dots lit in each line of pixels, from top to bottom. + let mut counts: Vec = (0..ROWS) + .map(|line| (0..dots).filter(|dot| lit(line * cell, *dot)).count()) + .collect(); + if solid_last { + counts.reverse(); + } + // The line next to the photo spans the paper; the others thin out. + assert_eq!(counts[0], dots); + assert!( + counts.windows(2).all(|pair| pair[0] > pair[1]), + "{counts:?}" + ); + // Pixels are solid squares: every dot row of a line is the same. + for line in 0..ROWS { + for dot_row in 1..cell { + for dot in 0..dots { + assert_eq!(lit(line * cell, dot), lit(line * cell + dot_row, dot)); + } } } } } - // After the footer comes the strip (48 rows at 576 dots), then the cut. + // Caption, strip, photo, strip, footer, cut: the strips are 48 rows at + // 576 dots and enclose the photo's single row. let bitmap = Bitmap { width_bytes: 72, - data: vec![0; 72], + data: vec![0xFF; 72], }; let job = encode(&bitmap, &Head::default(), 1, STAMP, 0, 5); - assert_eq!(job.len(), 5); // caption, photo, footer, strip, cut - assert!(job[3].starts_with(&[0x1B, b'@', 0x1D, b'v', b'0', 0, 72, 0, 48, 0])); - assert!(job[4].ends_with(&[0x1D, b'V', 66, 3])); - // Copies get different strips. + assert_eq!(job.len(), 6); + let raster = |rows: u8| [0x1B, b'@', 0x1D, b'v', b'0', 0, 72, 0, rows, 0]; + assert!(job[1].starts_with(&raster(48)) && job[3].starts_with(&raster(48))); + assert_eq!(&job[2][..10], raster(1)); + assert!(job[5].ends_with(&[0x1D, b'V', 66, 3])); + // Nothing is printed after the quote but the feed and the cut. + assert!(job[4].windows(2).all(|pair| pair != [0x1D, b'v'])); + // The two strips differ, and so do those of the next copy. let two = encode(&bitmap, &Head::default(), 2, STAMP, 0, 5); - assert_ne!(two[3], two[8]); + assert_ne!(two[1], two[3]); + assert_ne!(two[1], two[7]); } #[test] @@ -737,12 +763,12 @@ mod tests { let last = QUOTES.len() - 1; let job = encode(&bitmap, &Head::default(), 2, STAMP, last, 0); assert!(contains_line(&job[0], EVENT_TITLE) && contains_line(&job[0], EVENT_PLACE)); - assert!(contains_line(&job[2], KEEPSAKE_DE) && contains_line(&job[2], KEEPSAKE_EN)); - assert!(contains_line(&job[2], STAMP)); + assert!(contains_line(&job[4], KEEPSAKE_DE) && contains_line(&job[4], KEEPSAKE_EN)); + assert!(contains_line(&job[4], STAMP)); // Consecutive copies get consecutive quotes, wrapping round the list. - assert!(QUOTES[last].iter().all(|line| contains_line(&job[2], line))); - assert!(QUOTES[0].iter().all(|line| contains_line(&job[7], line))); - assert!(job[2].ends_with(&footer(&Head::default(), STAMP, QUOTES[last])[1..])); + assert!(QUOTES[last].iter().all(|line| contains_line(&job[4], line))); + assert!(QUOTES[0].iter().all(|line| contains_line(&job[10], line))); + assert!(job[4].ends_with(&footer(&Head::default(), STAMP, QUOTES[last])[1..])); // The real stamp is as wide as the one used here. let now = Local::now().format(STAMP_FORMAT).to_string(); assert!(now.is_ascii() && now.len() == STAMP.len(), "{now}"); -- 2.49.1 From 34f5914bb15f36d4d7590bbe4b39dae13dbcf21a Mon Sep 17 00:00:00 2001 From: bankosegger Date: Wed, 18 Nov 2026 17:48:16 +0100 Subject: [PATCH 4/5] feat: draw snowy fir trees above the photo and icicles below it Replaces the random pixel noise with Christmas scenery: snow next to the photo, small trees and flakes on top, icicles hanging underneath. Co-Authored-By: Claude Sonnet 5.5 --- src/artwork.rs | 185 +++++++++++++++++++++++++++++++++++-------------- src/printer.rs | 58 ++++++++++------ 2 files changed, 168 insertions(+), 75 deletions(-) diff --git a/src/artwork.rs b/src/artwork.rs index 3caac17..c83d215 100644 --- a/src/artwork.rs +++ b/src/artwork.rs @@ -1,36 +1,80 @@ -//! A strip of random pixel art for the bottom of every printed slip. +//! Christmas pixel art that frames the photo on every printed slip. //! -//! The first line is solid; every line below it has fewer pixels, so the -//! strip dissolves towards the bottom edge of the slip. +//! Both strips are a few lines of pixels. The first line, the snow next to the +//! photo, is solid; the pixels above it thin out away from the photo. Lines +//! are ordered from the photo outward, so index 0 is always the solid one. -/// Lines of pixels in the strip. +/// Lines of pixels in a strip. pub const ROWS: usize = 4; -/// Pixels across the paper that the strip aims for; the printer picks the -/// pixel size that comes closest (12 dots on 80 mm paper, 8 on 58 mm). +/// Pixels across the paper that a strip aims for; the printer picks the pixel +/// size that comes closest (12 dots on 80 mm paper, 8 on 58 mm). pub const CELLS_ACROSS: usize = 48; -/// Percent of the pixels that are set in each line, from the solid one down. -const DENSITY: [usize; ROWS] = [100, 65, 35, 12]; -/// The pixels of each line for `seed`; the same seed always gives the same -/// strip. Every line has exactly `columns * DENSITY / 100` pixels set, in -/// random places. -pub fn pattern(seed: u64, columns: usize) -> [Vec; ROWS] { +pub type Lines = [Vec; ROWS]; + +/// Snow with small fir trees standing on it and a few snowflakes in between, +/// for the strip above the photo. +/// +/// Trees are 3 or 5 pixels wide at the base and narrow by two pixels per line +/// to a single tip, so they are 2 or 3 lines high. +pub fn trees(seed: u64, columns: usize) -> Lines { let mut state = seed; - std::array::from_fn(|row| { - let filled = columns * DENSITY[row] / 100; - // Partial Fisher-Yates shuffle: the first `filled` entries are a - // uniform random choice of columns. - let mut order: Vec = (0..columns).collect(); - for index in 0..filled { - let other = index + (next(&mut state) % (columns - index) as u64) as usize; - order.swap(index, other); + let mut lines = snow(columns); + let mut left = (next(&mut state) % 4) as usize; + loop { + let base = if chance(&mut state, 50) { 5 } else { 3 }; + if left + base > columns { + break; } - let mut line = vec![false; columns]; - for &column in &order[..filled] { - line[column] = true; + for (line, cells) in lines.iter_mut().enumerate().skip(1) { + let Some(width) = (base + 2).checked_sub(2 * line).filter(|width| *width > 0) else { + continue; + }; + let start = left + (base - width) / 2; + cells[start..start + width].fill(true); } - line - }) + left += base + 1 + (next(&mut state) % 4) as usize; + } + for cells in lines.iter_mut().skip(1) { + for cell in cells.iter_mut().filter(|cell| !**cell) { + *cell = chance(&mut state, 4); + } + } + lines +} + +/// Snow with icicles hanging from it, for the strip below the photo. +/// +/// Icicles are one pixel wide and 1 to 3 pixels long, never side by side, so +/// the longer ones are rarer and the strip thins out downwards. +pub fn icicles(seed: u64, columns: usize) -> Lines { + let mut state = seed; + let mut lines = snow(columns); + let mut hanging = false; + for column in 0..columns { + if std::mem::take(&mut hanging) || !chance(&mut state, 55) { + continue; + } + let length = match next(&mut state) % 10 { + 0..=4 => 1, + 5..=7 => 2, + _ => 3, + }; + for cells in &mut lines[1..=length] { + cells[column] = true; + } + hanging = true; + } + lines +} + +/// The solid first line and nothing above it yet. +fn snow(columns: usize) -> Lines { + std::array::from_fn(|line| vec![line == 0; columns]) +} + +fn chance(state: &mut u64, percent: u64) -> bool { + next(state) % 100 < percent } /// SplitMix64: a few lines, well mixed, and good enough for decoration. @@ -46,42 +90,79 @@ fn next(state: &mut u64) -> u64 { mod tests { use super::*; + const WIDTHS: [usize; 4] = [8, 16, 48, 50]; + + fn count(cells: &[bool]) -> usize { + cells.iter().filter(|cell| **cell).count() + } + + /// Longest run of set pixels in one line. + fn longest_run(cells: &[bool]) -> usize { + cells + .split(|cell| !cell) + .map(<[bool]>::len) + .max() + .unwrap_or(0) + } + #[test] - fn the_first_line_is_solid_and_each_line_is_sparser() { - for columns in [8, 16, 48, 50] { + fn snow_is_solid_and_the_strips_have_the_right_size() { + for columns in WIDTHS { for seed in 0..200 { - let lines = pattern(seed, columns); - let counts: Vec = lines - .iter() - .map(|line| line.iter().filter(|cell| **cell).count()) - .collect(); - assert_eq!(counts[0], columns, "{columns} columns, seed {seed}"); - assert!( - counts.windows(2).all(|pair| pair[0] > pair[1]), - "{columns} columns, seed {seed}: {counts:?}" - ); - assert!(lines.iter().all(|line| line.len() == columns)); + for lines in [trees(seed, columns), icicles(seed, columns)] { + assert_eq!(count(&lines[0]), columns, "{columns} columns, seed {seed}"); + assert!(lines.iter().all(|line| line.len() == columns)); + } } } } #[test] - fn a_seed_gives_one_pattern_and_seeds_give_many() { - assert_eq!(pattern(7, 48), pattern(7, 48)); - let distinct: std::collections::HashSet<_> = - (0..1000).map(|seed| pattern(seed, 48)).collect(); - assert_eq!(distinct.len(), 1000); - } - - #[test] - fn sparse_pixels_land_everywhere_across_the_strip() { - // Not clumped on one side: over many seeds each column gets used. - let mut seen = [false; 48]; + fn trees_have_a_base_and_thin_out_upwards() { for seed in 0..200 { - for (column, set) in pattern(seed, 48)[3].iter().enumerate() { - seen[column] |= *set; + let lines = trees(seed, 48); + // Every strip has trees: runs of at least three pixels on line 1. + assert!(longest_run(&lines[1]) >= 3, "seed {seed}"); + // Each tree line is sparser than the one below it, on the whole. + assert!(count(&lines[1]) < 48, "seed {seed}"); + assert!(count(&lines[1]) > count(&lines[3]), "seed {seed}"); + } + } + + #[test] + fn icicles_hang_from_the_snow_apart_and_thin_out_downwards() { + let mut longest = 0; + for columns in WIDTHS { + for seed in 0..200 { + let lines = icicles(seed, columns); + for column in 0..columns { + for line in 1..ROWS { + // Hanging, not floating. + assert!(!lines[line][column] || lines[line - 1][column]); + } + if column > 0 { + assert!(!(lines[1][column] && lines[1][column - 1])); + } + } + assert!(count(&lines[1]) >= count(&lines[2])); + assert!(count(&lines[2]) >= count(&lines[3])); + longest = longest.max(count(&lines[3])); } } - assert!(seen.iter().all(|used| *used)); + assert!(longest > 0, "no icicle ever reaches the third line"); + } + + #[test] + fn a_seed_gives_one_picture_and_seeds_give_many() { + assert_eq!(trees(7, 48), trees(7, 48)); + assert_eq!(icicles(7, 48), icicles(7, 48)); + let distinct = |picture: fn(u64, usize) -> Lines| { + (0..1000) + .map(|seed| picture(seed, 48)) + .collect::>() + .len() + }; + assert_eq!(distinct(trees), 1000); + assert_eq!(distinct(icicles), 1000); } } diff --git a/src/printer.rs b/src/printer.rs index 5ac9219..8c636e2 100644 --- a/src/printer.rs +++ b/src/printer.rs @@ -26,10 +26,10 @@ //! Each photo is captioned with the event name and place above it, and a //! keepsake line, the capture date and time and one of `QUOTES` below it. The //! captions are in German with the English directly underneath, the quotes in -//! English only. A strip of random pixel art (see `artwork`) frames the photo -//! above and below, solid next to it and thinning out away from it. The -//! timestamp is the system clock in local time, so the booth's clock has to be right for it to mean -//! anything. Text goes out in the printer's own code page (PC437), since it +//! English only. Christmas pixel art (see `artwork`) frames the photo: snow +//! with small fir trees above it and snow with icicles below it, different on +//! every slip. The timestamp is the system clock in local time, so the +//! booth's clock has to be right for it to mean anything. Text goes out in the printer's own code page (PC437), since it //! prints UTF-8 bytes as separate glyphs; see `code_page`. //! //! Each photo is converted to gray, resized to the exact dot width, contrast @@ -365,15 +365,15 @@ fn encode( ) -> Vec> { let mut job = Vec::new(); for copy in 0..copies { - // Two different strips frame the photo, each solid next to it. + // Trees above the photo and icicles below it, new ones for every copy. let dots = bitmap.width_bytes * 8; let seed = seed.wrapping_add(2 * copy as u64); job.push(header(head)); - raster_bands(&mut job, &pixel_strip(dots, seed, true), head); + raster_bands(&mut job, &pixel_strip(dots, seed, Side::Above), head); raster_bands(&mut job, bitmap, head); raster_bands( &mut job, - &pixel_strip(dots, seed.wrapping_add(1), false), + &pixel_strip(dots, seed.wrapping_add(1), Side::Below), head, ); job.push(footer( @@ -400,23 +400,34 @@ fn raster_bands(job: &mut Vec>, bitmap: &Bitmap, head: &Head) { } } -/// The random pixel strip across the whole paper: `ROWS` lines of pixels that -/// get sparser downwards, or upwards when `solid_last`, so that the solid line -/// can sit next to the photo on either side. Pixels are 12 dots on 80 mm paper -/// and 8 on 58 mm. -fn pixel_strip(dots: usize, seed: u64, solid_last: bool) -> Bitmap { +/// Which side of the photo a pixel strip goes on. +#[derive(Clone, Copy)] +enum Side { + /// Snow with trees standing on it, so the snow is the strip's bottom line. + Above, + /// Snow with icicles hanging from it, so the snow is the strip's top line. + Below, +} + +/// The random Christmas pixel strip across the whole paper, `ROWS` lines of +/// pixels with the solid snow next to the photo. Pixels are 12 dots on 80 mm +/// paper and 8 on 58 mm. +fn pixel_strip(dots: usize, seed: u64, side: Side) -> Bitmap { let cell = (dots / CELLS_ACROSS).max(1); let columns = dots / cell; let left = (dots - columns * cell) / 2; let stride = dots / 8; - let lines = artwork::pattern(seed, columns); + let lines = match side { + Side::Above => artwork::trees(seed, columns), + Side::Below => artwork::icicles(seed, columns), + }; let mut data = vec![0u8; stride * ROWS * cell]; for y in 0..ROWS * cell { for x in 0..columns * cell { - let line = if solid_last { - ROWS - 1 - y / cell - } else { - y / cell + // Lines are numbered from the photo outward. + let line = match side { + Side::Above => ROWS - 1 - y / cell, + Side::Below => y / cell, }; if lines[line][x / cell] { let dot = left + x; @@ -701,11 +712,11 @@ mod tests { } #[test] - fn frames_the_photo_with_pixel_strips_that_thin_out_away_from_it() { + fn frames_the_photo_with_snow_trees_and_icicles() { for dots in [384, 576] { let cell = dots / CELLS_ACROSS; - for solid_last in [false, true] { - let strip = pixel_strip(dots, 42, solid_last); + for side in [Side::Above, Side::Below] { + let strip = pixel_strip(dots, 42, side); assert_eq!(strip.width_bytes, dots / 8); assert_eq!(strip.data.len(), dots / 8 * ROWS * cell); let lit = |row: usize, dot: usize| { @@ -715,13 +726,14 @@ mod tests { let mut counts: Vec = (0..ROWS) .map(|line| (0..dots).filter(|dot| lit(line * cell, *dot)).count()) .collect(); - if solid_last { + if matches!(side, Side::Above) { counts.reverse(); } - // The line next to the photo spans the paper; the others thin out. + // The snow next to the photo spans the paper; what is on it + // does not, and is there. assert_eq!(counts[0], dots); assert!( - counts.windows(2).all(|pair| pair[0] > pair[1]), + counts[1..].iter().all(|count| (1..dots).contains(count)), "{counts:?}" ); // Pixels are solid squares: every dot row of a line is the same. -- 2.49.1 From b8c4ada06a1f4bb59ca4f7d051bad08bb1aa35f7 Mon Sep 17 00:00:00 2001 From: bankosegger Date: Wed, 18 Nov 2026 17:53:45 +0100 Subject: [PATCH 5/5] feat: frame the photo with Christmas trees, presents and ornaments Trees with stars, presents and falling snow stand on a line of snow above the photo; baubles, stars, bells and snowflakes hang below it. Pixels shrink to 6 dots so the motifs are recognisable at the same height. Co-Authored-By: Claude Opus 5.5 --- src/artwork.rs | 323 +++++++++++++++++++++++++++++++++++-------------- src/printer.rs | 69 +++++------ 2 files changed, 266 insertions(+), 126 deletions(-) diff --git a/src/artwork.rs b/src/artwork.rs index c83d215..8333c30 100644 --- a/src/artwork.rs +++ b/src/artwork.rs @@ -1,76 +1,177 @@ //! Christmas pixel art that frames the photo on every printed slip. //! -//! Both strips are a few lines of pixels. The first line, the snow next to the -//! photo, is solid; the pixels above it thin out away from the photo. Lines -//! are ordered from the photo outward, so index 0 is always the solid one. +//! Above the photo stands a snowy scene of fir trees and presents under +//! falling snow; below it hang Christmas ornaments on strings of different +//! lengths. Both strips are solid next to the photo and thin out away from it, +//! and the motifs are arranged at random, so every slip gets its own. /// Lines of pixels in a strip. -pub const ROWS: usize = 4; +pub const ROWS: usize = 12; /// Pixels across the paper that a strip aims for; the printer picks the pixel -/// size that comes closest (12 dots on 80 mm paper, 8 on 58 mm). -pub const CELLS_ACROSS: usize = 48; +/// size that comes closest (6 dots on 80 mm paper, 4 on 58 mm). +pub const CELLS_ACROSS: usize = 96; +/// A strip's pixels, line by line from top to bottom as printed. pub type Lines = [Vec; ROWS]; -/// Snow with small fir trees standing on it and a few snowflakes in between, -/// for the strip above the photo. -/// -/// Trees are 3 or 5 pixels wide at the base and narrow by two pixels per line -/// to a single tip, so they are 2 or 3 lines high. -pub fn trees(seed: u64, columns: usize) -> Lines { +/// Hand-drawn motif, `#` for a black pixel; every row is equally wide. +type Sprite = &'static [&'static str]; + +/// Fir tree with a star on top, a trunk and two baubles left blank. +const BIG_TREE: Sprite = &[ + ".....#.....", + "....###....", + ".....#.....", + "....###....", + "...#####...", + "....###....", + "...##.##...", + "..#######..", + ".#########.", + "####.######", + "....###....", +]; +const SMALL_TREE: Sprite = &[ + "...#...", // + "..###..", "...#...", "..###..", ".##.##.", "..###..", ".#####.", "#######", "...#...", +]; +/// Present with a bow and a ribbon left blank. +const PRESENT: Sprite = &[ + ".##.##.", // + "...#...", "#######", "###.###", "###.###", "###.###", +]; +const SMALL_PRESENT: Sprite = &[ + ".#.#.", // + "..#..", "#####", "##.##", "##.##", +]; +/// Round bauble with its cap and a highlight. +const BAUBLE: Sprite = &[ + "...#...", // + "..###..", ".#####.", "##.####", "#######", ".#####.", "..###..", +]; +const STAR: Sprite = &[ + "...#...", // + "..###..", "#######", ".#####.", "..###..", ".##.##.", "##...##", +]; +const BELL: Sprite = &[ + "...#...", // + "..###..", ".#####.", ".#####.", ".#####.", "#######", "...#...", +]; +const SNOWFLAKE: Sprite = &[ + "#.#.#", // + ".###.", "#####", ".###.", "#.#.#", +]; +const FLAKE: Sprite = &["#"]; + +/// What stands on the snow above the photo, with how often each turns up. +const STANDING: [(Sprite, u64); 4] = [ + (BIG_TREE, 35), + (SMALL_TREE, 30), + (PRESENT, 20), + (SMALL_PRESENT, 15), +]; +/// What hangs below the photo; every one has its hook in the middle of its +/// top row. +const HANGING: [Sprite; 4] = [BAUBLE, STAR, BELL, SNOWFLAKE]; + +/// Trees and presents on a solid line of snow, the last line, with snow +/// falling in the free sky above them. +pub fn scenery(seed: u64, columns: usize) -> Lines { let mut state = seed; - let mut lines = snow(columns); + let mut lines = blank(columns); + lines[ROWS - 1].fill(true); let mut left = (next(&mut state) % 4) as usize; loop { - let base = if chance(&mut state, 50) { 5 } else { 3 }; - if left + base > columns { + let sprite = weighted(&mut state, &STANDING); + if left + width(sprite) > columns { break; } - for (line, cells) in lines.iter_mut().enumerate().skip(1) { - let Some(width) = (base + 2).checked_sub(2 * line).filter(|width| *width > 0) else { - continue; - }; - let start = left + (base - width) / 2; - cells[start..start + width].fill(true); - } - left += base + 1 + (next(&mut state) % 4) as usize; + stamp(&mut lines, sprite, left, ROWS - 1 - sprite.len()); + left += width(sprite) + 2 + (next(&mut state) % 5) as usize; } - for cells in lines.iter_mut().skip(1) { - for cell in cells.iter_mut().filter(|cell| !**cell) { - *cell = chance(&mut state, 4); + // Flakes keep a pixel of free space around them, so they never touch the + // trees, the presents, the snow or each other. + for top in 0..ROWS { + for left in 0..columns { + if chance(&mut state, 3) { + let flake = if chance(&mut state, 25) { + SNOWFLAKE + } else { + FLAKE + }; + if is_free(&lines, flake, left, top) { + stamp(&mut lines, flake, left, top); + } + } } } lines } -/// Snow with icicles hanging from it, for the strip below the photo. -/// -/// Icicles are one pixel wide and 1 to 3 pixels long, never side by side, so -/// the longer ones are rarer and the strip thins out downwards. -pub fn icicles(seed: u64, columns: usize) -> Lines { +/// Ornaments hanging on strings from a solid line, the first line. +pub fn ornaments(seed: u64, columns: usize) -> Lines { let mut state = seed; - let mut lines = snow(columns); - let mut hanging = false; - for column in 0..columns { - if std::mem::take(&mut hanging) || !chance(&mut state, 55) { - continue; + let mut lines = blank(columns); + lines[0].fill(true); + let mut left = (next(&mut state) % 4) as usize; + loop { + let sprite = HANGING[(next(&mut state) % HANGING.len() as u64) as usize]; + if left + width(sprite) > columns { + break; } - let length = match next(&mut state) % 10 { - 0..=4 => 1, - 5..=7 => 2, - _ => 3, - }; - for cells in &mut lines[1..=length] { - cells[column] = true; + // From one line of string up to as much as still fits. + let longest = ROWS - 1 - sprite.len(); + let string = 1 + (next(&mut state) % longest as u64) as usize; + for line in &mut lines[1..=string] { + line[left + width(sprite) / 2] = true; } - hanging = true; + stamp(&mut lines, sprite, left, 1 + string); + left += width(sprite) + 2 + (next(&mut state) % 4) as usize; } lines } -/// The solid first line and nothing above it yet. -fn snow(columns: usize) -> Lines { - std::array::from_fn(|line| vec![line == 0; columns]) +fn blank(columns: usize) -> Lines { + std::array::from_fn(|_| vec![false; columns]) +} + +fn width(sprite: Sprite) -> usize { + sprite[0].len() +} + +fn stamp(lines: &mut Lines, sprite: Sprite, left: usize, top: usize) { + for (row, pixels) in sprite.iter().enumerate() { + for (column, pixel) in pixels.bytes().enumerate() { + if pixel == b'#' { + lines[top + row][left + column] = true; + } + } + } +} + +/// Whether the sprite fits at this place with a free pixel all around it. +fn is_free(lines: &Lines, sprite: Sprite, left: usize, top: usize) -> bool { + let columns = lines[0].len(); + if top + sprite.len() > ROWS || left + width(sprite) > columns { + return false; + } + let rows = top.saturating_sub(1)..(top + sprite.len() + 1).min(ROWS); + let around = left.saturating_sub(1)..(left + width(sprite) + 1).min(columns); + lines[rows] + .iter() + .all(|line| line[around.clone()].iter().all(|pixel| !pixel)) +} + +fn weighted(state: &mut u64, choices: &[(Sprite, u64)]) -> Sprite { + let total: u64 = choices.iter().map(|(_, weight)| weight).sum(); + let mut roll = next(state) % total; + for &(sprite, weight) in choices { + if roll < weight { + return sprite; + } + roll -= weight; + } + unreachable!("the roll is below the total weight") } fn chance(state: &mut u64, percent: u64) -> bool { @@ -90,79 +191,121 @@ fn next(state: &mut u64) -> u64 { mod tests { use super::*; - const WIDTHS: [usize; 4] = [8, 16, 48, 50]; + const WIDTHS: [usize; 4] = [8, 16, 96, 100]; - fn count(cells: &[bool]) -> usize { - cells.iter().filter(|cell| **cell).count() + /// Sizes of the 8-connected groups of black pixels, with whether each one + /// reaches into `line`. + fn groups(lines: &Lines, line: usize) -> Vec<(usize, bool)> { + let columns = lines[0].len(); + let mut seen = vec![vec![false; columns]; ROWS]; + let mut found = Vec::new(); + for row in 0..ROWS { + for column in 0..columns { + if !lines[row][column] || seen[row][column] { + continue; + } + let (mut size, mut reaches) = (0, false); + let mut todo = vec![(row, column)]; + seen[row][column] = true; + while let Some((y, x)) = todo.pop() { + size += 1; + reaches |= y == line; + for ny in y.saturating_sub(1)..=(y + 1).min(ROWS - 1) { + for nx in x.saturating_sub(1)..=(x + 1).min(columns - 1) { + if lines[ny][nx] && !seen[ny][nx] { + seen[ny][nx] = true; + todo.push((ny, nx)); + } + } + } + } + found.push((size, reaches)); + } + } + found } - /// Longest run of set pixels in one line. - fn longest_run(cells: &[bool]) -> usize { - cells - .split(|cell| !cell) - .map(<[bool]>::len) - .max() - .unwrap_or(0) + fn pixels(sprite: Sprite) -> usize { + sprite.iter().map(|row| row.matches('#').count()).sum() } #[test] - fn snow_is_solid_and_the_strips_have_the_right_size() { + fn sprites_are_rectangular_and_fit_the_strip() { + let standing = STANDING.map(|(sprite, _)| sprite); + for sprite in standing.into_iter().chain(HANGING).chain([FLAKE]) { + assert!(sprite.iter().all(|row| row.len() == width(sprite))); + assert!( + sprite + .iter() + .all(|row| row.chars().all(|c| "#.".contains(c))) + ); + } + // Standing on the snow, with nothing above the tallest tree. + assert!(standing.iter().all(|sprite| sprite.len() < ROWS)); + // Hanging on at least one line of string, hooked in the middle. + for sprite in HANGING { + assert!(sprite.len() + 2 <= ROWS); + assert_eq!(sprite[0].as_bytes()[width(sprite) / 2], b'#'); + } + } + + #[test] + fn the_line_next_to_the_photo_is_solid() { for columns in WIDTHS { for seed in 0..200 { - for lines in [trees(seed, columns), icicles(seed, columns)] { - assert_eq!(count(&lines[0]), columns, "{columns} columns, seed {seed}"); - assert!(lines.iter().all(|line| line.len() == columns)); - } + let above = scenery(seed, columns); + let below = ornaments(seed, columns); + assert!(above[ROWS - 1].iter().all(|pixel| *pixel)); + assert!(below[0].iter().all(|pixel| *pixel)); + assert!(above.iter().chain(&below).all(|line| line.len() == columns)); } } } #[test] - fn trees_have_a_base_and_thin_out_upwards() { + fn trees_and_presents_stand_on_the_snow_and_only_flakes_float() { for seed in 0..200 { - let lines = trees(seed, 48); - // Every strip has trees: runs of at least three pixels on line 1. - assert!(longest_run(&lines[1]) >= 3, "seed {seed}"); - // Each tree line is sparser than the one below it, on the whole. - assert!(count(&lines[1]) < 48, "seed {seed}"); - assert!(count(&lines[1]) > count(&lines[3]), "seed {seed}"); + let lines = scenery(seed, 96); + let groups = groups(&lines, ROWS - 1); + let (ground, _) = groups.iter().find(|(_, grounded)| *grounded).unwrap(); + // Several trees and presents on 96 pixels of snow. + assert!(*ground > 96 + 4 * pixels(SMALL_PRESENT), "seed {seed}"); + // Everything else is a single flake. + let flakes: Vec<_> = groups.iter().filter(|(_, grounded)| !grounded).collect(); + assert!( + flakes + .iter() + .all(|(size, _)| [1, pixels(SNOWFLAKE)].contains(size)), + "seed {seed}: {flakes:?}" + ); } } #[test] - fn icicles_hang_from_the_snow_apart_and_thin_out_downwards() { - let mut longest = 0; + fn ornaments_all_hang_from_the_line() { for columns in WIDTHS { for seed in 0..200 { - let lines = icicles(seed, columns); - for column in 0..columns { - for line in 1..ROWS { - // Hanging, not floating. - assert!(!lines[line][column] || lines[line - 1][column]); - } - if column > 0 { - assert!(!(lines[1][column] && lines[1][column - 1])); - } - } - assert!(count(&lines[1]) >= count(&lines[2])); - assert!(count(&lines[2]) >= count(&lines[3])); - longest = longest.max(count(&lines[3])); + let lines = ornaments(seed, columns); + assert!(groups(&lines, 0).iter().all(|(_, hanging)| *hanging)); } } - assert!(longest > 0, "no icicle ever reaches the third line"); + // And there are several of them. + let lines = ornaments(1, 96); + let hooked = (0..96).filter(|column| lines[1][*column]).count(); + assert!(hooked >= 5, "{hooked} ornaments"); } #[test] fn a_seed_gives_one_picture_and_seeds_give_many() { - assert_eq!(trees(7, 48), trees(7, 48)); - assert_eq!(icicles(7, 48), icicles(7, 48)); + assert_eq!(scenery(7, 96), scenery(7, 96)); + assert_eq!(ornaments(7, 96), ornaments(7, 96)); let distinct = |picture: fn(u64, usize) -> Lines| { (0..1000) - .map(|seed| picture(seed, 48)) + .map(|seed| picture(seed, 96)) .collect::>() .len() }; - assert_eq!(distinct(trees), 1000); - assert_eq!(distinct(icicles), 1000); + assert_eq!(distinct(scenery), 1000); + assert_eq!(distinct(ornaments), 1000); } } diff --git a/src/printer.rs b/src/printer.rs index 8c636e2..b2f40e3 100644 --- a/src/printer.rs +++ b/src/printer.rs @@ -26,11 +26,12 @@ //! Each photo is captioned with the event name and place above it, and a //! keepsake line, the capture date and time and one of `QUOTES` below it. The //! captions are in German with the English directly underneath, the quotes in -//! English only. Christmas pixel art (see `artwork`) frames the photo: snow -//! with small fir trees above it and snow with icicles below it, different on -//! every slip. The timestamp is the system clock in local time, so the -//! booth's clock has to be right for it to mean anything. Text goes out in the printer's own code page (PC437), since it -//! prints UTF-8 bytes as separate glyphs; see `code_page`. +//! English only. Christmas pixel art (see `artwork`) frames the photo: fir +//! trees and presents in the snow above it and ornaments hanging below it, +//! arranged differently on every slip. The timestamp is the system clock in +//! local time, so the booth's clock has to be right for it to mean anything. +//! Text goes out in the printer's own code page (PC437), since it prints UTF-8 +//! bytes as separate glyphs; see `code_page`. //! //! Each photo is converted to gray, resized to the exact dot width, contrast //! equalized (CLAHE), slightly sharpened, gamma brightened and finally Atkinson @@ -365,7 +366,7 @@ fn encode( ) -> Vec> { let mut job = Vec::new(); for copy in 0..copies { - // Trees above the photo and icicles below it, new ones for every copy. + // A scene above the photo and ornaments below it, new for every copy. let dots = bitmap.width_bytes * 8; let seed = seed.wrapping_add(2 * copy as u64); job.push(header(head)); @@ -403,33 +404,28 @@ fn raster_bands(job: &mut Vec>, bitmap: &Bitmap, head: &Head) { /// Which side of the photo a pixel strip goes on. #[derive(Clone, Copy)] enum Side { - /// Snow with trees standing on it, so the snow is the strip's bottom line. + /// Trees and presents standing on the snow, the strip's bottom line. Above, - /// Snow with icicles hanging from it, so the snow is the strip's top line. + /// Ornaments hanging from the strip's solid top line. Below, } /// The random Christmas pixel strip across the whole paper, `ROWS` lines of -/// pixels with the solid snow next to the photo. Pixels are 12 dots on 80 mm -/// paper and 8 on 58 mm. +/// pixels with the solid line next to the photo. Pixels are 6 dots on 80 mm +/// paper and 4 on 58 mm. fn pixel_strip(dots: usize, seed: u64, side: Side) -> Bitmap { let cell = (dots / CELLS_ACROSS).max(1); let columns = dots / cell; let left = (dots - columns * cell) / 2; let stride = dots / 8; let lines = match side { - Side::Above => artwork::trees(seed, columns), - Side::Below => artwork::icicles(seed, columns), + Side::Above => artwork::scenery(seed, columns), + Side::Below => artwork::ornaments(seed, columns), }; let mut data = vec![0u8; stride * ROWS * cell]; for y in 0..ROWS * cell { for x in 0..columns * cell { - // Lines are numbered from the photo outward. - let line = match side { - Side::Above => ROWS - 1 - y / cell, - Side::Below => y / cell, - }; - if lines[line][x / cell] { + if lines[y / cell][x / cell] { let dot = left + x; data[y * stride + dot / 8] |= 0x80 >> (dot % 8); } @@ -712,7 +708,7 @@ mod tests { } #[test] - fn frames_the_photo_with_snow_trees_and_icicles() { + fn frames_the_photo_with_christmas_pixel_art() { for dots in [384, 576] { let cell = dots / CELLS_ACROSS; for side in [Side::Above, Side::Below] { @@ -722,20 +718,18 @@ mod tests { let lit = |row: usize, dot: usize| { strip.data[row * strip.width_bytes + dot / 8] & (0x80 >> (dot % 8)) != 0 }; - // Dots lit in each line of pixels, from top to bottom. + // Dots lit in each line of pixels, from the photo outward. let mut counts: Vec = (0..ROWS) .map(|line| (0..dots).filter(|dot| lit(line * cell, *dot)).count()) .collect(); if matches!(side, Side::Above) { counts.reverse(); } - // The snow next to the photo spans the paper; what is on it - // does not, and is there. + // The line next to the photo spans the paper, and there is + // more than that line. assert_eq!(counts[0], dots); - assert!( - counts[1..].iter().all(|count| (1..dots).contains(count)), - "{counts:?}" - ); + assert!(counts[1..].iter().all(|count| *count < dots), "{counts:?}"); + assert!(counts[1..].iter().sum::() > dots, "{counts:?}"); // Pixels are solid squares: every dot row of a line is the same. for line in 0..ROWS { for dot_row in 1..cell { @@ -746,24 +740,27 @@ mod tests { } } } - // Caption, strip, photo, strip, footer, cut: the strips are 48 rows at - // 576 dots and enclose the photo's single row. + // Caption, strip, photo, strip, footer, cut. At 576 dots each strip is + // 72 rows, a full band and 8 more, around the photo's single row. let bitmap = Bitmap { width_bytes: 72, data: vec![0xFF; 72], }; let job = encode(&bitmap, &Head::default(), 1, STAMP, 0, 5); - assert_eq!(job.len(), 6); + assert_eq!(job.len(), 8); let raster = |rows: u8| [0x1B, b'@', 0x1D, b'v', b'0', 0, 72, 0, rows, 0]; - assert!(job[1].starts_with(&raster(48)) && job[3].starts_with(&raster(48))); - assert_eq!(&job[2][..10], raster(1)); - assert!(job[5].ends_with(&[0x1D, b'V', 66, 3])); + for strip in [1, 4] { + assert!(job[strip].starts_with(&raster(BAND_ROWS as u8))); + assert!(job[strip + 1].starts_with(&raster(8))); + } + assert_eq!(&job[3][..10], raster(1)); + assert!(job[7].ends_with(&[0x1D, b'V', 66, 3])); // Nothing is printed after the quote but the feed and the cut. - assert!(job[4].windows(2).all(|pair| pair != [0x1D, b'v'])); - // The two strips differ, and so do those of the next copy. + assert!(job[6].windows(2).all(|pair| pair != [0x1D, b'v'])); + // The next copy gets a different scene. let two = encode(&bitmap, &Head::default(), 2, STAMP, 0, 5); - assert_ne!(two[1], two[3]); - assert_ne!(two[1], two[7]); + assert_ne!(two[1], two[9]); + assert_ne!(two[4], two[12]); } #[test] -- 2.49.1