A drawing app built for agent/human collaboration
Rust
Godot rigs and parallax scenes, and the rig sample
Indicode BV78000f617985
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2182816..9c0231f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,9 @@ The first downloadable builds.- `klad --version` and About show the commit a build was made from.- In-betweens blend colours evenly (in OKLab), so light can follow a turning limb when the second key is coloured for it.- `klad arcs` follows the part of a foot on the ground: a heel-to-toe roll is no longer reported as a slide.+- Bones: a layer or group gets a skeleton (`klad bone`, the bone tool J), weights from the bones or painted (`klad weights`), and poses that bend the drawing (`klad pose`, pose mode); in-betweens of two poses turn the bones.+- Keys: layers, groups and shapes move, turn, scale and fade between frames with eases (`klad key`, the keys section of the inspector).+- Godot: `--godot-rig` exports a Skeleton2D with Polygon2D parts and the poses as animations; `--godot-scene` a parallax scene with a Parallax2D per depth plane.- `klad paintover` (and "paint over" in the layers panel): brushwork from any picture, strokes that follow its forms and stop at its colour edges, big to small, detail where the picture has it; `--like` and `--frames` carry it through an animation without boiling.- `klad compare` (and "compare with the reference" in the editor): a drawing against a reference picture in numbers and words, with a heat map.- Large stills render several times faster: strokes land only where they painted, and the CLI replays a drawing's tiles on every core (same pixels).diff --git a/crates/app/src/editor/clips.rs b/crates/app/src/editor/clips.rsindex 2ee1298..522530f 100644--- a/crates/app/src/editor/clips.rs+++ b/crates/app/src/editor/clips.rs@@ -334,6 +334,24 @@ impl Editor {self.timeline.godot.1.trim().to_string()}+ pub(super) fn export_godot_as(&mut self, how: &str) {+ let typed = self.godot_folder();+ let args = godot_args(&self.scene.bundle.root, how, &resolve(&self.bundle_home(), &typed));+ self.start_job(Spec {+ tag: Tag::Export,+ name: format!(+ "export a Godot {} ({typed})",+ if how == "--godot-rig" { "rig" } else { "parallax scene" }+ ),+ exe: PathBuf::new(),+ args,+ env: Vec::new(),+ reruns: 3,+ summary: |out, _| out.lines().last().unwrap_or_default().to_string(),+ failure: |_, err| failure(err),+ });+ }+pub(super) fn export_godot(&mut self) {let typed = self.godot_folder();let mut args: Vec<String> = vec![@@ -358,10 +376,29 @@ impl Editor {}}+pub(super) fn godot_args(bundle: &std::path::Path, how: &str, folder: &std::path::Path) -> Vec<String> {+ vec![+ "export".into(),+ bundle.to_string_lossy().to_string(),+ how.to_string(),+ folder.to_string_lossy().to_string(),+ ]+}+#[cfg(test)]mod tests {use super::*;+ #[test]+ fn the_scene_and_rig_buttons_run_the_cli_export() {+ let args = godot_args(+ std::path::Path::new("/w/a.draw"),+ "--godot-rig",+ std::path::Path::new("/w/game/art"),+ );+ assert_eq!(args.join(" "), "export /w/a.draw --godot-rig /w/game/art");+ }+#[test]fn overlapping_clips_take_separate_lanes() {let clips = vec![diff --git a/crates/app/src/editor/export.rs b/crates/app/src/editor/export.rsindex 4a798f8..6959876 100644--- a/crates/app/src/editor/export.rs+++ b/crates/app/src/editor/export.rs@@ -211,6 +211,23 @@ impl Editor {{self.export_godot();}+ if ui+ .button("as a parallax scene")+ .hint("each top-level layer a texture with its fog, on a Parallax2D that scrolls by its depth")+ .clicked()+ {+ self.export_godot_as("--godot-scene");+ }+ let rigged = self.scene.bundle.doc.all_layers().iter().any(|l| !l.bones.is_empty());+ if ui+ .add_enabled(rigged, egui::Button::new("as a rig"))+ .hint(+ "the rest drawing on Polygon2Ds weighted to a Skeleton2D, and the poses of every clip; needs bones",+ )+ .clicked()+ {+ self.export_godot_as("--godot-rig");+ }});if run {self.export()?;diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rsindex e83f9ed..a3289f7 100644--- a/crates/cli/src/main.rs+++ b/crates/cli/src/main.rs@@ -20,6 +20,7 @@ mod marks;mod paintover;mod paths;mod rig;+mod scene;mod shapes;mod sheet;mod sprites;@@ -1498,6 +1499,20 @@ enum Command {help = "Keep the --godot folder as the document's, replacing the one it has")]store: bool,+ #[arg(+ long = "godot-scene",+ num_args = 0..=1,+ conflicts_with_all = ["sheet", "frames"],+ help = "A Godot parallax scene: each top-level layer a texture (with its fog) on a Parallax2D that scrolls by 1/(1+depth), into this folder (default: the document's export.godot)"+ )]+ godot_scene: Option<Option<PathBuf>>,+ #[arg(+ long = "godot-rig",+ num_args = 0..=1,+ conflicts_with_all = ["sheet", "frames"],+ help = "A Godot rig: the rest drawing as Polygon2Ds weighted to a Skeleton2D, and an AnimationPlayer with the poses of every clip, into this folder"+ )]+ godot_rig: Option<Option<PathBuf>>,#[arg(long, default_value_t = 2, help = "Sheets: transparent pixels around each picture")]padding: u32,#[arg(long, default_value_t = 4096, help = "Sheets: largest page side in px")]@@ -3085,10 +3100,23 @@ fn run() -> Result<()> {frames,godot,store,+ godot_scene,+ godot_rig,padding,max,out,} => {+ let scenes = godot_scene.is_some() || godot_rig.is_some();+ if let Some(dir) = godot_scene {+ scene::parallax(&bundle, dir.or(out.clone()), frame)?+ .iter()+ .for_each(|f| println!("{}", f.display()));+ }+ if let Some(dir) = godot_rig {+ scene::rig(&bundle, dir.or(out.clone()))?+ .iter()+ .for_each(|f| println!("{}", f.display()));+ }let look = sprites::Look {layer: layer.clone(),scale,@@ -3100,6 +3128,7 @@ fn run() -> Result<()> {(Some(spec), _, _) => sprites::sheet(&bundle, &spec, &look, &packing, out)?,(_, Some(spec), _) => sprites::frames(&bundle, &spec, &look, out)?,(_, _, Some(dir)) => sprites::godot(&bundle, dir.or(out), store, &look, &packing)?,+ _ if scenes => {}_ => export::run(&bundle,export::Export {diff --git a/crates/cli/src/scene.rs b/crates/cli/src/scene.rsnew file mode 100644index 0000000..3d8ca88--- /dev/null+++ b/crates/cli/src/scene.rs@@ -0,0 +1,658 @@+use crate::layers::{self, Vectors};+use crate::sprites::{bundle_dir, bundle_stem, file_safe, read};+use anyhow::{Context, Result, bail};+use klad_brush::{BrushSet, Raster, TILE};+use klad_core::bundle::{Bundle, write_atomic};+use klad_core::doc::Layer;+use klad_render::sprites::{header_uid, import_uid, node_name, number, quoted, uid_for};+use klad_render::{Rasters, flatten_with};+use std::fs;+use std::path::{Path, PathBuf};++pub fn rgba(raster: &Raster) -> Vec<u8> {+ let (w, h) = (raster.width as usize, raster.height as usize);+ let mut out = vec![0u8; w * h * 4];+ raster.occupied().for_each(|(index, tile)| {+ let (ox, oy) = ((index % raster.cols) * TILE, (index / raster.cols) * TILE);+ tile.chunks(4).enumerate().for_each(|(i, px)| {+ let (x, y) = (ox + i % TILE, oy + i / TILE);+ if x >= w || y >= h {+ return;+ }+ let a = px[3].to_f32().clamp(0.0, 1.0);+ if a <= 0.0 {+ return;+ }+ let at = (y * w + x) * 4;+ (0..3).for_each(|c| out[at + c] = ((px[c].to_f32() / a).clamp(0.0, 1.0) * 255.0).round() as u8);+ out[at + 3] = (a * 255.0).round() as u8;+ });+ });+ out+}++pub fn png(w: u32, h: u32, pixels: Vec<u8>) -> Result<Vec<u8>> {+ klad_render::assets::encode_png(&klad_render::assets::Rgba {+ width: w,+ height: h,+ pixels,+ })+}++fn target(bundle: &Bundle, dir: Option<PathBuf>) -> Result<PathBuf> {+ let home = bundle_dir(bundle);+ let target = match (dir, &bundle.doc.export.godot) {+ (Some(d), _) => d,+ (None, Some(s)) => home.join(s),+ (None, None) => {+ bail!("give the Godot folder to write into, or set one with klad export --godot <folder> first")+ }+ };+ fs::create_dir_all(&target).with_context(|| format!("making {}", target.display()))?;+ Ok(target)+}++fn uid_of(file: &Path) -> String {+ read(file)+ .and_then(|t| header_uid(&t))+ .unwrap_or_else(|| uid_for(&file.to_string_lossy()))+}++fn texture_uid(file: &Path) -> String {+ read(&file.with_extension("png.import"))+ .and_then(|t| import_uid(&t))+ .unwrap_or_else(|| uid_for(&format!("texture {}", file.display())))+}++pub fn scroll_scale(depth: f32) -> f32 {+ 1.0 / (1.0 + depth.max(0.0))+}++pub struct Plane {+ pub name: String,+ pub depth: f32,+ pub file: PathBuf,+}++pub fn rasters_at(bundle: &Bundle, frame: u32) -> Result<Rasters> {+ let brushes = BrushSet::for_bundle(bundle)?;+ let mut rasters = layers::load(bundle, frame, &brushes, true)?.rasters;+ Vectors::default().add_to(&bundle.doc, frame, &mut rasters)?;+ Ok(rasters)+}++pub fn parallax(path: &Path, dir: Option<PathBuf>, frame: u32) -> Result<Vec<PathBuf>> {+ let bundle = Bundle::open(path)?;+ let doc = &bundle.doc;+ let target = target(&bundle, dir)?;+ let stem = file_safe(&bundle_stem(&bundle));+ let rasters = rasters_at(&bundle, frame)?;+ let shown: Vec<&Layer> = doc.layers.iter().filter(|l| l.visible && !l.reference).collect();+ if shown.is_empty() {+ bail!("nothing to export: no visible layers");+ }+ let background = doc.canvas.background.clone();+ let planes: Vec<Plane> = shown+ .iter()+ .enumerate()+ .map(|(i, layer)| {+ let back = if i == 0 { background.as_deref() } else { None };+ let flat = flatten_with(doc, frame, &rasters, &[*layer], back, None, false)?;+ let file = target.join(format!("{stem}-{i:02}-{}.png", file_safe(&layer.name)));+ write_atomic(&file, &png(flat.width, flat.height, rgba(&flat))?)?;+ Ok(Plane {+ name: node_name(&layer.name),+ depth: layer.depth.unwrap_or(0.0),+ file,+ })+ })+ .collect::<Result<_>>()?;+ let scene = target.join(format!("{stem}-parallax.tscn"));+ let resources: String = planes+ .iter()+ .enumerate()+ .map(|(i, p)| {+ format!(+ "[ext_resource type=\"Texture2D\" uid={} path={} id=\"{}_plane\"]\n",+ quoted(&texture_uid(&p.file)),+ quoted(&p.file.file_name().unwrap_or_default().to_string_lossy()),+ i + 1+ )+ })+ .collect();+ let nodes: String = planes+ .iter()+ .enumerate()+ .map(|(i, p)| {+ let s = number(scroll_scale(p.depth));+ format!(+ "\n[node name={name} type=\"Parallax2D\" parent=\".\"]\nscroll_scale = Vector2({s}, {s})\n\n[node name=\"Sprite2D\" type=\"Sprite2D\" parent={name}]\ntexture = ExtResource(\"{}_plane\")\ncentered = false\n",+ i + 1,+ name = quoted(&format!("{:02} {}", i, p.name)),+ )+ })+ .collect();+ let text = format!(+ "[gd_scene load_steps={} format=3 uid={}]\n\n{resources}\n[node name={} type=\"Node2D\"]\n{nodes}",+ planes.len() + 1,+ quoted(&uid_of(&scene)),+ quoted(&node_name(&bundle_stem(&bundle))),+ );+ write_atomic(&scene, text.as_bytes())?;+ Ok(planes.iter().map(|p| p.file.clone()).chain([scene]).collect())+}++struct Part {+ name: String,+ file: PathBuf,+ origin: [f32; 2],+ vertices: Vec<[f32; 2]>,+ triangles: Vec<[usize; 3]>,+}++const GRID: u32 = 16;++fn mesh(alpha: &[u8], w: u32, h: u32, origin: [f32; 2]) -> (Vec<[f32; 2]>, Vec<[usize; 3]>) {+ let (cols, rows) = (w.div_ceil(GRID), h.div_ceil(GRID));+ let solid = |cx: i64, cy: i64| -> bool {+ (cy * GRID as i64..((cy + 1) * GRID as i64).min(h as i64)).any(|y| {+ (cx * GRID as i64..((cx + 1) * GRID as i64).min(w as i64))+ .any(|x| x >= 0 && y >= 0 && alpha[(y as u32 * w + x as u32) as usize] > 8)+ })+ };+ let used: Vec<(u32, u32)> = (0..rows)+ .flat_map(|cy| (0..cols).map(move |cx| (cx, cy)))+ .filter(|&(cx, cy)| (-1..=1).any(|dy| (-1..=1).any(|dx| solid(cx as i64 + dx, cy as i64 + dy))))+ .collect();+ let mut index: std::collections::BTreeMap<(u32, u32), usize> = std::collections::BTreeMap::new();+ let mut vertices = Vec::new();+ let mut vertex = |gx: u32, gy: u32| -> usize {+ *index.entry((gx, gy)).or_insert_with(|| {+ vertices.push([+ origin[0] + (gx * GRID).min(w) as f32,+ origin[1] + (gy * GRID).min(h) as f32,+ ]);+ vertices.len() - 1+ })+ };+ let triangles = used+ .iter()+ .flat_map(|&(cx, cy)| {+ let (a, b, c, d) = (+ vertex(cx, cy),+ vertex(cx + 1, cy),+ vertex(cx + 1, cy + 1),+ vertex(cx, cy + 1),+ );+ [[a, b, c], [a, c, d]]+ })+ .collect();+ (vertices, triangles)+}++fn rest_cel(layer: &Layer) -> Option<String> {+ let mut counts: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new();+ layer+ .cels()+ .iter()+ .filter_map(|c| c.pose.as_ref())+ .for_each(|p| *counts.entry(p.rest.as_str()).or_default() += 1);+ counts+ .into_iter()+ .max_by_key(|(_, n)| *n)+ .map(|(r, _)| r.to_string())+ .or_else(|| layer.content_at(0).map(|c| c.id.clone()))+}++fn transform(angle: f32, at: [f32; 2]) -> String {+ let (s, c) = (angle.sin(), angle.cos());+ format!(+ "Transform2D({}, {}, {}, {}, {}, {})",+ number(c),+ number(s),+ number(-s),+ number(c),+ number(at[0]),+ number(at[1])+ )+}++pub fn bone_paths(bones: &[klad_core::rig::Bone]) -> Vec<String> {+ bones+ .iter()+ .map(|b| {+ let mut chain = vec![node_name(&b.name)];+ let mut parent = b.parent.clone();+ while let Some(p) = parent {+ let found = bones.iter().find(|o| o.name == p);+ chain.push(node_name(&p));+ parent = found.and_then(|o| o.parent.clone());+ }+ chain.reverse();+ chain.join("/")+ })+ .collect()+}++pub fn local(bones: &[klad_core::rig::Bone], i: usize) -> (f32, [f32; 2]) {+ let b = &bones[i];+ match b.parent.as_ref().and_then(|p| bones.iter().find(|o| &o.name == p)) {+ None => (b.angle(), b.head),+ Some(p) => {+ let a = p.angle();+ let (dx, dy) = (b.head[0] - p.head[0], b.head[1] - p.head[1]);+ let (s, c) = (a.sin(), a.cos());+ (b.angle() - a, [dx * c + dy * s, -dx * s + dy * c])+ }+ }+}++fn real(v: f32) -> String {+ let text = number(v);+ match text.contains('.') {+ true => text,+ false => format!("{text}.0"),+ }+}++fn floats(values: &[f32]) -> String {+ format!(+ "PackedFloat32Array({})",+ values.iter().map(|v| number(*v)).collect::<Vec<_>>().join(", ")+ )+}++pub fn rig(path: &Path, dir: Option<PathBuf>) -> Result<Vec<PathBuf>> {+ let bundle = Bundle::open(path)?;+ let doc = &bundle.doc;+ let target = target(&bundle, dir)?;+ let stem = file_safe(&bundle_stem(&bundle));+ let owners = crate::rig::owners(doc);+ if owners.is_empty() {+ bail!("this drawing has no bones: add them with klad bone (or the bone tool) first");+ }+ let brushes = BrushSet::for_bundle(&bundle)?;+ let (cw, ch) = (doc.canvas.width, doc.canvas.height);+ let mut written = Vec::new();+ owners.iter().try_for_each(|owner| -> Result<()> {+ let bones = &owner.bones;+ let weights = match bundle.read_weights(&owner.id)? {+ w if w.maps.is_empty() => klad_core::rig::Weights::auto(bones, (cw, ch)),+ w => w,+ };+ let name = file_safe(&owner.name);+ let mut parts: Vec<Part> = Vec::new();+ klad_core::rig::painted(owner).iter().try_for_each(|layer| -> Result<()> {+ let Some(rest) = rest_cel(layer) else {+ return Ok(());+ };+ let cel = layer.cels().iter().find(|c| c.id == rest).context("the rest drawing is gone")?;+ let marks = bundle.read_marks(&layer.id, &rest)?;+ let mut groups: Vec<(String, Vec<klad_core::stroke::Mark>)> = cel+ .parts+ .iter()+ .map(|(n, ids)| (n.clone(), marks.iter().filter(|m| ids.contains(&m.id())).cloned().collect()))+ .collect();+ let loose: Vec<klad_core::stroke::Mark> = marks+ .iter()+ .filter(|m| !cel.parts.values().any(|ids| ids.contains(&m.id())))+ .cloned()+ .collect();+ if !loose.is_empty() {+ groups.insert(0, (layer.name.clone(), loose));+ }+ groups.into_iter().try_for_each(|(part, marks)| -> Result<()> {+ let raster = klad_brush::replay(cw, ch, &marks, &brushes)?.raster;+ let pixels = rgba(&raster);+ let alpha: Vec<u8> = pixels.chunks(4).map(|p| p[3]).collect();+ let (mut x0, mut y0, mut x1, mut y1) = (cw, ch, 0, 0);+ (0..ch).for_each(|y| {+ (0..cw).filter(|&x| alpha[(y * cw + x) as usize] > 0).for_each(|x| {+ x0 = x0.min(x);+ y0 = y0.min(y);+ x1 = x1.max(x + 1);+ y1 = y1.max(y + 1);+ })+ });+ if x1 <= x0 || y1 <= y0 {+ return Ok(());+ }+ let (w, h) = (x1 - x0, y1 - y0);+ let crop: Vec<u8> = (y0..y1)+ .flat_map(|y| pixels[((y * cw + x0) * 4) as usize..((y * cw + x1) * 4) as usize].to_vec())+ .collect();+ let file = target.join(format!("{stem}-{name}-{}-{}.png", file_safe(&layer.name), file_safe(&part)));+ write_atomic(&file, &png(w, h, crop)?)?;+ let small: Vec<u8> = (y0..y1)+ .flat_map(|y| (x0..x1).map(move |x| (x, y)))+ .map(|(x, y)| alpha[(y * cw + x) as usize])+ .collect();+ let (vertices, triangles) = mesh(&small, w, h, [x0 as f32, y0 as f32]);+ parts.push(Part {+ name: node_name(&format!("{} {}", layer.name, part)),+ file,+ origin: [x0 as f32, y0 as f32],+ vertices,+ triangles,+ });+ Ok(())+ })+ })?;+ let scene = target.join(format!("{stem}-{name}-rig.tscn"));+ let paths = bone_paths(bones);+ let resources: String = parts+ .iter()+ .enumerate()+ .map(|(i, p)| {+ format!(+ "[ext_resource type=\"Texture2D\" uid={} path={} id=\"{}_part\"]\n",+ quoted(&texture_uid(&p.file)),+ quoted(&p.file.file_name().unwrap_or_default().to_string_lossy()),+ i + 1+ )+ })+ .collect();+ let fps = doc.timeline.fps.max(1) as f32;+ let clips: Vec<(String, u32, u32, bool, f32)> = match doc.timeline.clips.is_empty() {+ true => vec![("all".into(), 0, doc.timeline.frames.saturating_sub(1), true, fps)],+ false => doc+ .timeline+ .clips+ .iter()+ .map(|c| (c.name.clone(), c.from, c.to, c.looping, c.fps.map_or(fps, |f| f as f32)))+ .collect(),+ };+ let first = klad_core::rig::painted(owner).into_iter().next().context("no paint layer under the bones")?;+ let mut unposed = Vec::new();+ let animations: Vec<String> = clips+ .iter()+ .enumerate()+ .map(|(k, (clip, from, to, looping, fps))| {+ let poses: Vec<(f32, klad_core::rig::Pose)> = (*from..=*to)+ .filter_map(|f| {+ let cel = first.cel_at(f).filter(|c| c.frame == f || f == *from)?;+ let shown = first.content_of(cel);+ match &shown.pose {+ Some(p) => Some(((f - from) as f32 / fps, p.clone())),+ None if shown.id == rest_cel(first).unwrap_or_default() => {+ Some(((f - from) as f32 / fps, klad_core::rig::Pose::default()))+ }+ None => {+ unposed.push(f);+ None+ }+ }+ })+ .collect();+ let times: Vec<f32> = poses.iter().map(|(t, _)| *t).collect();+ let tracks: String = bones+ .iter()+ .enumerate()+ .map(|(i, b)| {+ let (rest, _) = local(bones, i);+ let values: Vec<f32> = poses+ .iter()+ .map(|(_, p)| rest + p.angles.get(&b.name).copied().unwrap_or(0.0).to_radians())+ .collect();+ format!(+ "tracks/{i}/type = \"value\"\ntracks/{i}/imported = false\ntracks/{i}/enabled = true\ntracks/{i}/path = NodePath(\"Skeleton2D/{}:rotation\")\ntracks/{i}/interp = 0\ntracks/{i}/loop_wrap = true\ntracks/{i}/keys = {{\n\"times\": {},\n\"transitions\": {},\n\"update\": 0,\n\"values\": [{}]\n}}\n",+ paths[i],+ floats(×),+ floats(&vec![1.0; times.len()]),+ values.iter().map(|v| real(*v)).collect::<Vec<_>>().join(", ")+ )+ })+ .collect();+ format!(+ "[sub_resource type=\"Animation\" id=\"Animation_{k}\"]\nresource_name = {}\nlength = {}\nloop_mode = {}\nstep = {}\n{tracks}\n",+ quoted(clip),+ number((to - from + 1) as f32 / fps),+ if *looping { 1 } else { 0 },+ number(1.0 / fps)+ )+ })+ .collect();+ let library = format!(+ "[sub_resource type=\"AnimationLibrary\" id=\"AnimationLibrary_1\"]\n_data = {{\n{}\n}}\n",+ clips+ .iter()+ .enumerate()+ .map(|(k, (c, ..))| format!("&{}: SubResource(\"Animation_{k}\")", quoted(c)))+ .collect::<Vec<_>>()+ .join(",\n")+ );+ let skeleton: String = bones+ .iter()+ .enumerate()+ .map(|(i, b)| {+ let (angle, at) = local(bones, i);+ let parent = match paths[i].rsplit_once('/') {+ Some((p, _)) => format!("Skeleton2D/{p}"),+ None => "Skeleton2D".into(),+ };+ format!(+ "\n[node name={} type=\"Bone2D\" parent={}]\nposition = Vector2({}, {})\nrotation = {}\nrest = {}\nauto_calculate_length_and_angle = false\nlength = {}\nbone_angle = 0.0\n",+ quoted(&node_name(&b.name)),+ quoted(&parent),+ number(at[0]),+ number(at[1]),+ number(angle),+ transform(angle, at),+ number(b.length())+ )+ })+ .collect();+ let polygons: String = parts+ .iter()+ .enumerate()+ .map(|(k, p)| {+ let uv: Vec<String> = p+ .vertices+ .iter()+ .map(|v| format!("{}, {}", number(v[0] - p.origin[0]), number(v[1] - p.origin[1])))+ .collect();+ let points: Vec<String> = p.vertices.iter().map(|v| format!("{}, {}", number(v[0]), number(v[1]))).collect();+ let tris: Vec<String> = p+ .triangles+ .iter()+ .map(|t| format!("PackedInt32Array({}, {}, {})", t[0], t[1], t[2]))+ .collect();+ let per_vertex: Vec<Vec<f32>> = p.vertices.iter().map(|v| weights.at(bones, *v)).collect();+ let bone_list: Vec<String> = paths+ .iter()+ .enumerate()+ .map(|(i, path)| {+ format!(+ "NodePath({}), {}",+ quoted(path),+ floats(&per_vertex.iter().map(|w| w[i]).collect::<Vec<_>>())+ )+ })+ .collect();+ format!(+ "\n[node name={} type=\"Polygon2D\" parent=\".\"]\ntexture = ExtResource(\"{}_part\")\nskeleton = NodePath(\"../Skeleton2D\")\npolygon = PackedVector2Array({})\nuv = PackedVector2Array({})\npolygons = [{}]\nbones = [{}]\n",+ quoted(&format!("{:02} {}", k, p.name)),+ k + 1,+ points.join(", "),+ uv.join(", "),+ tris.join(", "),+ bone_list.join(", ")+ )+ })+ .collect();+ let text = format!(+ "[gd_scene load_steps={} format=3 uid={}]\n\n{resources}\n{}{library}\n[node name={} type=\"Node2D\"]\n{polygons}\n[node name=\"Skeleton2D\" type=\"Skeleton2D\" parent=\".\"]\n{skeleton}\n[node name=\"AnimationPlayer\" type=\"AnimationPlayer\" parent=\".\"]\nlibraries = {{\n&\"\": SubResource(\"AnimationLibrary_1\")\n}}\nautoplay = {}\n",+ parts.len() + clips.len() + 2,+ quoted(&uid_of(&scene)),+ animations.join(""),+ quoted(&node_name(&owner.name)),+ quoted(&clips[0].0)+ );+ write_atomic(&scene, text.as_bytes())?;+ if !unposed.is_empty() {+ unposed.sort_unstable();+ unposed.dedup();+ eprintln!(+ "frames {} of {} are not poses of the rest drawing: the rig cannot show them; the frames export (--godot) carries them",+ unposed.iter().map(|f| f.to_string()).collect::<Vec<_>>().join(", "),+ owner.name+ );+ }+ written.extend(parts.iter().map(|p| p.file.clone()));+ written.push(scene);+ Ok(())+ })?;+ Ok(written)+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::agent::Output;+ use klad_core::doc::Document;+ use klad_core::ops::parse_lines;+ use std::process::Command;++ const CHECK: &str = r#"extends SceneTree++var frames := 0+var out := {}+var scene: Node+var camera: Camera2D++func _initialize():+ var rig = load("res://art/arm-arm-rig.tscn").instantiate()+ root.add_child(rig)+ var player: AnimationPlayer = rig.get_node("AnimationPlayer")+ var bone: Bone2D = rig.get_node("Skeleton2D/upper/fore")+ var poly: Polygon2D = rig.get_child(0)+ out["anims"] = player.get_animation_list()+ out["bones"] = poly.get_bone_count()+ out["vertices"] = poly.polygon.size()+ out["weights"] = poly.get_bone_weights(1).size()+ player.play("wave")+ player.seek(0.1, true)+ out["held"] = bone.rotation+ player.seek(0.35, true)+ out["posed"] = bone.rotation+ scene = load("res://art/arm-parallax.tscn").instantiate()+ root.add_child(scene)+ camera = Camera2D.new()+ root.add_child(camera)+ camera.make_current()++func _process(_delta):+ frames += 1+ if frames == 2:+ camera.position = Vector2(300, 0)+ if frames == 5:+ var planes = []+ for p in scene.get_children():+ if p is Parallax2D:+ planes.append([p.scroll_scale.x, p.screen_offset.x, p.get_child(0).global_position.x])+ out["planes"] = planes+ print("RESULT ", JSON.stringify(out))+ quit()+ return false+"#;++ fn quiet() -> Output {+ Output {+ json: false,+ render: false,+ scale: None,+ frame: 0,+ overlay: None,+ }+ }++ #[test]+ fn a_rig_and_a_parallax_scene_export_for_godot() {+ let dir = std::env::temp_dir().join(format!("klad-scene-{}", std::process::id()));+ let _ = fs::remove_dir_all(&dir);+ let project = dir.join("game");+ fs::create_dir_all(project.join("art")).unwrap();+ fs::write(+ project.join("project.godot"),+ "config_version=5\n\n[application]\n\nconfig/name=\"klad check\"\n",+ )+ .unwrap();+ fs::write(project.join("check.gd"), CHECK).unwrap();+ let path = dir.join("arm.draw");+ let mut doc = Document::new(600, 400);+ doc.canvas.background = Some("#f0e8dc".into());+ doc.timeline.frames = 8;+ doc.layers = vec![Layer::paint("far", "far", "c1"), Layer::paint("arm", "arm", "c2")];+ doc.layers[0].depth = Some(3.0);+ doc.next_id = 10;+ Bundle::create(&path, doc).unwrap();+ let edit = |ops: &str| crate::agent::edit(&path, &parse_lines(ops).unwrap(), &quiet()).unwrap();+ edit(+ r##"{"op":"fill","layer":"far","polygon":[[0,250],[600,250],[600,400],[0,400]],"color":"#8090a0"}+{"op":"stroke","layer":"arm","brush":"ink","size":24,"color":"#c06a3a","path":"M100 200 L 300 200 L 480 200"}+{"op":"clip","add":"wave","from":0,"to":7,"loop":true}"##,+ );+ edit(+ r#"{"op":"bone","layer":"arm","add":"upper","head":[100,200],"tail":[300,200]}+{"op":"bone","layer":"arm","add":"fore","parent":"upper","head":[300,200],"tail":[480,200]}"#,+ );+ edit(r#"{"op":"weights","layer":"arm","auto":true}"#);+ edit(r#"{"op":"pose","layer":"arm","from":0,"to":4,"bones":{"fore":-70}}"#);+ let made = rig(&path, Some(project.join("art"))).unwrap();+ let text = fs::read_to_string(made.last().unwrap()).unwrap();+ assert!(text.contains("type=\"Skeleton2D\"") && text.contains("NodePath(\"Skeleton2D/upper/fore:rotation\")"));+ assert!(+ text.contains("\"values\": [0.0, -1.222]"),+ "angles in radians, as floats"+ );+ let planes = parallax(&path, Some(project.join("art")), 0).unwrap();+ let scene = fs::read_to_string(planes.last().unwrap()).unwrap();+ assert!(scene.contains("scroll_scale = Vector2(0.25, 0.25)") && scene.contains("scroll_scale = Vector2(1, 1)"));+ let again = uid_of(planes.last().unwrap());+ parallax(&path, Some(project.join("art")), 0).unwrap();+ assert_eq!(uid_of(planes.last().unwrap()), again, "a re-export keeps its uid");+ let binary = std::env::var("GODOT").unwrap_or_else(|_| "godot".into());+ if !Command::new(&binary)+ .arg("--version")+ .output()+ .is_ok_and(|o| o.status.success())+ {+ eprintln!("no godot on PATH (or $GODOT): skipping the import check");+ return;+ }+ let run = |args: &[&str]| {+ let o = Command::new(&binary)+ .args(["--headless", "--path"])+ .arg(&project)+ .args(args)+ .output()+ .unwrap();+ String::from_utf8_lossy(&o.stdout).to_string() + &String::from_utf8_lossy(&o.stderr)+ };+ run(&["--import"]);+ let output = run(&["-s", "check.gd"]);+ let line = output+ .lines()+ .find_map(|l| l.strip_prefix("RESULT "))+ .unwrap_or_else(|| panic!("{output}"));+ let got: serde_json::Value = serde_json::from_str(line).unwrap();+ assert_eq!(got["anims"], serde_json::json!(["wave"]));+ assert_eq!(got["bones"], 2);+ assert_eq!(got["vertices"], got["weights"]);+ assert!(+ got["held"].as_f64().unwrap().abs() < 1e-3,+ "the rest pose holds until the pose's frame"+ );+ assert!((got["posed"].as_f64().unwrap() + 70f64.to_radians()).abs() < 1e-3);+ let planes = got["planes"].as_array().unwrap();+ let (far, near) = (&planes[0], &planes[1]);+ let moved = |p: &serde_json::Value| p[2].as_f64().unwrap();+ let offset = far[1].as_f64().unwrap();+ assert!(+ (moved(far) - offset * 0.75).abs() < 1.0,+ "the far plane scrolls at a quarter of the camera: {planes:?}"+ );+ assert!(moved(near).abs() < 1e-3);+ fs::remove_dir_all(&dir).unwrap();+ }+}diff --git a/crates/cli/src/sprites.rs b/crates/cli/src/sprites.rsindex c40a5c3..f364766 100644--- a/crates/cli/src/sprites.rs+++ b/crates/cli/src/sprites.rs@@ -54,13 +54,13 @@ impl Name {}}-fn bundle_stem(bundle: &Bundle) -> String {+pub(crate) fn bundle_stem(bundle: &Bundle) -> String {let root = bundle.root.components().collect::<PathBuf>();root.file_stem().map_or("export".into(), |s| s.to_string_lossy().to_string())}-fn bundle_dir(bundle: &Bundle) -> PathBuf {+pub(crate) fn bundle_dir(bundle: &Bundle) -> PathBuf {let root = bundle.root.components().collect::<PathBuf>();match root.parent() {Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),@@ -68,7 +68,7 @@ fn bundle_dir(bundle: &Bundle) -> PathBuf {}}-fn file_safe(text: &str) -> String {+pub(crate) fn file_safe(text: &str) -> String {text.chars().map(|c| match c {'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' => c,@@ -389,7 +389,7 @@ pub fn relative(from: &Path, to: &Path) -> PathBuf {}}-fn read(path: &Path) -> Option<String> {+pub(crate) fn read(path: &Path) -> Option<String> {fs::read_to_string(path).ok()}diff --git a/crates/render/src/sprites.rs b/crates/render/src/sprites.rsindex 3b09e72..68757ed 100644--- a/crates/render/src/sprites.rs+++ b/crates/render/src/sprites.rs@@ -339,11 +339,11 @@ pub fn aseprite(sheet: &Sheet) -> Value {json!({ "frames": frames, "meta": meta })}-fn quoted(text: &str) -> String {+pub fn quoted(text: &str) -> String {format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\""))}-fn number(v: f32) -> String {+pub fn number(v: f32) -> String {let text = format!("{v:.3}");let text = text.trim_end_matches('0').trim_end_matches('.');match text {diff --git a/docs/DESIGN.md b/docs/DESIGN.mdindex 042d491..fa66c49 100644--- a/docs/DESIGN.md+++ b/docs/DESIGN.md@@ -1,4 +1,4 @@-_Last updated: 2026-11-05 21:14_+_Last updated: 2026-11-05 22:06_# klad: design@@ -99,7 +99,7 @@ art.draw/Committed: everything except `.cache/`. A fresh clone rebuilds the cache by replaying strokes and fills.-### doc.json (format `draw-anything/8`)+### doc.json (format `draw-anything/9`)```json{@@ -243,6 +243,9 @@ 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.+- **Rigs (M6).** A paint layer or a group gets `bones` (format 9): each a name, an optional parent that comes before it, a head and a tail in canvas px. A group's skeleton poses every paint layer in it together, so a character's lines, colour and shading layers stay in step. Each bone has a weight map in `weights/<owner>.weights` (zstd: a JSON header with the grid size and bone names, then one byte per cell per bone, cells of 4 px), written by `Bundle::apply` with the edit and kept in its history step; weights are normalised across bones when read (bilinear between cells), and a place no bone weighs follows the nearest bone. Automatic weights are 1/(d + 0.15 L + 1)^3 by distance to each bone segment (L its length), so joints blend over a short stretch; `set` paints soft dabs (smoothstep falloff towards a value), `part` gives a named part's cells to one bone at 1 and the others 0, `smooth` blurs every map once. A pose (`pose` on a cel: its rest drawing's id, an angle per bone in degrees from rest, a root move) is linear blend skinning: each bone's rest matrix (head, angle) and posed matrix (its parent's posed matrix times the rest offset times its turn) give a skin matrix, and every stroke sample moves by the weighted sum; stroke sizes scale by the mean local stretch (the Jacobian's determinant, square-rooted); polygon fills move their points; flood fills are warped through a 4 px triangle mesh over their coverage (each posed triangle rasterised, sampling the rest coverage by barycentric position). The rest pose returns the marks untouched. `pose` (computed by the CLI, `cli/src/rig.rs`) makes or re-poses a drawing at `to` on every paint layer under the skeleton from the rest drawing shown at `from` (a posed drawing's own rest when `from` shows one). In-betweens of two poses of one rest drawing (or a pose and its rest) mix the angles and root by t instead of matching strokes (`rig::posed_pair`), and keep the mixed pose. The editor's bone tool (J) draws bones (from a bone's end makes a child), picks, renames and removes them, paints weights in its own process (`klad_core::rig::weights_for`) over a tint of the picked bone's map, and turns bones in pose mode, committing the pose through `klad pose` as a job; the drawing is not deformed live while turning, only the skeleton.+- **Keys (M6, S6.5).** Layers, groups and vector nodes keep `keys`: per property (`x`, `y`, `rotate`, `sx`, `sy`, `opacity`) a sorted list of frame, value and ease (linear, in, out, in-out, step, or a cubic curve x1,y1,x2,y2 solved by bisection). A segment follows its first key's ease; values hold before the first key and after the last. Layers and groups composite with their keyed opacity and, when moved, with their keyed transform about the canvas centre (drawn whole, not tile by tile, while moved); nodes take keyed transforms and opacity when rasterised (`nodes_at`). The editor's frame and plane caches hash the keyed values; its vector raster cache does not follow node keys yet, so keyed shapes move in `klad render` and the exports, not in the editor.+- **Godot scenes (M6, S6.6, S6.7).** `export --godot-scene` flattens each visible top-level layer (with its fog; the background with the first) into a texture on a `Parallax2D` with `scroll_scale` 1/(1 + depth), the factor the editor's depth preview (hold D) uses. `export --godot-rig` writes per skeleton: each part of the rest drawing (named parts of each paint layer's rest drawing, the loose marks as one) replayed alone, trimmed, on a `Polygon2D` with a 16 px triangle mesh over its pixels (one cell of margin), UVs, and per-vertex weights sampled from the maps; a `Skeleton2D` with a `Bone2D` per bone at rest (local position and angle against the parent, `rest`, `length`); and an `AnimationPlayer` with one animation per clip (or one for the timeline) whose value tracks hold each bone's rest angle plus its pose at the frame each posed drawing starts (stepped, so drawings hold as in klad); frames that are not poses of the rest drawing are listed for the frames export. Re-exports keep their uids. `samples/rig` builds a figure with all of it.- **Paint over (M5, S5.29).** `paintover` (`cli/src/paintover.rs`, resolved before the shape ops, alone in its batch) flattens the source (the `from` layers, or every visible layer below the target's top-level layer with the background) into OKLab, then follows Hertzmann's painterly method: for each brush size, biggest first, the source is blurred to that size, a grid at half the size finds cells whose mean difference from the painting so far (an estimate made by stamping discs of each stroke's colour) exceeds `threshold`, and a stroke starts at each such cell's worst pixel in a seeded random order. A stroke walks in steps of half its size across the luminance gradient (Sobel), turning towards it by `curve` times how sure the gradient is (weak gradients keep the stroke's direction; with none, a smooth seeded field of mostly level angles), and stops past its minimum length when the source there is closer to the painting than to the stroke's colour, at a colour change over twice the threshold, at the edge of the region or at its maximum length. `focus` keeps the last size to a shape grown by three of those sizes. Each stroke becomes a stroke op with a press-in and lift-off pressure, its size a little varied, its colour broken by `vary` from a hash of its seed, in the part `part`. `like <cel>` carries a paint-over to another drawing: every source paint layer's two drawings are paired as in-betweens pair them; each stroke rides the topmost source mark under its centre (a stroke within half its size, a polygon fill, a flood fill's coverage) with `tween::carry` along that mark's line (still marks: it stays; marks gone: it fades to opacity 0); it keeps its seed and is recoloured from the new source at its start, faded when it would now cross an edge; new strokes, in `<part> added`, only go where the source changed (its colour or alpha, grown by the biggest size) or where carried strokes left a gap. `--frames a-b` repeats that drawing to drawing, making a drawing on the target wherever a source layer starts one (a link where they link). `samples/paintover` paints over the lemons and carries a paint-over through the creature's walk; frame to frame its background changes by 0.03 of 255 on average.- **Compare (M5, S5.30).** `compare` (`cli/src/compare.rs`) renders the drawing at the reference's width (or reads a PNG or JPEG), resamples it to the reference's size, composites both over white and compares in OKLab: L at the 5th, 50th and 95th percentile, mean chroma, texture as the mean absolute Laplacian of L, sharpness as the 99th percentile of the gradient, and the mean difference, each x100; per `--region` the mean colours and their difference; words when a difference passes a threshold (2 L, 1.5 in a or b, 10% chroma, 20% texture, 15% sharpness); `--heat` writes the per-pixel difference as black to red to yellow to white at 20. The editor's "compare with the reference" runs it as a job against the first picture on a reference layer and shows the numbers and the heat in a window.- **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.@@ -407,6 +410,11 @@ An error is one line on stderr (`error: reading a.draw/doc.json: No such file or| `klad export <bundle> --godot [dir] [--store] [--scale s]` | the sheet, a `SpriteFrames` `.tres` and an `AnimatedSprite2D` `.tscn` (see Exports) || `klad hash <bundle> [--frame n] [--all]` | pixel hash for the parity check; `--all` one line per frame || `klad open [bundle]` | the editor; without a bundle, the start window: New, Open (the platform's open panel or a pasted path), Recent with thumbnails |+| `klad bone <bundle> <layer> --add n [--parent p] --head x,y --tail x,y`, `--rm n`, `--rename n --as m`, `--move n [--head] [--tail]`, `--reparent n [--parent p]`; `klad bones <bundle> [--json]` | skeletons (see Rigs) |+| `klad weights <bundle> <layer> --auto \| --bone b --set 'x,y,r,w ...' \| --bone b --part p [--value v] \| --smooth` | how much each bone moves the drawing |+| `klad pose <bundle> <layer> [--from f] --to f --bone name=deg ... [--root x,y] [--hold n]` | a posed drawing from the rest drawing |+| `klad key <bundle> <id> --frame f prop=value ... [--ease e] [--rm]`; `klad keys <bundle> [id] [--json]` | animate layers, groups and shapes (see Keys) |+| `klad export <bundle> --godot-scene [dir]`, `--godot-rig [dir]` | a Godot parallax scene; a Godot rig with its animations || `klad paintover <bundle> <layer> [--from] [--in] [--sizes 32,16,8] [--threshold 6] [--length 1,8] [--curve 0.5] [--brush oil] [--focus] [--vary] [--like <cel> [--frames a-b]] [--part] [--seed]` | brushwork from what is below the layer (see Paint over) || `klad compare <drawing\|png> <reference> [--frame] [--region name=x,y,w,h]... [--heat out.png] [--json]` | values, saturation, texture, edges and colour against a reference, in numbers and words || `klad install [--dir]`, `klad skill` | put `klad` on the terminal's path; print the agent skill |diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.mdindex bdd2d78..596f6f7 100644--- a/docs/skill/SKILL.md+++ b/docs/skill/SKILL.md@@ -213,6 +213,28 @@ klad prepare art.draw- Details that make a prop read as made rather than blocked in (an early version of the lantern read "kind of as good, but its details are not too great"): connect what hangs (hook, links, bead, cap: every piece touches the next; a link seen face-on is a closed ring through `--path`, one seen edge-on a small filled bar); give a round form a crisp core shadow with its own `light` pass (`--soft 1`, depth about a third of its width, `shadeOpacity` 1) instead of a soft gradient; build a stone or block from two planes (a top face and a darker side as its own shape) and keep texture to the side plane; plant grass as a few tufts where things meet the ground, leaning away from the object, not a fringe along an edge; ink a shape that enters another as an open path, so its cut edge is not drawn on top.- The ops are `ink`, `light`, `hatch`, `paint`, `scatter` and `fill` with `shape`; shapes added earlier in the same `apply` can be used by them. `samples/lantern/` builds the inked prop, and with `PAINTED=1` the painted one (`paint` by form in place of `light` and `hatch`).+## Bones, poses and keys++Draw a character once and pose it, instead of redrawing every frame. Put its paint layers (lines, colour, shading) in a group and give the group bones: the skeleton poses every layer in it together. Name parts as you draw (`"part"` on strokes and fills): they are what weights and the rig export use.++```bash+klad bone art.draw figure --add body --head 400,590 --tail 400,360+klad bone art.draw figure --add upper --parent body --head 452,392 --tail 560,360 # a child starts at its parent's end, or anywhere+klad weights art.draw figure --auto # blend from the bones+klad weights art.draw figure --bone head --part head # a part held rigidly by one bone+klad weights art.draw figure --bone upper --set '470,380,20,1 500,370,16,0.8' # soft dabs: x,y,radius,weight+klad pose art.draw figure --from 0 --to 4 --bone upper=-35 --bone fore=-55 --hold 4+klad inbetween art.draw --layers colour,lines --from 0 --to 4 # poses of one rest drawing in-between on the bones+klad render art.draw --frame 4 --overlay bones # or --overlay weights:upper+klad key art.draw lantern --frame 0 y=0 --ease in-out; klad key art.draw lantern --frame 12 y=-18+klad export art.draw --godot-rig game/art --godot-scene game/art+```++- Angles are degrees from the rest pose, positive turning clockwise on screen; a child follows its parent. Pose from the rest drawing (`--from` its frame); posing a frame again re-poses it.+- Automatic weights bend joints over a short stretch; hold rigid things (head, hands, props) with `--part`, or a stiff limb with dabs at 1. Look at `--overlay weights:<bone>` before posing.+- Keys move whole layers, groups and shapes (`x`, `y`, `rotate`, `sx`, `sy`, `scale`, `opacity`) between frames with an ease (`linear`, `in`, `out`, `in-out`, `step`, or a curve `x1,y1,x2,y2`); a segment follows its first key's ease. A lantern that floats, a glow that pulses, a far plane that drifts: no drawing per frame.+- Godot: `--godot` exports frames (always works), `--godot-rig` a Skeleton2D with Polygon2D parts and an AnimationPlayer per clip (only frames that are poses of the rest drawing; the others are listed), `--godot-scene` one Parallax2D per top-level layer scrolling by its depth. `samples/rig` builds all of it.+## Painting over, and measuring against a reference`paintover` turns a flat or smooth picture into a painted one: it renders what is below a paint layer (or `--from` layers) and lays brush strokes on that layer, big to small. Each stroke takes the source's colour where it starts and runs along the forms (across the colour gradient) until the colour under it changes; smaller brushes only go where the painting still differs from the source by more than `--threshold`, so detail lands where the source has it. Flat areas get broad, mostly level strokes. The strokes are ordinary strokes in the part `paint over`, so `body` and `relief` light them and the user can edit them.diff --git a/justfile b/justfileindex 23df3af..483f95d 100644--- a/justfile+++ b/justfile@@ -19,7 +19,7 @@ lint:cargo clippy --workspace --all-targets -- -D warningssamples: build- for s in lantern ink-shapes bounce creature courier solids lemons ruin sign tree meadow paintover; do FORCE=1 bash samples/$s/build.sh >/dev/null || { echo "samples/$s failed" >&2; exit 1; }; echo "samples/$s"; done+ for s in lantern ink-shapes bounce creature courier solids lemons ruin sign tree meadow paintover rig; do FORCE=1 bash samples/$s/build.sh >/dev/null || { echo "samples/$s failed" >&2; exit 1; }; echo "samples/$s"; doneapp:bash packaging/macos/app.shdiff --git a/samples/README.md b/samples/README.mdindex 7208099..8f6b31f 100644--- a/samples/README.md+++ b/samples/README.md@@ -15,6 +15,7 @@ Drawings made from scratch with the `klad` CLI, each from a generator that print| `tree` | Foliage that reads as leaves: clumps built from leaf marks with `klad foliage`, each lit as a form and turning with the whole crown, leaves breaking the outline, a bark trunk painted as a cylinder || `meadow` | Grass that reads as grass with `klad grass`: a field receding in soft light patches, a near bank whose blades break its crest, and tufts with seed heads from a brush the build script makes itself (pictures drawn in klad, added with `klad brushes --picture` and `--set`) || `paintover` | Brushwork from a picture: the lemons repainted with `klad paintover`, and the creature's walk painted over once and carried drawing to drawing with `--like` and `--frames`, so the strokes move with the creature and the background stays still |+| `rig` | Bones instead of a drawing per frame: a figure in a group with a skeleton, weights from the bones with the head, body and hand held rigidly by their parts, a wave posed at four keys and in-betweened on the bones, a lantern floating on keys, a far plane for parallax, and the Godot rig and parallax scene (`rig-godot/`) || `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/rig/build.sh b/samples/rig/build.shnew file mode 100755index 0000000..6e3d589--- /dev/null+++ b/samples/rig/build.sh@@ -0,0 +1,30 @@+#!/usr/bin/env bash+set -euo pipefail+here="$(cd "$(dirname "$0")" && pwd)"+root="$(cd "$here/../.." && pwd)"+case "$(uname -s)" in+ Darwin) built=target ;;+ Linux) built=target/linux ;;+ *) built=target/windows ;;+esac+klad="${KLAD:-$root/${KLAD_TARGET_DIR:-$built}/release/klad}"+out="${1:-$here/rig.draw}"+if [ -e "$out" ] && [ "${FORCE:-0}" != 1 ]; then+ echo "$out exists and may hold edits made in the editor; give another path, or FORCE=1 to rebuild it" >&2+ exit 1+fi+rm -rf "$out"+"$klad" new "$out" --width 800 --height 800 --layers 0 --background '#e9e2d4' >/dev/null+for step in drawing rig weights poses keys; do+ python3 "$here/generate.py" "$step" | "$klad" apply "$out" >/dev/null+done+"$klad" inbetween "$out" --layers colour,lines --from 0 --to 4 | grep 'on bones' || true+for keys in "4 8" "8 12" "12 16"; do+ set -- $keys+ "$klad" inbetween "$out" --layers colour,lines --from "$1" --to "$2" >/dev/null+done+"$klad" bones "$out"+"$klad" render "$out" --frame 8 --overlay bones -o "${out%.draw}-bones.png" | tail -1+"$klad" render "$out" --sheet wave --drawings -o "${out%.draw}-sheet.png" | tail -1+"$klad" export "$out" --godot-rig "${out%.draw}-godot" --godot-scene "${out%.draw}-godot" 2>&1 | tail -2+"$klad" hash "$out" --all --no-cache | sed -n '1p;9p;13p'diff --git a/samples/rig/generate.py b/samples/rig/generate.pynew file mode 100644index 0000000..0e80249--- /dev/null+++ b/samples/rig/generate.py@@ -0,0 +1,101 @@+import json+import math+import sys++INK = "#1f1d26"+SKIN = "#e2b48c"+COAT = "#3f6f8f"+COAT_DARK = "#2c4f66"+++def layer(id, kind, within=None, **extra):+ op = {"op": "add", "layer": {"id": id, "kind": kind, "name": id, **extra}}+ if within:+ op["in"] = within+ return op+++def ellipse(cx, cy, rx, ry, n=40):+ return [[round(cx + rx * math.cos(2 * math.pi * k / n), 1), round(cy + ry * math.sin(2 * math.pi * k / n), 1)] for k in range(n)]+++def fill(layer, points, colour, part):+ return {"op": "fill", "layer": layer, "polygon": points, "color": colour, "part": part}+++def stroke(layer, path, size, colour, part, brush="ink"):+ return {"op": "stroke", "layer": layer, "brush": brush, "size": size, "color": colour, "path": path, "part": part,+ "pressure": [0.6, 1, 1, 0.8]}+++def drawing():+ out = [+ {"op": "timeline", "frames": 24, "fps": 12},+ layer("sky", "paint", depth=3),+ layer("figure", "group"),+ layer("colour", "paint", "figure"),+ layer("lines", "paint", "figure"),+ layer("lantern", "vector"),+ fill("sky", [[0, 560], [800, 540], [800, 800], [0, 800]], "#6f7f6a", "hill"),+ fill("sky", ellipse(620, 160, 60, 60), "#f4e4b0", "moon"),+ fill("colour", ellipse(400, 470, 90, 130), COAT, "body"),+ fill("colour", ellipse(400, 290, 62, 66), SKIN, "head"),+ stroke("colour", "M452 390 L 560 360", 44, COAT_DARK, "upper arm", "round-bristle"),+ stroke("colour", "M560 360 L 650 330", 36, COAT_DARK, "forearm", "round-bristle"),+ fill("colour", ellipse(672, 322, 22, 20), SKIN, "hand"),+ stroke("lines", "M400 340 C 300 360 300 590 400 600 C 500 590 500 360 400 340", 6, INK, "body"),+ stroke("lines", "M400 224 C 330 228 330 352 400 356 C 470 352 470 228 400 224", 5, INK, "head"),+ stroke("lines", "M452 368 L 560 338 M 456 412 L 562 384", 4, INK, "upper arm"),+ stroke("lines", "M560 342 L 650 312 M 562 380 L 652 350", 4, INK, "forearm"),+ stroke("lines", "M376 286 L 382 300 M 420 286 L 426 300", 5, INK, "head"),+ {"op": "add", "node": {"id": "flame", "type": "ellipse", "cx": 170, "cy": 260, "rx": 20, "ry": 28, "fill": "#ffcc66",+ "blur": 6}, "in": "lantern"},+ {"op": "add", "node": {"id": "lamp", "type": "rect", "x": 150, "y": 230, "w": 40, "h": 64, "radius": 8,+ "fill": "none", "stroke": {"paint": INK, "width": 4}}, "in": "lantern"},+ ]+ return out+++def rig():+ bone = lambda name, parent, head, tail: {"op": "bone", "layer": "figure", "add": name, "head": head, "tail": tail,+ **({"parent": parent} if parent else {})}+ return [+ bone("body", None, [400, 590], [400, 360]),+ bone("head", "body", [400, 360], [400, 230]),+ bone("upper", "body", [452, 392], [560, 360]),+ bone("fore", "upper", [560, 360], [650, 330]),+ bone("hand", "fore", [650, 330], [694, 316]),+ ]+++def weights():+ return [+ {"op": "weights", "layer": "figure", "auto": True},+ {"op": "weights", "layer": "figure", "bone": "head", "part": "head"},+ {"op": "weights", "layer": "figure", "bone": "body", "part": "body"},+ {"op": "weights", "layer": "figure", "bone": "hand", "part": "hand"},+ ]+++def poses():+ wave = [(4, {"upper": -35, "fore": -55, "hand": -10}), (8, {"upper": -50, "fore": -20, "hand": 25}),+ (12, {"upper": -35, "fore": -55, "hand": -10}), (16, {"upper": -50, "fore": -20, "hand": 25})]+ return [{"op": "pose", "layer": "figure", "from": 0, "to": f, "bones": b, "hold": 8 if f == 16 else 4} for f, b in wave]+++def keys():+ return [+ {"op": "key", "id": "lantern", "frame": 0, "y": 0, "ease": "in-out"},+ {"op": "key", "id": "lantern", "frame": 12, "y": -18, "ease": "in-out"},+ {"op": "key", "id": "lantern", "frame": 23, "y": 0},+ {"op": "key", "id": "flame", "frame": 0, "opacity": 1, "ease": "in-out"},+ {"op": "key", "id": "flame", "frame": 6, "opacity": 0.55, "ease": "in-out"},+ {"op": "key", "id": "flame", "frame": 12, "opacity": 1},+ {"op": "clip", "add": "wave", "from": 0, "to": 23, "loop": True},+ ]+++if __name__ == "__main__":+ part = sys.argv[1] if len(sys.argv) > 1 else "drawing"+ ops = {"drawing": drawing, "rig": rig, "weights": weights, "poses": poses, "keys": keys}[part]()+ print("\n".join(json.dumps(op) for op in ops))