A drawing app built for agent/human collaboration
Rust
Grass grows in species: fine, broad, dry, seed heads and clover
Indicode BV8484cbbfe524
diff --git a/crates/brush/src/images.rs b/crates/brush/src/images.rsindex c2435f1..a8a3608 100644--- a/crates/brush/src/images.rs+++ b/crates/brush/src/images.rs@@ -209,6 +209,37 @@ fn leaf_twig(u: f32, v: f32) -> f32 {.max(small(-0.35, 0.3, 0.95, 0.36))}+fn seed_head(u: f32, v: f32) -> f32 {+ let stem = match u > -1.0 && u < 0.92 {+ true => 1.0 - smoothstep(0.018, 0.035, (v - 0.04 * u * u).abs()),+ false => 0.0,+ };+ (0..9).fold(stem, |most, k| {+ let along = -0.7 + 0.18 * k as f32;+ let side = if k % 2 == 0 { 1.0 } else { -1.0 };+ let turn = side * (0.75 - 0.04 * k as f32);+ let (s, c) = (libm::sinf(turn), libm::cosf(turn));+ let (du, dv) = (u - along - 0.1, v - 0.04 * along * along - side * 0.1);+ let (lu, lv) = ((du * c + dv * s) / 0.2, (dv * c - du * s) / 0.2);+ most.max(blade(lu, lv, 0.28 * libm::powf((1.0 - lu * lu).max(0.0), 0.7), 0.0))+ })+}++fn trefoil(u: f32, v: f32) -> f32 {+ (0..3).fold(0.0f32, |most, k| {+ let a = -std::f32::consts::FRAC_PI_2 + k as f32 * std::f32::consts::TAU / 3.0;+ let (cx, cy) = (0.36 * libm::cosf(a), 0.36 * libm::sinf(a));+ let lobe = |ox: f32, oy: f32| {+ let d = libm::sqrtf((u - cx - ox).powi(2) + (v - cy - oy).powi(2));+ 1.0 - smoothstep(0.24, 0.3, d)+ };+ let (px, py) = (-libm::sinf(a) * 0.1, libm::cosf(a) * 0.1);+ let vein =+ 1.0 - 0.5 * (1.0 - smoothstep(0.012, 0.03, ((u - cx) * libm::sinf(a) - (v - cy) * libm::cosf(a)).abs()));+ most.max(lobe(px, py).max(lobe(-px, -py)) * vein)+ })+}+fn grass(u: f32, v: f32) -> f32 {let height = (1.0 - v) / 2.0;(0..5).fold(0.0f32, |most, k| {@@ -247,6 +278,8 @@ pub fn library_tip(name: &str) -> Option<TipMask> {"leaf-lance" => leaf_lance,"leaf-lobed" => leaf_lobed,"leaf-twig" => leaf_twig,+ "seed-head" => seed_head,+ "trefoil" => trefoil,_ => return None,};let data = (0..TIP_SIZE * TIP_SIZE)diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rsindex 57a5a06..6cf3238 100644--- a/crates/cli/src/main.rs+++ b/crates/cli/src/main.rs@@ -1200,6 +1200,11 @@ enum Command {patch: Option<f32>,#[arg(long, default_value = "blade")]brush: String,+ #[arg(+ long,+ help = "The species, as JSON: [{\"name\":\"fine\",\"share\":0.5,\"width\":0.7},{\"brush\":\"my-clover\",\"low\":true,\"share\":0.2}] (default: a meadow mix of fine, broad, dry, seed heads and clover)"+ )]+ kinds: Option<String>,#[arg(long, default_value_t = 1)]seed: u32,#[arg(long, default_value_t = 0)]@@ -2574,11 +2579,18 @@ fn run() -> Result<()> {edge,patch,brush,+ kinds,seed,frame,part,flags,} => {+ let kinds = match kinds {+ Some(text) => {+ serde_json::from_str(&text).map_err(|e| anyhow!("--kinds is not a list of species: {e}"))?+ }+ None => Vec::new(),+ };let lamp = lamp.as_deref().map(|l| -> Result<[f32; 3]> {@@ -2604,6 +2616,7 @@ fn run() -> Result<()> {edge,patch,brush,+ kinds,seed,part,};diff --git a/crates/cli/src/shapes.rs b/crates/cli/src/shapes.rsindex ccaeb0b..c89b2fc 100644--- a/crates/cli/src/shapes.rs+++ b/crates/cli/src/shapes.rs@@ -3,7 +3,8 @@ use klad_core::bundle::Bundle;use klad_core::color;use klad_core::doc::Document;use klad_core::ops::{- FillSpec, FoliageSpec, GrassSpec, HatchSpec, InkSpec, LightSpec, Op, PaintSpec, ScatterSpec, StrokeSpec, apply_all,+ FillSpec, FoliageSpec, GrassKind, GrassSpec, 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};@@ -540,6 +541,83 @@ fn field(x: f32, y: f32, seed: u32) -> f32 {at(x, y, 0x51) * 0.7 + at(x * 2.3 + 17.0, y * 2.3 + 5.0, 0xa7) * 0.3}+struct Kind {+ share: f32,+ brush: String,+ picture: bool,+ length: f32,+ width: f32,+ curl: f32,+ spread: f32,+ palette: [[f32; 3]; 3],+ head: Option<(String, f32)>,+ low: bool,+ patchy: f32,+}++fn turn_hue(lab: [f32; 3], degrees: f32) -> [f32; 3] {+ let (s, c) = degrees.to_radians().sin_cos();+ [lab[0], lab[1] * c - lab[2] * s, lab[1] * s + lab[2] * c]+}++fn default_kinds(mid: [f32; 3]) -> Vec<GrassKind> {+ let straw = [mid[0] + 0.08, mid[1] * 0.2 + 0.012, mid[2] * 0.5 + 0.06];+ let kind = |name: &str, share: f32| GrassKind {+ name: Some(name.into()),+ share,+ brush: None,+ length: 1.0,+ width: 1.0,+ curl: 0.0,+ spread: 0.0,+ color: None,+ hue: 0.0,+ head: None,+ head_size: 0.32,+ low: false,+ patchy: 0.5,+ };+ vec![+ GrassKind {+ width: 0.7,+ curl: 0.12,+ ..kind("fine", 0.44)+ },+ GrassKind {+ length: 0.72,+ width: 1.7,+ curl: 0.55,+ hue: -10.0,+ patchy: 0.6,+ ..kind("broad", 0.24)+ },+ GrassKind {+ length: 0.9,+ width: 0.55,+ curl: 0.3,+ color: Some(color::to_hex(color::from_oklab(straw, 1.0))),+ ..kind("dry", 0.1)+ },+ GrassKind {+ length: 1.45,+ width: 0.3,+ curl: 0.1,+ hue: 6.0,+ head: Some("seed-head".into()),+ patchy: 0.7,+ ..kind("heads", 0.06)+ },+ GrassKind {+ brush: Some("clover".into()),+ length: 0.5,+ hue: -14.0,+ low: true,+ patchy: 0.85,+ ..kind("clover", 0.16)+ },+ ]+}+fn grass(doc: &Document, bundle: &Bundle, spec: &GrassSpec) -> Result<Vec<Op>> {let found = areas(doc, &spec.within, &None, "grass")?;let colour = |text: &str| -> Result<[f32; 3]> { Ok(color::to_oklab(color::parse_hex(&doc.resolve_color(text)?)?)) };@@ -553,10 +631,50 @@ fn grass(doc: &Document, bundle: &Bundle, spec: &GrassSpec) -> Result<Vec<Op>> {let lit = given(&spec.lit, [0.16, -0.012, 0.05])?;let shade = given(&spec.shade, [-0.2, -0.01, -0.04])?;let hex = |lab: [f32; 3]| color::to_hex(color::from_oklab(lab, 1.0));- let picture = klad_brush::BrushSet::for_bundle(bundle)?- .def(&spec.brush)- .map(|d| matches!(d.tip, klad_core::brushes::TipDef::Image { .. }))- .ok_or_else(|| anyhow::anyhow!("no brush {}: klad brushes lists them", spec.brush))?;+ let brushes = klad_brush::BrushSet::for_bundle(bundle)?;+ let pictured = |id: &str| -> Result<bool> {+ brushes+ .def(id)+ .map(|d| matches!(d.tip, klad_core::brushes::TipDef::Image { .. }))+ .ok_or_else(|| anyhow::anyhow!("no brush {id}: klad brushes lists them"))+ };+ let listed = match spec.kinds.is_empty() {+ true => default_kinds(mid),+ false => spec.kinds.clone(),+ };+ let kinds: Vec<Kind> = listed+ .iter()+ .map(|k| {+ let brush = k.brush.clone().unwrap_or_else(|| spec.brush.clone());+ let palette = match &k.color {+ Some(c) => {+ let own = colour(c)?;+ [+ std::array::from_fn(|i| own[i] + [-0.2, -0.01, -0.04][i]),+ own,+ std::array::from_fn(|i| own[i] + [0.14, -0.008, 0.04][i]),+ ]+ }+ None => [turn_hue(shade, k.hue), turn_hue(mid, k.hue), turn_hue(lit, k.hue)],+ };+ if let Some(head) = &k.head {+ pictured(head)?;+ }+ Ok(Kind {+ share: k.share.max(0.0),+ picture: pictured(&brush)?,+ brush,+ length: k.length,+ width: k.width,+ curl: k.curl,+ spread: k.spread,+ palette,+ head: k.head.clone().map(|h| (h, k.head_size)),+ low: k.low,+ patchy: k.patchy.clamp(0.0, 1.0),+ })+ })+ .collect::<Result<_>>()?;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]));@@ -576,44 +694,127 @@ fn grass(doc: &Document, bundle: &Bundle, spec: &GrassSpec) -> Result<Vec<Op>> {None => [spec.light[0] / flat, spec.light[1] / flat],}};- let mound = |p: P| {+ let ground = |p: P, salt: u32, size: f32| {let s = scale(p[1]);- field(p[0] / (patch * s), p[1] / (patch * 0.3 * s), spec.seed)+ field(p[0] / (size * s), p[1] / (size * 0.3 * s), spec.seed ^ salt)};+ let mound = |p: P| ground(p, 0, patch);let tone_at = |p: P| -> f32 {let l = towards(p);let d = patch * 0.25;let facing = mound([p[0] - l[0] * d, p[1] - l[1] * d]) - mound([p[0] + l[0] * d, p[1] + l[1] * d]);- let raw = 0.5 + 1.3 * facing + 0.3 * (mound(p) - 0.5);+ let raw = 0.5 + 1.0 * facing + 0.25 * (mound(p) - 0.5);let near = 0.6 + 0.4 * depth(p[1]);(0.5 + (raw - 0.5) * near).clamp(0.0, 1.0)};let step = |tone: f32| (tone * 3.0).floor().min(2.0) / 3.0 + 1.0 / 6.0;- let shaded = |tone: f32| -> [f32; 3] {+ let shaded = |palette: &[[f32; 3]; 3], tone: f32| -> [f32; 3] {match tone < 0.5 {- true => mix_lab(shade, mid, (tone * 2.0).clamp(0.0, 1.0)),- false => mix_lab(mid, lit, (tone * 2.0 - 1.0).clamp(0.0, 1.0)),+ true => mix_lab(palette[0], palette[1], (tone * 2.0).clamp(0.0, 1.0)),+ false => mix_lab(palette[1], palette[2], (tone * 2.0 - 1.0).clamp(0.0, 1.0)),+ }+ };+ let choose = |rng: &mut klad_core::rng::Rng, p: P, upright: bool| -> Option<usize> {+ let weights: Vec<f32> = kinds+ .iter()+ .enumerate()+ .map(|(i, k)| {+ if upright && k.low {+ return 0.0;+ }+ let n = ground(p, 0x9e37 + i as u32 * 977, patch * 1.3);+ let t = ((n - 0.4) / 0.35).clamp(0.0, 1.0);+ let detail = match k.head.is_some() || k.low {+ true => (depth(p[1]) * 1.5 - 0.3).clamp(0.05, 1.0),+ false => 1.0,+ };+ detail * k.share * (1.0 - k.patchy + k.patchy * 2.2 * t * t * (3.0 - 2.0 * t))+ })+ .collect();+ let total: f32 = weights.iter().sum();+ if total <= 0.0 {+ return None;}+ let mut pick = (rng.signed() + 1.0) / 2.0 * total;+ weights+ .iter()+ .position(|w| {+ pick -= w;+ pick <= 0.0+ })+ .or(Some(kinds.len() - 1))};let mut rng = klad_core::rng::Rng::new(spec.seed as u64 * 6_271 + 3);- let mut blades: Vec<(f32, Op)> = Vec::new();- let mut blade = |rng: &mut klad_core::rng::Rng, root: P, length: f32, tall: f32| -> Result<()> {+ let mut marks: Vec<(f32, Op)> = Vec::new();+ let push = |marks: &mut Vec<(f32, Op)>,+ key: f32,+ brush: &str,+ first: [f32; 3],+ second: [f32; 3],+ size: f32,+ run: Run|+ -> Result<()> {+ let seed = spec.seed.wrapping_mul(1_299_709).wrapping_add(marks.len() as u32 * 7);+ let mut value = json!({+ "layer": spec.layer, "frame": spec.frame, "brush": brush, "color": hex(first), "second": hex(second),+ "size": size, "points": run, "seed": seed, "taper": [0.0, 0.0],+ });+ if let Some(part) = &spec.part {+ value["part"] = json!(part);+ }+ marks.push((key, Op::Stroke(serde_json::from_value(value)?)));+ Ok(())+ };+ let stamp = |at: P, dir: P| -> Run {+ let (a, b) = (+ [at[0] - dir[0] * 0.5, at[1] - dir[1] * 0.5],+ [at[0] + dir[0] * 0.5, at[1] + dir[1] * 0.5],+ );+ vec![[a[0], a[1], 1.0], [b[0], b[1], 1.0]]+ };+ let grow = |rng: &mut klad_core::rng::Rng,+ marks: &mut Vec<(f32, Op)>,+ root: P,+ length: f32,+ tall: f32,+ upright: bool|+ -> Result<()> {+ let Some(k) = choose(rng, root, upright).map(|i| &kinds[i]) else {+ return Ok(());+ };let s = scale(root[1]);- let lean = (spec.wind + rng.signed() * 14.0).to_radians();- let dir = [lean.sin(), -lean.cos()];- let side = [-dir[1], dir[0]];- let length = length * s * tall;- let bend = length * (0.08 + 0.08 * rng.signed().abs()) * if spec.wind < 0.0 { -1.0 } else { 1.0 };let tone = tone_at(root);let family = step(tone) + (tone - step(tone)) * 0.55;- let l = towards(root);- let catches = (dir[0] * l[0] + dir[1] * l[1]).max(0.0) * 0.15;- let base = shaded((family - 0.28).max(0.0));- let top = shaded((family + 0.12 + catches + rng.signed() * 0.05 * (0.3 + family)).clamp(0.0, 1.0));- let jitter = |lab: [f32; 3], r: &mut klad_core::rng::Rng| {- [lab[0] + r.signed() * 0.02, lab[1], lab[2] + r.signed() * 0.008]+ let vary = |lab: [f32; 3], r: &mut klad_core::rng::Rng| {+ let turned = turn_hue(lab, r.signed() * 7.0);+ let chroma = 1.0 + r.signed() * 0.18;+ [turned[0] + r.signed() * 0.025, turned[1] * chroma, turned[2] * chroma]};- let (base, top) = (jitter(base, rng), jitter(top, rng));+ if k.low {+ let size = length * k.length * s * (0.8 + 0.4 * (rng.signed() + 1.0) / 2.0);+ let turn = (rng.signed() * 70.0).to_radians();+ let dir = [turn.sin(), -turn.cos()];+ let at = [root[0] + dir[0] * size * 0.2, root[1] - size * 0.15];+ let lab = vary(shaded(&k.palette, (family - 0.12).max(0.0)), rng);+ return push(+ marks,+ root[1] - spec.blade * 0.3 * s,+ &k.brush,+ lab,+ lab,+ size,+ stamp(at, dir),+ );+ }+ let lean = (spec.wind + rng.signed() * (14.0 + k.spread)).to_radians();+ let dir = [lean.sin(), -lean.cos()];+ let side = [-dir[1], dir[0]];+ let length = length * k.length * s * tall;+ let flop = match k.curl > 0.3 && rng.signed() < -0.2 {+ true => -1.0,+ false => 1.0,+ } * if spec.wind < 0.0 { -1.0 } else { 1.0 };+ let bend = length * (0.08 + 0.08 * rng.signed().abs() + k.curl * 0.45 * rng.signed().abs()) * flop;let at = |t: f32| -> [f32; 2] {let curve = bend * t * t;[@@ -621,32 +822,77 @@ fn grass(doc: &Document, bundle: &Bundle, spec: &GrassSpec) -> Result<Vec<Op>> {root[1] + dir[1] * length * t + side[1] * curve,]};- let (run, size): (Run, f32) = match picture {- true => {- let (a, b) = (at(0.48), at(0.52));- (vec![[a[0], a[1], 1.0], [b[0], b[1], 1.0]], length)- }- false => (- [(0.0, 1.0), (0.3, 0.85), (0.6, 0.55), (0.85, 0.25), (1.0, 0.05)]- .iter()- .map(|&(t, p)| {- let q = at(t);- [q[0], q[1], p]- })- .collect(),- width * s * (0.8 + 0.4 * (rng.signed() + 1.0) / 2.0),+ let l = towards(root);+ let catches = (dir[0] * l[0] + dir[1] * l[1]).max(0.0) * 0.15;+ let base = vary(shaded(&k.palette, (family - 0.28).max(0.0)), rng);+ let top = vary(+ shaded(+ &k.palette,+ (family + 0.12 + catches + rng.signed() * 0.05 * (0.3 + family)).clamp(0.0, 1.0),),- };- let seed = spec.seed.wrapping_mul(1_299_709).wrapping_add(blades.len() as u32 * 7);- let mut value = json!({- "layer": spec.layer, "frame": spec.frame, "brush": spec.brush,- "color": hex(if picture { mix_lab(base, top, 0.45) } else { base }), "second": hex(top),- "size": size, "points": run, "seed": seed, "taper": [0.0, 0.0],- });- if let Some(part) = &spec.part {- value["part"] = json!(part);+ rng,+ );+ if k.picture {+ let (a, b) = (at(0.48), at(0.52));+ let d = [(b[0] - a[0]) / 0.04, (b[1] - a[1]) / 0.04];+ let n = (d[0] * d[0] + d[1] * d[1]).sqrt().max(1e-4);+ push(+ marks,+ root[1],+ &k.brush,+ mix_lab(base, top, 0.7),+ top,+ length,+ stamp(at(0.5), [d[0] / n, d[1] / n]),+ )?;+ return Ok(());+ }+ let blunt = 0.04 + 0.22 * (rng.signed() + 1.0) / 2.0 * (rng.signed() > 0.3) as i32 as f32;+ let run: Run = [+ (0.0, 1.0),+ (0.3, 0.85),+ (0.6, 0.55),+ (0.85, 0.25 + blunt * 0.5),+ (1.0, blunt),+ ]+ .iter()+ .map(|&(t, p)| {+ let q = at(t);+ [q[0], q[1], p]+ })+ .collect();+ let size = width * k.width * s * (0.8 + 0.4 * (rng.signed() + 1.0) / 2.0);+ push(marks, root[1], &k.brush, base, top, size, run)?;+ if family > 0.55 && rng.signed() > -0.2 {+ let toward = if side[0] * l[0] + side[1] * l[1] > 0.0 {+ 1.0+ } else {+ -1.0+ };+ let glint: Run = [(0.3, 0.2), (0.6, 0.8), (0.88, 0.1)]+ .iter()+ .map(|&(t, p)| {+ let q = at(t);+ [+ q[0] + side[0] * size * 0.22 * toward,+ q[1] + side[1] * size * 0.22 * toward,+ p,+ ]+ })+ .collect();+ let shine = [top[0] + 0.06, top[1] * 0.9, top[2] * 0.9 + 0.01];+ push(marks, root[1] + 0.01, &k.brush, shine, shine, size * 0.4, glint)?;+ }+ if let Some((head, share)) = &k.head {+ let (a, b) = (at(0.96), at(1.0));+ let d = [b[0] - a[0], b[1] - a[1]];+ let n = (d[0] * d[0] + d[1] * d[1]).sqrt().max(1e-4);+ let d = [d[0] / n, d[1] / n];+ let size = length * share;+ let centre = [b[0] + d[0] * size * 0.35, b[1] + d[1] * size * 0.35];+ let ripe = mix_lab(top, [top[0] + 0.05, top[1] * 0.4 + 0.01, top[2] * 0.7 + 0.04], 0.6);+ push(marks, root[1] + 0.02, head, ripe, ripe, size, stamp(centre, d))?;}- blades.push((root[1], Op::Stroke(serde_json::from_value(value)?)));Ok(())};let gap = |y: f32| (width * scale(y) * 1.3 / spec.density.max(0.05)).max(1.0);@@ -658,7 +904,7 @@ fn grass(doc: &Document, bundle: &Bundle, spec: &GrassSpec) -> Result<Vec<Op>> {if inside(&found, root) {let tall = 0.75 + 0.5 * mound(root);let length = spec.blade * (0.55 + 0.45 * (rng.signed() + 1.0) / 2.0);- blade(&mut rng, root, length, tall)?;+ grow(&mut rng, &mut marks, root, length, tall, false)?;}x += gap(y) * 1.2;}@@ -680,10 +926,17 @@ fn grass(doc: &Document, bundle: &Bundle, spec: &GrassSpec) -> Result<Vec<Op>> {p[1] - n[1] * spec.blade * scale(p[1]) * 0.12,];let length = spec.blade * (0.6 + 0.5 * (rng.signed() + 1.0) / 2.0);- blade(&mut rng, root, length, spec.edge * (0.8 + 0.45 * mound(root)))+ grow(+ &mut rng,+ &mut marks,+ root,+ length,+ spec.edge * (0.8 + 0.45 * mound(root)),+ true,+ )})?;- blades.sort_by(|a, b| a.0.total_cmp(&b.0));- Ok(blades.into_iter().map(|(_, op)| op).collect())+ marks.sort_by(|a, b| a.0.total_cmp(&b.0));+ Ok(marks.into_iter().map(|(_, op)| op).collect())}fn shapes_change(op: &Op) -> bool {@@ -808,27 +1061,42 @@ mod tests {.unwrap();let made = expand(&b, ops.clone()).unwrap();assert_eq!(made, expand(&b, ops).unwrap(), "seeded");- let blades: Vec<(P, P, f32, String, Option<String>)> = made+ let marks: Vec<&StrokeSpec> = made.iter().filter_map(|o| match o {- Op::Stroke(s) => {- let p = s.points.as_ref()?;- Some((- [p[0][0], p[0][1]],- [p[p.len() - 1][0], p[p.len() - 1][1]],- s.size,- s.color.clone(),- s.second.clone(),- ))- }+ Op::Stroke(s) => Some(s),_ => None,}).collect();- assert!(blades.len() > 500, "{} blades", blades.len());+ let kinds: std::collections::BTreeSet<&str> = marks.iter().map(|s| s.brush.as_str()).collect();+ assert_eq!(+ kinds,+ ["blade", "clover", "seed-head"].into(),+ "the meadow mix grows several species"+ );+ let light = |hex: &str| color::to_oklab(color::parse_hex(hex).unwrap());assert!(- blades.windows(2).all(|w| w[0].0[1] <= w[1].0[1]),- "far blades are drawn first"+ marks+ .iter()+ .filter(|s| s.brush == "blade" && light(&s.color)[2] > 0.09)+ .count()+ > 20,+ "some blades are dry straw");+ let blades: Vec<(P, P, String, Option<String>)> = marks+ .iter()+ .filter(|s| s.brush == "blade" && s.points.as_ref().is_some_and(|p| p.len() == 5))+ .map(|s| {+ let p = s.points.as_ref().unwrap();+ (+ [p[0][0], p[0][1]],+ [p[4][0], p[4][1]],+ s.color.clone(),+ s.second.clone(),+ )+ })+ .collect();+ assert!(blades.len() > 400, "{} blades", blades.len());let long = |pick: &dyn Fn(f32) -> bool| {let chosen: Vec<f32> = blades.iter()@@ -844,13 +1112,22 @@ mod tests {blades.iter().filter(|b| b.1[1] < 140.0).count() > 10,"the top edge is broken by blades");- let light = |hex: &str| color::to_oklab(color::parse_hex(hex).unwrap())[0];assert!(blades.iter()- .all(|b| b.4.as_deref().is_some_and(|tip| light(tip) > light(&b.3))),+ .all(|b| b.3.as_deref().is_some_and(|tip| light(tip)[0] > light(&b.2)[0])),"each blade is darker at the root than at the tip");+ let heads = |pick: &dyn Fn(f32) -> bool| {+ marks+ .iter()+ .filter(|s| s.brush == "seed-head" && s.points.as_ref().is_some_and(|p| pick(p[0][1])))+ .count()+ };+ assert!(+ heads(&|y| y > 220.0) > heads(&|y| y < 180.0) * 2,+ "seed heads thin out with distance"+ );std::fs::remove_dir_all(&dir).unwrap();}diff --git a/crates/core/brushes/library/blade.json b/crates/core/brushes/library/blade.jsonindex 7a5284b..9c3c480 100644--- a/crates/core/brushes/library/blade.json+++ b/crates/core/brushes/library/blade.json@@ -4,5 +4,6 @@"tip": { "round": { "hardness": 0.85 } },"spacing": 0.12,"dynamics": { "size": { "pressure": { "min": 0.06 } } },- "color": { "value": 0.03, "strokeValue": 0.03, "pressure": { "min": 0.0 } }+ "color": { "value": 0.03, "strokeValue": 0.03, "pressure": { "min": 0.0 } },+ "grain": { "paper": { "seed": 31, "feature": 2 }, "strength": 0.18 }}diff --git a/crates/core/brushes/library/clover.json b/crates/core/brushes/library/clover.jsonnew file mode 100644index 0000000..d585c64--- /dev/null+++ b/crates/core/brushes/library/clover.json@@ -0,0 +1,9 @@+{+ "format": "draw-anything-brush/1",+ "name": "Clover",+ "tip": { "image": { "image": "trefoil" } },+ "spacing": 1.0,+ "angle": "follow",+ "jitter": { "size": 0.3, "angle": 0.6 },+ "color": { "hue": 4.0, "value": 0.05, "saturation": 0.05 }+}diff --git a/crates/core/brushes/library/seed-head.json b/crates/core/brushes/library/seed-head.jsonnew file mode 100644index 0000000..1609ab1--- /dev/null+++ b/crates/core/brushes/library/seed-head.json@@ -0,0 +1,9 @@+{+ "format": "draw-anything-brush/1",+ "name": "Seed head",+ "tip": { "image": { "image": "seed-head" } },+ "spacing": 1.0,+ "angle": "follow",+ "jitter": { "size": 0.2, "angle": 0.12 },+ "color": { "value": 0.05, "saturation": 0.05 }+}diff --git a/crates/core/src/brushes.rs b/crates/core/src/brushes.rsindex cb4667c..202d94f 100644--- a/crates/core/src/brushes.rs+++ b/crates/core/src/brushes.rs@@ -22,6 +22,8 @@ const LIBRARY: &[(&str, &str)] = &[("leaves", include_str!("../brushes/library/leaves.json")),("grass", include_str!("../brushes/library/grass.json")),("blade", include_str!("../brushes/library/blade.json")),+ ("seed-head", include_str!("../brushes/library/seed-head.json")),+ ("clover", include_str!("../brushes/library/clover.json")),("splatter", include_str!("../brushes/library/splatter.json")),("wet", include_str!("../brushes/library/wet.json")),("smudge", include_str!("../brushes/library/smudge.json")),@@ -96,7 +98,7 @@ pub enum TipDef {},}-pub const TIP_IMAGES: [&str; 10] = [+pub const TIP_IMAGES: [&str; 12] = ["bristle-flat","bristle-round","sponge",@@ -107,6 +109,8 @@ pub const TIP_IMAGES: [&str; 10] = ["leaf-lance","leaf-lobed","leaf-twig",+ "seed-head",+ "trefoil",];#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]@@ -532,7 +536,7 @@ mod tests {let back = BrushDef::parse(&def.to_json().unwrap()).unwrap();assert_eq!(back, def, "{id}");});- assert_eq!(library_ids().len(), 22);+ assert_eq!(library_ids().len(), 24);assert!(library("ink").unwrap().taper[1] > 0.0);assert_eq!(legacy_m1("ink").unwrap().taper, [0.0, 0.0]);assert!(legacy_m1("marker").is_none());diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rsindex f917e69..dc965e1 100644--- a/crates/core/src/ops.rs+++ b/crates/core/src/ops.rs@@ -608,12 +608,53 @@ pub struct GrassSpec {pub patch: Option<f32>,#[serde(default = "grass_brush")]pub brush: String,+ #[serde(default)]+ pub kinds: Vec<GrassKind>,#[serde(default = "first_seed")]pub seed: u32,#[serde(default)]pub part: Option<String>,}+#[derive(Clone, Debug, PartialEq, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct GrassKind {+ #[serde(default)]+ pub name: Option<String>,+ #[serde(default = "full")]+ pub share: f32,+ #[serde(default)]+ pub brush: Option<String>,+ #[serde(default = "full")]+ pub length: f32,+ #[serde(default = "full")]+ pub width: f32,+ #[serde(default)]+ pub curl: f32,+ #[serde(default)]+ pub spread: f32,+ #[serde(default)]+ pub color: Option<String>,+ #[serde(default)]+ pub hue: f32,+ #[serde(default)]+ pub head: Option<String>,+ #[serde(default = "grass_head_size")]+ pub head_size: f32,+ #[serde(default)]+ pub low: bool,+ #[serde(default = "grass_patchy")]+ pub patchy: f32,+}++fn grass_head_size() -> f32 {+ 0.32+}++fn grass_patchy() -> f32 {+ 0.5+}+fn grass_color() -> String {"#5f8a3e".into()}diff --git a/docs/DESIGN.md b/docs/DESIGN.mdindex 5370776..25b8780 100644--- a/docs/DESIGN.md+++ b/docs/DESIGN.md@@ -239,7 +239,7 @@ Every layer has `blend`, `opacity`, `visible`, `locked`, optional `mask`, `clip`- **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.-- **Grass (M5, S5.28).** `grass` is a shape op too: rows of blades from the far (top) edge of the shapes to the near one, scaled from `far` to 1 by depth, leaning by `wind` with a bend, each from a dark root (`color`) to a lit tip (`second`, the `blade` brush blends to it by pressure as the blade thins) over ground that rolls in a value noise foreshortened with depth, lit by the light or lamp in soft value families; taller blades root just inside the top edge and break it; strokes are sorted far to near. A picture brush gets one stamp per blade. Both ops take any brush: they place and light marks, the brush (often the agent's own pictures) gives them their look.+- **Grass (M5, S5.28).** `grass` is a shape op too: rows of blades from the far (top) edge of the shapes to the near one, scaled from `far` to 1 by depth, leaning by `wind` with a bend, each from a dark root (`color`) to a lit tip (`second`, the `blade` brush blends to it by pressure as the blade thins) over ground that rolls in a value noise foreshortened with depth, lit by the light or lamp in soft value families; taller blades root just inside the top edge and break it; lit blades get a thin glint on their lit side; strokes are sorted far to near. Each root picks a species (`kinds`, by default fine, broad, dry, seed heads and clover) weighted by its share and by a noise of its own, so species grow in patches; heads and low plants thin out with distance. Per blade the hue, chroma and taper vary. A picture brush gets one stamp per blade; a species with a `head` gets a picture stamped at its tip; `low` species are stamped near the root and drawn before the blades around them. Both ops take any brush: they place and light marks, the brush (often the agent's own pictures) gives them their look.- **Picture brushes start facing the stroke (engine version 6).** A brush whose angle follows the stroke places its first dab before it knows the stroke's direction, so that dab points right. For a picture tip that made one-dab marks (a leaf, a tuft) never turn; such a brush now holds its first dab until the second point gives the direction (a tap is drawn when the stroke ends, `StrokePainter::end`, called by the replay and by the editor at pen up), the same live and in replay. Round, chalk and bristle tips keep the old first dab, so M1 drawings and every painted sample render as before; only strokes with picture tips and a following angle (`leaves`) change.## Strokesdiff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.mdindex 65daf31..9476e4c 100644--- a/docs/skill/SKILL.md+++ b/docs/skill/SKILL.md@@ -205,7 +205,7 @@ klad prepare art.draw- `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.-- Grass: `grass` grows blades from the far (top) edge of a shape to the near one, smaller and denser far off (`--far`), leaning with `--wind`, each from a dark root to a lit tip over ground that rolls in soft light patches, with taller blades breaking the top edge. Fill the shape a dark green first so gaps read as depth. Several passes make a meadow: a field with short blades, a near bank with long ones, accents (tufts, seed heads) with a brush of your own, laid before the blades so the grass grows over their bases. Distant grass is a soft mass, not blades.+- Grass: `grass` grows blades from the far (top) edge of a shape to the near one, smaller and denser far off (`--far`), leaning with `--wind`, each from a dark root to a lit tip over ground that rolls in soft light patches, with taller blades breaking the top edge and thin glints on lit blades. One kind of blade everywhere looks plastic: grass is a mix of species, each growing in its own patches. Without `kinds` the op grows a meadow mix (fine blades, broad flopping ones, dry straw, stalks with seed heads, clover low between them); give your own with `kinds` (JSON: `name`, `share`, `brush`, `length` and `width` against the blade, `curl`, `spread`, `color` or `hue`, `head` a picture brush stamped at the tip with `head_size`, `low` for rosettes and clover, `patchy` 0 to 1). Seed heads and low plants thin out with distance. Fill the shape a dark green first so gaps read as depth. A field with short blades and a near bank with long ones make a meadow; rare accents (your own tufts or flowers) are a species with a small share. Distant grass is a soft mass, not blades.- The shape ops decide where marks go and how light colours them; the brush decides what a mark looks like, and it should be yours when the subject needs it. `foliage`, `grass`, `scatter` and `paint` all take `--brush`: a stroke brush (round or chalk tip) draws each leaf or blade as a stroke, a picture brush stamps one picture per mark, turned to it. To make one, draw the shape in a small drawing of its own (black on transparent, pointing right for brushes whose angle follows the stroke), `klad render` it to a PNG, add it with `klad brushes art.draw --picture tuft tuft.png`, and define the brush with `klad brushes art.draw --set tuft tuft.json` (`{"tip":{"image":{"image":"tuft","more":["tuft-b"]}},"angle":"follow","spacing":1}`; several pictures give variety). `samples/meadow/build.sh` does exactly this. Make a new leaf or tuft for each species and style instead of reusing the library's for everything.- 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/`.diff --git a/samples/meadow/generate.py b/samples/meadow/generate.pyindex 2b5f66c..357da25 100644--- a/samples/meadow/generate.py+++ b/samples/meadow/generate.py@@ -87,10 +87,16 @@ def ops():out.append({"op": "grass", "layer": "field", "in": ["field-shape"], "color": COLOURS["field"], "light": LIGHT, "blade": 30,"far": 0.22, "wind": 12, "seed": 11})out.append({"op": "fill", "layer": "bank", "shape": "bank-shape", "color": "bank deep", "expand": 0})- out.append({"op": "grass", "layer": "bank", "in": ["bank-shape"], "color": COLOURS["tuft"], "light": LIGHT, "blade": 165,- "far": 0.85, "wind": 10, "density": 0.12, "edge": 1.2, "brush": "tuft", "seed": 17})+ kinds = [+ {"name": "fine", "share": 0.4, "width": 0.7, "curl": 0.12},+ {"name": "broad", "share": 0.22, "length": 0.72, "width": 1.7, "curl": 0.55, "hue": -10, "patchy": 0.6},+ {"name": "dry", "share": 0.12, "length": 0.9, "width": 0.55, "curl": 0.3, "color": "#a99d5c"},+ {"name": "heads", "share": 0.06, "length": 1.45, "width": 0.3, "curl": 0.1, "hue": 6, "head": "seed-head", "patchy": 0.7},+ {"name": "tufts", "share": 0.005, "brush": "tuft", "length": 2.4, "color": COLOURS["tuft"], "patchy": 0.8},+ {"name": "clover", "share": 0.16, "brush": "clover", "length": 0.5, "hue": -14, "low": True, "patchy": 0.85},+ ]out.append({"op": "grass", "layer": "bank", "in": ["bank-shape"], "color": COLOURS["bank"], "light": LIGHT, "blade": 58,- "far": 0.8, "wind": 14, "edge": 1.5, "seed": 13})+ "far": 0.8, "wind": 14, "edge": 1.5, "kinds": kinds, "seed": 13})return out