A drawing app built for agent/human collaboration
Rust
Palette variants: other colours for the same sprite, shown and exported one by one
Indicode BV71f0521d9d97
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2e40d0b..5d6e8f1 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.+- Palette variants. A drawing can hold other colours for the same sprite, like a blue team beside a red one. In the Colour panel **new variant** makes one and shows it; colours you change while it is shown are its own, and the palette itself keeps its colours. Pick **base** or a variant under the palette to show it. The export window exports what is shown, one variant, or **every variant** in one go. From the command line: `klad palette --new-variant blue`, `--variant base`, `--rename-variant`, `--rm-variant`, and `klad export --variant blue` or `--variants`.- 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. A GIF holds 255 colours: `--dither` (the **dither** box) mixes them in a fine pattern so the soft gradients of a painting do not band.- 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.diff --git a/crates/app/src/commands.rs b/crates/app/src/commands.rsindex 9136356..22a7951 100644--- a/crates/app/src/commands.rs+++ b/crates/app/src/commands.rs@@ -67,6 +67,10 @@ pub enum Cmd {UpdateSwatch,AddRamp,LoadPalette,+ NewVariant,+ NextVariant,+ RenameVariant,+ RemoveVariant,NewPaintLayer,NewPixelLayer,NewVectorLayer,@@ -517,7 +521,7 @@ use Repeat as R;use Trigger as T;impl Cmd {- pub const ALL: [Cmd; 190] = [+ pub const ALL: [Cmd; 194] = [Cmd::Brush,Cmd::Eraser,Cmd::Fill,@@ -581,6 +585,10 @@ impl Cmd {Cmd::UpdateSwatch,Cmd::AddRamp,Cmd::LoadPalette,+ Cmd::NewVariant,+ Cmd::NextVariant,+ Cmd::RenameVariant,+ Cmd::RemoveVariant,Cmd::NewPaintLayer,Cmd::NewPixelLayer,Cmd::NewVectorLayer,@@ -1279,6 +1287,42 @@ impl Cmd {R::No,"add the colours of a palette that comes with klad, or of a palette file (a list of hex colours or a GIMP palette)",),+ Cmd::NewVariant => spec(+ "colour.variant.new",+ "new palette variant",+ icon::PALETTE,+ G::Colour,+ T::None,+ R::No,+ "another set of colours for the same palette, like a blue team beside a red one, named after the name typed next to it; it is shown at once, and colours you change while it is shown are its own",+ ),+ Cmd::NextVariant => spec(+ "colour.variant.next",+ "show the next palette variant",+ icon::PALETTE,+ G::Colour,+ T::None,+ R::No,+ "show the drawing in its next palette variant, and after the last one in the palette itself",+ ),+ Cmd::RenameVariant => spec(+ "colour.variant.rename",+ "rename the palette variant",+ icon::PALETTE,+ G::Colour,+ T::None,+ R::No,+ "give the variant that is shown the name typed next to it",+ ),+ Cmd::RemoveVariant => spec(+ "colour.variant.remove",+ "remove the palette variant",+ icon::PALETTE,+ G::Colour,+ T::None,+ R::No,+ "remove the variant that is shown; the drawing goes back to the palette itself",+ ),Cmd::NewPaintLayer => spec("layer.new-paint","new paint layer",@@ -2486,6 +2530,10 @@ impl Cmd {Cmd::UpdateSwatch => "Change palette colour to this",Cmd::AddRamp => "Add a ramp of the colour",Cmd::LoadPalette => "Load a palette…",+ Cmd::NewVariant => "New palette variant",+ Cmd::NextVariant => "Show the next palette variant",+ Cmd::RenameVariant => "Rename the palette variant",+ Cmd::RemoveVariant => "Remove the palette variant",Cmd::NewPaintLayer => "New paint layer",Cmd::NewPixelLayer => "New pixel layer",Cmd::NewVectorLayer => "New vector layer",@@ -2762,6 +2810,11 @@ pub const MENUS: [Menu; 9] = [Run(Cmd::UpdateSwatch),Run(Cmd::AddRamp),Run(Cmd::LoadPalette),+ Line,+ Run(Cmd::NewVariant),+ Run(Cmd::NextVariant),+ Run(Cmd::RenameVariant),+ Run(Cmd::RemoveVariant),],},Menu {diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rsindex 6243825..d3fef74 100644--- a/crates/app/src/editor.rs+++ b/crates/app/src/editor.rs@@ -5221,6 +5221,32 @@ impl Editor {});ui.label("palette");let edit = self.palette_row(ui);+ let variants: Vec<String> = self+ .scene+ .bundle+ .doc+ .variant_names()+ .into_iter()+ .map(String::from)+ .collect();+ let shown = self.scene.bundle.doc.shown_variant().to_string();+ let mut show = None;+ if variants.len() > 1 {+ ui.horizontal_wrapped(|ui| {+ ui.label("variant");+ variants.iter().for_each(|name| {+ let hint = match name == klad_core::doc::BASE_VARIANT {+ true => "show the palette itself".to_string(),+ false => format!(+ "show the drawing in the colours of {name}; colours changed while it is shown are its own"+ ),+ };+ if ui.selectable_label(*name == shown, name).hint(hint).clicked() && *name != shown {+ show = Some(name.clone());+ }+ });+ });+ }ui.horizontal_wrapped(|ui| {let label = ui.label("name");ui.add(@@ -5236,7 +5262,15 @@ impl Editor {}self.command_button(ui, Cmd::AddRamp, Some("ramp"));self.command_button(ui, Cmd::LoadPalette, Some("palettes"));+ if variants.len() > 1 || self.can_run(Cmd::NewVariant).is_none() {+ self.command_button(ui, Cmd::NewVariant, Some("new variant"));+ }+ if !self.scene.bundle.doc.variants.shown.is_empty() {+ self.command_button(ui, Cmd::RenameVariant, Some("rename variant"));+ self.command_button(ui, Cmd::RemoveVariant, Some("remove variant"));+ }});+ let edit = edit.or(show.map(|name| klad_core::ops::PaletteEdit::Variant { name }));if !self.settings.recent.is_empty() {ui.label("recent");let recent = self.settings.recent.clone();diff --git a/crates/app/src/editor/commands.rs b/crates/app/src/editor/commands.rsindex 0552812..be1a6e2 100644--- a/crates/app/src/editor/commands.rs+++ b/crates/app/src/editor/commands.rs@@ -194,6 +194,28 @@ impl Editor {}}Cmd::WrapCanvas => editing,+ Cmd::NewVariant => match self.scene.bundle.doc.all_layers().iter().any(|l| l.pixel()) {+ true => editing,+ false => Some(+ "palette variants recolour pixel layers, and this drawing has none: Layer > New pixel layer"+ .to_string(),+ ),+ },+ Cmd::NextVariant if self.scene.bundle.doc.variants.is_empty() => {+ Some("the drawing has no palette variants yet: make one with new variant".to_string())+ }+ Cmd::NextVariant => editing,+ Cmd::RenameVariant | Cmd::RemoveVariant if self.scene.bundle.doc.variants.shown.is_empty() => Some(+ match self.scene.bundle.doc.variants.is_empty() {+ true => "the drawing has no palette variants yet: make one with new variant",+ false => "the palette itself is shown: show a variant first",+ }+ .to_string(),+ ),+ Cmd::RenameVariant if self.swatch_name.trim().is_empty() => {+ Some("type the new name in the name field first".to_string())+ }+ Cmd::RenameVariant | Cmd::RemoveVariant => editing,Cmd::PixelGrid => (!self.scene.bundle.doc.pixel_art()).then(|| "this drawing has no pixel layer: Layer > New pixel layer adds one".to_string()),Cmd::Corner | Cmd::Smooth => direct@@ -582,6 +604,40 @@ impl Editor {Cmd::Unwrap => self.unwrap()?,Cmd::ImportPicture => self.windows.import = !self.windows.import,Cmd::LoadPalette => self.windows.palettes = !self.windows.palettes,+ Cmd::NewVariant => {+ let typed = self.swatch_name.trim().to_string();+ let doc = &self.scene.bundle.doc;+ let taken =+ |name: &str| klad_core::doc::Variants::key(name).is_empty() || doc.variants.find(name).is_some();+ let name = match typed.is_empty() || taken(&typed) {+ false => typed,+ true => (doc.variants.sets.len() + 2..)+ .map(|n| format!("variant {n}"))+ .find(|n| !taken(n))+ .unwrap_or(typed),+ };+ self.swatch_name.clear();+ self.apply(vec![Op::Palette(PaletteEdit::NewVariant { name })])?;+ }+ Cmd::NextVariant => {+ let doc = &self.scene.bundle.doc;+ let names = doc.variant_names();+ let at = names.iter().position(|n| *n == doc.shown_variant()).unwrap_or(0);+ let name = names[(at + 1) % names.len()].to_string();+ self.apply(vec![Op::Palette(PaletteEdit::Variant { name })])?;+ }+ Cmd::RenameVariant => {+ let edit = PaletteEdit::RenameVariant {+ name: self.scene.bundle.doc.variants.shown.clone(),+ to: self.swatch_name.trim().to_string(),+ };+ self.apply(vec![Op::Palette(edit)])?;+ self.swatch_name.clear();+ }+ Cmd::RemoveVariant => {+ let name = self.scene.bundle.doc.variants.shown.clone();+ self.apply(vec![Op::Palette(PaletteEdit::RemoveVariant { name })])?;+ }Cmd::UpdateSwatch => {if let Some(at) = self.swatch_picked {let edit = PaletteEdit::Recolour {diff --git a/crates/app/src/editor/export.rs b/crates/app/src/editor/export.rsindex fd26888..18e6f9c 100644--- a/crates/app/src/editor/export.rs+++ b/crates/app/src/editor/export.rs@@ -22,6 +22,7 @@ pub(super) struct Form {pub background: bool,pub deep: bool,pub dither: bool,+ pub variant: String,pub range: String,pub padding: u32,pub max: u32,@@ -37,6 +38,7 @@ impl Default for Form {background: false,deep: false,dither: false,+ variant: String::new(),range: "all".into(),padding: 2,max: 4096,@@ -45,6 +47,8 @@ impl Default for Form {}}+pub(super) const EVERY: &str = "*";+pub(super) fn args(bundle: &Path, home: &Path, frame: u32, form: &Form) -> Vec<String> {let mut args = vec!["export".to_string(), bundle.to_string_lossy().to_string()];let mut push = |a: &str, b: Option<String>| {@@ -72,6 +76,11 @@ pub(super) fn args(bundle: &Path, home: &Path, frame: u32, form: &Form) -> Vec<Sif form.dither && form.what == What::Gif {push("--dither", None);}+ match form.variant.as_str() {+ "" => {}+ EVERY => push("--variants", None),+ name => push("--variant", Some(name.to_string())),+ }if form.what == What::Sheet {push("--padding", Some(form.padding.to_string()));push("--max", Some(form.max.to_string()));@@ -140,7 +149,11 @@ impl Editor {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 variants: Vec<String> = doc.variant_names().into_iter().map(String::from).collect();let form = &mut self.export;+ if form.variant != EVERY && !form.variant.is_empty() && !variants.contains(&form.variant) {+ form.variant.clear();+ }ui.horizontal(|ui| {ui.selectable_value(&mut form.what, What::Image, "image").hint("this frame as one PNG");@@ -218,6 +231,24 @@ impl Editor {ui.checkbox(&mut form.background, "keep the background colour").hint("off: a transparent picture");}+ if variants.len() > 1 {+ let chosen = match form.variant.as_str() {+ "" => "as shown".to_string(),+ EVERY => "every variant".to_string(),+ name => name.to_string(),+ };+ egui::ComboBox::from_label("palette variant")+ .selected_text(chosen)+ .show_ui(ui, |ui| {+ ui.selectable_value(&mut form.variant, String::new(), "as shown");+ ui.selectable_value(&mut form.variant, EVERY.to_string(), "every variant");+ variants.iter().for_each(|name| {+ ui.selectable_value(&mut form.variant, name.clone(), name);+ });+ })+ .response+ .hint("the colours to export in: what the drawing shows now, one variant, or a file for each (the variant's name is added to the file name)");+ }if form.what == What::Gif && !pixel {ui.checkbox(&mut form.dither, "dither").hint("a GIF holds 255 colours: mix them in a fine pattern so soft gradients do not band; off keeps flat areas of one colour");@@ -327,6 +358,23 @@ mod tests {args(bundle, home, 0, &gif).join(" "),"export /w/art.klad --gif hop --scale 8 --background --dither");+ let every = Form {+ what: What::Sheet,+ variant: EVERY.into(),+ ..Form::default()+ };+ assert_eq!(+ args(bundle, home, 0, &every).join(" "),+ "export /w/art.klad --sheet all --variants --padding 2 --max 4096"+ );+ let blue = Form {+ variant: "blue".into(),+ ..Form::default()+ };+ assert_eq!(+ args(bundle, home, 2, &blue).join(" "),+ "export /w/art.klad --frame 2 --variant blue"+ );let image = Form {dither: true,..Form::default()diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rsindex 0275211..ef943a9 100644--- a/crates/app/src/editor/ui_tests.rs+++ b/crates/app/src/editor/ui_tests.rs@@ -1729,6 +1729,83 @@ fn a_clicked_palette_colour_is_updated_with_its_pixels_and_ramps_and_palettes_jo"two new colours: black is in the palette already");let _ = std::fs::remove_file(&file);+ assert!(+ h.state().can_run(Cmd::NextVariant).is_some() && h.state().can_run(Cmd::RemoveVariant).is_some(),+ "without variants there is nothing to show or remove"+ );+ let first = h.state().scene.bundle.doc.palette[0].color.clone();+ h.state_mut().swatch_name = "night".into();+ h.state_mut().invoke(Cmd::NewVariant).unwrap();+ h.run_steps(3);+ assert_eq!(h.state().scene.bundle.doc.shown_variant(), "night");+ assert!(h.state().swatch_name.is_empty());+ assert!(+ h.query_all(By::new().label("variant")).count() > 0 && h.query_by_label("night").is_some(),+ "the palette panel lists the variants"+ );+ h.state_mut().swatch_picked = Some(0);+ h.state_mut()+ .set_colour(klad_core::color::parse_hex("#101040").unwrap());+ h.state_mut().invoke(Cmd::UpdateSwatch).unwrap();+ h.run_steps(3);+ assert_eq!(h.state().scene.bundle.doc.palette[0].color, "#101040");+ [Pane::Brush, Pane::Layers, Pane::Inspector, Pane::Preview]+ .into_iter()+ .filter(|pane| h.state().settings.layout.is_open(*pane))+ .collect::<Vec<_>>()+ .into_iter()+ .for_each(|pane| h.state_mut().settings.layout.toggle(pane));+ h.run_steps(3);+ h.get_by_label("base").click();+ h.run_steps(3);+ assert_eq!(+ h.state().scene.bundle.doc.shown_variant(),+ "base",+ "a click shows the palette itself"+ );+ assert_eq!(+ h.state().scene.bundle.doc.palette[0].color,+ first,+ "which kept its colour"+ );+ assert!(+ h.state()+ .can_run(Cmd::RenameVariant)+ .is_some_and(|why| why.contains("show a variant first"))+ );+ h.state_mut().invoke(Cmd::NextVariant).unwrap();+ h.run_steps(2);+ assert_eq!(h.state().scene.bundle.doc.palette[0].color, "#101040");+ h.state_mut().invoke(Cmd::NewVariant).unwrap();+ h.run_steps(2);+ assert_eq!(+ h.state().scene.bundle.doc.variant_names(),+ ["base", "night", "variant 3"],+ "an unnamed variant gets a name of its own"+ );+ h.state_mut().swatch_name = "dusk".into();+ h.state_mut().invoke(Cmd::RenameVariant).unwrap();+ h.run_steps(2);+ assert_eq!(h.state().scene.bundle.doc.shown_variant(), "dusk");+ {+ let ed = h.state_mut();+ ed.windows.export = true;+ ed.export.variant = "gone".into();+ }+ h.run_steps(3);+ assert!(+ h.query_all(By::new().label("palette variant")).count() > 0,+ "the export window offers the variants"+ );+ assert!(+ h.state().export.variant.is_empty(),+ "a variant that is gone falls back to what is shown"+ );+ h.state_mut().windows.export = false;+ h.state_mut().invoke(Cmd::RemoveVariant).unwrap();+ h.run_steps(2);+ assert_eq!(h.state().scene.bundle.doc.variant_names(), ["base", "night"]);+ assert_eq!(h.state().scene.bundle.doc.shown_variant(), "base");let _ = std::fs::remove_dir_all(&path);}diff --git a/crates/cli/src/export.rs b/crates/cli/src/export.rsindex 7572c52..58db669 100644--- a/crates/cli/src/export.rs+++ b/crates/cli/src/export.rs@@ -13,6 +13,7 @@ pub struct Export {pub depth: u8,pub background: bool,pub references: bool,+ pub variant: Option<String>,pub out: Option<PathBuf>,}@@ -24,7 +25,7 @@ pub(crate) fn scale_tag(scale: f32) -> String {format!("@{}x", text.trim_end_matches('0').trim_end_matches('.'))}-pub fn default_path(bundle: &Bundle, layer: Option<&str>, frame: u32, scale: f32) -> PathBuf {+pub fn default_path(bundle: &Bundle, layer: Option<&str>, frame: u32, scale: f32, variant: Option<&str>) -> PathBuf {let root = bundle.root.components().collect::<PathBuf>();let stem = root.file_stem()@@ -35,9 +36,11 @@ pub fn default_path(bundle: &Bundle, layer: Option<&str>, frame: u32, scale: f32} else {String::new()};- root.parent()- .unwrap_or(Path::new("."))- .join(format!("{stem}{layer}{frame}{}.png", scale_tag(scale)))+ root.parent().unwrap_or(Path::new(".")).join(format!(+ "{stem}{}{layer}{frame}{}.png",+ layers::variant_tag(variant),+ scale_tag(scale)+ ))}pub fn run(path: &Path, opts: Export) -> Result<()> {@@ -54,7 +57,14 @@ pub fn run(path: &Path, opts: Export) -> Result<()> {let layer = opts.layer.as_deref().map(|key| doc.find_layer(key)).transpose()?;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 brushes = BrushSet::for_bundle(&bundle)?;+ let dress = layers::dress_of(doc, opts.variant.as_deref())?;+ let rasters = layers::dressed(+ &bundle,+ &brushes,+ layers::load_at(&bundle, opts.frame, &brushes, detail)?,+ &dress,+ )?;let target = match layer {Some(l) => Target::Layer(l),None => Target::Frame,@@ -81,7 +91,7 @@ pub fn run(path: &Path, opts: Export) -> Result<()> {});let out = opts.out- .unwrap_or_else(|| default_path(&bundle, name, opts.frame, opts.scale));+ .unwrap_or_else(|| default_path(&bundle, name, opts.frame, opts.scale, opts.variant.as_deref()));write_atomic(&out, &bytes)?;println!("{}", out.display());eprintln!(@@ -108,9 +118,15 @@ mod tests {let mut doc = Document::new(64, 32);doc.layers.push(Layer::paint("l1", "ink", "c1"));let bundle = Bundle::create(dir.join("art.klad/"), doc).unwrap();- assert_eq!(default_path(&bundle, None, 0, 1.0), dir.join("art.png"));- assert_eq!(default_path(&bundle, Some("ink"), 0, 2.0), dir.join("[email protected]"));- assert_eq!(default_path(&bundle, None, 0, 0.5), dir.join("[email protected]"));+ assert_eq!(default_path(&bundle, None, 0, 1.0, None), dir.join("art.png"));+ assert_eq!(+ default_path(&bundle, Some("ink"), 0, 2.0, Some("Blue team")),+ dir.join("[email protected]")+ );+ assert_eq!(+ default_path(&bundle, None, 0, 0.5, Some("base")),+ dir.join("[email protected]")+ );let out = dir.join("out/ink.png");run(&dir.join("art.klad"),@@ -121,6 +137,7 @@ mod tests {depth: 16,background: false,references: false,+ variant: None,out: Some(out.clone()),},)diff --git a/crates/cli/src/layers.rs b/crates/cli/src/layers.rsindex a3b66d7..7ca42f3 100644--- a/crates/cli/src/layers.rs+++ b/crates/cli/src/layers.rs@@ -102,6 +102,73 @@ pub fn load_cels_at(.collect()}+pub fn dress_of(doc: &Document, variant: Option<&str>) -> Result<BTreeMap<String, [u16; 4]>> {+ match variant {+ Some(name) => doc.dress(name),+ None => Ok(BTreeMap::new()),+ }+}++pub fn variant_tag(variant: Option<&str>) -> String {+ match variant.map(klad_core::doc::Variants::key) {+ None | Some("") => String::new(),+ Some(name) => format!("-{}", crate::sprites::file_safe(name)),+ }+}++pub fn dressed(+ bundle: &Bundle,+ brushes: &BrushSet,+ mut rasters: Rasters,+ dress: &BTreeMap<String, [u16; 4]>,+) -> Result<Rasters> {+ if dress.is_empty() {+ return Ok(rasters);+ }+ let (width, height) = (bundle.doc.canvas.width, bundle.doc.canvas.height);+ let cels: Vec<(String, String)> = bundle+ .doc+ .all_layers()+ .into_iter()+ .filter(|layer| layer.pixel())+ .flat_map(|layer| {+ layer+ .cels()+ .iter()+ .filter(|c| rasters.contains_key(&c.id))+ .map(move |c| (layer.id.clone(), c.id.clone()))+ })+ .collect();+ let redrawn = cels+ .par_iter()+ .map(|(layer, cel)| {+ let mut marks = bundle.read_marks(layer, cel)?;+ let swapped = marks+ .iter_mut()+ .filter_map(|mark| match mark {+ klad_core::stroke::Mark::Fill(fill) => Some(fill),+ _ => None,+ })+ .filter_map(|fill| {+ let colour = fill.entry().and_then(|entry| dress.get(entry)).copied()?;+ fill.color = colour;+ Some(())+ })+ .count();+ match swapped {+ 0 => Ok(None),+ _ => {+ let (_, raster, _) =+ CelReplay::replay_tiled(width, height, marks, brushes).with_context(|| format!("cel {cel}"))?;+ Ok(Some((cel.clone(), raster)))+ }+ }+ })+ .collect::<Result<Vec<_>>>()?;+ rasters.extend(redrawn.into_iter().flatten());+ Ok(rasters)+}+pub fn load_at(bundle: &Bundle, frame: u32, brushes: &BrushSet, detail: f32) -> Result<Rasters> {if detail == 1.0 {return Ok(load(bundle, frame, brushes, true)?.rasters);diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rsindex 590969d..28b573a 100644--- a/crates/cli/src/main.rs+++ b/crates/cli/src/main.rs@@ -1798,7 +1798,7 @@ enum Command {},#[command(about = "The document palette: list it, --add or --rm a colour, --recolour one, --load a palette, or group colours in a --ramp",- long_about = "The document palette, kept in doc.json. Named colours can be used wherever a colour goes (--color skin). On pixel layers every mark is bound to the palette colour it was drawn with, so changing that colour here changes the marks.\n\n klad palette art.klad\n klad palette art.klad --add '#f0c8a0' --name skin\n klad palette art.klad --add '#d0a080' --name skin (changes skin)\n klad palette art.klad --recolour skin --to '#e8b796' (by name, colour, index or id)\n klad palette art.klad --rm skin\n klad palette art.klad --load pico-8 (a palette that comes with klad: klad palettes lists them)\n klad palette art.klad --load my.hex (a list of hex colours, one per line, or a GIMP .gpl palette)\n klad palette art.klad --ramp wood --base '#8b5a2b' --steps 5 (wood-1 to wood-5, dark and cool to light and warm)\n klad palette art.klad --ramp skin --of skin-dark,skin,skin-light (group colours it has, dark to light)\n\nA loaded colour the palette already holds is not added again. A ramp is a row of colours from dark to light, used to shade one material.\n\nAs ops: {\"op\":\"palette\",\"add\":\"#f0c8a0\",\"name\":\"skin\"}, {\"op\":\"palette\",\"rm\":\"skin\"}, {\"op\":\"palette\",\"recolour\":\"skin\",\"to\":\"#e8b796\"}, {\"op\":\"palette\",\"load\":\"pico-8\"}, {\"op\":\"palette\",\"ramp\":\"skin\",\"of\":[\"skin-dark\",\"skin\"]}, {\"op\":\"palette\",\"set\":[{\"color\":\"#1b1b1b\",\"name\":\"ink\"}]}"+ long_about = "The document palette, kept in doc.json. Named colours can be used wherever a colour goes (--color skin). On pixel layers every mark is bound to the palette colour it was drawn with, so changing that colour here changes the marks.\n\n klad palette art.klad\n klad palette art.klad --add '#f0c8a0' --name skin\n klad palette art.klad --add '#d0a080' --name skin (changes skin)\n klad palette art.klad --recolour skin --to '#e8b796' (by name, colour, index or id)\n klad palette art.klad --rm skin\n klad palette art.klad --load pico-8 (a palette that comes with klad: klad palettes lists them)\n klad palette art.klad --load my.hex (a list of hex colours, one per line, or a GIMP .gpl palette)\n klad palette art.klad --ramp wood --base '#8b5a2b' --steps 5 (wood-1 to wood-5, dark and cool to light and warm)\n klad palette art.klad --ramp skin --of skin-dark,skin,skin-light (group colours it has, dark to light)\n\nA loaded colour the palette already holds is not added again. A ramp is a row of colours from dark to light, used to shade one material.\n\nPalette variants are named sets of other colours for the same palette (a red and a blue team). The drawing shows one at a time; base is the palette itself. A colour changed while a variant is shown belongs to that variant, and the base keeps its own; a variant follows the base for every colour it has not changed.\n\n klad palette art.klad --new-variant blue (a variant, shown at once)\n klad palette art.klad --recolour team --to '#2a6fdb' (blue's team colour; the base keeps its red)\n klad palette art.klad --variant base (show the base again; --variant blue shows blue)\n klad palette art.klad --rename-variant blue --to navy\n klad palette art.klad --rm-variant navy\n klad export art.klad --sheet all --variants (a sheet for the base and one for each variant, art-blue-sheet.png)\n klad export art.klad --variant blue --scale 8 (one variant, whatever is shown)\n\nAs ops: {\"op\":\"palette\",\"add\":\"#f0c8a0\",\"name\":\"skin\"}, {\"op\":\"palette\",\"rm\":\"skin\"}, {\"op\":\"palette\",\"recolour\":\"skin\",\"to\":\"#e8b796\"}, {\"op\":\"palette\",\"load\":\"pico-8\"}, {\"op\":\"palette\",\"ramp\":\"skin\",\"of\":[\"skin-dark\",\"skin\"]}, {\"op\":\"palette\",\"set\":[{\"color\":\"#1b1b1b\",\"name\":\"ink\"}]}, {\"op\":\"palette\",\"newVariant\":\"blue\"}, {\"op\":\"palette\",\"variant\":\"base\"}, {\"op\":\"palette\",\"rmVariant\":\"blue\"}, {\"op\":\"palette\",\"renameVariant\":\"blue\",\"to\":\"navy\"}")]Palette {bundle: PathBuf,@@ -1816,8 +1816,33 @@ enum Command {help = "Change one colour (a name, a colour, an index or an id) to --to; pixel marks drawn with it change too")]recolour: Option<String>,- #[arg(long, requires = "recolour", help = "The new colour for --recolour")]+ #[arg(long, help = "The new colour for --recolour, or the new name for --rename-variant")]to: Option<String>,+ #[arg(+ long,+ conflicts_with_all = ["add", "rm", "recolour", "load", "ramp"],+ help = "Show a palette variant (base is the palette itself): every pixel mark takes that variant's colours"+ )]+ variant: Option<String>,+ #[arg(+ long,+ conflicts_with_all = ["add", "rm", "recolour", "load", "ramp", "variant"],+ help = "A new palette variant, shown at once; colours changed while it is shown are its own"+ )]+ new_variant: Option<String>,+ #[arg(+ long,+ conflicts_with_all = ["add", "rm", "recolour", "load", "ramp", "variant", "new_variant"],+ help = "Remove a palette variant"+ )]+ rm_variant: Option<String>,+ #[arg(+ long,+ requires = "to",+ conflicts_with_all = ["add", "rm", "recolour", "load", "ramp", "variant", "new_variant", "rm_variant"],+ help = "Rename a palette variant to --to"+ )]+ rename_variant: Option<String>,#[arg(long,conflicts_with_all = ["add", "rm", "recolour"],@@ -1949,6 +1974,18 @@ enum Command {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,+ conflicts_with_all = ["variants", "godot_scene", "godot_rig"],+ help = "Export in this palette variant (base is the palette itself), whatever the drawing shows now; the file names end in the variant's name"+ )]+ variant: Option<String>,+ #[arg(+ long,+ conflicts_with_all = ["godot_scene", "godot_rig"],+ help = "Export once for every palette variant: the base under the usual name, each variant with its name added (art-blue.png)"+ )]+ variants: bool,#[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")]@@ -3944,8 +3981,31 @@ fn run() -> Result<()> {base,steps,of,+ variant,+ new_variant,+ rm_variant,+ rename_variant,flags,} => {+ if to.is_some() && recolour.is_none() && rename_variant.is_none() {+ return Err(anyhow!(+ "--to goes with --recolour (a colour) or --rename-variant (a name)"+ ));+ }+ let of_variants = match (variant, new_variant, rm_variant, rename_variant) {+ (Some(name), ..) => Some(PaletteEdit::Variant { name }),+ (_, Some(name), ..) => Some(PaletteEdit::NewVariant { name }),+ (_, _, Some(name), _) => Some(PaletteEdit::RemoveVariant { name }),+ (_, _, _, Some(name)) => Some(PaletteEdit::RenameVariant {+ name,+ to: to.clone().unwrap_or_default(),+ }),+ _ => None,+ };+ if let Some(edit) = of_variants {+ agent::edit(&bundle, &[Op::Palette(edit)], &output(&flags, 0))?;+ return Ok(());+ }let edit = match (add, rm, recolour, load, ramp) {(Some(color), ..) => Some(PaletteEdit::Add {color,@@ -4020,6 +4080,8 @@ fn run() -> Result<()> {godot_rig,padding,max,+ variant,+ variants,out,} => {let scenes = godot_scene.is_some() || godot_rig.is_some();@@ -4033,32 +4095,51 @@ fn run() -> Result<()> {.iter().for_each(|f| println!("{}", f.display()));}- let look = sprites::Look {- layer: layer.clone(),- scale,- depth,- background,- };let packing = sprites::Packing { padding, max };- match (sheet, frames, godot) {- _ if gif.is_some() => sprites::gif(&bundle, gif.as_deref().unwrap_or("all"), &look, dither, 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)?,- _ if scenes => {}- _ => export::run(- &bundle,- export::Export {- layer,- frame,- scale,- depth,- background,- references,- out,- },- )?,- }+ let names: Vec<Option<String>> = match variants {+ true => Bundle::open(&bundle)?+ .doc+ .variant_names()+ .into_iter()+ .map(|name| Some(name.to_string()))+ .collect(),+ false => vec![variant],+ };+ let several = names.len() > 1;+ names.into_iter().try_for_each(|variant| {+ let tag = layers::variant_tag(variant.as_deref());+ let out = match (&out, several && !tag.is_empty() && godot.is_none()) {+ (Some(given), true) => Some(sprites::tagged(given, &tag)),+ _ => out.clone(),+ };+ let look = sprites::Look {+ layer: layer.clone(),+ scale,+ depth,+ background,+ variant: variant.clone(),+ };+ match (&sheet, &frames, &godot) {+ _ if gif.is_some() => sprites::gif(&bundle, gif.as_deref().unwrap_or("all"), &look, dither, out),+ (Some(spec), _, _) => sprites::sheet(&bundle, spec, &look, &packing, out),+ (_, Some(spec), _) => sprites::frames(&bundle, spec, &look, out),+ (_, _, Some(dir)) => sprites::godot(&bundle, dir.clone().or(out), store, &look, &packing),+ _ if scenes => Ok(()),+ _ => export::run(+ &bundle,+ export::Export {+ layer: layer.clone(),+ frame,+ scale,+ depth,+ background,+ references,+ variant,+ out,+ },+ ),+ }+ })?;}Command::Brushes {bundle,@@ -4810,6 +4891,10 @@ fn palette(path: &Path, as_json: bool) -> Result<()> {if palette.is_empty() {println!("the palette is empty: klad palette <bundle> --add '#rrggbb' --name <name>");}+ let doc = &bundle.doc;+ if !doc.variants.is_empty() {+ println!("showing {}", doc.shown_variant());+ }palette.iter().enumerate().for_each(|(i, s)| {let ramp = match s.ramp.is_empty() {true => String::new(),@@ -4820,6 +4905,24 @@ fn palette(path: &Path, as_json: bool) -> Result<()> {format!("{i:<3} {:<10} {:<8} {}{ramp}", s.color, s.id, s.name).trim_end());});+ doc.variants.sets.iter().for_each(|variant| {+ let own: Vec<String> = palette+ .iter()+ .filter_map(|s| variant.colors.get(&s.id).map(|colour| (s, colour)))+ .map(|(s, colour)| match s.name.is_empty() {+ true => format!("{} {colour}", s.id),+ false => format!("{} {colour}", s.name),+ })+ .collect();+ println!(+ "variant {}: {}",+ variant.name,+ match own.is_empty() {+ true => "the base colours".to_string(),+ false => own.join(", "),+ }+ );+ });Ok(())}diff --git a/crates/cli/src/sprites.rs b/crates/cli/src/sprites.rsindex 1dc874e..0f5576f 100644--- a/crates/cli/src/sprites.rs+++ b/crates/cli/src/sprites.rs@@ -18,6 +18,26 @@ pub struct Look {pub scale: f32,pub depth: u8,pub background: bool,+ pub variant: Option<String>,+}++pub fn tagged(path: &Path, tag: &str) -> PathBuf {+ let stem = path+ .file_stem()+ .map_or(String::new(), |s| s.to_string_lossy().to_string());+ let name = match path.extension() {+ Some(ext) => format!("{stem}{tag}.{}", ext.to_string_lossy()),+ None => format!("{stem}{tag}"),+ };+ path.with_file_name(name)+}++fn stem_for(bundle: &Bundle, look: &Look) -> String {+ format!(+ "{}{}",+ bundle_stem(bundle),+ crate::layers::variant_tag(look.variant.as_deref())+ )}pub struct Packing {@@ -88,6 +108,7 @@ pub fn pictures(bundle: &Bundle, animations: Vec<Animation>, look: &Look) -> Resreferences: false,detail: detail_of(doc, look.scale),};+ let dress = crate::layers::dress_of(doc, look.variant.as_deref())?;let frames: BTreeSet<u32> = animations.iter().flat_map(|a| a.from..=a.to).collect();let mut firsts: BTreeMap<Vec<String>, u32> = BTreeMap::new();let first_of: BTreeMap<u32, u32> = frames@@ -108,7 +129,12 @@ pub fn pictures(bundle: &Bundle, animations: Vec<Animation>, look: &Look) -> Res.collect::<BTreeSet<_>>().into_iter().collect();- let rasters = load_cels_at(bundle, &brushes, &needed, options.detail)?;+ let rasters = crate::layers::dressed(+ bundle,+ &brushes,+ load_cels_at(bundle, &brushes, &needed, options.detail)?,+ &dress,+ )?;let done = batch.par_iter().map(|(frame, _)| {@@ -262,7 +288,7 @@ pub fn sheet(path: &Path, spec: &str, look: &Look, packing: &Packing, out: Optiocheck_look(look)?;let bundle = Bundle::open(path)?;let animations = sprites::animations(&bundle.doc, spec)?;- let stem = bundle_stem(&bundle);+ let stem = stem_for(&bundle, look);let name = match out {Some(out) => Name {dir: out.parent().map_or(PathBuf::from("."), Path::to_path_buf),@@ -321,7 +347,7 @@ pub fn frames(path: &Path, spec: &str, look: &Look, out: Option<PathBuf>) -> Rescheck_look(look)?;let bundle = Bundle::open(path)?;let animations = sprites::animations(&bundle.doc, spec)?;- let stem = bundle_stem(&bundle);+ let stem = stem_for(&bundle, look);let prefix = match spec {"all" => stem.clone(),other => file_safe(other),@@ -381,13 +407,14 @@ pub fn gif(path: &Path, spec: &str, look: &Look, dither: bool, out: Option<PathBlet 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,+ variant: look.variant.clone(),};+ let stem = stem_for(&bundle, &look);let pics = pictures(&bundle, animations, &look)?;let (sw, sh) = pics.source;let full: Vec<Vec<u8>> = pics@@ -505,7 +532,7 @@ pub fn godot(path: &Path, dir: Option<PathBuf>, store: bool, look: &Look, packin}let doc = &bundle.doc;let animations = sprites::animations(doc, "all")?;- let stem = file_safe(&bundle_stem(&bundle));+ let stem = file_safe(&stem_for(&bundle, look));let name = Name {dir: target.clone(),stem: stem.clone(),@@ -546,7 +573,7 @@ pub fn godot(path: &Path, dir: Option<PathBuf>, store: bool, look: &Look, packin.ok_or_else(|| anyhow!("nothing to export"))?;let scene_text = sprites::scene(&Scene {uid: &scene_uid,- node: &sprites::node_name(&bundle_stem(&bundle)),+ node: &sprites::node_name(&stem_for(&bundle, look)),frames_path: &file_name(&tres),frames_uid: &frames_uid,animation: &first,@@ -689,6 +716,7 @@ func _init():scale,depth: 8,background: false,+ variant: None,}}diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rsindex 5440069..af18845 100644--- a/crates/cli/tests/binary.rs+++ b/crates/cli/tests/binary.rs@@ -1267,6 +1267,146 @@ fn a_pixel_drawing_exports_sharp_at_whole_number_scales_as_png_gif_sheet_and_godstd::fs::remove_dir_all(&dir).unwrap();}+#[test]+fn palette_variants_are_made_shown_and_exported_one_by_one() {+ let dir = std::env::temp_dir().join(format!("draw-binary-variants-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ let bundle = dir.join("team.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", "8x8", "--frames", "2", "--fps", "8"]);+ draw(&["palette", path, "--add", "#22223b", "--name", "ink"]);+ draw(&["palette", path, "--add", "#c0392b", "--name", "team"]);+ draw(&["pixel", path, "l1", "--color", "ink", "--rect", "1,1,6,6"]);+ draw(&["pixel", path, "l1", "--color", "team", "--rect", "2,2,4,4", "--filled"]);+ let row = |at: usize| -> String {+ draw(&["pixels", path, "l1", "--plain"])+ .lines()+ .skip_while(|line| !line.is_empty())+ .skip(1)+ .nth(at)+ .unwrap()+ .to_string()+ };+ let before = row(3);++ draw(&["palette", path, "--new-variant", "blue"]);+ draw(&["palette", path, "--recolour", "team", "--to", "#2a6fdb"]);+ let listed = draw(&["palette", path]);+ assert!(listed.starts_with("showing blue\n"), "{listed}");+ assert!(+ listed.contains("#2a6fdb") && listed.contains("variant blue: team #2a6fdb"),+ "{listed}"+ );+ assert_eq!(row(3), before, "the pixels are the same pixels, in another colour");+ draw(&["palette", path, "--variant", "base"]);+ let listed = draw(&["palette", path]);+ assert!(+ listed.starts_with("showing base\n") && listed.contains("#c0392b"),+ "{listed}"+ );+ assert!(refused(&["palette", path, "--variant", "pink"]).contains("base, blue"));+ assert!(refused(&["palette", path, "--to", "navy"]).contains("--rename-variant"));++ let pixel = |file: &std::path::Path| -> Vec<u8> { std::fs::read(file).unwrap() };+ let named: Vec<String> = draw(&["export", path, "--variants"])+ .lines()+ .map(String::from)+ .collect();+ let names: Vec<String> = named+ .iter()+ .map(|p| {+ std::path::Path::new(p)+ .file_name()+ .unwrap()+ .to_string_lossy()+ .to_string()+ })+ .collect();+ assert_eq!(names, ["team-f0.png", "team-blue-f0.png"]);+ assert_ne!(+ pixel(std::path::Path::new(&named[0])),+ pixel(std::path::Path::new(&named[1]))+ );+ let alone = dir.join("alone.png");+ draw(&["export", path, "--variant", "blue", "-o", alone.to_str().unwrap()]);+ assert_eq!(+ pixel(&alone),+ pixel(std::path::Path::new(&named[1])),+ "one variant by name, while the base is shown"+ );+ draw(&["palette", path, "--variant", "blue"]);+ let shown = dir.join("shown.png");+ draw(&["export", path, "-o", shown.to_str().unwrap()]);+ assert_eq!(+ pixel(&shown),+ pixel(&alone),+ "the same picture as showing the variant and exporting"+ );+ let base = dir.join("base.png");+ draw(&["export", path, "--variant", "base", "-o", base.to_str().unwrap()]);+ assert_eq!(+ pixel(&base),+ pixel(std::path::Path::new(&named[0])),+ "and the base while blue is shown"+ );++ let sheet = dir.join("out").join("sheet.png");+ std::fs::create_dir_all(sheet.parent().unwrap()).unwrap();+ let sheets = draw(&[+ "export",+ path,+ "--sheet",+ "all",+ "--variants",+ "-o",+ sheet.to_str().unwrap(),+ ]);+ assert!(+ sheets.contains("sheet.png") && sheets.contains("sheet-blue.png"),+ "{sheets}"+ );+ assert!(dir.join("out").join("sheet-blue.json").exists());+ let gifs = draw(&["export", path, "--gif", "--variants", "--scale", "2"]);+ assert!(+ gifs.contains("[email protected]") && gifs.contains("[email protected]"),+ "{gifs}"+ );+ let table = |file: &str| std::fs::read(file.trim()).unwrap()[13..19].to_vec();+ let both: Vec<Vec<u8>> = gifs.lines().map(table).collect();+ assert_eq!(both[0], [0x22, 0x22, 0x3b, 0xc0, 0x39, 0x2b]);+ assert_eq!(both[1], [0x22, 0x22, 0x3b, 0x2a, 0x6f, 0xdb]);+ let game = dir.join("game");+ let godot = draw(&["export", path, "--godot", game.to_str().unwrap(), "--variants"]);+ assert!(+ godot.contains("team.tscn") && godot.contains("team-blue.tscn") && godot.contains("team-blue.png"),+ "{godot}"+ );++ draw(&["palette", path, "--rename-variant", "blue", "--to", "navy"]);+ assert!(draw(&["palette", path]).contains("variant navy: team #2a6fdb"));+ draw(&["palette", path, "--rm-variant", "navy"]);+ let listed = draw(&["palette", path]);+ assert!(!listed.contains("showing") && listed.contains("#c0392b"), "{listed}");+ assert!(refused(&["export", path, "--variant", "navy"]).contains("no palette variant"));+ 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/core/src/bundle.rs b/crates/core/src/bundle.rsindex 96f1f77..b8ac1d8 100644--- a/crates/core/src/bundle.rs+++ b/crates/core/src/bundle.rs@@ -1775,6 +1775,148 @@ mod tests {fs::remove_dir_all(&dir).unwrap();}+ #[test]+ fn palette_variants_swap_colours_keep_their_own_edits_and_leave_the_base_alone() {+ use crate::ops::parse_lines;+ let dir = scratch("variants");+ let mut bundle = Bundle::blank(+ &dir,+ &Blank {+ width: 8,+ height: 8,+ pixel: true,+ ..Blank::default()+ },+ "cli",+ )+ .unwrap();+ let layer = bundle.doc.layers[0].id.clone();+ let cel = bundle.doc.layers[0].cels()[0].id.clone();+ let run = |bundle: &mut Bundle, lines: &str| bundle.apply(&parse_lines(lines).unwrap()).unwrap();+ let fails = |bundle: &mut Bundle, line: &str| -> String {+ format!("{:#}", bundle.apply(&parse_lines(line).unwrap()).unwrap_err())+ };+ run(+ &mut bundle,+ &format!(+ "{}\n{}\n{}\n{}\n{}",+ r##"{"op":"palette","add":"#c0392b","name":"team"}"##,+ r##"{"op":"palette","add":"#2b2d42","name":"ink"}"##,+ r##"{"op":"palette","add":"#f0c8a0","name":"skin"}"##,+ format_args!(r##"{{"op":"pixel","layer":"{layer}","color":"team","cells":[[1,1],[2,1]]}}"##),+ format_args!(r##"{{"op":"pixel","layer":"{layer}","color":"ink","cells":[[3,3]]}}"##),+ ),+ );+ let shown = |bundle: &Bundle| -> Vec<String> {+ crate::stroke::fills_of(&bundle.read_marks(&layer, &cel).unwrap())+ .map(|f| crate::color::to_hex(f.color()))+ .collect()+ };+ let palette = |bundle: &Bundle| -> Vec<String> { bundle.doc.palette.iter().map(|s| s.color.clone()).collect() };+ let team = bundle.doc.palette[0].id.clone();+ assert!(bundle.doc.variants.is_empty() && bundle.doc.shown_variant() == "base");++ run(&mut bundle, r##"{"op":"palette","newVariant":"blue"}"##);+ assert_eq!(bundle.doc.shown_variant(), "blue", "a new variant is shown at once");+ assert!(+ bundle.doc.palette.iter().all(|s| !s.id.is_empty()),+ "every colour has an id now"+ );+ assert_eq!(shown(&bundle), ["#c0392b", "#2b2d42"], "it starts as what was shown");+ run(&mut bundle, r##"{"op":"palette","recolour":"team","to":"#2a6fdb"}"##);+ assert_eq!(shown(&bundle), ["#2a6fdb", "#2b2d42"]);+ assert_eq!(+ bundle.doc.variants.sets[0].colors.get(&team).map(String::as_str),+ Some("#2a6fdb")+ );+ assert_eq!(bundle.doc.variants.base.get(&team).map(String::as_str), Some("#c0392b"));++ run(&mut bundle, r##"{"op":"palette","variant":"base"}"##);+ assert_eq!(shown(&bundle), ["#c0392b", "#2b2d42"], "the base kept its colour");+ assert_eq!(palette(&bundle)[0], "#c0392b");+ assert!(bundle.doc.variants.base.is_empty());+ run(&mut bundle, r##"{"op":"palette","recolour":"ink","to":"#101020"}"##);+ run(&mut bundle, r##"{"op":"palette","recolour":"team","to":"#d0402b"}"##);+ run(&mut bundle, r##"{"op":"palette","variant":"Blue"}"##);+ assert_eq!(+ shown(&bundle),+ ["#2a6fdb", "#101020"],+ "a variant follows the base where it has no colour of its own, and keeps the ones it has"+ );+ assert_eq!(bundle.doc.variants.base.get(&team).map(String::as_str), Some("#d0402b"));++ run(&mut bundle, r##"{"op":"palette","newVariant":"green"}"##);+ run(&mut bundle, r##"{"op":"palette","recolour":"team","to":"#3a9d5d"}"##);+ assert_eq!(bundle.doc.variant_names(), ["base", "blue", "green"]);+ let colour_of = |bundle: &Bundle, name: &str| -> String {+ bundle+ .doc+ .variant_colours(name)+ .unwrap()+ .into_iter()+ .find(|(id, _)| *id == team)+ .unwrap()+ .1+ };+ assert_eq!(+ (+ colour_of(&bundle, "base"),+ colour_of(&bundle, "blue"),+ colour_of(&bundle, "green")+ ),+ ("#d0402b".to_string(), "#2a6fdb".to_string(), "#3a9d5d".to_string())+ );+ let dress = bundle.doc.dress("blue").unwrap();+ assert_eq!(dress.len(), 1, "only the colours that differ from what is shown");+ assert!(dress.contains_key(&team));+ assert!(bundle.doc.dress("green").unwrap().is_empty());++ run(&mut bundle, r##"{"op":"palette","recolour":"team","to":"#d0402b"}"##);+ assert!(+ bundle.doc.variants.sets[1].colors.is_empty() && bundle.doc.variants.base.is_empty(),+ "set back to the base colour, it is no longer the variant's own"+ );+ run(&mut bundle, r##"{"op":"palette","recolour":"team","to":"#3a9d5d"}"##);+ crate::history::step(&mut bundle, crate::history::Stack::Undo).unwrap();+ assert_eq!(shown(&bundle)[0], "#d0402b", "undo takes the variant's colour back");+ assert!(bundle.doc.variants.sets[1].colors.is_empty());+ crate::history::step(&mut bundle, crate::history::Stack::Redo).unwrap();++ run(+ &mut bundle,+ r##"{"op":"palette","renameVariant":"green","to":"forest"}"##,+ );+ assert_eq!(bundle.doc.shown_variant(), "forest");+ assert!(+ fails(+ &mut bundle,+ r##"{"op":"palette","renameVariant":"forest","to":"blue"}"##+ )+ .contains("already has")+ );+ assert!(fails(&mut bundle, r##"{"op":"palette","newVariant":"Base"}"##).contains("other than base"));+ assert!(fails(&mut bundle, r##"{"op":"palette","variant":"pink"}"##).contains("base, blue, forest"));+ assert!(fails(&mut bundle, r##"{"op":"palette","rmVariant":"base"}"##).contains("cannot be removed"));++ run(&mut bundle, r##"{"op":"palette","rm":"team"}"##);+ assert!(+ bundle.doc.variants.sets.iter().all(|v| v.colors.is_empty()) && bundle.doc.variants.base.is_empty(),+ "a removed colour leaves the variants too"+ );+ run(&mut bundle, r##"{"op":"palette","recolour":"skin","to":"#ffe0c0"}"##);+ run(&mut bundle, r##"{"op":"palette","rmVariant":"forest"}"##);+ assert_eq!(+ bundle.doc.shown_variant(),+ "base",+ "removing the shown variant shows the base"+ );+ assert_eq!(palette(&bundle)[1], "#f0c8a0", "with the base's colours");+ let reopened = Bundle::open(&dir).unwrap();+ assert_eq!(reopened.doc.variants, bundle.doc.variants);+ assert_eq!(reopened.doc.variant_names(), ["base", "blue"]);+ fs::remove_dir_all(&dir).unwrap();+ }+#[test]fn a_swatch_change_recolours_the_marks_bound_to_it_and_ramps_and_loads_shape_the_palette() {use crate::ops::parse_lines;diff --git a/crates/core/src/doc.rs b/crates/core/src/doc.rsindex 301fd63..9542271 100644--- a/crates/core/src/doc.rs+++ b/crates/core/src/doc.rs@@ -21,6 +21,8 @@ pub struct Document {pub timeline: Timeline,#[serde(default, skip_serializing_if = "Vec::is_empty")]pub palette: Vec<Swatch>,+ #[serde(default, skip_serializing_if = "Variants::is_empty")]+ pub variants: Variants,pub layers: Vec<Layer>,#[serde(default, skip_serializing_if = "Exports::is_empty")]pub export: Exports,@@ -38,6 +40,7 @@ impl PartialEq for Document {&& self.canvas == other.canvas&& self.timeline == other.timeline&& self.palette == other.palette+ && self.variants == other.variants&& self.layers == other.layers&& self.export == other.export&& self.atmosphere == other.atmosphere@@ -84,6 +87,45 @@ pub struct Swatch {pub ramp: String,}+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct Variant {+ pub name: String,+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]+ pub colors: BTreeMap<String, String>,+}++#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct Variants {+ #[serde(default, skip_serializing_if = "String::is_empty")]+ pub shown: String,+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]+ pub base: BTreeMap<String, String>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub sets: Vec<Variant>,+}++pub const BASE_VARIANT: &str = "base";++impl Variants {+ pub fn is_empty(&self) -> bool {+ self.sets.is_empty()+ }++ pub fn key(name: &str) -> &str {+ match name.trim() {+ n if n.eq_ignore_ascii_case(BASE_VARIANT) => "",+ n => n,+ }+ }++ pub fn find(&self, name: &str) -> Option<usize> {+ let key = Self::key(name);+ self.sets.iter().position(|v| v.name.eq_ignore_ascii_case(key))+ }+}+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]pub struct Timeline {pub fps: u32,@@ -1060,6 +1102,7 @@ impl Document {},timeline: Timeline::default(),palette: Vec::new(),+ variants: Variants::default(),layers: Vec::new(),export: Exports::default(),atmosphere: None,@@ -1272,6 +1315,71 @@ impl Document {self.palette.iter().find(|s| !s.id.is_empty() && s.id == id)}+ pub fn bind_all(&mut self) {+ let mut taken: BTreeSet<String> = self.palette.iter().map(|s| s.id.clone()).collect();+ (0..self.palette.len()).for_each(|at| {+ if self.palette[at].id.is_empty() {+ self.palette[at].id = self.alloc_id_in('p', &mut taken);+ }+ });+ }++ pub fn shown_variant(&self) -> &str {+ match self.variants.shown.is_empty() {+ true => BASE_VARIANT,+ false => &self.variants.shown,+ }+ }++ pub fn variant_names(&self) -> Vec<&str> {+ std::iter::once(BASE_VARIANT)+ .chain(self.variants.sets.iter().map(|v| v.name.as_str()))+ .collect()+ }++ pub fn base_colour<'a>(&'a self, swatch: &'a Swatch) -> &'a str {+ self.variants.base.get(&swatch.id).map_or(&swatch.color, String::as_str)+ }++ pub fn variant_colours(&self, name: &str) -> Result<Vec<(String, String)>> {+ let set = match Variants::key(name) {+ "" => None,+ _ => Some(+ self.variants+ .find(name)+ .map(|at| &self.variants.sets[at])+ .ok_or_else(|| {+ anyhow!(+ "the drawing has no palette variant {name:?}: it has {}",+ self.variant_names().join(", ")+ )+ })?,+ ),+ };+ Ok(self+ .palette+ .iter()+ .filter(|s| !s.id.is_empty())+ .map(|s| {+ let colour = set+ .and_then(|v| v.colors.get(&s.id))+ .map_or(self.base_colour(s), String::as_str);+ (s.id.clone(), colour.to_string())+ })+ .collect())+ }++ pub fn dress(&self, name: &str) -> Result<BTreeMap<String, [u16; 4]>> {+ self.variant_colours(name)?+ .into_iter()+ .filter(|(id, colour)| {+ self.entry(id)+ .is_some_and(|now| !now.color.eq_ignore_ascii_case(colour))+ })+ .map(|(id, colour)| Ok((id, crate::color::to_u16(parse_hex(&colour)?))))+ .collect()+ }+pub fn bind_swatch(&mut self, key: &str) -> Result<(String, String)> {let key = key.trim();let at = match self.swatch(key) {@@ -1370,6 +1478,34 @@ impl Document {}Ok(())})?;+ let sets = &self.variants;+ let mut variant_names = BTreeSet::new();+ sets.sets.iter().try_for_each(|variant| {+ let name = variant.name.trim();+ if name.is_empty() || name != variant.name || Variants::key(name).is_empty() {+ bail!("palette variant {:?} needs a name other than base", variant.name);+ }+ if !variant_names.insert(name.to_ascii_lowercase()) {+ bail!("palette variant {name} is there twice");+ }+ variant.colors.iter().try_for_each(|(id, colour)| {+ parse_hex(colour).with_context(|| format!("palette variant {name}, colour of {id}"))?;+ Ok::<_, anyhow::Error>(())+ })+ })?;+ if !sets.shown.is_empty() && sets.find(&sets.shown).is_none() {+ bail!(+ "the drawing shows palette variant {}, which it does not have",+ sets.shown+ );+ }+ if sets.shown.is_empty() && !sets.base.is_empty() {+ bail!("the base palette is shown, so no base colours should be kept aside");+ }+ sets.base.values().try_for_each(|colour| {+ parse_hex(colour).context("a base colour kept aside for a palette variant")?;+ Ok::<_, anyhow::Error>(())+ })?;let t = &self.timeline;if t.fps == 0 || t.fps > 240 || t.frames == 0 {bail!("timeline needs 1 to 240 fps and at least one frame");diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rsindex 1134c66..1f192e6 100644--- a/crates/core/src/ops.rs+++ b/crates/core/src/ops.rs@@ -280,6 +280,28 @@ pub enum PaletteEdit {name: String,keys: Vec<String>,},+ Variant {+ name: String,+ },+ NewVariant {+ name: String,+ },+ RemoveVariant {+ name: String,+ },+ RenameVariant {+ name: String,+ to: String,+ },+}++impl PaletteEdit {+ pub fn of_variants(&self) -> bool {+ matches!(+ self,+ Self::Variant { .. } | Self::NewVariant { .. } | Self::RemoveVariant { .. } | Self::RenameVariant { .. }+ )+ }}#[derive(Clone, Debug, PartialEq, Deserialize)]@@ -3027,11 +3049,148 @@ fn parse_palette(map: &mut Map<String, Value>) -> Result<PaletteEdit> {};return Ok(PaletteEdit::Ramp { name, keys });}+ if let Some(name) = take_str(map, "variant")? {+ return Ok(PaletteEdit::Variant { name });+ }+ if let Some(name) = take_str(map, "newVariant")? {+ return Ok(PaletteEdit::NewVariant { name });+ }+ if let Some(name) = take_str(map, "rmVariant")? {+ return Ok(PaletteEdit::RemoveVariant { name });+ }+ if let Some(name) = take_str(map, "renameVariant")? {+ let to = take_str(map, "to")?.ok_or_else(|| anyhow!("palette renameVariant needs \"to\": the new name"))?;+ return Ok(PaletteEdit::RenameVariant { name, to });+ }bail!(- "palette needs \"add\" (with \"name\"), \"rm\", \"set\", \"recolour\" (with \"to\"), \"load\" or \"ramp\" (with \"of\")"+ "palette needs \"add\" (with \"name\"), \"rm\", \"set\", \"recolour\" (with \"to\"), \"load\", \"ramp\" (with \"of\"), or for its variants \"variant\" (show one), \"newVariant\", \"rmVariant\" or \"renameVariant\" (with \"to\")")}+fn variant_name(doc: &Document, name: &str) -> Result<String> {+ let name = name.trim();+ if name.is_empty() || crate::doc::Variants::key(name).is_empty() {+ bail!("a palette variant needs a name other than base, which is the palette itself");+ }+ if name.starts_with('#') || name.contains(['/', '\\']) {+ bail!("a palette variant's name cannot start with # or hold a slash: {name:?}");+ }+ if doc.variants.find(name).is_some() {+ bail!("the drawing already has a palette variant {name}");+ }+ Ok(name.to_string())+}++fn show_variant(doc: &mut Document, name: &str) -> Result<()> {+ let colours = doc.variant_colours(name)?;+ let set = doc.variants.find(name);+ let base: BTreeMap<String, String> = match set {+ None => BTreeMap::new(),+ Some(at) => doc+ .palette+ .iter()+ .filter(|s| doc.variants.sets[at].colors.contains_key(&s.id))+ .map(|s| (s.id.clone(), doc.base_colour(s).to_string()))+ .collect(),+ };+ colours.into_iter().for_each(|(id, colour)| {+ if let Some(swatch) = doc.palette.iter_mut().find(|s| s.id == id) {+ swatch.color = colour;+ }+ });+ doc.variants.shown = set.map_or(String::new(), |at| doc.variants.sets[at].name.clone());+ doc.variants.base = base;+ Ok(())+}++fn edit_variants(doc: &mut Document, edit: &PaletteEdit) -> Result<()> {+ match edit {+ PaletteEdit::Variant { name } => show_variant(doc, name)?,+ PaletteEdit::NewVariant { name } => {+ let name = variant_name(doc, name)?;+ doc.bind_all();+ let colors = doc+ .variants+ .find(&doc.variants.shown)+ .map(|at| doc.variants.sets[at].colors.clone())+ .unwrap_or_default();+ doc.variants.sets.push(crate::doc::Variant {+ name: name.clone(),+ colors,+ });+ doc.variants.shown = name;+ }+ PaletteEdit::RemoveVariant { name } => {+ let Some(at) = doc.variants.find(name) else {+ doc.variant_colours(name)?;+ bail!("base is the palette itself and cannot be removed");+ };+ if doc.variants.shown == doc.variants.sets[at].name {+ show_variant(doc, crate::doc::BASE_VARIANT)?;+ }+ doc.variants.sets.remove(at);+ }+ PaletteEdit::RenameVariant { name, to } => {+ let Some(at) = doc.variants.find(name) else {+ doc.variant_colours(name)?;+ bail!("base is the palette itself and keeps its name");+ };+ let old = doc.variants.sets[at].name.clone();+ if !old.eq_ignore_ascii_case(to.trim()) {+ variant_name(doc, to)?;+ }+ let to = to.trim().to_string();+ if doc.variants.shown == old {+ doc.variants.shown = to.clone();+ }+ doc.variants.sets[at].name = to;+ }+ _ => {}+ }+ Ok(())+}++fn keep_variant(doc: &mut Document, before: &[Swatch]) {+ if doc.variants.sets.is_empty() {+ return;+ }+ doc.bind_all();+ let live: BTreeSet<String> = doc.palette.iter().map(|s| s.id.clone()).collect();+ doc.variants.base.retain(|id, _| live.contains(id));+ doc.variants+ .sets+ .iter_mut()+ .for_each(|v| v.colors.retain(|id, _| live.contains(id)));+ let Some(at) = doc+ .variants+ .find(&doc.variants.shown)+ .filter(|_| !doc.variants.shown.is_empty())+ else {+ return;+ };+ let changed: Vec<(String, String, String)> = before+ .iter()+ .filter(|old| !old.id.is_empty())+ .filter_map(|old| {+ doc.entry(&old.id)+ .filter(|now| !now.color.eq_ignore_ascii_case(&old.color))+ .map(|now| (old.id.clone(), old.color.clone(), now.color.clone()))+ })+ .collect();+ changed.into_iter().for_each(|(id, old, now)| {+ let base = doc.variants.base.entry(id.clone()).or_insert(old).clone();+ match base.eq_ignore_ascii_case(&now) {+ true => {+ doc.variants.base.remove(&id);+ doc.variants.sets[at].colors.remove(&id);+ }+ false => {+ doc.variants.sets[at].colors.insert(id, now);+ }+ }+ });+}+fn edit_palette(doc: &mut Document, edit: &PaletteEdit) -> Result<()> {match edit {PaletteEdit::Add { color, name, index } => {@@ -3133,6 +3292,7 @@ fn edit_palette(doc: &mut Document, edit: &PaletteEdit) -> Result<()> {rest.splice(at..at, chosen);doc.palette = rest;}+ _ => {}}Ok(())}@@ -4026,7 +4186,13 @@ pub fn apply(doc: &mut Document, op: &Op, out: &mut Applied) -> Result<()> {}Op::Palette(edit) => {let before = doc.palette.clone();- edit_palette(doc, edit)?;+ match edit.of_variants() {+ true => edit_variants(doc, edit)?,+ false => {+ edit_palette(doc, edit)?;+ keep_variant(doc, &before);+ }+ }follow_palette(doc, &before, out)?;if !out.changed.iter().any(|c| c == "palette") {out.changed.push("palette".into());diff --git a/crates/core/src/patch.rs b/crates/core/src/patch.rsindex 1954242..9e90cf9 100644--- a/crates/core/src/patch.rs+++ b/crates/core/src/patch.rs@@ -98,6 +98,7 @@ fn doc_shell(doc: &Document) -> Document {canvas: doc.canvas.clone(),timeline: doc.timeline.clone(),palette: doc.palette.clone(),+ variants: doc.variants.clone(),layers: Vec::new(),export: doc.export.clone(),atmosphere: doc.atmosphere.clone(),diff --git a/docs/DESIGN.md b/docs/DESIGN.mdindex fdd5c3d..4405549 100644--- a/docs/DESIGN.md+++ b/docs/DESIGN.md@@ -1,4 +1,4 @@-_Last updated: 2026-11-12 08:30_+_Last updated: 2026-11-12 11:00_# 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. 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 otherwise, each pixel then taking the nearest entry, or with `--dither` (the export window's dither box) the nearest entry of the colour moved by an 8x8 ordered pattern, offset per channel, as far as the table's entries lie apart on average (`gif::Pattern`, `spacing`); ordered and not error diffusion, so the pattern holds still from frame to frame; it is an option and off by default because flat art is cleaner without it, and it does nothing when nothing was reduced; 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.+- **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 otherwise, each pixel then taking the nearest entry, or with `--dither` (the export window's dither box) the nearest entry of the colour moved by an 8x8 ordered pattern, offset per channel, as far as the table's entries lie apart on average (`gif::Pattern`, `spacing`); ordered and not error diffusion, so the pattern holds still from frame to frame; it is an option and off by default because flat art is cleaner without it, and it does nothing when nothing was reduced; 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. Palette variants (`doc.variants`, S9.12) are named sets of colour overrides by swatch id. The drawing always is in one variant: the palette and the marks hold the shown variant's colours, `variants.base` keeps the base colours that variant overrides, and showing another one is an ordinary palette edit (`PaletteEdit::Variant`, through `follow_palette`), so the editor, the previews, undo and every reader of the file need nothing new and a variant can never be seen half applied. A view-only variant was the alternative; it would have needed a second set of rasters in the editor's compositor and would have left the question of which variant an edit belongs to. Here the rule is simple: a colour changed while a variant is shown is that variant's (`ops::keep_variant` records it, and drops it again when it is set back to the base colour); a variant follows the base wherever it has no colour of its own. Exports of a variant that is not shown do not touch the drawing: `Document::dress(name)` gives the colours that differ from what is shown, and `layers::dressed` replays the pixel drawings that use them with those colours (`klad export --variant`, `--variants`; file names take the variant after the drawing's name). Both paths rest on `Document::variant_colours`. 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 2747f3b..8c8ea25 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -3231,7 +3231,17 @@ The document palette, kept in doc.json. Named colours can be used wherever a colA loaded colour the palette already holds is not added again. A ramp is a row of colours from dark to light, used to shade one material.-As ops: {"op":"palette","add":"#f0c8a0","name":"skin"}, {"op":"palette","rm":"skin"}, {"op":"palette","recolour":"skin","to":"#e8b796"}, {"op":"palette","load":"pico-8"}, {"op":"palette","ramp":"skin","of":["skin-dark","skin"]}, {"op":"palette","set":[{"color":"#1b1b1b","name":"ink"}]}+Palette variants are named sets of other colours for the same palette (a red and a blue team). The drawing shows one at a time; base is the palette itself. A colour changed while a variant is shown belongs to that variant, and the base keeps its own; a variant follows the base for every colour it has not changed.++ klad palette art.klad --new-variant blue (a variant, shown at once)+ klad palette art.klad --recolour team --to '#2a6fdb' (blue's team colour; the base keeps its red)+ klad palette art.klad --variant base (show the base again; --variant blue shows blue)+ klad palette art.klad --rename-variant blue --to navy+ klad palette art.klad --rm-variant navy+ klad export art.klad --sheet all --variants (a sheet for the base and one for each variant, art-blue-sheet.png)+ klad export art.klad --variant blue --scale 8 (one variant, whatever is shown)++As ops: {"op":"palette","add":"#f0c8a0","name":"skin"}, {"op":"palette","rm":"skin"}, {"op":"palette","recolour":"skin","to":"#e8b796"}, {"op":"palette","load":"pico-8"}, {"op":"palette","ramp":"skin","of":["skin-dark","skin"]}, {"op":"palette","set":[{"color":"#1b1b1b","name":"ink"}]}, {"op":"palette","newVariant":"blue"}, {"op":"palette","variant":"base"}, {"op":"palette","rmVariant":"blue"}, {"op":"palette","renameVariant":"blue","to":"navy"}Usage: klad palette [OPTIONS] <BUNDLE>@@ -3253,7 +3263,19 @@ Options:Change one colour (a name, a colour, an index or an id) to --to; pixel marks drawn with it change too--to <TO>- The new colour for --recolour+ The new colour for --recolour, or the new name for --rename-variant++ --variant <VARIANT>+ Show a palette variant (base is the palette itself): every pixel mark takes that variant's colours++ --new-variant <NEW_VARIANT>+ A new palette variant, shown at once; colours changed while it is shown are its own++ --rm-variant <RM_VARIANT>+ Remove a palette variant++ --rename-variant <RENAME_VARIANT>+ Rename a palette variant to --to--load <LOAD>Add the colours of a palette that comes with klad (klad palettes), or of a .hex or .gpl file@@ -3409,6 +3431,12 @@ Options:--godot-rig [<GODOT_RIG>]A Godot rig: the rest drawing as Polygon2Ds weighted to a Skeleton2D, and an AnimationPlayer with the poses of every clip, into this folder+ --variant <VARIANT>+ Export in this palette variant (base is the palette itself), whatever the drawing shows now; the file names end in the variant's name++ --variants+ Export once for every palette variant: the base under the usual name, each variant with its name added (art-blue.png)+--padding <PADDING>Sheets: transparent pixels around each picturediff --git a/docs/format.md b/docs/format.mdindex d4feb7c..2573041 100644--- a/docs/format.md+++ b/docs/format.md@@ -1,4 +1,4 @@-_Last updated: 2026-11-12 04:00 (format `klad/7`, stroke files `KLST` version 3, brushes `klad-brush/1`)_+_Last updated: 2026-11-12 11:00 (format `klad/7`, stroke files `KLST` version 3, brushes `klad-brush/1`)_# The klad drawing format@@ -64,12 +64,28 @@ Writers replace files atomically (write a temporary file, then rename), so a rea| `canvas` | object | | `width`, `height` (px), `background` (a colour; none is transparent), `wrap` (bool, default false: the drawing is a tile, and klad brings pixel marks drawn past an edge back in on the other side; it changes nothing about how the drawing renders) || `timeline` | object | 12 fps, 1 frame | see below || `palette` | array | `[]` | swatches: `color`, optional `name` (unique, not starting with `#`), optional `id` (unique; set once a pixel mark uses the swatch), optional `ramp` (the name of the ramp it belongs to) |+| `variants` | object | none | palette variants (below): `sets`, `shown` and `base`; left out when the drawing has none || `layers` | array | | the layers, **bottom first** || `export` | object | `{}` | `godot`: the folder Godot exports go to, relative to the folder holding the bundle || `atmosphere` | object | none | fog by depth: `color` (`#9aa8b8`), `top` (a colour higher up), `density` (0.5), `blur` (1), `desaturate` (0.15) |Strokes and fills store their colour, so for them the palette is a list of names for colours, never a reference: renaming or recolouring a swatch changes nothing drawn. Pixel marks (below) also name the swatch they were drawn with, by its `id`: when klad changes that swatch's colour it rewrites the colour of every pixel mark bound to it, and when the swatch is removed it clears the marks' binding and leaves their colour. A reader draws a pixel mark in the colour the mark stores. A **ramp** is the swatches that share a `ramp` name, in palette order, dark to light.+**Palette variants.** `variants` holds named sets of other colours for the same swatches (a red and a blue team):++```json+"variants": {+ "shown": "blue",+ "base": { "p4": "#c0392b" },+ "sets": [{ "name": "blue", "colors": { "p4": "#2a6fdb" } }]+}+```++- `sets`: each variant has a `name` (unique without regard to case, never `base`) and `colors`, the swatch `id`s it gives a colour of its own. A swatch a variant does not name has the base colour in that variant.+- `shown`: the variant the drawing shows now; left out when it shows the palette itself (called `base`). The palette's `color`s, and the colours stored in pixel marks, are always those of the shown variant, so a reader that knows nothing of variants still draws the picture as it was saved.+- `base`: while a variant is shown, the base colour of every swatch that variant changes, by `id`; empty when the base is shown. Together with `sets` it gives every variant's colours whatever is shown: a swatch's colour in variant V is V's `colors[id]`, else `base[id]`, else the swatch's `color`.+- Once a drawing has variants every swatch has an `id`. A removed swatch leaves `sets` and `base` too.+### The timeline| Key | Type | Default | Meaning |@@ -352,4 +368,4 @@ Drawing a stroke: walk the samples, interpolate between them, stamp the tip ever| `klad/4` | skeletons move to bones layers, and paint layers join one with `rig` (2026-11-08). Older drawings open without their bones, IK, weights links and the `pose` of their cels; the drawings themselves, posed ones too, stay. || `klad/5` | `rev` and `nextId` leave `doc.json`, and new ids carry the tag of the copy that made them, so drawings diff and merge in git (2026-11-09). Older drawings open with their ids unchanged; their counters move to `.cache/copy.json`. || `klad/6` | stroke files version 2: eraser, smudge and blender strokes record the marks they are attached to, and attached erasers erase only those (2026-11-09). Older drawings open unchanged, with nothing attached. |-| `klad/7` | pixel layers: paint layers with `pixel`, pixel marks in stroke files (version 3), and palette swatches with an `id` (2026-11-11). Older drawings open unchanged. |+| `klad/7` | pixel layers: paint layers with `pixel`, pixel marks in stroke files (version 3), palette swatches with an `id` (2026-11-11), and palette `variants` (2026-11-12). Older drawings open unchanged. |diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.mdindex 635dabb..5301200 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.+- Palette variants are other colours for the same sprite (teams, seasons, a hurt flash, day and night): `klad palette sprite.klad --new-variant blue` makes one and shows it, and every colour you change while it is shown (`--recolour team --to '#2a6fdb'`, `--add` with an existing name) is blue's own; the base palette keeps its colours, and a variant follows the base for every colour it has not changed. `--variant base` (or `--variant blue`) shows another one: the pixels stay the same marks, only their colours change, as one undo step. `klad palette sprite.klad` lists what is shown and each variant's own colours; `--rename-variant blue --to navy` and `--rm-variant navy` do what they say. Draw in the base palette and bind the parts that will change to their own palette colours (a `team` colour and its shades, not the same red that is also used for the mouth), or a variant changes more than you meant. Export without switching: `klad export sprite.klad --variant blue` renders that variant whatever is shown (file names get `-blue` after the drawing's name), and `--variants` exports the base and every variant in one go; both work with `--sheet`, `--frames`, `--gif` and `--godot`. Variants recolour pixel marks only: strokes on paint layers and vector shapes store their own colours.- 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).