A drawing app built for agent/human collaboration
Rust
Pixel checks: klad check lists the usual slips of pixel art with their places
Indicode BV6ea6111f661b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 73f2b75..6fa699f 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.+- Pixel checks. `klad check sprite.klad` lists the usual slips of pixel art with their places: single stray pixels, doubled corners in one-pixel lines, jagged lines, banding, and colours that are not in the palette. In the editor **Check the pixels** marks them on the canvas and follows your edits until you turn it off. They are places to look at, not errors.- Tilesets. **View > Tileset: cut into tiles…** cuts a drawing into tiles of one size; the canvas shows the tile lines, and **as a tile set** in the export window writes a Godot TileSet with a tile for every cell that is not empty. From the command line: `klad new ground.klad --pixel 64x48 --tile 16`, `klad canvas --tile 16`, `klad pixels --tile 2,0` and `klad pixel --grid --tile 2,0` to read and draw one tile at a time, and `klad export --tileset <folder>`.- Pictures to pixels. **File > Pixels of a picture…** turns a PNG or JPEG into pixels on the pixel layer you are on, in the palette's colours, or makes a pixel drawing of the layer you are on or of the whole picture at a size you choose. From the command line: `klad pixelize sprite.klad --image ref.png --to l1`, `klad pixelize hero.klad --size 64`, and `klad import ref.png` for a new pixel drawing from a picture. Each pixel becomes part of a mark bound to a palette colour, so the result is edited like any pixel drawing.- Aseprite files in and out. `klad import hero.aseprite` opens an Aseprite file as a klad drawing: its layers and groups, every frame's drawing, linked cels, the palette and its tags as clips. In the editor, **Choose an Aseprite file...** in the start window (or its path pasted there) does the same and opens the drawing it made. `klad export hero.klad --aseprite`, or **Aseprite** in the export window, writes a drawing's pixel layers back to an Aseprite file. klad says what it leaves out each way.diff --git a/crates/app/src/commands.rs b/crates/app/src/commands.rsindex b24a79e..0c8c4af 100644--- a/crates/app/src/commands.rs+++ b/crates/app/src/commands.rs@@ -191,6 +191,7 @@ pub enum Cmd {Refill,FillLike,ShowGaps,+ CheckPixels,ShowParts,ShowArcs,CloseDocument,@@ -523,7 +524,7 @@ use Repeat as R;use Trigger as T;impl Cmd {- pub const ALL: [Cmd; 196] = [+ pub const ALL: [Cmd; 197] = [Cmd::Brush,Cmd::Eraser,Cmd::Fill,@@ -717,6 +718,7 @@ impl Cmd {Cmd::FillLike,Cmd::PaintOver,Cmd::ShowGaps,+ Cmd::CheckPixels,Cmd::ShowParts,Cmd::ShowArcs,Cmd::CompareReference,@@ -2380,6 +2382,15 @@ impl Cmd {R::No,"outline the closed regions no fill covers on the active layer, on this frame or the selected frames",),+ Cmd::CheckPixels => spec(+ "colour.check-pixels",+ "check the pixels",+ icon::SEARCH,+ G::Colour,+ T::None,+ R::No,+ "mark the places to look at on the pixel layer you are on: single pixels, doubled corners, jagged lines, banding and colours off the palette; it stays on and follows your edits until you turn it off",+ ),Cmd::ShowParts => spec("view.parts","show parts",@@ -2673,6 +2684,7 @@ impl Cmd {Cmd::Refill => "Refill drawing",Cmd::FillLike => "Fill like first drawing",Cmd::ShowGaps => "Show gaps",+ Cmd::CheckPixels => "Check the pixels",Cmd::ShowParts => "Show parts",Cmd::ShowArcs => "Show arcs",Cmd::CloseDocument => "Close",@@ -2889,6 +2901,7 @@ pub const MENUS: [Menu; 9] = [Line,Run(Cmd::Refill),Run(Cmd::ShowGaps),+ Run(Cmd::CheckPixels),],},Menu {diff --git a/crates/app/src/editor/checks.rs b/crates/app/src/editor/checks.rsindex dd48677..692483d 100644--- a/crates/app/src/editor/checks.rs+++ b/crates/app/src/editor/checks.rs@@ -12,12 +12,36 @@ use std::path::PathBuf;#[derive(Clone, Debug, Default, PartialEq)]pub(super) struct Checks {pub gaps: Option<Gaps>,+ pub pixels: Option<PixelCheck>,pub arcs: Option<Arcs>,pub parts: bool,pub part: String,pub font: String,}+#[derive(Clone, Debug, PartialEq)]+pub(super) struct PixelCheck {+ pub layer: String,+ pub frame: u32,+ pub rev: u64,+ pub found: Vec<klad_core::pixelcheck::Finding>,+}++pub(super) fn tally(found: &[klad_core::pixelcheck::Finding]) -> String {+ use klad_core::pixelcheck::Kind;+ let parts: Vec<String> = Kind::ALL+ .iter()+ .filter_map(|kind| {+ let count = found.iter().filter(|f| f.kind == *kind).count();+ (count > 0).then(|| format!("{count} {}", kind.name()))+ })+ .collect();+ match parts.is_empty() {+ true => "nothing to look at on this layer".to_string(),+ false => format!("to look at, marked on the canvas: {}", parts.join(", ")),+ }+}+#[derive(Clone, Debug, PartialEq)]pub(super) struct Gaps {pub layer: String,@@ -406,9 +430,72 @@ impl Editor {}}+ fn pixel_findings(&self) -> Option<PixelCheck> {+ let layer = self.scene.active_layer().filter(|l| l.pixel())?;+ let doc = &self.scene.bundle.doc;+ let grid = klad_core::pixel::grid_of(self.scene.active_marks(), doc.canvas.width, doc.canvas.height);+ let colour = |key: &str| match doc.entry(key) {+ Some(swatch) => klad_core::color::parse_hex(&swatch.color).ok(),+ None => klad_core::color::parse_hex(key).ok(),+ };+ Some(PixelCheck {+ layer: layer.id.clone(),+ frame: self.scene.frame,+ rev: doc.rev,+ found: klad_core::pixelcheck::check(&grid, doc.canvas.wrap, &colour),+ })+ }++ pub(super) fn check_pixels(&mut self) {+ if self.checks.pixels.take().is_some() {+ return;+ }+ self.checks.pixels = self.pixel_findings();+ if let Some(check) = &self.checks.pixels {+ let words = tally(&check.found);+ self.say(+ match check.found.is_empty() {+ true => Tone::Done,+ false => Tone::Refused,+ },+ words,+ );+ }+ }++ pub(super) fn follow_pixel_check(&mut self) {+ let stale = self.checks.pixels.as_ref().is_some_and(|check| {+ check.rev != self.scene.bundle.doc.rev+ || check.frame != self.scene.frame+ || self.scene.active_id().as_deref() != Some(check.layer.as_str())+ });+ if stale {+ self.checks.pixels = self.pixel_findings();+ }+ }+pub(super) fn draw_checks(&self, painter: &egui::Painter, place: impl Fn(Vec2) -> Pos2) {let frame = self.scene.frame;let dark = Stroke::new(3.5, Color32::from_black_alpha(150));+ if let Some(check) = &self.checks.pixels {+ use klad_core::pixelcheck::Kind;+ check.found.iter().for_each(|f| {+ let tint = match f.kind {+ Kind::Stray => Color32::from_rgb(255, 196, 0),+ Kind::Corner => Color32::from_rgb(255, 80, 120),+ Kind::Jagged => Color32::from_rgb(255, 120, 40),+ Kind::Banding => Color32::from_rgb(90, 200, 255),+ Kind::OffPalette => Color32::from_rgb(200, 120, 255),+ };+ let r = Rect::from_two_pos(+ place(vec2(f.at[0] as f32, f.at[1] as f32)),+ place(vec2(f.to[0] as f32 + 1.0, f.to[1] as f32 + 1.0)),+ )+ .expand(2.0);+ painter.rect_stroke(r, 1.0, dark, egui::StrokeKind::Middle);+ painter.rect_stroke(r, 1.0, Stroke::new(1.5, tint), egui::StrokeKind::Middle);+ });+ }if let Some(gaps) = &self.checks.gaps {let warn = Color32::from_rgb(255, 80, 120);gaps.framesdiff --git a/crates/app/src/editor/commands.rs b/crates/app/src/editor/commands.rsindex 6adb142..24b065d 100644--- a/crates/app/src/editor/commands.rs+++ b/crates/app/src/editor/commands.rs@@ -194,6 +194,9 @@ impl Editor {}}Cmd::WrapCanvas => editing,+ Cmd::CheckPixels if self.checks.pixels.is_none() && !self.scene.on_grid() => {+ Some("pick a pixel layer first: the check reads pixel art".to_string())+ }Cmd::NewVariant => match self.scene.bundle.doc.all_layers().iter().any(|l| l.pixel()) {true => editing,false => Some(@@ -499,6 +502,7 @@ impl Editor {Cmd::PaintOver => self.windows.paintover,Cmd::CompareReference => self.windows.compare,Cmd::ShowGaps => self.checks.gaps.is_some(),+ Cmd::CheckPixels => self.checks.pixels.is_some(),Cmd::ShowParts => self.checks.parts,Cmd::ShowArcs => self.checks.arcs.is_some(),Cmd::BrushWindow => self.windows.brush,@@ -884,6 +888,7 @@ impl Editor {Cmd::Refill => self.refill()?,Cmd::FillLike => self.fill_like()?,Cmd::ShowGaps => self.show_gaps()?,+ Cmd::CheckPixels => self.check_pixels(),Cmd::ShowParts => self.checks.parts = !self.checks.parts,Cmd::ShowArcs => self.show_arcs()?,Cmd::InstallCommand => self.start_job(install_job()),diff --git a/crates/app/src/editor/panels.rs b/crates/app/src/editor/panels.rsindex c6d51a9..ef437d5 100644--- a/crates/app/src/editor/panels.rs+++ b/crates/app/src/editor/panels.rs@@ -79,6 +79,7 @@ impl Editor {|| self.capturing.is_some();self.check(|e| e.sync());self.tend_jobs();+ self.follow_pixel_check();self.check(|e| e.tab_keys());let window = ctx.content_rect().size();self.settings.layout.clamp(window);diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rsindex 862d1f4..d05d6c5 100644--- a/crates/app/src/editor/ui_tests.rs+++ b/crates/app/src/editor/ui_tests.rs@@ -1809,6 +1809,72 @@ fn a_clicked_palette_colour_is_updated_with_its_pixels_and_ramps_and_palettes_jolet _ = std::fs::remove_dir_all(&path);}+#[test]+fn checking_the_pixels_marks_the_places_and_follows_edits_until_it_is_turned_off() {+ use klad_core::pixelcheck::Kind;+ let path = pixel_sample("check");+ let mut h = harness(editor(&path), vec2(1440.0, 900.0));+ h.run_steps(2);+ assert_eq!(h.state().is_on(Cmd::CheckPixels), Some(false));+ h.state_mut().invoke(Cmd::CheckPixels).unwrap();+ h.run_steps(2);+ let kinds = |h: &Harness<'static, Editor>| -> Vec<(Kind, [u32; 2])> {+ h.state()+ .checks+ .pixels+ .as_ref()+ .map(|check| check.found.iter().map(|f| (f.kind, f.at)).collect())+ .unwrap_or_default()+ };+ assert_eq!(+ kinds(&h),+ [(Kind::Stray, [5, 5])],+ "the red pixel in the ring stands alone"+ );+ let said = h.state().messages.latest().map(|m| m.text.clone()).unwrap_or_default();+ assert!(said.contains("1 stray pixel"), "{said}");+ assert_eq!(h.state().is_on(Cmd::CheckPixels), Some(true));+ let layer = h.state().scene.active_id().unwrap();+ let pixel = |cells: serde_json::Value, colour: &str| {+ klad_core::ops::Op::parse(serde_json::json!({"op":"pixel","layer":layer,"color":colour,"cells":cells})).unwrap()+ };+ h.state_mut()+ .apply(vec![pixel(serde_json::json!([[5, 5]]), "#2b2d42")])+ .unwrap();+ h.run_steps(3);+ assert!(+ kinds(&h).is_empty(),+ "painted over, the finding goes without asking again"+ );+ h.state_mut()+ .apply(vec![pixel(+ serde_json::json!([[12, 10], [13, 10], [13, 11], [14, 11], [14, 12], [15, 12]]),+ "#ef233c",+ )])+ .unwrap();+ h.run_steps(3);+ assert_eq!(+ kinds(&h).iter().filter(|(kind, _)| *kind == Kind::Corner).count(),+ 4,+ "a staircase drawn with doubles is marked at each of its corners: {:?}",+ kinds(&h)+ );+ h.state_mut().invoke(Cmd::CheckPixels).unwrap();+ h.run_steps(2);+ assert!(h.state().checks.pixels.is_none() && h.state().is_on(Cmd::CheckPixels) == Some(false));+ let painting = sample("check-paint");+ let plain = harness(editor(&painting), vec2(1440.0, 900.0));+ assert!(+ plain+ .state()+ .can_run(Cmd::CheckPixels)+ .is_some_and(|why| why.contains("pixel layer")),+ "on a painting the check says what it needs"+ );+ let _ = std::fs::remove_dir_all(&path);+ let _ = std::fs::remove_dir_all(&painting);+}+#[test]fn the_brush_tool_is_a_pixel_pencil_and_eraser_on_a_pixel_layer() {let path = pixel_sample("pencil");diff --git a/crates/cli/src/check.rs b/crates/cli/src/check.rsnew file mode 100644index 0000000..d0647d5--- /dev/null+++ b/crates/cli/src/check.rs@@ -0,0 +1,181 @@+use anyhow::{Result, bail};+use klad_core::bundle::Bundle;+use klad_core::color::{Rgba, parse_hex};+use klad_core::doc::{Document, Layer};+use klad_core::pixelcheck::{Finding, Kind, check};+use serde_json::json;+use std::path::Path;++const SHOWN: usize = 12;++fn colour_of(doc: &Document, key: &str) -> Option<Rgba> {+ match doc.entry(key) {+ Some(swatch) => parse_hex(&swatch.color).ok(),+ None => parse_hex(key).ok(),+ }+}++fn name_of(doc: &Document, key: &str) -> String {+ match doc.entry(key) {+ Some(swatch) if !swatch.name.is_empty() => swatch.name.clone(),+ Some(swatch) => swatch.color.clone(),+ None => key.to_string(),+ }+}++fn spot(finding: &Finding) -> String {+ match finding.at == finding.to {+ true => format!("{},{}", finding.at[0], finding.at[1]),+ false => format!(+ "{},{} to {},{}",+ finding.at[0], finding.at[1], finding.to[0], finding.to[1]+ ),+ }+}++fn words(doc: &Document, finding: &Finding) -> String {+ match finding.beside.as_slice() {+ [a, b] => format!("{}, between {} and {}", finding.note, name_of(doc, a), name_of(doc, b)),+ _ => finding.note.clone(),+ }+}++struct Checked<'a> {+ layer: &'a Layer,+ frame: u32,+ found: Vec<Finding>,+}++fn drawings<'a>(layers: &[&'a Layer], frames: &[u32]) -> Vec<(&'a Layer, u32, String)> {+ layers+ .iter()+ .flat_map(|layer| {+ let mut seen: Vec<String> = Vec::new();+ frames+ .iter()+ .filter_map(|frame| {+ let cel = layer.content_at(*frame)?;+ match seen.contains(&cel.id) {+ true => None,+ false => {+ seen.push(cel.id.clone());+ Some((*layer, *frame, cel.id.clone()))+ }+ }+ })+ .collect::<Vec<_>>()+ })+ .collect()+}++fn within<'a>(layer: &'a Layer, out: &mut Vec<&'a Layer>) {+ out.push(layer);+ layer.children().iter().for_each(|child| within(child, out));+}++pub fn run(path: &Path, layer: Option<&str>, frame: u32, all: bool, as_json: bool) -> Result<()> {+ let bundle = Bundle::open(path)?;+ let doc = &bundle.doc;+ if frame >= doc.timeline.frames {+ bail!("frame {frame} is past the last frame {}", doc.timeline.frames - 1);+ }+ let layers: Vec<&Layer> = match layer {+ Some(key) => {+ let owner = doc.find_layer(key)?;+ let mut inside: Vec<&Layer> = Vec::new();+ within(owner, &mut inside);+ let pixel: Vec<&Layer> = inside.into_iter().filter(|l| l.pixel()).collect();+ if pixel.is_empty() {+ bail!(+ "{} is a {} layer: klad check reads pixel layers",+ owner.name,+ owner.kind_name()+ );+ }+ pixel+ }+ None => doc.all_layers().into_iter().filter(|l| l.pixel()).collect(),+ };+ if layers.is_empty() {+ bail!("this drawing has no pixel layers: klad check reads pixel art");+ }+ let frames: Vec<u32> = match all {+ true => (0..doc.timeline.frames).collect(),+ false => vec![frame],+ };+ let checked: Vec<Checked> = drawings(&layers, &frames)+ .into_iter()+ .map(|(layer, frame, cel)| {+ let marks = bundle.read_marks(&layer.id, &cel)?;+ let grid = klad_core::pixel::grid_of(&marks, doc.canvas.width, doc.canvas.height);+ Ok(Checked {+ layer,+ frame,+ found: check(&grid, doc.canvas.wrap, &|key| colour_of(doc, key)),+ })+ })+ .collect::<Result<_>>()?;+ let total: usize = checked.iter().map(|c| c.found.len()).sum();+ if as_json {+ let findings: Vec<serde_json::Value> = checked+ .iter()+ .flat_map(|c| {+ c.found.iter().map(move |f| {+ json!({+ "layer": c.layer.id,+ "frame": c.frame,+ "kind": f.kind,+ "at": f.at,+ "to": f.to,+ "color": name_of(doc, &f.key),+ "note": words(doc, f),+ })+ })+ })+ .collect();+ println!(+ "{}",+ json!({+ "checked": checked.iter().map(|c| json!({"layer": c.layer.id, "name": c.layer.name, "frame": c.frame})).collect::<Vec<_>>(),+ "findings": findings,+ })+ );+ return Ok(());+ }+ checked.iter().for_each(|c| {+ let head = format!("{} ({}), frame {}", c.layer.name, c.layer.id, c.frame);+ if c.found.is_empty() {+ println!("{head}: nothing to look at");+ return;+ }+ println!("{head}: {} to look at", c.found.len());+ Kind::ALL.iter().for_each(|kind| {+ let of_kind: Vec<&Finding> = c.found.iter().filter(|f| f.kind == *kind).collect();+ of_kind.iter().take(SHOWN).for_each(|f| {+ println!(+ " {:<16} {:<16} {:<12} {}",+ kind.name(),+ spot(f),+ name_of(doc, &f.key),+ words(doc, f)+ );+ });+ if of_kind.len() > SHOWN {+ println!(+ " {:<16} and {} more (--json lists them all)",+ kind.name(),+ of_kind.len() - SHOWN+ );+ }+ });+ });+ if total > 0 {+ println!();+ Kind::ALL+ .iter()+ .filter(|kind| checked.iter().any(|c| c.found.iter().any(|f| f.kind == **kind)))+ .for_each(|kind| println!("{}: {}", kind.name(), kind.advice()));+ println!("These are places to look at, not errors: a single pixel can be an eye.");+ }+ Ok(())+}diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rsindex 2e8dfee..65d57c2 100644--- a/crates/cli/src/main.rs+++ b/crates/cli/src/main.rs@@ -3,6 +3,7 @@ mod arcs;mod aseprite;mod bench;mod brushes;+mod check;mod colour;mod compare;mod demo;@@ -1997,6 +1998,21 @@ enum Command {)]tile: Option<[i64; 2]>,},+ #[command(+ about = "Look over pixel art: stray pixels, doubled corners, jagged lines, banding, colours off the palette",+ long_about = "Look over the pixel layers of a drawing for the usual slips of pixel art, and list each with its place:\n\n stray pixel a single pixel with no neighbour of its colour\n doubled corner an L in a one-pixel line, where the line reads thick (a corner whose arms are both two pixels or longer, as on a box, is left alone)\n jagged line a short run between two longer ones in a one-pixel line, a step that breaks its rhythm\n banding a band one pixel wide, lighter than one side and darker than the other, that follows the edge next to it for four pixels or more\n off the palette pixels in a colour that is not a palette entry\n\n klad check sprite.klad every pixel layer, frame 0\n klad check sprite.klad body --frame 4 one layer (or a group's layers) at a frame\n klad check sprite.klad --all every drawing of every pixel layer\n klad check sprite.klad --json\n\nPlaces are canvas pixels, x,y from the top left, the way klad pixels counts them. These are places to look at, not errors: a single pixel can be an eye, and a band can be a rim light. klad render --focus or klad pixels shows the spot; klad pixel fixes it."+ )]+ Check {+ bundle: PathBuf,+ #[arg(help = "A pixel layer or a group (default: every pixel layer)")]+ layer: Option<String>,+ #[arg(long, default_value_t = 0)]+ frame: u32,+ #[arg(long, conflicts_with = "frame", help = "Every drawing on every frame, each once")]+ all: bool,+ #[arg(long)]+ json: bool,+ },#[command(about = "The palettes that come with klad, to load with klad palette <bundle> --load <name>")]Palettes {#[arg(long)]@@ -4286,6 +4302,13 @@ fn run() -> Result<()> {}}Command::Palettes { json } => palettes(json),+ Command::Check {+ bundle,+ layer,+ frame,+ all,+ json,+ } => check::run(&bundle, layer.as_deref(), frame, all, json)?,Command::Pixels {bundle,layer,diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rsindex 9676ea9..463a37d 100644--- a/crates/cli/tests/binary.rs+++ b/crates/cli/tests/binary.rs@@ -1904,6 +1904,116 @@ fn a_drawing_cut_into_tiles_is_read_drawn_and_exported_tile_by_tile() {std::fs::remove_dir_all(&dir).unwrap();}+#[test]+fn klad_check_lists_the_slips_of_pixel_art_with_their_places() {+ let dir = std::env::temp_dir().join(format!("draw-binary-check-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ let bundle = dir.join("slips.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", "24x16", "--frames", "3"]);+ draw(&["palette", path, "--add", "#1b1b2f", "--name", "dark"]);+ draw(&["palette", path, "--add", "#5a6e9a", "--name", "mid"]);+ draw(&["palette", path, "--add", "#cfd8ea", "--name", "light"]);+ draw(&["palette", path, "--add", "#22223b", "--name", "ink"]);+ draw(&["set", path, "l1", "name=body"]);+ assert!(draw(&["check", path]).contains("body (l1), frame 0: nothing to look at"));+ let grid = dir.join("slips.txt");+ std::fs::write(+ &grid,+ "d = dark\nm = mid\nl = light\ni = ink\n\n\+ dddddd..........i.......\n\+ mmmmmm..................\n\+ llllll..................\n\+ ........................\n\+ iiii....................\n\+ ....i...................\n\+ .....iiii...............\n\+ ........................\n\+ ii......................\n\+ .ii.....................\n\+ ..i.....................\n",+ )+ .unwrap();+ draw(&["pixel", path, "body", "--grid", grid.to_str().unwrap()]);+ draw(&["pixel", path, "body", "--color", "#ff00ff", "--cells", "20,12 21,12"]);+ draw(&["palette", path, "--rm", "#ff00ff"]);+ let listed = draw(&["check", path]);+ assert!(listed.contains("body (l1), frame 0:"), "{listed}");+ let line = |kind: &str| {+ listed+ .lines()+ .find(|l| l.trim_start().starts_with(kind))+ .unwrap_or_else(|| panic!("no {kind} in:\n{listed}"))+ .to_string()+ };+ assert!(+ line("stray pixel").contains("16,0") && line("stray pixel").contains("ink"),+ "{listed}"+ );+ assert!(line("doubled corner").contains("1,8"), "{listed}");+ assert!(+ line("jagged line").contains("4,5") && line("jagged line").contains("a run of 1 between runs of 4 and 4"),+ "{listed}"+ );+ assert!(+ line("banding").contains("0,1 to 5,1")+ && line("banding").contains("mid")+ && line("banding").contains("between dark and light"),+ "{listed}"+ );+ assert!(+ line("off the palette").contains("20,12")+ && line("off the palette").contains("#ff00ff")+ && line("off the palette").contains("2 pixels"),+ "{listed}"+ );+ assert!(listed.contains("not errors"), "{listed}");+ let found: serde_json::Value = serde_json::from_str(&draw(&["check", path, "body", "--json"])).unwrap();+ let kinds: std::collections::BTreeSet<&str> = found["findings"]+ .as_array()+ .unwrap()+ .iter()+ .map(|f| f["kind"].as_str().unwrap())+ .collect();+ assert_eq!(+ kinds.into_iter().collect::<Vec<_>>(),+ ["banding", "corner", "jagged", "off-palette", "stray"]+ );+ assert_eq!(found["checked"][0]["name"], "body");+ draw(&["add", path, "cel", "--in", "l1", "frame=2"]);+ let every = draw(&["check", path, "--all"]);+ assert!(+ every.contains("frame 0:") && every.contains("body (l1), frame 2: nothing to look at"),+ "{every}"+ );+ assert_eq!(+ every.matches("body (l1), frame").count(),+ 2,+ "each drawing once, not each frame: {every}"+ );+ assert!(refused(&["check", path, "--frame", "9"]).contains("past the last frame"));+ let painting = dir.join("painting.klad");+ draw(&["new", painting.to_str().unwrap(), "--width", "64", "--height", "64"]);+ assert!(refused(&["check", painting.to_str().unwrap()]).contains("no pixel layers"));+ 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/lib.rs b/crates/core/src/lib.rsindex 4fdbf54..3cf189a 100644--- a/crates/core/src/lib.rs+++ b/crates/core/src/lib.rs@@ -20,6 +20,7 @@ pub mod patch;pub mod path;pub mod pathedit;pub mod pixel;+pub mod pixelcheck;pub mod repair;pub mod retime;pub mod rig;diff --git a/crates/core/src/pixelcheck.rs b/crates/core/src/pixelcheck.rsnew file mode 100644index 0000000..280d786--- /dev/null+++ b/crates/core/src/pixelcheck.rs@@ -0,0 +1,552 @@+use crate::color::{Rgba, to_oklab};+use crate::pixel::Grid;+use serde::Serialize;+use std::collections::{BTreeMap, BTreeSet};++const ARM: u32 = 2;+const BAND: u32 = 4;+const STEP: u32 = 2;++#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]+#[serde(rename_all = "kebab-case")]+pub enum Kind {+ Stray,+ Corner,+ Jagged,+ Banding,+ OffPalette,+}++impl Kind {+ pub const ALL: [Kind; 5] = [Kind::Stray, Kind::Corner, Kind::Jagged, Kind::Banding, Kind::OffPalette];++ pub fn name(self) -> &'static str {+ match self {+ Kind::Stray => "stray pixel",+ Kind::Corner => "doubled corner",+ Kind::Jagged => "jagged line",+ Kind::Banding => "banding",+ Kind::OffPalette => "off the palette",+ }+ }++ pub fn advice(self) -> &'static str {+ match self {+ Kind::Stray => {+ "a single pixel with no neighbour of its colour: keep it if it is a detail, else join it to a cluster or remove it"+ }+ Kind::Corner => "an L in a one-pixel line, which reads as a thick spot: remove the corner pixel",+ Kind::Jagged => "a short run between longer ones breaks the line's rhythm: even out the run lengths",+ Kind::Banding => {+ "a one-pixel band that follows the edge next to it: break it up, or let the shade form its own shape"+ }+ Kind::OffPalette => {+ "pixels in a colour the palette does not hold: recolour them to a palette colour, or add the colour"+ }+ }+ }+}++#[derive(Clone, Debug, PartialEq, Serialize)]+pub struct Finding {+ pub kind: Kind,+ pub at: [u32; 2],+ pub to: [u32; 2],+ pub key: String,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub beside: Vec<String>,+ pub note: String,+}++type Cell = (i64, i64);++const AROUND: [Cell; 8] = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)];++struct Field<'a> {+ grid: &'a Grid,+ wrap: bool,+}++impl<'a> Field<'a> {+ fn at(&self, (x, y): Cell) -> Option<&'a str> {+ let (w, h) = (self.grid.width as i64, self.grid.height as i64);+ let (x, y) = match self.wrap {+ true => (x.rem_euclid(w.max(1)), y.rem_euclid(h.max(1))),+ false => (x, y),+ };+ match x >= 0 && y >= 0 && x < w && y < h {+ true => self.grid.at(x as u32, y as u32),+ false => None,+ }+ }++ fn is(&self, cell: Cell, key: &str) -> bool {+ self.at(cell) == Some(key)+ }++ fn same(&self, (x, y): Cell, key: &str) -> Vec<Cell> {+ AROUND+ .iter()+ .filter(|(dx, dy)| self.is((x + dx, y + dy), key))+ .copied()+ .collect()+ }++ fn arm(&self, (x, y): Cell, (dx, dy): Cell, key: &str) -> u32 {+ let most = self.grid.width.max(self.grid.height) as i64;+ (1..=most)+ .take_while(|n| self.is((x + dx * n, y + dy * n), key))+ .count() as u32+ }++ fn cells(&self) -> impl Iterator<Item = (Cell, &'a str)> + '_ {+ let (w, h) = (self.grid.width as i64, self.grid.height as i64);+ (0..h)+ .flat_map(move |y| (0..w).map(move |x| (x, y)))+ .filter_map(|cell| self.at(cell).map(|key| (cell, key)))+ }+}++fn place((x, y): Cell) -> [u32; 2] {+ [x.max(0) as u32, y.max(0) as u32]+}++fn strays(field: &Field) -> Vec<Finding> {+ field+ .cells()+ .filter(|(cell, key)| field.same(*cell, key).is_empty())+ .map(|(cell, key)| Finding {+ kind: Kind::Stray,+ at: place(cell),+ to: place(cell),+ key: key.to_string(),+ beside: Vec::new(),+ note: "alone: no neighbour of its colour".into(),+ })+ .collect()+}++fn corners(field: &Field) -> Vec<Finding> {+ const BESIDE: [Cell; 4] = [(0, -1), (1, 0), (0, 1), (-1, 0)];+ field+ .cells()+ .filter(|(cell, key)| {+ let arms: Vec<Cell> = BESIDE+ .iter()+ .filter(|(dx, dy)| field.is((cell.0 + dx, cell.1 + dy), key))+ .copied()+ .collect();+ let [a, b] = arms.as_slice() else {+ return false;+ };+ let square = a.0 * b.0 + a.1 * b.1 == 0;+ let inside = (cell.0 + a.0 + b.0, cell.1 + a.1 + b.1);+ square && !field.is(inside, key) && !(field.arm(*cell, *a, key) >= ARM && field.arm(*cell, *b, key) >= ARM)+ })+ .map(|(cell, key)| Finding {+ kind: Kind::Corner,+ at: place(cell),+ to: place(cell),+ key: key.to_string(),+ beside: Vec::new(),+ note: "an L in a one-pixel line".into(),+ })+ .collect()+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum Lie {+ Across,+ Down,+ Dot,+}++#[derive(Clone, Copy, Debug)]+struct Stretch {+ lie: Lie,+ first: Cell,+ last: Cell,+ length: u32,+}++fn chains(field: &Field, key: &str, cells: &[Cell]) -> Vec<Vec<Cell>> {+ let thin: BTreeSet<Cell> = cells+ .iter()+ .filter(|cell| {+ let same = field.same(**cell, key);+ same.len() <= 2+ })+ .copied()+ .collect();+ let next_of = |cell: Cell, seen: &BTreeSet<Cell>| -> Option<Cell> {+ let mut around: Vec<Cell> = AROUND+ .iter()+ .map(|(dx, dy)| (cell.0 + dx, cell.1 + dy))+ .filter(|c| thin.contains(c) && !seen.contains(c))+ .collect();+ around.sort_by_key(|c| ((c.0 - cell.0).abs() + (c.1 - cell.1).abs(), c.1, c.0));+ around.first().copied()+ };+ let ends: Vec<Cell> = thin+ .iter()+ .filter(|cell| {+ AROUND+ .iter()+ .filter(|(dx, dy)| thin.contains(&(cell.0 + dx, cell.1 + dy)))+ .count()+ <= 1+ })+ .copied()+ .collect();+ let mut seen: BTreeSet<Cell> = BTreeSet::new();+ let mut made = Vec::new();+ ends.iter().chain(thin.iter()).for_each(|start| {+ if seen.contains(start) {+ return;+ }+ let mut chain = vec![*start];+ seen.insert(*start);+ while let Some(next) = next_of(*chain.last().unwrap_or(start), &seen) {+ seen.insert(next);+ chain.push(next);+ }+ made.push(chain);+ });+ made+}++fn stretches(chain: &[Cell]) -> Vec<Stretch> {+ let mut made: Vec<Stretch> = Vec::new();+ chain.iter().for_each(|cell| {+ let joins = made.last().map(|run| {+ let (dx, dy) = (cell.0 - run.last.0, cell.1 - run.last.1);+ match (run.lie, dx.abs(), dy.abs()) {+ (Lie::Dot | Lie::Across, 1, 0) => Some(Lie::Across),+ (Lie::Dot | Lie::Down, 0, 1) => Some(Lie::Down),+ _ => None,+ }+ });+ match (joins, made.last_mut()) {+ (Some(Some(lie)), Some(run)) => {+ run.lie = lie;+ run.last = *cell;+ run.length += 1;+ }+ _ => made.push(Stretch {+ lie: Lie::Dot,+ first: *cell,+ last: *cell,+ length: 1,+ }),+ }+ });+ made+}++fn jagged(field: &Field) -> Vec<Finding> {+ let mut by_key: BTreeMap<&str, Vec<Cell>> = BTreeMap::new();+ field+ .cells()+ .for_each(|(cell, key)| by_key.entry(key).or_default().push(cell));+ by_key+ .iter()+ .flat_map(|(key, cells)| {+ chains(field, key, cells)+ .into_iter()+ .flat_map(|chain| {+ let runs = stretches(&chain);+ runs.windows(3)+ .filter(|w| {+ let (a, b, c) = (w[0], w[1], w[2]);+ let lies = a.lie == c.lie && a.lie != Lie::Dot && (b.lie == a.lie || b.lie == Lie::Dot);+ let along = |run: &Stretch| match a.lie {+ Lie::Down => (run.last.1 - run.first.1).signum(),+ _ => (run.last.0 - run.first.0).signum(),+ };+ let aside = |from: &Stretch, to: &Stretch| match a.lie {+ Lie::Down => (to.first.0 - from.last.0).signum(),+ _ => (to.first.1 - from.last.1).signum(),+ };+ let onward = along(&a) == along(&c) && (b.length == 1 || along(&b) == along(&a));+ let one_way = aside(&a, &b) == aside(&b, &c) && aside(&a, &b) != 0;+ lies && onward && one_way && b.length + STEP <= a.length && b.length + STEP <= c.length+ })+ .map(|w| Finding {+ kind: Kind::Jagged,+ at: place((w[1].first.0.min(w[1].last.0), w[1].first.1.min(w[1].last.1))),+ to: place((w[1].first.0.max(w[1].last.0), w[1].first.1.max(w[1].last.1))),+ key: key.to_string(),+ beside: Vec::new(),+ note: format!(+ "a run of {} between runs of {} and {}",+ w[1].length, w[0].length, w[2].length+ ),+ })+ .collect::<Vec<_>>()+ })+ .collect::<Vec<_>>()+ })+ .collect()+}++fn banding(field: &Field, colour: &dyn Fn(&str) -> Option<Rgba>) -> Vec<Finding> {+ let light = |key: &str| colour(key).map(|c| to_oklab(c)[0]);+ let between = |a: &str, b: &str, c: &str| -> bool {+ match (light(a), light(b), light(c)) {+ (Some(la), Some(lb), Some(lc)) => (la < lb && lb < lc) || (la > lb && lb > lc),+ _ => false,+ }+ };+ let (w, h) = (field.grid.width as i64, field.grid.height as i64);+ let sides = |cell: Cell, down: bool| -> Option<(&str, &str, &str)> {+ let (before, after) = match down {+ true => ((cell.0 - 1, cell.1), (cell.0 + 1, cell.1)),+ false => ((cell.0, cell.1 - 1), (cell.0, cell.1 + 1)),+ };+ let (a, b, c) = (field.at(before)?, field.at(cell)?, field.at(after)?);+ (a != b && b != c && a != c).then_some((a, b, c))+ };+ let lines = |down: bool| -> Vec<Finding> {+ let (outer, inner) = match down {+ true => (w, h),+ false => (h, w),+ };+ (0..outer)+ .flat_map(|fixed| {+ let cell = move |moving: i64| match down {+ true => (fixed, moving),+ false => (moving, fixed),+ };+ let mut found: Vec<Finding> = Vec::new();+ let mut start = 0;+ while start < inner {+ let Some(first) = sides(cell(start), down) else {+ start += 1;+ continue;+ };+ let length = (start..inner)+ .take_while(|at| sides(cell(*at), down) == Some(first))+ .count() as i64;+ if length as u32 >= BAND && between(first.0, first.1, first.2) {+ found.push(Finding {+ kind: Kind::Banding,+ at: place(cell(start)),+ to: place(cell(start + length - 1)),+ key: first.1.to_string(),+ beside: vec![first.0.to_string(), first.2.to_string()],+ note: format!("one pixel wide for {length} pixels"),+ });+ }+ start += length;+ }+ found+ })+ .collect()+ };+ lines(false).into_iter().chain(lines(true)).collect()+}++fn off_palette(field: &Field) -> Vec<Finding> {+ let mut seen: BTreeMap<&str, (Cell, usize)> = BTreeMap::new();+ field+ .cells()+ .filter(|(_, key)| key.starts_with('#'))+ .for_each(|(cell, key)| seen.entry(key).or_insert((cell, 0)).1 += 1);+ seen.into_iter()+ .map(|(key, (first, count))| Finding {+ kind: Kind::OffPalette,+ at: place(first),+ to: place(first),+ key: key.to_string(),+ beside: Vec::new(),+ note: match count {+ 1 => "1 pixel".to_string(),+ n => format!("{n} pixels, the first here"),+ },+ })+ .collect()+}++pub fn check(grid: &Grid, wrap: bool, colour: &dyn Fn(&str) -> Option<Rgba>) -> Vec<Finding> {+ let field = Field { grid, wrap };+ let mut found: Vec<Finding> = strays(&field)+ .into_iter()+ .chain(corners(&field))+ .chain(jagged(&field))+ .chain(banding(&field, colour))+ .chain(off_palette(&field))+ .collect();+ found.sort_by(|a, b| {+ a.kind+ .cmp(&b.kind)+ .then(a.at[1].cmp(&b.at[1]))+ .then(a.at[0].cmp(&b.at[0]))+ });+ found+}++#[cfg(test)]+mod tests {+ use super::*;++ fn grid(rows: &[&str]) -> Grid {+ Grid {+ width: rows[0].chars().count() as u32,+ height: rows.len() as u32,+ cells: rows+ .iter()+ .flat_map(|row| row.chars())+ .map(|c| match c {+ '.' => None,+ '?' => Some("#ff00ff".to_string()),+ other => Some(other.to_string()),+ })+ .collect(),+ }+ }++ fn shade(key: &str) -> Option<Rgba> {+ let v = match key {+ "a" => 0.1,+ "b" => 0.4,+ "c" => 0.8,+ "i" => 0.0,+ _ => 0.6,+ };+ Some([v, v, v, 1.0])+ }++ fn found(rows: &[&str], kind: Kind) -> Vec<([u32; 2], [u32; 2])> {+ check(&grid(rows), false, &shade)+ .into_iter()+ .filter(|f| f.kind == kind)+ .map(|f| (f.at, f.to))+ .collect()+ }++ #[test]+ fn a_pixel_with_no_neighbour_of_its_colour_is_stray() {+ let rows = ["i....", ".bb..", ".bb.i", "....."];+ assert_eq!(found(&rows, Kind::Stray), [([0, 0], [0, 0]), ([4, 2], [4, 2])]);+ assert!(found(&["ii", "ii"], Kind::Stray).is_empty());+ assert_eq!(+ check(&grid(&["i..", "...", "..i"]), true, &shade)+ .iter()+ .filter(|f| f.kind == Kind::Stray)+ .count(),+ 0,+ "on a canvas that wraps the two corners touch"+ );+ }++ #[test]+ fn an_l_in_a_thin_line_is_a_doubled_corner_but_a_box_corner_is_not() {+ let stairs = ["ii...", ".ii..", "..ii.", "...ii"];+ assert_eq!(+ found(&stairs, Kind::Corner),+ [+ ([1, 0], [1, 0]),+ ([1, 1], [1, 1]),+ ([2, 1], [2, 1]),+ ([2, 2], [2, 2]),+ ([3, 2], [3, 2]),+ ([3, 3], [3, 3])+ ]+ );+ let clean = ["i....", ".i...", "..i..", "...i."];+ assert!(found(&clean, Kind::Corner).is_empty());+ let boxed = ["iiiii", "i...i", "i...i", "iiiii"];+ assert!(+ found(&boxed, Kind::Corner).is_empty(),+ "arms of two or more both ways are a corner that is meant"+ );+ let small = ["iiii", "i..i", "iiii"];+ assert!(found(&small, Kind::Corner).is_empty(), "also on a small box");+ let filled = ["iii", "iii"];+ assert!(found(&filled, Kind::Corner).is_empty());+ let hook = ["iiiii", "....i", "....."];+ assert_eq!(+ found(&hook, Kind::Corner),+ [([4, 0], [4, 0])],+ "a short arm is not a box"+ );+ }++ #[test]+ fn a_short_run_between_longer_ones_is_jagged() {+ let jag = ["iiii.........", "....i........", ".....iiii....", "............."];+ assert_eq!(found(&jag, Kind::Jagged), [([4, 1], [4, 1])]);+ let note = check(&grid(&jag), false, &shade)+ .into_iter()+ .find(|f| f.kind == Kind::Jagged)+ .unwrap()+ .note;+ assert_eq!(note, "a run of 1 between runs of 4 and 4");+ let even = ["iii......", "...iii...", "......iii"];+ assert!(found(&even, Kind::Jagged).is_empty());+ let arc = ["i........", ".i.......", "..ii.....", "....iiii.", "........i"];+ assert!(+ found(&arc, Kind::Jagged).is_empty(),+ "runs that grow along a curve are fine"+ );+ let steep = ["i..", "i..", "i..", "i..", ".i.", "..i", "..i", "..i", "..i"];+ assert_eq!(+ found(&steep, Kind::Jagged),+ [([1, 4], [1, 4])],+ "the same down a column"+ );+ let bump = ["iiii.iiii", "....i...."];+ assert!(+ found(&bump, Kind::Jagged).is_empty(),+ "a notch that comes back is not a step"+ );+ }++ #[test]+ fn a_one_pixel_band_between_a_darker_and_a_lighter_colour_is_banding() {+ let bands = ["aaaaaa", "bbbbbb", "cccccc"];+ assert_eq!(found(&bands, Kind::Banding), [([0, 1], [5, 1])]);+ let wide = ["aaaaaa", "bbbbbb", "bbbbbb", "cccccc"];+ assert!(+ found(&wide, Kind::Banding).is_empty(),+ "two pixels wide is a shape of its own"+ );+ let line = ["cccccc", "iiiiii", "cccccc"];+ assert!(+ found(&line, Kind::Banding).is_empty(),+ "a line through one colour is a detail"+ );+ let dark = ["bbbbbb", "iiiiii", "cccccc"];+ assert!(+ found(&dark, Kind::Banding).is_empty(),+ "darker than both sides is a line, not a step"+ );+ let short = ["aaa", "bbb", "ccc"];+ assert!(found(&short, Kind::Banding).is_empty());+ let edge = ["......", "bbbbbb", "cccccc"];+ assert!(+ found(&edge, Kind::Banding).is_empty(),+ "an outline next to nothing is not banding"+ );+ let down = ["abc", "abc", "abc", "abc"];+ assert_eq!(found(&down, Kind::Banding), [([1, 0], [1, 3])]);+ }++ #[test]+ fn colours_that_are_not_palette_entries_are_listed_once_with_their_count() {+ let rows = ["bb?", "b??", "bbb"];+ let all = check(&grid(&rows), false, &shade);+ let off: Vec<&Finding> = all.iter().filter(|f| f.kind == Kind::OffPalette).collect();+ assert_eq!(off.len(), 1);+ assert_eq!(+ (off[0].at, off[0].key.as_str(), off[0].note.as_str()),+ ([2, 0], "#ff00ff", "3 pixels, the first here")+ );+ assert!(+ check(&grid(&["bb", "bb"]), false, &shade).is_empty(),+ "a clean drawing has no findings"+ );+ assert_eq!(Kind::ALL.len(), 5);+ assert!(Kind::ALL.iter().all(|k| !k.name().is_empty() && !k.advice().is_empty()));+ }+}diff --git a/docs/DESIGN.md b/docs/DESIGN.mdindex a45dc2c..4e25df5 100644--- a/docs/DESIGN.md+++ b/docs/DESIGN.md@@ -1,4 +1,4 @@-_Last updated: 2026-11-12 19:30_+_Last updated: 2026-11-12 21:30_# klad: design@@ -232,7 +232,7 @@ Unknown keys are errors that list the valid ones, so a typo never passes silentlEvery layer has `blend`, `opacity`, `visible`, `locked`, optional `mask`, `clip` and (M5, format 8) `effects`. Effects are layer settings, not a layer kind: the planned `filter` kind became them.-- **Pixel layers (M9).** A pixel layer is a paint layer flagged `pixel`, so it shares cels, masks, clipping, lock alpha, effects, the timeline and every export with paint layers. One pixel is one canvas pixel: a 64x64 sprite is a 64x64 drawing shown enlarged, and a drawing never mixes pixel sizes. Its marks stay data, as strokes do: a pixel mark is a fill record whose source is cells (`FillSource::Cells`), a set of whole pixels (coverage 0 or 255) with the id of the palette swatch it was drawn with, or a set of pixels to erase. So the same addresses, `set`, `rm`, `transform`, lasso, copy and history work on them; scaling, flipping and turning sample the nearest pixel (`markedit::resampled` with `hard`), which also makes an export above full size hard-edged. Colours are palette entries: `Document::bind_swatch` finds or adds the swatch and gives it an `id` the first time a mark uses it, and `set color=` on a pixel mark binds it to the new entry. The `pixel` op (`klad pixel`) is the first way to make marks; brush strokes and flood or lasso fills are refused on a pixel layer (`ops::off_the_grid`). A drawing with a pixel layer (`Document::pixel_art`) gets a sharp view on both sides. In the editor the zoom moves in whole screen pixels per pixel above real size (`View::whole`, `View::fit_whole`; free below it), a pixel grid shows from 8 screen pixels per pixel (a dark line with light dashes, so it reads on any colour; View > Pixel grid), the pixel under the pointer is outlined on a pixel layer and named in the status line, and the Real size pane (`Pane::Preview`, opened the first time a pixel drawing is opened) shows the composed frame at 1, 2 or 4 screen pixels per pixel for drawings up to 512 px. In the CLI, `klad render` and edit previews enlarge by a whole number to about 512 px (`agent::pixel_scale`), and `--overlay grid` draws the same lines with the pixel numbers along the top and left (`overlay::draw_cells`). The palette is what a pixel drawing is bound to. A mark stores its swatch's id and its colour, so every reader of a stroke file draws it without the palette; when a palette edit changes a swatch's colour, `ops::follow_palette` adds a `MarkChange::Entry` for every pixel drawing, which rewrites the colour of the marks bound to that swatch in the same transaction (one undo step), and a removed swatch unbinds its marks. A palette rewritten without ids keeps them by name, then by colour (`carry_ids`). Swatches carry an optional `ramp` name: a ramp is the swatches sharing it, in palette order, dark to light (`palettes::ramp` makes one from a base colour with `color::value_step`, darker and cooler to lighter and warmer). Palettes that come with klad are colour lists in `core/src/palettes.rs` (`klad palettes`), and `palettes::parse` reads a list of hex colours or a GIMP palette. The pencil is grid geometry in `core/src/pixel.rs`, shared by both hands: `line` (Bresenham), `extend` (a run that follows the pen with no holes), `perfect` (drops the corner pixel of an L, so a hand-drawn line stays one pixel thin), `stamp` (a size is a square of whole pixels) and `of_path` (SVG path data flattened and traced; corners the path asks for are kept, the corners that flattening a curve leaves are not). The `pixel` op takes `cells` or a `path`, and a `size`. In the editor the brush tool on a pixel layer is the pencil (the eraser command and the pen's eraser end erase): the run is drawn over the canvas as it grows and committed on release as one `pixel` op marked as made by hand, so the palette binding, history and sync are the op's. Shift click draws a straight line from the last pixel; `[` and `]` change the size. An agent reads and writes a pixel layer as text, which is exact where a picture is not. `pixel::grid_of` works out what a drawing's marks show, pixel by pixel (later marks over earlier ones, erasing marks, lock alpha, cuts), as the palette entry or the colour of each pixel; `pixel::legend` gives each one a character (the first letter of its name where free) and `pixel::ruled` or `pixel::plain` print the rows (`klad pixels`). The other way, `pixel::parse_text` reads a legend and rows and the grid form of the `pixel` op (`rows`, `legend`, `at`) turns each character into one mark bound to its colour (`klad pixel --grid`), so what `klad pixels --plain` prints draws the same picture again. Text grids are the agent's side only: a person draws with the pencil. Shapes and fills are the same op with other sources: `line`, `rect` and `ellipse` (the ellipse that fits a box of pixels, by an integer midpoint walk, so even and odd sizes stay symmetric; `filled` takes the rows between its outline) are pure geometry in `core/src/pixel.rs`; `fill` is a flood over what the drawing shows (`pixel::flood` on the grid of `grid_of`: pixels joined to the seed with exactly its entry or colour, four neighbours or eight), reading this layer, another pixel layer or all of them merged. A flood needs the marks, which an op cannot read, so `Bundle::settle_pixels` turns every `fill` into its cells before the ops are applied, walking the batch so a fill sees the marks the ops before it made; `Bundle::apply_as` calls it, so the CLI, `klad apply` and the editor share it. In the editor the fill tool floods on a click and the shape tool drags a rectangle, an ellipse or a line of pixels on a pixel layer, previewed as the pixels it will make. Editing pixel marks reuses the selection and transform of strokes and fills, with three differences that keep the grid. A lasso that cuts would leave a supersampled cut on a mark (a soft edge), so `markedit::split` divides a pixel mark's coverage between whole pixels instead, by pixel middles, and the two halves carry no cut. A transform whose matrix is whole numbers (flips, quarter turns, whole scales) is rounded onto the grid in `transform_fill` (`on_the_grid`: matrix and offset rounded), so every pixel lands on a pixel whatever the pivot and marks transformed together still fit; other transforms sample the nearest pixel. Recolouring pixel marks gives each exactly the target colour and its palette entry, where paint marks keep their shades. In the editor the stroke tool on a pixel layer drags a box (or a loop) that snaps out to whole pixels and takes pixels, its box is the selected area, drags move by whole pixels, scale by whole numbers and turn by quarters (`Drag.whole`), and Select same colour takes every mark of the selected marks' palette entries. Shading builds on ramps. `shade` (a number of ramp steps) is a way to colour, not a source: for the pixels of any source, `Bundle::settled` reads what the layer shows and makes one mark per target colour, each pixel taking the swatch `Document::ramp_step` gives for its own (pixels in no ramp, or at its end, are left). `dither` keeps the pixels a 4x4 Bayer pattern fixed to the canvas turns on for that share (`pixel::dithered`), and `second` gives the rest another colour, as a second mark. `outline` is a source: the empty pixels that touch a drawn one (or, `inside`, the drawn ones that touch an empty one) on the grid of this layer, another or all (`pixel::outline`). All three need the drawing, so they are settled in the bundle with `fill`, and `settle_pixels` may return more ops than it was given. Mark by mark, `klad recolour --step` and the selection bar's Lighter and Darker move a mark to the next swatch of its ramp, and `klad recolour --from` rebinds every mark of one colour. A colour's character in the text view is fixed by its place in the palette, not by which colours are in use. Two things multiply what is drawn. A mirror (`mirrorX`, `mirrorY` on the `pixel` op; the editor's mirror line) adds each pixel's twin across a line that stands between two pixels or through a column (`pixel::mirrored`); it is part of the op, so the mark holds both halves. Wrap is a property of the canvas (`canvas.wrap`, set by the `canvas` op): the drawing is a tile, so `PixelSpec::coverage` brings pixels past an edge back in on the other side (`pixel::wrapped`) instead of dropping them, and floods and outlines take their neighbours round the edges. It changes what is drawn, never how the drawing renders; to see the repeat, the editor draws the canvas quad three times across and down with the copies dimmed (the shader repeats the texture when the view's uniform says so) and `klad render --repeat N` tiles the finished picture. Transforms of marks do not wrap. Animation on pixel layers is the timeline as it is: drawings on frames, holds, links, clips and onion skins need nothing new, since a pixel layer is a paint layer. Two things differ. A keyed layer or group that holds only pixel layers (`Layer::grid_only`) is drawn at its key's position rounded to whole pixels and sampled nearest (`render::draw_content`), so a keyed move never softens a sprite. And the ops that move points refuse pixel layers with the reason and what to do instead (`ops::grid_refusal`, checked in `ops::apply` and before the CLI resolves anything): `inbetween`, `pose`, `weights` and attaching to bones. 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 (S9.13): `render/src/aseprite.rs` reads and writes the published binary format into a plain `Sprite` (layers with their nesting level, cels with a picture or a link, per-frame durations, tags, palette); reading turns indexed and grey pixels into RGBA (the transparent index is clear except on a background layer) and lists what it drops, writing is always RGBA with zlib cels. It was checked against files made by Aseprite itself (its public test sprites, not in the repository) and, for the writer, against an independent dump of the chunks. `cli/src/aseprite.rs` maps a sprite to a drawing and back. In: one `add layer` op per top-level layer with its children and cels (explicit cel ids, so linked cels become klad links and a cel followed by an empty frame gets a `hold`), then one pixel op per colour per cel, bound to the palette entry with that colour (file palette first, other colours added, at most 1024), tags as clips; frame times become whole frames at the lowest fps from 1 to 120 with the least error (`timing`), said when it is not exact. Out: pixel layers and groups only (others are named in a note), one file frame per stretch of timeline in which no layer starts or ends a drawing and no clip starts or ends, so holds do not multiply frames and a file that came in goes out with the frames it had; a drawing shown again is a linked cel; a pixel layer's own keyed x, y and opacity go into the cel's position and opacity (every frame is then its own). `klad import` makes the drawing, `klad export --aseprite` the file; the editor opens an Aseprite file by running `klad import` (`start::brought_in`, used by `Home::open`, so the start window, a path given at launch and the system's open all work) and has an Aseprite choice in the export window. Indexed output and tag directions are not kept on the way out. Pictures to pixels (S9.14): `render/src/pixelise.rs` decodes a picture with Skia, shrinks it by area average on premultiplied colour (`shrunk`; exact for whole-number reductions of enlarged pixel art), picks colours (`colours`: the picture's own, most used first, when few enough, else the GIF encoder's median cut, dark to light) and maps every pixel at least half solid to the nearest colour in Oklab (`mapped`). `cli/src/pixelise.rs` turns that into ordinary pixel ops, one mark per colour, so nothing new is stored: a picture file onto a pixel layer in the drawing's palette (`klad pixelize --image --to`), a picture as a new pixel drawing (`klad import x.png`), and a painted or vector layer, or the whole picture, as a new pixel drawing with every frame rendered through the export path, shrunk, and held when it equals the frame before (`klad pixelize --size`). The palette rule is the same everywhere: `--colors N` makes colours from the picture, else an existing palette of two or more solid colours is used as it is, else the picture's own colours (32 when it has more than 256, 16 for a painting). No dithering and no outline repair: the result is a start to clean up. The editor has one window for it (File > Pixels of a picture…, `editor/pixels.rs`) that runs the same command. Tilesets (S9.15): `canvas.tile` is the size of the tiles a drawing is cut into, and nothing else is stored: a tile is a region of the one canvas (`Canvas::tile_at(column, row)`), so every tool, layer, frame and palette works on a tileset as on any drawing, and the cut can be changed or taken away without touching a mark. The canvas has to be a whole number of tiles each way (`Canvas::cut`, checked by the op and when a drawing is opened), which keeps tile addresses and the export exact. The CLI reads and draws one tile at a time (`klad pixels --tile`, `klad pixel --grid --tile`), the editor draws the tile lines over the canvas at any zoom and sets the size in View > Tileset: cut into tiles…, and `klad export --tileset` (the export window's tile set button) renders the frame and writes a Godot `TileSet` with one `TileSetAtlasSource` and a tile for every cell with anything in it (`sprites::tile_set`), into the drawing's Godot folder with a kept uid; a test loads it in Godot. Not there: animated tiles, per-tile wrapping, collision or terrain data, margins between tiles.+- **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 (S9.13): `render/src/aseprite.rs` reads and writes the published binary format into a plain `Sprite` (layers with their nesting level, cels with a picture or a link, per-frame durations, tags, palette); reading turns indexed and grey pixels into RGBA (the transparent index is clear except on a background layer) and lists what it drops, writing is always RGBA with zlib cels. It was checked against files made by Aseprite itself (its public test sprites, not in the repository) and, for the writer, against an independent dump of the chunks. `cli/src/aseprite.rs` maps a sprite to a drawing and back. In: one `add layer` op per top-level layer with its children and cels (explicit cel ids, so linked cels become klad links and a cel followed by an empty frame gets a `hold`), then one pixel op per colour per cel, bound to the palette entry with that colour (file palette first, other colours added, at most 1024), tags as clips; frame times become whole frames at the lowest fps from 1 to 120 with the least error (`timing`), said when it is not exact. Out: pixel layers and groups only (others are named in a note), one file frame per stretch of timeline in which no layer starts or ends a drawing and no clip starts or ends, so holds do not multiply frames and a file that came in goes out with the frames it had; a drawing shown again is a linked cel; a pixel layer's own keyed x, y and opacity go into the cel's position and opacity (every frame is then its own). `klad import` makes the drawing, `klad export --aseprite` the file; the editor opens an Aseprite file by running `klad import` (`start::brought_in`, used by `Home::open`, so the start window, a path given at launch and the system's open all work) and has an Aseprite choice in the export window. Indexed output and tag directions are not kept on the way out. Pictures to pixels (S9.14): `render/src/pixelise.rs` decodes a picture with Skia, shrinks it by area average on premultiplied colour (`shrunk`; exact for whole-number reductions of enlarged pixel art), picks colours (`colours`: the picture's own, most used first, when few enough, else the GIF encoder's median cut, dark to light) and maps every pixel at least half solid to the nearest colour in Oklab (`mapped`). `cli/src/pixelise.rs` turns that into ordinary pixel ops, one mark per colour, so nothing new is stored: a picture file onto a pixel layer in the drawing's palette (`klad pixelize --image --to`), a picture as a new pixel drawing (`klad import x.png`), and a painted or vector layer, or the whole picture, as a new pixel drawing with every frame rendered through the export path, shrunk, and held when it equals the frame before (`klad pixelize --size`). The palette rule is the same everywhere: `--colors N` makes colours from the picture, else an existing palette of two or more solid colours is used as it is, else the picture's own colours (32 when it has more than 256, 16 for a painting). No dithering and no outline repair: the result is a start to clean up. The editor has one window for it (File > Pixels of a picture…, `editor/pixels.rs`) that runs the same command. Tilesets (S9.15): `canvas.tile` is the size of the tiles a drawing is cut into, and nothing else is stored: a tile is a region of the one canvas (`Canvas::tile_at(column, row)`), so every tool, layer, frame and palette works on a tileset as on any drawing, and the cut can be changed or taken away without touching a mark. The canvas has to be a whole number of tiles each way (`Canvas::cut`, checked by the op and when a drawing is opened), which keeps tile addresses and the export exact. The CLI reads and draws one tile at a time (`klad pixels --tile`, `klad pixel --grid --tile`), the editor draws the tile lines over the canvas at any zoom and sets the size in View > Tileset: cut into tiles…, and `klad export --tileset` (the export window's tile set button) renders the frame and writes a Godot `TileSet` with one `TileSetAtlasSource` and a tile for every cell with anything in it (`sprites::tile_set`), into the drawing's Godot folder with a kept uid; a test loads it in Godot. Not there: animated tiles, per-tile wrapping, collision or terrain data, margins between tiles. Pixel checks (S9.16): `core/src/pixelcheck.rs` reads what a pixel layer shows (the `Grid` of palette keys, wrapping where the canvas does) and returns findings, each a kind, a place and a note: a pixel with none of its colour among its eight neighbours; a pixel with exactly two neighbours of its colour beside it at right angles, nothing of its colour in the corner between them, and an arm of one pixel (a doubled corner, as against a box corner); in chains of thin pixels, a straight run at least two shorter than the runs before and after it when the line keeps going the same way and stepping to the same side (a jag, as against the flat top of an arc or a notch); a one-pixel band whose lightness lies between the colours on its two sides for four pixels or more (banding, as against an outline or a line through one colour); and colours that are not palette entries. They are heuristics with those stated limits, and the wording says look, not error. `klad check` prints them by layer and drawing; the editor's Check the pixels (`Cmd::CheckPixels`) runs the same function in the editor, marks the places on the canvas and recomputes when the drawing, the frame or the layer changes, until it is turned off.- **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 d6a0db5..f84aff8 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -66,6 +66,7 @@ This reference is licensed under the MIT License (`LICENSE-MIT`), unlike klad it- [`klad refill`](#klad-refill): Recompute the flood fills of a paint cel after the lines they were made from changed- [`klad palette`](#klad-palette): The document palette: list it, --add or --rm a colour, --recolour one, --load a palette, or group colours in a --ramp- [`klad pixels`](#klad-pixels): Read a pixel layer as a grid of characters, one per pixel, with a legend of its palette colours+- [`klad check`](#klad-check): Look over pixel art: stray pixels, doubled corners, jagged lines, banding, colours off the palette- [`klad palettes`](#klad-palettes): The palettes that come with klad, to load with klad palette <bundle> --load <name>- [`klad export`](#klad-export): Export PNGs, sprite sheets, numbered frames or a Godot SpriteFrames and scene- [`klad brushes`](#klad-brushes): List brushes: the library, and with a bundle the ones it embeds@@ -3473,6 +3474,47 @@ Options:Print help (see a summary with '-h')```+## klad check++```text+Look over the pixel layers of a drawing for the usual slips of pixel art, and list each with its place:++ stray pixel a single pixel with no neighbour of its colour+ doubled corner an L in a one-pixel line, where the line reads thick (a corner whose arms are both two pixels or longer, as on a box, is left alone)+ jagged line a short run between two longer ones in a one-pixel line, a step that breaks its rhythm+ banding a band one pixel wide, lighter than one side and darker than the other, that follows the edge next to it for four pixels or more+ off the palette pixels in a colour that is not a palette entry++ klad check sprite.klad every pixel layer, frame 0+ klad check sprite.klad body --frame 4 one layer (or a group's layers) at a frame+ klad check sprite.klad --all every drawing of every pixel layer+ klad check sprite.klad --json++Places are canvas pixels, x,y from the top left, the way klad pixels counts them. These are places to look at, not errors: a single pixel can be an eye, and a band can be a rim light. klad render --focus or klad pixels shows the spot; klad pixel fixes it.++Usage: klad check [OPTIONS] <BUNDLE> [LAYER]++Arguments:+ <BUNDLE>+++ [LAYER]+ A pixel layer or a group (default: every pixel layer)++Options:+ --frame <FRAME>+ [default: 0]++ --all+ Every drawing on every frame, each once++ --json+++ -h, --help+ Print help (see a summary with '-h')+```+## klad palettes```textdiff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.mdindex 2aed2ec..5969a6c 100644--- a/docs/skill/SKILL.md+++ b/docs/skill/SKILL.md@@ -143,8 +143,9 @@ klad export sprite.klad --scale 8 -o [email protected] square pixels, to keep- 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.+- Check your pixels before you call a sprite done: `klad check sprite.klad` (a layer or group, `--frame N`, `--all` for every drawing, `--json`) lists the usual slips with their places in canvas pixels: `stray pixel` (a single pixel with no neighbour of its colour), `doubled corner` (an L in a one-pixel line, where it reads thick; corners whose arms are both two pixels or longer, as on a box, are left alone), `jagged line` (a short run between two longer ones, a step that breaks the line's rhythm), `banding` (a one-pixel band between a darker and a lighter colour that follows the edge beside it for four pixels or more) and `off the palette` (pixels in a colour that is not a palette entry). They are places to look at, not errors: an eye is a stray pixel, a rim light is a band. Fix what is a slip (`klad pixel --erase --cells`, redraw the run, `klad recolour`), leave what is meant, and run it again; a clean drawing prints `nothing to look at`.- Tilesets. A drawing can be cut into tiles of one size: `klad new ground.klad --pixel 64x48 --tile 16` (or `klad canvas ground.klad --tile 16`, `16x24` for other shapes, `--tile off` to undo); each side of the canvas has to be a whole number of tiles, and `klad canvas ground.klad` says how many there are. Work one tile at a time: `klad pixels ground.klad l1 --tile 2,0 --plain` reads the tile in column 2 of row 0 with its pixels counted from its own corner, and `klad pixel ground.klad l1 --grid - --tile 2,0` draws a grid there (`--at` then moves it inside the tile); every other command still uses canvas pixels, and a tile's corner is column times width, row times height. Keep each tile inside its own cell, and check seams by reading two neighbours: a tile's last column has to meet the next tile's first. `klad export ground.klad --tileset ../game/art` writes a Godot TileSet (`ground-tiles.png` and `ground-tiles.tres`, one atlas source, a tile for every cell that is not empty; `--scale`, `--frame` and `--variant` as for other exports; the folder is the drawing's Godot folder once given). In Godot the TileMapLayer's texture filter has to be Nearest for pixel tiles. `--wrap` is a different thing: it makes the whole canvas one repeating tile.-- Pictures to pixels. `klad pixelize sprite.klad --image ref.png --to l1` puts a PNG or JPEG on a pixel layer: every pixel takes the nearest colour of the drawing's palette (so it lands in the colours the sprite has; `--colors N` makes N colours from the picture and adds them instead), `--size 48` shrinks it to 48 px on its longest side first (each pixel the average of the area it covers; a picture enlarged by a whole number comes back exact; pixels less than half solid stay empty), `--at x,y` places its top left, `--frame` picks the drawing. `klad import ref.png [--size N] [--colors N]` makes a new pixel drawing from a picture, with the picture's own colours as its palette (reduced to 32 when it has more than 256). `klad pixelize hero.klad --size 64 [--layer body] [--colors 12] [-o out.klad]` makes a new pixel drawing (`hero-pixel.klad`) of a painted or vector layer or of the whole picture, every frame with one set of colours, frames that come out the same held, clips kept; the drawing itself is not changed. All three give marks bound to palette colours, one per colour, so the result is edited like anything else here. Treat it as a start, not a finish: shrinking blurs edges into in-between colours and breaks one-pixel outlines, so look at it at real size, then redraw the outline, and cut stray colours with `klad recolour --from a --to b`.+- Pictures to pixels. `klad pixelize sprite.klad --image ref.png --to l1` puts a PNG or JPEG on a pixel layer: every pixel takes the nearest colour of the drawing's palette (so it lands in the colours the sprite has; `--colors N` makes N colours from the picture and adds them instead), `--size 48` shrinks it to 48 px on its longest side first (each pixel the average of the area it covers; a picture enlarged by a whole number comes back exact; pixels less than half solid stay empty), `--at x,y` places its top left, `--frame` picks the drawing. `klad import ref.png [--size N] [--colors N]` makes a new pixel drawing from a picture, with the picture's own colours as its palette (reduced to 32 when it has more than 256). `klad pixelize hero.klad --size 64 [--layer body] [--colors 12] [-o out.klad]` makes a new pixel drawing (`hero-pixel.klad`) of a painted or vector layer or of the whole picture, every frame with one set of colours, frames that come out the same held, clips kept; the drawing itself is not changed. All three give marks bound to palette colours, one per colour, so the result is edited like anything else here. Treat it as a start, not a finish: shrinking blurs edges into in-between colours and breaks one-pixel outlines, so look at it at real size, then redraw the outline, cut stray colours with `klad recolour --from a --to b`, and run `klad check` on it.- Aseprite files: `klad import hero.aseprite` (or `.ase`; `-o` names the drawing) makes `hero.klad` next to the file: image layers as pixel layers with their name, visibility, opacity and blend mode, groups as groups, every cel as a drawing on its frame (linked cels stay links), the palette with its names, tags as clips. Frame times become whole frames at the slowest speed that fits (100 ms frames are 10 fps; a 300 ms frame holds for three). Indexed, grey and RGBA files all open, every pixel bound to its palette colour. It says what it leaves out: tilemap layers, tilesets, slices, tag directions other than forwards, blend modes klad lacks. `klad export hero.klad --aseprite` writes the pixel layers and groups back (RGBA; holds and links as linked cels, clips as tags, a pixel layer's keyed moves and opacity baked into its cels; `--variant` and `--variants` work); paint, vector and other layers are left out and named. Use it to hand work to someone who uses Aseprite, or to take over a sprite made there.- 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).