Skip to content

Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.

feat(pixel-draw): a style of your own, sets of up to 64 frames drawn four a call, one motion, and the GIF's frame time

Soohong Kim7642e1061abe
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b6013ed..07bad14 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,13 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the
## Unreleased
- **New: `background-tile --axis xy` makes one tile seamless in both directions and measures both joins.** It quilts along x, then along y with a cyclic seam: the second seam's two ends, which meet across the x wrap, may differ by one step at most, so the second quilt cannot break the first one's join. The report measures the finished tile on both axes (`axes.x`, `axes.y`, each with its join, quilt seam, `status` and reasons); the top-level `status` is `needs-review` when either axis is, and each reason names its axis. Two separate one-axis runs had no such rule, and the second run's report measured only its own axis. `inspect_tile_xy(image)` measures both joins of any tile ([asset-tools](docs/asset-tools.md#both-axes-a-ground-tile)).
+- **New: `pixel-draw` draws a set of up to 64 frames, four a call.** One call still draws at most four frames, so the frames of one answer share a palette and a design; a longer set — a hand-drawn motion of several seconds — is drawn four at a time, one call after another. Every call's prompt names all the frames and which ones it draws; each call after the first writes the first call's palette again — a colour it adds is refused and the rows that use it go to the row repair, a colour it changes is put back, both recorded in G1's `recovered` (`palette_added`, `palette_changed`) — and is shown the first frame and the four just before its own, as the grid it writes (about 6,000 input tokens at 48 px, by the characters a token Opus's own answers wrote). The row repair and the one redraw are each call's own (`c1-part2-gen1`, `c1-part2-gen1-fix1`, `c1-part2-gen2`), the gates run once every frame is drawn, `--resume` reads every call back, and stderr says before the first request how many calls and tokens the set may take. A `--spec` frame may be `{"name": ..., "pose": ...}`, which puts that pose on the frame's own line of its call's prompt. Previews put the frames in rows of eight, and a pick sheet larger than Claude reads unscaled (2576 px on the long edge, 4784 patches, read off Claude's vision page on 2026-10-15) is drawn at the largest smaller whole enlargement that fits, nearest-neighbour, instead of being blurred by the API's downscale. The report's candidates carry `parts`. An effect stays 2–8 frames in one call ([pixel-draw](docs/pixel-draw.md#more-than-four-frames)).
+- **New: `pixel-draw --style TEXT` draws in a style of your own.** It takes the place of the kind's style sentence (a sprite's "a dark (not pure black) outline around the silhouette, 2-3 shades per material, light from the top-left …") and of nothing else: the transparent background, the safe area and the floor row, a tile's seams and an effect's centre stay. The pick judges craft against the same words in place of its fixed "clean silhouette and outline". Without `--style` both prompts are byte for byte what they were. Same name and meaning as `prepare --style`; spec key `style`; `request.style` in the report ([pixel-draw](docs/pixel-draw.md#the-style)).
+- **New: `pixel-draw --motion TEXT`: the frames, in their order, are one motion.** The prompt says so in your words, and G6 takes the rule of one motion, written once in the header of `pixel_gates.py`: a frame off the ground row still fails, but a height that changes (an arm raised over the head, a blade swung past it) is asked whether the body changed size or only its pose, by the reading `video-loop --body-height` already makes of a cut (`video.gait_fallback.size_change` on height, mass and breadth) — a pose is an info line, a body drawn at another size warns — and a frame drawn twice is a hold, an info line. `gates.G6` then has `rule: "motion"`, `size_change`, `resized`, `posed` and `holds`. Same name and meaning as `video-prompt --motion`; spec key `motion`; also on `--grid` ([pixel-draw](docs/pixel-draw.md#gates)).
+- **Behavior change: a `pixel-draw --walk-cycle` is one motion.** Its two passing frames drawn alike, or a height that changes by more than a pixel with the pose, no longer fail G6: they are info lines, and a body drawn at another size warns. A walk cycle still fails off the ground row, and still warns when its legs barely change sides.
+- **New: `pixel-draw --duration-ms N` times `anim.gif`** (and an effect's `delay_ms`), 150 ms by default as before, at least 10; spec key `duration_ms`, also on `--grid`. Same name and meaning as `compose-cycle --duration-ms`.
+- **Docs: `pixel-draw`'s note that only effort xhigh spent every token thinking and wrote nothing is corrected** — a set of four 48 px frames at effort high did too (2026-10-14).
+- **Tests** — `tests/gen/test_pixel_draw_frames.py` (a set of six drawn in two calls, the second holding the first's palette with a colour it added refused and repaired, shown the frames before it and carrying its frames' poses, read back whole on `--resume`; a later call shown the first frame and the four just before its own; a call drawn again on its own one effort lower; a call that fails ending its candidate; each call its own batch; spec frames refused; `--style` in the drawing and the pick of every kind with the structure kept; the default drawing and pick prompts frozen byte for byte from before; `--motion` refused for one frame and for an effect; a synthetic 48 px set of 46 frames of one motion — an arm raised for ten frames and held for four — passing `--grid` with `--motion`, and failing without it; `--duration-ms` in `anim.gif` and an effect's strip; a pick sheet of 46 frames for two candidates drawn at ×3 within Claude's unscaled size), `tests/gen/test_pixel_gates.py` (G6 of one motion lets a raised arm and a hold through, fails a frame off the ground and warns a body drawn larger; a walk cycle is one motion) and `tests/gen/test_pixel_grid.py` (a palette held, with a colour added and one changed; parts joined; previews in rows of eight).
- **Fix: a `pixel-draw` answer that writes its block more than once is read from the last block that reads whole.** An answer sometimes writes a first try — the palette and `END` with no frame — then "Corrected:" and the whole block (seen 2026-10-15 on a 16 px icon); G1 read the first block, found the frame missing and drew the candidate again. Now every block is read and the last one that reads whole is the answer (when none does, the last whose rows the row repair can fix), recorded in G1's `recovered` as `block_many` with which block was read. An answer of one block is read as before.
- **Tests** — `tests/gen/test_pixel_grid.py` (several blocks read from the last whole one, or the last with rows to repair; one block as before) and an answer of two blocks drawn once in `tests/gen/test_pixel_draw.py`.
- **New: alpha haze cleanup for transparent sheets (`frames.alpha_floor.clear_haze`).** Pixels at or above a floor, and faint pixels within a few pixels of them (an object's anti-aliased edge), are kept byte for byte; every other faint pixel becomes fully transparent. The report measures the haze share before and after and counts the solid and edge pixels that changed (`0`). Used by `ui-kit` (on by default) and `slice-sheet --alpha-floor N` (off by default; writes `<prefix>alpha-cleanup.json`). `slice-sheet --chroma-key none` cuts a sheet that is already transparent on its own alpha ([sheet-slicing](docs/sheet-slicing.md#transparent-sheets)).
diff --git a/docs/README.md b/docs/README.md
index 14ebe49..026b850 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -80,7 +80,7 @@ grouping is derived from `sprite_gen/_modules.py`, the one taxonomy table.
|---|---|
| [gen.md](gen.md) | `sprite-gen gen` / `gen-set`: providers, default resolution, transparency strategy per provider, when a refused provider request is sent again, row usage |
| [`sprite-gen sound`](sound.md) | Generate normalized SFX and BGM audio assets with Opus and AAC encoding, SQLite raw request caching, and Web Audio loop metadata. |
-| [pixel-draw.md](pixel-draw.md) | `sprite-gen pixel-draw` (experimental): Claude Opus draws 8–48 px pixel art as a pixel grid — the inputs, the safe area, the run folder and its report, gates G1–G8, the row repair and the one redraw, the pick between candidates, Message Batches and `--resume`, re-rendering an edited `grid.txt` |
+| [pixel-draw.md](pixel-draw.md) | `sprite-gen pixel-draw` (experimental): Claude Opus draws 8–48 px pixel art as a pixel grid — the inputs, the safe area, the style (`--style`), a set of up to 64 frames drawn four at a time and one motion (`--motion`), the run folder and its report, gates G1–G8, the row repair and the one redraw, the pick between candidates, Message Batches and `--resume`, re-rendering an edited `grid.txt` |
| [prompt-assembly.md](prompt-assembly.md) | What the engine adds to a still or clip prompt and when: the pieces, the 2.22.0 freeze without `--handed`, what counts as already said, and the notes on the caller's own words |
| [video.md](video.md) | `sprite-gen video` / `video-extend` / `video-edit` / `video-resume`: stills and clips to mp4 through Grok Imagine (image-to-video, last-frame pin, references, extension, editing, asking again for an unfinished generation) with the user's own credential |
| [video-pipeline.md](video-pipeline.md) | Pipeline B engine contract: state canvas, keyed frames, true-period and one-shot cycles, strip/GIF/WebP, the batch, a set's directions on one sheet |
diff --git a/docs/pixel-draw.md b/docs/pixel-draw.md
index cd50bde..5d7637d 100644
--- a/docs/pixel-draw.md
+++ b/docs/pixel-draw.md
@@ -4,7 +4,7 @@
> varies from run to run: expect to compare candidates, re-draw, or touch up `grid.txt` by hand. The numbers below come from a
> small set of measured runs, not from a benchmark.
-> Owns: `sprite-gen pixel-draw`: the inputs, the safe area of a sprite or icon, the run folder and `report.json`, gates G1–G8 and what they take from sprite-gen, the row repair, the one redraw, the pick between candidates, Message Batches and `--resume`, re-rendering an edited `grid.txt` · Index: [docs/README.md](README.md)
+> Owns: `sprite-gen pixel-draw`: the inputs, the safe area of a sprite or icon, the style a drawing is asked in, a set of more than four frames drawn four at a time, the run folder and `report.json`, gates G1–G8 and what they take from sprite-gen, the row repair, the one redraw, the pick between candidates, Message Batches and `--resume`, re-rendering an edited `grid.txt` · Index: [docs/README.md](README.md)
The model does not paint an image that is then shrunk to a grid. It writes the grid itself: a
palette of keys and, per frame, one line of keys per pixel row. Code checks every answer, asks for
@@ -12,8 +12,9 @@ broken rows again one at a time, renders the frames and, among candidates that p
vision call pick. `grid.txt` — the palette and the rows — is the truth of a run; every PNG is
derived from it and can be derived again.
-Use it for a single small asset: an item icon, a prop, a monster, a character still, four facing
-directions, a draft walk cycle, a grass or water tile. It was measured on `claude-opus-5-5` on
+Use it for a small asset: an item icon, a prop, a monster, a character still, four facing
+directions, a draft walk cycle, a grass or water tile — or a hand-drawn motion of up to 64 frames
+([below](#more-than-four-frames)). It was measured on `claude-opus-5-5` on
2026-10-12 (250 drawings of 12 subjects at 16–48 px, judged by a vision model against the same
subjects made with GPT images shrunk by sprite-gen's own functions):
@@ -27,8 +28,9 @@ subjects made with GPT images shrunk by sprite-gen's own functions):
frames: it is a draft for a touch-up, and the run says so (G6 warning). A real loop belongs to the
[video → loop pipeline](video-pipeline.md);
- a fixed palette (`pico8`) was kept every time, at a visible cost in material rendering;
-- dense small-pattern tiles (cobblestones) sometimes spent every token thinking and wrote nothing,
- at effort xhigh only.
+- an answer sometimes spends every token thinking and writes nothing: dense small-pattern tiles
+ (cobblestones) at effort xhigh on 2026-10-12, and a set of four 48 px frames at effort high, all
+ 64,000 tokens, on 2026-10-14 — the run draws it once more one effort lower.
It runs on `ANTHROPIC_API_KEY` and **every call is billed per call** against that key; the run
says so on stderr before the first request leaves, and `report.json` adds up what it cost.
@@ -57,6 +59,26 @@ sprite-gen pixel-draw --out-dir runs/knight-walk --frames walk1,walk2,walk3,walk
# a repeating tile, twenty of them at half price: --batch
sprite-gen pixel-draw --out-dir runs/grass --kind tile --batch \
--subject "A top-down grass ground tile: short green grass with a few lighter blades and small darker tufts."
+
+# one motion of twelve frames, four a call, in a style of its own, at ten frames a second
+sprite-gen pixel-draw --out-dir runs/twirl --spec twirl.json --duration-ms 100
+```
+
+`twirl.json` — a frame is a name, or a name and what that frame shows:
+
+```json
+{
+ "subject": "A small swordsman, side view facing right.",
+ "size": 48,
+ "motion": "he spins the sword once around his hand and catches it",
+ "style": "no outline: selective outlining only where a shape meets its own colour, shadows hue-shifted toward blue",
+ "frames": [
+ {"name": "s01", "pose": "standing, the sword held low"},
+ {"name": "s02", "pose": "the wrist turns, the blade rising"},
+ "s03", "s04", "s05", "s06", "s07", "s08", "s09", "s10", "s11",
+ {"name": "s12", "pose": "the sword caught, back where it started"}
+ ]
+}
```
On success the report is printed on stdout and written to `<out-dir>/report.json`; the picked
@@ -67,11 +89,14 @@ candidate's files are at the top of the run folder.
| Flag | Values (default) | What it does |
|---|---|---|
| `--subject TEXT` | words | What to draw. For several frames, say what each one is (the frame names are listed for the model, their meaning comes from your words). |
-| `--spec FILE` | JSON object | `subject`, `size`, `kind`, `frames`, `walk_cycle`, `palette` instead of the flags. A key given both in the file and as a flag takes the flag, said on one stderr line ([run contract](run-contract.md#1-pipeline-stages)). |
+| `--spec FILE` | JSON object | `subject`, `size`, `kind`, `frames`, `walk_cycle`, `palette`, `style`, `motion`, `duration_ms` instead of the flags; a `frames` entry may be `{"name": ..., "pose": ...}`, which puts that pose on the frame's own line of the prompt. A key given both in the file and as a flag takes the flag, said on one stderr line ([run contract](run-contract.md#1-pipeline-stages)). |
| `--size N` | 8–48 (32) | Canvas side in pixels; every frame is N×N, a sprite's or icon's body about the size of the [safe area](#the-safe-area) (26×26 at 32). Measured best at 32 or less. |
-| `--kind` | `sprite`, `icon`, `tile` (`sprite`) | Sprites and icons have a transparent background, a dark outline and a margin around the body; a tile fills every pixel and repeats seamlessly. |
-| `--frames a,b,…` | 1–4 names (one frame named after `--kind`) | Frames drawn **in one call**, so they share one palette and one design. Names are letters, digits, `_` and `-`. |
-| `--walk-cycle` | flag | The four frames are contact, passing, contact, passing: the prompt says so and G6 checks the legs change sides. |
+| `--kind` | `sprite`, `icon`, `tile` (`sprite`) | Sprites and icons have a transparent background and a margin around the body (and, unless `--style` says otherwise, a dark outline); a tile fills every pixel and repeats seamlessly. |
+| `--frames a,b,…` | 1–64 names (one frame named after `--kind`) | Up to four are drawn **in one call**, so they share one palette and one design; more are drawn four at a time ([below](#more-than-four-frames)). Names are letters, digits, `_` and `-`. |
+| `--walk-cycle` | flag | The four frames are contact, passing, contact, passing: the prompt says so, G6 takes them as one motion and checks the legs change sides. |
+| `--motion TEXT` | words | The frames, in their order, are one motion — the prompt says so in your words, and G6 fails only a frame off the ground row: a height that changes with the pose and a frame held are reported ([gates](#gates)). Not for an effect, whose frames are a lifetime already. |
+| `--style TEXT` | words (the kind's own) | The style to draw in, in place of the kind's style sentence ([below](#the-style)). The pick judges craft against the same words. |
+| `--duration-ms N` | at least 10 (150) | Each frame of `anim.gif` (and an effect's `delay_ms`), in milliseconds; a GIF keeps hundredths of a second. |
| `--palette` | `free[:N]` (`free:16`), `pico8`, `#RRGGBB,…`, or a file | A free palette allows at most N colours; a fixed one allows only its colours. A file is JSON (a list, or `{"colors": [...]}`) or one colour per line (`RRGGBB` or `#RRGGBB`, `;` comments — Lospec's `.hex`). |
| `--candidates K` | 1–6 (2) | Answers drawn for the request, each on its own; one is picked (G7). |
| `--effort` | `medium`, `high`, `xhigh` (`high`) | Thinking effort of each drawing. |
@@ -89,8 +114,10 @@ candidate's files are at the top of the run folder.
For each candidate, independently (in parallel, or in one batch):
1. **Draw** at `--effort`, with the prompt built from the inputs: the subject, the canvas, the frames
- (and the walk cycle), the palette rule, the kind's background, [safe area](#the-safe-area) and
- style rules, and the exact output format.
+ (and the walk cycle or the motion, and what each frame shows), the palette rule, the kind's
+ background, [safe area](#the-safe-area) and [style](#the-style), and the exact output format. A
+ set of more than four frames is drawn four at a time, one call after another
+ ([below](#more-than-four-frames)); steps 2 and 3 are each call's own.
2. **G1 parse.** The answer is read strictly ([below](#gates)). A row one key too long or short, a
key that is not in the palette, rows missing at the end — those rows go back to the model on
their own, each with the rows above and below and a column ruler, and it answers
@@ -99,8 +126,9 @@ For each candidate, independently (in parallel, or in one batch):
3. **Redraw, once.** An answer still broken after its repairs, or broken beyond its rows (no block,
a broken palette, a frame missing, too many rows), is drawn again at the same effort. An answer
that spent all `--max-tokens` thinking and wrote nothing is drawn again **one effort lower**
- (xhigh → high → medium → low). A candidate is drawn at most twice in all.
-4. **G2–G6 and G8** on the pixels. G2, G3 and G6 fail the candidate; G4, G5, the walk check and G8
+ (xhigh → high → medium → low). A call is drawn at most twice; a call that still fails ends its
+ candidate.
+4. **G2–G6 and G8** on the pixels of every frame, once all are drawn. G2, G3 and G6 fail the candidate; G4, G5, the walk check and G8
(a frame past the physical cap, feet off the floor row) warn; G8 also notes a frame past the safe
area within the cap in an info line, which asks for nothing. G3, G4, G5 and G8 are judgments
sprite-gen already makes elsewhere, asked rather than copied ([below](#what-it-takes-from-sprite-gen)).
@@ -157,16 +185,86 @@ two passing frames alike and failed G6, as walk drafts do. Those seven were draw
asked for only a thin detail in the margin and the canvas edge clear; the wording that lets a pose go
past the safe area has not been measured yet.
+## The style
+
+Unless `--style` gives one, each kind is asked for a style of its own, in one sentence of the
+prompt:
+
+| Kind | Style sentence |
+|---|---|
+| `sprite`, `icon` | clean, readable pixel art for a 2D RPG: a dark (not pure black) outline around the silhouette, 2-3 shades per material, light from the top-left, no anti-aliasing noise and no stray single pixels |
+| `tile` | clean, readable pixel art for a 2D RPG: 2-3 shades per material, light from the top-left, no noisy single-pixel speckle |
+| `effect` | none (its background line already says no dark outline and no antialiasing) |
+
+`--style TEXT` (spec `style`) takes that sentence's place, in your words, and only that sentence:
+what the kind must be stays — a transparent background, the [safe area](#the-safe-area) and the
+floor row, a tile that fills every pixel and repeats with no border, an effect around a fixed
+centre. The pick judges craft against the same words in place of its fixed "clean silhouette and
+outline". Without `--style` both prompts are byte for byte what they were, so a run started
+before reads its calls back on `--resume`.
+
+Pixel art without a dark outline, for example, is two habits worth naming:
+
+- **selective outlining** (sel-out): the edge of a shape is a darker shade of its own colour, or
+ of the colour it meets, rather than one dark line around everything, and it drops where the lit
+ side meets the background;
+- **hue shifting**: a shadow moves toward a cooler hue (skin toward red-purple, yellow hair toward
+ green or blue) and a highlight toward a warmer one, instead of only darker and lighter.
+
+```bash
+sprite-gen pixel-draw --out-dir runs/knight-soft --size 48 --subject "A small knight, standing." \
+ --style "no outline: selective outlining only where a shape meets its own colour, shadows hue-shifted toward blue, highlights toward yellow"
+```
+
+## More than four frames
+
+One call draws at most four frames: one answer holds one palette and one design, and that is what
+keeps the frames of a set alike. A set of more frames — up to 64, a hand-drawn motion of several
+seconds — is drawn four at a time, one call after another, in order (an effect stays 2–8 frames in
+one call):
+
+- every call's prompt names all the frames, says which answer it is and which frames it draws
+ (`This is answer 3 of 12: it draws s09, s10, s11, s12 (frames 9-12).`), and carries the motion
+ and what each of its own frames shows;
+- each call after the first is given the first call's palette and writes it again unchanged. A key
+ the answer adds is refused, and the rows that use it go to the row repair under the palette it
+ was given; a colour it changes is put back. Both are recorded in G1's `recovered`
+ (`palette_added`, `palette_changed`);
+- each call after the first is shown the first frame and the four frames just before its own, as
+ the grid the answer writes (a ```` ```reference ```` block), so the motion goes on from where it
+ is and the design from where it began. A frame written as keys is about 1,200 tokens at 48 px
+ (Opus's own answers, recorded 2026-10-12 to 14, wrote 2.0 characters a token at 32 px and 2.5 at
+ 48 px), so the five add about 6,000 input tokens — about $0.02 at the price below — to a call
+ whose thinking and answer run to tens of thousands of output tokens;
+- the row repair and the one redraw are each call's own (`c1-part2-gen1`, `c1-part2-gen1-fix1`,
+ `c1-part2-gen2`); a call that still fails ends its candidate, and the gates run once every frame
+ is drawn;
+- `--resume` reads every call back by its id: a later call's prompt is built from the answers
+ before it, so it is the same prompt again. With `--batch`, each call is a batch of its own,
+ since the next one needs the frames before it.
+
+Before the first request, the run says on stderr what it is about to draw — `[pixel-draw] 46
+frames (at most 64): 12 calls a candidate of at most 4 frames each, 24 drawings in all; each may
+write up to 64000 output tokens, thinking included, and each call after a candidate's first also
+reads its palette and up to 5 frames already drawn, about 5880 input tokens`.
+
+The previews and the pick sheet put the frames in rows of eight. Claude 4.7 and later models read an
+image unscaled up to 2576 px on its long edge and 4784 patches of 28×28 px; a larger one is scaled
+down, which blurs pixel art ([vision](https://platform.claude.com/docs/en/build-with-claude/vision),
+"Resolution and token cost", read 2026-10-15). A sheet past that is drawn at the largest smaller
+whole enlargement that fits — nearest-neighbour, so every pixel stays a square block (46 frames at
+48 px, two candidates: ×3 instead of ×5).
+
## Gates
| Gate | Checks | On failure |
|---|---|---|
-| G1 parse | One block; palette lines `<key> #RRGGBB` (`.` is transparent and nothing else); the frames asked for, each exactly N rows of N palette keys | Row issues → row repair (two rounds), then one redraw; anything else → one redraw. Recovered by code and recorded: a single frame written without its `FRAME` line or under another name, frames in another order, the fence tagged otherwise, no `END` line; an answer that writes its block more than once — a first try, then "Corrected:" and the block again — is read from the last block that reads whole (when none does, the last whose rows can be repaired), `block_many` saying which |
+| G1 parse | One block; palette lines `<key> #RRGGBB` (`.` is transparent and nothing else); the frames asked for, each exactly N rows of N palette keys | Row issues → row repair (two rounds), then one redraw; anything else → one redraw. Recovered by code and recorded: a single frame written without its `FRAME` line or under another name, frames in another order, the fence tagged otherwise, no `END` line; an answer that writes its block more than once — a first try, then "Corrected:" and the block again — is read from the last block that reads whole (when none does, the last whose rows can be repaired), `block_many` saying which; a later call's palette held to the first call's (`palette_added`, `palette_changed`, [above](#more-than-four-frames)) |
| G2 palette | Opaque colours used ≤ the limit; a fixed palette's colours only | fails |
| G3 alpha | Each frame's background by the judgment `gen` reads a generated raw by (`alpha_verdict`, [gen.md](gen.md#transparent-output--strategy-per-provider)): `real-alpha` is at least 5 % of the pixels and half the one-pixel border alpha 0, `no-alpha` none. Sprite/icon: `real-alpha`, something drawn, four transparent corners. Tile: `no-alpha` | fails |
| G4 tile seam | Each tile frame's join along x and along y, by the measure `background-tile` reports (`inspect_tile`, [asset-tools.md](asset-tools.md#repeating-tiles)): the wrap edge against the tile's own neighbours | warns where it says `needs-review`, with its reasons — a local measure, never proof that the tile repeats cleanly; look at `tiled-3x3.png` |
| G5 stray pixels | Lone pixels of a sprite/icon by the judgment the matte cleanup erases them by (`isolated_dots`, [chroma-alpha.md](chroma-alpha.md#chromamode-ycbcr--chrominance-plane-matting-opt-in)): opaque, with no opaque pixel among their eight neighbours — a pixel touching another only at a corner, as in a diagonal stroke, is joined | warns |
-| G6 frames | Same bottom row in every frame, heights within one pixel, no two frames the same; a sprite's or icon's rows are measured inside the [safe area](#the-safe-area), so a staff raised or a spark into the margin in one frame is not a taller figure (the margin is G8's). With `--walk-cycle`: the contact frames differ by at least 40% of the mean contact↔passing difference | fails; the walk check warns ("weak leg alternation — touch up the legs") |
+| G6 frames | Same bottom row in every frame, heights within one pixel, no two frames the same; a sprite's or icon's rows are measured inside the [safe area](#the-safe-area), so a staff raised or a spark into the margin in one frame is not a taller figure (the margin is G8's). With `--motion` or `--walk-cycle` the frames are one motion, whose rule is written once, in the header of [`pixel_gates.py`](../sprite_gen/gen/pixel_gates.py): only the ground row fails; a height that changes is asked whether the body changed size or only its pose. With `--walk-cycle`: the contact frames differ by at least 40% of the mean contact↔passing difference | fails; of one motion, a body that changes size warns, and a height that changes with the pose and a frame held are info lines; the walk check warns ("weak leg alternation — touch up the legs") |
| G8 safe area | Sprite/icon: each frame's opaque box against the [safe area](#the-safe-area) and the physical cap, by the pixel snap's own judgment (`safe_area_fit`, [pixel-unfake.md](pixel-unfake.md#pixel_unfake-mode)); a sprite's body box ending on the floor row | never fails: past the physical cap, and feet off the floor row, warn; past the safe area within the cap is an info line (`info`), which asks for nothing. Below 11 px the margin is 0: the safe area and the cap are the canvas |
| G7 pick | Two or more passed: the vision pick (or a person) | a pick that fails ends the run `pick_failed`, candidates kept |
@@ -183,6 +281,10 @@ answers a question the verb asks, it asks that function; a part that is its own
| G5 stray pixels | `frames.extract.isolated_dots`, the YCbCr matte cleanup's lone pixels | [chroma-alpha.md](chroma-alpha.md#chromamode-ycbcr--chrominance-plane-matting-opt-in) |
| G8 safe area | `frames.extract.safe_area_fit`, the pixel snap's judgment; a frame's opaque box, `frames.extract.solid_alpha_bbox` | [pixel-unfake.md](pixel-unfake.md#pixel_unfake-mode) |
| `--spec` and a flag with the same key | `gen.base.flags_over_spec`, `prepare --request`'s answer: the flag wins, said on one line | [run-contract.md](run-contract.md#1-pipeline-stages) |
+| G6 of one motion: a height that changed — the body's size, or its pose? | `video.gait_fallback.size_change` on `body_size` (height, mass, breadth), the reading `video-loop --body-height` makes of a cut against the clip's first frame, asked of each frame against the first inside the safe area | [video-pipeline.md](video-pipeline.md) (`--body-height`) |
+| `--style`'s name and meaning: a style in the caller's words | `prepare --style` | [run-contract.md](run-contract.md#1-pipeline-stages) |
+| `--motion`'s name and meaning: the motion in the caller's words | `video-prompt --motion` | [prompt-assembly.md](prompt-assembly.md#the-callers-own-words) |
+| `--duration-ms`'s name and meaning: a GIF frame's time in milliseconds | `compose-cycle --duration-ms` | — |
| A call sent again, and the wait | `gen.retry`, every direct provider call's rule | [gen.md](gen.md#a-refused-request-sent-again) |
| A palette colour read and written | `util.hexcolor` | — |
| `run(**kwargs)` | `util.cli_kwargs.namespace_from_kwargs` | — |
@@ -198,7 +300,12 @@ do not), G2's count against the rule, G6 (one pixel of height across a drawn set
check is for a frame the matte broke, under 35 % or over 275 % of the median frame's area), the walk check (the
video path's legs read a filmed cycle's steps, not whether two drawn contact frames swap legs), the
3×3 tiling, the vision pick, Message Batches and `--resume` (`video-resume` asks xAI again by request
-id; a batch is collected, and every answered call read back), and the cost in `report.json`.
+id; a batch is collected, and every answered call read back), the cost in `report.json`, a set drawn
+over several calls with its palette held and its frames shown (nothing else in sprite-gen draws a
+grid in parts), an answer that writes its block more than once, and the pick sheet kept within what
+Claude reads unscaled (no other verb sends Claude a sheet that large). G6's height within one pixel
+stays its own for frames that are not one motion; a motion asks the image path's size reading
+above.
## The run folder
@@ -209,9 +316,9 @@ id; a batch is collected, and every answered call read back), and the cost in `r
grid.txt the picked candidate's grid: the truth, editable, diffable
palette.json its keys and colours, the rule, the colours used
frame-<name>.png each frame at its own size, byte for byte reproducible
- preview-x<s>.png the frames side by side, nearest-neighbour ×s (about 256 px a frame)
+ preview-x<s>.png the frames side by side in rows of eight, nearest-neighbour ×s (about 256 px a frame)
tiled-3x3.png a tile repeated 3×3 (×s)
- anim.gif two or more frames, 150 ms each (×s)
+ anim.gif two or more frames, --duration-ms each (150 ms; a frame held is one GIF frame shown as long) (×s)
candidates/c1/… the same files for every candidate whose grid parsed whole
calls/<id>.json every model call: prompt, answer, thinking summary, usage, request id
batches/<id>.json every batch submitted, the moment it was
@@ -230,11 +337,11 @@ zlib build. The previews, the tiling and the GIF are views for the eye.
| Field | |
|---|---|
| `status` | `ok`, `failed` (no candidate passed), `refused` (every candidate refused), `pick_failed`, `unfinished` (a batch not collected yet) |
-| `request` | the resolved inputs (`palette` with its rule and colours) |
+| `request` | the resolved inputs (`palette` with its rule and colours; `style`, `motion`, `poses` and `duration_ms`) |
| `chosen`, `files`, `warnings`, `info` | the picked candidate, its top-level files, its warnings (worth a look, maybe a redraw) and its info lines (nothing to do) |
| `pick` | `by` (`vision` / `only` / `human`), `best`, and for the vision pick its `labels`, `sheet` and `verdict` |
-| `candidates[]` | per candidate: `status`, `reason`, `effort` of the answer kept, `generations` (call ids), `redraws` (after which call, why, at which effort), `repairs` (rows asked, answered, still broken), `G1` (issues and what was recovered), `gates` (G2–G6 and G8 with their measures), `warnings`, `info`, `files` |
-| `calls[]` | per call: `id` (`c1-gen1`, `c1-gen1-fix1`, `pick`), `purpose`, `mode` (`realtime` / `batch`), `model`, `effort`, `max_tokens`, `request_id`, `message_id`, `batch_id`, `stop_reason`, `stop_details`, `usage` (as the API reported it), `thinking_tokens`, `cost_usd`, `seconds`, and for a failed call `error` and `billed` |
+| `candidates[]` | per candidate: `status`, `reason`, `effort` of the answer kept, `generations` (call ids), `redraws` (after which call, why, at which effort), `repairs` (rows asked, answered, still broken), `G1` (issues and what was recovered), `gates` (G2–G6 and G8 with their measures), `warnings`, `info`, `files`, and for a set drawn over several calls `parts` (each call's frames and the effort it was drawn at; `effort` is then the lowest) |
+| `calls[]` | per call: `id` (`c1-gen1`, `c1-gen1-fix1`, `c1-part2-gen1` for a set drawn over several calls, `pick`), `purpose`, `mode` (`realtime` / `batch`), `model`, `effort`, `max_tokens`, `request_id`, `message_id`, `batch_id`, `stop_reason`, `stop_details`, `usage` (as the API reported it), `thinking_tokens`, `cost_usd`, `seconds`, and for a failed call `error` and `billed` |
| `batches[]` | per batch: `id`, `custom_ids`, `submitted_at`, `collected`, `ended_at`, `waited_seconds` |
| `usage`, `cost_usd`, `seconds` | totals over the calls, and the run's wall time |
@@ -284,14 +391,15 @@ request than the one in `request.json` stops the run rather than being reused.
## Editing `grid.txt` — `--grid`
```bash
-sprite-gen pixel-draw --grid runs/slime/grid.txt --out-dir runs/slime-edit [--kind sprite] [--palette free:16] [--walk-cycle]
+sprite-gen pixel-draw --grid runs/slime/grid.txt --out-dir runs/slime-edit [--kind sprite] [--palette free:16] [--walk-cycle] [--motion TEXT] [--duration-ms N]
```
Reads a character grid (the frames and size are what it holds), runs G1 (no repair: an issue is
reported with its frame and row) and G2–G6 and G8 — the safe area of the grid's own size — and writes
the same files and a report with no calls.
-Pass the `--kind`, `--palette` and `--walk-cycle` the grid was drawn under; the run's
-`request.json` has them.
+Pass the `--kind`, `--palette`, `--walk-cycle` and `--motion` the grid was drawn under; the run's
+`request.json` has them. `--duration-ms` times `anim.gif` anew; `--style` belongs to a drawing and is
+refused here.
## Model, effort and price
diff --git a/sprite_gen/gen/pixel_draw.py b/sprite_gen/gen/pixel_draw.py
index ba42774..98ab702 100644
--- a/sprite_gen/gen/pixel_draw.py
+++ b/sprite_gen/gen/pixel_draw.py
@@ -10,17 +10,24 @@ asked for again on its own.
One run, `--candidates` K answers to the same request:
-1. Each candidate is drawn once at `--effort`. An answer that used all `--max-tokens` thinking
- and wrote nothing is drawn once more one effort lower; a refusal is reported as it came.
+1. Each candidate is drawn once at `--effort`, in one call of at most FRAMES_MAX frames — the
+ frames of one answer share a palette and a design. A set of more frames (up to FRAMES_TOTAL_MAX)
+ is drawn over several calls in order: each later call writes the first call's palette again
+ (`pixel_grid.hold_palette`: a colour added is refused and its rows repaired) and is shown the
+ first frame and the frames just before its own (`drawn_lines`). An answer that used all
+ `--max-tokens` thinking and wrote nothing is drawn once more one effort lower; a refusal is
+ reported as it came.
2. G1 parse. Row issues are repaired one row at a time (`ROW <frame> <n>: …`, two rounds at most);
- an answer still broken, or broken beyond its rows, is drawn once more. A candidate is drawn at
- most twice in all.
-3. G2 palette, G3 alpha and G6 frames fail a candidate; G4 tile seam, G5 stray pixels, the walk
- cycle's leg alternation and G8 safe area (a frame past the physical cap, a sprite off the floor
- row) warn, and G8 notes a frame past the safe area within the cap in an info line. G3, G4, G5
- and G8 are judgments sprite-gen already makes elsewhere, called rather than copied
- (`pixel_gates`). The prompt gives a sprite or icon the engine's safe area (`safe_area_lines`) in
- rows and columns, as a target for the body's size that a pose may go past.
+ an answer still broken, or broken beyond its rows, is drawn once more. Each call is drawn at
+ most twice; a call that fails ends its candidate.
+3. G2 palette, G3 alpha and G6 frames fail a candidate, on every frame once all are drawn; G4 tile
+ seam, G5 stray pixels, the walk cycle's leg alternation and G8 safe area (a frame past the
+ physical cap, a sprite off the floor row) warn, and G8 notes a frame past the safe area within
+ the cap in an info line. Frames of one motion (`--motion`, a walk cycle) take G6's motion rule
+ (`pixel_gates` header). G3, G4, G5, G6's size reading and G8 are judgments sprite-gen already
+ makes elsewhere, called rather than copied (`pixel_gates`). The prompt gives a sprite or icon the
+ engine's safe area (`safe_area_lines`) in rows and columns, as a target for the body's size that
+ a pose may go past.
4. G7: of two or more candidates that passed, one vision call (effort low) picks, or a person
does (`--pick human`). One that passed alone is the pick.
@@ -37,12 +44,13 @@ import hashlib
import io
import json
import random
+import re
import shutil
import sys
import threading
import time
from concurrent.futures import ThreadPoolExecutor
-from dataclasses import asdict, dataclass, field
+from dataclasses import asdict, dataclass, field, replace
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable, Generator
@@ -58,20 +66,26 @@ from .anthropic_api import ApiError, Reply
from .base import announce_api_billing, flags_over_spec, print_json
from .pixel_gates import colors_used, evaluate, safe_area
from .pixel_grid import (
- FORMATS, Grid, Issue, PaletteRule, check_rows, frame_name_ok, frame_pixels, palette_rule, parse_answer,
- parse_row_answers, png_bytes, preview_scale, preview_strip, read_grid_text, recovered, row_issues, row_text,
- save_gif, splice, structural, tiled_3x3, to_text, image_of,
+ FORMATS, PREVIEW_COLUMNS, Grid, Issue, PaletteRule, check_rows, frame_name_ok, frame_pixels, hold_palette,
+ joined, palette_rule, parse_answer, parse_row_answers, png_bytes, preview_scale, preview_strip, read_grid_text,
+ recovered, row_issues, row_text, save_gif, splice, structural, tiled_3x3, to_text, image_of,
)
VERB = "pixel-draw"
SIZE_MIN, SIZE_MAX, SIZE_DEFAULT = 8, 48, 32
-FRAMES_MAX = 4
+FRAMES_MAX = 4 # frames one call draws: one answer, one palette, one design
+FRAMES_TOTAL_MAX = 64 # frames one request draws, FRAMES_MAX a call
+DRAWN_SHOWN = 4 # frames just before a later call's own that it is shown, with the first frame
+# Characters of a written grid per token, for the estimate said before a long set is drawn: Opus's
+# own answers recorded 2026-10-12..14 wrote 2.0 characters a token at 32 px, 2.5 at 48 px.
+GRID_CHARS_PER_TOKEN = 2
EFFECT_FRAMES_MAX = 8
EFFECT_FRAMES = ("birth", "peak", "decay", "gone")
KINDS = ("sprite", "icon", "tile", "effect")
CANDIDATES_MIN, CANDIDATES_MAX, CANDIDATES_DEFAULT = 1, 6, 2
EFFORT_CHOICES = ("medium", "high", "xhigh")
EFFORT_DEFAULT = "high"
+EFFORTS = ("low", "medium", "high", "xhigh", "max")
LOWER_EFFORT = {"max": "xhigh", "xhigh": "high", "high": "medium", "medium": "low"}
MAX_TOKENS_SINGLE, MAX_TOKENS_MULTI = 32000, 64000
MAX_TOKENS_MIN = 1024
@@ -81,10 +95,18 @@ PICKS = ("vision", "human")
BATCH_WAIT_DEFAULT = 3600.0
BATCH_POLL_SECONDS = 30.0
GIF_FRAME_MS = 150
-SPEC_KEYS = ("subject", "size", "kind", "frames", "walk_cycle", "palette")
+DURATION_MS_MIN = 10 # a GIF times its frames in hundredths of a second
+SPEC_KEYS = ("subject", "size", "kind", "frames", "walk_cycle", "palette", "style", "motion", "duration_ms")
RUN_FLAGS = ("candidates", "effort", "answer_format", "batch", "max_tokens", "pick")
REPORT_KIND = "sprite-gen-pixel-draw-report"
+# The style sentence a kind is drawn in unless `--style` gives one; what a kind must be — a transparent
+# background, the safe area and the floor, a tile's seams, an effect's centre — stays outside it.
+SPRITE_STYLE = ("clean, readable pixel art for a 2D RPG: a dark (not pure black) outline around the silhouette, "
+ "2-3 shades per material, light from the top-left, no anti-aliasing noise and no stray single pixels.")
+TILE_STYLE = ("clean, readable pixel art for a 2D RPG: 2-3 shades per material, light from the top-left, no noisy "
+ "single-pixel speckle.")
+
SYSTEM = ("You are an expert pixel artist who draws game assets directly as pixel data. "
"What you write is converted to a PNG mechanically, pixel for pixel, with no cleanup: "
"what you write is exactly what ships.")
@@ -128,6 +150,10 @@ class PixelRequest:
batch: bool
max_tokens: int
pick: str
+ style: str | None = None # in place of the kind's style sentence, in the drawing and the pick
+ motion: str | None = None # the frames, in order, are this one motion
+ poses: dict[str, str] = field(default_factory=dict) # frame name -> what that frame shows
+ duration_ms: int = GIF_FRAME_MS # each frame of anim.gif
def to_dict(self) -> dict[str, Any]:
data = asdict(self)
@@ -146,10 +172,21 @@ def _refuse(message: str) -> SystemExit:
return SystemExit(f"{VERB}: {message}")
-def _frames(value: Any, kind: str = "sprite") -> tuple[str, ...]:
- names = [n.strip() for n in value.split(",")] if isinstance(value, str) else value
- if not isinstance(names, list) or not names or not all(isinstance(n, str) and n for n in names):
+def _frames(value: Any, kind: str = "sprite") -> tuple[tuple[str, ...], dict[str, str]]:
+ """The frame names, and what each frame shows where a spec gave it (`{"name": ..., "pose": ...}`)."""
+ items = [n.strip() for n in value.split(",")] if isinstance(value, str) else value
+ if not isinstance(items, list) or not items:
raise _refuse("--frames takes comma-separated frame names, e.g. down,up,left,right")
+ names, poses = [], {}
+ for item in items:
+ if isinstance(item, dict) and set(item) == {"name", "pose"} and isinstance(item["name"], str) \
+ and isinstance(item["pose"], str) and item["pose"].strip():
+ names.append(item["name"])
+ poses[item["name"]] = item["pose"].strip()
+ elif isinstance(item, str) and item:
+ names.append(item)
+ else:
+ raise _refuse('a frame is a name or {"name": ..., "pose": ...} with a pose in words, got ' + repr(item))
bad = [n for n in names if not frame_name_ok(n)]
if bad:
raise _refuse("frame names are letters, digits, '_' or '-' (at most 32): " + ", ".join(map(repr, bad)))
@@ -157,9 +194,30 @@ def _frames(value: Any, kind: str = "sprite") -> tuple[str, ...]:
raise _refuse("frame names must differ: " + ", ".join(names))
if kind == "effect" and not 2 <= len(names) <= EFFECT_FRAMES_MAX:
raise _refuse(f"an effect needs 2..{EFFECT_FRAMES_MAX} frames, got {len(names)}")
- if kind != "effect" and len(names) > FRAMES_MAX:
- raise _refuse(f"at most {FRAMES_MAX} frames in one call, got {len(names)}")
- return tuple(names)
+ if kind != "effect" and len(names) > FRAMES_TOTAL_MAX:
+ raise _refuse(f"at most {FRAMES_TOTAL_MAX} frames, got {len(names)}")
+ return tuple(names), poses
+
+
+def _duration(value: Any) -> int:
+ if not isinstance(value, int) or isinstance(value, bool) or value < DURATION_MS_MIN:
+ raise _refuse(f"--duration-ms is at least {DURATION_MS_MIN}, got {value!r}")
+ return value
+
+
+def _words(value: Any, flag: str) -> str | None:
+ if value is None:
+ return None
+ if not isinstance(value, str) or not value.strip():
+ raise _refuse(f"{flag} is a sentence of words, got {value!r}")
+ return value.strip()
+
+
+def _motion(motion: str | None, kind: str, frames: tuple[str, ...]) -> None:
+ if motion is not None and kind == "effect":
+ raise _refuse("--motion does not apply to an effect (its frames are a lifetime already)")
+ if motion is not None and len(frames) < 2:
+ raise _refuse(f"--motion is two or more frames in order, got {len(frames)}")
def _load_spec(path: Path) -> dict[str, Any]:
@@ -190,7 +248,11 @@ def resolve_request(args: argparse.Namespace) -> PixelRequest:
kind = merged.get("kind", "sprite")
if kind not in KINDS:
raise _refuse(f"--kind is one of {', '.join(KINDS)}, got {kind!r}")
- frames = _frames(merged["frames"], kind) if "frames" in merged else (EFFECT_FRAMES if kind == "effect" else (kind,))
+ frames, poses = _frames(merged["frames"], kind) if "frames" in merged else (
+ EFFECT_FRAMES if kind == "effect" else (kind,), {})
+ style, motion = _words(merged.get("style"), "--style"), _words(merged.get("motion"), "--motion")
+ _motion(motion, kind, frames)
+ duration_ms = _duration(merged.get("duration_ms", GIF_FRAME_MS))
walk_cycle = bool(merged.get("walk_cycle", False))
if walk_cycle and kind == "effect":
raise _refuse("--walk-cycle does not apply to an effect")
@@ -209,15 +271,58 @@ def resolve_request(args: argparse.Namespace) -> PixelRequest:
return PixelRequest(
subject=subject.strip(), size=size, kind=kind, frames=frames, walk_cycle=walk_cycle, palette=rule,
candidates=candidates, effort=args.effort or EFFORT_DEFAULT, answer_format=args.answer_format or "chargrid",
- batch=bool(args.batch), max_tokens=max_tokens, pick=args.pick or "vision",
+ batch=bool(args.batch), max_tokens=max_tokens, pick=args.pick or "vision", style=style, motion=motion,
+ poses=poses, duration_ms=duration_ms,
)
+# ----------------------------------------------------------------------------- calls of at most four frames
+
+@dataclass(frozen=True)
+class Part:
+ """One call's share of a request's frames: call `number` of `count`."""
+
+ number: int
+ count: int
+ frames: tuple[str, ...]
+
+
+def call_parts(request: PixelRequest) -> list[Part]:
+ """The request's frames, FRAMES_MAX a call, in order. An effect is one call of its 2..8 frames."""
+ frames = request.frames
+ if request.kind == "effect" or len(frames) <= FRAMES_MAX:
+ return [Part(1, 1, frames)]
+ chunks = [frames[i:i + FRAMES_MAX] for i in range(0, len(frames), FRAMES_MAX)]
+ return [Part(number, len(chunks), chunk) for number, chunk in enumerate(chunks, 1)]
+
+
+def shown_frames(drawn: Grid) -> list[str]:
+ """What a later call is shown of the frames already drawn: the first, and the DRAWN_SHOWN just before
+ its own. At 48 px a frame written as keys is about 1,200 tokens (GRID_CHARS_PER_TOKEN), so the five
+ add about 6,000 input tokens to a call whose answer and thinking run to tens of thousands."""
+ names = list(drawn.frames)
+ return list(dict.fromkeys([names[0], *names[-DRAWN_SHOWN:]]))
+
+
+def drawn_lines(request: PixelRequest, drawn: Grid) -> list[str]:
+ """The palette and the shown frames already drawn, written as the answer writes them."""
+ names = shown_frames(drawn)
+ if request.answer_format == "chargrid":
+ block = "```reference\n" + to_text(replace(drawn, frames={n: drawn.frames[n] for n in names})) + "```"
+ else:
+ palette = json.dumps(["transparent" if c is None else c for c in drawn.palette.values()])
+ frames = ",\n".join(f' "{n}": [\n' + ",\n".join(" [" + ", ".join(row) + "]" for row in drawn.frames[n]) + "]"
+ for n in names)
+ block = "```reference\n" + f'{{"palette": {palette}, "frames": {{\n{frames}}}}}' + "\n```"
+ return ["Frames already drawn - the first frame and the frames just before this answer's - with the palette, "
+ "for reference; do not write them again:", block]
+
+
# ----------------------------------------------------------------------------- prompts
-def _format_spec(request: PixelRequest) -> str:
+def _format_spec(request: PixelRequest, frames: tuple[str, ...]) -> str:
w = h = request.size
- names = ", ".join(request.frames)
+ names = ", ".join(frames)
if request.answer_format == "chargrid":
return (
"Output format: exactly one fenced code block tagged `pixels`, and nothing after it:\n"
@@ -266,8 +371,22 @@ def safe_area_lines(request: PixelRequest) -> list[str]:
return lines
-def generation_prompt(request: PixelRequest) -> str:
+def _part_line(request: PixelRequest, part: Part) -> str:
+ first = request.frames.index(part.frames[0]) + 1
+ last = first + len(part.frames) - 1
+ which = f"frame {first}" if first == last else f"frames {first}-{last}"
+ line = (f"The {len(request.frames)} frames are drawn {FRAMES_MAX} at a time, over {part.count} answers in order. "
+ f"This is answer {part.number} of {part.count}: it draws {', '.join(part.frames)} ({which}).")
+ if part.number == 1:
+ line += " The answers after it keep this answer's palette and design, so choose them for the whole set."
+ return line
+
+
+def generation_prompt(request: PixelRequest, part: Part | None = None, drawn: Grid | None = None) -> str:
+ """The drawing prompt; for a set drawn over several calls, the prompt of call `part`, shown the
+ frames `drawn` so far after the first call."""
frames = request.frames
+ own = part.frames if part is not None else frames
lines = [f"Draw: {request.subject}", f"Canvas: exactly {request.size}x{request.size} pixels per frame."]
if request.kind == "effect":
lines.append(f"Frames: {', '.join(frames)}. One effect's lifetime: appears, grows to a peak, then disappears. "
@@ -281,7 +400,17 @@ def generation_prompt(request: PixelRequest) -> str:
lines.append(f"The frames are one looping walk cycle: {a} = contact pose with the front leg forward, "
f"{b} = passing pose (legs together, body one pixel higher), {c} = contact pose with the "
f"other leg forward, {d} = passing pose.")
- if request.palette.fixed:
+ if request.motion:
+ lines.append(f"Motion: the frames, in this order, are one continuous motion: {request.motion}")
+ if part is not None and part.count > 1:
+ lines.append(_part_line(request, part))
+ posed = [(name, request.poses[name]) for name in own if name in request.poses]
+ if posed:
+ lines += ["What each frame shows:", *(f"- {name}: {pose}" for name, pose in posed)]
+ if drawn is not None:
+ lines.append("Palette: keep the palette of the frames already drawn, shown below: write it again exactly as "
+ "it is - the same keys and the same colors, no color added and none changed.")
+ elif request.palette.fixed:
lines.append(f"Palette: use only these {len(request.palette.colors)} colors and transparent, no others: "
+ " ".join(request.palette.colors) + ".")
else:
@@ -290,18 +419,19 @@ def generation_prompt(request: PixelRequest) -> str:
lines.append("This is a tile: fill every pixel (no transparency) and make it repeat seamlessly in a grid, "
"so the left edge continues into the right edge and the top edge into the bottom edge. "
"No border or outline around the tile.")
- lines.append("Style: clean, readable pixel art for a 2D RPG: 2-3 shades per material, light from the "
- "top-left, no noisy single-pixel speckle.")
+ lines.append(f"Style: {request.style or TILE_STYLE}")
elif request.kind == "effect":
lines.append("Background: transparent. Draw readable clusters of light; detached sparks are intentional. "
"No dark outline, no ground plane, no antialiasing. Use the full canvas around its fixed center.")
+ if request.style:
+ lines.append(f"Style: {request.style}")
else:
lines.append("Background: transparent.")
lines += safe_area_lines(request)
- lines.append("Style: clean, readable pixel art for a 2D RPG: a dark (not pure black) outline around the "
- "silhouette, 2-3 shades per material, light from the top-left, no anti-aliasing noise and "
- "no stray single pixels.")
- lines += ["", _format_spec(request)]
+ lines.append(f"Style: {request.style or SPRITE_STYLE}")
+ if drawn is not None:
+ lines += ["", *drawn_lines(request, drawn)]
+ lines += ["", _format_spec(request, own)]
return "\n".join(lines)
@@ -311,13 +441,14 @@ def _ruler(n: int) -> str:
def repair_prompt(request: PixelRequest, grid: Grid, issues: list[Issue]) -> tuple[str, list[tuple[str, int]]]:
"""The broken rows with their neighbours (and a column ruler), and the rows to write."""
- wanted = sorted({(i.frame, i.row) for i in issues}, key=lambda fr: (request.frames.index(fr[0]), fr[1]))
+ order = list(grid.frames) # this call's frames, in order
+ wanted = sorted({(i.frame, i.row) for i in issues}, key=lambda fr: (order.index(fr[0]), fr[1]))
broken = {(i.frame, i.row): [] for i in issues}
for issue in issues:
broken[(issue.frame, issue.row)].append(issue)
chargrid = grid.fmt == "chargrid"
parts: list[str] = []
- for name in request.frames:
+ for name in order:
rows = grid.frames[name]
for number, row in enumerate(rows, 1):
found = broken.get((name, number))
@@ -380,17 +511,25 @@ def pick_prompt(request: PixelRequest, labels: list[str]) -> str:
]
if request.kind == "tile":
lines.append("Each tile is shown alone and, to its right, repeated 3x3 so seams are visible.")
- if multi:
+ if multi and len(request.frames) > PREVIEW_COLUMNS:
+ lines.append(f"Each candidate's {len(request.frames)} frames run left to right in rows of {PREVIEW_COLUMNS}, top "
+ f"to bottom, in this order: {', '.join(request.frames)}.")
+ elif multi:
lines.append(f"Each candidate is a row of {len(request.frames)} frames in this order: {', '.join(request.frames)}.")
lines += [
f"The request was: {request.subject} Canvas {request.size}x{request.size} pixels per frame{_kept(request)}.",
"Score every candidate:",
"- subject_read 1-5: how clearly it reads as the requested subject (5 instantly, 1 unrecognisable).",
- "- craft 1-5: pixel-art craft: clean silhouette and outline, consistent shading and light, no noise, sensible "
- "use of the canvas (5 professional, 3 acceptable indie, 1 broken)."
+ (f"- craft 1-5: pixel-art craft judged against the style the request asked for - {request.style} - consistent "
+ "shading and light, no noise, sensible use of the canvas (5 professional, 3 acceptable indie, 1 broken)."
+ if request.style else
+ "- craft 1-5: pixel-art craft: clean silhouette and outline, consistent shading and light, no noise, sensible "
+ "use of the canvas (5 professional, 3 acceptable indie, 1 broken).")
+ (" For tiles, visible seams in the 3x3 repeat count against craft." if request.kind == "tile" else ""),
("- consistency 1-5: a readable lifetime around a fixed center, with a peak and decay; "
"changing extent, detached sparks and an empty final frame are intentional." if request.kind == "effect" else
+ "- consistency 1-5: the same subject, proportions and colours across frames, and the frames following one "
+ f"another as one motion in their order ({request.motion})." if multi and request.motion else
"- consistency 1-5: the same subject, proportions and colours across frames, and correct poses/directions "
"for the frame names." if multi else "- consistency: 0 (single frame)."),
"- verdict: ship (usable in a game as is), touch_up (usable after a few pixel fixes), redraw (not usable).",
@@ -622,15 +761,17 @@ class Candidate:
info: list[str] = field(default_factory=list)
grid: Grid | None = None
files: dict[str, Any] = field(default_factory=dict)
+ parts: list[dict[str, Any]] = field(default_factory=list) # per call of a set drawn over several
def end(self, status: str, reason: str | None = None) -> "Candidate":
self.status, self.reason = status, reason
return self
def to_dict(self) -> dict[str, Any]:
- return {"id": self.id, "status": self.status, "reason": self.reason, "effort": self.effort,
+ data = {"id": self.id, "status": self.status, "reason": self.reason, "effort": self.effort,
"generations": self.generations, "redraws": self.redraws, "repairs": self.repairs, "G1": self.g1,
"gates": self.gates, "warnings": self.warnings, "info": self.info, "files": self.files}
+ return {**data, "parts": self.parts} if self.parts else data
def _g1(issues: list[Issue]) -> dict[str, Any]:
@@ -656,49 +797,78 @@ class Run:
self.batch_wait = batch_wait
self.note = note
- def generation_body(self, effort: str) -> dict[str, Any]:
- return api.message_body(system=SYSTEM, content=generation_prompt(self.request), effort=effort,
+ def generation_body(self, effort: str, part: Part | None = None, drawn: Grid | None = None) -> dict[str, Any]:
+ return api.message_body(system=SYSTEM, content=generation_prompt(self.request, part, drawn), effort=effort,
max_tokens=self.request.max_tokens)
def flow(self, cid: str) -> Generator[Ask, Reply | ApiError, Candidate]:
+ """A candidate's calls, one part after another; the gates once every frame is drawn."""
request = self.request
candidate = Candidate(cid)
+ parts = call_parts(request)
+ drawn: Grid | None = None
+ issues: list[Issue] = []
+ efforts: list[str] = []
+ for part in parts:
+ outcome = yield from self.draw_part(candidate, part, drawn, issues)
+ if isinstance(outcome, Candidate):
+ return outcome
+ grid, part_issues, effort = outcome
+ drawn = grid if drawn is None else joined([drawn, grid])
+ issues += part_issues
+ efforts.append(effort)
+ if len(parts) > 1:
+ candidate.parts.append({"part": part.number, "frames": list(part.frames), "effort": effort})
+ candidate.g1 = _g1(issues)
+ candidate.effort, candidate.grid = min(efforts, key=EFFORTS.index), drawn
+ pixels = {name: frame_pixels(drawn, name) for name in request.frames}
+ candidate.gates = evaluate(pixels, kind=request.kind, rule=request.palette, walk_cycle=request.walk_cycle,
+ motion=bool(request.motion))
+ candidate.warnings, candidate.info = candidate.gates["warnings"], candidate.gates["info"]
+ if candidate.gates["ok"]:
+ return candidate.end("passed")
+ return candidate.end("failed", "failed " + ", ".join(candidate.gates["failed"]))
+
+ def draw_part(self, candidate: Candidate, part: Part, drawn: Grid | None, earlier: list[Issue]
+ ) -> Generator[Ask, Reply | ApiError, Candidate | tuple[Grid, list[Issue], str]]:
+ """One call's frames: drawn, held to the palette of the frames `drawn` before it, repaired, and
+ drawn once more when they still do not read whole. Returns the part's grid, its issues and the
+ effort it was drawn at, or the candidate ended."""
+ request = self.request
+ cid = candidate.id
+ prefix, who = (cid, cid) if part.count == 1 else (f"{cid}-part{part.number}", f"{cid} part {part.number}")
effort, number, redrawn = request.effort, 1, False
while True:
- ask = Ask(f"{cid}-gen{number}", cid, effort, self.generation_body(effort))
+ ask = Ask(f"{prefix}-gen{number}", cid, effort, self.generation_body(effort, part, drawn))
outcome = yield ask
candidate.generations.append(ask.call_id)
if isinstance(outcome, ApiError):
return candidate.end("error", outcome.line)
if outcome.stop_reason == "refusal":
return candidate.end("refused", _refusal_reason(outcome))
- grid, issues = parse_answer(outcome.text, request.answer_format, request.size, request.size, request.frames)
+ grid, issues = parse_answer(outcome.text, request.answer_format, request.size, request.size, part.frames)
+ if drawn is not None and grid is not None and not structural(issues):
+ grid, issues = hold_palette(grid, issues, drawn.palette)
if outcome.stop_reason == "max_tokens" and grid is None: # nothing readable was written
lower = LOWER_EFFORT.get(effort)
if not redrawn and lower:
self.note(f"{ask.call_id}: all {request.max_tokens} tokens went to thinking and nothing was "
- f"written; drawing {cid} once more at effort {lower}")
+ f"written; drawing {who} once more at effort {lower}")
candidate.redraws.append({"after": ask.call_id, "why": "max_tokens", "effort": lower})
effort, number, redrawn = lower, number + 1, True
continue
return candidate.end("failed", f"max_tokens: {ask.call_id} used all {request.max_tokens} tokens "
f"at effort {effort} and wrote nothing")
grid, issues = self.repair(candidate, ask.call_id, grid, issues)
- candidate.g1 = _g1(issues)
+ candidate.g1 = _g1(earlier + issues)
if not candidate.g1["ok"]:
if not redrawn:
- self.note(f"{ask.call_id}: G1 still fails ({_issue_list(issues)}); drawing {cid} once more")
+ self.note(f"{ask.call_id}: G1 still fails ({_issue_list(issues)}); drawing {who} once more")
candidate.redraws.append({"after": ask.call_id, "why": "G1", "effort": effort})
number, redrawn = number + 1, True
continue
return candidate.end("failed", f"G1: {_issue_list(issues)}")
- candidate.effort, candidate.grid = effort, grid
- pixels = {name: frame_pixels(grid, name) for name in request.frames}
- candidate.gates = evaluate(pixels, kind=request.kind, rule=request.palette, walk_cycle=request.walk_cycle)
- candidate.warnings, candidate.info = candidate.gates["warnings"], candidate.gates["info"]
- if candidate.gates["ok"]:
- return candidate.end("passed")
- return candidate.end("failed", "failed " + ", ".join(candidate.gates["failed"]))
+ return grid, issues, effort
def repair(self, candidate: Candidate, gen_id: str, grid: Grid | None,
issues: list[Issue]) -> tuple[Grid | None, list[Issue]]:
@@ -779,7 +949,8 @@ class Run:
order = list(passed)
random.Random(_sha(self.request.to_dict())).shuffle(order)
by_label = {label: c for label, c in zip(labels, order)}
- sheet = pick_sheet(self.run_dir, by_label, tile=self.request.kind == "tile")
+ sheet = pick_sheet(self.run_dir, by_label, tile=self.request.kind == "tile",
+ scale=preview_scale(self.request.size))
sheet_path = self.run_dir / "pick-sheet.png"
sheet_path.write_bytes(sheet)
content = [{"type": "image", "source": {"type": "base64", "media_type": "image/png",
@@ -811,19 +982,50 @@ def _issue_list(issues: list[Issue]) -> str:
PICK_CHECKER_SQUARE = 8 # sheet pixels a square of the checker under a preview
+# What Claude reads of an image unscaled, on Claude 4.7 and later models (Opus 5.5 among them): a long
+# edge of at most 2576 px and at most 4784 patches of 28x28 px; a larger image is scaled down, which
+# blurs pixel art (platform.claude.com/docs/en/build-with-claude/vision, "Resolution and token cost",
+# read 2026-10-15). An image past 8000 px a side is refused outright.
+PICK_SHEET_LONG_EDGE, PICK_SHEET_PATCHES, PICK_SHEET_PATCH = 2576, 4784, 28
+PICK_PAD, PICK_LABEL_WIDTH = 16, 56
+
+
+def _sheet_size(rows: list[tuple[str, Image.Image, Image.Image | None]]) -> tuple[int, int]:
+ width = max(PICK_LABEL_WIDTH + p.width + (t.width + PICK_PAD if t else 0) for _, p, t in rows) + PICK_PAD * 2
+ height = sum(max(p.height, t.height if t else 0) + PICK_PAD for _, p, t in rows) + PICK_PAD
+ return width, height
+
+
+def _fits(size: tuple[int, int]) -> bool:
+ width, height = size
+ patches = -(-width // PICK_SHEET_PATCH) * -(-height // PICK_SHEET_PATCH)
+ return max(size) <= PICK_SHEET_LONG_EDGE and patches <= PICK_SHEET_PATCHES
+
+
+def _rescaled(image: Image.Image | None, scale: int, step: int) -> Image.Image | None:
+ """A preview enlarged `scale` times, enlarged `step` times instead — nearest-neighbour, exact: every
+ side is a whole number of `scale`-pixel units, and each becomes `step` pixels."""
+ if image is None or step == scale:
+ return image
+ return image.resize((image.width * step // scale, image.height * step // scale), Image.NEAREST)
-def pick_sheet(run_dir: Path, by_label: dict[str, Candidate], *, tile: bool) -> bytes:
+def pick_sheet(run_dir: Path, by_label: dict[str, Candidate], *, tile: bool, scale: int = 1) -> bytes:
"""One sheet of the candidates' previews (and 3x3 tilings), each row labelled, a preview's
- transparency on the engine's preview checker (`qa.preview.checker`)."""
- rows = []
+ transparency on the engine's preview checker (`qa.preview.checker`). The previews are enlarged
+ `scale` times; when the sheet is larger than Claude reads unscaled — many frames, many candidates —
+ they are drawn at the largest smaller whole enlargement at which it fits."""
+ loaded = []
for label, candidate in by_label.items():
preview = Image.open(run_dir / candidate.files["preview"]).convert("RGBA")
tiled = Image.open(run_dir / candidate.files["tiled"]).convert("RGBA") if tile else None
- rows.append((label, preview, tiled))
- pad, label_width = 16, 56
- width = max(label_width + p.width + (t.width + pad if t else 0) for _, p, t in rows) + pad * 2
- height = sum(max(p.height, t.height if t else 0) + pad for _, p, t in rows) + pad
+ loaded.append((label, preview, tiled))
+ for step in range(scale, 0, -1):
+ rows = [(label, _rescaled(p, scale, step), _rescaled(t, scale, step)) for label, p, t in loaded]
+ if _fits(_sheet_size(rows)):
+ break
+ pad, label_width = PICK_PAD, PICK_LABEL_WIDTH
+ width, height = _sheet_size(rows)
sheet = Image.new("RGBA", (width, height), (255, 255, 255, 255))
draw = ImageDraw.Draw(sheet)
y = pad
@@ -842,8 +1044,9 @@ def pick_sheet(run_dir: Path, by_label: dict[str, Candidate], *, tile: bool) ->
# ----------------------------------------------------------------------------- files and report
def write_files(directory: Path, grid: Grid, request_frames: tuple[str, ...], kind: str, rule: PaletteRule,
- pixels_used: list[str]) -> dict[str, Any]:
- """grid.txt, palette.json, frame-<name>.png, preview-x<s>.png, tiled-3x3.png (tile), anim.gif (2+ frames)."""
+ pixels_used: list[str], duration_ms: int = GIF_FRAME_MS) -> dict[str, Any]:
+ """grid.txt, palette.json, frame-<name>.png, preview-x<s>.png (rows of PREVIEW_COLUMNS frames),
+ tiled-3x3.png (tile), anim.gif (2+ frames, `duration_ms` each)."""
directory.mkdir(parents=True, exist_ok=True)
frames = {name: frame_pixels(grid, name) for name in request_frames}
scale = preview_scale(max(grid.width, grid.height))
@@ -863,7 +1066,7 @@ def write_files(directory: Path, grid: Grid, request_frames: tuple[str, ...], ki
tiled_3x3(frames[request_frames[0]], scale).save(directory / "tiled-3x3.png")
files["tiled"] = "tiled-3x3.png"
if len(frames) > 1:
- save_gif(list(frames.values()), scale, directory / "anim.gif", GIF_FRAME_MS, loop=None if kind == "effect" else 0)
+ save_gif(list(frames.values()), scale, directory / "anim.gif", duration_ms, loop=None if kind == "effect" else 0)
files["gif"] = "anim.gif"
if kind == "effect":
strip = Image.new("RGBA", (grid.width * len(frames), grid.height))
@@ -873,7 +1076,7 @@ def write_files(directory: Path, grid: Grid, request_frames: tuple[str, ...], ki
meta = {"kind": "effect", "frames": len(frames), "w": grid.width, "h": grid.height,
"loop": False, "hold_last": False, "end_frame": len(frames) - 1,
"events": [], "blend": "add", "anchor": [grid.width / 2, grid.height / 2],
- "delay_ms": GIF_FRAME_MS, "frame_names": list(frames)}
+ "delay_ms": duration_ms, "frame_names": list(frames)}
atomic_write_text(directory / "effect.strip.json", json.dumps(meta, indent=2) + "\n")
files.update(strip="effect.strip.png", metadata="effect.strip.json")
return files
@@ -917,11 +1120,19 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
"measured best at 32 or less)")
parser.add_argument("--kind", choices=KINDS, help="sprite (default) and icon have a transparent background; a tile is "
"opaque and repeats; an effect has a centered lifetime")
- parser.add_argument("--frames", help=f"comma-separated frame names drawn in one call, at most {FRAMES_MAX} "
- "(effect: 2..8, default birth,peak,decay,gone; others: one named after --kind)")
+ parser.add_argument("--frames", help=f"comma-separated frame names, at most {FRAMES_TOTAL_MAX}, drawn {FRAMES_MAX} a "
+ "call (effect: 2..8 in one call, default birth,peak,decay,gone; others: one "
+ "named after --kind); a --spec frame may be {\"name\": ..., \"pose\": ...}")
parser.add_argument("--walk-cycle", action="store_true", default=None,
help="the four frames are one walk cycle (contact, passing, contact, passing): says so in the "
"prompt and checks the legs change sides")
+ parser.add_argument("--motion", help="the frames, in this order, are one motion, in words: says so in the prompt, "
+ "and G6 fails only a frame off the ground row (a pose's height and a hold "
+ "are reported)")
+ parser.add_argument("--style", help="the style to draw in, in words, in place of the kind's (a dark outline, 2-3 "
+ "shades, light from the top-left); the pick judges craft against it")
+ parser.add_argument("--duration-ms", type=int, help=f"each frame of anim.gif, in milliseconds (default "
+ f"{GIF_FRAME_MS}; at least {DURATION_MS_MIN})")
parser.add_argument("--palette", help="free[:N] (default free:16), pico8, #RRGGBB,#RRGGBB,..., or a palette file "
"(.json list, or one colour per line)")
parser.add_argument("--candidates", type=int, help=f"answers drawn for the request, {CANDIDATES_MIN}..{CANDIDATES_MAX} "
@@ -965,7 +1176,7 @@ def _note_printer() -> Callable[[str], None]:
def _run_grid(args: argparse.Namespace) -> int:
- extra = _given(args, ("size", "frames") + RUN_FLAGS + ("batch_wait",)) + (["--resume"] if args.resume else [])
+ extra = _given(args, ("size", "frames", "style") + RUN_FLAGS + ("batch_wait",)) + (["--resume"] if args.resume else [])
if extra:
raise _refuse(f"--grid checks and renders a grid as it is; drop {', '.join(extra)}")
try:
@@ -977,6 +1188,8 @@ def _run_grid(args: argparse.Namespace) -> int:
except ValueError as exc:
raise _refuse(str(exc)) from exc
kind = args.kind or "sprite"
+ motion = _words(args.motion, "--motion")
+ duration_ms = _duration(GIF_FRAME_MS if args.duration_ms is None else args.duration_ms)
grid, issues = read_grid_text(text)
if grid is not None and not (SIZE_MIN <= grid.width <= SIZE_MAX and SIZE_MIN <= grid.height <= SIZE_MAX):
raise _refuse(f"--grid {args.grid}: {grid.width}x{grid.height}; each side is {SIZE_MIN}..{SIZE_MAX} pixels")
@@ -987,20 +1200,22 @@ def _run_grid(args: argparse.Namespace) -> int:
raise _refuse("--walk-cycle does not apply to an effect")
if args.walk_cycle and len(frames) != 4:
raise _refuse(f"--walk-cycle is four frames, the grid holds {len(frames)}")
+ if grid is not None:
+ _motion(motion, kind, frames)
out_dir = Path(args.out_dir).expanduser().resolve()
_fresh_dir(out_dir)
report: dict[str, Any] = {"kind": REPORT_KIND, "status": "failed", "out_dir": str(out_dir), "source": "grid",
"grid_source": str(Path(args.grid).expanduser().resolve()), "model": None,
"request": {"kind": kind, "frames": list(frames), "walk_cycle": bool(args.walk_cycle),
- "palette": rule.to_dict()},
+ "motion": motion, "palette": rule.to_dict(), "duration_ms": duration_ms},
"G1": _g1(issues), "gates": None, "warnings": [], "info": [], "files": {}, "calls": [],
"cost_usd": 0.0}
if grid is None or not report["G1"]["ok"]:
path = _write_report(out_dir, report)
raise _refuse(f"{args.grid} does not parse whole: {_issue_list(issues)}; report {path}")
pixels = {name: frame_pixels(grid, name) for name in frames}
- gates = evaluate(pixels, kind=kind, rule=rule, walk_cycle=bool(args.walk_cycle))
- files = write_files(out_dir, grid, frames, kind, rule, colors_used(pixels))
+ gates = evaluate(pixels, kind=kind, rule=rule, walk_cycle=bool(args.walk_cycle), motion=bool(motion))
+ files = write_files(out_dir, grid, frames, kind, rule, colors_used(pixels), duration_ms)
report.update(status="ok" if gates["ok"] else "failed", gates=gates, warnings=gates["warnings"], info=gates["info"],
files=files, request={**report["request"], "size": [grid.width, grid.height]})
path = _write_report(out_dir, report)
@@ -1038,6 +1253,7 @@ def _run(args: argparse.Namespace, *, sleep: Callable[[float], None] = time.slee
started = time.monotonic()
calls = Calls(out_dir, token, sleep=sleep, note=note)
run = Run(request, out_dir, calls, batch_wait=batch_wait, note=note)
+ _say_parts(request, note)
report: dict[str, Any] = {"kind": REPORT_KIND, "status": None, "out_dir": str(out_dir), "source": "model",
"model": api.MODEL, "request": request.to_dict(), "chosen": None, "files": {},
"pick": None, "candidates": [], "warnings": [], "info": []}
@@ -1053,7 +1269,7 @@ def _run(args: argparse.Namespace, *, sleep: Callable[[float], None] = time.slee
if candidate.grid is not None:
pixels = {name: frame_pixels(candidate.grid, name) for name in request.frames}
files = write_files(out_dir / "candidates" / candidate.id, candidate.grid, request.frames, request.kind,
- request.palette, colors_used(pixels))
+ request.palette, colors_used(pixels), request.duration_ms)
candidate.files = _prefixed(files, f"candidates/{candidate.id}")
passed = [c for c in candidates if c.status == "passed"]
report["candidates"] = [c.to_dict() for c in candidates]
@@ -1095,10 +1311,23 @@ def _finish(report: dict[str, Any], calls: Calls, started: float) -> Path:
def _call_order(call_id: str) -> tuple:
+ """c<candidate>[-part<n>]-gen<n>[-fix<n>] in the order the calls were made; the pick last."""
if call_id == "pick":
return (10**6,)
- parts = call_id.replace("-gen", " ").replace("-fix", " ").split()
- return (int(parts[0][1:]), *[int(p) for p in parts[1:]])
+ return tuple(int(n) for n in re.findall(r"\d+", call_id))
+
+
+def _say_parts(request: PixelRequest, note: Callable[[str], None]) -> None:
+ """Before a set of more than FRAMES_MAX frames is drawn: how many calls, and what they may spend."""
+ parts = call_parts(request)
+ if len(parts) == 1:
+ return
+ shown = min(len(request.frames) - len(parts[-1].frames), 1 + DRAWN_SHOWN)
+ reads = shown * request.size * (request.size + 1) // GRID_CHARS_PER_TOKEN
+ note(f"{len(request.frames)} frames (at most {FRAMES_TOTAL_MAX}): {len(parts)} calls a candidate of at most "
+ f"{FRAMES_MAX} frames each, {len(parts) * request.candidates} drawings in all; each may write up to "
+ f"{request.max_tokens} output tokens, thinking included, and each call after a candidate's first also "
+ f"reads its palette and up to {shown} frames already drawn, about {reads} input tokens")
def run(**kwargs: Any) -> int:
diff --git a/sprite_gen/gen/pixel_gates.py b/sprite_gen/gen/pixel_gates.py
index 011262d..bab2089 100644
--- a/sprite_gen/gen/pixel_gates.py
+++ b/sprite_gen/gen/pixel_gates.py
@@ -24,6 +24,20 @@ function each, called here, never a copy (docs/pixel-draw.md "Gates"):
the margin). A walk cycle (contact, passing, contact, passing) also warns when
its two contact frames differ by less than 40% of the mean contact↔passing difference: the legs
barely change sides.
+- G6 of one motion — the frames, in their order, are one motion (`--motion`; a walk cycle is one
+ too). This is the rule's one place; docs/pixel-draw.md points here. A motion changes the
+ silhouette: an arm goes over the head, a blade swings past it, a pose is held for a beat. So:
+ * one ground still fails: every frame stands on the same bottom row (inside the safe area, as
+ above);
+ * a height that differs from the first frame's by more than the pixel G6 allows is asked of the
+ judgment the image path makes of the same question — did the body change size, or only its
+ pose? — `video.gait_fallback.size_change`, on `body_size` (height, mass, breadth) of each frame
+ against the first, inside the safe area. A pose moves the three apart (an arm over the head adds
+ height, not mass); a body drawn larger or smaller moves them together. When all three move one
+ way by more than that pixel of the first frame's height, it warns (the body changes size — a
+ redraw candidate); otherwise it is an info line (the height changes with the pose);
+ * frames drawn the same are a hold, an info line.
+ Nothing but the ground fails a motion.
- G8 safe area, on a sprite or icon: the engine's safe area (`safe_area`, the margin `prepare`
keeps around every cell), a target for the body's average size and not a wall. G8 never fails.
Its judgment is the one the image path makes when it snaps a sprite to pixels,
@@ -145,9 +159,34 @@ def _difference(a: Frame, b: Frame) -> int:
return sum(1 for y in range(len(a)) for x in range(len(a[0])) if a[y][x] != b[y][x])
-def g6_frames(frames: dict[str, Frame], *, walk_cycle: bool, box: Sequence[int] | None = None) -> dict[str, Any]:
+def _sizes(frames: dict[str, Frame], heights: dict[str, int], box: Sequence[int] | None) -> dict[str, dict[str, Any]]:
+ """Per frame whose height differs from the first frame's by more than HEIGHT_SPREAD_MAX: how much
+ larger its body is than the first's, by the image path's reading (`gait_fallback.size_change`: the
+ least of height, mass and breadth when all three move one way, 0 when they part), inside `box`."""
+ # Imported here: the judgment is the video path's, made in one place (it pulls in NumPy).
+ from sprite_gen.video.gait_fallback import body_size, size_change
+
+ names = list(frames)
+ first = names[0]
+ crop = (box[0], box[1], box[2] + 1, box[3] + 1) if box else None
+
+ def size(name: str):
+ image = image_of(frames[name])
+ return body_size(image.crop(crop) if crop else image)
+
+ out = {}
+ for name in names[1:]:
+ if abs(heights[name] - heights[first]) > HEIGHT_SPREAD_MAX:
+ change = size_change(size(first), [size(name)])
+ out[name] = {key: change[key] for key in ("change", "height", "mass", "breadth")}
+ return out
+
+
+def g6_frames(frames: dict[str, Frame], *, walk_cycle: bool, box: Sequence[int] | None = None,
+ motion: bool = False) -> dict[str, Any]:
"""`box` (first and last column and row) is where the rows and heights are measured: a sprite's
- or icon's safe area, the whole frame without one."""
+ or icon's safe area, the whole frame without one. `motion` (a walk cycle is one) takes the rule of
+ one motion in this module's header."""
names = list(frames)
spans = {name: _bbox_rows(frames[name], box) for name in names}
baselines = {name: (span[1] if span else None) for name, span in spans.items()}
@@ -155,12 +194,18 @@ def g6_frames(frames: dict[str, Frame], *, walk_cycle: bool, box: Sequence[int]
identical = [[names[i], names[j]] for i in range(len(names)) for j in range(i + 1, len(names))
if frames[names[i]] == frames[names[j]]]
spread = max(heights.values()) - min(heights.values())
+ grounded = len(set(baselines.values())) == 1 and None not in baselines.values()
result: dict[str, Any] = {
- "ok": len(set(baselines.values())) == 1 and None not in baselines.values()
- and spread <= HEIGHT_SPREAD_MAX and not identical,
+ "ok": grounded and spread <= HEIGHT_SPREAD_MAX and not identical,
"baselines": baselines, "heights": heights, "height_spread": spread, "identical_pairs": identical,
"measured_in": list(box) if box else None,
}
+ if motion or walk_cycle:
+ sizes = _sizes(frames, heights, box)
+ first = heights[names[0]]
+ resized = [name for name, size in sizes.items() if abs(size["change"]) * first > HEIGHT_SPREAD_MAX]
+ result.update(ok=grounded, rule="motion", size_change=sizes, resized=resized,
+ posed=[name for name in sizes if name not in resized], holds=identical)
if walk_cycle:
a, b, c, d = (frames[n] for n in names)
contact = _difference(a, c)
@@ -248,10 +293,30 @@ def _g8_lines(g8: dict[str, Any]) -> tuple[list[str], list[str]]:
return warnings, info
-def evaluate(frames: dict[str, Frame], *, kind: str, rule: PaletteRule, walk_cycle: bool) -> dict[str, Any]:
+def _g6_motion_lines(g6: dict[str, Any]) -> tuple[list[str], list[str]]:
+ """G6's warning (a body drawn at another size) and info lines (a height that changed with the pose,
+ a hold) for one motion."""
+ first = next(iter(g6["heights"]))
+ warnings, info = [], []
+ if g6["resized"]:
+ said = ", ".join(f"{name} {g6['size_change'][name]['change']:+.0%}" for name in g6["resized"])
+ warnings.append("G6 the body changes size, not only its pose - its height, mass and breadth all grow or "
+ f"shrink by more than a pixel: {said} against {first}")
+ if g6["posed"]:
+ said = ", ".join(f"{name} {g6['heights'][name]} px" for name in g6["posed"])
+ info.append("G6 the height changes with the pose, not the body's size (informational, no action): "
+ f"{said} against {first} {g6['heights'][first]} px")
+ if g6["holds"]:
+ info.append("G6 frames drawn the same, a hold (informational, no action): "
+ + ", ".join(f"{a}={b}" for a, b in g6["holds"]))
+ return warnings, info
+
+
+def evaluate(frames: dict[str, Frame], *, kind: str, rule: PaletteRule, walk_cycle: bool,
+ motion: bool = False) -> dict[str, Any]:
"""Every gate of one candidate. `ok` is G2, G3 and G6 together; `warnings` say what G4, G5, the
- walk check and G8 found that may want a redraw, `info` what G8 found that asks for nothing, one
- line each."""
+ walk check, G6 of a motion and G8 found that may want a redraw, `info` what G6 of a motion and G8
+ found that asks for nothing, one line each. `motion`: the frames are one motion (the header)."""
gates: dict[str, Any] = {"G2": g2_palette(frames, rule), "G3": g3_alpha(frames, kind)}
warnings: list[str] = []
info: list[str] = []
@@ -269,15 +334,20 @@ def evaluate(frames: dict[str, Frame], *, kind: str, rule: PaletteRule, walk_cyc
gates["G6"] = {"ok": 2 <= len(frames) <= 8 and any(frame != first for frame in frames.values()),
"rule": "2..8 frames with a visible change; extent, height and empty frames may differ"}
elif len(frames) > 1:
- gates["G6"] = g6_frames(frames, walk_cycle=walk_cycle, box=area["box"] if area else None)
+ gates["G6"] = g6_frames(frames, walk_cycle=walk_cycle, box=area["box"] if area else None, motion=motion)
walk = gates["G6"].get("walk")
if walk and walk["warn"]:
warnings.append(f"G6 weak leg alternation: the contact frames differ by {walk['contact_difference']} "
f"pixels, {walk['ratio']:.0%} of the contact-passing difference (under "
f"{WALK_CONTACT_RATIO_MIN:.0%}) — touch up the legs")
+ if gates["G6"].get("rule") == "motion":
+ g6_warnings, g6_info = _g6_motion_lines(gates["G6"])
+ warnings += g6_warnings
+ info += g6_info
if area is not None:
gates["G8"] = g8_safe_area(frames, kind, area)
- g8_warnings, info = _g8_lines(gates["G8"])
+ g8_warnings, g8_info = _g8_lines(gates["G8"])
warnings += g8_warnings
+ info += g8_info
failed = [name for name in ("G2", "G3", "G6") if name in gates and not gates[name]["ok"]]
return {"ok": not failed, "failed": failed, "warnings": warnings, "info": info, **gates}
diff --git a/sprite_gen/gen/pixel_grid.py b/sprite_gen/gen/pixel_grid.py
index b803180..d971a07 100644
--- a/sprite_gen/gen/pixel_grid.py
+++ b/sprite_gen/gen/pixel_grid.py
@@ -17,7 +17,8 @@ Parsing is strict and says what it found (`Issue`):
- recovered issues are code-recoverable and recorded, never silent: the fence tagged otherwise or
missing, a fence never closed, a single frame written without its `FRAME` line or under another
name, frames in another order, no `END` line, an answer that wrote its block more than once (the
- last block that reads whole is read).
+ last block that reads whole is read), and — for a later answer of a set drawn over several, which
+ is given the first answer's palette (`hold_palette`) — a colour it added or changed.
`png_bytes` writes a frame as a PNG whose bytes depend only on its pixels — stored deflate
blocks, no compressor in the loop — so the same grid gives the same file on any machine and any
@@ -46,6 +47,7 @@ KEYS = string.ascii_lowercase + string.ascii_uppercase + string.digits
TRANSPARENT_KEY = "."
HEX = re.compile(r"^#[0-9A-Fa-f]{6}$")
PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
+PREVIEW_COLUMNS = 8 # frames a preview row holds before the next row
# PICO-8's 16 colours (lexaloffle.com/pico-8.php, the fixed palette of the console).
PICO8 = ("#000000", "#1D2B53", "#7E2553", "#008751", "#AB5236", "#5F574F", "#C2C3C7", "#FFF1E8",
@@ -59,7 +61,7 @@ STRUCTURAL = frozenset({
})
ROW_CODES = frozenset({"row_width", "unknown_symbol", "row_missing"})
RECOVERED = frozenset({"block_tag", "block_unclosed", "block_many", "frame_header_missing", "frame_renamed",
- "frame_order", "no_end"})
+ "frame_order", "no_end", "palette_added", "palette_changed"})
_PALETTE_LINE = re.compile(r"^(\S)\s+(transparent|#[0-9A-Fa-f]{6})$")
_ROW_ANSWER = re.compile(r"^\s*`?\s*ROW\s+(\S+)\s+(\d+)\s*:\s*(.*?)\s*`?\s*$", re.M)
@@ -420,6 +422,26 @@ def parse_answer(text: str, fmt: str, width: int, height: int, frames: Sequence[
return _read_body(body, found, fmt, width, height, frames)
+def hold_palette(grid: Grid, issues: list[Issue], palette: dict[str, str | None]) -> tuple[Grid, list[Issue]]:
+ """`grid` under the palette it was given — a later answer of a set drawn over several, which writes
+ the first answer's palette again. A key it added is refused, so its rows become row issues for the
+ row repair; a colour it changed is put back. Both are recorded."""
+ found = []
+ for key, color in grid.palette.items():
+ if key not in palette:
+ found.append(Issue("palette_added", None, None, f"{key} {color}"))
+ elif (color or "").lower() != (palette[key] or "").lower():
+ found.append(Issue("palette_changed", None, None, f"{key} {color}, kept {palette[key]}"))
+ held = replace(grid, palette=dict(palette))
+ return held, [i for i in issues if i.code not in ROW_CODES] + found + check_rows(held)
+
+
+def joined(grids: Sequence[Grid]) -> Grid:
+ """The frames of several answers, in order, under the first answer's palette (`hold_palette`)."""
+ frames = {name: rows for grid in grids for name, rows in grid.frames.items()}
+ return replace(grids[0], frames=frames)
+
+
def read_grid_text(text: str) -> tuple[Grid | None, list[Issue]]:
"""Read a `grid.txt` (the character grid with or without its fence); the frames and the canvas
size are what it holds — the commonest row length is the width, the commonest row count the
@@ -555,15 +577,18 @@ def preview_scale(size: int) -> int:
return max(1, 256 // size)
-def preview_strip(frames: Sequence[Sequence[Sequence[Pixel]]], scale: int) -> Image.Image:
- """The frames side by side, each enlarged `scale` times, two enlarged pixels apart."""
+def preview_strip(frames: Sequence[Sequence[Sequence[Pixel]]], scale: int,
+ columns: int = PREVIEW_COLUMNS) -> Image.Image:
+ """The frames side by side, each enlarged `scale` times, two enlarged pixels apart; past `columns`
+ frames they go on in rows, left to right and top to bottom, so a long set stays readable."""
images = [image_of(f).resize((len(f[0]) * scale, len(f) * scale), Image.NEAREST) for f in frames]
gap = 2 * scale
- strip = Image.new("RGBA", (sum(i.width for i in images) + gap * (len(images) - 1), max(i.height for i in images)))
- x = 0
- for image in images:
- strip.paste(image, (x, 0))
- x += image.width + gap
+ across = min(columns, len(images))
+ down = -(-len(images) // across)
+ width, height = max(i.width for i in images), max(i.height for i in images)
+ strip = Image.new("RGBA", (width * across + gap * (across - 1), height * down + gap * (down - 1)))
+ for number, image in enumerate(images):
+ strip.paste(image, ((number % across) * (width + gap), (number // across) * (height + gap)))
return strip
diff --git a/tests/gen/test_pixel_draw.py b/tests/gen/test_pixel_draw.py
index ae17765..0ba179e 100644
--- a/tests/gen/test_pixel_draw.py
+++ b/tests/gen/test_pixel_draw.py
@@ -444,7 +444,10 @@ def test_a_used_folder_is_refused(tmp_path, claude):
@pytest.mark.parametrize("args,message", [
(["--size", "7"], "--size is 8..48 pixels, got 7"),
(["--size", "49"], "--size is 8..48 pixels, got 49"),
- (["--frames", "a,b,c,d,e"], "at most 4 frames in one call, got 5"),
+ (["--frames", ",".join(f"f{i}" for i in range(65))], "at most 64 frames, got 65"),
+ (["--frames", "a,b", "--duration-ms", "5"], "--duration-ms is at least 10, got 5"),
+ (["--style", " "], "--style is a sentence of words, got ' '"),
+ (["--motion", "a spin"], "--motion is two or more frames"),
(["--frames", "a b"], "frame names are letters, digits"),
(["--frames", "a,a"], "frame names must differ"),
(["--frames", "a,b", "--walk-cycle"], "--walk-cycle is four frames"),
@@ -562,7 +565,8 @@ def test_no_key_is_refused_before_the_folder_is_made(tmp_path, monkeypatch):
def test_the_cli_names_the_verb_and_its_flags():
flags = help_options("-m", "sprite_gen.cli", "pixel-draw")
assert {"--subject", "--spec", "--grid", "--size", "--kind", "--frames", "--walk-cycle", "--palette", "--candidates",
- "--effort", "--format", "--batch", "--batch-wait", "--max-tokens", "--pick", "--out-dir", "--resume"} <= flags
+ "--effort", "--format", "--batch", "--batch-wait", "--max-tokens", "--pick", "--out-dir", "--resume",
+ "--style", "--motion", "--duration-ms"} <= flags
def pixel_request(**changes) -> pixel_draw.PixelRequest:
diff --git a/tests/gen/test_pixel_draw_frames.py b/tests/gen/test_pixel_draw_frames.py
new file mode 100644
index 0000000..46d1450
--- /dev/null
+++ b/tests/gen/test_pixel_draw_frames.py
@@ -0,0 +1,411 @@
+# SPDX-License-Identifier: Apache-2.0
+"""`pixel-draw` past four frames, in a style of its own, as one motion: a set of more than four
+frames is drawn four at a time, each later call holding the first call's palette and shown the
+frames already drawn; `--style` replaces the kind's style sentence in the drawing and the pick
+alike (the default prompts stay byte for byte); `--motion` says the frames are one motion and G6
+lets a pose change the height and a hold repeat a frame; `--duration-ms` times `anim.gif`. No key,
+no network: a fake Claude at the transport seam, and synthetic grids."""
+from __future__ import annotations
+
+import io
+import json
+import math
+from pathlib import Path
+
+import pytest
+from PIL import Image, ImageSequence
+
+from test_pixel_draw import KEY, asked, claude, draw, pixel_request, reply, report_of # noqa: F401 (fixture)
+from sprite_gen.gen import pixel_draw
+from sprite_gen.gen import pixel_grid as pg
+
+INK, GOLD = "#2a1f2e", "#c8a040"
+NAMES = tuple(f"f{i}" for i in range(1, 7))
+
+
+def figure_rows(i: int, size: int = 16) -> list[str]:
+ """A 16 px figure on the floor row (columns 5-10, rows 5-15 counted from 1) with a gold mark that
+ moves one column a frame, so no two frames are the same."""
+ rows = []
+ for y in range(size):
+ row = ["."] * size
+ if 4 <= y <= 14:
+ row[5:11] = ["a"] * 6
+ if y == 8:
+ row[5 + i] = "b"
+ rows.append("".join(row))
+ return rows
+
+
+def answer(names, *, extra: str = "", rows: dict[str, list[str]] | None = None) -> str:
+ frames = "".join(f"FRAME {n}\n" + "\n".join((rows or {}).get(n) or figure_rows(int(n[1:]) - 1)) + "\n"
+ for n in names)
+ return f"```pixels\nPALETTE\n. transparent\na {INK}\nb {GOLD}\n{extra}{frames}END\n```"
+
+
+def prompt_of(fake, call_id: str) -> str:
+ return dict(fake.asked)[call_id]["messages"][0]["content"]
+
+
+def lantern_spec(tmp_path: Path) -> Path:
+ spec = tmp_path / "spec.json"
+ spec.write_text(json.dumps({
+ "subject": "a guard swinging a lantern", "size": 16, "motion": "one swing of the lantern",
+ "frames": list(NAMES[:4]) + [{"name": "f5", "pose": "the lantern at the top of its swing"},
+ {"name": "f6", "pose": "the lantern coming down"}]}), encoding="utf-8")
+ return spec
+
+
+# ----------------------------------------------------------------------------- more than four frames
+
+def test_more_than_four_frames_are_drawn_four_at_a_time_from_the_frames_before(tmp_path, claude, capsys):
+ broken = figure_rows(5)
+ broken[8] = broken[8][:12] + "c" + broken[8][13:] # a colour the first answer did not choose
+ fake = claude({"c1-part1-gen1": reply(answer(NAMES[:4])),
+ "c1-part2-gen1": reply(answer(NAMES[4:], extra="c #ff0000\n", rows={"f6": broken})),
+ "c1-part2-gen1-fix1": reply(f"ROW f6 9: {figure_rows(5)[8]}")})
+ out = tmp_path / "run"
+ assert draw(out, "--spec", str(lantern_spec(tmp_path)), "--candidates", "1") == 0
+ assert asked(fake) == ["c1-part1-gen1", "c1-part2-gen1", "c1-part2-gen1-fix1"]
+
+ first, second = prompt_of(fake, "c1-part1-gen1"), prompt_of(fake, "c1-part2-gen1")
+ motion = "Motion: the frames, in this order, are one continuous motion: one swing of the lantern"
+ assert motion in first and motion in second
+ assert "Frames: f1, f2, f3, f4, f5, f6. All frames share one palette" in first
+ assert "This is answer 1 of 2: it draws f1, f2, f3, f4 (frames 1-4)." in first
+ assert "Frames in this order: f1, f2, f3, f4." in first
+ assert "Frames already drawn" not in first and "- f5:" not in first
+ assert "This is answer 2 of 2: it draws f5, f6 (frames 5-6)." in second
+ assert "Frames in this order: f5, f6." in second
+ assert ("What each frame shows:\n- f5: the lantern at the top of its swing\n- f6: the lantern coming down"
+ in second)
+ assert "write it again exactly as it is" in second and "at most 16 colors" not in second
+ drawn = ("```reference\nPALETTE\n. transparent\na #2a1f2e\nb #c8a040\n"
+ + "".join(f"FRAME {n}\n" + "\n".join(figure_rows(i)) + "\n" for i, n in enumerate(NAMES[:4]))
+ + "END\n```")
+ assert drawn in second
+ fix = prompt_of(fake, "c1-part2-gen1-fix1")
+ assert "Rows to write: f6 9" in fix and "c #ff0000" not in fix and "b #c8a040" in fix
+
+ report = report_of(out)
+ (candidate,) = report["candidates"]
+ assert candidate["status"] == "passed" and candidate["generations"] == ["c1-part1-gen1", "c1-part2-gen1"]
+ assert candidate["parts"] == [{"part": 1, "frames": list(NAMES[:4]), "effort": "high"},
+ {"part": 2, "frames": list(NAMES[4:]), "effort": "high"}]
+ assert {"code": "palette_added", "detail": "c #ff0000"} in candidate["G1"]["recovered"]
+ assert candidate["repairs"][0]["rows_asked"] == ["f6 9"] and candidate["repairs"][0]["rows_still_broken"] == []
+ assert [c["id"] for c in report["calls"]] == ["c1-part1-gen1", "c1-part2-gen1", "c1-part2-gen1-fix1"]
+ assert report["request"]["poses"] == {"f5": "the lantern at the top of its swing", "f6": "the lantern coming down"}
+ assert report["request"]["motion"] == "one swing of the lantern" and report["request"]["frames"] == list(NAMES)
+ grid, issues = pg.read_grid_text((out / "grid.txt").read_text(encoding="utf-8"))
+ assert pg.row_issues(issues) == [] and list(grid.frames) == list(NAMES)
+ assert grid.palette == {".": None, "a": INK, "b": GOLD}
+ assert grid.frames["f6"] == [list(row) for row in figure_rows(5)]
+ with Image.open(out / "anim.gif") as gif:
+ assert gif.n_frames == 6
+ err = capsys.readouterr().err
+ assert "6 frames (at most 64): 2 calls a candidate of at most 4 frames each, 2 drawings in all" in err
+
+ again = claude({})
+ assert pixel_draw.main(["--out-dir", str(out), "--resume"]) == 0
+ assert again.asked == [] and pg.read_grid_text((out / "grid.txt").read_text(encoding="utf-8"))[0] == grid
+
+
+def test_a_later_call_shows_the_first_frame_and_the_four_just_before():
+ names = tuple(f"f{i}" for i in range(1, 11))
+ request = pixel_request(size=16, frames=names, max_tokens=64000)
+ drawn, _ = pg.parse_answer(answer(names[:8]), "chargrid", 16, 16, names[:8])
+ part = pixel_draw.call_parts(request)[2]
+ assert part == pixel_draw.Part(3, 3, ("f9", "f10"))
+ prompt = pixel_draw.generation_prompt(request, part, drawn)
+ shown = [line[6:] for line in prompt.splitlines() if line.startswith("FRAME f")]
+ assert shown == ["f1", "f5", "f6", "f7", "f8"]
+ assert "This is answer 3 of 3: it draws f9, f10 (frames 9-10)." in prompt
+ assert [p.frames for p in pixel_draw.call_parts(request)] == [names[:4], names[4:8], names[8:]]
+
+
+def test_a_part_drawn_again_is_drawn_again_on_its_own(tmp_path, claude, capsys):
+ fake = claude({"c1-part1-gen1": reply(answer(NAMES[:4])),
+ "c1-part2-gen1": reply("", stop="max_tokens", output=64000, thinking=64000),
+ "c1-part2-gen2": reply(answer(NAMES[4:]))})
+ out = tmp_path / "run"
+ assert draw(out, "--spec", str(lantern_spec(tmp_path)), "--candidates", "1") == 0
+ assert asked(fake) == ["c1-part1-gen1", "c1-part2-gen1", "c1-part2-gen2"]
+ assert [body["output_config"]["effort"] for _, body in fake.asked] == ["high", "high", "medium"]
+ (candidate,) = report_of(out)["candidates"]
+ assert candidate["redraws"] == [{"after": "c1-part2-gen1", "why": "max_tokens", "effort": "medium"}]
+ assert [p["effort"] for p in candidate["parts"]] == ["high", "medium"] and candidate["effort"] == "medium"
+ assert "drawing c1 part 2 once more at effort medium" in capsys.readouterr().err
+ assert prompt_of(fake, "c1-part2-gen2") == prompt_of(fake, "c1-part2-gen1")
+
+
+def test_a_part_that_fails_ends_its_candidate(tmp_path, claude):
+ fake = claude({"c1-part1-gen1": reply(answer(NAMES[:4])), "c1-part2-gen1": reply("no grid"),
+ "c1-part2-gen2": reply("still no grid")})
+ with pytest.raises(SystemExit, match=r"c1: G1: no_block"):
+ draw(tmp_path / "run", "--spec", str(lantern_spec(tmp_path)), "--candidates", "1")
+ assert asked(fake) == ["c1-part1-gen1", "c1-part2-gen1", "c1-part2-gen2"]
+
+
+def test_batches_draw_each_part_in_its_own_round(tmp_path, claude):
+ fake = claude({"c1-part1-gen1": reply(answer(NAMES[:4])), "c1-part2-gen1": reply(answer(NAMES[4:]))})
+ out = tmp_path / "run"
+ assert draw(out, "--spec", str(lantern_spec(tmp_path)), "--candidates", "1", "--batch") == 0
+ assert [[cid for cid, _ in requests] for _, requests in fake.submitted] == [["c1-part1-gen1"], ["c1-part2-gen1"]]
+ assert "Frames already drawn" in fake.submitted[1][1][0][1]["messages"][0]["content"]
+
+
[email protected]("frames,message", [
+ ([f"f{i}" for i in range(65)], "at most 64 frames, got 65"),
+ ([{"name": "a", "pose": ""}, "b"], "a frame is a name or {\"name\": ..., \"pose\": ...}"),
+ ([{"name": "a", "pose": "up", "hold": 2}, "b"], "a frame is a name or {\"name\": ..., \"pose\": ...}"),
+])
+def test_spec_frames_refused(tmp_path, claude, frames, message):
+ spec = tmp_path / "spec.json"
+ spec.write_text(json.dumps({"subject": "x", "frames": frames}), encoding="utf-8")
+ fake = claude({})
+ with pytest.raises(SystemExit) as caught:
+ draw(tmp_path / "run", "--spec", str(spec))
+ assert message in str(caught.value) and fake.asked == []
+
+
+def test_sixty_four_frames_are_sixteen_calls():
+ names = tuple(f"f{i}" for i in range(64))
+ assert len(pixel_draw.call_parts(pixel_request(frames=names, max_tokens=64000))) == 16
+ effect = pixel_request(kind="effect", frames=tuple(f"e{i}" for i in range(8)))
+ assert pixel_draw.call_parts(effect) == [pixel_draw.Part(1, 1, effect.frames)]
+
+
+# ----------------------------------------------------------------------------- --style
+
+STYLE = "no outline: selective outlining only where a shape meets its own colour, hue-shifted shadows"
+
+
[email protected]("kind,frames", [("sprite", ("sprite",)), ("icon", ("icon",)), ("tile", ("tile",)),
+ ("effect", ("birth", "peak", "decay", "gone"))])
+def test_a_style_replaces_the_kinds_style_sentence_and_keeps_its_structure(kind, frames):
+ default = pixel_draw.generation_prompt(pixel_request(kind=kind, frames=frames))
+ styled = pixel_draw.generation_prompt(pixel_request(kind=kind, frames=frames, style=STYLE))
+ assert f"\nStyle: {STYLE}\n" in styled and styled.count("Style:") == 1
+ assert "2D RPG" not in styled and "outline around the silhouette" not in styled
+ for line in default.splitlines():
+ if not line.startswith("Style:"):
+ assert line in styled.splitlines(), line
+ if kind == "tile":
+ assert "No border or outline around the tile." in styled
+ if kind in ("sprite", "icon"):
+ assert "Background: transparent." in styled and "Safe area:" in styled
+
+
+def test_the_pick_judges_craft_against_the_same_style():
+ pick = pixel_draw.pick_prompt(pixel_request(frames=("down", "up"), style=STYLE), ["A", "B"])
+ craft = next(line for line in pick.splitlines() if line.startswith("- craft"))
+ assert STYLE in craft and "outline" not in craft.replace(STYLE, "")
+ default = pixel_draw.pick_prompt(pixel_request(frames=("down", "up")), ["A", "B"])
+ assert "clean silhouette and outline" in default
+
+
+def test_a_style_rides_the_request_and_the_report(tmp_path, claude):
+ fake = claude({"c1-gen1": reply(answer(("f1",)).replace("FRAME f1", "FRAME sprite"))})
+ out = tmp_path / "run"
+ assert draw(out, "--subject", "a guard", "--size", "16", "--candidates", "1", "--style", STYLE) == 0
+ assert f"Style: {STYLE}" in prompt_of(fake, "c1-gen1")
+ assert report_of(out)["request"]["style"] == STYLE
+ assert json.loads((out / "request.json").read_text(encoding="utf-8"))["style"] == STYLE
+
+
+# The prompts as they were before --style, --motion and calls past four frames: a request that
+# uses none of them asks the same bytes, so a run started before reads its calls back on --resume.
+SPRITE_PROMPT = "\n".join([
+ "Draw: a knight",
+ "Canvas: exactly 32x32 pixels per frame.",
+ "Frames: down, up. All frames share one palette and show the same subject with the same proportions, colors "
+ "and size.",
+ "Palette: at most 16 colors plus transparent.",
+ "Background: transparent.",
+ "Safe area: draw the subject's body about the size of the central 26x26 pixels - rows 4-29 and columns 4-29, "
+ "counting rows and columns from 1 - inside a 3-pixel margin on every side. That is a target for its average "
+ "size, not a wall: when a pose or a detail needs the room (a raised weapon, a long blade, an effect, a wide "
+ "stance), it may reach past the safe area into the margin, up to the canvas edge. Keep the four corner pixels "
+ "transparent.",
+ "Floor: row 29, the bottom row of the safe area, is the ground: the feet (or the lowest point the subject rests "
+ "on) stand on row 29 in every frame.",
+ "Style: clean, readable pixel art for a 2D RPG: a dark (not pure black) outline around the silhouette, 2-3 "
+ "shades per material, light from the top-left, no anti-aliasing noise and no stray single pixels.",
+ "",
+ "Output format: exactly one fenced code block tagged `pixels`, and nothing after it:",
+ "```pixels",
+ "PALETTE",
+ ". transparent",
+ "a #RRGGBB",
+ "b #RRGGBB",
+ "...",
+ "FRAME <frame name>",
+ "<32 lines, each exactly 32 characters>",
+ "...",
+ "END",
+ "```",
+ "- Each palette line is one key character and one #RRGGBB color. Keys are single characters from a-z, A-Z, "
+ "0-9; `.` is always transparent and is never redefined.",
+ "- Each frame is exactly 32 lines of exactly 32 characters, every character a palette key, with no spaces.",
+ "- Frames in this order: down, up. Write `FRAME <name>` before each frame and `END` once after the last frame.",
+])
+TILE_PROMPT_HEAD = "\n".join([
+ "Draw: grass",
+ "Canvas: exactly 32x32 pixels per frame.",
+ "Palette: at most 8 colors plus transparent.",
+ "This is a tile: fill every pixel (no transparency) and make it repeat seamlessly in a grid, so the left edge "
+ "continues into the right edge and the top edge into the bottom edge. No border or outline around the tile.",
+ "Style: clean, readable pixel art for a 2D RPG: 2-3 shades per material, light from the top-left, no noisy "
+ "single-pixel speckle.",
+ "",
+ "Output format: exactly one fenced code block tagged `pixels`, and nothing after it:",
+])
+PICK_PROMPT = "\n".join([
+ "You are judging pixel-art game assets for a game asset service.",
+ "The image shows 2 candidates labelled A, B for the same request. Each is enlarged with nearest-neighbour "
+ "scaling, so every square block is one pixel; the grey checkerboard stands for transparency.",
+ "Each candidate is a row of 2 frames in this order: down, up.",
+ "The request was: a knight Canvas 32x32 pixels per frame, the body about the size of the central 26x26, inside "
+ "a 3-pixel margin a pose may reach into.",
+ "Score every candidate:",
+ "- subject_read 1-5: how clearly it reads as the requested subject (5 instantly, 1 unrecognisable).",
+ "- craft 1-5: pixel-art craft: clean silhouette and outline, consistent shading and light, no noise, sensible "
+ "use of the canvas (5 professional, 3 acceptable indie, 1 broken).",
+ "- consistency 1-5: the same subject, proportions and colours across frames, and correct poses/directions for "
+ "the frame names.",
+ "- verdict: ship (usable in a game as is), touch_up (usable after a few pixel fixes), redraw (not usable).",
+ "- note: one short sentence naming the main flaw or strength.",
+ "Then best: the label of the candidate you would ship; any_shippable: whether at least one is ship or touch_up.",
+ "Judge only what is visible.",
+])
+
+
+def test_the_default_prompts_are_byte_for_byte_what_they_were():
+ assert pixel_draw.generation_prompt(pixel_request(frames=("down", "up"), max_tokens=64000)) == SPRITE_PROMPT
+ tile = pixel_draw.generation_prompt(pixel_request(kind="tile", frames=("tile",), subject="grass",
+ palette=pg.palette_rule("free:8")))
+ assert tile.startswith(TILE_PROMPT_HEAD + "\n```pixels\n")
+ assert pixel_draw.pick_prompt(pixel_request(frames=("down", "up")), ["A", "B"]) == PICK_PROMPT
+
+
+# ----------------------------------------------------------------------------- --motion and --duration-ms
+
+def test_motion_is_two_or_more_frames_and_no_effect(tmp_path, claude):
+ claude({})
+ with pytest.raises(SystemExit, match="--motion is two or more frames"):
+ draw(tmp_path / "a", "--subject", "x", "--motion", "a spin")
+ with pytest.raises(SystemExit, match="--motion does not apply to an effect"):
+ draw(tmp_path / "b", "--subject", "x", "--kind", "effect", "--motion", "a spin")
+
+
+def test_the_motion_sentence_follows_the_frames_line():
+ prompt = pixel_draw.generation_prompt(pixel_request(frames=("a", "b"), motion="a bow"))
+ lines = prompt.splitlines()
+ assert lines[lines.index(next(l for l in lines if l.startswith("Frames:"))) + 1] == (
+ "Motion: the frames, in this order, are one continuous motion: a bow")
+ pick = pixel_draw.pick_prompt(pixel_request(frames=("a", "b"), motion="a bow"), ["A", "B"])
+ assert "one motion in their order (a bow)" in pick
+
+
+def swing_grid(count: int = 46, size: int = 48) -> str:
+ """A synthetic 48 px figure twirling a blade, one turn over the set: the arm raised above the head
+ for frames 11-20, those held for frames 21-24, every other frame its own drawing, the feet on the
+ floor row (44 counted from 1) throughout."""
+ def frame(i: int) -> list[str]:
+ px = [["."] * size for _ in range(size)]
+ for y in range(16, 44):
+ for x in range(18, 30):
+ px[y][x] = "a"
+ for y in range(10, 16):
+ for x in range(21, 27):
+ px[y][x] = "b"
+ raised = 11 <= i <= 24
+ hand = (6, 31) if raised else (26, 31)
+ for y in range(hand[0], hand[0] + 8):
+ px[y][30] = px[y][31] = "c"
+ angle = 2 * math.pi * (min(i, 20) if 21 <= i <= 24 else i) / count
+ for step in range(1, 10):
+ y = round(hand[0] - step * math.cos(angle))
+ x = round(hand[1] + step * math.sin(angle))
+ if 4 <= y <= 43 and 0 <= x < size:
+ px[y][x] = "d"
+ return ["".join(row) for row in px]
+
+ body = "".join(f"FRAME s{i:02d}\n" + "\n".join(frame(i)) + "\n" for i in range(1, count + 1))
+ return "PALETTE\n. transparent\na #3a2f4e\nb #e8b890\nc #d8a880\nd #c0c8d8\n" + body + "END\n"
+
+
+def test_forty_six_frames_of_one_motion_pass_as_a_grid(tmp_path, capsys):
+ grid = tmp_path / "swing.txt"
+ grid.write_text(swing_grid(), encoding="utf-8")
+ out = tmp_path / "out"
+ assert pixel_draw.main(["--grid", str(grid), "--out-dir", str(out), "--motion", "a sword twirl",
+ "--duration-ms", "100"]) == 0
+ report = report_of(out)
+ assert json.loads(capsys.readouterr().out) == report
+ g6 = report["gates"]["G6"]
+ assert report["status"] == "ok" and g6["ok"] and g6["rule"] == "motion"
+ assert len(set(g6["baselines"].values())) == 1 and g6["resized"] == []
+ assert g6["posed"] == [f"s{i:02d}" for i in range(11, 25)]
+ assert g6["holds"] == [["s20", "s21"], ["s20", "s22"], ["s20", "s23"], ["s20", "s24"], ["s21", "s22"],
+ ["s21", "s23"], ["s21", "s24"], ["s22", "s23"], ["s22", "s24"], ["s23", "s24"]]
+ assert not any(w.startswith("G6") for w in report["warnings"])
+ assert [line[:40] for line in report["info"] if line.startswith("G6")] == [
+ "G6 the height changes with the pose, not", "G6 frames drawn the same, a hold (inform"]
+ assert report["request"]["motion"] == "a sword twirl" and report["request"]["duration_ms"] == 100
+ with Image.open(out / "anim.gif") as gif: # the four frames held are one GIF frame, shown five times as long
+ durations = [frame.info["duration"] for frame in ImageSequence.Iterator(gif)]
+ assert len(durations) == 42 and sum(durations) == 46 * 100 and durations[19] == 500
+ with Image.open(out / report["files"]["preview"]) as preview:
+ assert preview.size == (8 * 240 + 7 * 10, 6 * 240 + 5 * 10) # rows of eight frames
+ with pytest.raises(SystemExit, match="fails G6"):
+ pixel_draw.main(["--grid", str(grid), "--out-dir", str(tmp_path / "still")])
+
+
+def test_the_frame_time_is_a_flag_with_its_default_kept(tmp_path):
+ grid = tmp_path / "swing.txt"
+ grid.write_text(swing_grid(count=4), encoding="utf-8")
+ assert pixel_draw.main(["--grid", str(grid), "--out-dir", str(tmp_path / "a"), "--motion", "x"]) == 0
+ with Image.open(tmp_path / "a" / "anim.gif") as gif:
+ assert gif.info["duration"] == 150
+ with pytest.raises(SystemExit, match="--duration-ms is at least 10, got 5"):
+ pixel_draw.main(["--grid", str(grid), "--out-dir", str(tmp_path / "b"), "--duration-ms", "5"])
+ with pytest.raises(SystemExit, match="--grid checks and renders a grid as it is; drop --style"):
+ pixel_draw.main(["--grid", str(grid), "--out-dir", str(tmp_path / "c"), "--style", "x"])
+
+
+def test_an_effect_strip_takes_the_frame_time(tmp_path):
+ rows = "\n".join("." * 8 for _ in range(8))
+ spark = "\n".join(("...aa..." if y in (3, 4) else "." * 8) for y in range(8))
+ grid = tmp_path / "fx.txt"
+ grid.write_text(f"PALETTE\n. transparent\na #ffcc00\nFRAME birth\n{spark}\nFRAME gone\n{rows}\nEND\n",
+ encoding="utf-8")
+ out = tmp_path / "out"
+ assert pixel_draw.main(["--grid", str(grid), "--kind", "effect", "--out-dir", str(out), "--duration-ms", "80"]) == 0
+ meta = json.loads((out / "effect.strip.json").read_text(encoding="utf-8"))
+ assert meta["delay_ms"] == 80
+
+
+# ----------------------------------------------------------------------------- the pick sheet
+
+def test_a_sheet_of_many_frames_fits_what_the_vision_model_reads_unscaled(tmp_path):
+ """Forty-six 48 px frames in rows of eight, two candidates: drawn at x5 the sheet is past the
+ 2576 px long edge and the 4784 patches Claude reads unscaled, so it is drawn at the largest whole
+ enlargement that fits - x3 - nearest-neighbour, every pixel still a square block."""
+ by_label = {}
+ for label, cid in (("A", "c1"), ("B", "c2")):
+ (tmp_path / cid).mkdir()
+ Image.new("RGBA", (8 * 240 + 7 * 10, 6 * 240 + 5 * 10), (40, 30, 46, 255)).save(tmp_path / cid / "p.png")
+ by_label[label] = pixel_draw.Candidate(cid, files={"preview": f"{cid}/p.png"})
+ sheet = Image.open(io.BytesIO(pixel_draw.pick_sheet(tmp_path, by_label, tile=False, scale=5)))
+ assert sheet.size == (16 + 56 + 8 * 144 + 7 * 6 + 16, 16 + 2 * (6 * 144 + 5 * 6 + 16))
+ assert max(sheet.size) <= 2576 and math.ceil(sheet.width / 28) * math.ceil(sheet.height / 28) <= 4784
+ small = pixel_draw.pick_sheet(tmp_path, {"A": by_label["A"]}, tile=False, scale=1)
+ assert Image.open(io.BytesIO(small)).size == (16 + 56 + 1990 + 16, 16 + 1490 + 16)
+
+
+def test_the_pick_reads_many_frames_in_rows():
+ names = tuple(f"s{i:02d}" for i in range(1, 47))
+ pick = pixel_draw.pick_prompt(pixel_request(frames=names, size=48, max_tokens=64000), ["A", "B"])
+ assert "Each candidate's 46 frames run left to right in rows of 8, top to bottom, in this order: s01, s02" in pick
diff --git a/tests/gen/test_pixel_effect.py b/tests/gen/test_pixel_effect.py
index c857c5d..39618b7 100644
--- a/tests/gen/test_pixel_effect.py
+++ b/tests/gen/test_pixel_effect.py
@@ -19,14 +19,18 @@ def test_only_effects_accept_two_to_eight_frames():
names = ",".join(f"f{i}" for i in range(8))
assert len(request("--kind", "effect", "--frames", names).frames) == 8
assert len(request("--kind", "effect").frames) >= 2
+ many = ",".join(f"f{i}" for i in range(65))
for kind in ("sprite", "icon", "tile"):
- with pytest.raises(SystemExit, match="at most 4"):
- request("--kind", kind, "--frames", names)
+ assert len(request("--kind", kind, "--frames", names).frames) == 8 # drawn four at a time
+ with pytest.raises(SystemExit, match="at most 64"):
+ request("--kind", kind, "--frames", many)
for names in ("only", ",".join(f"f{i}" for i in range(9))):
with pytest.raises(SystemExit, match="2.*8"):
request("--kind", "effect", "--frames", names)
with pytest.raises(SystemExit, match="walk-cycle"):
request("--kind", "effect", "--walk-cycle")
+ with pytest.raises(SystemExit, match="--motion does not apply to an effect"):
+ request("--kind", "effect", "--motion", "a burst")
prompt = draw.generation_prompt(request("--kind", "effect"))
assert "center" in prompt and "empty" in prompt and "brightness" in prompt
assert "same proportions" not in prompt and "floor" not in prompt
diff --git a/tests/gen/test_pixel_gates.py b/tests/gen/test_pixel_gates.py
index 6a3fbd7..8897d4e 100644
--- a/tests/gen/test_pixel_gates.py
+++ b/tests/gen/test_pixel_gates.py
@@ -342,3 +342,51 @@ def test_g8_reads_a_frames_opaque_box_off_the_image_paths_judgment(monkeypatch):
monkeypatch.setattr(extract, "solid_alpha_bbox", lambda image, threshold=128: (0, 3, 16, 13))
g8 = evaluate({"f": frame}, kind="sprite", rule=FREE16, walk_cycle=False)["G8"]
assert g8["frames"]["f"]["bbox"] == [0, 3, 15, 12] and g8["frames"]["f"]["size"] == [16, 10]
+
+
+# ----------------------------------------------------------------------------- G6 of one motion
+
+def lifted(frame, rows: int):
+ """`frame` drawn `rows` rows higher."""
+ return frame[rows:] + [[CLEAR] * len(frame[0]) for _ in range(rows)]
+
+
+def test_g6_of_a_motion_lets_a_raised_arm_and_a_hold_through_and_still_fails_the_ground():
+ """One motion (`--motion`, or a walk cycle): the frames must stand on one ground row, but an arm
+ raised over the head changes the height with the pose - its height, mass and breadth part, so the
+ image path's size reading (`gait_fallback.size_change`) says the body did not grow - and a frame
+ drawn twice is a hold."""
+ side = paint(paint(canvas(), 8, 10, 23, 28), 24, 14, 25, 20) # a body and an arm at its side
+ raised = paint(paint(canvas(), 8, 10, 23, 28), 24, 3, 25, 9) # the same arm over the head
+ frames = {"a": side, "b": raised, "c": [r[:] for r in raised]}
+ still = evaluate(frames, kind="sprite", rule=FREE16, walk_cycle=False)
+ assert still["failed"] == ["G6"] # without --motion, as before
+ gates = evaluate(frames, kind="sprite", rule=FREE16, walk_cycle=False, motion=True)
+ g6 = gates["G6"]
+ assert gates["ok"] and g6["ok"] and g6["rule"] == "motion"
+ assert g6["heights"] == {"a": 19, "b": 26, "c": 26} and g6["posed"] == ["b", "c"] and g6["resized"] == []
+ assert g6["size_change"]["b"]["change"] == 0.0 and g6["holds"] == [["b", "c"]]
+ assert not any(w.startswith("G6") for w in gates["warnings"])
+ assert [line for line in gates["info"] if line.startswith("G6")] == [
+ "G6 the height changes with the pose, not the body's size (informational, no action): b 26 px, c 26 px "
+ "against a 19 px",
+ "G6 frames drawn the same, a hold (informational, no action): b=c"]
+ off = evaluate({**frames, "d": lifted(frames["a"], 2)}, kind="sprite", rule=FREE16, walk_cycle=False, motion=True)
+ assert off["failed"] == ["G6"] and off["G6"]["baselines"]["d"] == 26
+
+
+def test_g6_of_a_motion_warns_a_body_drawn_larger():
+ small = paint(canvas(), 10, 12, 21, 28)
+ large = paint(canvas(), 8, 7, 23, 28)
+ gates = evaluate({"a": small, "b": large}, kind="sprite", rule=FREE16, walk_cycle=False, motion=True)
+ g6 = gates["G6"]
+ assert gates["ok"] and g6["resized"] == ["b"] and g6["posed"] == []
+ assert g6["size_change"]["b"]["change"] > 0.25
+ assert [w for w in gates["warnings"] if w.startswith("G6")] == [
+ "G6 the body changes size, not only its pose - its height, mass and breadth all grow or shrink by more "
+ "than a pixel: b +29% against a"]
+
+
+def test_a_walk_cycle_is_a_motion():
+ gates = evaluate(frames_of("walk-32-safe-area-pass.txt", 32, WALK), kind="sprite", rule=FREE16, walk_cycle=True)
+ assert gates["G6"]["rule"] == "motion" and gates["G6"]["walk"]["warn"]
diff --git a/tests/gen/test_pixel_grid.py b/tests/gen/test_pixel_grid.py
index 1b71711..fadc8ab 100644
--- a/tests/gen/test_pixel_grid.py
+++ b/tests/gen/test_pixel_grid.py
@@ -288,3 +288,36 @@ def test_one_block_reads_as_it_always_did():
assert pg.parse_answer(whole, "chargrid", 8, 8, ("icon",))[1] == []
assert pg.parse_answer("text then " + whole + " and a note", "chargrid", 8, 8, ("icon",))[1] == []
+
+# ----------------------------------------------------------------------------- the palette held across answers
+
+def test_a_later_answer_keeps_the_palette_it_was_given():
+ """A later answer of a set larger than one call writes the first answer's palette again: a key it
+ adds is refused (its rows go to the row repair) and a colour it changes is put back, both recorded."""
+ held = {".": None, "a": "#2a1f2e", "b": "#c8a040"}
+ rows = ["........", ".aaaaaa.", ".abbbba.", ".acccca.", ".aaaaaa.", ".aaaaaa.", ".aaaaaa.", "........"]
+ text = _block(". transparent\na #2a1f2e\nb #ffffff\nc #ff0000", {"f5": rows})
+ grid, issues = pg.parse_answer(text, "chargrid", 8, 8, ("f5",))
+ assert issues == []
+ grid, issues = pg.hold_palette(grid, issues, held)
+ assert grid.palette == held
+ assert [i.to_dict() for i in pg.recovered(issues)] == [
+ {"code": "palette_changed", "detail": "b #ffffff, kept #c8a040"}, {"code": "palette_added", "detail": "c #ff0000"}]
+ assert [(i.code, i.frame, i.row) for i in pg.row_issues(issues)] == [("unknown_symbol", "f5", 4)]
+
+
+def test_parts_are_joined_in_order_under_the_first_palette():
+ one, _ = pg.parse_answer(_block(". transparent\na #112233", {"f1": ROWS8, "f2": ROWS8}), "chargrid", 8, 8, ("f1", "f2"))
+ two, _ = pg.parse_answer(_block(". transparent\na #112233", {"f3": ROWS8}), "chargrid", 8, 8, ("f3",))
+ joined = pg.joined([one, two])
+ assert list(joined.frames) == ["f1", "f2", "f3"] and joined.palette == one.palette
+ assert pg.to_text(joined).count("FRAME ") == 3
+
+
+def test_a_preview_of_more_than_eight_frames_wraps_into_rows():
+ frame = [[(17, 34, 51, 255)] * 8 for _ in range(8)]
+ four = pg.preview_strip([frame] * 4, 2)
+ assert four.size == (4 * 16 + 3 * 4, 16) # one row, as before
+ ten = pg.preview_strip([frame] * 10, 2)
+ assert ten.size == (8 * 16 + 7 * 4, 2 * 16 + 4)
+ assert ten.getpixel((0, 20)) == (17, 34, 51, 255) and ten.getpixel((40, 20)) == (0, 0, 0, 0) # the third place of the second row is empty