A drawing app built for agent/human collaboration
Rust
Pixel art samples and guide, and a calmer doubled-corner check
Indicode BV2214ac647fff
diff --git a/.gitignore b/.gitignoreindex ba5409a..6235d2e 100644--- a/.gitignore+++ b/.gitignore@@ -8,6 +8,7 @@ target/__pycache__//samples/*/*.klad//samples/*/*.png+/samples/*/*.gif/samples/*/*-godot//samples/*/*.json/distdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex f4e10f7..2afb232 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.+- Two pixel art samples, `sprout` (a 32 px character with an idle and a walk) and `ground` (a tileset of 16 px tiles), in the start window and `klad samples`, and a guide, Drawing pixel art.- A third agent skill, `klad skill pixel`: the craft of pixel art (size and palette, silhouette, clusters, clean lines, outlines, ramps with hue shift, shading without pillow shading or banding, anti-aliasing by hand, tiles, animation, and a checklist at real size). Under the MIT licence, like the other two.- 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>`.diff --git a/README.md b/README.mdindex 48c37bb..9d87f4f 100644--- a/README.md+++ b/README.md@@ -98,7 +98,7 @@ Building takes about ten minutes the first time.2. `git clone https://github.com/klad-app/klad && cd klad`, then `just compile` makes `klad` and `klad-editor` for the machine you are on, in `target/release/` (on Linux in `target/linux/release/`). What you build is for your own use, or your company's if it had less than 500,000 euros in revenue last year (see [Licence](#licence)).3. `target/release/klad open` starts the editor on its start window: make a drawing and start painting, or take first steps (Help > First steps in the editor).4. `target/release/klad install` puts `klad` on your terminal's path, for you and for agents (the editor's document menu has the same as "install the klad command").-5. `just samples` builds the sample drawings in `samples/` (a lantern, a walking creature, a running courier, an underground ruin, an inn sign, a tree, a meadow, painted solids, a bowl of lemons and the same painted over with brushwork, a bouncing ball, ink examples); open one with `target/release/klad open samples/lantern/lantern.klad`. The six listed in `samples/shipped.json` show in the start window and go into every build (`packaging/samples.sh`).+5. `just samples` builds the sample drawings in `samples/` (a lantern, a walking creature, a running courier, an underground ruin, an inn sign, a tree, a meadow, painted solids, a bowl of lemons and the same painted over with brushwork, a bouncing ball, ink examples, a pixel art character and a tileset); open one with `target/release/klad open samples/lantern/lantern.klad`. The eight listed in `samples/shipped.json` show in the start window and go into every build (`packaging/samples.sh`).6. On a Mac, `just app` makes `klad.app` and a disk image in `dist/`; `just dist` packs this machine's build as an archive. Each machine builds for itself: a Mac builds the Mac version, Linux the Linux one.## What's roughdiff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rsindex d05d6c5..ea6f9ff 100644--- a/crates/app/src/editor/ui_tests.rs+++ b/crates/app/src/editor/ui_tests.rs@@ -1848,15 +1848,19 @@ fn checking_the_pixels_marks_the_places_and_follows_edits_until_it_is_turned_off);h.state_mut().apply(vec![pixel(- serde_json::json!([[12, 10], [13, 10], [13, 11], [14, 11], [14, 12], [15, 12]]),+ serde_json::json!([[12, 10], [13, 11], [14, 11], [14, 12], [15, 13]]),"#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)+ .iter()+ .filter(|(kind, _)| *kind == Kind::Corner)+ .map(|(_, at)| *at)+ .collect::<Vec<_>>(),+ [[14, 11]],+ "a diagonal line with one L in it is marked at the corner: {:?}",kinds(&h));h.state_mut().invoke(Cmd::CheckPixels).unwrap();diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rsindex 1cd58af..50d0c7e 100644--- a/crates/cli/src/main.rs+++ b/crates/cli/src/main.rs@@ -2000,7 +2000,7 @@ enum Command {},#[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."+ 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 a lone 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, steps that go on all the way, and the edges of shapes are 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,diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rsindex 92824a5..fd36591 100644--- a/crates/cli/tests/binary.rs+++ b/crates/cli/tests/binary.rs@@ -1985,9 +1985,10 @@ fn klad_check_lists_the_slips_of_pixel_art_with_their_places() {....i...................\n\.....iiii...............\n\........................\n\- ii......................\n\+ i.......................\n\.ii.....................\n\- ..i.....................\n",+ ..i.....................\n\+ ...i....................\n",).unwrap();draw(&["pixel", path, "body", "--grid", grid.to_str().unwrap()]);@@ -2006,7 +2007,7 @@ fn klad_check_lists_the_slips_of_pixel_art_with_their_places() {line("stray pixel").contains("16,0") && line("stray pixel").contains("ink"),"{listed}");- assert!(line("doubled corner").contains("1,8"), "{listed}");+ assert!(line("doubled corner").contains("2,9"), "{listed}");assert!(line("jagged line").contains("4,5") && line("jagged line").contains("a run of 1 between runs of 4 and 4"),"{listed}"diff --git a/crates/core/src/pixelcheck.rs b/crates/core/src/pixelcheck.rsindex 280d786..1e972d3 100644--- a/crates/core/src/pixelcheck.rs+++ b/crates/core/src/pixelcheck.rs@@ -126,22 +126,39 @@ fn strays(field: &Field) -> Vec<Finding> {.collect()}-fn corners(field: &Field) -> Vec<Finding> {+fn elbow(field: &Field, cell: Cell, key: &str) -> Option<[Cell; 2]> {const BESIDE: [Cell; 4] = [(0, -1), (1, 0), (0, 1), (-1, 0)];+ 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 None;+ };+ 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);+ let meant = field.arm(cell, *a, key) >= ARM && field.arm(cell, *b, key) >= ARM;+ (square && !field.is(inside, key) && !meant).then_some([(cell.0 + a.0, cell.1 + a.1), (cell.0 + b.0, cell.1 + b.1)])+}++fn corners(field: &Field) -> Vec<Finding> {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 {+ let Some(arms) = elbow(field, *cell, key) 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)+ let thin = field.same(*cell, key).len() <= 3;+ let alone = arms.iter().all(|arm| elbow(field, *arm, key).is_none());+ let goes_on = arms.iter().any(|arm| {+ field+ .same(*arm, key)+ .iter()+ .map(|(dx, dy)| (arm.0 + dx, arm.1 + dy))+ .any(|next| next != *cell && !arms.contains(&next))+ });+ thin && alone && goes_on}).map(|(cell, key)| Finding {kind: Kind::Corner,@@ -441,20 +458,15 @@ mod tests {#[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 slip = ["i....", ".ii..", "..i..", "...i."];+ assert_eq!(found(&slip, Kind::Corner), [([2, 1], [2, 1])]);let clean = ["i....", ".i...", "..i..", "...i."];assert!(found(&clean, Kind::Corner).is_empty());+ let stairs = ["ii...", ".ii..", "..ii.", "...ii"];+ assert!(+ found(&stairs, Kind::Corner).is_empty(),+ "steps all the way are a diagonal two pixels wide, not a slip"+ );let boxed = ["iiiii", "i...i", "i...i", "iiiii"];assert!(found(&boxed, Kind::Corner).is_empty(),@@ -470,6 +482,16 @@ mod tests {[([4, 0], [4, 0])],"a short arm is not a box");+ let blob = ["ii.", "i..", "..."];+ assert!(+ found(&blob, Kind::Corner).is_empty(),+ "three pixels are a cluster, not a line"+ );+ let wedge = ["..iii", "iii..", "ii...", "i...."];+ assert!(+ found(&wedge, Kind::Corner).is_empty(),+ "the stepped edge of a shape is not a line"+ );}#[test]diff --git a/docs/DESIGN.md b/docs/DESIGN.mdindex 66e8b51..b57b3f1 100644--- a/docs/DESIGN.md+++ b/docs/DESIGN.md@@ -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 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.+- **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, in a thin line that goes on, whose two neighbours are not such corners themselves (a doubled corner, as against a box corner, a staircase that is a two-pixel diagonal, the stepped edge of a shape or a three-pixel cluster; the sprout sample's legs and highlight showed the need for those exceptions); 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 a73be76..acd709c 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -3480,7 +3480,7 @@ Options: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)+ doubled corner a lone 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, steps that go on all the way, and the edges of shapes are left alone)jagged line a short run between two longer ones in a one-pixel line, a step that breaks its rhythmbanding 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 moreoff the palette pixels in a colour that is not a palette entrydiff --git a/docs/guide/exporting.md b/docs/guide/exporting.mdindex be5f7fd..13ae662 100644--- a/docs/guide/exporting.md+++ b/docs/guide/exporting.md@@ -1,4 +1,4 @@-_Last updated: 2026-11-08 14:50_+_Last updated: 2026-11-12 23:55_# Exporting@@ -7,11 +7,15 @@ Export a picture, numbered frames or a sprite sheet, or send your animation stra## Export a picture or frames1. Press **cmd E**.-2. Pick **image** for the frame you're on, **frames** for one PNG per frame, or **sprite sheet**.+2. Pick **image** for the frame you're on, **frames** for one PNG per frame, **sprite sheet**, or **GIF** for an animated picture.3. Click **export**. Without a path, the files go next to the drawing.Pictures are transparent unless you tick **keep the background colour**. A sprite sheet comes with a JSON file in Aseprite's layout, with a tag per clip.+## Export palette variants++If the drawing has [palette variants](pixel-art.md), select **every variant** under **palette variant** before you click **export**. You get one file for each, with the variant's name in the file name.+## Export into a Godot project1. In the timeline, click a clip's bar.diff --git a/docs/guide/meta.json b/docs/guide/meta.jsonindex 520c442..d83db9e 100644--- a/docs/guide/meta.json+++ b/docs/guide/meta.json@@ -1,4 +1,4 @@{"title": "Guides",- "pages": ["getting-started", "painting", "layers", "selecting", "filling", "shapes-and-text", "animating", "bones", "exporting", "with-an-agent"]+ "pages": ["getting-started", "painting", "layers", "selecting", "filling", "shapes-and-text", "pixel-art", "animating", "bones", "exporting", "with-an-agent"]}diff --git a/docs/guide/pixel-art.md b/docs/guide/pixel-art.mdnew file mode 100644index 0000000..7c2ce74--- /dev/null+++ b/docs/guide/pixel-art.md@@ -0,0 +1,46 @@+_Last updated: 2026-11-12 23:50_++# Drawing pixel art++Draw sprites and tiles on a grid where one pixel is one pixel, in the colours of a palette, and export them sharp.++++## Start a pixel drawing++1. In the start window, select **Pixel art** and choose a size, such as 32 x 32.+2. Click **Create**. The drawing opens enlarged, with a grid between the pixels, and the **Real size** panel shows it at the size it really is.++## Draw and erase++1. Press **B** and draw. Each pixel takes the current colour, and the colour joins the palette.+2. Shift click to draw a straight line from the last pixel.+3. Press **E** and drag to clear pixels.+4. Press **G** and click inside a shape to fill it, or **U** to drag a rectangle, an ellipse or a line.++To change a colour everywhere, click it in the palette, change the colour, and click **update**.++## Shade along a ramp++1. Click a palette colour and click **ramp**. Five steps of it join the palette, dark to light.+2. Draw a shape with the middle step.+3. In the pencil's options, select **darker** or **lighter** and go over the pixels: each one moves a step along its ramp.++## Check your pixels++Select **Layer > Check the pixels**. Single pixels, doubled corners, jagged lines, banding and colours outside the palette get a box on the canvas. The boxes follow your edits; select it again to turn it off.++## Make a tile or a tileset++- For one tile that repeats, select **View > Tile: wrap at the edges**. What you draw past an edge comes back in on the other side.+- For a set of tiles, select **View > Tileset: cut into tiles…**, enter the tile size, and click **cut into tiles**. The canvas shows the tile lines.++## Export it sharp++1. Press **cmd E**.+2. Pick **image**, **GIF**, **sprite sheet** or **Aseprite**.+3. Set **times real size** to a whole number, such as 8, and click **export**.++A tileset goes to Godot with **as a tile set** in the same window. For other colourings of the same sprite, see [palette variants](exporting.md#export-palette-variants).++Working with an agent? Give it `klad skill` and `klad skill pixel`: [With an agent](with-an-agent.md).diff --git a/docs/guide/with-an-agent.md b/docs/guide/with-an-agent.mdindex a7151f3..fa2bd95 100644--- a/docs/guide/with-an-agent.md+++ b/docs/guide/with-an-agent.md@@ -1,4 +1,4 @@-_Last updated: 2026-11-08 14:50_+_Last updated: 2026-11-12 23:55_# Working with an agent@@ -7,7 +7,7 @@ Let an agent you already use, such as Claude Code or Codex, paint into the drawi## Set it up1. In the document menu at the foot of the tool strip, click **install the klad command**.-2. Ask your agent to run `klad skill` and read what it prints.+2. Ask your agent to run `klad skill` and read what it prints. For pixel art, ask it to run `klad skill pixel` too.3. Copy the drawing's path from the File menu and tell the agent what you want: "Paint a lantern on its own layer in art.klad, lit from the left."## Point at somethingdiff --git a/docs/images/guide-pixel.png b/docs/images/guide-pixel.pngnew file mode 100644index 0000000..485f0ffBinary files /dev/null and b/docs/images/guide-pixel.png differdiff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.mdindex 56f13c0..b700f05 100644--- a/docs/skill/SKILL.md+++ b/docs/skill/SKILL.md@@ -145,7 +145,7 @@ 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`.+- 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` (a lone L in a one-pixel line, where it reads thick; corners whose arms are both two pixels or longer, as on a box, regular steps and the edges of shapes 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, 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.diff --git a/justfile b/justfileindex ded8629..6e1899c 100644--- a/justfile+++ b/justfile@@ -23,7 +23,7 @@ lint:cargo clippy --workspace --all-targets -- -D warningssamples: compile- for s in lantern ink-shapes bounce creature courier solids lemons ruin sign tree meadow paintover rig; do FORCE=1 bash samples/$s/build.sh >/dev/null || { echo "samples/$s failed" >&2; exit 1; }; echo "samples/$s"; done+ for s in lantern ink-shapes bounce creature courier solids lemons ruin sign tree meadow paintover rig sprout ground; do FORCE=1 bash samples/$s/build.sh >/dev/null || { echo "samples/$s failed" >&2; exit 1; }; echo "samples/$s"; doneapp:bash packaging/macos/app.shdiff --git a/packaging/samples.sh b/packaging/samples.shindex 9905b9b..37cb53d 100755--- a/packaging/samples.sh+++ b/packaging/samples.sh@@ -9,6 +9,8 @@ mkdir -p "$dest""$python" - "$root/samples" "$dest" "$klad" "$python" <<'PY'import json, os, pathlib, shutil, subprocess, syssrc, dest, klad, python = pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2]), sys.argv[3], sys.argv[4]+def pixel_art(layers):+ return bool(layers) and all(l.get("pixel") or pixel_art(l.get("children", [])) for l in layers)def run(command, env=None):done = subprocess.run(command, env=env, capture_output=True, text=True)if done.returncode != 0:@@ -19,8 +21,10 @@ for entry in json.loads((src / "shipped.json").read_text()):env = dict(os.environ, KLAD=klad, PYTHON=python, FORCE="1")run(["bash", str(bundle.parent / "build.sh"), str(bundle)], env)shutil.copytree(bundle, dest / entry["bundle"], ignore=shutil.ignore_patterns(".cache"))- canvas = json.loads((bundle / "doc.json").read_text())["canvas"]- scale = min(1.0, 336 / max(canvas["width"], canvas["height"]))+ doc = json.loads((bundle / "doc.json").read_text())+ canvas = doc["canvas"]+ side = max(canvas["width"], canvas["height"])+ scale = max(1, 336 // side) if pixel_art(doc["layers"]) else min(1.0, 336 / side)thumb = (dest / entry["bundle"]).with_name(bundle.stem + ".thumb.png")run([klad, "render", str(bundle), "--scale", f"{scale:.4f}", "-o", str(thumb)])shutil.copy2(src / "shipped.json", dest / "shipped.json")diff --git a/samples/README.md b/samples/README.mdindex fba8a72..02f2327 100644--- a/samples/README.md+++ b/samples/README.md@@ -17,5 +17,7 @@ Drawings made from scratch with the `klad` CLI, each from a generator that print| `paintover` | Brushwork from a picture: the lemons repainted with `klad paintover`, and the creature's walk painted over once and carried drawing to drawing with `--like` and `--frames`, so the strokes move with the creature and the background stays still || `rig` | Bones instead of a drawing per frame: a figure in a group with a skeleton, weights from the bones with the head, body and hand held rigidly by their parts, a wave posed at four keys and in-betweened on the bones, a lantern floating on keys, a far plane for parallax, and the Godot rig and parallax scene (`rig-godot/`) || `solids` | Painting stroke by stroke: a sphere, a cube and a cylinder built in 3D with `docs/skill/drawkit.py`, lit, painted with natural strokes |+| `sprout` | Pixel art: a 32 px character on three pixel layers (legs, body, sprout) drawn from text grids with `klad pixel`, a palette of two ramps, an idle of two drawings held and a walk of four, each drawing passing `klad check`, exported as a GIF and a sheet |+| `ground` | A tileset: a 64x48 pixel drawing cut into 16 px tiles (`--tile 16`), grass over dirt as nine pieces, a floating platform, a stone block and a plant, exported as a Godot TileSet |The generated `.klad` bundles and pictures stay out of git.diff --git a/samples/ground/build.sh b/samples/ground/build.shnew file mode 100755index 0000000..33cae2a--- /dev/null+++ b/samples/ground/build.sh@@ -0,0 +1,23 @@+#!/usr/bin/env bash+set -euo pipefail+here="$(cd "$(dirname "$0")" && pwd)"+root="$(cd "$here/../.." && pwd)"+case "$(uname -s)" in+ Darwin) built=target ;;+ Linux) built=target/linux ;;+ *) built=target/windows ;;+esac+klad="${KLAD:-$root/${KLAD_TARGET_DIR:-$built}/release/klad}"+out="${1:-$here/ground.klad}"+if [ -e "$out" ] && [ "${FORCE:-0}" != 1 ]; then+ echo "$out exists and may hold edits made in the editor; give another path, or FORCE=1 to rebuild it from generate.py" >&2+ exit 1+fi+rm -rf "$out"+"$klad" new "$out" --pixel 64x48 --layers 0 --tile 16 >/dev/null+"${PYTHON:-python3}" "$here/generate.py" | "$klad" apply "$out" >/dev/null+"$klad" canvas "$out"+"$klad" check "$out"+"$klad" hash "$out" --no-cache+"$klad" export "$out" --scale 8 -o "${out%.klad}.png"+"$klad" export "$out" --tileset "${out%.klad}-godot" >/dev/nulldiff --git a/samples/ground/generate.py b/samples/ground/generate.pynew file mode 100644index 0000000..68601c6--- /dev/null+++ b/samples/ground/generate.py@@ -0,0 +1,181 @@+import json++T = 16+COLUMNS, ROWS = 4, 3++PALETTE = [+ ("ink", "#231d2b", ""),+ ("grass-1", "#2c5a45", "grass"),+ ("grass-2", "#4a8a3c", "grass"),+ ("grass-3", "#8cc24a", "grass"),+ ("dirt-1", "#4b2f2d", "dirt"),+ ("dirt-2", "#7d5136", "dirt"),+ ("dirt-3", "#b07f4f", "dirt"),+ ("stone-1", "#3c3f52", "stone"),+ ("stone-2", "#6b7084", "stone"),+ ("stone-3", "#a7adbd", "stone"),+ ("petal", "#f2c14e", ""),+]++LEGEND = {+ "k": "ink",+ "d": "grass-1",+ "g": "grass-2",+ "l": "grass-3",+ "s": "dirt-1",+ "b": "dirt-2",+ "t": "dirt-3",+ "n": "stone-1",+ "m": "stone-2",+ "h": "stone-3",+ "p": "petal",+}++PEBBLES = [+ [(3, 7, "ss"), (10, 6, "tt"), (6, 11, "ss"), (12, 12, "tt"), (2, 13, "tt")],+ [(4, 6, "tt"), (11, 8, "ss"), (2, 10, "ss"), (8, 13, "tt"), (12, 12, "ss")],+ [(2, 6, "ss"), (9, 9, "tt"), (5, 12, "tt"), (11, 13, "ss"), (13, 7, "tt")],+ [(5, 3, "ss"), (11, 2, "tt"), (2, 8, "tt"), (8, 7, "ss"), (4, 12, "ss"), (11, 11, "tt")],+ [(3, 2, "tt"), (10, 4, "ss"), (6, 8, "tt"), (12, 9, "ss"), (3, 11, "ss"), (9, 13, "tt")],+ [(6, 2, "ss"), (2, 5, "tt"), (11, 6, "tt"), (4, 9, "ss"), (9, 11, "ss"), (13, 13, "tt")],+]++CAP = [+ "llgllllgllllllgl",+ "gggggggggggggggg",+ "gggggggggggggggg",+ "gddggdddggddgggg",+ "bddbbbbbbbddbbbb",+]+++def tile(fill="."):+ return [[fill] * T for _ in range(T)]+++def dirt(pebbles):+ grid = tile("b")+ for x, y, run in PEBBLES[pebbles]:+ for i, c in enumerate(run):+ grid[y][x + i] = c+ return grid+++def cap(grid):+ for y, row in enumerate(CAP):+ for x, c in enumerate(row):+ grid[y][x] = c+ return grid+++def edge(grid, left=False, right=False, bottom=False, top=False):+ if left:+ for y in range(T):+ grid[y][0] = "d" if grid[y][0] in "gl" else "s"+ if right:+ for y in range(T):+ grid[y][T - 1] = "d" if grid[y][T - 1] in "gl" else "s"+ if bottom:+ grid[T - 1] = ["s"] * T+ if top and left:+ grid[0][0] = "."+ grid[0][1] = "g"+ if top and right:+ grid[0][T - 1] = "."+ grid[0][T - 2] = "g"+ if bottom and left:+ grid[T - 1][0] = "."+ if bottom and right:+ grid[T - 1][T - 1] = "."+ return grid+++PLATFORM = [+ ".gllllgllllllgg.",+ "dggggggggggggggd",+ "dggggggggggggggd",+ "dgddggdddggddggd",+ "sbddbbbbbbbddbbs",+ "sbbbbbbbttbbbbbs",+ "sbbssbbbbbbbbbbs",+ "sbbbbbbbbbbssbbs",+ ".sbbbttbbbbbbbs.",+ "..ssbbbbbbbbss..",+ "....ssssssss....",+ "................",+ "................",+ "................",+ "................",+ "................",+]++STONE = [+ ".hhhhhhhhhhhhhh.",+ "hhmmmmmmmmmmmmmn",+ "hmmmmmmmmmmmmmmn",+ "hmmmmmmmmnnmmmmn",+ "hmmmmmmmnnmmmmmn",+ "hmmmmmmmnmmmmmmn",+ "hmmhhmmmmmmmmmmn",+ "hmmhmmmmmmmmmmmn",+ "hmmmmmmmmmmmmmmn",+ "hmmmmmmmmmmhhmmn",+ "hmmmnnmmmmmhmmmn",+ "hmmnnmmmmmmmmmmn",+ "hmmmmmmmmmmmmmmn",+ "hmmmmmmmmmmmmmnn",+ "hnnnnnnnnnnnnnnn",+ ".nnnnnnnnnnnnnn.",+]++PLANT = [+ "................",+ "................",+ "................",+ "................",+ ".........pp.....",+ "........pkkp....",+ "........pkkp....",+ ".........pp.....",+ "..........d.....",+ "....l.....d.....",+ "....l.....d.....",+ ".l..g.....d..l..",+ ".l..g..l..d..l..",+ "..g.g..l..d.g...",+ "..g.gg.g..d.g...",+ "..gggggggggggg..",+]+++def text(part):+ return [list(row) for row in part]+++TILES = [+ [edge(cap(dirt(0)), left=True, top=True), cap(dirt(1)), edge(cap(dirt(2)), right=True, top=True), text(PLATFORM)],+ [edge(dirt(3), left=True), dirt(4), edge(dirt(5), right=True), text(STONE)],+ [edge(dirt(1), left=True, bottom=True), edge(dirt(0), bottom=True), edge(dirt(2), right=True, bottom=True), text(PLANT)],+]+++def main():+ canvas = [["."] * (T * COLUMNS) for _ in range(T * ROWS)]+ for row, tiles in enumerate(TILES):+ for column, grid in enumerate(tiles):+ for y in range(T):+ for x in range(T):+ canvas[row * T + y][column * T + x] = grid[y][x]+ out = [+ {+ "op": "palette",+ "set": [{"color": c, "name": n, **({"ramp": r} if r else {})} for n, c, r in PALETTE],+ },+ {"op": "add", "layer": {"id": "l-tiles", "kind": "pixel", "name": "tiles"}},+ {"op": "pixel", "layer": "l-tiles", "rows": ["".join(row) for row in canvas], "legend": LEGEND},+ ]+ for op in out:+ print(json.dumps(op))+++main()diff --git a/samples/shipped.json b/samples/shipped.jsonindex a8bcef7..21db172 100644--- a/samples/shipped.json+++ b/samples/shipped.json@@ -4,5 +4,7 @@{ "name": "bounce", "bundle": "bounce/bounce.klad", "about": "frame by frame: keys, holds and a clip" },{ "name": "creature", "bundle": "creature/creature.klad", "about": "a walk and an idle from keys, in-betweened" },{ "name": "rig", "bundle": "rig/rig.klad", "about": "a figure posed with bones, and a lantern on keys" },- { "name": "ruin", "bundle": "ruin/ruin.klad", "about": "a game background in depth planes, lit by one lantern" }+ { "name": "ruin", "bundle": "ruin/ruin.klad", "about": "a game background in depth planes, lit by one lantern" },+ { "name": "sprout", "bundle": "sprout/sprout.klad", "about": "pixel art: a character with an idle and a walk" },+ { "name": "ground", "bundle": "ground/ground.klad", "about": "pixel art: a tileset of 16 px tiles for Godot" }]diff --git a/samples/sprout/build.sh b/samples/sprout/build.shnew file mode 100755index 0000000..21af504--- /dev/null+++ b/samples/sprout/build.sh@@ -0,0 +1,24 @@+#!/usr/bin/env bash+set -euo pipefail+here="$(cd "$(dirname "$0")" && pwd)"+root="$(cd "$here/../.." && pwd)"+case "$(uname -s)" in+ Darwin) built=target ;;+ Linux) built=target/linux ;;+ *) built=target/windows ;;+esac+klad="${KLAD:-$root/${KLAD_TARGET_DIR:-$built}/release/klad}"+out="${1:-$here/sprout.klad}"+if [ -e "$out" ] && [ "${FORCE:-0}" != 1 ]; then+ echo "$out exists and may hold edits made in the editor; give another path, or FORCE=1 to rebuild it from generate.py" >&2+ exit 1+fi+rm -rf "$out"+"$klad" new "$out" --pixel 32x32 --layers 0 --fps 8 --frames 12 >/dev/null+"${PYTHON:-python3}" "$here/generate.py" | "$klad" apply "$out" >/dev/null+"$klad" frames "$out"+"$klad" check "$out" --all+"$klad" hash "$out" --all --no-cache+"$klad" export "$out" --scale 8 -o "${out%.klad}.png"+"$klad" export "$out" --gif --scale 8+"$klad" export "$out" --sheet all -o "${out%.klad}-sheet.png"diff --git a/samples/sprout/generate.py b/samples/sprout/generate.pynew file mode 100644index 0000000..3a3cd44--- /dev/null+++ b/samples/sprout/generate.py@@ -0,0 +1,162 @@+import json++W, H = 32, 32+FPS = 8++PALETTE = [+ ("ink", "#231d2b", ""),+ ("leaf-1", "#2c5a45", "leaf"),+ ("leaf-2", "#4a8a3c", "leaf"),+ ("leaf-3", "#8cc24a", "leaf"),+ ("soil-1", "#4b2f2d", "soil"),+ ("soil-2", "#7d5136", "soil"),+ ("soil-3", "#b07f4f", "soil"),+ ("visor", "#27304f", ""),+ ("eye", "#e9f1ff", ""),+]++LEGEND = {+ "k": "ink",+ "d": "leaf-1",+ "g": "leaf-2",+ "l": "leaf-3",+ "s": "soil-1",+ "b": "soil-2",+ "t": "soil-3",+ "v": "visor",+ "e": "eye",+}++BODY = [+ "......kkkkkk......",+ "....kklllgggkk....",+ "...klllggggggdk...",+ "..kllgggggggggdk..",+ ".klgggggggggggddk.",+ ".kggggggggggggddk.",+ "kgggggggggggggdddk",+ "kggggggggggggddddk",+ "kddddddddddddddddk",+ ".kttbbbbbbvvvvvvk.",+ ".ktbbbbbbvvevvevk.",+ ".kbbbbbbbvvevvevk.",+ "..kbbbbbbbvvvvvk..",+ "...kssbbbbsssvk...",+ "....kkkkkkkkkk....",+]++SQUASH = BODY[:6] + BODY[7:]++SPROUT = {+ "up": [+ "..ll...l....",+ ".lggg.lgg...",+ "..ggg.gg....",+ "....k.k.....",+ ".....k......",+ ],+ "back": [+ ".ll...l.....",+ "lggg.lgg....",+ ".ggg.gg.....",+ "....k.k.....",+ ".....k......",+ ],+ "fore": [+ "...ll...l...",+ "..lggg.lgg..",+ "...ggg.gg...",+ "....k.k.....",+ ".....k......",+ ],+}++LEGS = {+ "stand": [+ "...kk..ss...",+ "...kk..ss...",+ "...kk..ss...",+ "...kkk.kkk..",+ ],+ "tuck": [+ "...kk..ss...",+ "...kk..ss...",+ "...kkk.kkk..",+ ],+ "stride": [+ "..kk...ss...",+ ".kk.....ss..",+ "kk.......ss.",+ "kkk......kkk",+ ],+ "pass-near": [+ "...kk.ss....",+ "...kk.ss....",+ "...kkkss....",+ "......kkk...",+ ],+ "stride-far": [+ "..ss...kk...",+ ".ss.....kk..",+ "ss.......kk.",+ "kkk......kkk",+ ],+ "pass-far": [+ "...kk.ss....",+ "...kk.ss....",+ "...kk.kkk...",+ "...kkk......",+ ],+}++def blank():+ return [["."] * W for _ in range(H)]+++def stamp(grid, part, x, y):+ for dy, row in enumerate(part):+ for dx, c in enumerate(row):+ if c != "." and 0 <= y + dy < H and 0 <= x + dx < W:+ grid[y + dy][x + dx] = c+++def rows(grid):+ return ["".join(row) for row in grid]+++POSES = [+ (0, dict(body=BODY, by=8, sprout="up", legs="stand")),+ (4, dict(body=SQUASH, by=9, sprout="back", legs="tuck")),+ (8, dict(body=BODY, by=9, sprout="back", legs="stride")),+ (9, dict(body=BODY, by=8, sprout="up", legs="pass-near")),+ (10, dict(body=BODY, by=9, sprout="fore", legs="stride-far")),+ (11, dict(body=BODY, by=8, sprout="up", legs="pass-far")),+]+BX = 7+++def main():+ out = [+ {+ "op": "palette",+ "set": [{"color": c, "name": n, **({"ramp": r} if r else {})} for n, c, r in PALETTE],+ }+ ]+ cels = [{"frame": start} for start, _ in POSES]+ for layer in ("legs", "body", "sprout"):+ out.append({"op": "add", "layer": {"id": f"l-{layer}", "kind": "pixel", "name": layer, "cels": cels}})+ for frame, pose in POSES:+ legs, body, sprout = blank(), blank(), blank()+ stamp(legs, LEGS[pose["legs"]], BX + 3, pose["by"] + len(pose["body"]) - 1)+ stamp(body, pose["body"], BX, pose["by"])+ stamp(sprout, SPROUT[pose["sprout"]], BX + 3, pose["by"] - 5)+ for layer, grid in (("legs", legs), ("body", body), ("sprout", sprout)):+ out.append({"op": "pixel", "layer": f"l-{layer}", "frame": frame, "rows": rows(grid), "legend": LEGEND})+ out.append({"op": "clip", "add": "idle", "from": 0, "to": 7, "loop": True})+ out.append({"op": "clip", "add": "walk", "from": 8, "to": 11, "loop": True})+ out.append({"op": "timeline", "origin": [16, 26]})+ for op in out:+ print(json.dumps(op))+++main()