From f27373b6933657c09a4d433b1583b59c68545d24 Mon Sep 17 00:00:00 2001 From: astar76 Date: Sat, 24 Oct 2026 14:20:10 -0500 Subject: [PATCH] Cookie Clicker: draw the building picture faster and cache it Co-Authored-By: Claude Sonnet 5.5 --- src/commands/games/cookie.rs | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/src/commands/games/cookie.rs b/src/commands/games/cookie.rs index 50999d6..7001a3f 100644 --- a/src/commands/games/cookie.rs +++ b/src/commands/games/cookie.rs @@ -98,20 +98,38 @@ fn building_strip(sheet: &image::RgbaImage, owned: &[u64; N]) -> Option> } let label = format!("×{}", short(*count as f64)); let (x, y) = ((cx + 76) as i32, (cy + 22) as i32); + // shape the text once per colour and draw it at a few offsets for the outline + let (dark, light) = (layout(&label, 26.0, &shadow, None, Align::Left), layout(&label, 26.0, &white, None, Align::Left)); for (dx, dy) in [(-2, 0), (2, 0), (0, -2), (0, 2), (2, 2)] { - layout(&label, 26.0, &shadow, None, Align::Left).draw(&mut img, x + dx, y + dy); + dark.draw(&mut img, x + dx, y + dy); } - layout(&label, 26.0, &white, None, Align::Left).draw(&mut img, x, y); + light.draw(&mut img, x, y); } let mut out = Vec::new(); img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).ok()?; Some(out) } +/// Pictures already drawn, by what they show: drawing is the slow part on a small machine. +fn strip_cache() -> &'static Mutex>> { + static C: OnceLock>>> = OnceLock::new(); + C.get_or_init(Default::default) +} + async fn strip_for(state: &State, b: &Bakery) -> Option> { - let sheet = building_sheet(state).await?; let owned = b.owned; - tokio::task::spawn_blocking(move || building_strip(&sheet, &owned)).await.ok().flatten() + if let Some(png) = strip_cache().lock().ok().and_then(|c| c.get(&owned).cloned()) { + return Some(png); + } + let sheet = building_sheet(state).await?; + let png = tokio::task::spawn_blocking(move || building_strip(&sheet, &owned)).await.ok().flatten()?; + if let Ok(mut c) = strip_cache().lock() { + if c.len() >= 200 { + c.clear(); + } + c.insert(owned, png.clone()); + } + Some(png) } // ---- the numbers ----------------------------------------------------------------------------------------------------------- @@ -925,7 +943,10 @@ mod tests { for (i, n) in [43, 3, 1, 12, 2, 1, 7, 4, 9, 120, 5, 3, 2, 1, 1, 1, 8, 2, 1, 1].iter().enumerate() { owned[i] = *n; } - std::fs::write(std::env::var("DEZIO_OUT").unwrap(), building_strip(&sheet, &owned).unwrap()).unwrap(); + let started = std::time::Instant::now(); + let png = building_strip(&sheet, &owned).unwrap(); + eprintln!("strip took {:?}", started.elapsed()); + std::fs::write(std::env::var("DEZIO_OUT").unwrap(), png).unwrap(); } #[test]