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 <noreply@anthropic.com>
This commit is contained in:
bankosegger
2026-11-18 17:38:34 +01:00
parent a465c5c88f
commit 16993e8231
3 changed files with 204 additions and 35 deletions

65
src/artwork.rs Normal file
View File

@@ -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<u32> = 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<Sprite> = (0..1000).map(sprite).collect();
assert!(distinct.len() > 200, "{} sprites", distinct.len());
}
}

View File

@@ -20,6 +20,7 @@ use slint::{Rgb8Pixel, SharedPixelBuffer};
slint::include_modules!();
mod artwork;
mod camera;
mod capture;
mod diagnostics;

View File

@@ -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<Vec<u8>> {
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, &QUOTES[(first_quote + copy) % QUOTES.len()]));
raster_bands(&mut job, bitmap, head);
job.push(footer(
head,
stamp,
&QUOTES[(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<Vec<u8>>, 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<u8> {
/// Appends one line of text, encoded for the printer.
fn text_line(write: &mut Vec<u8>, 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<u8> {
let mut write = centered(head);
write.extend([0x1B, b'd', 1]);
@@ -438,6 +494,14 @@ fn footer(head: &Head, stamp: &str, quote: &[&str]) -> Vec<u8> {
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<u8> {
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<usize> =
(0..1000).map(|_| first_quote()).collect();
let picked: std::collections::BTreeSet<usize> = (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!(
&copy[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);
}
}