A drawing app built for agent/human collaboration
Rust
Foliage that reads as leaves: clumps built from lit leaves
Indicode BV1fee877ff5fd
diff --git a/README.md b/README.mdindex 59e074e..2f5fe65 100644--- a/README.md+++ b/README.md@@ -51,7 +51,7 @@ There are no downloads yet; build it from source (about ten minutes the first ti1. Install Rust with [rustup](https://rustup.rs) and [`just`](https://github.com/casey/just) (`brew install just`, or `cargo install just`). On Linux also `pkg-config`, `libfreetype-dev` and `libfontconfig1-dev`.2. `git clone https://github.com/klad-app/klad && cd klad`, then `just build` makes the `klad` binary in `target/release/` (on Linux in `target/linux/release/`).3. On a Mac, `target/release/klad open` starts the editor on its start window: make a drawing and start painting.-4. `just samples` builds the sample drawings in `samples/` (a lantern, a walking creature, a running courier, an underground ruin, an inn sign, painted solids, a bowl of lemons, a bouncing ball, ink examples); open one with `target/release/klad open samples/lantern/lantern.draw`.+4. `just samples` builds the sample drawings in `samples/` (a lantern, a walking creature, a running courier, an underground ruin, an inn sign, a tree, painted solids, a bowl of lemons, a bouncing ball, ink examples); open one with `target/release/klad open samples/lantern/lantern.draw`.## Drawing with an agentdiff --git a/crates/app/src/editor/brushwin.rs b/crates/app/src/editor/brushwin.rsindex 4ee18b3..97f6187 100644--- a/crates/app/src/editor/brushwin.rs+++ b/crates/app/src/editor/brushwin.rs@@ -45,7 +45,8 @@ fn tip_name(tip: &TipDef) -> String {match tip {TipDef::Round { .. } => "round".into(),TipDef::Chalk { .. } => "chalk".into(),- TipDef::Image { image } => image.clone(),+ TipDef::Image { image, more } if more.is_empty() => image.clone(),+ TipDef::Image { image, more } => format!("{image} +{}", more.len()),}}@@ -63,7 +64,14 @@ fn tip_choice(ui: &mut egui::Ui, salt: &str, tip: &mut TipDef, pictures: &[Strinpick(ui, "round", TipDef::Round { hardness: 0.8 });pick(ui, "chalk", TipDef::Chalk { seed: 7 });pictures.iter().for_each(|name| {- pick(ui, name, TipDef::Image { image: name.clone() });+ pick(+ ui,+ name,+ TipDef::Image {+ image: name.clone(),+ more: Vec::new(),+ },+ );});}).response@@ -205,6 +213,7 @@ impl Editor {def.dual = dual.then(|| DualDef {tip: TipDef::Image {image: "bristle-round".into(),+ more: Vec::new(),},size: 0.5,scatter: 1.0,diff --git a/crates/brush/src/brush.rs b/crates/brush/src/brush.rsindex 3db64a9..5be55fe 100644--- a/crates/brush/src/brush.rs+++ b/crates/brush/src/brush.rs@@ -11,6 +11,7 @@ use std::sync::{Arc, Mutex, OnceLock};pub enum Tip {Round { hardness: f32 },Mask(Arc<TipMask>),+ Masks(Vec<Arc<TipMask>>),}#[derive(Clone, Copy, Debug)]@@ -134,13 +135,24 @@ fn tip_of(def: &TipDef, pictures: &Pictures) -> Result<Tip> {Ok(match def {TipDef::Round { hardness } => Tip::Round { hardness: *hardness },TipDef::Chalk { seed } => Tip::Mask(memo(&CHALK, *seed, || TipMask::chalk(*seed))),- TipDef::Image { image } => match (library_index(image), pictures.get(image)) {- (_, Some(picture)) => Tip::Mask(memo(&PICTURE_TIPS, picture.hash, || images::tip_from(picture))),- (Some(i), None) => Tip::Mask(memo(&LIBRARY_TIPS, i, || {- images::library_tip(TIP_IMAGES[i]).expect("a library tip")- })),- (None, None) => return Err(missing(image)),- },+ TipDef::Image { image, more } if more.is_empty() => Tip::Mask(picture_tip(image, pictures)?),+ TipDef::Image { image, more } => Tip::Masks(+ [image]+ .into_iter()+ .chain(more)+ .map(|i| picture_tip(i, pictures))+ .collect::<Result<_>>()?,+ ),+ })+}++fn picture_tip(image: &str, pictures: &Pictures) -> Result<Arc<TipMask>> {+ Ok(match (library_index(image), pictures.get(image)) {+ (_, Some(picture)) => memo(&PICTURE_TIPS, picture.hash, || images::tip_from(picture)),+ (Some(i), None) => memo(&LIBRARY_TIPS, i, || {+ images::library_tip(TIP_IMAGES[i]).expect("a library tip")+ }),+ (None, None) => return Err(missing(image)),})}@@ -371,6 +383,32 @@ impl BrushSet {mod tests {use super::*;+ #[test]+ fn a_tip_with_more_pictures_holds_one_mask_each_and_round_trips() {+ let def = brushes::library("leaves").unwrap();+ assert!(def.images().is_empty(), "library pictures are not the bundle's");+ match Brush::from_def(&def).tip {+ Tip::Masks(masks) => {+ assert_eq!(masks.len(), 5);+ assert!(+ masks[0].data != masks[1].data && masks[1].data != masks[3].data,+ "the shapes differ"+ );+ }+ _ => panic!("leaves draws from several pictures"),+ }+ let text = serde_json::to_string(&def.tip).unwrap();+ assert!(text.contains("\"more\""), "{text}");+ let one = TipDef::Image {+ image: "leaf".into(),+ more: Vec::new(),+ };+ assert!(+ !serde_json::to_string(&one).unwrap().contains("more"),+ "a single picture is written as before"+ );+ }+#[test]fn every_preset_builds() {let set = BrushSet::presets();diff --git a/crates/brush/src/engine.rs b/crates/brush/src/engine.rsindex 49b4899..2e40f09 100644--- a/crates/brush/src/engine.rs+++ b/crates/brush/src/engine.rs@@ -66,6 +66,7 @@ pub struct StrokePainter {size: f32,flow: f32,rng: Rng,+ seed: u32,last: Option<Point>,heading: f32,speed: f32,@@ -118,6 +119,7 @@ impl StrokePainter {size: stroke.size,flow: stroke.flow,rng: Rng::new(stroke.seed as u64),+ seed: stroke.seed,last: None,heading: 0.0,speed: 0.0,@@ -321,6 +323,7 @@ impl StrokePainter {count,color,lift,+ pick: klad_core::rng::hash2(self.dabs as i32, self.seed as i32, 0x1eaf) as usize,};match self.brush.def.paint {Some(PaintDef::Smudge { strength }) => {@@ -444,6 +447,7 @@ struct Dab {count: usize,color: Option<[f32; 3]>,lift: Option<f32>,+ pick: usize,}const GROOVES: usize = 256;@@ -539,7 +543,7 @@ enum Replace {Blend,}-fn tip_value(tip: &Tip, u: f32, v: f32, d2: f32, radius: f32) -> f32 {+fn tip_value(tip: &Tip, u: f32, v: f32, d2: f32, radius: f32, pick: usize) -> f32 {match tip {Tip::Round { hardness } => {let d = libm::sqrtf(d2);@@ -548,6 +552,7 @@ fn tip_value(tip: &Tip, u: f32, v: f32, d2: f32, radius: f32) -> f32 {(1.0 - t * t * (3.0 - 2.0 * t)).min(edge)}Tip::Mask(mask) => mask.sample(u, v),+ Tip::Masks(masks) => masks[pick % masks.len()].sample(u, v),}}@@ -569,7 +574,7 @@ impl Edge {soft: smoothstep(0.5, 2.0, fade),})}- Tip::Mask(_) => None,+ Tip::Mask(_) | Tip::Masks(_) => None,}}@@ -603,7 +608,7 @@ fn dual_value(brush: &Brush, dab: &Dab, u: f32, v: f32, radius: f32) -> f32 {let d2 = ru * ru + rv * rv;match d2 >= 1.0 {true => most,- false => most.max(tip_value(&dual.tip, ru, rv, d2, radius * dual.size)),+ false => most.max(tip_value(&dual.tip, ru, rv, d2, radius * dual.size, 0)),}})}@@ -706,7 +711,7 @@ fn stamp(buffer: &mut StrokeBuffer, brush: &Brush, dab: Dab, bristles: Option<(&}let (cover, reach) = match &edge {Some(edge) => edge.cover(libm::sqrtf(d2) * radius),- None => (tip_value(&brush.tip, u, v, d2, radius), 1.0),+ None => (tip_value(&brush.tip, u, v, d2, radius, dab.pick), 1.0),};let mut a = cover * flow;if dab.count > 0 {@@ -787,7 +792,7 @@ fn stamp_replace(if d2 >= reach2 {return None;}- let mut a = tip_value(&brush.tip, u, v, d2, radius) * flow;+ let mut a = tip_value(&brush.tip, u, v, d2, radius, dab.pick) * flow;if dab.count > 0 {a *= dual_value(brush, &dab, u, v, radius);}diff --git a/crates/brush/src/images.rs b/crates/brush/src/images.rsindex 889a46d..c2435f1 100644--- a/crates/brush/src/images.rs+++ b/crates/brush/src/images.rs@@ -167,6 +167,48 @@ fn leaf(u: f32, v: f32) -> f32 {body * rib}+fn blade(u: f32, v: f32, half: f32, rib: f32) -> f32 {+ if u.abs() >= 1.0 || half <= 0.0 {+ return 0.0;+ }+ let body = 1.0 - smoothstep(half * 0.86, half, v.abs());+ let vein = match u > -0.8 && u < 0.8 {+ true => 1.0 - rib * (1.0 - smoothstep(0.012, 0.03, v.abs())),+ false => 1.0,+ };+ body * vein+}++fn leaf_oval(u: f32, v: f32) -> f32 {+ let half = 0.5 * libm::powf((1.0 - u * u).max(0.0), 0.6) * (1.0 - 0.22 * u);+ blade(u, v, half, 0.45)+}++fn leaf_lance(u: f32, v: f32) -> f32 {+ blade(u, v, 0.2 * libm::powf((1.0 - u * u).max(0.0), 0.9), 0.3)+}++fn leaf_lobed(u: f32, v: f32) -> f32 {+ let lobes = 0.7 + 0.3 * libm::cosf((u + 0.1) * std::f32::consts::PI * 3.0);+ let half = 0.46 * libm::powf((1.0 - u * u).max(0.0), 0.55) * lobes;+ blade(u, v, half, 0.4)+}++fn leaf_twig(u: f32, v: f32) -> f32 {+ let small = |cu: f32, cv: f32, turn: f32, scale: f32| {+ let (s, c) = (libm::sinf(turn), libm::cosf(turn));+ let (du, dv) = (u - cu, v - cv);+ leaf_oval((du * c + dv * s) / scale, (dv * c - du * s) / scale)+ };+ let stem = match u > -0.95 && u < 0.35 {+ true => 1.0 - smoothstep(0.02, 0.04, v.abs()),+ false => 0.0,+ };+ stem.max(small(0.55, 0.0, 0.0, 0.45))+ .max(small(0.05, -0.33, -0.9, 0.38))+ .max(small(-0.35, 0.3, 0.95, 0.36))+}+fn grass(u: f32, v: f32) -> f32 {let height = (1.0 - v) / 2.0;(0..5).fold(0.0f32, |most, k| {@@ -201,6 +243,10 @@ pub fn library_tip(name: &str) -> Option<TipMask> {"leaf" => leaf,"grass" => grass,"splatter" => splatter,+ "leaf-oval" => leaf_oval,+ "leaf-lance" => leaf_lance,+ "leaf-lobed" => leaf_lobed,+ "leaf-twig" => leaf_twig,_ => return None,};let data = (0..TIP_SIZE * TIP_SIZE)diff --git a/crates/cli/src/brushes.rs b/crates/cli/src/brushes.rsindex 54b5326..11b5a18 100644--- a/crates/cli/src/brushes.rs+++ b/crates/cli/src/brushes.rs@@ -49,7 +49,7 @@ fn tip(def: &BrushDef) -> String {let main = match &def.tip {TipDef::Round { hardness } => format!("round {hardness}"),TipDef::Chalk { seed } => format!("chalk {seed}"),- TipDef::Image { image } => image.clone(),+ TipDef::Image { image, more } => [image].into_iter().chain(more).cloned().collect::<Vec<_>>().join("+"),};let extras: Vec<&str> = [(def.dual.is_some(), "dual"),diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rsindex ac26f1f..ef626e6 100644--- a/crates/cli/src/main.rs+++ b/crates/cli/src/main.rs@@ -29,8 +29,8 @@ use klad_core::fill::{EXPAND, FillSource, TOLERANCE};use klad_core::history::Stack;use klad_core::markedit::{LassoAction, MarkTransform};use klad_core::ops::{- ClipEdit, CopySpec, CopyTarget, FillSpec, HatchSpec, InbetweenSpec, InkSpec, LassoSpec, LightSpec, Op, PaintSpec,- PaletteEdit, Place, ScatterSpec, StrokeSpec,+ ClipEdit, CopySpec, CopyTarget, FillSpec, FoliageSpec, HatchSpec, InbetweenSpec, InkSpec, LassoSpec, LightSpec, Op,+ PaintSpec, PaletteEdit, Place, ScatterSpec, StrokeSpec,};use klad_core::retime::{Retime, RetimeSpec};use klad_core::stroke::{fills_of, strokes_of};@@ -1099,6 +1099,56 @@ enum Command {#[command(flatten)]flags: EditFlags,},+ #[command(+ about = "Paint closed shapes as clumps of leaves, lit as forms",+ long_about = "Build each closed shape out of leaves: leaf marks across the clump take their colour from a round form lit by --light (or a --lamp x,y,height), in a few value steps from --shade through --color to --lit (by default darker and cooler, lighter and warmer than --color), with the most variety in the light; then leaves along the outline, most on the side facing the light and the sky, a few glowing (--glow) at the shadow side's edge, so the silhouette breaks up and the sky shows between them. --mass names a shape around the whole crown, so every clump also turns with the big form. --leaf is the leaf size in px, --density how close the leaves sit. Fill a darker, slightly smaller core under each clump first and paint clumps back to front on one layer. The brush is leaves (several leaf shapes, one per dab).\n\n klad foliage tree.draw canopy --in clump1 --color '#4d7a3b' --light -0.6,-0.8 --leaf 16 --mass crown\n\nAlso a foliage op: {\"op\":\"foliage\",\"layer\":\"canopy\",\"in\":[\"clump1\"],\"color\":\"#4d7a3b\",\"light\":[-0.6,-0.8],\"leaf\":16,\"mass\":\"crown\"}."+ )]+ Foliage {+ bundle: PathBuf,+ layer: String,+ #[arg(+ long = "in",+ value_delimiter = ',',+ help = "Closed vector shapes, each a clump of leaves"+ )]+ within: Vec<String>,+ #[arg(long, default_value = "#4f7a3c", help = "The leaves' middle colour")]+ color: String,+ #[arg(long, help = "The lit leaves' colour (default: lighter and warmer)")]+ lit: Option<String>,+ #[arg(long, help = "The shadowed leaves' colour (default: darker and cooler)")]+ shade: Option<String>,+ #[arg(+ long,+ help = "Light through thin leaves at the shadow edge (default: a warm yellow-green)"+ )]+ glow: Option<String>,+ #[arg(long, value_parser = parse_pair, allow_hyphen_values = true, default_value = "-1,-1")]+ light: [f32; 2],+ #[arg(long, help = "A lamp at x,y,height in canvas px instead of a direction")]+ lamp: Option<String>,+ #[arg(long, default_value_t = 14.0, help = "Leaf size in px")]+ leaf: f32,+ #[arg(long, default_value_t = 1.0, help = "How close the leaves sit (2 is twice as many)")]+ density: f32,+ #[arg(+ long,+ help = "A shape around the whole crown, so each clump also turns with the big form"+ )]+ mass: Option<String>,+ #[arg(long, default_value = "leaves")]+ brush: String,+ #[arg(long, help = "Only the leaves along the outline, not across the clump")]+ edges_only: bool,+ #[arg(long, default_value_t = 1)]+ seed: u32,+ #[arg(long, default_value_t = 0)]+ frame: u32,+ #[arg(long, help = "Put the new marks in this part of the drawing (see klad part)")]+ part: Option<String>,+ #[command(flatten)]+ flags: EditFlags,+ },#[command(about = "List closed regions of the lines that no fill on the layer covers",long_about = "List the closed regions of a fill layer's reference (the lines its flood fills fill against) that no fill on the layer covers: pockets a fill missed, or drawings not coloured yet. Regions open to the canvas edge are the outside and do not count. Each pocket prints its bounds and size, and a render of the frame marks them in magenta with a box.\n\n klad gaps art.draw colour --frame 4\n klad gaps art.draw colour --sheet all\n klad gaps art.draw colour --sheet walk --ref lines --gap 4\n\nThe reference, gap and tolerance default to those of the layer's flood fills on those frames."@@ -2399,6 +2449,54 @@ fn run() -> Result<()> {};agent::edit(&bundle, &[Op::Scatter(spec)], &output(&flags, frame))?;}+ Command::Foliage {+ bundle,+ layer,+ within,+ color,+ lit,+ shade,+ glow,+ light,+ lamp,+ leaf,+ density,+ mass,+ brush,+ edges_only,+ seed,+ frame,+ part,+ flags,+ } => {+ let lamp = lamp+ .as_deref()+ .map(|l| -> Result<[f32; 3]> {+ parse_numbers(l)?+ .try_into()+ .map_err(|_| anyhow!("--lamp {l:?} is not x,y,height"))+ })+ .transpose()?;+ let spec = FoliageSpec {+ layer: layer_id(&bundle, &layer)?,+ frame,+ within,+ color,+ lit,+ shade,+ glow,+ light,+ lamp,+ leaf,+ mass,+ density,+ brush,+ body: !edges_only,+ seed,+ part,+ };+ agent::edit(&bundle, &[Op::Foliage(spec)], &output(&flags, frame))?;+ }Command::Gaps {bundle,layer,diff --git a/crates/cli/src/shapes.rs b/crates/cli/src/shapes.rsindex 37faf8b..4459207 100644--- a/crates/cli/src/shapes.rs+++ b/crates/cli/src/shapes.rs@@ -2,7 +2,9 @@ use anyhow::{Context, Result, bail};use klad_core::bundle::Bundle;use klad_core::color;use klad_core::doc::Document;-use klad_core::ops::{FillSpec, HatchSpec, InkSpec, LightSpec, Op, PaintSpec, ScatterSpec, StrokeSpec, apply_all};+use klad_core::ops::{+ FillSpec, FoliageSpec, HatchSpec, InkSpec, LightSpec, Op, PaintSpec, ScatterSpec, StrokeSpec, apply_all,+};use klad_render::form::{self, Form, FormRules, Lighting, Shadow};use klad_render::shapes::{self, HatchRules, InkRules, Outline, P, Run, ScatterRules};use serde_json::json;@@ -323,6 +325,208 @@ fn scatter(doc: &Document, spec: &ScatterSpec) -> Result<Vec<Op>> {.collect()}+fn inside(polygons: &[Vec<P>], at: P) -> bool {+ polygons.iter().fold(false, |odd, poly| {+ let crossings = (0..poly.len())+ .filter(|&i| {+ let (a, b) = (poly[i], poly[(i + 1) % poly.len()]);+ (a[1] > at[1]) != (b[1] > at[1]) && at[0] < a[0] + (at[1] - a[1]) / (b[1] - a[1]) * (b[0] - a[0])+ })+ .count();+ odd ^ (crossings % 2 == 1)+ })+}++fn resample(poly: &[Vec<P>], step: f32) -> Vec<(P, P)> {+ poly.iter()+ .flat_map(|points| {+ let n = points.len();+ let mut out = Vec::new();+ let mut carry = 0.0;+ (0..n).for_each(|i| {+ let (a, b) = (points[i], points[(i + 1) % n]);+ let len = ((b[0] - a[0]).powi(2) + (b[1] - a[1]).powi(2)).sqrt();+ if len < 1e-4 {+ return;+ }+ let t = [(b[0] - a[0]) / len, (b[1] - a[1]) / len];+ let mut d = carry;+ while d < len {+ out.push(([a[0] + t[0] * d, a[1] + t[1] * d], t));+ d += step;+ }+ carry = d - len;+ });+ out+ })+ .collect()+}++fn mix_lab(a: [f32; 3], b: [f32; 3], t: f32) -> [f32; 3] {+ std::array::from_fn(|i| a[i] + (b[i] - a[i]) * t)+}++fn foliage(doc: &Document, spec: &FoliageSpec) -> Result<Vec<Op>> {+ let found = areas(doc, &spec.within, &None, "foliage")?;+ let colour = |text: &str| -> Result<[f32; 3]> { Ok(color::to_oklab(color::parse_hex(&doc.resolve_color(text)?)?)) };+ let mid = colour(&spec.color)?;+ let given = |c: &Option<String>, shift: [f32; 3]| -> Result<[f32; 3]> {+ match c {+ Some(c) => colour(c),+ None => Ok(std::array::from_fn(|i| mid[i] + shift[i])),+ }+ };+ let lit = given(&spec.lit, [0.15, -0.012, 0.05])?;+ let shade = given(&spec.shade, [-0.2, -0.01, -0.045])?;+ let glow = given(&spec.glow, [0.1, -0.03, 0.09])?;+ let hex = |lab: [f32; 3]| color::to_hex(color::from_oklab(lab, 1.0));+ let (mut x0, mut y0, mut x1, mut y1) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);+ found.iter().flatten().for_each(|p| {+ (x0, y0, x1, y1) = (x0.min(p[0]), y0.min(p[1]), x1.max(p[0]), y1.max(p[1]));+ });+ let (cx, cy, rx, ry) = (+ (x0 + x1) / 2.0,+ (y0 + y1) / 2.0,+ ((x1 - x0) / 2.0).max(1.0),+ ((y1 - y0) / 2.0).max(1.0),+ );+ let crown = match &spec.mass {+ Some(id) => {+ let outline = areas(doc, std::slice::from_ref(id), &None, "foliage's mass")?;+ let (mut a0, mut b0, mut a1, mut b1) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);+ outline.iter().flatten().for_each(|p| {+ (a0, b0, a1, b1) = (a0.min(p[0]), b0.min(p[1]), a1.max(p[0]), b1.max(p[1]));+ });+ Some((+ (a0 + a1) / 2.0,+ (b0 + b1) / 2.0,+ ((a1 - a0) / 2.0).max(1.0),+ ((b1 - b0) / 2.0).max(1.0),+ ))+ }+ None => None,+ };+ let bulge = |p: P, (cx, cy, rx, ry): (f32, f32, f32, f32)| -> [f32; 3] {+ let (u, v) = ((p[0] - cx) / rx, (p[1] - cy) / ry);+ let flat = (u * u + v * v).min(1.0);+ let n = [u * 0.9, v * 0.9, (1.0 - flat).max(0.0).sqrt() + 0.15];+ let d = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();+ [n[0] / d, n[1] / d, n[2] / d]+ };+ let blended = |p: P, own: [f32; 3]| -> [f32; 3] {+ match crown {+ Some(c) => {+ let big = bulge(p, c);+ let n: [f32; 3] = std::array::from_fn(|i| own[i] * 0.45 + big[i] * 0.55);+ let d = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt().max(1e-4);+ [n[0] / d, n[1] / d, n[2] / d]+ }+ None => own,+ }+ };+ let flat = (spec.light[0].powi(2) + spec.light[1].powi(2)).sqrt().max(1e-4);+ let sun = [spec.light[0] / flat * 0.8, spec.light[1] / flat * 0.8, 0.6];+ let towards = |p: P| -> [f32; 3] {+ match spec.lamp {+ Some([lx, ly, lz]) => {+ let v = [lx - p[0], ly - p[1], lz.max(1.0)];+ let d = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt().max(1e-4);+ [v[0] / d, v[1] / d, v[2] / d]+ }+ None => sun,+ }+ };+ let tone_at = |p: P, normal: [f32; 3]| -> f32 {+ let l = towards(p);+ let lambert = normal[0] * l[0] + normal[1] * l[1] + normal[2] * l[2];+ let under = normal[1].max(0.0) * 0.4;+ (0.42 + 0.7 * lambert - under).clamp(0.0, 1.0)+ };+ let mut rng = klad_core::rng::Rng::new(spec.seed as u64 * 7_919 + 13);+ let mut leaves: Vec<(f32, Op)> = Vec::new();+ let mut leaf = |rng: &mut klad_core::rng::Rng, at: P, out: P, size: f32, tone: f32, shine: bool| -> Result<()> {+ let stepped = (tone * 3.0).floor().min(2.0) / 3.0 + 1.0 / 6.0;+ let tone = (stepped + (tone - stepped) * 0.35 + rng.signed() * 0.05 * (0.2 + tone)).clamp(0.0, 1.0);+ let lab = match (shine, tone < 0.5) {+ (true, _) => glow,+ (false, true) => mix_lab(shade, mid, (tone * 2.0).clamp(0.0, 1.0)),+ (false, false) => mix_lab(mid, lit, (tone * 2.0 - 1.0).clamp(0.0, 1.0)),+ };+ let spread = 0.015 + 0.03 * tone;+ let lab = [+ lab[0] + rng.signed() * spread,+ lab[1] + rng.signed() * 0.006,+ lab[2] + rng.signed() * 0.01,+ ];+ let turn = rng.signed() * 0.9;+ let (s, c) = (turn.sin(), turn.cos());+ let d = [out[0] * c - out[1] * s, out[0] * s + out[1] * c];+ let reach = size * (0.3 + 0.2 * (rng.signed() + 1.0));+ let a = [at[0] - d[0] * size * 0.3, at[1] - d[1] * size * 0.3];+ let b = [at[0] + d[0] * reach, at[1] + d[1] * reach];+ let run: Run = vec![[a[0], a[1], 0.8], [b[0], b[1], 1.0]];+ let seed = spec.seed.wrapping_mul(2_750_159).wrapping_add(leaves.len() as u32 * 31);+ let op = stroke(+ &spec.layer,+ spec.frame,+ &spec.brush,+ &hex(lab),+ size,+ 1.0,+ Some([0.0, 0.0]),+ seed,+ &run,+ &spec.part,+ )?;+ leaves.push((tone, op));+ Ok(())+ };+ if spec.body {+ let step = spec.leaf * 0.6 / spec.density.max(0.05);+ let (cols, rows) = (((x1 - x0) / step).ceil() as i32, ((y1 - y0) / step).ceil() as i32);+ (0..rows)+ .flat_map(|r| (0..cols).map(move |c| (r, c)))+ .try_for_each(|(r, c)| {+ let p = [+ x0 + (c as f32 + 0.5 + rng.signed() * 0.45) * step,+ y0 + (r as f32 + 0.5 + rng.signed() * 0.45) * step,+ ];+ if !inside(&found, p) {+ return Ok::<_, anyhow::Error>(());+ }+ let (u, v) = ((p[0] - cx) / rx, (p[1] - cy) / ry);+ let normal = blended(p, bulge(p, (cx, cy, rx, ry)));+ let out = {+ let d = (u * u + v * v).sqrt().max(1e-3);+ [u / d, v / d]+ };+ let size = spec.leaf * (0.75 + 0.2 * (rng.signed() + 1.0));+ leaf(&mut rng, p, out, size, tone_at(p, normal), false)+ })?;+ }+ let step = spec.leaf * 0.4 / spec.density.max(0.05);+ resample(&found, step).into_iter().try_for_each(|(p, t)| {+ let probe = (spec.leaf * 0.25).max(1.0);+ let mut n = [t[1], -t[0]];+ if inside(&found, [p[0] + n[0] * probe, p[1] + n[1] * probe]) {+ n = [-n[0], -n[1]];+ }+ let normal = blended(p, [n[0] * 0.92, n[1] * 0.92, 0.38]);+ let tone = tone_at(p, normal);+ let up = (-n[1]).max(0.0);+ let keep = (0.5 + 0.5 * tone + 0.25 * up).min(1.0);+ if (rng.signed() + 1.0) / 2.0 > keep {+ return Ok::<_, anyhow::Error>(());+ }+ let size = spec.leaf * (0.75 + 0.25 * (rng.signed() + 1.0));+ let shine = tone < 0.35 && up < 0.5 && rng.signed() > 0.75;+ let at = [p[0] + n[0] * size * 0.05, p[1] + n[1] * size * 0.05];+ leaf(&mut rng, at, n, size, tone, shine)+ })?;+ leaves.sort_by(|a, b| a.0.total_cmp(&b.0));+ Ok(leaves.into_iter().map(|(_, op)| op).collect())+}+fn shapes_change(op: &Op) -> bool {matches!(op,@@ -346,6 +550,7 @@ pub fn expand(bundle: &Bundle, ops: Vec<Op>) -> Result<Vec<Op>> {Op::Hatch(spec) => Some(hatch(&doc, spec)),Op::Paint(spec) => Some(paint(&doc, spec)),Op::Scatter(spec) => Some(scatter(&doc, spec)),+ Op::Foliage(spec) => Some(foliage(&doc, spec)),Op::Fill(spec) => spec.shape.as_ref().map(|id| shape_fill(&doc, spec, id)),_ => None,};@@ -390,6 +595,49 @@ mod tests {(dir.clone(), Bundle::create(&dir, doc).unwrap())}+ #[test]+ fn foliage_builds_a_clump_from_leaves_lit_as_a_form_with_a_broken_edge() {+ let (dir, b) = bundle("foliage");+ let ops = parse_lines(+ r##"{"op":"add","node":{"id":"clump","type":"ellipse","cx":200,"cy":150,"rx":110,"ry":80},"in":"l4","frame":0}+{"op":"foliage","layer":"l1","in":["clump"],"color":"#4d7a3b","light":[-0.6,-0.8],"leaf":12,"seed":4}"##,+ )+ .unwrap();+ let made = expand(&b, ops.clone()).unwrap();+ assert_eq!(made, expand(&b, ops).unwrap(), "seeded");+ let leaves: Vec<(f32, f32, f32)> = made+ .iter()+ .filter_map(|o| match o {+ Op::Stroke(s) => {+ let points = s.points.as_ref()?;+ let (x, y) = (points[0][0], points[0][1]);+ let lab = color::to_oklab(color::parse_hex(&s.color).ok()?);+ assert_eq!(s.brush, "leaves");+ Some((x, y, lab[0]))+ }+ _ => None,+ })+ .collect();+ assert!(leaves.len() > 200, "{} leaves", leaves.len());+ let mean = |pick: &dyn Fn(f32, f32) -> bool| {+ let chosen: Vec<f32> = leaves.iter().filter(|(x, y, _)| pick(*x, *y)).map(|l| l.2).collect();+ chosen.iter().sum::<f32>() / chosen.len().max(1) as f32+ };+ let lit = mean(&|x, y| x < 170.0 && y < 130.0);+ let dark = mean(&|x, y| x > 230.0 && y > 170.0);+ assert!(lit > dark + 0.08, "the lit side is lighter: {lit} against {dark}");+ let outside = made+ .iter()+ .filter_map(|o| match o {+ Op::Stroke(s) => s.points.as_ref().and_then(|p| p.last().copied()),+ _ => None,+ })+ .filter(|p| ((p[0] - 200.0) / 110.0).powi(2) + ((p[1] - 150.0) / 80.0).powi(2) > 1.0)+ .count();+ assert!(outside > 40, "leaves break the outline ({outside})");+ std::fs::remove_dir_all(&dir).unwrap();+ }+#[test]fn shapes_added_in_a_batch_are_inked_filled_lit_and_textured_in_the_same_batch() {let (dir, mut b) = bundle("batch");diff --git a/crates/core/brushes/library/leaves.json b/crates/core/brushes/library/leaves.jsonindex 23aaa75..17e4cd8 100644--- a/crates/core/brushes/library/leaves.json+++ b/crates/core/brushes/library/leaves.json@@ -1,9 +1,10 @@{"format": "draw-anything-brush/1","name": "Leaves",- "tip": { "image": { "image": "leaf" } },+ "tip": { "image": { "image": "leaf", "more": ["leaf-oval", "leaf-oval", "leaf-lance", "leaf-twig"] } },"spacing": 0.6,"angle": "follow",- "jitter": { "size": 0.5, "angle": 1.2, "scatter": 1.2 },- "color": { "hue": 8.0, "saturation": 0.1, "value": 0.15, "strokeValue": 0.05 }+ "jitter": { "size": 0.35, "angle": 0.5, "scatter": 0.45 },+ "dynamics": { "size": { "pressure": { "min": 0.5 } } },+ "color": { "hue": 4.0, "saturation": 0.05, "value": 0.04, "pressure": { "min": 0.0 } }}diff --git a/crates/core/src/brushes.rs b/crates/core/src/brushes.rsindex f86845a..4d18947 100644--- a/crates/core/src/brushes.rs+++ b/crates/core/src/brushes.rs@@ -82,12 +82,31 @@ pub struct BrushDef {#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "lowercase", deny_unknown_fields)]pub enum TipDef {- Round { hardness: f32 },- Chalk { seed: u32 },- Image { image: String },-}--pub const TIP_IMAGES: [&str; 6] = ["bristle-flat", "bristle-round", "sponge", "leaf", "grass", "splatter"];+ Round {+ hardness: f32,+ },+ Chalk {+ seed: u32,+ },+ Image {+ image: String,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ more: Vec<String>,+ },+}++pub const TIP_IMAGES: [&str; 10] = [+ "bristle-flat",+ "bristle-round",+ "sponge",+ "leaf",+ "grass",+ "splatter",+ "leaf-oval",+ "leaf-lance",+ "leaf-lobed",+ "leaf-twig",+];#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]#[serde(deny_unknown_fields)]@@ -323,7 +342,7 @@ impl TipDef {match self {TipDef::Round { hardness } => within(&format!("{what} hardness"), *hardness, 0.0, 1.0),TipDef::Chalk { .. } => Ok(()),- TipDef::Image { image } => valid_image(image),+ TipDef::Image { image, more } => [image].into_iter().chain(more).try_for_each(|i| valid_image(i)),}}}@@ -436,15 +455,15 @@ impl BrushDef {}pub fn images(&self) -> Vec<&str> {- fn tip(t: &TipDef) -> Option<&str> {+ fn tip(t: &TipDef) -> Vec<&str> {match t {- TipDef::Image { image } => Some(image.as_str()),- _ => None,+ TipDef::Image { image, more } => [image].into_iter().chain(more).map(String::as_str).collect(),+ _ => Vec::new(),}}tip(&self.tip).into_iter()- .chain(self.dual.as_ref().and_then(|d| tip(&d.tip)))+ .chain(self.dual.as_ref().map(|d| tip(&d.tip)).unwrap_or_default()).chain(self.grain.as_ref().and_then(|g| g.image.as_deref())).filter(|name| !TIP_IMAGES.contains(name)).collect()diff --git a/crates/core/src/bundle.rs b/crates/core/src/bundle.rsindex ea39cdf..51b8ea5 100644--- a/crates/core/src/bundle.rs+++ b/crates/core/src/bundle.rs@@ -527,6 +527,7 @@ pub fn summarize(ops: &[Op]) -> String {Op::Hatch(spec) => format!("hatch on {}", spec.layer),Op::Paint(spec) => format!("paint on {}", spec.layer),Op::Scatter(spec) => format!("scatter on {}", spec.layer),+ Op::Foliage(spec) => format!("foliage on {}", spec.layer),Op::Inbetween(spec) if spec.redo => "redo in-betweens".to_string(),Op::Inbetween(spec) => format!("in-between {} frames {} to {}",diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rsindex 3aa3183..dcf5f17 100644--- a/crates/core/src/ops.rs+++ b/crates/core/src/ops.rs@@ -145,6 +145,7 @@ pub enum Op {Hatch(HatchSpec),Paint(PaintSpec),Scatter(ScatterSpec),+ Foliage(FoliageSpec),Clip(ClipEdit),Export {godot: Option<String>,@@ -536,6 +537,58 @@ pub struct ScatterSpec {pub part: Option<String>,}+#[derive(Clone, Debug, PartialEq, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct FoliageSpec {+ pub layer: String,+ #[serde(default)]+ pub frame: u32,+ #[serde(default, rename = "in")]+ pub within: Vec<String>,+ #[serde(default = "foliage_color")]+ pub color: String,+ #[serde(default)]+ pub lit: Option<String>,+ #[serde(default)]+ pub shade: Option<String>,+ #[serde(default)]+ pub glow: Option<String>,+ #[serde(default = "default_light")]+ pub light: [f32; 2],+ #[serde(default)]+ pub lamp: Option<[f32; 3]>,+ #[serde(default = "foliage_leaf")]+ pub leaf: f32,+ #[serde(default)]+ pub mass: Option<String>,+ #[serde(default = "full")]+ pub density: f32,+ #[serde(default = "foliage_brush")]+ pub brush: String,+ #[serde(default = "foliage_body")]+ pub body: bool,+ #[serde(default = "first_seed")]+ pub seed: u32,+ #[serde(default)]+ pub part: Option<String>,+}++fn foliage_color() -> String {+ "#4f7a3c".into()+}++fn foliage_leaf() -> f32 {+ 14.0+}++fn foliage_brush() -> String {+ "leaves".into()+}++fn foliage_body() -> bool {+ true+}+fn ink_weight() -> f32 {6.0}@@ -1149,6 +1202,7 @@ impl Op {"hatch" => Op::Hatch(serde_json::from_value(Value::Object(std::mem::take(&mut map)))?),"paint" => Op::Paint(serde_json::from_value(Value::Object(std::mem::take(&mut map)))?),"scatter" => Op::Scatter(serde_json::from_value(Value::Object(std::mem::take(&mut map)))?),+ "foliage" => Op::Foliage(serde_json::from_value(Value::Object(std::mem::take(&mut map)))?),"clip" => Op::Clip(parse_clip(&mut map)?),"export" => Op::Export {godot: match map.remove("godot") {@@ -2435,9 +2489,9 @@ pub fn apply(doc: &mut Document, op: &Op, out: &mut Applied) -> Result<()> {let id = duplicate_layer(doc, layer, out)?;out.added.push(id);}- Op::Ink(_) | Op::Light(_) | Op::Hatch(_) | Op::Paint(_) | Op::Scatter(_) => {+ Op::Ink(_) | Op::Light(_) | Op::Hatch(_) | Op::Paint(_) | Op::Scatter(_) | Op::Foliage(_) => {bail!(- "ink, light, hatch, paint and scatter are turned into strokes and fills by klad ink, klad light, klad hatch, klad paint, klad scatter or klad apply first"+ "ink, light, hatch, paint, scatter and foliage are turned into strokes and fills by klad ink, klad light, klad hatch, klad paint, klad scatter, klad foliage or klad apply first");}Op::Inbetween(spec) => {diff --git a/docs/DESIGN.md b/docs/DESIGN.mdindex 83e6434..a25c829 100644--- a/docs/DESIGN.md+++ b/docs/DESIGN.md@@ -238,6 +238,7 @@ Every layer has `blend`, `opacity`, `visible`, `locked`, optional `mask`, `clip`- **Generators (M5).** `scatter` (copies of its children over a region, `count`, `seed`, `size` and `turn` ranges, `avoid`: SVG paths no copy's centre may fall in), `repeat` (`count` copies, each `step` further, turning `turn` degrees and growing `scale` about `pivot`, or a grid `columns` wide with `row` between rows) and `mirror` (its children and their reflection across a line through `x, y` at `angle`) are nodes whose children are drawn once per instance (`generators.rs`); they stay settings, the inspector edits them, and "repeat it", "scatter it", "mirror it" put a selected shape inside one; "take the shapes out" removes one and keeps its shapes where its first copy was. Their children keep their ids, so V can still pick inside.- **Text (M5).** `{"type": "text", "text", "font", "x", "y", "size", "tracking", "leading", "align", "weight"}` with the node's fill and outline. The font is a file in the bundle's `fonts/` folder, so a drawing renders the same anywhere. Each line is shaped by `harfrust` (HarfBuzz's shaping in Rust: GPOS and `kern` kerning, ligatures, marks, scripts), `weight` sets a variable font's `wght` axis, and the outlines come from the file through `skrifa`, each glyph's contours merged with Skia's path ops so an outline never shows the overlaps variable fonts are built with; they are drawn as one path, never by the system's font engine, so the Mac and the container draw the same pixels. A missing font is refused with its name.- **Fonts (M5, S5.26).** klad ships about fifty open families for game art in `fonts/` (sans, serif, mono, display, handwriting, pixel; OFL-1.1 or Apache-2.0, unchanged from the Google Fonts repository at a pinned commit, listed with their licences in the notices; `fonts/update.py` fetches them again). `klad_render::fonts` finds that folder next to the binary (also `../Resources/fonts` in a Mac app and the repository's `fonts/` for development builds; `KLAD_FONTS` overrides), and keeps families downloaded on request in a per-user folder (`~/Library/Application Support/klad/fonts`, `$XDG_DATA_HOME/klad/fonts`, `%APPDATA%\klad\fonts`). `fonts/catalogue.json` lists every open family on Google Fonts (about 1,900) with its group and folder at the same commit, so `klad fonts --search` works offline and a download (`klad fonts --get`, or naming a family anywhere a font is taken) fetches exactly that commit's files with `curl`. Choosing a font anywhere (the CLI's `font=`, `klad font`, the editor's picker) copies the file and its licence into the bundle; the node keeps the file name. This replaces M5 choice 3 (no fonts with the app). The editor's frame and plane caches fold `klad_render::RENDER_VERSION` into their keys, so pictures cached before a renderer change are not shown again. A light layer is no kind of its own: a paint layer set to `add` with a soft glow (a shortcut button for it only confused the layers pane).+- **Foliage (M5, S5.27).** `foliage` is a shape op (CLI only, principle 7): each closed shape becomes a clump built from leaf strokes on a jittered grid, each coloured from the clump lit as a round form (a normal from its bounding ellipse, mixed with the normal of an optional `mass` shape so clumps turn with the whole crown, a key light or a lamp, the underside darker) and stepped into three value families between `shade`, `color` and `lit` (OKLab; by default darker and cooler, lighter and warmer), with more variety in the light; then leaves along the outline, kept more where the outline faces the light or the sky, a few in `glow` on the shadow edge. Strokes are sorted dark to light so lit leaves land on top. It puts how foliage is painted (light families on the clump, the big mass before the texture, a broken silhouette) into one op, so an agent does not scatter leaves like confetti.## Strokes@@ -301,7 +302,7 @@ The editor keeps this record per paint cel. The CLI keeps the final tiles in `.c### Brushes as data-A brush is JSON. The library is built in (`crates/core/brushes/library/`: `ink` inking pen, `pencil`, `marker`, `airbrush`, `soft`, `chalk`, `eraser`, and since M5 the painting set: `flat-bristle`, `round-bristle`, `sponge`, `fog`, `leaves`, `grass`, `splatter`, `wet`, `smudge`, `blender`, `dry-brush`, `two-tone`). The brush window (F5, `editor/brushwin.rs`) edits every setting with a live sample, draws with the edits at once (as a variant id, like the quick tuning), and saves a named brush into the bundle; pictures for tips and textures come in by path or by dropping a PNG on it. The brush fingerprint covers the bundle's pictures when it has any. A bundle embeds every brush its strokes use in `brushes/<id>.json` the first time a stroke with it is written, and from then on that file defines the id for that document, so changing the library never changes an existing render. Lookups go bundle first, then library.+A brush is JSON. The library is built in (`crates/core/brushes/library/`: `ink` inking pen, `pencil`, `marker`, `airbrush`, `soft`, `chalk`, `eraser`, and since M5 the painting set: `flat-bristle`, `round-bristle`, `sponge`, `fog`, `leaves`, `grass`, `splatter`, `wet`, `smudge`, `blender`, `dry-brush`, `two-tone`). The brush window (F5, `editor/brushwin.rs`) edits every setting with a live sample, draws with the edits at once (as a variant id, like the quick tuning), and saves a named brush into the bundle; pictures for tips and textures come in by path or by dropping a PNG on it. The brush fingerprint covers the bundle's pictures when it has any. A tip may hold several pictures (`"more"` beside `"image"`); each dab takes one, chosen by a hash of the stroke's seed and the dab's number so other brushes' random sequences are untouched (`leaves` draws from four leaf shapes since S5.27). A bundle embeds every brush its strokes use in `brushes/<id>.json` the first time a stroke with it is written, and from then on that file defines the id for that document, so changing the library never changes an existing render. Lookups go bundle first, then library.```json{diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.mdindex 830eb36..4260a0e 100644--- a/docs/skill/SKILL.md+++ b/docs/skill/SKILL.md@@ -49,7 +49,7 @@ klad stroke art.draw l4 --brush ink --size 5 --taper 8,20 --path 'M100 100 L140```- `klad brushes art.draw` lists the brushes: the ones the bundle embeds and the library (`ink` inking pen, `pencil`, `marker`, `airbrush`, `soft`, `chalk`, `eraser`, and for painting `flat-bristle`, `round-bristle`, `sponge`, `fog`, `leaves`, `grass`, `splatter`, `wet`, `smudge`, `blender`, `dry-brush`, `two-tone`); the tip column says `+dual`, `+texture`, `+colour`, `+wet`, `+smudge`, `+blend` or `+body`. `--show <id>` prints one as JSON. A bundle keeps every brush it uses, so `ink` in an older bundle can be the older ink; `--brush` takes any id from that list.-- Painting brushes: `wet` picks up the colour under it and mixes it in, `smudge` pulls paint along, `blender` softens what it crosses; all three read only the layer they paint on (paint the colours to mix on one layer). `leaves`, `grass` and `splatter` scatter their picture tips with jittered colour; `two-tone` paints `--second` at a light press and `--color` at a full one. `--second '#e0a040'` (`"second"` in `apply`) is the second colour for brushes with colour dynamics.+- Painting brushes: `wet` picks up the colour under it and mixes it in, `smudge` pulls paint along, `blender` softens what it crosses; all three read only the layer they paint on (paint the colours to mix on one layer). `leaves`, `grass` and `splatter` scatter their picture tips with jittered colour (`leaves` picks one of several leaf shapes per dab: `leaf`, `leaf-oval`, `leaf-lance`, `leaf-twig`; a tip takes more pictures as `{"image":{"image":"leaf","more":["leaf-oval","leaf-lobed"]}}`); `two-tone` paints `--second` at a light press and `--color` at a full one. `--second '#e0a040'` (`"second"` in `apply`) is the second colour for brushes with colour dynamics.- New brushes: write the JSON (copy one from `--show`; keys `tip` (`round`, `chalk` or `{"image":{"image":"name"}}`), `dual`, `grain` (`paper` or `image`, `strength`, `scale`, `contrast`, `pressure`), `color` (`hue`, `saturation`, `value`, `strokeHue`, ..., `pressure`, `along`), `paint` (`wet`, `smudge`, `blend`)) and `klad brushes art.draw --set my-oil brush.json` (`-` reads stdin). Pictures for tips and textures: `klad brushes art.draw --picture bark bark.png` (dark is paint, or the alpha). Ids and pictures are fixed once in the bundle, since strokes keep their brush.- `--taper in,out` thins the first and last px of the line to a point whatever the pressure; without it the brush's taper applies (`ink` is `10,24`), `--taper 0,0` gives round ends. Short hatching wants about `8,20`, long contours `30,80`.- `--pressure` spreads values evenly along the stroke; several subpaths in `--path` make several strokes. `--points 'x,y,p x,y,p'` gives explicit samples.@@ -194,6 +194,7 @@ klad hatch art.draw shade --in body --angle 30 --spacing 8 --length 10-24 --coloklad scatter art.draw lines --in ground --mark "M0 0 Q 3 -22 8 -40" --count 20 --turn -25,25klad paint art.draw paint --in body --color skin --light -1,-1 --weight 12 # a round form, painted from a light modelklad paint art.draw paint --in pillar --form cylinder --axis 90 --lamp 200,600,150 --color '#c9b8a0'+klad foliage art.draw canopy --in clump1 --color '#4d7a3b' --light -0.6,-0.8 --leaf 16 --mass crown # a clump built from lit leavesklad prepare art.draw # buffer every drawing before the user opens it```@@ -202,6 +203,7 @@ klad prepare art.draw- `klad light` takes `--lamp x,y,height` too: each shape is shaded away from the lamp instead of one direction for all.- `klad prepare art.draw [--from 0 --to 23]` replays every painted drawing of those frames into the cache after a big CLI change, so the editor opens and plays it without replaying strokes. The editor still makes its frame pictures itself, quickly, from the cached drawings.+- Foliage: never one leaf picture scattered evenly, and never a smooth blob with leaves sprinkled on its edge; both look fake. Block the crown in as 6 to 12 clump shapes (irregular blobs with lobes) plus one `crown` shape around them all, then for each clump from back to front: fill a darker, slightly smaller core (about 0.82 of the clump, so the sky shows between the edge leaves) and run `foliage` on it with `mass: "crown"`. Every leaf takes its colour from the clump lit as a round form and turned with the whole crown, in three value families from a cool shade through `--color` to a warm `--lit`, with the most variety in the light; leaves along the outline break the silhouette, most where light and sky reach, a few glowing at the shadow edge. Back clumps a darker colour, front ones lighter; leaf size about a fiftieth of the crown's width (`samples/tree`). Far canopies stay soft vector masses.- Ink rules: heavier on the side away from `--light` (the direction the light comes from, -1,-1 is top left), heavier on the silhouette than on inner lines (an outline inside another shape given in the same call), thinner on tight curves, a seeded wobble (`--wobble 0` for none). Outlines split into separate strokes at corners sharper than `--break` (60 degrees); `--gap 3` leaves inkers' gaps where lines meet. Open details (folds, cracks, ribs) go through `--path "M..."`.- `klad light` writes lasso fills with a cut: on the shade layer the shape minus itself moved towards the light (`--soft 3` overlapping steps soften the inner edge), on the rim layer a band along the lit edge. Clip the shade layer (multiply) and the rim layer to the flats, as in `samples/lantern/`.- `samples/lantern/generate.py` is the whole recipe for a prop in about 100 lines; `samples/ink-shapes/` shows the ink options side by side.diff --git a/justfile b/justfileindex 3cdfc56..22313d7 100644--- a/justfile+++ b/justfile@@ -19,7 +19,7 @@ lint:cargo clippy --workspace --all-targets -- -D warningssamples: build- for s in lantern ink-shapes bounce creature courier solids lemons ruin sign; do FORCE=1 bash samples/$s/build.sh >/dev/null && echo "samples/$s/$s.draw"; done+ for s in lantern ink-shapes bounce creature courier solids lemons ruin sign tree; do FORCE=1 bash samples/$s/build.sh >/dev/null && echo "samples/$s/$s.draw"; donenotices:bash licenses/notices.shdiff --git a/samples/README.md b/samples/README.mdindex 157363e..4afa3d6 100644--- a/samples/README.md+++ b/samples/README.md@@ -12,6 +12,7 @@ Drawings made from scratch with the `klad` CLI, each from a generator that print| `ruin` | A game background lit by one lantern: stone blocks with chalk and dry-brush tool marks, relief per pillar facing the lamp, depth planes in fog, glow || `lemons` | Painting by form with `klad paint` on locked flats, and a shadow colour: lavender shadows instead of brown ones (`PLAIN=1`: without it; `RELIEF=1`: with a relief effect on every object, lighting the thickness of the oil strokes) || `sign` | Lettering in fonts that come with klad: a gilded inn sign on a painted board, the text clipped to the board with a shadow and grain over it |+| `tree` | Foliage that reads as leaves: clumps built from leaf marks with `klad foliage`, each lit as a form and turning with the whole crown, leaves breaking the outline, a bark trunk painted as a cylinder || `solids` | Painting stroke by stroke: a sphere, a cube and a cylinder built in 3D with `docs/skill/drawkit.py`, lit, painted with natural strokes |The generated `.draw` bundles and pictures stay out of git.diff --git a/samples/tree/build.sh b/samples/tree/build.shnew file mode 100755index 0000000..3276bdb--- /dev/null+++ b/samples/tree/build.sh@@ -0,0 +1,21 @@+#!/usr/bin/env bash+set -euo pipefail+here="$(cd "$(dirname "$0")" && pwd)"+root="$(cd "$here/../.." && pwd)"+case "$(uname -s)" in+ Darwin) built=target ;;+ Linux) built=target/linux ;;+ *) built=target/windows ;;+esac+klad="${KLAD:-$root/${KLAD_TARGET_DIR:-$built}/release/klad}"+out="${1:-$here/tree.draw}"+if [ -e "$out" ] && [ "${FORCE:-0}" != 1 ]; then+ echo "$out exists and may hold edits made in the editor; give another path, or FORCE=1 to rebuild it from generate.py" >&2+ exit 1+fi+rm -rf "$out"+"$klad" new "$out" --width 1024 --height 1280 --layers 0 >/dev/null+python3 "$here/generate.py" | "$klad" apply "$out" >/dev/null+"$klad" render "$out" -o "${out%.draw}.png"+"$klad" export "$out" --scale 2 -o "${out%.draw}@2x.png"+"$klad" hash "$out" --no-cachediff --git a/samples/tree/generate.py b/samples/tree/generate.pynew file mode 100644index 0000000..4ed998f--- /dev/null+++ b/samples/tree/generate.py@@ -0,0 +1,126 @@+import json+import math+import random++LIGHT = [-0.6, -0.8]+KEY = "#fff0cf"+GROUND = 1176+COLOURS = {"bark": "#5d4a3a", "bark dark": "#3b2f27", "leaf back": "#3c6233", "leaf": "#4d7a3b", "leaf front": "#5a8740",+ "grass": "#4a7034", "deep": "#25392a"}++CLUMPS = [+ ("clump1", 318, 452, 170, 128, "leaf back", 3),+ ("clump2", 700, 436, 182, 136, "leaf back", 5),+ ("clump3", 512, 300, 206, 150, "leaf back", 7),+ ("clump4", 238, 610, 150, 112, "leaf", 11),+ ("clump5", 790, 600, 160, 116, "leaf", 13),+ ("clump6", 508, 520, 214, 150, "leaf", 17),+ ("clump7", 390, 700, 150, 104, "leaf front", 19),+ ("clump8", 640, 704, 156, 106, "leaf front", 23),+ ("clump9", 470, 390, 150, 108, "leaf front", 29),+]+++def path(points, closed=True):+ d = "M" + " L".join(f"{x:.1f} {y:.1f}" for x, y in points)+ return d + (" Z" if closed else "")+++def blob(cx, cy, rx, ry, seed, count=72):+ rnd = random.Random(seed)+ waves = [(rnd.randint(3, 5), rnd.uniform(0, math.tau), rnd.uniform(0.08, 0.12)),+ (rnd.randint(6, 9), rnd.uniform(0, math.tau), rnd.uniform(0.06, 0.09)),+ (rnd.randint(13, 17), rnd.uniform(0, math.tau), rnd.uniform(0.02, 0.035))]+ points = []+ for i in range(count):+ a = math.tau * i / count+ r = 1 + sum(amp * math.sin(k * a + ph) for k, ph, amp in waves)+ r *= 1 - 0.07 * max(0.0, math.sin(a))+ points.append((cx + rx * r * math.cos(a), cy + ry * r * math.sin(a)))+ return path(points)+++def limb(points, w0, w1):+ left, right = [], []+ for i, (x, y) in enumerate(points):+ a, b = points[max(i - 1, 0)], points[min(i + 1, len(points) - 1)]+ dx, dy = b[0] - a[0], b[1] - a[1]+ d = math.hypot(dx, dy) or 1+ w = (w0 + (w1 - w0) * i / (len(points) - 1)) / 2+ left.append((x - dy / d * w, y + dx / d * w))+ right.append((x + dy / d * w, y - dx / d * w))+ return path(left + right[::-1])+++def trunk():+ left = [(408, GROUND + 6), (446, GROUND - 14), (466, GROUND - 70), (470, 1020), (474, 900), (480, 800), (486, 700)]+ right = [(544, 700), (548, 800), (552, 900), (556, 1020), (560, GROUND - 70), (582, GROUND - 16), (626, GROUND + 6)]+ return path(left + right + [(560, GROUND + 14), (512, GROUND + 18), (462, GROUND + 14)])+++LIMBS = [+ ([(500, 760), (470, 690), (420, 620), (360, 560)], 40, 14),+ ([(528, 750), (566, 676), (622, 606), (690, 540)], 38, 14),+ ([(514, 720), (512, 620), (506, 520), (500, 420)], 36, 12),+ ([(470, 690), (420, 700), (330, 660)], 18, 8),+]+++def layer(id, kind, **extra):+ return {"op": "add", "layer": {"id": id, "kind": kind, "name": id, **extra}}+++def wood(shape, axis, seed):+ return {"op": "paint", "layer": "wood", "in": [shape], "color": COLOURS["bark"], "form": "cylinder", "axis": axis,+ "light": LIGHT, "key": KEY, "shadow": "#4a4660", "shadowMix": 0.5, "weight": 9, "decisive": 0.6, "seed": seed}+++def ops():+ out = [{"op": "palette", "add": c, "name": n} for n, c in COLOURS.items()]+ out += [+ layer("sketch", "vector", visible=False),+ layer("ground", "vector"),+ layer("wood", "paint"),+ layer("canopy", "paint"),+ layer("grass", "paint"),+ ]+ sketch = [("trunk", trunk())] + [(f"limb{i}", limb(*l)) for i, l in enumerate(LIMBS)]+ sketch += [(cid, blob(cx, cy, rx, ry, seed)) for cid, cx, cy, rx, ry, _, seed in CLUMPS]+ sketch += [(f"{cid}-core", blob(cx, cy + 6, rx * 0.84, ry * 0.8, seed)) for cid, cx, cy, rx, ry, _, seed in CLUMPS]+ sketch.append(("crown", blob(510, 500, 430, 330, 41)))+ sketch.append(("base", path([(380, GROUND - 6), (650, GROUND - 6), (650, GROUND + 26), (380, GROUND + 26)])))+ out += [{"op": "add", "node": {"id": sid, "type": "path", "d": d}, "in": "sketch"} for sid, d in sketch]+ out.append({"op": "add", "node": {"type": "ellipse", "cx": 520, "cy": GROUND + 8, "rx": 300, "ry": 34, "fill": "#1d2a1666",+ "blur": 14}, "in": "ground"})+ out.append({"op": "add", "node": {"type": "ellipse", "cx": 500, "cy": GROUND + 4, "rx": 120, "ry": 16, "fill": "#14200f99",+ "blur": 6}, "in": "ground"})+ for sid in ["trunk"] + [f"limb{i}" for i in range(len(LIMBS))]:+ out.append({"op": "fill", "layer": "wood", "shape": sid, "color": "bark", "expand": 1})+ out.append({"op": "set", "id": "wood", "lockAlpha": True})+ out.append(wood("trunk", 92, 2))+ out += [wood(f"limb{i}", [125, 52, 92, 160][i], 3 + i) for i in range(len(LIMBS))]+ out.append({"op": "stroke", "layer": "wood", "brush": "soft", "size": 90, "color": "#2b2622", "opacity": 0.55,+ "path": "M512 720 L 512 900", "pressure": [1, 0.7, 0.1]})+ rnd = random.Random(31)+ for i in range(46):+ t = rnd.random()+ x = 470 + 84 * t + rnd.uniform(-4, 4)+ top, bottom = rnd.uniform(760, 1000), rnd.uniform(1040, GROUND - 10)+ lit = t < 0.4 and rnd.random() < 0.7+ points = [(x + 3 * math.sin(y * 0.03 + i), y) for y in range(int(top), int(bottom), 24)]+ out.append({"op": "stroke", "layer": "wood", "brush": "dry-brush", "size": rnd.uniform(3, 7),+ "color": "#8a735c" if lit else "#2f261f", "opacity": rnd.uniform(0.3, 0.6),+ "path": path(points, False), "pressure": [0.2, 0.9, 1, 0.8, 0.15]})+ out.append({"op": "set", "id": "wood", "lockAlpha": False})+ out.append({"op": "set", "id": "wood", "effects": [{"relief": {"light": LIGHT, "strength": 1.6, "softness": 1.6}}]})+ for cid, cx, cy, rx, ry, colour, seed in CLUMPS:+ out.append({"op": "fill", "layer": "canopy", "shape": f"{cid}-core", "color": "deep", "expand": 0})+ out.append({"op": "foliage", "layer": "canopy", "in": [cid], "color": COLOURS[colour], "light": LIGHT,+ "leaf": 17, "mass": "crown", "seed": seed})+ out.append({"op": "scatter", "layer": "grass", "in": ["base"], "mark": "M0 0 Q 2 -16 6 -30", "count": 70,+ "size": [0.7, 1.4], "turn": [-25, 25], "weight": 4, "brush": "ink", "color": "grass", "seed": 5})+ return out+++if __name__ == "__main__":+ print("\n".join(json.dumps(op) for op in ops()))