A drawing app built for agent/human collaboration
Rust
Exports that stay sharp, and animated GIFs
Indicode BV43aec59857a3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e72c494..5f96b67 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,7 @@The first builds, and klad's licences.- A new icon, painted in klad: a K in two brush strokes.+- Exports that stay sharp, and GIFs. A pixel drawing exports at whole-number sizes only, up to 64 times (`klad export sprite.klad --scale 8`), enlarged pixel for pixel; the export window shows **times real size** and the size in pixels. Sheets, numbered frames and Godot exports follow the same rule, and the Godot scenes of a pixel drawing turn texture filtering off. New for every drawing: `klad export art.klad --gif` and **GIF** in the export window write an animated GIF for each clip, or one of the whole timeline, with each frame's own duration.- Animating pixel layers. Frames, holds, links, clips and onion skins work on pixel layers as on paint layers. A keyed pixel layer moves by whole pixels and stays sharp. In-betweens, poses, weights and bones refuse pixel layers and say why: they move points and bend strokes, so draw the frames or key the layer's position.- Mirror and tiles for pixel art. The pixel pencil, shape and fill tools draw each pixel's twin across the **mirror** line. **View > Tile: wrap at the edges** makes the drawing a tile: what you draw past an edge comes back in on the other side, fills go round the edges, and the canvas shows its repeats around it. From the command line: `klad pixel --mirror-x 16` (and `--mirror-y`), `klad new tile.klad --pixel 16 --wrap`, `klad canvas tile.klad --wrap on`, and `klad render --repeat 3` to see a tile repeated.- Shading pixels. The pixel pencil, the shape tool and the fill tool have three inks: **colour**, **lighter** and **darker**; the last two step the pixels you go over along their colour's ramp. **dither** draws a share of the pixels in an even pattern, with the **second colour** for the rest. **Layer > Outline the pixels** adds a one-pixel outline in the current colour, and **Lighter** and **Darker** in the bar under selected marks step them along their ramp. From the command line: `klad pixel --shade`, `--dither` with `--second`, `--outline` (`--inside`), `klad recolour --step`, and `klad recolour --from skin --to skin-dark` to replace a colour.diff --git a/crates/app/src/editor/export.rs b/crates/app/src/editor/export.rsindex eeeddb3..95ab7af 100644--- a/crates/app/src/editor/export.rs+++ b/crates/app/src/editor/export.rs@@ -11,6 +11,7 @@ pub(super) enum What {Image,Frames,Sheet,+ Gif,}#[derive(Clone, Debug, PartialEq)]@@ -52,6 +53,7 @@ pub(super) fn args(bundle: &Path, home: &Path, frame: u32, form: &Form) -> Vec<SWhat::Image => push("--frame", Some(frame.to_string())),What::Frames => push("--frames", Some(form.range.trim().to_string())),What::Sheet => push("--sheet", Some(form.range.trim().to_string())),+ What::Gif => push("--gif", Some(form.range.trim().to_string())),}if let Some(layer) = form.layer.as_ref().filter(|_| form.what != What::Frames) {push("--layer", Some(layer.clone()));@@ -59,10 +61,10 @@ pub(super) fn args(bundle: &Path, home: &Path, frame: u32, form: &Form) -> Vec<Sif form.scale != 1.0 {push("--scale", Some(form.scale.to_string()));}- if form.deep && form.what != What::Frames {+ if form.deep && matches!(form.what, What::Image | What::Sheet) {push("--depth", Some("16".into()));}- if form.background && form.what == What::Image {+ if form.background && matches!(form.what, What::Image | What::Gif) {push("--background", None);}if form.what == What::Sheet {@@ -79,7 +81,7 @@ fn written(out: &str, err: &str) -> String {out.lines().chain(err.lines()).map(str::trim)- .filter(|l| l.ends_with(".png") || l.ends_with(".json") || l.contains(" in all"))+ .filter(|l| l.ends_with(".png") || l.ends_with(".json") || l.ends_with(".gif") || l.contains(" in all")).take(3).collect::<Vec<_>>().join("; ")@@ -96,6 +98,7 @@ impl Editor {What::Image => format!("export frame {}", self.scene.frame),What::Frames => format!("export frames {}", form.range.trim()),What::Sheet => format!("export the sheet of {}", form.range.trim()),+ What::Gif => format!("export a GIF of {}", form.range.trim()),};self.start_job(Spec {tag: Tag::Export,@@ -129,6 +132,9 @@ impl Editor {.iter().map(|c| c.name.clone()).collect();+ let doc = &self.scene.bundle.doc;+ let (pixel, most) = (doc.pixel_art(), klad_render::export::pixel_most(doc));+ let (width, height) = (doc.canvas.width, doc.canvas.height);let form = &mut self.export;ui.horizontal(|ui| {ui.selectable_value(&mut form.what, What::Image, "image")@@ -137,6 +143,8 @@ impl Editor {.hint("numbered PNGs, one per frame");ui.selectable_value(&mut form.what, What::Sheet, "sprite sheet").hint("sheet pages and Aseprite JSON");+ ui.selectable_value(&mut form.what, What::Gif, "GIF")+ .hint("an animated GIF: one for each clip, or one of the whole timeline");});if form.what != What::Frames {let shown = form@@ -172,19 +180,38 @@ impl Editor {});});}- ui.add(- egui::Slider::new(&mut form.scale, 0.125..=4.0)- .logarithmic(true)- .text("scale"),- )- .hint("the size of the export against the canvas");- if form.what != What::Frames {+ match pixel {+ true => {+ form.scale = form.scale.round().clamp(1.0, most);+ ui.add(+ egui::Slider::new(&mut form.scale, 1.0..=most.min(32.0))+ .step_by(1.0)+ .fixed_decimals(0)+ .text("times real size"),+ )+ .hint("pixel art is enlarged by whole numbers only, so every pixel stays a sharp square");+ ui.weak(format!(+ "{} x {} px",+ width * form.scale as u32,+ height * form.scale as u32+ ));+ }+ false => {+ ui.add(+ egui::Slider::new(&mut form.scale, 0.125..=4.0)+ .logarithmic(true)+ .text("scale"),+ )+ .hint("the size of the export against the canvas");+ }+ }+ if matches!(form.what, What::Image | What::Sheet) {ui.checkbox(&mut form.deep, "16 bits per channel").hint("16-bit PNGs; 8-bit ones are dithered so gradients do not band");}- if form.what == What::Image {+ if matches!(form.what, What::Image | What::Gif) {ui.checkbox(&mut form.background, "keep the background colour")- .hint("off: a transparent PNG");+ .hint("off: a transparent picture");}if form.what == What::Sheet {ui.add(egui::Slider::new(&mut form.padding, 0..=16).text("padding px"))@@ -278,5 +305,24 @@ mod tests {args(bundle, home, 0, &frames).join(" "),"export /w/art.klad --frames 0-11 --scale 0.5");+ let gif = Form {+ what: What::Gif,+ range: "hop".into(),+ scale: 8.0,+ deep: true,+ background: true,+ ..Form::default()+ };+ assert_eq!(+ args(bundle, home, 0, &gif).join(" "),+ "export /w/art.klad --gif hop --scale 8 --background"+ );+ assert_eq!(+ written(+ "/w/[email protected]\n",+ "128x96 4 frames (2 pictures), 500 ms, loops 0.5 KB\n"+ ),+ "/w/[email protected]"+ );}}diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rsindex 37ccc9a..0275211 100644--- a/crates/app/src/editor/ui_tests.rs+++ b/crates/app/src/editor/ui_tests.rs@@ -2184,6 +2184,25 @@ fn the_pixel_pencil_mirrors_across_a_line_and_wraps_on_a_tile() {.is_some_and(|why| why.contains("pixel layer") && why.contains("Draw the frames")),"in-betweens say why they do not apply to pixels");+ {+ let ed = h.state_mut();+ ed.windows.export = true;+ ed.export.what = super::export::What::Gif;+ ed.export.scale = 2.6;+ }+ h.run_steps(3);+ assert!(+ h.query_all(By::new().label("times real size")).count() > 0,+ "a pixel drawing exports at whole-number sizes"+ );+ assert_eq!(h.state().export.scale, 3.0, "a size in between lands on a whole number");+ assert_eq!(+ h.query_all(By::new().label("16 bits per channel")).count(),+ 0,+ "a GIF has no 16-bit form"+ );+ h.state_mut().windows.export = false;+ h.run_steps(2);assert_eq!(h.state().is_on(Cmd::Symmetry), Some(false));h.state_mut().invoke(Cmd::Symmetry).unwrap();h.run_steps(2);diff --git a/crates/cli/src/export.rs b/crates/cli/src/export.rsindex a8d751e..7572c52 100644--- a/crates/cli/src/export.rs+++ b/crates/cli/src/export.rs@@ -2,7 +2,7 @@ use crate::layers;use anyhow::{Result, bail};use klad_brush::BrushSet;use klad_core::bundle::{Bundle, write_atomic};-use klad_render::export::{Options, Target, detail_for, png8, png16, render};+use klad_render::export::{Options, Target, png8, png16, render};use std::path::{Path, PathBuf};use std::time::Instant;@@ -52,7 +52,8 @@ pub fn run(path: &Path, opts: Export) -> Result<()> {);}let layer = opts.layer.as_deref().map(|key| doc.find_layer(key)).transpose()?;- let detail = detail_for(opts.scale);+ klad_render::export::check_scale(doc, opts.scale)?;+ let detail = klad_render::export::detail_of(doc, opts.scale);let rasters = layers::load_at(&bundle, opts.frame, &BrushSet::for_bundle(&bundle)?, detail)?;let target = match layer {Some(l) => Target::Layer(l),@@ -167,8 +168,8 @@ mod tests {drawn <= 4 && stretched >= drawn + 3,"soft pixels across the line: stretched {stretched}, drawn {drawn}");- assert_eq!(detail_for(4.0), 4.0);- assert_eq!(detail_for(0.5), 1.0);+ assert_eq!(klad_render::export::detail_for(4.0), 4.0);+ assert_eq!(klad_render::export::detail_for(0.5), 1.0);std::fs::remove_dir_all(&dir).unwrap();}@@ -206,7 +207,8 @@ mod tests {assert_eq!(bundle.doc.palette.len(), 256);let brushes = BrushSet::for_bundle(&bundle).unwrap();let pixels = |scale: f32| {- let detail = detail_for(scale);+ let detail = klad_render::export::detail_of(&bundle.doc, scale);+ assert_eq!(detail, 1.0, "a pixel drawing is drawn at its real size, then enlarged");let rasters = layers::load_at(&bundle, 0, &brushes, detail).unwrap();let options = Options {scale,@@ -235,6 +237,81 @@ mod tests {std::fs::remove_dir_all(&dir).unwrap();}+ #[test]+ fn a_pixel_drawing_is_enlarged_pixel_for_pixel() {+ use klad_core::bundle::Blank;+ let dir = std::env::temp_dir().join(format!("draw-export-pixel-sharp-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ let mut bundle = Bundle::blank(+ dir.join("art.klad"),+ &Blank {+ width: 6,+ height: 4,+ pixel: true,+ ..Blank::default()+ },+ "cli",+ )+ .unwrap();+ let layer = bundle.doc.layers[0].id.clone();+ bundle+ .apply(+ &klad_core::ops::parse_lines(&format!(+ r##"{{"op":"pixel","layer":"{layer}","color":"#ef233c","cells":[[1,1],[3,2],[4,2]]}}"##+ ))+ .unwrap(),+ )+ .unwrap();+ let doc = &bundle.doc;+ let brushes = BrushSet::for_bundle(&bundle).unwrap();+ let rasters = layers::load_at(&bundle, 0, &brushes, 1.0).unwrap();+ let shown = |scale: f32| {+ let options = Options {+ scale,+ background: false,+ references: false,+ detail: klad_render::export::detail_of(doc, scale),+ };+ let image = render(doc, 0, &rasters, &Target::Frame, options).unwrap();+ (image.width() as usize, klad_render::export::dither8(&image).unwrap())+ };+ let (_, real) = shown(1.0);+ let (wide, big) = shown(5.0);+ assert_eq!(wide, 30);+ (0..20usize).for_each(|y| {+ (0..30usize).for_each(|x| {+ let from = ((y / 5) * 6 + x / 5) * 4;+ let at = (y * 30 + x) * 4;+ assert_eq!(+ big[at..at + 4],+ real[from..from + 4],+ "pixel {x},{y} of the enlarged picture"+ );+ });+ });+ assert_eq!(real[(6 + 1) * 4..(6 + 1) * 4 + 4], [0xef, 0x23, 0x3c, 255]);+ let whole = |scale: f32| klad_render::export::check_scale(doc, scale);+ assert!(whole(64.0).is_ok() && whole(1.0).is_ok());+ assert!(whole(1.5).is_err() && whole(0.5).is_err() && whole(65.0).is_err());+ let mut wide_doc = doc.clone();+ wide_doc.canvas.width = 1024;+ assert_eq!(+ klad_render::export::pixel_most(&wide_doc),+ 16.0,+ "no side goes past 16384 px"+ );+ let mut painting = doc.clone();+ painting.layers.iter_mut().for_each(|l| {+ if let klad_core::doc::LayerContent::Paint { pixel, .. } = &mut l.content {+ *pixel = false;+ }+ });+ assert!(!painting.pixel_art());+ assert!(klad_render::export::check_scale(&painting, 2.5).is_ok());+ assert!(klad_render::export::check_scale(&painting, 9.0).is_err());+ std::fs::remove_dir_all(&dir).unwrap();+ }+#[test]fn a_keyed_pixel_layer_moves_by_whole_pixels_and_stays_hard() {use klad_core::bundle::Blank;diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rsindex 702f8c1..dbea0b4 100644--- a/crates/cli/src/main.rs+++ b/crates/cli/src/main.rs@@ -1879,7 +1879,7 @@ enum Command {},#[command(about = "Export PNGs, sprite sheets, numbered frames or a Godot SpriteFrames and scene",- long_about = "Export a transparent PNG of the whole image or one layer or group, at a frame, at any scale from 1/16 to 8 (vectors stay sharp; paint layers are resampled). 8-bit PNGs are dithered from the 16-bit float pixels so gradients do not band; --depth 16 writes 16-bit PNGs. --background keeps the canvas background colour.\n\n klad export art.klad\n klad export art.klad --scale 2\n klad export art.klad --layer lines --scale 4 --depth 16 -o lines.png\n\nAnimations (each clip, or the whole timeline when there are no clips):\n\n klad export art.klad --sheet all [--scale 0.5] [--padding 2] [--max 4096]\n a PNG holding each distinct picture once, trimmed to its pixels (more pages, art-sheet-2.png ..., when it does not fit --max), plus art-sheet.json in Aseprite's array layout: one entry per exposure with its duration in ms, frameTags for clips\n klad export art.klad --sheet run one clip; --sheet 0-11 a range\n klad export art.klad --frames run numbered full-size PNGs, one per frame (run-0000.png ...) in art-run/\n klad export art.klad --godot ../game/art the sheet, art.tres (SpriteFrames: one animation per clip with its fps, loop and per-frame durations) and art.tscn (an AnimatedSprite2D placed so the timeline's origin sits on the node's position). The first folder given is kept in the document (export.godot); later exports and the editor's button write there, and Godot uids are kept so scenes using them keep working. --store replaces a kept folder."+ long_about = "Export a transparent PNG of the whole image or one layer or group, at a frame, at any scale from 1/16 to 8 (vectors stay sharp; paint layers are resampled). A pixel drawing exports at whole-number scales only, up to 64 (or 16384 px a side), enlarged pixel for pixel so it stays sharp: --scale 8 turns a 32 px sprite into 256 px. 8-bit PNGs are dithered from the 16-bit float pixels so gradients do not band; --depth 16 writes 16-bit PNGs. --background keeps the canvas background colour.\n\n klad export art.klad\n klad export art.klad --scale 2\n klad export art.klad --layer lines --scale 4 --depth 16 -o lines.png\n\nAnimations (each clip, or the whole timeline when there are no clips):\n\n klad export art.klad --sheet all [--scale 0.5] [--padding 2] [--max 4096]\n a PNG holding each distinct picture once, trimmed to its pixels (more pages, art-sheet-2.png ..., when it does not fit --max), plus art-sheet.json in Aseprite's array layout: one entry per exposure with its duration in ms, frameTags for clips\n klad export art.klad --sheet run one clip; --sheet 0-11 a range\n klad export art.klad --frames run numbered full-size PNGs, one per frame (run-0000.png ...) in art-run/\n klad export art.klad --gif [run] [--scale 8] an animated GIF with each frame's own duration: one per clip (art-run.gif; clips that loop, loop), or art.gif of the whole timeline; up to 255 colours kept exactly, more are reduced to the nearest of 255; transparent unless --background\n klad export art.klad --godot ../game/art the sheet, art.tres (SpriteFrames: one animation per clip with its fps, loop and per-frame durations) and art.tscn (an AnimatedSprite2D placed so the timeline's origin sits on the node's position). For a pixel drawing the scenes set texture_filter to nearest, so the sprite stays sharp in the game. The first folder given is kept in the document (export.godot); later exports and the editor's button write there, and Godot uids are kept so scenes using them keep working. --store replaces a kept folder.")]Export {bundle: PathBuf,@@ -1909,6 +1909,14 @@ enum Command {help = "Numbered PNGs, one per frame: all, a clip or a range")]frames: Option<String>,+ #[arg(+ long,+ num_args = 0..=1,+ default_missing_value = "all",+ conflicts_with_all = ["sheet", "frames", "godot"],+ help = "An animated GIF: all (a GIF for each clip, or one of the whole timeline), a clip or a range like 0-11"+ )]+ gif: Option<String>,#[arg(long,num_args = 0..=1,@@ -3998,6 +4006,7 @@ fn run() -> Result<()> {references,sheet,frames,+ gif,godot,store,godot_scene,@@ -4025,6 +4034,7 @@ fn run() -> Result<()> {};let packing = sprites::Packing { padding, max };match (sheet, frames, godot) {+ _ if gif.is_some() => sprites::gif(&bundle, gif.as_deref().unwrap_or("all"), &look, out)?,(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)?,diff --git a/crates/cli/src/scene.rs b/crates/cli/src/scene.rsindex 72e6d89..ba1c69d 100644--- a/crates/cli/src/scene.rs+++ b/crates/cli/src/scene.rs@@ -132,8 +132,12 @@ pub fn parallax(path: &Path, dir: Option<PathBuf>, frame: u32) -> Result<Vec<Pat)}).collect();+ let sharp = match bundle.doc.pixel_art() {+ true => "texture_filter = 1\n",+ false => "",+ };let text = format!(- "[gd_scene load_steps={} format=3 uid={}]\n\n{resources}\n[node name={} type=\"Node2D\"]\n{nodes}",+ "[gd_scene load_steps={} format=3 uid={}]\n\n{resources}\n[node name={} type=\"Node2D\"]\n{sharp}{nodes}",planes.len() + 1,quoted(&uid_of(&scene)),quoted(&node_name(&bundle_stem(&bundle))),diff --git a/crates/cli/src/sprites.rs b/crates/cli/src/sprites.rsindex e9dc824..5f85fef 100644--- a/crates/cli/src/sprites.rs+++ b/crates/cli/src/sprites.rs@@ -5,7 +5,7 @@ use anyhow::{Context, Result, anyhow, bail};use klad_brush::BrushSet;use klad_core::bundle::{Bundle, write_atomic};use klad_core::ops::Op;-use klad_render::export::{Options, Target, detail_for, render};+use klad_render::export::{Options, Target, detail_of, render};use klad_render::sprites::{self, Animation, Pixels, Placed, Rect, Run, Scene, Sheet, SpriteFrames, Texture};use rayon::prelude::*;use std::collections::{BTreeMap, BTreeSet};@@ -86,7 +86,7 @@ pub fn pictures(bundle: &Bundle, animations: Vec<Animation>, look: &Look) -> Resscale: look.scale,background: look.background,references: false,- detail: detail_for(look.scale),+ detail: detail_of(doc, look.scale),};let frames: BTreeSet<u32> = animations.iter().flat_map(|a| a.from..=a.to).collect();let mut firsts: BTreeMap<Vec<String>, u32> = BTreeMap::new();@@ -377,6 +377,78 @@ pub fn frames(path: &Path, spec: &str, look: &Look, out: Option<PathBuf>) -> ResOk(())}+pub fn gif(path: &Path, spec: &str, look: &Look, out: Option<PathBuf>) -> Result<()> {+ let start = Instant::now();+ let bundle = Bundle::open(path)?;+ let animations = sprites::animations(&bundle.doc, spec)?;+ let stem = bundle_stem(&bundle);+ let look = Look {+ layer: look.layer.clone(),+ scale: look.scale,+ depth: 8,+ background: look.background,+ };+ let pics = pictures(&bundle, animations, &look)?;+ let (sw, sh) = pics.source;+ let full: Vec<Vec<u8>> = pics+ .cut+ .par_iter()+ .zip(&pics.trims)+ .map(|(cut, trim)| {+ let mut whole = Pixels::blank(sw, sh, 8);+ let all = Rect {+ x: 0,+ y: 0,+ w: cut.width,+ h: cut.height,+ };+ whole.blit(cut, all, trim.x, trim.y);+ whole.bytes().to_vec()+ })+ .collect();+ let alone = pics.animations.len() == 1;+ let folder = out.as_ref().filter(|_| !alone);+ if let Some(dir) = folder {+ fs::create_dir_all(dir).with_context(|| format!("making {}", dir.display()))?;+ }+ pics.animations.iter().try_for_each(|(animation, runs)| {+ let shots: Vec<klad_render::gif::Shot> = runs+ .iter()+ .map(|r| klad_render::gif::Shot {+ rgba: full[r.picture].clone(),+ ms: r.ms,+ })+ .collect();+ let bytes = klad_render::gif::encode(sw, sh, &shots, animation.looping)?;+ let name = match animation.clip {+ true => format!("{stem}-{}{}.gif", file_safe(&animation.name), scale_tag(look.scale)),+ false => format!("{stem}{}.gif", scale_tag(look.scale)),+ };+ let file = match (&out, folder) {+ (_, Some(dir)) => dir.join(name),+ (Some(given), None) => given.clone(),+ (None, None) => bundle_dir(&bundle).join(name),+ };+ write_atomic(&file, &bytes)?;+ println!("{}", file.display());+ eprintln!(+ "{sw}x{sh} {} frames ({} pictures), {} ms, {} {:.1} KB",+ runs.iter().map(|r| r.frames).sum::<u32>(),+ shots.len(),+ shots.iter().map(|s| s.ms).sum::<u32>(),+ match (shots.len(), animation.looping) {+ (1, _) => "one still picture",+ (_, true) => "loops",+ (_, false) => "plays once",+ },+ bytes.len() as f64 / 1024.0+ );+ Ok::<_, anyhow::Error>(())+ })?;+ eprintln!("{:.0} ms", start.elapsed().as_secs_f64() * 1000.0);+ Ok(())+}+pub fn relative(from: &Path, to: &Path) -> PathBuf {let a: Vec<Component> = from.components().collect();let b: Vec<Component> = to.components().collect();@@ -479,6 +551,7 @@ pub fn godot(path: &Path, dir: Option<PathBuf>, store: bool, look: &Look, packinframes_uid: &frames_uid,animation: &first,origin: [ox * sx, oy * sy],+ pixel: bundle.doc.pixel_art(),});write_atomic(&tres, frames_text.as_bytes())?;write_atomic(&tscn, scene_text.as_bytes())?;diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rsindex ee8e703..f9a6a39 100644--- a/crates/cli/tests/binary.rs+++ b/crates/cli/tests/binary.rs@@ -1128,6 +1128,127 @@ fn a_pixel_layer_animates_frame_by_frame_moves_by_whole_pixels_and_refuses_in_bestd::fs::remove_dir_all(&dir).unwrap();}+#[test]+fn a_pixel_drawing_exports_sharp_at_whole_number_scales_as_png_gif_sheet_and_godot_scene() {+ let dir = std::env::temp_dir().join(format!("draw-binary-pixel-export-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ let bundle = dir.join("hop.klad");+ let path = bundle.to_str().unwrap();+ let run = |args: &[&str]| Command::new(env!("CARGO_BIN_EXE_klad")).args(args).output().unwrap();+ let draw = |args: &[&str]| {+ let out = run(args);+ assert!(+ out.status.success(),+ "{args:?}: {}",+ String::from_utf8_lossy(&out.stderr)+ );+ String::from_utf8_lossy(&out.stdout).to_string()+ };+ let refused = |args: &[&str]| {+ let out = run(args);+ assert!(!out.status.success(), "{args:?} went through");+ String::from_utf8_lossy(&out.stderr).to_string()+ };+ draw(&["new", path, "--pixel", "16x12", "--frames", "4", "--fps", "8"]);+ draw(&["palette", path, "--add", "#22223b", "--name", "ink"]);+ draw(&["palette", path, "--add", "#ef233c", "--name", "red"]);+ draw(&["pixel", path, "l1", "--color", "ink", "--rect", "2,6,4,4", "--filled"]);+ draw(&["pixel", path, "l1", "--color", "red", "--cells", "3,7 4,7"]);+ draw(&["add", path, "cel", "--in", "l1", "frame=2"]);+ draw(&[+ "pixel", path, "l1", "--frame", "2", "--color", "ink", "--rect", "2,2,4,4", "--filled",+ ]);+ draw(&["clip", path, "--add", "hop", "--from", "0", "--to", "3", "--loop"]);++ let between = refused(&["export", path, "--scale", "2.5"]);+ assert!(+ between.contains("whole-number scales") && between.contains("not 2.5"),+ "{between}"+ );+ assert!(refused(&["export", path, "--scale", "0.5"]).contains("whole-number scales"));+ assert!(refused(&["export", path, "--scale", "65"]).contains("past 64"));+ assert!(refused(&["export", path, "--gif", "--scale", "1.5"]).contains("whole-number scales"));+ let size = |file: &std::path::Path| {+ let png = std::fs::read(file).unwrap();+ (+ u32::from_be_bytes(png[16..20].try_into().unwrap()),+ u32::from_be_bytes(png[20..24].try_into().unwrap()),+ )+ };+ let big = dir.join("big.png");+ draw(&["export", path, "--scale", "32", "-o", big.to_str().unwrap()]);+ assert_eq!(size(&big), (512, 384), "past the old limit of 8");++ let named = draw(&["export", path, "--gif", "--scale", "8"]);+ let gif_path = std::path::PathBuf::from(named.trim());+ assert_eq!(+ gif_path.file_name().unwrap(),+ "[email protected]",+ "one GIF per clip, named for it"+ );+ let gif = std::fs::read(&gif_path).unwrap();+ assert_eq!(&gif[..6], b"GIF89a");+ assert_eq!(+ (+ u16::from_le_bytes([gif[6], gif[7]]),+ u16::from_le_bytes([gif[8], gif[9]])+ ),+ (128, 96)+ );+ assert_eq!(+ &gif[13..19],+ [0x22, 0x22, 0x3b, 0xef, 0x23, 0x3c],+ "the drawing's two colours, exactly"+ );+ let delays: Vec<u16> = gif+ .windows(8)+ .filter(|w| w[0] == 0x21 && w[1] == 0xf9 && w[2] == 4 && w[7] == 0)+ .map(|w| u16::from_le_bytes([w[4], w[5]]))+ .collect();+ assert_eq!(delays, [25, 25], "two drawings, each held two frames at 8 a second");+ assert!(+ gif.windows(11).any(|w| w == b"NETSCAPE2.0"),+ "the clip loops, so the GIF does"+ );+ let range = dir.join("first.gif");+ draw(&["export", path, "--gif", "0-1", "-o", range.to_str().unwrap()]);+ assert_eq!(u16::from_le_bytes([std::fs::read(&range).unwrap()[6], 0]), 16);++ let sheet = dir.join("sheet.png");+ draw(&[+ "export",+ path,+ "--sheet",+ "all",+ "--scale",+ "3",+ "-o",+ sheet.to_str().unwrap(),+ ]);+ let json: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(dir.join("sheet.json")).unwrap()).unwrap();+ let first = &json["frames"][0];+ assert_eq!(+ (+ first["sourceSize"]["w"].as_u64(),+ first["frame"]["w"].as_u64(),+ first["frame"]["h"].as_u64()+ ),+ (Some(48), Some(12), Some(12)),+ "the sheet's cells are the drawing three times over: {first}"+ );++ let game = dir.join("game");+ draw(&["export", path, "--godot", game.to_str().unwrap(), "--scale", "2"]);+ let scene = std::fs::read_to_string(game.join("hop.tscn")).unwrap();+ assert!(+ scene.contains("type=\"AnimatedSprite2D\"") && scene.contains("texture_filter = 1\n"),+ "{scene}"+ );+ std::fs::remove_dir_all(&dir).unwrap();+}+#[test]fn recolour_moves_strokes_together_and_keeps_their_shades() {let dir = std::env::temp_dir().join(format!("draw-binary-recolour-{}", std::process::id()));diff --git a/crates/render/src/export.rs b/crates/render/src/export.rsindex 5e65654..ae11bb6 100644--- a/crates/render/src/export.rs+++ b/crates/render/src/export.rs@@ -9,6 +9,8 @@ use skia_safe::{pub const SNAP: f32 = 0.13;pub const MAX_SCALE: f32 = 8.0;+pub const PIXEL_MAX_SCALE: f32 = 64.0;+pub const PIXEL_MAX_SIDE: f32 = 16384.0;const BAYER: [u8; 64] = [0, 32, 8, 40, 2, 34, 10, 42, 48, 16, 56, 24, 50, 18, 58, 26, 12, 44, 4, 36, 14, 46, 6, 38, 60, 28, 52, 20, 62, 30,@@ -36,10 +38,51 @@ pub fn detail_for(scale: f32) -> f32 {}}+pub fn detail_of(doc: &Document, scale: f32) -> f32 {+ match doc.pixel_art() {+ true => 1.0,+ false => detail_for(scale),+ }+}++pub fn pixel_most(doc: &Document) -> f32 {+ let longest = doc.canvas.width.max(doc.canvas.height) as f32;+ PIXEL_MAX_SCALE.min((PIXEL_MAX_SIDE / longest).floor()).max(1.0)+}++pub fn check_scale(doc: &Document, scale: f32) -> Result<()> {+ if !doc.pixel_art() {+ if !(1.0 / 16.0..=MAX_SCALE).contains(&scale) {+ bail!("export scale {scale} is outside 1/16..{MAX_SCALE}");+ }+ return Ok(());+ }+ let most = pixel_most(doc);+ if scale.fract() != 0.0 || scale < 1.0 {+ bail!(+ "a pixel drawing exports at whole-number scales (1, 2, 3 up to {most}), so every pixel stays a square: not {scale}"+ );+ }+ if scale > most {+ bail!(+ "export scale {scale} is past {most} for this {}x{} pixel drawing",+ doc.canvas.width,+ doc.canvas.height+ );+ }+ Ok(())+}+pub fn render(doc: &Document, frame: u32, rasters: &Rasters, target: &Target, options: Options) -> Result<Image> {let scale = options.scale;- if !(1.0 / 16.0..=MAX_SCALE).contains(&scale) {- bail!("export scale {scale} is outside 1/16..{MAX_SCALE}");+ check_scale(doc, scale)?;+ if doc.pixel_art() && scale > 1.0 {+ let real = Options {+ scale: 1.0,+ detail: 1.0,+ ..options+ };+ return crate::resample(&render(doc, frame, rasters, target, real)?, scale);}let (w, h) = (((doc.canvas.width as f32 * scale).round() as u32).max(1),diff --git a/crates/render/src/gif.rs b/crates/render/src/gif.rsnew file mode 100644index 0000000..e41ea7e--- /dev/null+++ b/crates/render/src/gif.rs@@ -0,0 +1,424 @@+use anyhow::{Result, bail};+use std::collections::BTreeMap;++pub struct Shot {+ pub rgba: Vec<u8>,+ pub ms: u32,+}++const CLEAR_AT: usize = 128;++fn colours(shots: &[Shot]) -> BTreeMap<[u8; 3], usize> {+ let mut seen: BTreeMap<[u8; 3], usize> = BTreeMap::new();+ shots.iter().for_each(|shot| {+ shot.rgba+ .as_chunks::<4>()+ .0+ .iter()+ .filter(|px| px[3] >= CLEAR_AT as u8)+ .for_each(|px| *seen.entry([px[0], px[1], px[2]]).or_default() += 1);+ });+ seen+}++fn median_cut(counts: &BTreeMap<[u8; 3], usize>, room: usize) -> Vec<[u8; 3]> {+ let mut boxes: Vec<Vec<([u8; 3], usize)>> = vec![counts.iter().map(|(c, n)| (*c, *n)).collect()];+ while boxes.len() < room {+ let widest = boxes+ .iter()+ .enumerate()+ .filter(|(_, b)| b.len() > 1)+ .map(|(i, b)| {+ let spans: [u8; 3] = std::array::from_fn(|ch| {+ let low = b.iter().map(|(c, _)| c[ch]).min().unwrap_or(0);+ let high = b.iter().map(|(c, _)| c[ch]).max().unwrap_or(0);+ high - low+ });+ let channel = (0..3).max_by_key(|ch| spans[*ch]).unwrap_or(0);+ (spans[channel], i, channel)+ })+ .max();+ let Some((_, at, channel)) = widest else {+ break;+ };+ let mut split = boxes.swap_remove(at);+ split.sort_by_key(|(c, _)| c[channel]);+ let total: usize = split.iter().map(|(_, n)| n).sum();+ let mut run = 0;+ let cut = split+ .iter()+ .position(|(_, n)| {+ run += n;+ run * 2 >= total+ })+ .map_or(1, |i| (i + 1).clamp(1, split.len() - 1));+ let upper = split.split_off(cut);+ boxes.push(split);+ boxes.push(upper);+ }+ boxes+ .iter()+ .map(|b| {+ let total = b.iter().map(|(_, n)| *n).sum::<usize>().max(1);+ std::array::from_fn(|ch| (b.iter().map(|(c, n)| c[ch] as usize * n).sum::<usize>() / total) as u8)+ })+ .collect()+}++fn nearest(table: &[[u8; 3]], colour: [u8; 3]) -> usize {+ table+ .iter()+ .enumerate()+ .min_by_key(|(_, c)| (0..3).map(|ch| (c[ch] as i32 - colour[ch] as i32).pow(2)).sum::<i32>())+ .map_or(0, |(i, _)| i)+}++struct Bits {+ out: Vec<u8>,+ hold: u32,+ held: u32,+}++impl Bits {+ fn put(&mut self, code: u32, width: u32) {+ self.hold |= code << self.held;+ self.held += width;+ while self.held >= 8 {+ self.out.push((self.hold & 0xff) as u8);+ self.hold >>= 8;+ self.held -= 8;+ }+ }++ fn end(mut self) -> Vec<u8> {+ if self.held > 0 {+ self.out.push((self.hold & 0xff) as u8);+ }+ self.out+ }+}++fn lzw(indices: &[u8], min: u32) -> Vec<u8> {+ let (clear, end) = (1u32 << min, (1u32 << min) + 1);+ let mut bits = Bits {+ out: Vec::with_capacity(indices.len() / 2),+ hold: 0,+ held: 0,+ };+ let mut table: BTreeMap<(u32, u8), u32> = BTreeMap::new();+ let (mut next, mut width) = (end + 1, min + 1);+ bits.put(clear, width);+ let mut current: Option<u32> = None;+ indices.iter().for_each(|&index| {+ let Some(prefix) = current else {+ current = Some(index as u32);+ return;+ };+ match table.get(&(prefix, index)) {+ Some(&code) => current = Some(code),+ None => {+ bits.put(prefix, width);+ match next < 4096 {+ true => {+ table.insert((prefix, index), next);+ if next == 1 << width && width < 12 {+ width += 1;+ }+ next += 1;+ }+ false => {+ bits.put(clear, width);+ table.clear();+ next = end + 1;+ width = min + 1;+ }+ }+ current = Some(index as u32);+ }+ }+ });+ if let Some(prefix) = current {+ bits.put(prefix, width);+ }+ bits.put(end, width);+ bits.end()+}++fn blocks(out: &mut Vec<u8>, data: &[u8]) {+ data.chunks(255).for_each(|chunk| {+ out.push(chunk.len() as u8);+ out.extend_from_slice(chunk);+ });+ out.push(0);+}++pub fn delays(durations: &[u32]) -> Vec<u16> {+ let mut owed = 0i64;+ durations+ .iter()+ .map(|&ms| {+ owed += ms as i64;+ let ticks = ((owed + 5) / 10).max(1);+ owed -= ticks * 10;+ ticks.min(u16::MAX as i64) as u16+ })+ .collect()+}++pub fn encode(width: u32, height: u32, shots: &[Shot], looping: bool) -> Result<Vec<u8>> {+ if shots.is_empty() {+ bail!("a GIF needs at least one frame");+ }+ if width == 0 || height == 0 || width > u16::MAX as u32 || height > u16::MAX as u32 {+ bail!("a GIF is at most 65535 px a side, not {width}x{height}");+ }+ let pixels = width as usize * height as usize;+ if let Some(short) = shots.iter().find(|s| s.rgba.len() != pixels * 4) {+ bail!("a frame holds {} bytes, not {width}x{height} pixels", short.rgba.len());+ }+ let counts = colours(shots);+ let table: Vec<[u8; 3]> = match counts.len() <= 255 {+ true => counts.keys().copied().collect(),+ false => median_cut(&counts, 255),+ };+ let exact: BTreeMap<[u8; 3], usize> = table.iter().enumerate().map(|(i, c)| (*c, i)).collect();+ let clear = table.len();+ let bits = (clear + 1).next_power_of_two().trailing_zeros().max(1);+ let slots = 1usize << bits;+ let mut out = Vec::with_capacity(pixels / 2);+ out.extend_from_slice(b"GIF89a");+ out.extend_from_slice(&(width as u16).to_le_bytes());+ out.extend_from_slice(&(height as u16).to_le_bytes());+ out.extend_from_slice(&[0x80 | 0x70 | (bits as u8 - 1), 0, 0]);+ (0..slots).for_each(|i| out.extend_from_slice(&table.get(i).copied().unwrap_or([0, 0, 0])));+ if looping && shots.len() > 1 {+ out.extend_from_slice(&[0x21, 0xff, 11]);+ out.extend_from_slice(b"NETSCAPE2.0");+ out.extend_from_slice(&[3, 1, 0, 0, 0]);+ }+ let mut cache: BTreeMap<[u8; 3], usize> = BTreeMap::new();+ let ticks = delays(&shots.iter().map(|s| s.ms).collect::<Vec<_>>());+ shots.iter().zip(&ticks).for_each(|(shot, delay)| {+ let indices: Vec<u8> = shot+ .rgba+ .as_chunks::<4>()+ .0+ .iter()+ .map(|px| match px[3] >= CLEAR_AT as u8 {+ false => clear as u8,+ true => {+ let colour = [px[0], px[1], px[2]];+ let at = exact+ .get(&colour)+ .copied()+ .unwrap_or_else(|| *cache.entry(colour).or_insert_with(|| nearest(&table, colour)));+ at as u8+ }+ })+ .collect();+ out.extend_from_slice(&[0x21, 0xf9, 4, (2 << 2) | 1]);+ out.extend_from_slice(&delay.to_le_bytes());+ out.extend_from_slice(&[clear as u8, 0]);+ out.push(0x2c);+ out.extend_from_slice(&[0, 0, 0, 0]);+ out.extend_from_slice(&(width as u16).to_le_bytes());+ out.extend_from_slice(&(height as u16).to_le_bytes());+ out.push(0);+ let min = bits.max(2);+ out.push(min as u8);+ blocks(&mut out, &lzw(&indices, min));+ });+ out.push(0x3b);+ Ok(out)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn unpack(data: &[u8], min: u32) -> Vec<u8> {+ let (clear, end) = (1u32 << min, (1u32 << min) + 1);+ let mut table: Vec<Vec<u8>> = Vec::new();+ let reset = |table: &mut Vec<Vec<u8>>| {+ table.clear();+ (0..clear).for_each(|i| table.push(vec![i as u8]));+ table.push(Vec::new());+ table.push(Vec::new());+ };+ reset(&mut table);+ let (mut width, mut hold, mut held, mut at) = (min + 1, 0u32, 0u32, 0usize);+ let mut previous: Option<Vec<u8>> = None;+ let mut out = Vec::new();+ loop {+ while held < width {+ hold |= (data[at] as u32) << held;+ held += 8;+ at += 1;+ }+ let code = hold & ((1 << width) - 1);+ hold >>= width;+ held -= width;+ if code == clear {+ reset(&mut table);+ width = min + 1;+ previous = None;+ continue;+ }+ if code == end {+ return out;+ }+ let entry = match (table.get(code as usize), &previous) {+ (Some(known), _) if (code as usize) < table.len() => known.clone(),+ (_, Some(before)) => {+ let mut made = before.clone();+ made.push(before[0]);+ made+ }+ _ => panic!("a code before any pixel"),+ };+ out.extend_from_slice(&entry);+ if let Some(before) = previous {+ let mut made = before;+ made.push(entry[0]);+ table.push(made);+ if table.len() == 1 << width && width < 12 {+ width += 1;+ }+ }+ previous = Some(entry);+ }+ }++ fn frame(width: usize, height: usize, at: impl Fn(usize, usize) -> [u8; 4]) -> Vec<u8> {+ (0..height)+ .flat_map(|y| (0..width).map(move |x| (x, y)))+ .flat_map(|(x, y)| at(x, y))+ .collect()+ }++ #[test]+ fn the_packed_pixels_unpack_to_the_same_indices() {+ let noisy: Vec<u8> = (0..20_000u32)+ .map(|i| ((i.wrapping_mul(2_654_435_761) >> 13) % 7) as u8)+ .collect();+ assert_eq!(+ unpack(&lzw(&noisy, 3), 3),+ noisy,+ "enough codes to fill the table and start over"+ );+ let flat = vec![1u8; 5000];+ assert_eq!(unpack(&lzw(&flat, 2), 2), flat);+ assert_eq!(unpack(&lzw(&[0, 1, 2, 3], 2), 2), [0, 1, 2, 3]);+ }++ #[test]+ fn a_gif_keeps_exact_colours_a_clear_pixel_its_timing_and_its_loop() {+ let red = [0xef, 0x23, 0x3c, 255];+ let ink = [0x22, 0x22, 0x3b, 255];+ let shots = [+ Shot {+ rgba: frame(4, 2, |x, _| if x == 0 { red } else { [0, 0, 0, 0] }),+ ms: 83,+ },+ Shot {+ rgba: frame(4, 2, |x, _| if x == 1 { ink } else { [9, 9, 9, 40] }),+ ms: 83,+ },+ Shot {+ rgba: frame(4, 2, |x, _| if x == 2 { red } else { [0, 0, 0, 0] }),+ ms: 84,+ },+ ];+ let gif = encode(4, 2, &shots, true).unwrap();+ assert_eq!(&gif[..6], b"GIF89a");+ assert_eq!((gif[6], gif[8]), (4, 2));+ assert_eq!(gif[10] & 0x87, 0x81, "a global table of four slots");+ assert_eq!(+ &gif[13..19],+ [0x22, 0x22, 0x3b, 0xef, 0x23, 0x3c],+ "the two colours, exactly"+ );+ let text = String::from_utf8_lossy(&gif);+ assert!(text.contains("NETSCAPE2.0"), "it loops");+ assert_eq!(*gif.last().unwrap(), 0x3b);+ let controls: Vec<(u16, u8)> = gif+ .windows(8)+ .filter(|w| w[0] == 0x21 && w[1] == 0xf9 && w[2] == 4 && w[7] == 0)+ .map(|w| (u16::from_le_bytes([w[4], w[5]]), w[6]))+ .collect();+ assert_eq!(+ controls,+ [(8, 2), (9, 2), (8, 2)],+ "250 ms over three frames, in hundredths, with index 2 as the clear pixel"+ );+ assert!(!String::from_utf8_lossy(&encode(4, 2, &shots, false).unwrap()).contains("NETSCAPE"));+ assert_eq!(+ delays(&[83, 83, 84, 83, 83, 84]).iter().map(|d| *d as u32).sum::<u32>(),+ 50+ );+ assert_eq!(delays(&[1]), [1], "no frame is shorter than a hundredth");+ assert!(encode(4, 2, &[], true).is_err());+ }++ #[test]+ fn another_decoder_reads_back_the_same_picture() {+ use skia_safe::{AlphaType, ColorType, Data, Image, ImageInfo, image::CachingHint};+ let (w, h) = (37usize, 23usize);+ let rgba = frame(w, h, |x, y| match (x * 7 + y * 13) % 5 {+ 0 => [0, 0, 0, 0],+ 1 => [0xef, 0x23, 0x3c, 255],+ 2 => [0x22, 0x22, 0x3b, 255],+ 3 => [(x * 6) as u8, (y * 11) as u8, 200, 255],+ _ => [250, 250, (x + y) as u8, 255],+ });+ let gif = encode(+ w as u32,+ h as u32,+ &[Shot {+ rgba: rgba.clone(),+ ms: 100,+ }],+ false,+ )+ .unwrap();+ let image = Image::from_encoded(Data::new_copy(&gif)).expect("Skia reads the GIF");+ assert_eq!((image.width() as usize, image.height() as usize), (w, h));+ let info = ImageInfo::new((w as i32, h as i32), ColorType::RGBA8888, AlphaType::Unpremul, None);+ let mut read = vec![0u8; w * h * 4];+ assert!(image.read_pixels(&info, &mut read, w * 4, (0, 0), CachingHint::Allow));+ rgba.as_chunks::<4>()+ .0+ .iter()+ .zip(read.as_chunks::<4>().0)+ .enumerate()+ .for_each(|(i, (made, back))| match made[3] {+ 0 => assert_eq!(back[3], 0, "pixel {i} stays clear"),+ _ => assert_eq!(made, back, "pixel {i}"),+ });+ }++ #[test]+ fn more_than_255_colours_are_cut_down_to_a_palette_that_stays_close() {+ let rgba = frame(64, 64, |x, y| [(x * 4) as u8, (y * 4) as u8, ((x + y) * 2) as u8, 255]);+ let counts = colours(&[Shot {+ rgba: rgba.clone(),+ ms: 100,+ }]);+ assert!(counts.len() > 255);+ let table = median_cut(&counts, 255);+ assert_eq!(table.len(), 255);+ let worst = counts+ .keys()+ .map(|c| {+ let near = table[nearest(&table, *c)];+ (0..3)+ .map(|ch| (near[ch] as i32 - c[ch] as i32).abs())+ .max()+ .unwrap_or(0)+ })+ .max()+ .unwrap_or(0);+ assert!(worst <= 40, "the furthest colour is {worst} levels from its entry");+ assert!(encode(64, 64, &[Shot { rgba, ms: 100 }], false).is_ok());+ }+}diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rsindex e44ed11..72ed20f 100644--- a/crates/render/src/lib.rs+++ b/crates/render/src/lib.rs@@ -4,6 +4,7 @@ pub mod effects;pub mod export;pub mod fonts;pub mod form;+pub mod gif;pub mod onion;pub mod overlay;pub mod pngwrite;@@ -1059,7 +1060,7 @@ pub fn compose_image(doc: &Document, frame: u32, rasters: &Rasters) -> Result<ImOk(surface.image_snapshot())}-fn resample(image: &Image, scale: f32) -> Result<Image> {+pub(crate) fn resample(image: &Image, scale: f32) -> Result<Image> {let (w, h) = (((image.width() as f32 * scale).round() as u32).max(1),((image.height() as f32 * scale).round() as u32).max(1),diff --git a/crates/render/src/sprites.rs b/crates/render/src/sprites.rsindex 68757ed..83f3398 100644--- a/crates/render/src/sprites.rs+++ b/crates/render/src/sprites.rs@@ -136,7 +136,7 @@ impl Pixels {}}- fn bytes(&self) -> &[u8] {+ pub fn bytes(&self) -> &[u8] {match &self.data {Data::Rgba8(d) => d,Data::Rgba16(d) => bytemuck::cast_slice(d),@@ -438,6 +438,7 @@ pub struct Scene<'a> {pub frames_uid: &'a str,pub animation: &'a str,pub origin: [f32; 2],+ pub pixel: bool,}pub fn node_name(stem: &str) -> String {@@ -465,7 +466,10 @@ pub fn scene(s: &Scene) -> String {quoted(s.animation),number(-s.origin[0]),number(-s.origin[1])- )+ ) + match s.pixel {+ true => "texture_filter = 1\n",+ false => "",+ }}pub fn uid_text(mut id: u64) -> String {@@ -751,6 +755,7 @@ mod tests {frames_uid: "uid://frames",animation: "idle",origin: [16.0, 30.5],+ pixel: false,});assert!(tscn.contains("[node name=\"ball_v2\" type=\"AnimatedSprite2D\"]"));assert!(tscn.contains("offset = Vector2(-16, -30.5)\n"));diff --git a/docs/DESIGN.md b/docs/DESIGN.mdindex 83220ef..8adf4a2 100644--- a/docs/DESIGN.md+++ b/docs/DESIGN.md@@ -1,4 +1,4 @@-_Last updated: 2026-11-12 05:00_+_Last updated: 2026-11-12 06:30_# klad: design@@ -232,7 +232,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.-- **Pixel layers (M9).** A pixel layer is a paint layer flagged `pixel`, so it shares cels, masks, clipping, lock alpha, effects, the timeline and every export with paint layers. One pixel is one canvas pixel: a 64x64 sprite is a 64x64 drawing shown enlarged, and a drawing never mixes pixel sizes. Its marks stay data, as strokes do: a pixel mark is a fill record whose source is cells (`FillSource::Cells`), a set of whole pixels (coverage 0 or 255) with the id of the palette swatch it was drawn with, or a set of pixels to erase. So the same addresses, `set`, `rm`, `transform`, lasso, copy and history work on them; scaling, flipping and turning sample the nearest pixel (`markedit::resampled` with `hard`), which also makes an export above full size hard-edged. Colours are palette entries: `Document::bind_swatch` finds or adds the swatch and gives it an `id` the first time a mark uses it, and `set color=` on a pixel mark binds it to the new entry. The `pixel` op (`klad pixel`) is the first way to make marks; brush strokes and flood or lasso fills are refused on a pixel layer (`ops::off_the_grid`). A drawing with a pixel layer (`Document::pixel_art`) gets a sharp view on both sides. In the editor the zoom moves in whole screen pixels per pixel above real size (`View::whole`, `View::fit_whole`; free below it), a pixel grid shows from 8 screen pixels per pixel (a dark line with light dashes, so it reads on any colour; View > Pixel grid), the pixel under the pointer is outlined on a pixel layer and named in the status line, and the Real size pane (`Pane::Preview`, opened the first time a pixel drawing is opened) shows the composed frame at 1, 2 or 4 screen pixels per pixel for drawings up to 512 px. In the CLI, `klad render` and edit previews enlarge by a whole number to about 512 px (`agent::pixel_scale`), and `--overlay grid` draws the same lines with the pixel numbers along the top and left (`overlay::draw_cells`). The palette is what a pixel drawing is bound to. A mark stores its swatch's id and its colour, so every reader of a stroke file draws it without the palette; when a palette edit changes a swatch's colour, `ops::follow_palette` adds a `MarkChange::Entry` for every pixel drawing, which rewrites the colour of the marks bound to that swatch in the same transaction (one undo step), and a removed swatch unbinds its marks. A palette rewritten without ids keeps them by name, then by colour (`carry_ids`). Swatches carry an optional `ramp` name: a ramp is the swatches sharing it, in palette order, dark to light (`palettes::ramp` makes one from a base colour with `color::value_step`, darker and cooler to lighter and warmer). Palettes that come with klad are colour lists in `core/src/palettes.rs` (`klad palettes`), and `palettes::parse` reads a list of hex colours or a GIMP palette. The pencil is grid geometry in `core/src/pixel.rs`, shared by both hands: `line` (Bresenham), `extend` (a run that follows the pen with no holes), `perfect` (drops the corner pixel of an L, so a hand-drawn line stays one pixel thin), `stamp` (a size is a square of whole pixels) and `of_path` (SVG path data flattened and traced; corners the path asks for are kept, the corners that flattening a curve leaves are not). The `pixel` op takes `cells` or a `path`, and a `size`. In the editor the brush tool on a pixel layer is the pencil (the eraser command and the pen's eraser end erase): the run is drawn over the canvas as it grows and committed on release as one `pixel` op marked as made by hand, so the palette binding, history and sync are the op's. Shift click draws a straight line from the last pixel; `[` and `]` change the size. An agent reads and writes a pixel layer as text, which is exact where a picture is not. `pixel::grid_of` works out what a drawing's marks show, pixel by pixel (later marks over earlier ones, erasing marks, lock alpha, cuts), as the palette entry or the colour of each pixel; `pixel::legend` gives each one a character (the first letter of its name where free) and `pixel::ruled` or `pixel::plain` print the rows (`klad pixels`). The other way, `pixel::parse_text` reads a legend and rows and the grid form of the `pixel` op (`rows`, `legend`, `at`) turns each character into one mark bound to its colour (`klad pixel --grid`), so what `klad pixels --plain` prints draws the same picture again. Text grids are the agent's side only: a person draws with the pencil. Shapes and fills are the same op with other sources: `line`, `rect` and `ellipse` (the ellipse that fits a box of pixels, by an integer midpoint walk, so even and odd sizes stay symmetric; `filled` takes the rows between its outline) are pure geometry in `core/src/pixel.rs`; `fill` is a flood over what the drawing shows (`pixel::flood` on the grid of `grid_of`: pixels joined to the seed with exactly its entry or colour, four neighbours or eight), reading this layer, another pixel layer or all of them merged. A flood needs the marks, which an op cannot read, so `Bundle::settle_pixels` turns every `fill` into its cells before the ops are applied, walking the batch so a fill sees the marks the ops before it made; `Bundle::apply_as` calls it, so the CLI, `klad apply` and the editor share it. In the editor the fill tool floods on a click and the shape tool drags a rectangle, an ellipse or a line of pixels on a pixel layer, previewed as the pixels it will make. Editing pixel marks reuses the selection and transform of strokes and fills, with three differences that keep the grid. A lasso that cuts would leave a supersampled cut on a mark (a soft edge), so `markedit::split` divides a pixel mark's coverage between whole pixels instead, by pixel middles, and the two halves carry no cut. A transform whose matrix is whole numbers (flips, quarter turns, whole scales) is rounded onto the grid in `transform_fill` (`on_the_grid`: matrix and offset rounded), so every pixel lands on a pixel whatever the pivot and marks transformed together still fit; other transforms sample the nearest pixel. Recolouring pixel marks gives each exactly the target colour and its palette entry, where paint marks keep their shades. In the editor the stroke tool on a pixel layer drags a box (or a loop) that snaps out to whole pixels and takes pixels, its box is the selected area, drags move by whole pixels, scale by whole numbers and turn by quarters (`Drag.whole`), and Select same colour takes every mark of the selected marks' palette entries. Shading builds on ramps. `shade` (a number of ramp steps) is a way to colour, not a source: for the pixels of any source, `Bundle::settled` reads what the layer shows and makes one mark per target colour, each pixel taking the swatch `Document::ramp_step` gives for its own (pixels in no ramp, or at its end, are left). `dither` keeps the pixels a 4x4 Bayer pattern fixed to the canvas turns on for that share (`pixel::dithered`), and `second` gives the rest another colour, as a second mark. `outline` is a source: the empty pixels that touch a drawn one (or, `inside`, the drawn ones that touch an empty one) on the grid of this layer, another or all (`pixel::outline`). All three need the drawing, so they are settled in the bundle with `fill`, and `settle_pixels` may return more ops than it was given. Mark by mark, `klad recolour --step` and the selection bar's Lighter and Darker move a mark to the next swatch of its ramp, and `klad recolour --from` rebinds every mark of one colour. A colour's character in the text view is fixed by its place in the palette, not by which colours are in use. Two things multiply what is drawn. A mirror (`mirrorX`, `mirrorY` on the `pixel` op; the editor's mirror line) adds each pixel's twin across a line that stands between two pixels or through a column (`pixel::mirrored`); it is part of the op, so the mark holds both halves. Wrap is a property of the canvas (`canvas.wrap`, set by the `canvas` op): the drawing is a tile, so `PixelSpec::coverage` brings pixels past an edge back in on the other side (`pixel::wrapped`) instead of dropping them, and floods and outlines take their neighbours round the edges. It changes what is drawn, never how the drawing renders; to see the repeat, the editor draws the canvas quad three times across and down with the copies dimmed (the shader repeats the texture when the view's uniform says so) and `klad render --repeat N` tiles the finished picture. Transforms of marks do not wrap. Animation on pixel layers is the timeline as it is: drawings on frames, holds, links, clips and onion skins need nothing new, since a pixel layer is a paint layer. Two things differ. A keyed layer or group that holds only pixel layers (`Layer::grid_only`) is drawn at its key's position rounded to whole pixels and sampled nearest (`render::draw_content`), so a keyed move never softens a sprite. And the ops that move points refuse pixel layers with the reason and what to do instead (`ops::grid_refusal`, checked in `ops::apply` and before the CLI resolves anything): `inbetween`, `pose`, `weights` and attaching to bones. Sharp exports and Aseprite files follow in the milestone's later stories.+- **Pixel layers (M9).** A pixel layer is a paint layer flagged `pixel`, so it shares cels, masks, clipping, lock alpha, effects, the timeline and every export with paint layers. One pixel is one canvas pixel: a 64x64 sprite is a 64x64 drawing shown enlarged, and a drawing never mixes pixel sizes. Its marks stay data, as strokes do: a pixel mark is a fill record whose source is cells (`FillSource::Cells`), a set of whole pixels (coverage 0 or 255) with the id of the palette swatch it was drawn with, or a set of pixels to erase. So the same addresses, `set`, `rm`, `transform`, lasso, copy and history work on them; scaling, flipping and turning sample the nearest pixel (`markedit::resampled` with `hard`), which also makes an export above full size hard-edged. Colours are palette entries: `Document::bind_swatch` finds or adds the swatch and gives it an `id` the first time a mark uses it, and `set color=` on a pixel mark binds it to the new entry. The `pixel` op (`klad pixel`) is the first way to make marks; brush strokes and flood or lasso fills are refused on a pixel layer (`ops::off_the_grid`). A drawing with a pixel layer (`Document::pixel_art`) gets a sharp view on both sides. In the editor the zoom moves in whole screen pixels per pixel above real size (`View::whole`, `View::fit_whole`; free below it), a pixel grid shows from 8 screen pixels per pixel (a dark line with light dashes, so it reads on any colour; View > Pixel grid), the pixel under the pointer is outlined on a pixel layer and named in the status line, and the Real size pane (`Pane::Preview`, opened the first time a pixel drawing is opened) shows the composed frame at 1, 2 or 4 screen pixels per pixel for drawings up to 512 px. In the CLI, `klad render` and edit previews enlarge by a whole number to about 512 px (`agent::pixel_scale`), and `--overlay grid` draws the same lines with the pixel numbers along the top and left (`overlay::draw_cells`). The palette is what a pixel drawing is bound to. A mark stores its swatch's id and its colour, so every reader of a stroke file draws it without the palette; when a palette edit changes a swatch's colour, `ops::follow_palette` adds a `MarkChange::Entry` for every pixel drawing, which rewrites the colour of the marks bound to that swatch in the same transaction (one undo step), and a removed swatch unbinds its marks. A palette rewritten without ids keeps them by name, then by colour (`carry_ids`). Swatches carry an optional `ramp` name: a ramp is the swatches sharing it, in palette order, dark to light (`palettes::ramp` makes one from a base colour with `color::value_step`, darker and cooler to lighter and warmer). Palettes that come with klad are colour lists in `core/src/palettes.rs` (`klad palettes`), and `palettes::parse` reads a list of hex colours or a GIMP palette. The pencil is grid geometry in `core/src/pixel.rs`, shared by both hands: `line` (Bresenham), `extend` (a run that follows the pen with no holes), `perfect` (drops the corner pixel of an L, so a hand-drawn line stays one pixel thin), `stamp` (a size is a square of whole pixels) and `of_path` (SVG path data flattened and traced; corners the path asks for are kept, the corners that flattening a curve leaves are not). The `pixel` op takes `cells` or a `path`, and a `size`. In the editor the brush tool on a pixel layer is the pencil (the eraser command and the pen's eraser end erase): the run is drawn over the canvas as it grows and committed on release as one `pixel` op marked as made by hand, so the palette binding, history and sync are the op's. Shift click draws a straight line from the last pixel; `[` and `]` change the size. An agent reads and writes a pixel layer as text, which is exact where a picture is not. `pixel::grid_of` works out what a drawing's marks show, pixel by pixel (later marks over earlier ones, erasing marks, lock alpha, cuts), as the palette entry or the colour of each pixel; `pixel::legend` gives each one a character (the first letter of its name where free) and `pixel::ruled` or `pixel::plain` print the rows (`klad pixels`). The other way, `pixel::parse_text` reads a legend and rows and the grid form of the `pixel` op (`rows`, `legend`, `at`) turns each character into one mark bound to its colour (`klad pixel --grid`), so what `klad pixels --plain` prints draws the same picture again. Text grids are the agent's side only: a person draws with the pencil. Shapes and fills are the same op with other sources: `line`, `rect` and `ellipse` (the ellipse that fits a box of pixels, by an integer midpoint walk, so even and odd sizes stay symmetric; `filled` takes the rows between its outline) are pure geometry in `core/src/pixel.rs`; `fill` is a flood over what the drawing shows (`pixel::flood` on the grid of `grid_of`: pixels joined to the seed with exactly its entry or colour, four neighbours or eight), reading this layer, another pixel layer or all of them merged. A flood needs the marks, which an op cannot read, so `Bundle::settle_pixels` turns every `fill` into its cells before the ops are applied, walking the batch so a fill sees the marks the ops before it made; `Bundle::apply_as` calls it, so the CLI, `klad apply` and the editor share it. In the editor the fill tool floods on a click and the shape tool drags a rectangle, an ellipse or a line of pixels on a pixel layer, previewed as the pixels it will make. Editing pixel marks reuses the selection and transform of strokes and fills, with three differences that keep the grid. A lasso that cuts would leave a supersampled cut on a mark (a soft edge), so `markedit::split` divides a pixel mark's coverage between whole pixels instead, by pixel middles, and the two halves carry no cut. A transform whose matrix is whole numbers (flips, quarter turns, whole scales) is rounded onto the grid in `transform_fill` (`on_the_grid`: matrix and offset rounded), so every pixel lands on a pixel whatever the pivot and marks transformed together still fit; other transforms sample the nearest pixel. Recolouring pixel marks gives each exactly the target colour and its palette entry, where paint marks keep their shades. In the editor the stroke tool on a pixel layer drags a box (or a loop) that snaps out to whole pixels and takes pixels, its box is the selected area, drags move by whole pixels, scale by whole numbers and turn by quarters (`Drag.whole`), and Select same colour takes every mark of the selected marks' palette entries. Shading builds on ramps. `shade` (a number of ramp steps) is a way to colour, not a source: for the pixels of any source, `Bundle::settled` reads what the layer shows and makes one mark per target colour, each pixel taking the swatch `Document::ramp_step` gives for its own (pixels in no ramp, or at its end, are left). `dither` keeps the pixels a 4x4 Bayer pattern fixed to the canvas turns on for that share (`pixel::dithered`), and `second` gives the rest another colour, as a second mark. `outline` is a source: the empty pixels that touch a drawn one (or, `inside`, the drawn ones that touch an empty one) on the grid of this layer, another or all (`pixel::outline`). All three need the drawing, so they are settled in the bundle with `fill`, and `settle_pixels` may return more ops than it was given. Mark by mark, `klad recolour --step` and the selection bar's Lighter and Darker move a mark to the next swatch of its ramp, and `klad recolour --from` rebinds every mark of one colour. A colour's character in the text view is fixed by its place in the palette, not by which colours are in use. Two things multiply what is drawn. A mirror (`mirrorX`, `mirrorY` on the `pixel` op; the editor's mirror line) adds each pixel's twin across a line that stands between two pixels or through a column (`pixel::mirrored`); it is part of the op, so the mark holds both halves. Wrap is a property of the canvas (`canvas.wrap`, set by the `canvas` op): the drawing is a tile, so `PixelSpec::coverage` brings pixels past an edge back in on the other side (`pixel::wrapped`) instead of dropping them, and floods and outlines take their neighbours round the edges. It changes what is drawn, never how the drawing renders; to see the repeat, the editor draws the canvas quad three times across and down with the copies dimmed (the shader repeats the texture when the view's uniform says so) and `klad render --repeat N` tiles the finished picture. Transforms of marks do not wrap. Animation on pixel layers is the timeline as it is: drawings on frames, holds, links, clips and onion skins need nothing new, since a pixel layer is a paint layer. Two things differ. A keyed layer or group that holds only pixel layers (`Layer::grid_only`) is drawn at its key's position rounded to whole pixels and sampled nearest (`render::draw_content`), so a keyed move never softens a sprite. And the ops that move points refuse pixel layers with the reason and what to do instead (`ops::grid_refusal`, checked in `ops::apply` and before the CLI resolves anything): `inbetween`, `pose`, `weights` and attaching to bones. Exports of a pixel drawing take whole-number scales only (`export::check_scale`: 1 to `PIXEL_MAX_SCALE` 64, no side past 16384 px, checked before anything is drawn): the frame is drawn at its real size and enlarged with nearest sampling (`export::render`, the same `resample` the preview uses), so the detail of the rasters stays 1 (`export::detail_of`) and every export path (a frame, sheets, numbered frames, GIF, Godot) is sharp by the same code. Fractional scales are refused, not rounded, because a rounded scale would silently change the size asked for. The Godot scenes of a pixel drawing set `texture_filter = 1` (nearest) on the sprite, or on the root of a parallax scene, so nothing depends on the project's default filter. `render/src/gif.rs` writes animated GIFs (`klad export --gif`, the export window's GIF choice) with no new dependency: one global table of up to 255 colours plus a clear index, exact when the frames hold 255 colours or fewer (always, for palette art), median cut and nearest entry otherwise, no dithering; LZW with a table reset at 4096 codes; each run of equal pictures is one frame whose delay is its duration in hundredths with the rounding error carried to the next, so the total stays right; frames replace each other (disposal 2) since they are whole pictures with clear pixels. A test reads the result back with Skia's decoder. Aseprite files follow in the milestone's later stories.- **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), `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 (noise and haze read only their own pixel and add no margin, so they cost no neighbouring tiles); a tile skips a clip stack or group that puts no pixel in it (none of its rasters, live tiles or onion ghosts has a tile in the tile grown by its effects' margin; layers moved by keys, adjustment layers and vector layers drawn from their nodes always count), which leaves the tile the same since every blend leaves the pixels under a transparent layer as they are; 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.diff --git a/docs/cli.md b/docs/cli.mdindex 6609c88..056a3b5 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -3340,7 +3340,7 @@ Options:## klad export```text-Export a transparent PNG of the whole image or one layer or group, at a frame, at any scale from 1/16 to 8 (vectors stay sharp; paint layers are resampled). 8-bit PNGs are dithered from the 16-bit float pixels so gradients do not band; --depth 16 writes 16-bit PNGs. --background keeps the canvas background colour.+Export a transparent PNG of the whole image or one layer or group, at a frame, at any scale from 1/16 to 8 (vectors stay sharp; paint layers are resampled). A pixel drawing exports at whole-number scales only, up to 64 (or 16384 px a side), enlarged pixel for pixel so it stays sharp: --scale 8 turns a 32 px sprite into 256 px. 8-bit PNGs are dithered from the 16-bit float pixels so gradients do not band; --depth 16 writes 16-bit PNGs. --background keeps the canvas background colour.klad export art.kladklad export art.klad --scale 2@@ -3352,7 +3352,8 @@ Animations (each clip, or the whole timeline when there are no clips):a PNG holding each distinct picture once, trimmed to its pixels (more pages, art-sheet-2.png ..., when it does not fit --max), plus art-sheet.json in Aseprite's array layout: one entry per exposure with its duration in ms, frameTags for clipsklad export art.klad --sheet run one clip; --sheet 0-11 a rangeklad export art.klad --frames run numbered full-size PNGs, one per frame (run-0000.png ...) in art-run/- klad export art.klad --godot ../game/art the sheet, art.tres (SpriteFrames: one animation per clip with its fps, loop and per-frame durations) and art.tscn (an AnimatedSprite2D placed so the timeline's origin sits on the node's position). The first folder given is kept in the document (export.godot); later exports and the editor's button write there, and Godot uids are kept so scenes using them keep working. --store replaces a kept folder.+ klad export art.klad --gif [run] [--scale 8] an animated GIF with each frame's own duration: one per clip (art-run.gif; clips that loop, loop), or art.gif of the whole timeline; up to 255 colours kept exactly, more are reduced to the nearest of 255; transparent unless --background+ klad export art.klad --godot ../game/art the sheet, art.tres (SpriteFrames: one animation per clip with its fps, loop and per-frame durations) and art.tscn (an AnimatedSprite2D placed so the timeline's origin sits on the node's position). For a pixel drawing the scenes set texture_filter to nearest, so the sprite stays sharp in the game. The first folder given is kept in the document (export.godot); later exports and the editor's button write there, and Godot uids are kept so scenes using them keep working. --store replaces a kept folder.Usage: klad export [OPTIONS] <BUNDLE>@@ -3390,6 +3391,9 @@ Options:--frames <FRAMES>Numbered PNGs, one per frame: all, a clip or a range+ --gif [<GIF>]+ An animated GIF: all (a GIF for each clip, or one of the whole timeline), a clip or a range like 0-11+--godot [<GODOT>]Godot SpriteFrames and AnimatedSprite2D scene into this folder (default: the document's export.godot)diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.mdindex 77f8a84..d84a90c 100644--- a/docs/skill/SKILL.md+++ b/docs/skill/SKILL.md@@ -141,6 +141,7 @@ klad export sprite.klad --scale 8 -o [email protected] square pixels, to keep- Editing an area: `klad lasso sprite.klad l1 --box x,y,w,h --cut --move 2,0` takes the pixels in that box (its top left pixel and size; `--polygon` for another outline) and moves them by whole pixels; `--flip h`, `--rotate 90`, `--scale 2` and `--rm` work the same way. With `--cut` the box takes pixels: marks it crosses are split between whole pixels and the inside halves become marks of their own. Without it only marks that lie whole inside are taken. Quarter turns, flips and whole-number scales keep every pixel; other angles and scales stay hard but look jagged.- Editing by colour: `klad strokes sprite.klad l1 --entry skin` lists only the marks of one palette colour (with `--json`, their addresses), to move, remove or recolour them together. `klad recolour sprite.klad c2:s4 c2:s9 --to shadow` gives pixel marks exactly that palette colour (no shades are kept, unlike on paint layers); `--step 1` or `--step -1` moves each mark along its colour's ramp instead; `klad recolour sprite.klad --from skin --to skin-dark` replaces a colour, rebinding every mark drawn in it (`--layer`, `--frame` to limit it). To change what a colour looks like everywhere, change the swatch (`klad palette --recolour`); to move marks to another colour, replace.- Animation is frame by frame: a pixel layer holds a drawing per frame like a paint layer (`klad add sprite.klad cel --in l1 frame=2`, then `klad pixel ... --frame 2`; `klad duplicate`, links, holds, clips and `--overlay onion` all work). To make the next frame, read the last one (`klad pixels sprite.klad l1 --frame 0 --plain`), change the text and write it to the new frame. Keying a pixel layer (`klad key sprite.klad l1 --frame 4 x=6`) moves it by whole pixels: positions in between are rounded, so a slow move steps a pixel at a time. `klad inbetween`, `klad pose`, `klad weights` and `klad attach` refuse pixel layers and say why: they move points and bend strokes, which would take pixels off the grid.+- Exports stay sharp: a pixel drawing exports at whole-number scales only (`--scale 1` to 64, at most 16384 px a side), enlarged pixel for pixel, never smoothed; `--scale 2.5` is refused with the reason. That holds for `klad export` of a frame, `--sheet`, `--frames`, `--gif` and `--godot` (sheet cells and the Godot offset are scaled with it; the Godot scenes set `texture_filter` to nearest so the sprite stays sharp in the game). To show a sprite to someone, `klad export sprite.klad --gif --scale 8`; in a game, export at `--scale 1` and let the engine enlarge it.- Each mark, `<cel>:s<id>`, stays editable: `klad set sprite.klad c2:s1 color=shadow` recolours it (and binds it to that entry), `klad transform ... --move 2,0` moves it by whole pixels, `--flip h` and `--rotate 90` keep it hard, `klad rm` removes it. `klad strokes sprite.klad l1` lists the marks with their entry and cell count; `--json` gives each one's `cells`.- Later marks cover earlier ones; `--erase` (or `erase` in a grid's legend) makes a mark that clears what was drawn before it at those pixels (remove that mark and the pixels come back).- Looking: `klad render` and the `--render` preview of an edit enlarge a pixel drawing by a whole number to about 512 px, so every pixel is a square you can see (`--scale 1` gives the real size, which is how the player sees it: check there too). `--overlay grid` draws a line between pixels and numbers them along the top and the left, so a pixel's `x,y` can be read off the picture: the number is on the line where that column or row starts. `klad export --scale 8` (whole numbers) writes the enlarged PNG to keep.@@ -432,11 +433,13 @@ In `apply`: `{"op":"clip","add":"run","from":0,"to":11,"loop":true,"fps":24}`, `klad export art.klad --sheet all [--scale 0.5] [--padding 2] [--max 4096] [--depth 16]klad export art.klad --sheet run -o out/run.pngklad export art.klad --frames run # run-0000.png ... full size, one per frame, in art-run/+klad export art.klad --gif [run] [--scale 2] [--background] # art-run.gif per clip, or art.gif of the whole timelineklad export art.klad --godot ../game/art/hero # first time: the folder is kept in the documentklad export art.klad --godot # later: the kept folder (the editor's button does the same)```- `--sheet all` exports every clip (or the whole timeline as `default` when there are none), `--sheet <clip>` one, `--sheet 0-11` a range. The PNG holds each distinct picture once (holds, links and frames that render the same share one), trimmed to its pixels, in order of first appearance; beyond `--max` it goes to more pages (`art-sheet-2.png`, ...). The JSON is Aseprite's array layout: one entry per exposure with `duration` in ms at the clip's fps (a clip's durations add up to its length), `frame` (rect in the page), `spriteSourceSize` (the trim) and `sourceSize`, plus `frameTags` per clip (`repeat: "1"` when it plays once). Entries on later pages carry `image`.+- `--gif` writes an animated GIF for each clip (`art-<clip>.gif`; a clip that loops makes a GIF that loops), or one of the whole timeline when there are no clips; `--gif <clip>` or `--gif 0-11` writes one, and `-o` names the file (or the folder, for several). Each picture is shown for as long as its frames last, in hundredths of a second with the rounding carried over, so the GIF runs as long as the clip. A GIF holds 255 colours and one clear one: pixel art and flat colour come out exact, a painting with more colours is reduced to the nearest of 255 without dithering (gradients band; use `--frames` and a video tool for those), and half-clear pixels become clear or solid. Transparent unless `--background`.- `--godot <folder>` writes `art.png` (and pages), `art.tres` (a `SpriteFrames`: an `AtlasTexture` per picture with its trim as margin, one animation per clip with its name, speed, loop and per-frame durations in frames) and `art.tscn` (an `AnimatedSprite2D`, autoplaying the first clip, offset so the origin sits on the node's position). Re-exports keep the uids of the `.tres`, `.tscn` and the imported PNG, so scenes using them keep working. `--store` replaces a kept folder; the kept path (`export.godot`) is relative to the folder holding the bundle.- Exports print a pixel hash per page and of the JSON on stderr. The bounce (`samples/bounce/build.sh`) exports in about 0.25 s; 40 distinct 1024 frames to Godot in about 1.4 s warm, 2.3 s cold.