diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a0a0f6..5ec9058 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,19 @@ All notable changes to gitbonsai are recorded here. Any change to how a tree grows or looks is at least a minor version, because people will notice their tree changing. +## 0.1.1 + +Trees change look in this release: smoother wood and softer leaves. + +- An optional legend beside the tree (`[render] legend = "left"` or `"right"`, + or `render --legend`): each language's leaf color and what the signs mean. + Off by default; the PNG leaves it out. +- Smoother wood: curved outlines, no knobs where pieces meet, side branches + that start at their own girth instead of as thorns, and tapered tips. +- Softer leaves: each pad is lit as one volume in three soft tones, with cool + shadows and warm light. +- Smaller SVGs. + ## 0.1.0 The first release. diff --git a/Cargo.lock b/Cargo.lock index 9c3ccbd..d7e9a85 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -204,7 +204,7 @@ checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" [[package]] name = "gitbonsai" -version = "0.1.0" +version = "0.1.1" dependencies = [ "anyhow", "clap", diff --git a/Cargo.toml b/Cargo.toml index d52d1a7..7c67f99 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "gitbonsai" -version = "0.1.0" +version = "0.1.1" edition = "2024" rust-version = "1.99.0" license = "MIT OR Apache-2.0" diff --git a/README.md b/README.md index ad41a66..36affb0 100644 --- a/README.md +++ b/README.md @@ -4,13 +4,18 @@ Grow a Japanese maple bonsai from your GitHub activity: an animated SVG for your

- - A Japanese maple bonsai grown from synthetic GitHub activity + + A Japanese maple bonsai grown from synthetic GitHub activity, with a legend of its leaf colors and signs

The tree is yours: it grows from your own GitHub activity, week by week. The trunk rises with the years you've been active and thickens with every contribution you've ever made. Each language you write grows branches on its own side, with leaves in that language's color. Your last few months decide how full the leaves are, so busy stretches show and quiet ones thin the crown. Wood never shrinks, so the tree remembers everything. +| Newbie | Comeback | Veteran | +| :---: | :---: | :---: | +| A newcomer bonsai: a young tree in its first pot | A comeback bonsai: deadwood from the quiet years, new growth since | A veteran bonsai: tall, thick and full | +| a few months in | quiet for two years, then back | 16 years, busy since 2023 | +
What every part shows @@ -55,7 +60,7 @@ On your profile, copy [examples/profile-workflow.yml](examples/profile-workflow. On its own, `width="600"` suits a desktop column, and phones scale it down to fit. Next to other cards, use `400`. -Styles, leaf colors and the pot glaze go in a `bonsai.toml`; see [examples/bonsai.toml](examples/bonsai.toml). +Styles, leaf colors, the pot glaze and an optional legend (left or right of the tree) go in a `bonsai.toml`; see [examples/bonsai.toml](examples/bonsai.toml). ## Credits diff --git a/assets/comeback-dark.svg b/assets/comeback-dark.svg new file mode 100644 index 0000000..e585e09 --- /dev/null +++ b/assets/comeback-dark.svg @@ -0,0 +1 @@ +Bonsai for @fixture-comebackJapanese maple bonsai grown over 10 years, level 7. Leaves of Rust, Python. One language has turned to deadwood.gitbonsai 0.1.1; observed 2026-W44; moyogi; dark diff --git a/assets/comeback-light.svg b/assets/comeback-light.svg new file mode 100644 index 0000000..f88b2df --- /dev/null +++ b/assets/comeback-light.svg @@ -0,0 +1 @@ +Bonsai for @fixture-comebackJapanese maple bonsai grown over 10 years, level 7. Leaves of Rust, Python. One language has turned to deadwood.gitbonsai 0.1.1; observed 2026-W44; moyogi; light diff --git a/assets/newbie-dark.svg b/assets/newbie-dark.svg new file mode 100644 index 0000000..14f287f --- /dev/null +++ b/assets/newbie-dark.svg @@ -0,0 +1 @@ +Bonsai for @fixture-steadyJapanese maple bonsai grown over 4 months, level 2. Leaves of Python, Go, TypeScript.gitbonsai 0.1.1; observed 2022-W09; moyogi; dark diff --git a/assets/newbie-light.svg b/assets/newbie-light.svg new file mode 100644 index 0000000..173a4bf --- /dev/null +++ b/assets/newbie-light.svg @@ -0,0 +1 @@ +Bonsai for @fixture-steadyJapanese maple bonsai grown over 4 months, level 2. Leaves of Python, Go, TypeScript.gitbonsai 0.1.1; observed 2022-W09; moyogi; light diff --git a/assets/veteran-dark.svg b/assets/veteran-dark.svg index 48be06d..e3453b3 100644 --- a/assets/veteran-dark.svg +++ b/assets/veteran-dark.svg @@ -1 +1 @@ -Bonsai for @fixture-veteranJapanese maple bonsai grown over 16 years, level 8. Leaves of Rust, TypeScript, Python. Four languages have turned to deadwood.gitbonsai 0.1.0; observed 2026-W44; moyogi; dark +Bonsai for @fixture-veteranJapanese maple bonsai grown over 16 years, level 8. Leaves of Rust, TypeScript, Python. Four languages have turned to deadwood.gitbonsai 0.1.1; observed 2026-W44; moyogi; dark diff --git a/assets/veteran-legend-dark.svg b/assets/veteran-legend-dark.svg new file mode 100644 index 0000000..58633b1 --- /dev/null +++ b/assets/veteran-legend-dark.svg @@ -0,0 +1 @@ +Bonsai for @fixture-veteranJapanese maple bonsai grown over 16 years, level 8. Leaves of Rust, TypeScript, Python. Four languages have turned to deadwood.gitbonsai 0.1.1; observed 2026-W44; moyogi; darkLeavesRustTypeScriptPythondeadwood: Go, JavaScript, +2Signs16 years, 26,301 contributionsnew growth this weeklifetime level 8669-week streaklongest streak 669 weeks diff --git a/assets/veteran-legend-light.svg b/assets/veteran-legend-light.svg new file mode 100644 index 0000000..a0327bc --- /dev/null +++ b/assets/veteran-legend-light.svg @@ -0,0 +1 @@ +Bonsai for @fixture-veteranJapanese maple bonsai grown over 16 years, level 8. Leaves of Rust, TypeScript, Python. Four languages have turned to deadwood.gitbonsai 0.1.1; observed 2026-W44; moyogi; lightLeavesRustTypeScriptPythondeadwood: Go, JavaScript, +2Signs16 years, 26,301 contributionsnew growth this weeklifetime level 8669-week streaklongest streak 669 weeks diff --git a/assets/veteran-light.svg b/assets/veteran-light.svg index 7eb054f..3cfdfe0 100644 --- a/assets/veteran-light.svg +++ b/assets/veteran-light.svg @@ -1 +1 @@ -Bonsai for @fixture-veteranJapanese maple bonsai grown over 16 years, level 8. Leaves of Rust, TypeScript, Python. Four languages have turned to deadwood.gitbonsai 0.1.0; observed 2026-W44; moyogi; light +Bonsai for @fixture-veteranJapanese maple bonsai grown over 16 years, level 8. Leaves of Rust, TypeScript, Python. Four languages have turned to deadwood.gitbonsai 0.1.1; observed 2026-W44; moyogi; light diff --git a/examples/bonsai.toml b/examples/bonsai.toml index 39bb236..baf9095 100644 --- a/examples/bonsai.toml +++ b/examples/bonsai.toml @@ -20,4 +20,5 @@ color = "#F4C7D3" [render] animate = true -size = 400 # display width in px; the viewBox stays 512 +size = 400 # display width in px; the height follows the tree +legend = "off" # "left" or "right": what the colors and signs mean diff --git a/src/config.rs b/src/config.rs index b4526ca..f52893f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -97,6 +97,8 @@ pub struct RenderConfig { pub animate: bool, /// Display width in pixels; the height follows the tree's frame. pub size: u32, + /// A legend beside the tree: what the colors and signs mean. + pub legend: Legend, } impl Default for RenderConfig { @@ -104,6 +106,33 @@ impl Default for RenderConfig { Self { animate: true, size: 400, + legend: Legend::Off, + } + } +} + +/// Where the legend goes, if anywhere. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Legend { + /// No legend: just the tree. + #[default] + Off, + /// Left of the tree. + Left, + /// Right of the tree. + Right, +} + +impl std::str::FromStr for Legend { + type Err = String; + + fn from_str(s: &str) -> Result { + match s { + "off" => Ok(Self::Off), + "left" => Ok(Self::Left), + "right" => Ok(Self::Right), + _ => Err(format!("legend must be off, left or right, not {s:?}")), } } } diff --git a/src/eggs.rs b/src/eggs.rs index e231757..b66d530 100644 --- a/src/eggs.rs +++ b/src/eggs.rs @@ -27,6 +27,7 @@ use std::fmt::Write as _; use crate::Bonsai; use crate::color::Rgb; +use crate::config::Legend; use crate::growth::GOLDEN; use crate::math; use crate::noise::{fbm, hash01, noise1}; @@ -139,8 +140,9 @@ fn take_spot( /// The easter eggs of `b`'s achievements. /// Where the moon hangs: the clearer of the frame's top corners. When both /// are crowded, the frame grows upward until the moon's disc stands clear. -/// `k` is the moon's size relative to a full-grown frame. -fn moon_spot(scene: &Scene, frame: &mut Frame, k: f64) -> (f64, f64) { +/// `k` is the moon's size relative to a full-grown frame. With a legend, the +/// corner away from it wins whenever it is clear. +fn moon_spot(scene: &Scene, frame: &mut Frame, k: f64, legend: Legend) -> (f64, f64) { let inset = 34.0 * k; let clear = 30.0 * k; let mut pts: Vec<(f64, f64)> = scene @@ -165,10 +167,15 @@ fn moon_spot(scene: &Scene, frame: &mut Frame, k: f64) -> (f64, f64) { let top = frame.1 + inset; let left = (frame.0 + inset, top); let right = (frame.0 + frame.2 - inset, top); - let (spot, room) = if clearance(left) > clearance(right) { - (left, clearance(left)) - } else { - (right, clearance(right)) + let away = match legend { + Legend::Right => Some(left), + Legend::Left => Some(right), + Legend::Off => None, + }; + let (spot, room) = match away { + Some(c) if clearance(c) >= clear => (c, clearance(c)), + _ if clearance(left) > clearance(right) => (left, clearance(left)), + _ => (right, clearance(right)), }; if room >= clear { return spot; @@ -179,8 +186,16 @@ fn moon_spot(scene: &Scene, frame: &mut Frame, k: f64) -> (f64, f64) { (spot.0, spot.1 - lift) } -/// The easter eggs of `b`'s achievements. The moon may grow `frame` upward. -pub fn eggs(b: &Bonsai, scene: &Scene, paints: &Paints, pot: &Pot, frame: &mut Frame) -> Eggs { +/// The easter eggs of `b`'s achievements. The moon may grow `frame` upward, +/// and keeps clear of the legend's side. +pub fn eggs( + b: &Bonsai, + scene: &Scene, + paints: &Paints, + pot: &Pot, + frame: &mut Frame, + legend: Legend, +) -> Eggs { let mut e = Eggs::default(); let tier = |slug: &str| b.achievements.get(slug).copied(); if !DRAWN.iter().any(|slug| tier(slug).is_some()) { @@ -350,7 +365,7 @@ pub fn eggs(b: &Bonsai, scene: &Scene, paints: &Paints, pot: &Pot, frame: &mut F if t >= 3 { // Sized to the frame, so it never looms over a young tree. let k = (frame.2 / 480.0).clamp(0.5, 1.0); - let at = moon_spot(scene, frame, k); + let at = moon_spot(scene, frame, k, legend); // Golden with a halo on light backgrounds, pale on dark: visible on both. let (body, halo, crater) = if dark { ("#f3e3a3", "#f6e9b2", "#d9c47e") diff --git a/src/legend.rs b/src/legend.rs new file mode 100644 index 0000000..73b699e --- /dev/null +++ b/src/legend.rs @@ -0,0 +1,408 @@ +//! The optional legend: each language's leaf color and what the tree's signs +//! mean, set beside the tree. Only signs this tree actually shows are listed, +//! and the surprises around the pot are never explained. + +#![allow( + clippy::cast_precision_loss, + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "positions on a 512-unit canvas; contribution totals are small and positive" +)] + +use std::collections::BTreeMap; +use std::fmt::Write as _; + +use crate::Bonsai; +use crate::color::Rgb; +use crate::config::Legend; +use crate::foliage::LanguageState; +use crate::maple::MAPLE_GREEN; +use crate::paint::{Frame, Paints}; +use crate::render::{Num, escape}; + +/// The most languages listed; the rest are counted. +const MAX_LANGUAGES: usize = 8; + +/// What the tree shows besides its languages. +#[derive(Debug, Clone, Copy, Default)] +pub struct Signs { + /// Bronze tips: leaves that grew last week. + pub fresh: bool, + /// Leaves falling: a level crossed this week. + pub falling: bool, + /// The pot's glaze. + pub glaze: Option, +} + +/// A row's marker, drawn left of its words. +enum Mark { + Leaf(Rgb), + Twig(Rgb), + Trunk, + Seeds, + Falling, + Moss, + Pot(Rgb), +} + +/// One row: a heading, a marked line, or a plain line under the marks. +struct Row { + heading: bool, + mark: Option, + text: String, + note: Option<&'static str>, +} + +impl Row { + fn heading(text: &str) -> Self { + Self { + heading: true, + mark: None, + text: text.to_string(), + note: None, + } + } + + fn sign(mark: Mark, text: String) -> Self { + Self { + heading: false, + mark: Some(mark), + text, + note: None, + } + } +} + +/// `n` with thousands separators. +fn thousands(n: u64) -> String { + let digits = n.to_string(); + let mut out = String::new(); + for (i, c) in digits.chars().enumerate() { + if i > 0 && (digits.len() - i).is_multiple_of(3) { + out.push(','); + } + out.push(c); + } + out +} + +/// An age in words: weeks, then months, then years. +fn age(weeks: u32) -> String { + let plural = |n: u32, unit: &str| format!("{n} {unit}{}", if n == 1 { "" } else { "s" }); + if weeks < 9 { + plural(weeks, "week") + } else if weeks < 104 { + plural(weeks * 700 / 3044, "month") + } else { + plural(weeks * 100 / 5218, "year") + } +} + +/// A language name, cut to `max` characters. +fn short(name: &str, max: usize) -> String { + let mut out: String = name.chars().take(max).collect(); + if name.chars().count() > max { + out.push('…'); + } + out +} + +fn rows(b: &Bonsai, paints: &Paints, signs: Signs) -> Vec { + // Living languages first, busiest first; then resting ones by lifetime. + // Deadwood shares one line: it is history, not what the tree is now. + let mut lifetime: BTreeMap<&str, f64> = BTreeMap::new(); + for day in &b.timeline.days { + for (language, amount) in &day.by_language { + *lifetime.entry(language.as_str()).or_default() += amount; + } + } + let total = |l: &str| lifetime.get(l).copied().unwrap_or(0.0); + let of = |state: LanguageState| -> Vec<&String> { + let mut v: Vec<&String> = b + .order + .iter() + .filter(|l| b.state(Some(l)) == state) + .collect(); + v.sort_by(|x, y| { + let key = |l: &str| { + if state == LanguageState::Alive { + b.window.of_language(Some(l)) + } else { + total(l) + } + }; + key(y).total_cmp(&key(x)).then(x.cmp(y)) + }); + v + }; + let (alive, resting, dead) = ( + of(LanguageState::Alive), + of(LanguageState::Bare), + of(LanguageState::Jin), + ); + + let mut rows = vec![Row::heading("Leaves")]; + let shown: Vec<&String> = alive.iter().chain(&resting).copied().collect(); + for language in shown.iter().take(MAX_LANGUAGES) { + let (mark, note) = if b.state(Some(language)) == LanguageState::Alive { + let leaf = b + .maple + .leaf(Some(language), 0.5) + .shift(paints.leaf_shift, 0.0); + (Mark::Leaf(leaf), None) + } else { + (Mark::Twig(paints.bark), Some("resting")) + }; + rows.push(Row { + heading: false, + mark: Some(mark), + text: short(language, 16), + note, + }); + } + if shown.len() > MAX_LANGUAGES { + rows.push(Row { + heading: false, + mark: None, + text: format!("+{} more", shown.len() - MAX_LANGUAGES), + note: None, + }); + } + if !dead.is_empty() { + let mut names: Vec = dead.iter().take(2).map(|l| short(l, 12)).collect(); + if dead.len() > 2 { + names.push(format!("+{}", dead.len() - 2)); + } + rows.push(Row::sign( + Mark::Twig(paints.jin), + format!("deadwood: {}", names.join(", ")), + )); + } + + rows.push(Row::heading("Signs")); + rows.push(Row::sign( + Mark::Trunk, + format!( + "{}, {} contributions", + age(b.timeline.age_weeks()), + thousands(b.timeline.capped_lifetime().round() as u64) + ), + )); + if signs.fresh { + let bronze = MAPLE_GREEN + .mix(Rgb::hex(0xc8553d), 0.45) + .shift(0.06 + paints.leaf_shift, 0.0); + rows.push(Row::sign(Mark::Leaf(bronze), "new growth this week".into())); + } + if b.extras.level >= 3 { + rows.push(Row::sign( + Mark::Seeds, + format!("lifetime level {}", b.extras.level), + )); + } + if signs.falling { + rows.push(Row::sign(Mark::Falling, "a new level this week".into())); + } + if b.extras.current_streak > 0 && b.extras.moss > 0.0 { + rows.push(Row::sign( + Mark::Moss, + format!("{}-week streak", b.extras.current_streak), + )); + } + if let Some(glaze) = signs.glaze { + rows.push(Row::sign( + Mark::Pot(glaze), + format!("longest streak {} weeks", b.extras.longest_streak), + )); + } + rows +} + +/// The legend's markup, beside `frame` on `side`; `frame` grows to hold it. +/// Empty when the legend is off or the tree has nothing to explain yet. +pub fn legend( + b: &Bonsai, + paints: &Paints, + signs: Signs, + side: Legend, + frame: &mut Frame, +) -> String { + if side == Legend::Off || b.is_empty() { + return String::new(); + } + let rows = rows(b, paints, signs); + // Sized to the tree, so the words read the same at any tree size. + let fs = (frame.2.max(frame.3 * 1.2) * 0.036).clamp(10.0, 24.0); + let lh = fs * 1.7; + let mark = fs * 1.2; + let indent = mark + fs * 0.7; + let width = rows + .iter() + .map(|r| { + let words = r.text.chars().count() + r.note.map_or(0, |n| n.len() + 3); + let left = if r.heading { 0.0 } else { indent }; + left + words as f64 * fs * 0.52 + }) + .fold(0.0, f64::max); + let gap = fs * 1.6; + let height = rows.len() as f64 * lh; + + // Make room: beside the tree, and taller when the list is. + let grid = |v: f64| (v / 8.0).ceil() * 8.0; + let room = grid(width + gap); + let x0 = match side { + Legend::Left => { + frame.0 -= room; + frame.0 + fs * 0.6 + } + _ => frame.0 + frame.2 + gap, + }; + frame.2 += room; + let need = height + 2.0 * fs; + if need > frame.3 { + let grow = grid(need - frame.3); + frame.1 -= grow; + frame.3 += grow; + } + let top = frame.1 + (frame.3 - height) / 2.0; + + let (ink, muted) = if paints.dark { + ("#d4cbb9", "#988e7c") + } else { + ("#4f473b", "#8c816e") + }; + let mut s = format!( + r#""#, + Num(fs) + ); + for (i, row) in rows.iter().enumerate() { + let cy = top + (i as f64 + 0.5) * lh; + let baseline = cy + fs * 0.35; + let Some(m) = &row.mark else { + // Headings sit flush left and bold; a plain line lines up with the words. + let _ = write!( + s, + r#"{}"#, + Num(if row.heading { x0 } else { x0 + indent }), + Num(baseline), + if row.heading { + r#" font-weight="600" letter-spacing=".04em""# + } else { + "" + }, + escape(&row.text) + ); + continue; + }; + let mx = x0 + mark / 2.0; + s.push_str(&marker(m, mx, cy, mark, paints)); + let _ = write!( + s, + r#"{}"#, + Num(x0 + indent), + Num(baseline), + escape(&row.text) + ); + if let Some(note) = row.note { + let _ = write!(s, r#" · {note}"#); + } + s.push_str(""); + } + s.push_str(""); + s +} + +/// A row's marker, `size` across, centered on `(x, y)`. +fn marker(mark: &Mark, x: f64, y: f64, size: f64, paints: &Paints) -> String { + let h = size / 2.0; + match mark { + Mark::Leaf(color) => format!( + r##""##, + Num(x), + Num(y + h), + Num(size / 5.2) + ), + Mark::Twig(color) => format!( + r#""#, + Num(x - h), + Num(y + h * 0.8), + Num(x + h), + Num(y - h * 0.8), + Num(x), + Num(y), + Num(x + h * 0.15), + Num(y - h * 0.9), + Num(size * 0.14) + ), + Mark::Trunk => format!( + r#""#, + Num(x - h * 0.55), + Num(y + h), + Num(x - h * 0.1), + Num(y), + Num(x - h * 0.15), + Num(y - h), + Num(x + h * 0.2), + Num(y - h), + Num(x + h * 0.15), + Num(y), + Num(x + h * 0.6), + Num(y + h), + paints.bark + ), + Mark::Seeds => format!( + r##""##, + Num(x), + Num(y - h * 0.7), + Num(size / 9.0), + paints.crimson + ), + Mark::Falling => format!( + r##""##, + Num(x), + Num(y - h * 0.4), + Num(size / 5.6), + paints.crimson + ), + Mark::Moss => format!( + r#""#, + Num(x - h * 0.3), + Num(y + h * 0.3), + Num(h * 0.6), + Num(h * 0.3), + paints.moss[0], + Num(x + h * 0.35), + Num(y + h * 0.15), + Num(h * 0.45), + Num(h * 0.25), + paints.moss[1] + ), + Mark::Pot(glaze) => format!( + r#""#, + Num(x - h), + Num(y - h * 0.35), + Num(x + h), + Num(x + h * 0.7), + Num(y + h * 0.55), + Num(x - h * 0.7) + ), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn numbers_and_ages_read_naturally() { + assert_eq!(thousands(0), "0"); + assert_eq!(thousands(999), "999"); + assert_eq!(thousands(1_000), "1,000"); + assert_eq!(thousands(26_301), "26,301"); + assert_eq!(thousands(1_234_567), "1,234,567"); + assert_eq!(age(1), "1 week"); + assert_eq!(age(5), "5 weeks"); + assert_eq!(age(96), "22 months"); + assert_eq!(age(869), "16 years"); + } +} diff --git a/src/lib.rs b/src/lib.rs index 0ecf439..b44edf9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -36,6 +36,7 @@ pub mod fixtures; pub mod foliage; pub mod growth; pub mod html; +pub mod legend; pub mod maple; pub mod math; pub mod noise; diff --git a/src/main.rs b/src/main.rs index 6edc099..78dd56b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,6 +9,7 @@ use std::process::ExitCode; use anyhow::Result; use clap::{Parser, Subcommand}; +use gitbonsai::config::Legend; use gitbonsai::date::Date; use gitbonsai::{ Bonsai, Config, Error, Snapshot, Style, Theme, collect, explain, fixtures, html, output, render, @@ -75,6 +76,10 @@ enum Command { /// Leave every animation rule out #[arg(long)] no_animate: bool, + + /// Override [render] legend: off, left or right + #[arg(long)] + legend: Option, }, /// Print every derived number behind the tree @@ -174,6 +179,7 @@ fn run(cli: Cli) -> Result<()> { output_dir, size, no_animate, + legend, } => { let snapshot = load_snapshot(&snapshot)?; let mut config = load_config(&tree, &snapshot, &status)?; @@ -184,6 +190,9 @@ fn run(cli: Cli) -> Result<()> { if no_animate { config.render.animate = false; } + if let Some(legend) = legend { + config.render.legend = legend; + } let bonsai = Bonsai::grow(&snapshot, &config, as_of(&tree)?); render_outputs(&bonsai, &config, &output_dir)?; status(&format!("wrote {}", output_dir.display())); @@ -330,8 +339,10 @@ fn render_outputs(bonsai: &Bonsai, config: &Config, dir: &Path) -> Result<()> { let png = cfg!(feature = "png"); #[cfg(feature = "png")] { + // Without its font stack resvg draws no text, so the PNG goes without the legend. let mut still = config.clone(); still.render.animate = false; + still.render.legend = Legend::Off; let svg = render::svg(bonsai, &still, Theme::Light); let bytes = gitbonsai::raster::png(&svg, config.render.size)?; output::write_atomic(&dir.join("bonsai.png"), &bytes)?; diff --git a/src/paint.rs b/src/paint.rs index c5e7953..ebc5de7 100644 --- a/src/paint.rs +++ b/src/paint.rs @@ -155,15 +155,56 @@ pub fn norm((x, y): (f64, f64)) -> (f64, f64) { (x / l, y / l) } -/// A tube with a round end cap along `(x, y, r)` samples. -pub fn tube(points: &[(f64, f64, f64)]) -> PathData { +/// Continues `d` from `pts[0]` (the current point) through the rest of `pts` +/// on one smooth curve: Catmull-Rom, written as cubic Béziers. Interior +/// control points mirror each other, so after the first segment every one is +/// a short `s`. +pub fn smooth_through(d: &mut PathData, pts: &[(f64, f64)]) { + let n = pts.len(); + if n < 2 { + return; + } + if n == 2 { + // Two points make a straight curve: a line says the same, shorter. + d.l(pts[1]); + return; + } + let at = |i: isize| -> (f64, f64) { + if i < 0 { + (2.0 * pts[0].0 - pts[1].0, 2.0 * pts[0].1 - pts[1].1) + } else if i as usize >= n { + let (a, b) = (pts[n - 1], pts[n - 2]); + (2.0 * a.0 - b.0, 2.0 * a.1 - b.1) + } else { + pts[i as usize] + } + }; + for i in 0..n - 1 { + let k = i as isize; + let (p0, p1, p2, p3) = (at(k - 1), at(k), at(k + 1), at(k + 2)); + let c2 = (p2.0 - (p3.0 - p1.0) / 6.0, p2.1 - (p3.1 - p1.1) / 6.0); + if i == 0 { + let c1 = (p1.0 + (p2.0 - p0.0) / 6.0, p1.1 + (p2.1 - p0.1) / 6.0); + d.c(c1, c2, p2); + } else { + d.s(c2, p2); + } + } +} + +/// A tube along `(x, y, r)` samples, ending in a round cap when `cap` and cut +/// flat otherwise (for a piece that the next one overlaps). Its sides are +/// curves when `smooth`; thin twigs don't need them, and straight sides are +/// shorter to write. +pub fn tube(points: &[(f64, f64, f64)], cap: bool, smooth: bool) -> PathData { let n = points.len(); let mut d = PathData::coarse(); if n < 2 { return d; } + // Tangents over two neighbours each way, so sides don't wobble. let tangent = |i: usize| { - let (a, b) = (points[i.saturating_sub(1)], points[(i + 1).min(n - 1)]); + let (a, b) = (points[i.saturating_sub(2)], points[(i + 2).min(n - 1)]); norm((b.0 - a.0, b.1 - a.1)) }; let side = |i: usize, s: f64| { @@ -171,25 +212,60 @@ pub fn tube(points: &[(f64, f64, f64)]) -> PathData { let (x, y, r) = points[i]; (x - ty * r * s, y + tx * r * s) }; - d.m(side(0, -1.0)); - for i in 1..n { - d.l(side(i, -1.0)); - } - let (tx, ty) = tangent(n - 1); - let r = points[n - 1].2; - let (a, b) = (side(n - 1, -1.0), side(n - 1, 1.0)); - d.c( - (a.0 + tx * r * 1.33, a.1 + ty * r * 1.33), - (b.0 + tx * r * 1.33, b.1 + ty * r * 1.33), - b, - ); - for i in (0..n - 1).rev() { - d.l(side(i, 1.0)); + let left: Vec<(f64, f64)> = (0..n).map(|i| side(i, -1.0)).collect(); + let right: Vec<(f64, f64)> = (0..n).rev().map(|i| side(i, 1.0)).collect(); + let side_line = |d: &mut PathData, pts: &[(f64, f64)]| { + if smooth { + smooth_through(d, pts); + } else { + for &p in &pts[1..] { + d.l(p); + } + } + }; + d.m(left[0]); + side_line(&mut d, &left); + let (a, b) = (left[n - 1], right[0]); + if cap { + let (tx, ty) = tangent(n - 1); + let r = points[n - 1].2; + d.c( + (a.0 + tx * r * 1.33, a.1 + ty * r * 1.33), + (b.0 + tx * r * 1.33, b.1 + ty * r * 1.33), + b, + ); + } else { + d.l(b); } + side_line(&mut d, &right); d.z(); d } +/// Narrows the last stretch of a branch, about three tip-widths long, so it +/// ends in a slim rounded point instead of a blunt stub. Short stubs keep +/// their round end: tapered, they would read as thorns. +pub fn taper_tip(pts: &mut [(f64, f64, f64, f64)]) { + let Some(&(tx, ty, tr, _)) = pts.last() else { + return; + }; + let length: f64 = pts + .windows(2) + .map(|w| ((w[1].0 - w[0].0).powi(2) + (w[1].1 - w[0].1).powi(2)).sqrt()) + .sum(); + if length < tr * 10.0 { + return; + } + let reach = (tr * 3.0).max(1e-9); + for p in pts.iter_mut().rev() { + let d = ((p.0 - tx).powi(2) + (p.1 - ty).powi(2)).sqrt(); + if d >= reach { + break; + } + p.2 *= 0.6 + 0.4 * d / reach; + } +} + /// A five-point moving average; the ends stay put so chains still meet. pub fn relax(pts: &[(f64, f64, f64, f64)]) -> Vec<(f64, f64, f64, f64)> { let n = pts.len(); @@ -350,17 +426,12 @@ pub fn paint(b: &Bonsai, config: &Config, theme: Theme) -> Painted { (x, y, *r * WORLD, z) }) .collect(); - // Relax the growth zigzag, then subdivide; thin twigs need less. - let relaxed = relax(&relax(&pts)); + // Relax the growth zigzag, then subdivide; thin twigs need less. The + // outline is drawn as curves, so few points carry a smooth branch. + let relaxed = relax(&relax(&relax(&pts))); let thick = pts.iter().any(|p| p.2 > 3.2); - let fine = simplify( - &if thick { - chaikin(&chaikin(&relaxed)) - } else { - chaikin(&relaxed) - }, - 0.6, - ); + let mut fine = simplify(&chaikin(&relaxed), if thick { 1.0 } else { 0.6 }); + taper_tip(&mut fine); for p in &fine { extent = ( extent.0.min(p.0 - p.2), @@ -371,19 +442,32 @@ pub fn paint(b: &Bonsai, config: &Config, theme: Theme) -> Painted { // Thin twigs all share one path per color, drawn behind the leaves. if !thick { let seg: Vec<(f64, f64, f64)> = fine.iter().map(|p| (p.0, p.1, p.2)).collect(); - twigs[usize::from(*jin)].push_str(tube(&seg).as_str()); + twigs[usize::from(*jin)].push_str(tube(&seg, true, false).as_str()); continue; } let piece = 20; let mut start = 0; while start + 1 < fine.len() { let end = (start + piece).min(fine.len() - 1); - let seg: Vec<(f64, f64, f64)> = - fine[start..=end].iter().map(|p| (p.0, p.1, p.2)).collect(); + // Each piece runs two points into the next, which covers the seam, + // so only the branch's real tip gets a cap. + let last = end == fine.len() - 1; + let reach = if last { + end + } else { + (end + 2).min(fine.len() - 1) + }; + let seg: Vec<(f64, f64, f64)> = fine[start..=reach] + .iter() + .map(|p| (p.0, p.1, p.2)) + .collect(); let depth = fine[start..=end].iter().map(|p| p.3).sum::() / (end - start + 1) as f64; let base = haze(if *jin { paints.jin } else { paints.bark }, depth); - let mut s = format!(r#""#, tube(&seg).as_str()); + let mut s = format!( + r#""#, + tube(&seg, last, true).as_str() + ); if seg.iter().any(|p| p.2 > 4.5) { // The shadow falls on whichever side faces away from the light. let m = seg.len(); @@ -398,26 +482,30 @@ pub fn paint(b: &Bonsai, config: &Config, theme: Theme) -> Painted { } }; let strip = |from: f64, to: f64| { - let mut d = PathData::coarse(); - for i in 0..m { + let offset = |i: usize, k: f64| { let n = away(i); - let q = ( - seg[i].0 + n.0 * seg[i].2 * from, - seg[i].1 + n.1 * seg[i].2 * from, - ); - if i == 0 { - d.m(q) - } else { - d.l(q) - }; - } - for i in (0..m).rev() { - let n = away(i); - d.l(( - seg[i].0 + n.0 * seg[i].2 * to, - seg[i].1 + n.1 * seg[i].2 * to, - )); + (seg[i].0 + n.0 * seg[i].2 * k, seg[i].1 + n.1 * seg[i].2 * k) + }; + // Strips are soft bands inside the wood: a point every + // dozen units or so carries them on a smooth curve. + let mut idx = vec![0]; + let mut run = 0.0; + for i in 1..m { + run += ((seg[i].0 - seg[i - 1].0).powi(2) + + (seg[i].1 - seg[i - 1].1).powi(2)) + .sqrt(); + if run >= 14.0 || i == m - 1 { + idx.push(i); + run = 0.0; + } } + let there: Vec<(f64, f64)> = idx.iter().map(|&i| offset(i, from)).collect(); + let back: Vec<(f64, f64)> = idx.iter().rev().map(|&i| offset(i, to)).collect(); + let mut d = PathData::coarse(); + d.m(there[0]); + smooth_through(&mut d, &there); + d.l(back[0]); + smooth_through(&mut d, &back); d.z(); d }; @@ -490,22 +578,26 @@ pub fn paint(b: &Bonsai, config: &Config, theme: Theme) -> Painted { } } - // ---- leaves: lit by n.L, darkened by occlusion; bronze flush; samaras ---- + // ---- leaves: each pad lit as one smooth ball in three soft tones, the + // way painted backgrounds shade foliage; bronze flush; samaras ---- + let smoothstep = |e0: f64, e1: f64, v: f64| { + let t = ((v - e0) / (e1 - e0)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) + }; let mut fallen: Vec<(f64, f64, f64)> = Vec::new(); for (j, t) in scene.tufts.iter().enumerate() { let (x, y, depth) = project(t.p); let diffuse = v_dot(t.n, light).max(0.0); let shade = (0.25 + 0.75 * diffuse) * (0.55 + 0.45 * t.q); - let mut c = t.color.shift( - paints.leaf_shift + (shade - 0.55) * 0.38, - (shade - 0.5) * 0.04, - ); - // Light warms, shadow cools. - c = if shade > 0.55 { - c.mix(Rgb::hex(0xe8d27a), (shade - 0.55) * 0.25) - } else { - c.mix(Rgb::hex(0x24384a), (0.55 - shade) * 0.35) - }; + // Light from the pad's ball normal and height in the pad, then a + // ramp: cool shadow, the leaf color, warm light, with soft steps. + let s = 0.62 * diffuse + 0.38 * t.q; + let base = t.color.shift(paints.leaf_shift, 0.0); + let dark = base.shift(-0.15, -0.01).mix(Rgb::hex(0x2f3d63), 0.28); + let lit = base.shift(0.09, -0.005).mix(Rgb::hex(0xfff0c2), 0.22); + let mut c = base + .mix(dark, 1.0 - smoothstep(0.33, 0.39, s)) + .mix(lit, smoothstep(0.66, 0.72, s)); if t.fresh { // Japanese maples flush bronze-red before the leaves settle. c = c.mix(Rgb::hex(0xc8553d), 0.45).shift(0.06, 0.0); @@ -618,7 +710,14 @@ pub fn paint(b: &Bonsai, config: &Config, theme: Theme) -> Painted { glaze: pot_glaze(b.extras.pot_tier, config, &paints), }; out.frame = frame(extent, &pot); - let egg = eggs::eggs(b, &scene, &paints, &pot, &mut out.frame); + let egg = eggs::eggs( + b, + &scene, + &paints, + &pot, + &mut out.frame, + config.render.legend, + ); let body = &mut out.body; body.push_str(&egg.behind); @@ -692,6 +791,13 @@ pub fn paint(b: &Bonsai, config: &Config, theme: Theme) -> Painted { pot.glaze.shift(0.08, 0.0) ); body.push_str(&egg.top); + let signs = crate::legend::Signs { + fresh: scene.tufts.iter().any(|t| t.fresh), + falling: !fallen.is_empty(), + glaze: Some(pot.glaze), + }; + let legend = crate::legend::legend(b, &paints, signs, config.render.legend, &mut out.frame); + out.body.push_str(&legend); out } @@ -734,7 +840,7 @@ fn nebari(b: &Bonsai, paints: &Paints, base_r: f64) -> String { (x, y, base_r * 0.42 * (1.0 - t) + 0.5) }) .collect(); - roots.push_str(tube(&pts).as_str()); + roots.push_str(tube(&pts, true, false).as_str()); } format!( r#""#, diff --git a/src/render.rs b/src/render.rs index c4bd623..b573356 100644 --- a/src/render.rs +++ b/src/render.rs @@ -133,14 +133,57 @@ impl PathData { self } - /// Cubic curve to `to` with control points `c1` and `c2`. + /// Cubic curve to `to` with control points `c1` and `c2`. Coarse paths + /// write it relative (`c`), like `l`. pub fn c(&mut self, c1: (f64, f64), c2: (f64, f64), to: (f64, f64)) -> &mut Self { - self.d.push('C'); - self.point(c1); - self.d.push(' '); - self.point(c2); - self.d.push(' '); - self.point(to); + if self.coarse { + let step = |v: f64| (v * 10.0).round() / 10.0; + let rel = |p: (f64, f64), at: (f64, f64)| (step(p.0 - at.0), step(p.1 - at.1)); + let (a, b, t) = (rel(c1, self.at), rel(c2, self.at), rel(to, self.at)); + let _ = write!( + self.d, + "c{} {} {} {} {} {}", + Coarse(a.0), + Coarse(a.1), + Coarse(b.0), + Coarse(b.1), + Coarse(t.0), + Coarse(t.1) + ); + self.at = (self.at.0 + t.0, self.at.1 + t.1); + } else { + self.d.push('C'); + self.point(c1); + self.d.push(' '); + self.point(c2); + self.d.push(' '); + self.point(to); + } + self + } + + /// Smooth cubic curve to `to`, its first control point mirrored from the + /// last curve's. Coarse paths write it relative (`s`), like `l`. + pub fn s(&mut self, c2: (f64, f64), to: (f64, f64)) -> &mut Self { + if self.coarse { + let step = |v: f64| (v * 10.0).round() / 10.0; + let (cx, cy) = (step(c2.0 - self.at.0), step(c2.1 - self.at.1)); + let (dx, dy) = (step(to.0 - self.at.0), step(to.1 - self.at.1)); + let _ = write!( + self.d, + "s{} {} {} {}", + Coarse(cx), + Coarse(cy), + Coarse(dx), + Coarse(dy) + ); + self.at = (self.at.0 + dx, self.at.1 + dy); + } else { + self.d.push('S'); + self.point(c2); + self.d.push(' '); + self.point(to); + } self } diff --git a/src/scene.rs b/src/scene.rs index bd04f11..a64e2c4 100644 --- a/src/scene.rs +++ b/src/scene.rs @@ -206,13 +206,16 @@ impl Scene { // The trunk never becomes jin, whichever branch its heaviest path leads into. let jin = chain[0] != 0 && b.state(sk.nodes[last].language.as_deref()) == LanguageState::Jin; - scene.chains.push(( - chain - .iter() - .map(|&i| (lift(sk.nodes[i].p), radius(flow[i]))) - .collect(), - jin, - )); + let mut wood: Vec<(V3, f64)> = chain + .iter() + .map(|&i| (lift(sk.nodes[i].p), radius(flow[i]))) + .collect(); + // A side branch starts inside its parent at its own girth, a + // little flared, not the parent's: else short stubs become thorns. + if chain[0] != s0 && wood.len() > 1 { + wood[0].1 = wood[0].1.min(wood[1].1 * 1.3); + } + scene.chains.push((wood, jin)); } let seeds = samara_share(b.extras.level); diff --git a/tests/invariants.rs b/tests/invariants.rs index 60b1761..f063bdb 100644 --- a/tests/invariants.rs +++ b/tests/invariants.rs @@ -1,6 +1,6 @@ //! The growth model's promises, checked on every fixture. -use gitbonsai::config::Wind; +use gitbonsai::config::{Legend, Wind}; use gitbonsai::foliage::LanguageState; use gitbonsai::growth::H_REF; use gitbonsai::{Bonsai, Config, Style, Theme, fixtures, render}; @@ -194,6 +194,70 @@ fn the_svg_is_self_contained_and_accessible() { } } +/// The legend sits on either side, stays within budget, lists the living +/// languages, and never gives away a surprise. +#[test] +fn the_legend_explains_without_spoiling() { + let spoilers = [ + "fish", + "shark", + "tuna", + "star", + "furin", + "fūrin", + "moon", + "firefly", + "glow", + "pebble", + "crane", + "coin", + "snow", + "copter", + "kintsugi", + "achievement", + "drip", + "archived", + ]; + for fixture in fixtures::all() { + for side in [Legend::Left, Legend::Right] { + let mut config = Config::default(); + config.render.legend = side; + let bonsai = Bonsai::grow(&fixture.snapshot, &config, None); + for theme in Theme::ALL { + let svg = render::svg(&bonsai, &config, theme); + let label = format!("{}/{side:?}/{}", fixture.name, theme.name()); + assert!(svg.len() <= 150 * 1024, "{label}: {} bytes", svg.len()); + if bonsai.is_empty() { + assert!(!svg.contains("").next().unwrap_or("").to_lowercase()) + .collect(); + assert!( + words.contains("leaves") && words.contains("signs"), + "{label}" + ); + for language in &bonsai.order { + if bonsai.state(Some(language)) == LanguageState::Alive + && bonsai.order.len() <= 8 + { + assert!( + words.contains(&language.to_lowercase()), + "{label}: {language}" + ); + } + } + for word in spoilers { + assert!(!words.contains(word), "{label}: says {word}"); + } + } + } + } +} + /// The veteran: tall from age, level 8, Ruby turned to jin. #[test] fn the_veteran_matches_worked_example_a() {