Skip to content

armgit / klad

Public Imported from GitHub
0

A drawing app built for agent/human collaboration

Rust

Animating pixel layers: keyed moves by whole pixels, and a reason where in-betweens and bones do not apply

Indicode BV91016aa812ce
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cd41ff0..e72c494 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.
+- Animating pixel layers. Frames, holds, links, clips and onion skins work on pixel layers as on paint layers. A keyed pixel layer moves by whole pixels and stays sharp. In-betweens, poses, weights and bones refuse pixel layers and say why: they move points and bend strokes, so draw the frames or key the layer's position.
- Mirror and tiles for pixel art. The pixel pencil, shape and fill tools draw each pixel's twin across the **mirror** line. **View > Tile: wrap at the edges** makes the drawing a tile: what you draw past an edge comes back in on the other side, fills go round the edges, and the canvas shows its repeats around it. From the command line: `klad pixel --mirror-x 16` (and `--mirror-y`), `klad new tile.klad --pixel 16 --wrap`, `klad canvas tile.klad --wrap on`, and `klad render --repeat 3` to see a tile repeated.
- Shading pixels. The pixel pencil, the shape tool and the fill tool have three inks: **colour**, **lighter** and **darker**; the last two step the pixels you go over along their colour's ramp. **dither** draws a share of the pixels in an even pattern, with the **second colour** for the rest. **Layer > Outline the pixels** adds a one-pixel outline in the current colour, and **Lighter** and **Darker** in the bar under selected marks step them along their ramp. From the command line: `klad pixel --shade`, `--dither` with `--second`, `--outline` (`--inside`), `klad recolour --step`, and `klad recolour --from skin --to skin-dark` to replace a colour.
- Selecting and editing pixels. On a pixel layer the stroke tool (**S**) drags a box, or a loop, around pixels and takes them, cutting marks between whole pixels; drag them to move by whole pixels, scale by whole numbers or turn by quarters, and the bar under them flips, turns, recolours (exactly the current colour), copies and deletes. **Select same colour** takes every mark in the selected colours. From the command line: `klad lasso` takes `--box x,y,w,h`, `klad strokes --entry skin` lists one colour's marks, and `klad recolour` gives pixel marks the exact palette colour.
diff --git a/crates/app/src/editor/commands.rs b/crates/app/src/editor/commands.rs
index 9c7c93a..0552812 100644
--- a/crates/app/src/editor/commands.rs
+++ b/crates/app/src/editor/commands.rs
@@ -332,6 +332,10 @@ impl Editor {
Cmd::OnOnes | Cmd::OnTwos | Cmd::OnThrees | Cmd::FitFrames | Cmd::Reverse | Cmd::Pingpong => {
need_span().or_else(|| self.timeline_edit())
}
+ Cmd::Inbetween if self.scene.on_grid() => Some(
+ "this is a pixel layer: in-betweens move the points of strokes, and pixels have none. Draw the frames in between"
+ .to_string(),
+ ),
Cmd::Inbetween => need_span()
.or_else(|| self.timeline_edit())
.or_else(|| {
diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rs
index 5e859ed..37ccc9a 100644
--- a/crates/app/src/editor/ui_tests.rs
+++ b/crates/app/src/editor/ui_tests.rs
@@ -2178,6 +2178,12 @@ fn the_pixel_pencil_mirrors_across_a_line_and_wraps_on_a_tile() {
.map(|f| f.coverage.cells().collect())
.unwrap_or_default()
};
+ assert!(
+ h.state()
+ .can_run(Cmd::Inbetween)
+ .is_some_and(|why| why.contains("pixel layer") && why.contains("Draw the frames")),
+ "in-betweens say why they do not apply to pixels"
+ );
assert_eq!(h.state().is_on(Cmd::Symmetry), Some(false));
h.state_mut().invoke(Cmd::Symmetry).unwrap();
h.run_steps(2);
diff --git a/crates/cli/src/agent.rs b/crates/cli/src/agent.rs
index 4125bfe..d6d6420 100644
--- a/crates/cli/src/agent.rs
+++ b/crates/cli/src/agent.rs
@@ -605,6 +605,8 @@ pub fn preview(bundle: &Bundle, out: &Output) -> Result<Option<PathBuf>> {
pub fn edit(path: &Path, ops: &[Op], out: &Output) -> Result<()> {
let mut bundle = Bundle::open(path)?;
let mut ops = ops.to_vec();
+ ops.iter()
+ .try_for_each(|op| klad_core::ops::grid_refusal(&bundle.doc, op))?;
crate::paintover::resolve(&bundle, &mut ops)?
.iter()
.for_each(|n| eprintln!("{n}"));
diff --git a/crates/cli/src/export.rs b/crates/cli/src/export.rs
index f77d20c..a8d751e 100644
--- a/crates/cli/src/export.rs
+++ b/crates/cli/src/export.rs
@@ -234,4 +234,63 @@ mod tests {
});
std::fs::remove_dir_all(&dir).unwrap();
}
+
+ #[test]
+ fn a_keyed_pixel_layer_moves_by_whole_pixels_and_stays_hard() {
+ use klad_core::bundle::Blank;
+ let dir = std::env::temp_dir().join(format!("draw-export-pixel-key-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let mut bundle = Bundle::blank(
+ dir.join("art.klad"),
+ &Blank {
+ width: 12,
+ height: 4,
+ pixel: true,
+ frames: 5,
+ ..Blank::default()
+ },
+ "cli",
+ )
+ .unwrap();
+ let layer = bundle.doc.layers[0].id.clone();
+ bundle
+ .apply(
+ &klad_core::ops::parse_lines(&format!(
+ "{}\n{}\n{}",
+ format_args!(r##"{{"op":"pixel","layer":"{layer}","color":"#ef233c","cells":[[1,1],[2,1]]}}"##),
+ format_args!(r##"{{"op":"key","id":"{layer}","frame":0,"x":0}}"##),
+ format_args!(r##"{{"op":"key","id":"{layer}","frame":4,"x":6}}"##),
+ ))
+ .unwrap(),
+ )
+ .unwrap();
+ let brushes = BrushSet::for_bundle(&bundle).unwrap();
+ let reds = |frame: u32| -> Vec<usize> {
+ let rasters = layers::load_at(&bundle, frame, &brushes, 1.0).unwrap();
+ let options = Options {
+ scale: 1.0,
+ background: false,
+ references: false,
+ detail: 1.0,
+ };
+ let image = render(&bundle.doc, frame, &rasters, &Target::Frame, options).unwrap();
+ let pixels = klad_render::export::dither8(&image).unwrap();
+ (0..12)
+ .filter(|x| {
+ let at = (12 + x) * 4;
+ let px = &pixels[at..at + 4];
+ assert!(
+ px == [0xef, 0x23, 0x3c, 255] || px == [0, 0, 0, 0],
+ "frame {frame}, pixel {x} is {px:?}: neither the colour nor empty"
+ );
+ px[3] == 255
+ })
+ .collect()
+ };
+ assert_eq!(reds(0), [1, 2]);
+ assert_eq!(reds(1), [3, 4], "a quarter of the way is 1.5 pixels: it lands on 2");
+ assert_eq!(reds(2), [4, 5]);
+ assert_eq!(reds(4), [7, 8]);
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
}
diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rs
index e41de5c..ee8e703 100644
--- a/crates/cli/tests/binary.rs
+++ b/crates/cli/tests/binary.rs
@@ -1056,6 +1056,78 @@ fn a_tile_wraps_at_its_edges_mirrors_and_renders_repeated_from_the_command_line(
std::fs::remove_dir_all(&dir).unwrap();
}
+#[test]
+fn a_pixel_layer_animates_frame_by_frame_moves_by_whole_pixels_and_refuses_in_betweens_and_bones() {
+ let dir = std::env::temp_dir().join(format!("draw-binary-pixel-anim-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let bundle = dir.join("hop.klad");
+ let path = bundle.to_str().unwrap();
+ let run = |args: &[&str]| Command::new(env!("CARGO_BIN_EXE_klad")).args(args).output().unwrap();
+ let draw = |args: &[&str]| {
+ let out = run(args);
+ assert!(out.status.success(), "{}", 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", "12x6", "--frames", "4", "--fps", "8"]);
+ draw(&["palette", path, "--add", "#22223b", "--name", "ink"]);
+ draw(&["pixel", path, "l1", "--color", "ink", "--rect", "1,3,2,2", "--filled"]);
+ draw(&["add", path, "cel", "--in", "l1", "frame=2"]);
+ draw(&[
+ "pixel", path, "l1", "--frame", "2", "--color", "ink", "--rect", "1,1,2,2", "--filled",
+ ]);
+ let row = |frame: &str, at: usize| -> String {
+ draw(&["pixels", path, "l1", "--frame", frame, "--plain"])
+ .lines()
+ .skip_while(|line| !line.is_empty())
+ .skip(1)
+ .nth(at)
+ .unwrap()
+ .to_string()
+ };
+ assert_eq!(
+ (row("0", 3), row("1", 3), row("2", 3), row("2", 1)),
+ (
+ ".ii.........".to_string(),
+ ".ii.........".to_string(),
+ "............".to_string(),
+ ".ii.........".to_string()
+ ),
+ "each drawing holds until the next: frames 0 and 1 show the first, 2 and 3 the second"
+ );
+ draw(&["clip", path, "--add", "hop", "--from", "0", "--to", "3", "--loop"]);
+ assert!(draw(&["frames", path]).contains("hop"));
+ draw(&["key", path, "l1", "--frame", "0", "x=0"]);
+ draw(&["key", path, "l1", "--frame", "3", "x=4"]);
+ let hashes = draw(&["hash", path, "--all"]);
+ assert_eq!(hashes.lines().count(), 4);
+ let shown = |frame: &str| {
+ let out = dir.join(format!("f{frame}.png"));
+ draw(&["export", path, "--frame", frame, "-o", out.to_str().unwrap()]);
+ std::fs::read(&out).unwrap()
+ };
+ assert_ne!(shown("0"), shown("1"), "the key moves the drawing between frames");
+ let onion = run(&["render", path, "--frame", "2", "--overlay", "onion"]);
+ assert!(onion.status.success(), "{}", String::from_utf8_lossy(&onion.stderr));
+ let between = refused(&["inbetween", path, "--layers", "l1", "--from", "0", "--to", "2"]);
+ assert!(
+ between.contains("pixel layer") && between.contains("Draw the frames"),
+ "{between}"
+ );
+ draw(&["add", path, "layer", "bones", "name=bones"]);
+ let attached = refused(&["attach", path, "l1", "--bend", "--skeleton", "bones"]);
+ assert!(
+ attached.contains("pixel layer") && attached.contains("off the grid"),
+ "{attached}"
+ );
+ 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/doc.rs b/crates/core/src/doc.rs
index f1fd290..301fd63 100644
--- a/crates/core/src/doc.rs
+++ b/crates/core/src/doc.rs
@@ -589,6 +589,14 @@ impl Layer {
matches!(self.content, LayerContent::Paint { pixel: true, .. })
}
+ pub fn grid_only(&self) -> bool {
+ match &self.content {
+ LayerContent::Paint { pixel, .. } => *pixel,
+ LayerContent::Group { children } => !children.is_empty() && children.iter().all(Layer::grid_only),
+ _ => false,
+ }
+ }
+
pub fn kind_name(&self) -> &'static str {
match self.pixel() {
true => "pixel",
diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rs
index 5457158..1134c66 100644
--- a/crates/core/src/ops.rs
+++ b/crates/core/src/ops.rs
@@ -3743,6 +3743,7 @@ fn move_item(doc: &mut Document, id: &str, place: &Place) -> Result<()> {
}
pub fn apply(doc: &mut Document, op: &Op, out: &mut Applied) -> Result<()> {
+ grid_refusal(doc, op)?;
match op {
Op::AddLayer { layer, place } => {
let mut value = layer.clone();
@@ -4175,6 +4176,31 @@ fn put_pixels(doc: &mut Document, spec: &PixelSpec, out: &mut Applied) -> Result
Ok(())
}
+pub fn grid_refusal(doc: &Document, op: &Op) -> Result<()> {
+ let pixel = |key: &str| doc.find_layer(key).is_ok_and(Layer::pixel);
+ match op {
+ Op::Inbetween(spec) => match spec.layers.iter().find(|l| pixel(l)) {
+ Some(layer) => bail!(
+ "{layer} is a pixel layer: in-betweens move the points of strokes, and pixel marks have none. Draw the frames in between, or key the layer's position (klad key) to move it by whole pixels"
+ ),
+ None => Ok(()),
+ },
+ Op::Pose(spec) if pixel(&spec.layer) => bail!(
+ "{} is a pixel layer: a pose bends strokes point by point, which would take pixels off the grid. Draw each pose as a frame",
+ spec.layer
+ ),
+ Op::Weights(spec) if pixel(&spec.layer) => bail!(
+ "{} is a pixel layer: bone weights bend strokes, and pixel layers stay on the grid",
+ spec.layer
+ ),
+ Op::Attach(spec) if pixel(&spec.layer) && (spec.skeleton.is_some() || spec.bone.is_some()) => bail!(
+ "{} is a pixel layer: bones turn and bend what they hold, which would take pixels off the grid. Draw the frames, or key the layer's position",
+ spec.layer
+ ),
+ _ => Ok(()),
+ }
+}
+
fn off_the_grid(doc: &Document, layer: &str, what: &str) -> Result<()> {
if doc.layer(layer).is_some_and(Layer::pixel) {
bail!("{layer} is a pixel layer: it takes whole pixels (klad pixel), not {what}");
@@ -4860,6 +4886,32 @@ mod tests {
);
}
+ #[test]
+ fn in_betweens_poses_weights_and_bones_say_why_they_do_not_take_pixel_layers() {
+ let (doc, _) = apply_all(
+ &base(),
+ &ops(&[
+ json!({"op":"add","layer":{"kind":"pixel","name":"sprite","id":"lp"}}),
+ json!({"op":"add","layer":{"kind":"group","name":"both","id":"g1","children":[{"kind":"pixel","name":"a","id":"la"}]}}),
+ ]),
+ )
+ .unwrap();
+ assert!(doc.layer("lp").unwrap().grid_only() && doc.layer("g1").unwrap().grid_only());
+ assert!(!doc.find_layer("ink").unwrap().grid_only() && !doc.find_layer("shapes").unwrap().grid_only());
+ let why = |value: Value| {
+ let op = Op::parse(value).unwrap();
+ format!("{:#}", grid_refusal(&doc, &op).unwrap_err())
+ };
+ assert!(why(json!({"op":"inbetween","layers":["lp"],"from":0,"to":4})).contains("Draw the frames in between"));
+ assert!(why(json!({"op":"pose","layer":"lp","to":2})).contains("Draw each pose as a frame"));
+ assert!(why(json!({"op":"weights","layer":"lp","auto":true})).contains("stay on the grid"));
+ assert!(why(json!({"op":"attach","layer":"lp","bone":"arm"})).contains("off the grid"));
+ let fine = |value: Value| grid_refusal(&doc, &Op::parse(value).unwrap()).is_ok();
+ assert!(fine(json!({"op":"attach","layer":"lp"})), "unrigging is always fine");
+ assert!(fine(json!({"op":"inbetween","layers":["l2"],"from":0,"to":4})));
+ assert!(fine(json!({"op":"key","id":"lp","frame":2,"x":3})));
+ }
+
#[test]
fn palette_ops_add_rename_remove_and_name_stroke_colours() {
let (doc, applied) = apply_all(
diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs
index f8d9d9d..e44ed11 100644
--- a/crates/render/src/lib.rs
+++ b/crates/render/src/lib.rs
@@ -756,17 +756,24 @@ fn draw_content(canvas: &Canvas, layer: &Layer, ctx: Ctx) -> Result<()> {
let pivot = ctx.doc.map_or((0.0, 0.0), |d| {
(d.canvas.width as f32 / 2.0, d.canvas.height as f32 / 2.0)
});
+ let grid = layer.grid_only();
+ let (x, y) = match grid {
+ true => (moved.x.round(), moved.y.round()),
+ false => (moved.x, moved.y),
+ };
canvas.save();
- canvas.translate((moved.x + pivot.0, moved.y + pivot.1));
+ canvas.translate((x + pivot.0, y + pivot.1));
canvas.rotate(moved.rotate, None);
canvas.scale((moved.sx, moved.sy));
canvas.translate((-pivot.0, -pivot.1));
let whole = Ctx {
area: None,
- sampling: Some(
- ctx.sampling
+ sampling: Some(match grid {
+ true => SamplingOptions::new(FilterMode::Nearest, MipmapMode::None),
+ false => ctx
+ .sampling
.unwrap_or(SamplingOptions::new(FilterMode::Linear, MipmapMode::None)),
- ),
+ }),
..ctx
};
let drawn = draw_unmoved(canvas, layer, whole);
diff --git a/docs/DESIGN.md b/docs/DESIGN.md
index 6f78aa1..83220ef 100644
--- a/docs/DESIGN.md
+++ b/docs/DESIGN.md
@@ -1,4 +1,4 @@
-_Last updated: 2026-11-12 04:00_
+_Last updated: 2026-11-12 05:00_
# klad: design
@@ -232,7 +232,7 @@ Unknown keys are errors that list the valid ones, so a typo never passes silentl
Every 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. Sharp exports and Aseprite files follow in the milestone's later stories.
+- **Pixel layers (M9).** A pixel layer is a paint layer flagged `pixel`, so it shares cels, masks, clipping, lock alpha, effects, the timeline and every export with paint layers. One pixel is one canvas pixel: a 64x64 sprite is a 64x64 drawing shown enlarged, and a drawing never mixes pixel sizes. Its marks stay data, as strokes do: a pixel mark is a fill record whose source is cells (`FillSource::Cells`), a set of whole pixels (coverage 0 or 255) with the id of the palette swatch it was drawn with, or a set of pixels to erase. So the same addresses, `set`, `rm`, `transform`, lasso, copy and history work on them; scaling, flipping and turning sample the nearest pixel (`markedit::resampled` with `hard`), which also makes an export above full size hard-edged. Colours are palette entries: `Document::bind_swatch` finds or adds the swatch and gives it an `id` the first time a mark uses it, and `set color=` on a pixel mark binds it to the new entry. The `pixel` op (`klad pixel`) is the first way to make marks; brush strokes and flood or lasso fills are refused on a pixel layer (`ops::off_the_grid`). A drawing with a pixel layer (`Document::pixel_art`) gets a sharp view on both sides. In the editor the zoom moves in whole screen pixels per pixel above real size (`View::whole`, `View::fit_whole`; free below it), a pixel grid shows from 8 screen pixels per pixel (a dark line with light dashes, so it reads on any colour; View > Pixel grid), the pixel under the pointer is outlined on a pixel layer and named in the status line, and the Real size pane (`Pane::Preview`, opened the first time a pixel drawing is opened) shows the composed frame at 1, 2 or 4 screen pixels per pixel for drawings up to 512 px. In the CLI, `klad render` and edit previews enlarge by a whole number to about 512 px (`agent::pixel_scale`), and `--overlay grid` draws the same lines with the pixel numbers along the top and left (`overlay::draw_cells`). The palette is what a pixel drawing is bound to. A mark stores its swatch's id and its colour, so every reader of a stroke file draws it without the palette; when a palette edit changes a swatch's colour, `ops::follow_palette` adds a `MarkChange::Entry` for every pixel drawing, which rewrites the colour of the marks bound to that swatch in the same transaction (one undo step), and a removed swatch unbinds its marks. A palette rewritten without ids keeps them by name, then by colour (`carry_ids`). Swatches carry an optional `ramp` name: a ramp is the swatches sharing it, in palette order, dark to light (`palettes::ramp` makes one from a base colour with `color::value_step`, darker and cooler to lighter and warmer). Palettes that come with klad are colour lists in `core/src/palettes.rs` (`klad palettes`), and `palettes::parse` reads a list of hex colours or a GIMP palette. The pencil is grid geometry in `core/src/pixel.rs`, shared by both hands: `line` (Bresenham), `extend` (a run that follows the pen with no holes), `perfect` (drops the corner pixel of an L, so a hand-drawn line stays one pixel thin), `stamp` (a size is a square of whole pixels) and `of_path` (SVG path data flattened and traced; corners the path asks for are kept, the corners that flattening a curve leaves are not). The `pixel` op takes `cells` or a `path`, and a `size`. In the editor the brush tool on a pixel layer is the pencil (the eraser command and the pen's eraser end erase): the run is drawn over the canvas as it grows and committed on release as one `pixel` op marked as made by hand, so the palette binding, history and sync are the op's. Shift click draws a straight line from the last pixel; `[` and `]` change the size. An agent reads and writes a pixel layer as text, which is exact where a picture is not. `pixel::grid_of` works out what a drawing's marks show, pixel by pixel (later marks over earlier ones, erasing marks, lock alpha, cuts), as the palette entry or the colour of each pixel; `pixel::legend` gives each one a character (the first letter of its name where free) and `pixel::ruled` or `pixel::plain` print the rows (`klad pixels`). The other way, `pixel::parse_text` reads a legend and rows and the grid form of the `pixel` op (`rows`, `legend`, `at`) turns each character into one mark bound to its colour (`klad pixel --grid`), so what `klad pixels --plain` prints draws the same picture again. Text grids are the agent's side only: a person draws with the pencil. Shapes and fills are the same op with other sources: `line`, `rect` and `ellipse` (the ellipse that fits a box of pixels, by an integer midpoint walk, so even and odd sizes stay symmetric; `filled` takes the rows between its outline) are pure geometry in `core/src/pixel.rs`; `fill` is a flood over what the drawing shows (`pixel::flood` on the grid of `grid_of`: pixels joined to the seed with exactly its entry or colour, four neighbours or eight), reading this layer, another pixel layer or all of them merged. A flood needs the marks, which an op cannot read, so `Bundle::settle_pixels` turns every `fill` into its cells before the ops are applied, walking the batch so a fill sees the marks the ops before it made; `Bundle::apply_as` calls it, so the CLI, `klad apply` and the editor share it. In the editor the fill tool floods on a click and the shape tool drags a rectangle, an ellipse or a line of pixels on a pixel layer, previewed as the pixels it will make. Editing pixel marks reuses the selection and transform of strokes and fills, with three differences that keep the grid. A lasso that cuts would leave a supersampled cut on a mark (a soft edge), so `markedit::split` divides a pixel mark's coverage between whole pixels instead, by pixel middles, and the two halves carry no cut. A transform whose matrix is whole numbers (flips, quarter turns, whole scales) is rounded onto the grid in `transform_fill` (`on_the_grid`: matrix and offset rounded), so every pixel lands on a pixel whatever the pivot and marks transformed together still fit; other transforms sample the nearest pixel. Recolouring pixel marks gives each exactly the target colour and its palette entry, where paint marks keep their shades. In the editor the stroke tool on a pixel layer drags a box (or a loop) that snaps out to whole pixels and takes pixels, its box is the selected area, drags move by whole pixels, scale by whole numbers and turn by quarters (`Drag.whole`), and Select same colour takes every mark of the selected marks' palette entries. Shading builds on ramps. `shade` (a number of ramp steps) is a way to colour, not a source: for the pixels of any source, `Bundle::settled` reads what the layer shows and makes one mark per target colour, each pixel taking the swatch `Document::ramp_step` gives for its own (pixels in no ramp, or at its end, are left). `dither` keeps the pixels a 4x4 Bayer pattern fixed to the canvas turns on for that share (`pixel::dithered`), and `second` gives the rest another colour, as a second mark. `outline` is a source: the empty pixels that touch a drawn one (or, `inside`, the drawn ones that touch an empty one) on the grid of this layer, another or all (`pixel::outline`). All three need the drawing, so they are settled in the bundle with `fill`, and `settle_pixels` may return more ops than it was given. Mark by mark, `klad recolour --step` and the selection bar's Lighter and Darker move a mark to the next swatch of its ramp, and `klad recolour --from` rebinds every mark of one colour. A colour's character in the text view is fixed by its place in the palette, not by which colours are in use. Two things multiply what is drawn. A mirror (`mirrorX`, `mirrorY` on the `pixel` op; the editor's mirror line) adds each pixel's twin across a line that stands between two pixels or through a column (`pixel::mirrored`); it is part of the op, so the mark holds both halves. Wrap is a property of the canvas (`canvas.wrap`, set by the `canvas` op): the drawing is a tile, so `PixelSpec::coverage` brings pixels past an edge back in on the other side (`pixel::wrapped`) instead of dropping them, and floods and outlines take their neighbours round the edges. It changes what is drawn, never how the drawing renders; to see the repeat, the editor draws the canvas quad three times across and down with the copies dimmed (the shader repeats the texture when the view's uniform says so) and `klad render --repeat N` tiles the finished picture. Transforms of marks do not wrap. Animation on pixel layers is the timeline as it is: drawings on frames, holds, links, clips and onion skins need nothing new, since a pixel layer is a paint layer. Two things differ. A keyed layer or group that holds only pixel layers (`Layer::grid_only`) is drawn at its key's position rounded to whole pixels and sampled nearest (`render::draw_content`), so a keyed move never softens a sprite. And the ops that move points refuse pixel layers with the reason and what to do instead (`ops::grid_refusal`, checked in `ops::apply` and before the CLI resolves anything): `inbetween`, `pose`, `weights` and attaching to bones. Sharp exports and 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/skill/SKILL.md b/docs/skill/SKILL.md
index 85095ea..77f8a84 100644
--- a/docs/skill/SKILL.md
+++ b/docs/skill/SKILL.md
@@ -140,6 +140,7 @@ klad export sprite.klad --scale 8 -o [email protected] square pixels, to keep
- The palette is the drawing's colours, and changing one changes the picture: `klad palette sprite.klad --recolour skin --to '#e8b796'` (a name, a colour, an index or an id) recolours every pixel mark drawn with it, on every frame. So fix a colour in the palette, not mark by mark. `klad palette sprite.klad --load pico-8` adds a palette that comes with klad (`klad palettes` lists them: pico-8, resurrect-64, four-greens, 1-bit) or a file (`.hex`, one colour per line, or a GIMP `.gpl`); colours the palette holds are not added twice. A ramp is a row of colours for one material, dark to light: `klad palette sprite.klad --ramp wood --base '#8b5a2b' --steps 5` makes `wood-1` (dark, cooler) to `wood-5` (light, warmer) around the base, and `--ramp skin --of skin-dark,skin,skin-light` groups colours it has. Shade a form with the steps of its ramp, not with new colours.
- 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.
- Each mark, `<cel>:s<id>`, stays editable: `klad set sprite.klad c2:s1 color=shadow` recolours it (and binds it to that entry), `klad transform ... --move 2,0` moves it by whole pixels, `--flip h` and `--rotate 90` keep it hard, `klad rm` removes it. `klad strokes sprite.klad l1` lists the marks with their entry and cell count; `--json` gives each one's `cells`.
- Later marks cover earlier ones; `--erase` (or `erase` in a grid's legend) makes a mark that clears what was drawn before it at those pixels (remove that mark and the pixels come back).
- Looking: `klad render` and the `--render` preview of an edit enlarge a pixel drawing by a whole number to about 512 px, so every pixel is a square you can see (`--scale 1` gives the real size, which is how the player sees it: check there too). `--overlay grid` draws a line between pixels and numbers them along the top and the left, so a pixel's `x,y` can be read off the picture: the number is on the line where that column or row starts. `klad export --scale 8` (whole numbers) writes the enlarged PNG to keep.