A drawing app built for agent/human collaboration
Rust
Paint with body: strokes lay paint height and a relief effect lights it
Indicode BVb4bfa6c60076
diff --git a/crates/app/src/editor/brushwin.rs b/crates/app/src/editor/brushwin.rsindex aed1173..4ee18b3 100644--- a/crates/app/src/editor/brushwin.rs+++ b/crates/app/src/editor/brushwin.rs@@ -268,6 +268,13 @@ impl Editor {}});});+ changed |= slider(+ ui,+ &mut def.body,+ 0.0..=1.0,+ "body",+ "how thick the paint lies: strokes leave ridges that a relief effect on the layer lights; 0 is flat paint",+ );egui::ScrollArea::vertical().max_height(460.0).show(ui, |ui| {ui.set_max_width(380.0);ui.label(RichText::new("tip").strong());diff --git a/crates/app/src/editor/look.rs b/crates/app/src/editor/look.rsindex 91469d7..9b8ed9f 100644--- a/crates/app/src/editor/look.rs+++ b/crates/app/src/editor/look.rs@@ -302,7 +302,83 @@ fn effect_controls(seed(ui, touch, &mut d.seed);});}+ Effect::Relief(r) => {+ slide(+ ui,+ touch,+ &mut r.strength,+ 0.0..=8.0,+ "strength",+ "how deep the paint's ridges look; only paint from brushes with body has ridges",+ );+ slide(+ ui,+ touch,+ &mut r.softness,+ 0.0..=8.0,+ "softness",+ "how much the ridges are smoothed, in px",+ );+ ui.horizontal(|ui| {+ light_dial(ui, touch, &mut r.light);+ ui.vertical(|ui| {+ swatch(+ ui,+ touch,+ &mut r.highlight,+ current,+ "the colour ridges facing the light take",+ );+ swatch(+ ui,+ touch,+ &mut r.shade,+ current,+ "the colour sides away from the light take",+ );+ });+ });+ }+ }+}++pub(super) const DIAL: &str = "where the light comes from";++fn light_dial(ui: &mut egui::Ui, touch: &mut Touch, light: &mut [f32; 2]) {+ let side = 64.0;+ let (rect, response) = ui.allocate_exact_size(vec2(side, side), Sense::click_and_drag());+ response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Slider, true, DIAL));+ let response = response.hint(format!(+ "{DIAL}: click or drag towards it ({:.2}, {:.2})",+ light[0], light[1]+ ));+ let centre = rect.center();+ let reach = side * 0.5 - 6.0;+ let pressed = response.clicked() || response.dragged() || response.drag_stopped();+ if let Some(at) = response.interact_pointer_pos().filter(|_| pressed) {+ let towards = at - centre;+ if towards.length() > 3.0 {+ let unit = towards.normalized();+ let next = [(unit.x * 100.0).round() / 100.0, (unit.y * 100.0).round() / 100.0];+ if next != *light {+ *light = next;+ touch.add(match response.dragged() && !response.drag_stopped() {+ true => Touch::Preview,+ false => Touch::Commit,+ });+ }+ }}+ if response.drag_stopped() {+ touch.add(Touch::Commit);+ }+ let length = light[0].hypot(light[1]).max(1e-6);+ let sun = centre + vec2(light[0] / length, light[1] / length) * reach;+ let painter = ui.painter_at(rect);+ let line = ui.visuals().widgets.inactive.fg_stroke;+ painter.circle_stroke(centre, reach, Stroke::new(1.0, line.color.gamma_multiply(0.5)));+ painter.arrow(sun, (centre - sun) * 0.8, Stroke::new(1.5, line.color));+ painter.circle_filled(sun, 5.0, Color32::from_rgb(255, 214, 120));}fn curve_box(ui: &mut egui::Ui, points: &mut Vec<[f32; 2]>, state: &mut LookState, touch: &mut Touch, colour: Color32) {@@ -787,6 +863,7 @@ impl Editor {let mut added = None;egui::ComboBox::from_id_salt(format!("{}.effect.add", layer.id)).width(120.0)+ .height(EFFECTS.len() as f32 * (theme::TARGET + 6.0)).selected_text(format!("{} add an effect", theme::icon::PLUS)).show_ui(ui, |ui| {EFFECTS.iter().for_each(|name| {@@ -800,7 +877,7 @@ impl Editor {});}).response- .hint("blur, glow, outline, shadow, grain or displacement, applied after the ones above");+ .hint("blur, glow, outline, shadow, grain, displacement, haze or relief, applied after the ones above");if let Some(effect) = added {list.push(effect);touch.add(Touch::Commit);diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rsindex 997341b..34558e2 100644--- a/crates/app/src/editor/ui_tests.rs+++ b/crates/app/src/editor/ui_tests.rs@@ -2263,3 +2263,69 @@ fn the_cli_only_features_run_from_the_editor_and_give_what_the_cli_gives() {assert!(errors.is_empty(), "{errors:?}");std::fs::remove_dir_all(&base).unwrap();}++#[test]+fn paint_with_body_from_the_brush_window_lit_by_a_relief_turned_with_its_dial() {+ use klad_core::look::Effect;+ let path = sample("body");+ let mut h = harness(editor(&path), vec2(1440.0, 1400.0));+ [+ (Pane::Inspector, false),+ (Pane::Notes, true),+ (Pane::History, true),+ (Pane::Layers, true),+ (Pane::Tool, true),+ ]+ .into_iter()+ .for_each(|(pane, collapsed)| {+ if let Some(p) = h.state_mut().settings.layout.pane_mut(pane) {+ p.collapsed = collapsed;+ }+ });+ activate(&mut h, "lines");+ h.state_mut().pick("oil");+ h.key_press(Key::F5);+ h.run_steps(3);+ assert!(h.state().windows.brush);+ let track = h.get_by_role_and_label(Role::Slider, "body").rect();+ let at = egui::pos2(track.left() + track.width() * 0.9, track.center().y);+ drag(&mut h, at, at);+ h.run_steps(2);+ let body = h.state().custom.as_ref().map_or(0.0, |d| d.body);+ assert!(body > 0.7, "the slider sets the body: {body}");+ h.key_press(Key::F5);+ h.run_steps(2);+ let rect = h.state().canvas_rect;+ h.key_press(Key::B);+ h.run_steps(1);+ drag(+ &mut h,+ rect.center() + vec2(-120.0, 0.0),+ rect.center() + vec2(120.0, 10.0),+ );+ h.run_steps(3);+ assert!(+ h.state().scene.active_raster().is_some_and(|r| r.has_height()),+ "the stroke left paint height"+ );+ h.get_by_label_contains("applied after the ones above").click();+ h.run_steps(2);+ h.get_by_label("relief").click();+ h.run_steps(3);+ let relief = |h: &Harness<'static, Editor>| match h.state().scene.active_layer().unwrap().effects.first() {+ Some(Effect::Relief(r)) => r.clone(),+ other => panic!("{other:?}"),+ };+ assert_eq!(relief(&h).light, [-1.0, -1.0]);+ let dial = h.get_by_label(super::look::DIAL).rect();+ let right = egui::pos2(dial.right() - 4.0, dial.center().y);+ drag(&mut h, right, right);+ h.run_steps(3);+ let light = relief(&h).light;+ assert!(+ light[0] > 0.9 && light[1].abs() < 0.2,+ "the light comes from the right: {light:?}"+ );+ checked_audit(&mut h);+ let _ = std::fs::remove_dir_all(&path);+}diff --git a/crates/app/src/lift.rs b/crates/app/src/lift.rsindex b2f29db..9753acf 100644--- a/crates/app/src/lift.rs+++ b/crates/app/src/lift.rs@@ -199,7 +199,8 @@ mod tests {#[test]fn crops_copy_pixels_across_tiles_and_shrink_big_regions() {let mut raster = Raster::new(600, 300);- raster.ensure(raster.index(1, 0))[((10 * TILE) + 3) * 4 + 3] = f16::ONE;+ let i = raster.index(1, 0);+ raster.ensure(i)[((10 * TILE) + 3) * 4 + 3] = f16::ONE;let lifted = crop(&raster, [250.0, 5.0, 20.0, 10.0], 4096);assert_eq!((lifted.width, lifted.height), (20, 10));assert_eq!(lifted.rect, [250.0, 5.0, 20.0, 10.0]);diff --git a/crates/brush/src/engine.rs b/crates/brush/src/engine.rsindex 3e3c837..33f0d13 100644--- a/crates/brush/src/engine.rs+++ b/crates/brush/src/engine.rs@@ -1,16 +1,18 @@use crate::brush::{Angle, Brush, BrushSet, StrokeBlend, Texture, Tip, smoothstep, speed_amount, tilt_amount};use crate::cut;-use crate::tiles::{Mode, Raster, StrokeBuffer, TILE};+use crate::tiles::{Mode, Raster, StrokeBuffer, TILE, Tiles};use anyhow::Result;use half::f16;use klad_core::brushes::PaintDef;use klad_core::color::Rgba;use klad_core::cut::Cut;-use klad_core::rng::Rng;+use klad_core::rng::{Rng, hash2_unit};use klad_core::stroke::{Mark, Sample, Stroke};const MIN_RADIUS: f32 = 0.6;const SPEED_EASE: f32 = 0.5;+const SQUASH: f32 = 0.55;+const DEEPEST: f32 = 32.0;#[derive(Clone, Copy, Debug)]struct Point {@@ -77,7 +79,9 @@ pub struct StrokePainter {second: [f32; 3],shift: [f32; 3],reservoir: Option<[f32; 3]>,+ reservoir_height: Option<f32>,previous: Option<(f32, f32)>,+ bristles: Option<Box<Bristles>>,}const STROKE_COLOUR_SEED: u64 = 0x9e37_79b9_7f4a_7c15;@@ -127,7 +131,9 @@ impl StrokePainter {second,shift,reservoir: None,+ reservoir_height: None,previous: None,+ bristles: (brush.def.body > 0.0).then(|| Box::new(Bristles::new(stroke.seed ^ 0x5bd1_e995, stroke.size))),}}@@ -145,6 +151,8 @@ impl StrokePainter {pub fn push_on(&mut self, sample: &Sample, buffer: &mut StrokeBuffer, under: Option<&Raster>) {buffer.mode = self.mode();+ buffer.body = self.brush.def.body;+ buffer.lifting = buffer.mode != Mode::Flat && under.is_some_and(Raster::has_height);let (x, y) = sample.pos();let next = Point {x,@@ -274,6 +282,7 @@ impl StrokePainter {});let mut color = self.colour_here(at, along);let mut flow = flow;+ let mut lift = None;if let Some(PaintDef::Wet {wetness,pickup,@@ -289,6 +298,12 @@ impl StrokePainter {}color = Some(std::array::from_fn(|i| base[i] + (reservoir[i] - base[i]) * wetness));flow *= 1.0 - dilution * 0.9;+ if buffer.lifting {+ let picked_height = pick_height(buffer, under, cx, cy, size * 0.5);+ let held = self.reservoir_height.get_or_insert(picked_height);+ *held += (picked_height - *held) * pickup * picked[3].min(1.0);+ lift = Some(picked_height + (*held - picked_height) * wetness);+ }}let shift = self.previous.map_or((0.0, 0.0), |(px, py)| (cx - px, cy - py));self.previous = Some((cx, cy));@@ -304,6 +319,7 @@ impl StrokePainter {dual,count,color,+ lift,};match self.brush.def.paint {Some(PaintDef::Smudge { strength }) => {@@ -312,7 +328,10 @@ impl StrokePainter {Some(PaintDef::Blend { strength }) => {stamp_replace(buffer, &self.brush, dab, under, Replace::Blend, strength)}- _ => stamp(buffer, &self.brush, dab),+ _ => {+ let bristles = self.bristles.as_deref().map(|b| (b, b.load(along)));+ stamp(buffer, &self.brush, dab, bristles)+ }}}}@@ -377,6 +396,31 @@ fn state_at(buffer: &StrokeBuffer, under: Option<&Raster>, x: i64, y: i64) -> [f}}+fn height_at(buffer: &StrokeBuffer, under: Option<&Raster>, x: i64, y: i64) -> f32 {+ let grid = buffer.grid();+ if x < 0 || y < 0 || x >= grid.width as i64 || y >= grid.height as i64 {+ return 0.0;+ }+ let (x, y) = (x as usize, y as usize);+ let index = (y / TILE) * grid.cols + x / TILE;+ let px = (y % TILE) * TILE + x % TILE;+ let replaced = buffer.mode == Mode::Replace && buffer.coverage(index).is_some_and(|c| c[px] > 0.0);+ match (replaced, buffer.lift(index)) {+ (true, Some(lift)) => lift[px],+ _ => under.and_then(|r| r.height_tile(index)).map_or(0.0, |t| t[px].to_f32()),+ }+}++fn pick_height(buffer: &StrokeBuffer, under: Option<&Raster>, cx: f32, cy: f32, radius: f32) -> f32 {+ let r = radius * 0.4;+ let points = [(0.0, 0.0), (r, 0.0), (-r, 0.0), (0.0, r), (0.0, -r)];+ points+ .iter()+ .map(|(dx, dy)| height_at(buffer, under, (cx + dx).floor() as i64, (cy + dy).floor() as i64))+ .sum::<f32>()+ / points.len() as f32+}+fn pick(buffer: &StrokeBuffer, under: Option<&Raster>, cx: f32, cy: f32, radius: f32) -> [f32; 4] {let r = radius * 0.4;let points = [(0.0, 0.0), (r, 0.0), (-r, 0.0), (0.0, r), (0.0, -r)];@@ -398,6 +442,48 @@ struct Dab {dual: [[f32; 3]; 8],count: usize,color: Option<[f32; 3]>,+ lift: Option<f32>,+}++const GROOVES: usize = 256;+const RUN: f32 = 8.0;+const LIPS: usize = 64;++struct Bristles {+ grooves: [f32; GROOVES + 1],+ lips: [f32; LIPS + 1],+ run: f32,+}++impl Bristles {+ fn new(seed: u32, size: f32) -> Self {+ let count = (size / 3.5).clamp(3.0, 48.0);+ let wave = |x: f32, row: i32| {+ let i = libm::floorf(x);+ let f = x - i;+ let t = f * f * (3.0 - 2.0 * f);+ let at = |k: f32| hash2_unit(k as i32, row, seed);+ at(i) + (at(i + 1.0) - at(i)) * t+ };+ Self {+ grooves: std::array::from_fn(|k| {+ let x = k as f32 / GROOVES as f32 * count;+ 0.45 + 0.55 * (wave(x, 0) * 0.65 + wave(x * 2.3, 1) * 0.35)+ }),+ lips: std::array::from_fn(|k| 0.9 + 0.2 * smoothstep(0.5, 0.9, k as f32 / LIPS as f32)),+ run: size * RUN,+ }+ }++ fn load(&self, along: f32) -> f32 {+ 1.0 - 0.45 * smoothstep(0.0, self.run.max(1.0), along)+ }++ fn thickness(&self, d: f32, v: f32, load: f32) -> f32 {+ let groove = self.grooves[((v.clamp(-1.0, 1.0) * 0.5 + 0.5) * GROOVES as f32) as usize];+ let lip = self.lips[(d.min(1.0) * LIPS as f32) as usize];+ lip * groove * load+ }}const RING: [(f32, f32); 8] = [@@ -538,7 +624,7 @@ fn area(buffer: &StrokeBuffer, dab: &Dab) -> Option<Area> {})}-fn stamp(buffer: &mut StrokeBuffer, brush: &Brush, dab: Dab) {+fn stamp(buffer: &mut StrokeBuffer, brush: &Brush, dab: Dab, bristles: Option<(&Bristles, f32)>) {let Some(Area {x0,y0,@@ -562,7 +648,12 @@ fn stamp(buffer: &mut StrokeBuffer, brush: &Brush, dab: Dab) {if buffer.skip(ty * cols + tx) {continue;}- let (tile, mut paint) = buffer.tiles_mut(ty * cols + tx);+ let Tiles {+ coverage: tile,+ mut paint,+ mut lift,+ mut ridge,+ } = buffer.tiles_mut(ty * cols + tx);let (ox, oy) = (tx * TILE, ty * TILE);for y in y0.max(oy)..y1.min(oy + TILE) {let py = y as f32 + 0.5 - cy;@@ -586,6 +677,12 @@ fn stamp(buffer: &mut StrokeBuffer, brush: &Brush, dab: Dab) {if let Some(texture) = &brush.grain {a = (a - texture_value(texture, x, y, dab.p)).max(0.0);}+ if let (Some(ridge), Some((bristles, load))) = (ridge.as_deref_mut(), bristles)+ && a > 0.0+ {+ let r = &mut ridge[row + x - ox];+ *r = r.max(bristles.thickness(libm::sqrtf(d2), v, load));+ }if a > 0.0 && reach > 0.0 {let at = row + x - ox;let c = &mut tile[at];@@ -603,6 +700,9 @@ fn stamp(buffer: &mut StrokeBuffer, brush: &Brush, dab: Dab) {(0..3).for_each(|i| w[i] += colour[i] * gain);w[3] += gain;}+ if let (Some(lift), Some(height)) = (lift.as_deref_mut(), dab.lift) {+ lift[at] += height * gain;+ }}}}@@ -637,7 +737,8 @@ fn stamp_replace(let (sin, cos) = (libm::sinf(dab.angle), libm::cosf(dab.angle));let (inv_radius, inv_round) = (1.0 / radius, 1.0 / brush.def.roundness);let cols = buffer.grid().cols;- let changes: Vec<(usize, usize, [f32; 4])> = (y0..y1)+ let lifting = buffer.lifting;+ let changes: Vec<(usize, usize, [f32; 4], f32)> = (y0..y1).flat_map(|y| (x0..x1).map(move |x| (x, y))).filter(|&(x, y)| buffer.allowed((y / TILE) * cols + x / TILE)).filter_map(|(x, y)| {@@ -659,20 +760,21 @@ fn stamp_replace(if a <= 0.0 {return None;}- let here = state_at(buffer, under, x as i64, y as i64);+ let state = |x: i64, y: i64| {+ let s = state_at(buffer, under, x, y);+ let h = match lifting {+ true => height_at(buffer, under, x, y),+ false => 0.0,+ };+ [s[0], s[1], s[2], s[3], h]+ };+ let here = state(x as i64, y as i64);let from = match how {- Replace::Smudge((dx, dy)) => state_at(- buffer,- under,- (x as f32 - dx).round() as i64,- (y as f32 - dy).round() as i64,- ),+ Replace::Smudge((dx, dy)) => state((x as f32 - dx).round() as i64, (y as f32 - dy).round() as i64),Replace::Blend => {let reach = (radius * 0.3).max(1.0);let sum = RING.iter().fold(here, |acc, (dx, dy)| {- let s = state_at(- buffer,- under,+ let s = state((x as f32 + dx * reach).round() as i64,(y as f32 + dy * reach).round() as i64,);@@ -681,17 +783,24 @@ fn stamp_replace(sum.map(|v| v / (RING.len() + 1) as f32)}};- Some((x, y, std::array::from_fn(|c| here[c] + (from[c] - here[c]) * a)))+ let next: [f32; 5] = std::array::from_fn(|c| here[c] + (from[c] - here[c]) * a);+ Some((x, y, [next[0], next[1], next[2], next[3]], next[4]))}).collect();- changes.into_iter().for_each(|(x, y, value)| {+ changes.into_iter().for_each(|(x, y, value, height)| {let index = (y / TILE) * cols + x / TILE;let at = (y % TILE) * TILE + x % TILE;- let (tile, paint) = buffer.tiles_mut(index);- tile[at] = 1.0;- if let Some(paint) = paint {+ let tiles = buffer.tiles_mut(index);+ tiles.coverage[at] = 1.0;+ if let Some(paint) = tiles.paint {paint[at * 4..at * 4 + 4].copy_from_slice(&value);}+ if let Some(lift) = tiles.lift {+ lift[at] = height;+ }+ if let Some(ridge) = tiles.ridge {+ ridge[at] = 1.0;+ }});}@@ -844,11 +953,73 @@ fn commit_cut(if let (Some(target), Some(coverage)) = (target, buffer.coverage(index)) {land(target, coverage, buffer.paint(index), mode, color, opacity, blend);}+ land_body(raster, buffer, index, color, opacity, blend);});buffer.reset();touched}+fn land_body(raster: &mut Raster, buffer: &StrokeBuffer, index: usize, color: Rgba, opacity: f32, blend: StrokeBlend) {+ let (body, lift, ridge) = (buffer.body, buffer.lift(index), buffer.ridge(index));+ let Some(coverage) = buffer.coverage(index) else {+ return;+ };+ let erase = blend == StrokeBlend::Erase && buffer.mode != Mode::Replace;+ if !erase && body <= 0.0 && lift.is_none() {+ return;+ }+ if erase && raster.height_tile(index).is_none() {+ return;+ }+ let alpha = match buffer.mode {+ Mode::Replace => opacity.clamp(0.0, 1.0),+ _ => (opacity * color[3]).clamp(0.0, 1.0),+ };+ let atop = blend == StrokeBlend::Atop;+ let under: Option<Vec<f32>> = atop.then(|| match raster.at(index) {+ Some(t) => t.as_chunks::<4>().0.iter().map(|p| p[3].to_f32()).collect(),+ None => vec![0.0; TILE * TILE],+ });+ let weights: Option<Vec<f32>> = match buffer.mode {+ Mode::Colour => buffer+ .paint(index)+ .map(|p| p.as_chunks::<4>().0.iter().map(|w| w[3]).collect()),+ _ => None,+ };+ let mode = buffer.mode;+ let heights = raster.heights_mut().ensure(index);+ coverage+ .iter()+ .zip(heights.iter_mut())+ .enumerate()+ .filter(|(_, (c, _))| **c > 0.0)+ .for_each(|(px, (&c, h))| {+ let mut a = (c * alpha).clamp(0.0, 1.0);+ if let Some(under) = &under {+ a *= under[px];+ }+ let mut value = h.to_f32();+ if erase {+ value *= 1.0 - a;+ } else {+ if let Some(lift) = lift {+ let target = match (mode, &weights) {+ (Mode::Colour, Some(w)) if w[px] > 0.0 => lift[px] / w[px],+ (Mode::Colour, _) => value,+ _ => lift[px],+ };+ value += (target - value) * a;+ }+ if body > 0.0 {+ let thick = ridge.map_or(1.0, |r| r[px]);+ let laid = (c * (0.5 + 0.5 * alpha)).clamp(0.0, 1.0) * under.as_ref().map_or(1.0, |u| u[px]);+ value = value * (1.0 - SQUASH * a) + body * laid * thick;+ }+ }+ *h = f16::from_f32(value.clamp(0.0, DEEPEST));+ });+}+pub fn stroke_blend(brush: &Brush, lock: bool) -> Option<StrokeBlend> {match (brush.blend, lock) {(blend, false) => Some(blend),@@ -1343,6 +1514,100 @@ mod tests {commit(&mut raster, &mut buffer, wet.color(), wet.opacity, brush.blend);assert_eq!(raster.hash(), replay(512, 128, &marks, &brushes).unwrap().raster.hash());}++ fn height(raster: &Raster, x: usize, y: usize) -> f32 {+ raster+ .height_tile(raster.index(x / TILE, y / TILE))+ .map_or(0.0, |t| t[(y % TILE) * TILE + x % TILE].to_f32())+ }++ fn thick_and(brush: &str) -> Vec<Mark> {+ let oil = coloured("oil-load", 60.0, (40.0, 64.0), (220.0, 64.0), [0.8, 0.6, 0.2, 1.0], 1);+ let mut over = coloured(brush, 24.0, (100.0, 64.0), (400.0, 64.0), [0.2, 0.3, 0.8, 1.0], 2);+ over.id = 2;+ vec![oil.into(), over.into()]+ }++ #[test]+ fn a_brush_without_body_leaves_no_height() {+ let brushes = BrushSet::presets();+ ["ink", "pencil", "soft", "wet", "smudge", "chalk"]+ .iter()+ .for_each(|b| {+ let out = replay(512, 128, &base_and(b), &brushes).unwrap().raster;+ assert!(!out.has_height(), "{b} left height");+ });+ }++ #[test]+ fn paint_with_body_ridges_at_its_edges_builds_where_strokes_overlap_and_replays_the_same() {+ let brushes = BrushSet::presets();+ let one = replay(512, 128, &thick_and("ink")[..1], &brushes).unwrap().raster;+ assert!(one.has_height());+ let column: Vec<f32> = (0..128).map(|y| height(&one, 130, y)).collect();+ let top = column.iter().position(|&h| h > 0.05).unwrap();+ let bottom = column.iter().rposition(|&h| h > 0.05).unwrap();+ let reach = (bottom - top) as f32 / 2.0;+ let centre = (top + bottom) as f32 / 2.0;+ let band = |from: f32, to: f32| {+ let ys: Vec<usize> = (top..=bottom)+ .filter(|&y| ((y as f32 - centre).abs() / reach) >= from && ((y as f32 - centre).abs() / reach) < to)+ .collect();+ let n = ys.len() * 80;+ ys.iter()+ .flat_map(|&y| (100..180).map(move |x| (x, y)))+ .map(|(x, y)| height(&one, x, y))+ .sum::<f32>()+ / n as f32+ };+ let (middle, rim) = (band(0.0, 0.3), band(0.55, 0.8));+ assert!(middle > 0.3, "middle {middle}");+ assert!(rim > middle * 1.08, "a lip at the edge: rim {rim} middle {middle}");+ assert_eq!(height(&one, 130, 110), 0.0);+ let column: Vec<f32> = (40..88).map(|y| height(&one, 130, y)).collect();+ let grooves = column.windows(3).filter(|w| w[1] < w[0] && w[1] < w[2]).count();+ assert!(grooves >= 4, "bristles leave grooves along the stroke: {grooves}");+ let middle = height(&one, 130, 64);+ let mut twice = thick_and("oil-load");+ twice[1] = coloured("oil-load", 60.0, (130.0, 64.0), (300.0, 64.0), [0.8, 0.6, 0.2, 1.0], 2).into();+ let two = replay(512, 128, &twice, &brushes).unwrap().raster;+ assert!(height(&two, 175, 64) > middle * 1.2, "overlap builds up");+ assert_eq!(two.hash(), replay(512, 128, &twice, &brushes).unwrap().raster.hash());+ let (mut cel, mut raster, _) = crate::replay::CelReplay::replay(512, 128, twice.clone(), &brushes).unwrap();+ let mut edited = twice.clone();+ if let Mark::Stroke(s) = &mut edited[1] {+ s.size = 40.0;+ }+ cel.update(&mut raster, edited.clone(), &brushes).unwrap();+ assert_eq!(+ raster.hash(),+ replay(512, 128, &edited, &brushes).unwrap().raster.hash()+ );+ }++ #[test]+ fn the_eraser_takes_paint_height_smudge_and_wet_drag_it_and_the_blender_flattens_it() {+ let brushes = BrushSet::presets();+ let thick = replay(512, 128, &thick_and("ink")[..1], &brushes).unwrap().raster;+ let erased = replay(512, 128, &thick_and("eraser"), &brushes).unwrap().raster;+ assert!(height(&erased, 150, 64) < height(&thick, 150, 64) * 0.2);+ assert_eq!(height(&thick, 262, 64), 0.0, "the paint ends before x 262");+ let smudged = replay(512, 128, &thick_and("smudge"), &brushes).unwrap().raster;+ assert!(height(&smudged, 262, 64) > 0.05, "smudge pulls the paint along");+ let wet = replay(512, 128, &thick_and("wet"), &brushes).unwrap().raster;+ assert!(height(&wet, 262, 64) > 0.02, "wet paint carries some of it");+ let top = height(&thick, 150, 64);+ let slope = |r: &Raster| {+ (200..280)+ .filter(|&x| (0.1 * top..0.9 * top).contains(&height(r, x, 64)))+ .count()+ };+ let blended = replay(512, 128, &thick_and("blender"), &brushes).unwrap().raster;+ assert!(+ slope(&blended) > slope(&thick) + 3,+ "the blender flattens the paint's end"+ );+ }}#[cfg(test)]diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rsindex 4c6a2ad..ca0e9c1 100644--- a/crates/brush/src/lib.rs+++ b/crates/brush/src/lib.rs@@ -9,7 +9,7 @@ pub mod record;pub mod replay;pub mod tiles;-pub const ENGINE_VERSION: u32 = 3;+pub const ENGINE_VERSION: u32 = 4;pub use brush::{Brush, BrushSet};pub use engine::{diff --git a/crates/brush/src/replay.rs b/crates/brush/src/replay.rsindex a8dee4e..42ad274 100644--- a/crates/brush/src/replay.rs+++ b/crates/brush/src/replay.rs@@ -1,7 +1,7 @@use crate::brush::{BrushSet, StrokeBlend};use crate::engine::{commit, draw_stroke_on, land_stroke};use crate::fill::{fill_tiles, paint_fill_where};-use crate::tiles::{Raster, StrokeBuffer, TILE_PX};+use crate::tiles::{Raster, StrokeBuffer, TILE_PX, Tile};use anyhow::Result;use half::f16;use klad_core::stroke::{Mark, Stroke, fingerprint};@@ -11,8 +11,6 @@ use std::sync::Arc;pub const EVERY: usize = 128;pub const BUDGET: usize = 128 << 20;-type Tile = Option<Arc<[f16]>>;-#[derive(Clone)]struct Checkpoint {at: usize,@@ -53,10 +51,7 @@ fn painted(}fn put(raster: &mut Raster, index: usize, tile: &Tile) {- match tile {- Some(data) => raster.put(index, Box::from(&data[..])),- None => raster.clear(index),- }+ raster.restore(index, tile);}impl CelReplay {@@ -70,7 +65,7 @@ impl CelReplay {footprints: Vec::new(),checkpoints: vec![Checkpoint {at: 0,- tiles: vec![None; tiles.cols * tiles.rows],+ tiles: vec![(None, None); tiles.cols * tiles.rows],}],}}@@ -142,7 +137,7 @@ impl CelReplay {let mut tiles = last.tiles.clone();changed.iter()- .for_each(|&t| tiles[t as usize] = raster.at(t as usize).map(Arc::from));+ .for_each(|&t| tiles[t as usize] = raster.tile(t as usize));self.checkpoints.push(Checkpoint {at: self.keys.len(),tiles,@@ -161,13 +156,17 @@ impl CelReplay {}pub fn checkpoint_bytes(&self) -> usize {- let unique: BTreeSet<usize> = self+ let unique: BTreeSet<(usize, usize)> = self.checkpoints.iter()- .flat_map(|c| c.tiles.iter().flatten())- .map(|t| Arc::as_ptr(t) as *const f16 as usize)+ .flat_map(|c| c.tiles.iter())+ .flat_map(|(colour, height)| {+ let colour = colour.as_ref().map(|t| (Arc::as_ptr(t) as *const f16 as usize, 4));+ let height = height.as_ref().map(|t| (Arc::as_ptr(t) as *const f16 as usize, 1));+ colour.into_iter().chain(height)+ }).collect();- unique.len() * TILE_PX * 4 * std::mem::size_of::<f16>()+ unique.iter().map(|(_, c)| c).sum::<usize>() * TILE_PX * std::mem::size_of::<f16>()}pub fn commit_stroke(@@ -259,7 +258,7 @@ impl CelReplay {let mut tiles = old;(0..dirty.len()).filter(|&t| dirty[t])- .for_each(|t| tiles[t] = raster.at(t).map(Arc::from));+ .for_each(|t| tiles[t] = raster.tile(t));out.push(Checkpoint { at, tiles });};let mut last_kept = vec![0usize; tiles];diff --git a/crates/brush/src/tiles.rs b/crates/brush/src/tiles.rsindex ff95b37..fccb623 100644--- a/crates/brush/src/tiles.rs+++ b/crates/brush/src/tiles.rs@@ -1,6 +1,7 @@use anyhow::{Result, bail};use half::f16;use klad_core::rng::{FNV_OFFSET, fnv};+use std::ops::{Deref, DerefMut};use std::sync::Arc;pub const TILE: usize = 256;@@ -15,7 +16,29 @@ pub struct TileGrid<T, const C: usize> {tiles: Vec<Option<Arc<Box<[T]>>>>,}-pub type Raster = TileGrid<f16, 4>;+pub type Heights = TileGrid<f16, 1>;++#[derive(Clone)]+pub struct Raster {+ colour: TileGrid<f16, 4>,+ body: Option<Heights>,+}++impl Deref for Raster {+ type Target = TileGrid<f16, 4>;++ fn deref(&self) -> &Self::Target {+ &self.colour+ }+}++impl DerefMut for Raster {+ fn deref_mut(&mut self) -> &mut Self::Target {+ &mut self.colour+ }+}++pub type Tile = (Option<Arc<[f16]>>, Option<Arc<[f16]>>);impl<T: Copy + Default, const C: usize> TileGrid<T, C> {pub fn new(width: u32, height: u32) -> Self {@@ -78,23 +101,104 @@ impl<T: Copy + Default, const C: usize> TileGrid<T, C> {}const RASTER_MAGIC: &[u8; 4] = b"DART";+const HEIGHT_MAGIC: &[u8; 4] = b"HGHT";++fn fold_tiles<T: bytemuck::Pod + Default, const C: usize>(grid: &TileGrid<T, C>, from: u64) -> u64 {+ grid.occupied().fold(from, |h, (i, tile)| {+ fnv(fnv(h, &(i as u64).to_le_bytes()), bytemuck::cast_slice(tile))+ })+}++fn write_tiles<T: bytemuck::Pod + Default, const C: usize>(grid: &TileGrid<T, C>, out: &mut Vec<u8>) {+ out.extend_from_slice(&(grid.count() as u32).to_le_bytes());+ grid.occupied().for_each(|(i, tile)| {+ out.extend_from_slice(&(i as u32).to_le_bytes());+ out.extend_from_slice(bytemuck::cast_slice(tile));+ });+}impl Raster {+ pub fn new(width: u32, height: u32) -> Self {+ Self {+ colour: TileGrid::new(width, height),+ body: None,+ }+ }++ pub fn heights(&self) -> Option<&Heights> {+ self.body.as_ref().filter(|h| h.count() > 0)+ }++ pub fn heights_mut(&mut self) -> &mut Heights {+ let (w, h) = (self.colour.width, self.colour.height);+ self.body.get_or_insert_with(|| TileGrid::new(w, h))+ }++ pub fn height_tile(&self, index: usize) -> Option<&[f16]> {+ self.body.as_ref().and_then(|h| h.at(index))+ }++ pub fn height_tile_mut(&mut self, index: usize) -> Option<&mut [f16]> {+ self.body.as_mut().and_then(|h| h.at_mut(index))+ }++ pub fn has_height(&self) -> bool {+ self.heights().is_some()+ }++ pub fn clear(&mut self, index: usize) {+ self.colour.clear(index);+ if let Some(h) = self.body.as_mut() {+ h.clear(index);+ }+ }++ pub fn tile(&self, index: usize) -> Tile {+ (+ self.colour.at(index).map(Arc::from),+ self.height_tile(index).map(Arc::from),+ )+ }++ pub fn restore(&mut self, index: usize, (colour, height): &Tile) {+ match colour {+ Some(data) => self.colour.put(index, Box::from(&data[..])),+ None => self.colour.clear(index),+ }+ match (height, self.body.as_mut()) {+ (Some(data), _) => self.heights_mut().put(index, Box::from(&data[..])),+ (None, Some(h)) => h.clear(index),+ (None, None) => {}+ }+ }+pub fn hash(&self) -> u64 {- self.occupied().fold(FNV_OFFSET, |h, (i, tile)| {- fnv(fnv(h, &(i as u64).to_le_bytes()), bytemuck::cast_slice(tile))- })+ let colour = fold_tiles(&self.colour, FNV_OFFSET);+ match self.heights() {+ Some(h) => fold_tiles(h, fnv(colour, HEIGHT_MAGIC)),+ None => colour,+ }+ }++ pub fn height_bytes(&self) -> usize {+ self.heights().map_or(0, |h| h.bytes())+ }++ pub fn bytes(&self) -> usize {+ self.colour.bytes() + self.height_bytes()}pub fn encode(&self) -> Vec<u8> {- let header = [self.width, self.height, self.count() as u32];let mut out = Vec::with_capacity(16 + self.bytes() + self.count() * 4);out.extend_from_slice(RASTER_MAGIC);- header.iter().for_each(|v| out.extend_from_slice(&v.to_le_bytes()));- self.occupied().for_each(|(i, tile)| {- out.extend_from_slice(&(i as u32).to_le_bytes());- out.extend_from_slice(bytemuck::cast_slice(tile));- });+ [self.colour.width, self.colour.height]+ .iter()+ .for_each(|v| out.extend_from_slice(&v.to_le_bytes()));+ write_tiles(&self.colour, &mut out);+ if let Some(h) = self.heights() {+ out.extend_from_slice(HEIGHT_MAGIC);+ write_tiles(h, &mut out);+ }out}@@ -109,21 +213,29 @@ impl Raster {bail!("not a raster file");}let mut raster = Raster::new(word(4)?, word(8)?);- let count = word(12)? as usize;- let tile_bytes = TILE_PX * 4 * 2;- (0..count).try_for_each(|n| {- let at = 16 + n * (4 + tile_bytes);- let index = word(at)? as usize;- let Some(data) = bytes.get(at + 4..at + 4 + tile_bytes) else {- bail!("raster tile {n} ends early");- };- if index >= raster.cols * raster.rows {- bail!("raster tile index {index} out of range");- }- let tile: Vec<f16> = bytemuck::pod_collect_to_vec(data);- raster.put(index, tile.into_boxed_slice());- Ok(())- })?;+ let tiles = raster.cols * raster.rows;+ let read = |from: usize, channels: usize, put: &mut dyn FnMut(usize, Box<[f16]>)| -> Result<usize> {+ let count = word(from)? as usize;+ let tile_bytes = TILE_PX * channels * 2;+ (0..count).try_for_each(|n| {+ let at = from + 4 + n * (4 + tile_bytes);+ let index = word(at)? as usize;+ let Some(data) = bytes.get(at + 4..at + 4 + tile_bytes) else {+ bail!("raster tile {n} ends early");+ };+ if index >= tiles {+ bail!("raster tile index {index} out of range");+ }+ let tile: Vec<f16> = bytemuck::pod_collect_to_vec(data);+ put(index, tile.into_boxed_slice());+ Ok(())+ })?;+ Ok(from + 4 + count * (4 + tile_bytes))+ };+ let end = read(12, 4, &mut |i, t| raster.colour.put(i, t))?;+ if bytes.get(end..end + 4) == Some(HEIGHT_MAGIC) {+ read(end + 4, 1, &mut |i, t| raster.heights_mut().put(i, t))?;+ }Ok(raster)}}@@ -136,10 +248,21 @@ pub enum Mode {Replace,}+pub struct Tiles<'a> {+ pub coverage: &'a mut [f32],+ pub paint: Option<&'a mut [f32]>,+ pub lift: Option<&'a mut [f32]>,+ pub ridge: Option<&'a mut [f32]>,+}+pub struct StrokeBuffer {grid: TileGrid<f32, 1>,paint: TileGrid<f32, 4>,+ lift: TileGrid<f32, 1>,+ ridge: TileGrid<f32, 1>,pub mode: Mode,+ pub body: f32,+ pub lifting: bool,touched: Vec<usize>,marked: Vec<bool>,dirty: Vec<usize>,@@ -154,7 +277,11 @@ impl StrokeBuffer {Self {grid,paint: TileGrid::new(width, height),+ lift: TileGrid::new(width, height),+ ridge: TileGrid::new(width, height),mode: Mode::Flat,+ body: 0.0,+ lifting: false,touched: Vec::new(),dirty_marked: marked.clone(),marked,@@ -202,13 +329,30 @@ impl StrokeBuffer {self.grid.ensure(index)}- pub fn tiles_mut(&mut self, index: usize) -> (&mut [f32], Option<&mut [f32]>) {+ pub fn tiles_mut(&mut self, index: usize) -> Tiles<'_> {self.tile_mut(index);- let paint = match self.mode {- Mode::Flat => None,- _ => Some(self.paint.ensure(index)),- };- (self.grid.ensure(index), paint)+ Tiles {+ coverage: self.grid.ensure(index),+ paint: match self.mode {+ Mode::Flat => None,+ _ => Some(self.paint.ensure(index)),+ },+ lift: match self.lifting {+ true => Some(self.lift.ensure(index)),+ false => None,+ },+ ridge: match self.body > 0.0 {+ true => Some(self.ridge.ensure(index)),+ false => None,+ },+ }+ }++ pub fn ridge(&self, index: usize) -> Option<&[f32]> {+ match self.body > 0.0 {+ true => self.ridge.at(index),+ false => None,+ }}pub fn paint(&self, index: usize) -> Option<&[f32]> {@@ -218,6 +362,13 @@ impl StrokeBuffer {}}+ pub fn lift(&self, index: usize) -> Option<&[f32]> {+ match self.lifting {+ true => self.lift.at(index),+ false => None,+ }+ }+pub fn take_dirty(&mut self) -> Vec<usize> {let dirty = std::mem::take(&mut self.dirty);dirty.iter().for_each(|&i| self.dirty_marked[i] = false);@@ -246,10 +397,18 @@ impl StrokeBuffer {if let Some(tile) = self.paint.at_mut(i) {tile.fill(0.0);}+ if let Some(tile) = self.lift.at_mut(i) {+ tile.fill(0.0);+ }+ if let Some(tile) = self.ridge.at_mut(i) {+ tile.fill(0.0);+ }});self.touched = touched;self.touched.clear();self.mode = Mode::Flat;+ self.body = 0.0;+ self.lifting = false;}}@@ -259,20 +418,29 @@ mod tests {#[test]fn grid_covers_partial_tiles() {- let grid: Raster = TileGrid::new(300, 513);+ let grid = Raster::new(300, 513);assert_eq!((grid.cols, grid.rows), (2, 3));assert_eq!(grid.count(), 0);}#[test]fn raster_encode_round_trip() {- let mut raster: Raster = TileGrid::new(600, 300);+ let mut raster = Raster::new(600, 300);raster.ensure(4)[17] = f16::from_f32(0.25);raster.ensure(1)[3] = f16::from_f32(1.0);let back = Raster::decode(&raster.encode()).unwrap();assert_eq!(back.hash(), raster.hash());assert_eq!((back.width, back.height, back.count()), (600, 300, 2));+ assert!(!back.has_height());assert!(Raster::decode(&raster.encode()[..40]).is_err());+ let flat = raster.hash();+ raster.heights_mut().ensure(4)[17] = f16::from_f32(0.5);+ let back = Raster::decode(&raster.encode()).unwrap();+ assert_eq!(back.hash(), raster.hash());+ assert_ne!(raster.hash(), flat);+ assert_eq!(back.height_tile(4).unwrap()[17].to_f32(), 0.5);+ raster.clear(4);+ assert!(raster.height_tile(4).is_none());}#[test]diff --git a/crates/cli/src/agent.rs b/crates/cli/src/agent.rsindex 5e6a44f..a6828c6 100644--- a/crates/cli/src/agent.rs+++ b/crates/cli/src/agent.rs@@ -14,7 +14,7 @@ use std::io::Read;use std::path::{Path, PathBuf};pub const PREVIEW_SIDE: f32 = 1024.0;-const STRING_KEYS: [&str; 4] = ["name", "d", "id", "link"];+const STRING_KEYS: [&str; 5] = ["name", "d", "id", "link", "text"];pub struct Output {pub json: bool,@@ -72,7 +72,13 @@ pub fn parse_value(key: &str, text: &str) -> Value {if STRING_KEYS.contains(&last) {return Value::String(text.to_string());}- serde_json::from_str(text).unwrap_or_else(|_| Value::String(text.to_string()))+ serde_json::from_str(text).unwrap_or_else(|_| {+ let numbers: Option<Vec<f64>> = text.split(',').map(|n| n.trim().parse().ok()).collect();+ match numbers {+ Some(list) if list.len() > 1 => json!(list),+ _ => Value::String(text.to_string()),+ }+ })}pub fn parse_props(pairs: &[String]) -> Result<Map<String, Value>> {@@ -910,6 +916,8 @@ mod tests {assert_eq!(parse_value("fill", "#336699"), json!("#336699"));assert_eq!(parse_value("name", "42"), json!("42"));assert_eq!(parse_value("pivot", "[1,2]"), json!([1, 2]));+ assert_eq!(parse_value("light", "-1,-0.5"), json!([-1.0, -0.5]));+ assert_eq!(parse_value("name", "1,2"), json!("1,2"));assert_eq!(parse_value("visible", "false"), json!(false));}diff --git a/crates/cli/src/brushes.rs b/crates/cli/src/brushes.rsindex 9a754f3..54b5326 100644--- a/crates/cli/src/brushes.rs+++ b/crates/cli/src/brushes.rs@@ -58,6 +58,7 @@ fn tip(def: &BrushDef) -> String {(matches!(def.paint, Some(brushes::PaintDef::Wet { .. })), "wet"),(matches!(def.paint, Some(brushes::PaintDef::Smudge { .. })), "smudge"),(matches!(def.paint, Some(brushes::PaintDef::Blend { .. })), "blend"),+ (def.body > 0.0, "body"),].iter().filter(|(on, _)| *on)diff --git a/crates/core/brushes/library/oil-load.json b/crates/core/brushes/library/oil-load.jsonindex 036cec9..d612531 100644--- a/crates/core/brushes/library/oil-load.json+++ b/crates/core/brushes/library/oil-load.json@@ -8,5 +8,6 @@"opacity": 1.0,"dynamics": {"size": {"pressure": {"min": 0.15}}, "opacity": {"pressure": {"min": 0.65}}},"jitter": {"size": 0.05},- "grain": {"paper": {"seed": 29, "feature": 2}, "strength": 0.28}+ "grain": {"paper": {"seed": 29, "feature": 2}, "strength": 0.28},+ "body": 0.8}diff --git a/crates/core/brushes/library/oil.json b/crates/core/brushes/library/oil.jsonindex 815c8c5..e9a86be 100644--- a/crates/core/brushes/library/oil.json+++ b/crates/core/brushes/library/oil.json@@ -8,5 +8,6 @@"opacity": 1.0,"dynamics": {"size": {"pressure": {"min": 0.12}}, "opacity": {"pressure": {"min": 0.5}}},"jitter": {"size": 0.04},- "grain": {"paper": {"seed": 11, "feature": 3}, "strength": 0.12}+ "grain": {"paper": {"seed": 11, "feature": 3}, "strength": 0.12},+ "body": 0.45}diff --git a/crates/core/src/brushes.rs b/crates/core/src/brushes.rsindex b279dd3..f86845a 100644--- a/crates/core/src/brushes.rs+++ b/crates/core/src/brushes.rs@@ -75,6 +75,8 @@ pub struct BrushDef {pub stabilizer: f32,#[serde(default, skip_serializing_if = "is_zero")]pub smoothing: f32,+ #[serde(default, skip_serializing_if = "is_zero")]+ pub body: f32,}#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]@@ -416,7 +418,8 @@ impl BrushDef {within("taper in", self.taper[0], 0.0, 10_000.0)?;within("taper out", self.taper[1], 0.0, 10_000.0)?;within("stabilizer", self.stabilizer, 0.0, 500.0)?;- within("smoothing", self.smoothing, 0.0, 500.0)+ within("smoothing", self.smoothing, 0.0, 500.0)?;+ within("body", self.body, 0.0, 1.0)}pub fn to_json(&self) -> Result<String> {diff --git a/crates/core/src/look.rs b/crates/core/src/look.rsindex d7dca44..7672054 100644--- a/crates/core/src/look.rs+++ b/crates/core/src/look.rs@@ -14,6 +14,7 @@ pub enum Effect {Shadow(Shadow),Noise(Noise),Displace(Displace),+ Relief(Relief),}#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]@@ -205,11 +206,35 @@ impl Default for Displace {}}+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+#[serde(default, deny_unknown_fields)]+pub struct Relief {+ pub strength: f32,+ pub light: [f32; 2],+ pub highlight: String,+ pub shade: String,+ pub softness: f32,+}++impl Default for Relief {+ fn default() -> Self {+ Self {+ strength: 4.0,+ light: [-1.0, -1.0],+ highlight: "#fff4dc".into(),+ shade: "#1c1826".into(),+ softness: 0.8,+ }+ }+}+fn is_false(v: &bool) -> bool {!*v}-pub const EFFECTS: [&str; 7] = ["blur", "glow", "outline", "shadow", "noise", "displace", "haze"];+pub const EFFECTS: [&str; 8] = [+ "blur", "glow", "outline", "shadow", "noise", "displace", "haze", "relief",+];impl Effect {pub fn named(name: &str) -> Option<Self> {@@ -221,6 +246,7 @@ impl Effect {"noise" => Effect::Noise(Noise::default()),"displace" => Effect::Displace(Displace::default()),"haze" => Effect::Haze(Haze::default()),+ "relief" => Effect::Relief(Relief::default()),_ => return None,})}@@ -234,6 +260,7 @@ impl Effect {Effect::Noise(_) => "noise",Effect::Displace(_) => "displace",Effect::Haze(_) => "haze",+ Effect::Relief(_) => "relief",}}@@ -245,6 +272,7 @@ impl Effect {Effect::Shadow(s) => s.x.abs().max(s.y.abs()) + s.radius.max(0.0) * 3.0,Effect::Noise(_) | Effect::Haze(_) => 0.0,Effect::Displace(d) => d.amount.abs() + 1.0,+ Effect::Relief(r) => r.softness.max(0.0) * 3.0 + 2.0,}}@@ -274,6 +302,19 @@ impl Effect {colour(&h.color)?;h.top.as_deref().map_or(Ok(()), colour)}+ Effect::Relief(r) if !(0.0..=16.0).contains(&r.strength) => {+ bail!("relief strength {} is outside 0..16", r.strength)+ }+ Effect::Relief(r) if !(0.0..=32.0).contains(&r.softness) => {+ bail!("relief softness {} is outside 0..32", r.softness)+ }+ Effect::Relief(r) if r.light[0].hypot(r.light[1]) < 1e-3 => {+ bail!("relief light needs a direction, like -1,-1 for the upper left")+ }+ Effect::Relief(r) => {+ colour(&r.highlight)?;+ colour(&r.shade)+ }_ => Ok(()),}}diff --git a/crates/render/src/effects.rs b/crates/render/src/effects.rsindex 395c721..ccbfab6 100644--- a/crates/render/src/effects.rs+++ b/crates/render/src/effects.rs@@ -1,7 +1,7 @@use anyhow::Result;use klad_core::color::parse_hex;use klad_core::doc::Blend;-use klad_core::look::{self, Displace, Effect, Glow, Haze, Noise, Outline, Shadow};+use klad_core::look::{self, Displace, Effect, Glow, Haze, Noise, Outline, Relief, Shadow};use klad_core::rng::hash2_unit;use rayon::prelude::*;@@ -105,18 +105,17 @@ pub fn margin(effects: &[Effect], scale: f32) -> i32 {Effect::Glow(g) => factor(g.radius * scale) * 2 + 2,Effect::Shadow(s) => factor(s.radius * scale) * 2 + 2,Effect::Displace(_) => 2,+ Effect::Relief(r) => factor(r.softness * scale) * 2 + 2,_ => 1,}).sum();(look::reach(effects) * scale).ceil() as i32 + slack}-pub fn run(- effects: &[Effect],- img: Img,- space: Space,- by: &dyn Fn(&str) -> Result<Option<Img>>,-) -> Result<(Vec<Pass>, Img)> {+pub type Layer<'a> = &'a dyn Fn(&str) -> Result<Option<Img>>;+pub type Height<'a> = &'a dyn Fn() -> Result<Option<Img>>;++pub fn run(effects: &[Effect], img: Img, space: Space, by: Layer, height: Height) -> Result<(Vec<Pass>, Img)> {let s = space.scale;effects.iter().try_fold((Vec::new(), img), |(mut passes, img), effect| {let img = match effect {@@ -142,11 +141,52 @@ pub fn run(};displace(&img, d, space, map.as_ref())}+ Effect::Relief(r) => match height()? {+ Some(map) => relief(&img, r, s, &map)?,+ None => img,+ },};Ok((passes, img))})}+const LIFT: f32 = 0.85;+const DROP: f32 = 0.55;++pub fn relief(img: &Img, r: &Relief, scale: f32, height: &Img) -> Result<Img> {+ let [hr, hg, hb, _] = parse_hex(&r.highlight)?;+ let [sr, sg, sb, _] = parse_hex(&r.shade)?;+ let (high, low) = ([hr, hg, hb], [sr, sg, sb]);+ let length = r.light[0].hypot(r.light[1]).max(1e-6);+ let (lx, ly) = (r.light[0] / length, r.light[1] / length);+ let soft = blur(height, r.softness * scale);+ let k = r.strength * scale * 0.5;+ Ok(img.each(|gx, gy, p| {+ if p[3] <= 1e-5 {+ return p;+ }+ let h = |dx: i32, dy: i32| soft.at(gx + dx, gy + dy)[0];+ let (hx, hy) = ((h(1, 0) - h(-1, 0)) * k, (h(0, 1) - h(0, -1)) * k);+ let facing = -(hx * lx + hy * ly);+ let e = facing / libm::sqrtf(1.0 + hx * hx + hy * hy);+ if e.abs() < 1e-5 {+ return p;+ }+ let (to, t) = match e > 0.0 {+ true => (high, (e * LIFT).min(1.0)),+ false => (low, (-e * DROP).min(1.0)),+ };+ let a = p[3];+ let un = [p[0] / a, p[1] / a, p[2] / a];+ [+ (un[0] + (to[0] - un[0]) * t) * a,+ (un[1] + (to[1] - un[1]) * t) * a,+ (un[2] + (to[2] - un[2]) * t) * a,+ a,+ ]+ }))+}+pub fn over(top: &Img, under: &Img) -> Img {top.each(|gx, gy, t| {let u = under.at(gx, gy);@@ -539,11 +579,12 @@ mod tests {ty: 0.0,};let none = |_: &str| Ok(None);- let (_, reference) = run(&list, full.clone(), space, &none).unwrap();+ let flat = || Ok(None);+ let (_, reference) = run(&list, full.clone(), space, &none, &flat).unwrap();let m = margin(&list, 1.0);let (tx, ty, tw, th) = (128, 64, 64, 64);let window = full.crop(tx - m, ty - m, tw + 2 * m as usize, th + 2 * m as usize);- let (_, local) = run(&list, window, space, &none).unwrap();+ let (_, local) = run(&list, window, space, &none, &flat).unwrap();let (a, b) = (reference.crop(tx, ty, tw, th), local.crop(tx, ty, tw, th));let worst =a.px.iter()diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rsindex d46fb7a..ffaa01e 100644--- a/crates/render/src/lib.rs+++ b/crates/render/src/lib.rs@@ -269,7 +269,7 @@ pub fn draw_layers(canvas: &Canvas, layers: &[Layer], ctx: Ctx) -> Result<()> {.try_for_each(|(base, clipped)| draw_clipped(c, base, clipped, x))};match reads && !ctx.flat {- true => effected(canvas, ctx, &[], 1.0, Blend::Normal, &draw),+ true => effected(canvas, ctx, &[], None, 1.0, Blend::Normal, &draw),false => draw(canvas, ctx),}}@@ -297,7 +297,7 @@ fn draw_clipped(canvas: &Canvas, base: &Layer, clipped: &[&Layer], ctx: Ctx) ->draw_onions(canvas, std::iter::once(base).chain(shown.iter().copied()), ctx)?;let effects = ctx.effects(base);if !effects.is_empty() || shown.iter().any(|l| l.reads_under()) {- return effected(canvas, ctx, &effects, base.opacity, base.blend, &|c, x| {+ return effected(canvas, ctx, &effects, Some(base), base.opacity, base.blend, &|c, x| {draw_unit(c, base, &shown, x)}).with_context(|| format!("layer {}", base.id));@@ -337,7 +337,7 @@ fn draw_styled(canvas: &Canvas, layer: &Layer, ctx: Ctx) -> Result<()> {let effects = ctx.effects(layer);match effects.is_empty() {true => draw_content(canvas, layer, ctx),- false => effected(canvas, ctx, &effects, 1.0, Blend::Normal, &|c, x| {+ false => effected(canvas, ctx, &effects, Some(layer), 1.0, Blend::Normal, &|c, x| {draw_content(c, layer, x)}),}@@ -355,9 +355,15 @@ pub(crate) fn draw_layer(canvas: &Canvas, layer: &Layer, ctx: Ctx) -> Result<()>}let effects = ctx.effects(layer);if !effects.is_empty() {- return effected(canvas, ctx, &effects, layer.opacity, layer.blend, &|c, x| {- draw_content(c, layer, x)- })+ return effected(+ canvas,+ ctx,+ &effects,+ Some(layer),+ layer.opacity,+ layer.blend,+ &|c, x| draw_content(c, layer, x),+ ).with_context(|| format!("layer {}", layer.id));}let isolate = layer.opacity < 1.0 || layer.blend != Blend::Normal || layer.mask_at(ctx.frame).is_some();@@ -453,10 +459,86 @@ fn find<'a>(layers: &'a [Layer], id: &str) -> Option<&'a Layer> {.find_map(|l| (l.id == id).then_some(l).or_else(|| find(l.children(), id)))}+fn painted_cels(layer: &Layer, ctx: Ctx) -> Vec<String> {+ if !ctx.shows(layer) {+ return Vec::new();+ }+ match &layer.content {+ LayerContent::Paint { .. } => layer.content_at(ctx.frame).map(|c| c.id.clone()).into_iter().collect(),+ LayerContent::Group { children } => children.iter().flat_map(|l| painted_cels(l, ctx)).collect(),+ _ => Vec::new(),+ }+}++fn height_at(heights: &klad_brush::tiles::Heights, x: i32, y: i32) -> f32 {+ if x < 0 || y < 0 || x as u32 >= heights.width || y as u32 >= heights.height {+ return 0.0;+ }+ let (x, y) = (x as usize, y as usize);+ heights+ .get(x / TILE, y / TILE)+ .map_or(0.0, |t| t[(y % TILE) * TILE + x % TILE].to_f32())+}++fn sampled_height(heights: &klad_brush::tiles::Heights, cx: f32, cy: f32) -> f32 {+ let (fx, fy) = (cx - 0.5, cy - 0.5);+ let (x, y) = (fx.floor(), fy.floor());+ let (ax, ay) = (fx - x, fy - y);+ let (x, y) = (x as i32, y as i32);+ let top = height_at(heights, x, y) * (1.0 - ax) + height_at(heights, x + 1, y) * ax;+ let bottom = height_at(heights, x, y + 1) * (1.0 - ax) + height_at(heights, x + 1, y + 1) * ax;+ top * (1.0 - ay) + bottom * ay+}++fn height_img(window: IRect, space: Space, layer: &Layer, ctx: Ctx) -> Option<Img> {+ let maps: Vec<&klad_brush::tiles::Heights> = painted_cels(layer, ctx)+ .iter()+ .filter_map(|id| ctx.rasters.get(id).and_then(Raster::heights))+ .collect();+ if maps.is_empty() {+ return None;+ }+ let (w, h) = (window.width().max(0) as usize, window.height().max(0) as usize);+ let taps = ((1.0 / space.scale).ceil() as usize).clamp(1, 4);+ let step = 1.0 / (space.scale * taps as f32);+ let px = (0..h)+ .into_par_iter()+ .flat_map_iter(|row| {+ let maps = &maps;+ (0..w).map(move |col| {+ let (gx, gy) = (window.left + col as i32, window.top + row as i32);+ let (cx, cy) = (+ (gx as f32 - space.tx) / space.scale,+ (gy as f32 - space.ty) / space.scale,+ );+ let sum: f32 = (0..taps * taps)+ .map(|k| {+ let (sx, sy) = (+ cx + (k % taps) as f32 * step + step * 0.5,+ cy + (k / taps) as f32 * step + step * 0.5,+ );+ maps.iter().map(|m| sampled_height(m, sx, sy)).sum::<f32>()+ })+ .sum();+ [sum / (taps * taps) as f32, 0.0, 0.0, 0.0]+ })+ })+ .collect();+ Some(Img {+ x: window.left,+ y: window.top,+ w,+ h,+ px,+ })+}++#[allow(clippy::too_many_arguments)]fn effected(canvas: &Canvas,ctx: Ctx,list: &[Effect],+ owner: Option<&Layer>,opacity: f32,blend: Blend,draw: &dyn Fn(&Canvas, Ctx) -> Result<()>,@@ -474,9 +556,10 @@ fn effected(};offscreen(window, canvas, ctx, &|c, x| draw_content(c, layer, x.nested())).map(Some)};+ let height = || Ok(owner.and_then(|layer| height_img(window, space, layer, ctx)));let (passes, image) = match list.is_empty() {true => (Vec::new(), img),- false => effects::run(list, img, space, &by)?,+ false => effects::run(list, img, space, &by, &height)?,};canvas.save();canvas.reset_matrix();diff --git a/crates/render/src/look_tests.rs b/crates/render/src/look_tests.rsindex 8c52c87..4ab7dca 100644--- a/crates/render/src/look_tests.rs+++ b/crates/render/src/look_tests.rs@@ -502,3 +502,147 @@ fn an_imported_picture_draws_where_it_is_placed() {assert_eq!(frame.pixel(5, 5)[3], 0);let _ = std::fs::remove_dir_all(&root);}++fn painted(brush: &str, light: [f32; 2]) -> (Document, Rasters) {+ use klad_core::stroke::Stroke;+ let mut doc = Document::new(400, 200);+ doc.canvas.background = Some("#f0e8d8".into());+ let mut layer = Layer::paint("l1", "paint", "c1");+ layer.effects = vec![Effect::Relief(look::Relief {+ light,+ ..look::Relief::default()+ })];+ doc.layers = vec![layer];+ let points: Vec<(f32, f32, f32)> = (0..=40).map(|i| (40.0 + i as f32 * 8.0, 100.0, 1.0)).collect();+ let stroke = Stroke::new(1, brush, [0.75, 0.45, 0.2, 1.0], 56.0, 3).with_points(&points, 5.0);+ let raster = klad_brush::replay(400, 200, &[stroke.into()], &klad_brush::BrushSet::presets())+ .unwrap()+ .raster;+ let mut rasters = Rasters::new();+ rasters.insert("c1".into(), raster);+ (doc, rasters)+}++fn light_of(frame: &Frame, ys: std::ops::Range<u32>) -> u32 {+ ys.flat_map(|y| (120..280).map(move |x| (x, y)))+ .map(|(x, y)| frame.pixel(x, y)[..3].iter().map(|&c| c as u32).sum::<u32>())+ .sum()+}++#[test]+fn relief_lights_paint_edges_facing_the_light_and_leaves_flat_paint_alone() {+ let compose_with = |doc: &Document, rasters: &Rasters| compose(doc, 0, rasters, View::scaled(1.0)).unwrap();+ let (doc, rasters) = painted("oil-load", [0.0, -1.0]);+ let lit = compose_with(&doc, &rasters);+ let mut bare = doc.clone();+ bare.layers[0].effects.clear();+ let plain = compose_with(&bare, &rasters);+ assert_ne!(lit.hash(), plain.hash());+ let (top, bottom) = (78..86, 114..122);+ assert!(+ light_of(&lit, top.clone()) > light_of(&plain, top.clone()),+ "the top edge faces the light"+ );+ assert!(+ light_of(&lit, bottom.clone()) < light_of(&plain, bottom.clone()),+ "the bottom edge faces away"+ );+ let (from_below, _) = painted("oil-load", [0.0, 1.0]);+ let under = compose_with(&from_below, &rasters);+ assert!(+ light_of(&under, bottom.clone()) > light_of(&lit, bottom),+ "turning the light turns the relief"+ );+ let flat_rasters = painted("ink", [0.0, -1.0]).1;+ assert!(!flat_rasters["c1"].has_height());+ assert_eq!(+ compose_with(&doc, &flat_rasters).hash(),+ compose_with(&bare, &flat_rasters).hash()+ );+ let layers: Vec<&Layer> = doc.layers.iter().collect();+ let tiles = flatten(&doc, 0, &rasters, &layers, doc.canvas.background.as_deref()).unwrap();+ assert!(worst(&lit, &read_rgba8(&raster_image(&tiles).unwrap()).unwrap()) <= 1);+}++#[test]+#[ignore = "timing: cargo test --release -p klad-render relief_timing -- --ignored --nocapture"]+fn relief_timing() {+ use klad_core::stroke::Stroke;+ use std::time::Instant;+ let mut doc = Document::new(2048, 2048);+ doc.canvas.background = Some("#f0e8d8".into());+ let mut layer = Layer::paint("l1", "paint", "c1");+ layer.effects = vec![Effect::Relief(look::Relief::default())];+ doc.layers = vec![layer];+ let mut rng = klad_core::rng::Rng::new(7);+ let strokes: Vec<klad_core::stroke::Mark> = (0..600)+ .map(|i| {+ let (x, y) = (rng.unit() * 1900.0 + 74.0, rng.unit() * 1900.0 + 74.0);+ let turn = rng.signed() * 3.1;+ let points: Vec<(f32, f32, f32)> = (0..=12)+ .map(|k| {+ let t = k as f32 / 12.0 * 160.0;+ (x + t * turn.cos(), y + t * turn.sin(), 0.6 + 0.4 * (k as f32 / 12.0))+ })+ .collect();+ let colour = [0.5 + rng.unit() * 0.4, 0.4 + rng.unit() * 0.3, 0.2, 1.0];+ Stroke::new(i + 1, "oil-load", colour, 24.0 + rng.unit() * 40.0, i)+ .with_points(&points, 5.0)+ .into()+ })+ .collect();+ let started = Instant::now();+ let raster = klad_brush::replay(2048, 2048, &strokes, &klad_brush::BrushSet::presets())+ .unwrap()+ .raster;+ let replayed = started.elapsed().as_secs_f64() * 1000.0;+ let mut thin = klad_brush::BrushSet::presets();+ let mut def = thin.def("oil-load").unwrap().clone();+ def.body = 0.0;+ thin.insert("oil-load", def);+ let started = Instant::now();+ klad_brush::replay(2048, 2048, &strokes, &thin).unwrap();+ let flat_replay = started.elapsed().as_secs_f64() * 1000.0;+ let heights = raster.height_bytes() >> 20;+ let mut rasters = Rasters::new();+ rasters.insert("c1".into(), raster);+ let time = |doc: &Document, f: &dyn Fn(&Document)| {+ (0..5)+ .map(|_| {+ let t = Instant::now();+ f(doc);+ t.elapsed().as_secs_f64() * 1000.0+ })+ .fold(f64::MAX, f64::min)+ };+ let whole = |d: &Document| {+ compose(d, 0, &rasters, View::scaled(1.0)).unwrap();+ };+ let one = |d: &Document| {+ let items: Vec<TileItem> = d.layers.iter().map(TileItem::Layer).collect();+ compose_tile(+ &items,+ &TileJob {+ frame: 0,+ rasters: &rasters,+ background: d.canvas.background.as_deref(),+ tx: 3,+ ty: 3,+ swap: None,+ onions: None,+ doc: d,+ references: false,+ },+ )+ .unwrap();+ };+ let mut flat = doc.clone();+ flat.layers[0].effects.clear();+ println!(+ "2048 px, 600 oil-load strokes (replay {replayed:.0} ms, {flat_replay:.0} ms without body; heights {heights} MB): whole canvas {:.0} ms with relief, {:.0} ms without; one dirty tile {:.2} ms with, {:.2} ms without",+ time(&doc, &whole),+ time(&flat, &whole),+ time(&doc, &one),+ time(&flat, &one)+ );+}diff --git a/docs/DESIGN.md b/docs/DESIGN.mdindex b567cad..7f4d142 100644--- a/docs/DESIGN.md+++ b/docs/DESIGN.md@@ -1,4 +1,4 @@-_Last updated: 2026-11-04 20:11_+_Last updated: 2026-11-04 22:30_# klad: design@@ -228,7 +228,7 @@ Unknown keys are errors that list the valid ones, so a typo never passes silentlEvery layer has `blend`, `opacity`, `visible`, `locked`, optional `mask`, `clip` and (M5, format 8) `effects`. Effects are layer settings, not a layer kind: the planned `filter` kind became them.- **Blend modes.** `normal`, `multiply`, `screen`, `overlay`, `add`, and since M5 `color-dodge`, `soft-light`, `hard-light`, `lighten`, `darken`, `color`, `luminosity`, all as in the W3C compositing spec (Skia's modes; `look::blend_rgb` and `look::composite` hold the formulas the tests check them against).-- **Effects (M5).** `"effects": [{"glow": {...}}, {"outline": {...}}]`, applied in order to the layer's content (after its mask; for a clip base, to the base and its clipped layers together) before its opacity and blend: `blur` (radius, a Gaussian sigma), `glow` (radius, strength, threshold: 0 glows from every pixel, higher only from the bright ones; color: a tint; blend: how the glow mixes with what is under the layer, screen by default, normal lays it like paint under the layer), `outline` (width, color, inside), `shadow` (x, y, radius, color, laid under the layer), `noise` (amount, size, seed, mono: a grain fixed to the canvas), `displace` (amount, size, seed, by: smooth waves, or a layer whose red pushes across and green down). Each effect knows its reach (`look::reach`), so a tile is composed from its content within the tile plus that margin and tiles meet without seams; the pixels are computed in Rust (`klad-render/effects.rs`) on f32 with absolute coordinates, so a tile equals the same pixels of the whole image byte for byte (tested). Blurs use a direct kernel, below a sigma of 2 at full size and above it on a grid of 2, 4, ... px blocks anchored to the canvas, then sampled back.+- **Effects (M5).** `"effects": [{"glow": {...}}, {"outline": {...}}]`, applied in order to the layer's content (after its mask; for a clip base, to the base and its clipped layers together) before its opacity and blend: `blur` (radius, a Gaussian sigma), `glow` (radius, strength, threshold: 0 glows from every pixel, higher only from the bright ones; color: a tint; blend: how the glow mixes with what is under the layer, screen by default, normal lays it like paint under the layer), `outline` (width, color, inside), `shadow` (x, y, radius, color, laid under the layer), `noise` (amount, size, seed, mono: a grain fixed to the canvas), `displace` (amount, size, seed, by: smooth waves, or a layer whose red pushes across and green down), `relief` (strength, light, highlight, shade, softness: lights the paint height of the layer's drawings, below). Each effect knows its reach (`look::reach`), so a tile is composed from its content within the tile plus that margin and tiles meet without seams; the pixels are computed in Rust (`klad-render/effects.rs`) on f32 with absolute coordinates, so a tile equals the same pixels of the whole image byte for byte (tested). Blurs use a direct kernel, below a sigma of 2 at full size and above it on a grid of 2, 4, ... px blocks anchored to the canvas, then sampled back.- **Adjustment layers (M5).** An `adjust` layer changes what is under it in its list: the layers below it in its group, or, clipped, its base. A group holding an adjustment is composed apart, so the adjustment stays inside it. The colour math is on unpremultiplied sRGB values with alpha kept: `hsl` (hue in degrees, saturation and lightness -1..1), `levels` (black, white, gamma, low, high), `curves` (points, and red, green, blue applied before them; monotone cubic, no overshoot), `balance` (shadows, midtones, highlights: cyan to red, magenta to green, yellow to blue, keepLight), `gradient-map` (stops by brightness). The layer's opacity, blend and mask decide how much of the adjusted colour replaces the colour under it. `fill` (a solid or gradient paint) is drawn like a content layer instead, with the layer's blend.- **Rays (M5).** A vector node `{"type": "rays", "x", "y", "angle", "spread", "count", "length", "start", "falloff", "noise", "seed"}` draws soft beams from an origin (a gap `start` px wide), each a quad with a radial falloff and its own length and strength from the seed; the node's `fill` colours them and its `blur` softens them. Rays come from the agent (`klad add rays`); in the editor a selected rays node shows its settings in the inspector.- **Depth and atmosphere (M5).** A layer at the top of the stack (a plane, usually a group) may have a `depth` (0 is near; validation refuses it deeper in the tree). The document's `atmosphere` (`color`, an optional `top` colour blended down over the canvas height, `density`, `blur`, `desaturate`) turns each plane's depth into two effects after its own (`Document::effects_of`): a `haze` towards the fog of `1 - e^(-density x depth)` with `desaturate x depth` of its colour taken out, and a blur of `blur x depth` px. `haze` is an ordinary effect too. The depths are kept for M6's Parallax2D export; in the editor a depth field sits in each plane's row and inspector, the inspector holds the atmosphere, and holding D shows the planes (each flattened alone, in the background) sliding by `offset x 0.08 / (1 + depth)` with the pointer.@@ -294,6 +294,7 @@ The editor keeps this record per paint cel. The CLI keeps the final tiles in `.c- **Grain.** A canvas-space texture modulates dab alpha (paper tooth).- **Stroke buffer.** Dabs build up in an f32 coverage buffer towards a cap, the brush opacity times its opacity curve (flow vs opacity, as in Photoshop: one stroke never darkens itself past the cap, overlapping strokes do). A round tip's coverage is its profile averaged over the pixel, so a hard tip has a one pixel antialiased edge. Where the tip's falloff is under about a pixel wide (hard tips), a pixel builds up only to the coverage the dab gives it, not past it: dabs are placed a few per pixel, and building up towards the cap turned the half covered pixels along a line's edge solid, so hard lines lost their antialiasing and lines under 2 px were drawn heavier than their size. Tips with a falloff of 2 px or more build up as before, with a blend between. The stroke then composites into the layer at the stroke's opacity with the brush's blend (normal, erase).- **Wet paint, smudge and blend (M5).** A brush's `paint` is `wet` (wetness, pickup, dilution), `smudge` (strength) or `blend` (strength). They read only the drawing they paint into (its pixels before the stroke, and the stroke's own work so far), never other layers. The stroke buffer gains a colour layer: per-dab colour (colour dynamics and wet pickup, weighted by the coverage each dab adds) or, for smudge and blend, the replaced pixels (smudge takes each pixel from where the dab was before, blend averages a ring around it at 0.3 of the radius); landing a stroke lays its per-pixel colour over the layer or moves the layer's pixels towards the replaced ones. Replay is in stroke order, so a reading stroke sees what was under it; a tile-local update rebuilds the drawing when a reading stroke comes after the first changed mark (a test checks an edit under a smudge against a full replay). Live painting reads the active drawing too, so what is drawn is what replays.+- **Paint with body (M5, S5.23).** A brush's `body` (0 to 1, 0 by default; `oil` 0.45, `oil-load` 0.8) makes its strokes lay paint height. A drawing's raster (`klad_brush::Raster`) is its colour tiles plus an optional height channel (one f16 per pixel, in the same tiles), made the first time a stroke with body lands, so drawings without body cost nothing and keep their hash. While a stroke with body is drawn, each dab keeps the highest thickness it reaches per pixel (a lip rising towards the tip's edge times a groove profile across the stroke, fixed per stroke from its seed and size, so grooves follow the stroke; thinning to 55% after eight sizes of travel as the brush runs dry); when it lands, the height becomes `h (1 - 0.55 a) + body a' t`, with `a` the stroke's coverage times opacity, `a'` the coverage times half to all of it (thin strokes still have body) and `t` that thickness, so new paint partly squashes what is under it and the last few strokes' texture shows. Lock alpha lays height only where there is paint; the eraser scales it down by its coverage; smudge and blend carry height with the pixels they move, and wet paint takes it into its reservoir like colour. Height is kept in replay checkpoints and in the drawing cache (a height section after the colour tiles; engine version 4). The `relief` effect samples the height of the layer's drawings (a group: of all its paint layers) into the effect window at the view scale, blurs it by `softness`, and for each pixel moves the colour towards `highlight` where the slope faces `light` and towards `shade` where it faces away (an emboss, by the slope's share of `strength`); flat paint stays as it is. Costs on a 2048 canvas with 600 big oil-load strokes: replay 854 ms instead of 712 ms without body, 8 MB of height, a whole compose 127 ms instead of 15 ms, one dirty tile 1.8 ms.- **Reshaping (M5).** A stroke's `path` can be set (`set`, `klad reshape`, A in the editor): every sample keeps its pressure, tilt and timing and moves to the same fraction of the new path's length as it had of the old one. The editor and `klad strokes --json` fit a few points to a stroke (`pathedit::fit_polyline`, the simplification `klad path` uses, at 0.12 of the stroke's size between 1 and 6 px); A edits those points and writes the bent path as one `set`.### Brushes as data@@ -439,7 +440,7 @@ Scripts are any language that prints edit ops as JSON lines into `klad apply`. G- Notes on the canvas (M4 batch 4, `editor/pins.rs`): every open note is a pin, those of other frames dimmed with their frame, done ones on this frame checked in green. With the note tool a click on a pin opens its popover (the text to edit and save, done, remove, close); elsewhere it opens a popover for a new note at that spot ("pin it"). A right click on any pin, of this frame or a dimmed one of another, goes to its frame and selects it (an accent ring and its popover); Delete removes the selected note. The Notes pane lists the open notes (a click goes to the frame and opens the pin) and the done ones folded, each can be opened again. The editor watches `.cache/notes.json`, so the agent's `klad notes --done` shows at once.- Settings (M4 batch 4, `settings.rs`, `editor/prefs.rs`): the settings file carries a `version` (2; files without one, the M1 to M4 ones, load with the new fields at their defaults and are stamped 2), `keys` (command id to key labels such as `shift D`, only the changed ones), `uiScale` (0.75 to 2, egui's zoom factor, so every control grows with it) and `defaults` (brush and size for new windows, the shift K exposure, onion before, after and opacity, the grey around the canvas). The window has pen calibration, defaults, keys (search, change by pressing the key, no key, reset one or all) and layout. `commands::Bindings` holds the keys: a changed command's keys replace its first ones, a key another command already uses is refused and that command named (`taken_by`), holds (Q, W, space) keep their keys, and every key lookup (dispatch, hints, the palette, the strip's letters) goes through it.- Export to Godot (M3 batch 3): the clip row has a "Godot folder" field (the document's `export.godot`; a typed folder is relative to the folder holding the bundle) and an "export to Godot" button, which runs `klad export <bundle> --godot` (with the typed folder and `--store` when it differs) as a background job of the same binary, so the CLI and the editor write the same files; its summary or error is a message.-- CLI forms in the editor (M5, S5.25, `editor/checks.rs`, `editor/export.rs`): refill this drawing and show gaps (the fill tool's options and the palette), fill like the first drawing (the timeline selection toolbar), a part name for the selected marks (the stroke inspector, the `part` op), show parts and show arcs of the selected mark or part over the clip (the palette), an export window (the document menu, cmd E: this frame, a layer, numbered frames or a sprite sheet, and Godot) and add a font (the document menu and the text inspector, with the macOS open panel). Everything but the part name runs the `klad` binary as a background job with the same arguments a person would type (`crate::start::draw_binary` finds it next to the editor, and next to the test binaries in tests), so the CLI and the editor do the same thing by construction; gaps and arcs read the command's `--json` and draw on the canvas until the next edit. The ops that draw from shapes (`ink`, `light`, `hatch`, `paint`, `scatter`) stay CLI only (principle 7).+- CLI forms in the editor (M5, S5.25, `editor/checks.rs`, `editor/export.rs`): refill this drawing and show gaps (the fill tool's options and the palette), fill like the first drawing (the timeline selection toolbar), a part name for the selected marks (the stroke inspector, the `part` op), show parts and show arcs of the selected mark or part over the clip (the palette), an export window (the document menu, cmd E: this frame, a layer, numbered frames or a sprite sheet, and Godot) and add a font (the document menu and the text inspector, with the macOS open panel). Paint with body (S5.23): a body slider at the top of the brush window, and relief in the inspector's effects with a light dial (click or drag towards the light). Everything but the part name runs the `klad` binary as a background job with the same arguments a person would type (`crate::start::draw_binary` finds it next to the editor, and next to the test binaries in tests), so the CLI and the editor do the same thing by construction; gaps and arcs read the command's `--json` and draw on the canvas until the next edit. The ops that draw from shapes (`ink`, `light`, `hatch`, `paint`, `scatter`) stay CLI only (principle 7).- Agent channel: the current selection and pinned notes are written to `.cache/selection.json` and `.cache/notes.json` for `klad selection` and `klad notes`; both carry the frame.- Vector layers are rasterised into tiles when opened and when their nodes change; per-tile composition then only draws one tile per layer.diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.mdindex 5833e5d..42208fc 100644--- a/docs/skill/SKILL.md+++ b/docs/skill/SKILL.md@@ -48,7 +48,7 @@ klad stroke art.draw l4 --brush ink --size 14 --color '#1b1b1b' --path 'M100 400klad stroke art.draw l4 --brush ink --size 5 --taper 8,20 --path 'M100 100 L140 220'```-- `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` or `+blend`. `--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.+- `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.- 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`.@@ -117,7 +117,7 @@ klad add art.draw rays --in l7 x=430 y=0 angle=95 spread=40 count=9 length=600 sklad set art.draw l5 blend=soft-light```-- Effects are settings on a layer (or group), applied in order when it composes and always editable: `blur` (radius), `glow` (radius, strength, threshold: 0 glows from every pixel, about 0.7 only from the bright ones, as bloom; color tints it; blend: screen by default, add for hard light, normal lays it like paint), `outline` (width, color, inside=true), `shadow` (x, y, radius, color with alpha), `noise` (amount, size, seed, mono=false for coloured grain), `displace` (amount, size, seed; by=<layer> pushes with that layer's red across and green down, grey stays put; a hidden layer works as the map). In `apply` or `set`: `effects=[{"glow":{"radius":24}},{"outline":{"width":3}}]`.+- Effects are settings on a layer (or group), applied in order when it composes and always editable: `blur` (radius), `glow` (radius, strength, threshold: 0 glows from every pixel, about 0.7 only from the bright ones, as bloom; color tints it; blend: screen by default, add for hard light, normal lays it like paint), `outline` (width, color, inside=true), `shadow` (x, y, radius, color with alpha), `noise` (amount, size, seed, mono=false for coloured grain), `displace` (amount, size, seed; by=<layer> pushes with that layer's red across and green down, grey stays put; a hidden layer works as the map), `relief` (strength, light=x,y as in `paint --light`, highlight, shade, softness: lights the paint's thickness, so ridges and stroke edges facing the light catch it and the others darken; only strokes from brushes with `body` have thickness). In `apply` or `set`: `effects=[{"glow":{"radius":24}},{"outline":{"width":3}}]`.- Bloom: put everything that should bloom in a group and give the group a glow with a threshold and blend add. A light layer is a paint layer with `blend=add` and a soft glow (`'effects=[{"glow":{"radius":24,"strength":0.8}}]'`): paint light into it with `soft` or `airbrush`.- Blend modes: normal, multiply, screen, overlay, add, color-dodge, soft-light, hard-light, lighten, darken, color, luminosity.- Adjustment layers change what is under them in their group (or, with `clip=true`, only their base): `hsl` (hue in degrees, saturation and lightness -1..1), `levels` (black, white, gamma, low, high), `curves` (points, and red, green, blue applied first; x is the input brightness, y the output), `balance` (shadows, midtones, highlights as [cyan-red, magenta-green, yellow-blue] in -1..1, keepLight), `gradient-map` (stops by brightness), `fill` (paint: a colour or gradient, drawn with the layer's blend). Their opacity, blend and mask apply. To grade a scene, put one curves layer on top; to grade one part, put the part and the adjustment in a group.@@ -193,7 +193,7 @@ klad paint art.draw paint --in pillar --form cylinder --axis 90 --lamp 200,600,1klad prepare art.draw # buffer every drawing before the user opens it```-- Painting a form: after the flats, `klad paint` paints each shape as a form. `--form round` (default) bulges any closed shape like a pillow, its height growing with the distance to the outline; `flat` is a plane facing `--facing x,y,z` (z toward the viewer, y down); `cylinder` is round across `--axis` degrees. The light model is a key light from `--light x,y` at `--elevation` (or `--lamp x,y,height` in canvas px: the shape nearest the lamp gets the full key light, farther ones less by inverse square, so paint a cluster in one op), cool fill from above (`--fill`, `--fill-strength`), warm bounce from below (`--bounce`, `--bounce-strength`) and a darker core just past the terminator (`--core`); `--color` is the local colour in full light, so the lit side comes out at that colour and the shadow side about four value steps under it. The lights multiply the local colour, so a warm colour goes darker and browner in shadow; `--shadow <colour>` (`"shadow"` in `apply`) turns the side out of the key light towards that colour's hue and chroma while keeping the values the model gives it, by `--shadow-mix` (default 0.7) and less in the halftones, with the chroma lowered in the darkest parts. A cool lavender or blue grey keeps shadows from going brown or grey; raise `--fill-strength` (0.3 or so) for lighter shadow sides. Every colour option of `paint` takes palette names. Strokes follow the form (along bands of equal light on round forms, along the axis on cylinders, at `--angle` on planes), take their colour from the model where they lie and stop where the light changes, so none carries the lit colour into the shadow. Passes go from twice `--weight` down to half of it (the small ones only where the form turns), then a decisive pass with `--bold` (`oil-load`) in the lights and a few quiet strokes in the shadows (`--decisive 0` skips both); `--vary` lets each stroke stray in value and temperature. Paint on a layer clipped to the flats, or lock the flats layer and paint into it: strokes then run past the outline and short strokes along it cut the edge in; on a plain layer they stay inside it and the flats show at the rim.+- Painting a form: after the flats, `klad paint` paints each shape as a form. `--form round` (default) bulges any closed shape like a pillow, its height growing with the distance to the outline; `flat` is a plane facing `--facing x,y,z` (z toward the viewer, y down); `cylinder` is round across `--axis` degrees. The light model is a key light from `--light x,y` at `--elevation` (or `--lamp x,y,height` in canvas px: the shape nearest the lamp gets the full key light, farther ones less by inverse square, so paint a cluster in one op), cool fill from above (`--fill`, `--fill-strength`), warm bounce from below (`--bounce`, `--bounce-strength`) and a darker core just past the terminator (`--core`); `--color` is the local colour in full light, so the lit side comes out at that colour and the shadow side about four value steps under it. The lights multiply the local colour, so a warm colour goes darker and browner in shadow; `--shadow <colour>` (`"shadow"` in `apply`) turns the side out of the key light towards that colour's hue and chroma while keeping the values the model gives it, by `--shadow-mix` (default 0.7) and less in the halftones, with the chroma lowered in the darkest parts. A cool lavender or blue grey keeps shadows from going brown or grey; raise `--fill-strength` (0.3 or so) for lighter shadow sides. Every colour option of `paint` takes palette names. Strokes follow the form (along bands of equal light on round forms, along the axis on cylinders, at `--angle` on planes), take their colour from the model where they lie and stop where the light changes, so none carries the lit colour into the shadow. Thick paint: `oil` and `oil-load` have `body` (a brush key, 0 to 1), so their strokes lay paint height with bristle grooves and a lip at the edge, building up where they cross; `smudge` and `wet` drag it, `blender` flattens it, the eraser takes it. It shows only through a `relief` effect on the layer (`klad effect art.draw <layer> relief strength=3 light=-1,-1`): about 4 for fruit or a figure, 1 to 2 for a table or a wall, whose short decisive strokes otherwise stand out like stickers. Without the effect body changes no pixel. Passes go from twice `--weight` down to half of it (the small ones only where the form turns), then a decisive pass with `--bold` (`oil-load`) in the lights and a few quiet strokes in the shadows (`--decisive 0` skips both); `--vary` lets each stroke stray in value and temperature. Paint on a layer clipped to the flats, or lock the flats layer and paint into it: strokes then run past the outline and short strokes along it cut the edge in; on a plain layer they stay inside it and the flats show at the rim.- Every stroke the shape ops make is drawn like a hand (`--hand 1`, the default; `0` gives the old even strokes): its own pressure curve (a press-in, a peak, a longer lift-off), tapers that are a share of its length, a width that varies from stroke to stroke, and a slight bow on hatching and flat planes. Brushes for it: `oil` (soft edge, size and opacity from pressure) for building forms, `oil-load` (harder edge, more grain) for strokes that should stay visible.- `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.diff --git a/samples/README.md b/samples/README.mdindex 64fd024..d04eb77 100644--- a/samples/README.md+++ b/samples/README.md@@ -8,7 +8,7 @@ Drawings made from scratch with the `klad` CLI, each from a generator that print| `ink-shapes` | The ink options side by side: weight from the light, breaks, gaps, wobble, tapers || `bounce` | Frame-by-frame timing: keys, holds, a clip and the exports || `creature` | A walk and an idle from keys with named parts, in-betweened, coloured from the first drawing, with arcs checked |-| `lemons` | Painting by form with `klad paint` on locked flats, and a shadow colour: lavender shadows instead of brown ones (`PLAIN=1`: without it) |+| `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) || `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/lemons/build.sh b/samples/lemons/build.shindex 93fe217..3211f7d 100755--- a/samples/lemons/build.sh+++ b/samples/lemons/build.sh@@ -15,7 +15,7 @@ if [ -e "$out" ] && [ "${FORCE:-0}" != 1 ]; thenfirm -rf "$out""$klad" new "$out" --width 1200 --height 900 --layers 0 >/dev/null-python3 "$here/generate.py" ${PLAIN:+--plain} | "$klad" apply "$out" >/dev/null+python3 "$here/generate.py" ${PLAIN:+--plain} ${RELIEF:+--relief} | "$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/lemons/generate.py b/samples/lemons/generate.pyindex 862ba60..f0de3bd 100644--- a/samples/lemons/generate.py+++ b/samples/lemons/generate.py@@ -3,6 +3,7 @@ import mathimport sysPLAIN = "--plain" in sys.argv+RELIEF = "--relief" in sys.argvLIGHT = [-0.7, -0.7]KEY = "#fff1dc"SHADOW = "#9d8fc4"@@ -30,6 +31,7 @@ SHAPES = {"C 820 509 704 540 560 540 C 416 540 300 509 300 470 Z"},"lemon-c": {"type": "path", "d": lemon(905, 706, 102, 70, -8)},}+RELIEF_STRENGTH = {"table": 1.2, "inside": 2, "lemon-a": 4, "lemon-b": 4, "bowl": 2.5, "lemon-c": 4}PAINT = {"table": dict(color="table", form="flat", facing=[0, -1, 0.9], angle=2, weight=20, decisive=0.6),"inside": dict(color="clay inside", form="flat", facing=[0.35, 0.5, 1], angle=0, weight=12),@@ -61,6 +63,8 @@ def ops():paint.update(shadow=SHADOW, shadowMix=0.7)out.append(paint)out.append({"op": "set", "id": f"{id}-layer", "lockAlpha": False})+ if RELIEF:+ out.append({"op": "set", "id": f"{id}-layer", "effects": [{"relief": {"light": LIGHT, "highlight": KEY, "strength": RELIEF_STRENGTH[id]}}]})shadows = [("cast", 650, 704, 285, 40, COLOURS["cast"], 16), ("cast", 610, 694, 200, 16, COLOURS["contact"], 6),("cast-front", 948, 768, 110, 20, COLOURS["cast"], 10), ("cast-front", 925, 768, 70, 8, COLOURS["contact"], 4)]out += [{"op": "add", "node": {"type": "ellipse", "cx": x, "cy": y, "rx": rx, "ry": ry, "fill": c, "blur": b}, "in": f"{l}-layer"}