Skip to content

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

docs: define game-pack version 2 images, tiles and ui sections

Soohong Kim174cfe8cbd31
diff --git a/docs/README.md b/docs/README.md
index 2b122d6..75cf12e 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -22,7 +22,7 @@ flowchart LR
end
subgraph C["C · utilities"]
direction LR
- c1[cutout] ~~~ c2[slice-sheet] ~~~ c3[unpack-atlas]
+ c1[cutout] ~~~ c2[slice-sheet] ~~~ c4[ui-kit] ~~~ c3[unpack-atlas]
end
subgraph D["D · post-processing"]
direction LR
@@ -41,7 +41,7 @@ flowchart LR
|---|---|---|
| **A · atlas rows** — one still becomes a runtime sprite sheet | [run-contract.md](run-contract.md) | `prepare` → `gen` / `gen-set` → `extract` → `compose-atlas`; optional `curation` and recompose |
| **B · video → loop** — one still becomes transparent motion loops | [video-pipeline.md](video-pipeline.md) | `video-canvas` → `video` (or `video-prompt` and a video MCP on your agent) → `video-frames` → `video-loop`, `video-set`, `video-cycle-align`, `video-follow` (`video-follow-inspect` shows every cell of it and moves nothing), `video-set-sheet` (a set's directions on one sheet, on one ground line); `handed-check` for an item on one side |
-| **C · utilities** — imported images in, clean cuts out | [sheet-slicing.md](sheet-slicing.md) | `cutout`, `slice-sheet`, `unpack-atlas` |
+| **C · utilities** — imported images in, clean cuts out | [sheet-slicing.md](sheet-slicing.md) | `cutout`, `slice-sheet`, `ui-kit`, `unpack-atlas` |
| **D · post-processing** — finished sheets, refined | [recolor.md](recolor.md) | `recolor`, `recolor-palette`, `compose-layers`, breathing (compose), `export-pngs`, `export-aseprite` |
| **E · asset tools** — independent background, shadow and motion tools | [asset-tools.md](asset-tools.md) | `background-tile`, `shadow`, `inspect-motion` |
| **S · scene** — optional composition of existing assets | [scene.md](scene.md) | `scene-render`, `scene-inspect` |
@@ -119,6 +119,7 @@ grouping is derived from `sprite_gen/_modules.py`, the one taxonomy table.
|---|---|
| [directional-anchor-workflow.md](directional-anchor-workflow.md) | Directional / 45° rows: base → direction anchors → rows, the left-right gate |
| [sheet-slicing.md](sheet-slicing.md) | Multi-figure grid sheets to per-cell standing cuts; the `cutout` routes |
+| [ui-kit.md](ui-kit.md) | The UI kit layout guide, splitting a transparent UI kit sheet into nine-slice elements with measured insets and padding, and the shared alpha haze cleanup |
## QA
diff --git a/docs/game-pack.md b/docs/game-pack.md
index 67421c0..147c0fe 100644
--- a/docs/game-pack.md
+++ b/docs/game-pack.md
@@ -161,6 +161,108 @@ function registerGamePack(scene, imagesInPageOrder, pack) {
`addAtlasJSONHash` assigns `sourceIndex` offsets to frames across pages. The game runtime is responsible for reading `durations_ms` and applying animation playback policies (`repeat = anim.loop ? -1 : 0`, `hold_last`, `blend`, and `events`).
+## Version 2: images, tiles and UI
+
+Version 2 adds three sections for painted scene art: single images such as props (`images`), repeating ground tiles (`tiles`) and a UI kit with nine-slice frames and icons (`ui`). A request opts in with `"version": 2`; the manifest it produces says `"version": 2`. A version 1 request is packed exactly as before: the same files with the same bytes, and a version 1 manifest that has none of the new keys. A version 1 request that names `images`, `tiles` or `ui` is refused instead of being packed without them.
+
+### Version 2 request
+
+```json
+{
+ "version": 2,
+ "assets": [
+ { "id": "hero", "source": "hero.strip.json", "display": { "height": 96 } }
+ ],
+ "images": [
+ { "id": "fountain", "source": "props/fountain.png", "display": { "height": 120 },
+ "anchor": [256, 725], "footprint": "base" },
+ { "id": "lantern", "source": "props/lantern.png", "display": { "height": 96 },
+ "footprint": { "x": 180, "y": 640, "w": 150, "h": 80 } }
+ ],
+ "tiles": [
+ { "id": "ground", "source": "ground-tile.png", "display": { "width": 480 } }
+ ],
+ "ui": {
+ "kit": "ui/ui-kit.json",
+ "scale": 0.5,
+ "icons": [
+ { "id": "sword", "source": "icons/sword.png", "display": { "height": 48 } }
+ ]
+ }
+}
+```
+
+* `assets` and `audio` keep their version 1 meaning. In version 2, `assets` may be empty or absent; the request must still declare at least one asset, image, tile, UI kit or icon.
+* Every `id` uses the asset name characters (`[A-Za-z0-9_.-]`) and is unique within its section.
+* `images[]`: one PNG each (a static image or a one-frame descriptor; more frames are refused). `display` takes exactly one of `width` or `height` (no `body_height`), and `resample` works as for assets. `anchor` is `[x, y]` in source pixels and defaults to the bottom centre of the image. `footprint` is optional: an explicit `{x, y, w, h}` rectangle in source pixels, or `"base"` for the measured base described below.
+* `tiles[]`: one PNG each, ideally a seamless tile from [`background-tile --axis xy`](asset-tools.md#repeating-tiles). `display` takes exactly one of `width` or `height`: the size of one tile on screen. The tile's pixels are never resampled: the pack stores the source pixels and states both sizes.
+* `ui.kit`: the JSON report a [`ui-kit`](ui-kit.md) run wrote. Every element it lists becomes a nine-slice entry, with the element PNGs it names (paths relative to the report). `ui.scale` (default `1`, positive) resizes every kit element by the same factor, so the kit stays one consistent set.
+* `ui.icons[]`: fixed images such as upgrade or weapon icons, with `id`, `source` and `display` as for `images` (no anchor or footprint).
+* The `"base"` footprint is measured on the source image: take the bounding box of pixels with alpha at least 128, keep its lowest fifth (rounded up, at least one row), and the footprint is the bounding box of the pixels with alpha at least 128 inside that band. It is where a prop meets the ground in a top-down or three-quarter view. It is a measurement, not a collision shape the art guarantees.
+
+### Version 2 manifest
+
+```json
+{
+ "kind": "sprite-gen-game-pack",
+ "version": 2,
+ "textures": [ "...as in version 1; image, ui and icon frames are atlas frames here..." ],
+ "animations": { "...as in version 1..." },
+ "images": {
+ "fountain": {
+ "frame": "image/fountain",
+ "size": { "w": 104, "h": 120 },
+ "anchor": [52, 120],
+ "footprint": { "x": 10, "y": 96, "w": 84, "h": 24 }
+ }
+ },
+ "tiles": {
+ "ground": {
+ "image": "tile-ground.png",
+ "webp": "tile-ground.webp",
+ "size": { "w": 960, "h": 960 },
+ "display_size": { "w": 480, "h": 480 }
+ }
+ },
+ "ui": {
+ "nine_slice": {
+ "panel": {
+ "frame": "ui/panel",
+ "size": { "w": 288, "h": 200 },
+ "stretch": "xy",
+ "insets": { "left": 56, "right": 56, "top": 46, "bottom": 46 },
+ "padding": { "left": 24, "right": 24, "top": 22, "bottom": 22 }
+ },
+ "hp_bar_frame": {
+ "frame": "ui/hp_bar_frame",
+ "size": { "w": 304, "h": 56 },
+ "stretch": "x",
+ "insets": { "left": 66, "right": 30, "top": 0, "bottom": 0 },
+ "padding": { "left": 70, "right": 34, "top": 18, "bottom": 18 }
+ }
+ },
+ "icons": {
+ "sword": { "frame": "icon/sword", "size": { "w": 48, "h": 48 } }
+ }
+ }
+}
+```
+
+A version 2 manifest always has `images`, `tiles` and `ui`, and `ui` always has `nine_slice` and `icons`; each may be empty (`{}`). Keys are the request ids and are sorted.
+
+What each field means, with no reading left to the consumer:
+
+* **Where the pixels are.** `images[*].frame`, `ui.nine_slice[*].frame` and `ui.icons[*].frame` are atlas frame names in `textures[].frames`, so they load with the atlas like animation frames. Their names are `image/<id>`, `ui/<id>` and `icon/<id>`. A tile is not in the atlas: `tiles[*].image` is its own PNG file in the pack (with a lossless WebP copy in `webp`), because a repeating texture needs its own image to wrap.
+* **Units.** Every size, anchor, footprint, inset and padding is in pixels of the image as stored in the pack, after the display resize: the frame's own pixels for atlas frames, the PNG's pixels for tiles. Nothing is in source pixels.
+* `images[*].size` is the stored frame size. `anchor` is `[x, y]` from the frame's top-left corner (a fraction where the scaled point falls between pixels, as for animation anchors), and the atlas frame's `pivot` is the same point normalised. `footprint` is `{x, y, w, h}` from the frame's top-left corner, or `null` when the request declared none. A source footprint is scaled outward to whole pixels (left and top rounded down, right and bottom rounded up) and kept inside the frame.
+* `tiles[*].size` is the stored PNG size. `display_size` is the on-screen size of one tile: draw the repeating texture with a tile scale of `display_size.w / size.w` horizontally and `display_size.h / size.h` vertically.
+* `ui.nine_slice[*].size` is the stored frame size. `stretch` says how the element may be resized: `"xy"` both ways (a nine-slice), `"x"` in width only (a three-slice whose height stays `size.h`; `top` and `bottom` are `0`), `"none"` not at all (draw it at `size`; every inset is `0`). `insets` are the widths of the fixed border slices: in Phaser, `scene.add.nineslice(x, y, texture, frame, width, height, insets.left, insets.right, insets.top, insets.bottom)`. The stretched middle lies between the insets, and every corner ornament the [`ui-kit`](ui-kit.md) run found lies inside them. When the pack resizes the kit by `ui.scale`, insets are scaled and rounded up, so an ornament never slides into the stretched middle. A scale so small that the insets leave no stretchable middle, or the padding no content area, is refused.
+* `padding` places the element's content: the inner area where a panel's text, a card's contents, a badge's digits or a bar's fill goes. For an element drawn at width `W` and height `H` (its stored size or any size its `stretch` allows), the content rectangle is `x = padding.left`, `y = padding.top`, `w = W - padding.left - padding.right`, `h = H - padding.top - padding.bottom`, from the element's top-left corner. For `hp_bar_frame` and `xp_bar_frame` this is the track: fill it from its left edge to show a fraction. Paddings are scaled with `ui.scale` and rounded up, so the content area only shrinks.
+* `ui.icons[*].size` is the stored frame size; icons are drawn as they are.
+* The atlas frames of images, UI elements and icons have `trimmed: false`, `rotated: false` and the same one-pixel extrusion as animation frames. UI element and icon frames have the pivot `{x: 0.5, y: 0.5}`.
+
+The UI kit element names are fixed by the [`ui-kit` layout](ui-kit.md#layout): `panel`, `button`, `button_pressed`, `card`, `hp_bar_frame`, `xp_bar_frame` and `timer_badge`. Their `stretch` is part of the layout: the four frames and buttons are `"xy"`, the two bar frames `"x"`, the timer badge `"none"`.
+
## Audio Assets and Playback
Game packs support optional bundled audio declared in pack recipes via `request.audio`:
diff --git a/docs/ui-kit.md b/docs/ui-kit.md
new file mode 100644
index 0000000..9066f6f
--- /dev/null
+++ b/docs/ui-kit.md
@@ -0,0 +1,122 @@
+# `ui-kit` — one painted sheet to nine-slice UI elements
+
+> Owns: The UI kit layout guide, splitting a transparent UI kit sheet into elements, nine-slice insets and content padding · Index: [docs/README.md](README.md)
+
+A game UI kit is one transparent image with every frame on it: a panel, a button and its pressed state, a card frame, two bar frames and a timer badge. `gen --layout-guide ui-kit` asks the image model to draw each element in a fixed box. `ui-kit` cuts the sheet along those boxes, measures where each element may stretch, and writes one PNG per element with a JSON report. [`game-pack`](game-pack.md#version-2-images-tiles-and-ui) reads that report.
+
+## Generate the sheet
+
+```bash
+sprite-gen gen --provider openai --quality high --transparent --aspect-ratio 1:1 \
+ --layout-guide ui-kit --prompt-file uikit-prompt.txt --out uikit.png
+```
+
+`--layout-guide ui-kit` draws the [layout](#layout) as a guide image, attaches it after any `--ref`, and adds a sentence to the prompt that names every box and what to draw in it. The caller's prompt describes the style: material, palette, trim, mood. It does not need to list the elements or their positions. The guide asks for straight, even edges between corner ornaments, empty element centres, no text and empty space between elements, because only those can be nine-sliced. The sheet must be square; `--aspect-ratio 1:1` gives that on every provider that takes a ratio.
+
+## Layout
+
+The guide and the splitter read one table (`sprite_gen.frames.ui_kit.LAYOUT`). Boxes are in pixels of a 1024 × 1024 sheet and scale with the sheet's size; neighbouring boxes are 48 px apart.
+
+| Element | Box (x, y, w, h) | Stretch | Content |
+|---|---|---|---|
+| `panel` | 48, 48, 576, 400 | `xy` | a large frame with an empty centre |
+| `button` | 672, 48, 304, 128 | `xy` | a wide button, normal state |
+| `button_pressed` | 672, 224, 304, 128 | `xy` | the same button, pressed |
+| `card` | 704, 400, 272, 576 | `xy` | a tall card frame with an empty centre |
+| `hp_bar_frame` | 48, 496, 608, 112 | `x` | an empty horizontal health bar frame |
+| `xp_bar_frame` | 48, 656, 608, 112 | `x` | an empty horizontal experience bar frame |
+| `timer_badge` | 48, 816, 160, 160 | `none` | a small round badge with an empty centre |
+
+`stretch` is how a game may resize the element: `xy` as a nine-slice, `x` in width only (a three-slice), `none` not at all. It belongs to the layout, not to the measurement.
+
+## Split the sheet
+
+```bash
+sprite-gen ui-kit --sheet uikit.png --out-dir ui/
+```
+
+The command writes `ui/<element>.png` for every element of the layout and `ui/ui-kit.json`. It never changes the sheet and refuses an output directory that holds the sheet. Options:
+
+* `--alpha-floor N` (default `64`, `0` turns it off) and `--alpha-edge N` (default `2`): the [alpha cleanup](#alpha-cleanup) that runs before anything is cut.
+* `--report PATH`: write the JSON report elsewhere (default `<out-dir>/ui-kit.json`).
+
+1. **Alpha cleanup.** Faint haze between elements would join them, so it is cleared first (below).
+2. **Parts.** Pixels with alpha above zero form 8-connected parts. A part smaller than 16 pixels is dropped and counted.
+3. **Assignment.** Each part goes to the box that contains its centroid, with every box widened by half the gap (24 px at 1024). A part whose centroid lies in no widened box is reported under `unassigned`; it makes the report `needs-review` when it has at least 16 pixels.
+4. **Crop.** An element is the bounding box of its box's parts, so ornaments that reach past the box stay whole. A box with no part fails the command: the sheet has to be generated again.
+5. **Insets** and **padding** are measured on the cropped element (below).
+
+## Insets
+
+Insets are measured only along the axes the layout lets the element stretch; the others are `0`. Along x (columns; y is the same with rows):
+
+1. Colours are taken premultiplied by alpha, with alpha as a fourth channel, in 8-bit units.
+2. The reference band is the middle fifth of the columns (from 40 % to 60 % of the width). The reference column is the per-row median over that band.
+3. A pixel deviates when its largest channel difference from the reference column, in its row, exceeds twice the largest difference found in the reference band in that row, plus 8.
+4. A column with no deviating pixel is plain. The stretch band is the run of plain columns that contains the reference band.
+5. `left` is the band's first column plus a 2 px margin, and `right` is the distance from the band's end to the right edge plus 2 px; a side with no deviating column at all gets `0`.
+
+So every column with an ornament, a cap or a border line lies inside a fixed slice, and the stretched middle holds only columns that look like the middle of the element. When an ornament reaches the reference band itself, the band cannot grow on that side and the report says so (`needs-review`). A frame with an ornament in the middle of an edge cannot be nine-sliced; regenerate it.
+
+## Padding
+
+Padding places the content (text, a card's contents, a bar's fill, a badge's digits). On the element's middle five rows, take the per-column median; the interior is the run of columns around the centre whose largest channel difference from the centre pixel is at most 32. The same on the middle five columns gives the interior rows. When a corner of that rectangle is not interior (a round badge), the rectangle shrinks evenly toward the centre until all four corners are. Each padding is the distance from an element edge to that rectangle, plus 2 px. A content area narrower or shorter than a quarter of its element makes the report `needs-review`: the centre was probably not empty.
+
+## Alpha cleanup
+
+Transparent sheets from image models often carry a faint alpha haze: barely visible pixels around and between the drawn objects. The cleanup is shared by `ui-kit` and [`slice-sheet --alpha-floor`](sheet-slicing.md#transparent-sheets) (`sprite_gen.frames.alpha_floor.clear_haze`).
+
+* A pixel at or above the floor (`--alpha-floor`) is solid. A pixel above zero and below the floor is faint.
+* A faint pixel within `--alpha-edge` pixels (8-connected, so diagonals count) of a solid pixel is part of an object's anti-aliased edge and is kept unchanged.
+* Every other faint pixel is haze and becomes fully transparent (`0, 0, 0, 0`).
+
+Solid pixels and edge pixels are never changed, so a stroke stays whole as long as some of its pixels reach the floor. A stroke drawn entirely below the floor is indistinguishable from haze and is removed: lower the floor for very faint art. The report measures instead of asserting: it counts what actually changed.
+
+| Field | Meaning |
+|---|---|
+| `floor`, `edge_px` | the settings |
+| `pixels` | pixels in the image |
+| `faint_fraction_before`, `faint_fraction_after` | share of all pixels with alpha from 1 to `floor - 1`, before and after |
+| `haze_fraction_before`, `haze_fraction_after` | share of all pixels that are faint and farther than `edge_px` from a solid pixel |
+| `cleared_pixels` | pixels made transparent |
+| `changed_solid_pixels`, `changed_edge_pixels` | solid and kept-edge pixels whose value changed; `0` unless the cleanup is wrong |
+
+## Report
+
+`ui-kit.json`:
+
+```json
+{
+ "kind": "sprite-gen-ui-kit",
+ "version": 1,
+ "sheet": "/abs/path/uikit.png",
+ "sheet_size": [1024, 1024],
+ "status": "pass",
+ "review_reasons": [],
+ "alpha_cleanup": { "floor": 64, "edge_px": 2, "...": "..." },
+ "dropped_parts": 3,
+ "unassigned": [],
+ "elements": {
+ "panel": {
+ "file": "panel.png",
+ "box": { "x": 48, "y": 48, "w": 576, "h": 400 },
+ "rect": { "x": 52, "y": 50, "w": 570, "h": 396 },
+ "size": { "w": 570, "h": 396 },
+ "stretch": "xy",
+ "insets": { "left": 112, "right": 110, "top": 92, "bottom": 90 },
+ "padding": { "left": 40, "right": 40, "top": 38, "bottom": 38 },
+ "parts": 1
+ }
+ }
+}
+```
+
+`box` is the layout box scaled to this sheet and `rect` the element's bounding box, both in sheet pixels. `file` is relative to the report. `size`, `insets` and `padding` are in pixels of the element PNG. Elements appear in layout order. `status` is `needs-review` when any `review_reasons` apply; the PNGs are written either way, so the elements can be inspected.
+
+Like every measurement here, `pass` means the numbers found nothing to flag. Look at the elements stretched to a few sizes before shipping them.
+
+## Python API
+
+* `sprite_gen.frames.ui_kit.split_ui_kit(image, *, alpha_floor=64, alpha_edge=2) -> (elements, report)`: the elements as images by name, and the report without file names.
+* `sprite_gen.frames.ui_kit.measure_insets(image, stretch) -> dict` and `measure_padding(image) -> dict`.
+* `sprite_gen.frames.alpha_floor.clear_haze(image, *, floor=64, edge=2) -> (image, report)`.
diff --git a/tests/compose/test_game_pack_v2.py b/tests/compose/test_game_pack_v2.py
new file mode 100644
index 0000000..7fdf780
--- /dev/null
+++ b/tests/compose/test_game_pack_v2.py
@@ -0,0 +1,321 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Pack contract version 2 (docs/game-pack.md "Version 2"): images, tiles and ui sections.
+
+The manifest is checked field by field against the contract, with exact key sets, so a
+consumer never meets a field the doc does not define. A version 1 request keeps its bytes:
+the manifest text and every page's pixels are frozen below from the packer before version 2.
+"""
+import hashlib
+import json
+import math
+
+import pytest
+from PIL import Image, ImageDraw
+
+from sprite_gen.compose import game_pack
+from sprite_gen.util.resample import resize_cell
+
+
+def write_json(path, data):
+ path.write_text(json.dumps(data), encoding="utf-8")
+ return path
+
+
+def prop(path, size=(40, 60)):
+ """A tall prop on a transparent canvas: a pole over a wide base slab, so the base differs from the bbox."""
+ image = Image.new("RGBA", size, (0, 0, 0, 0))
+ draw = ImageDraw.Draw(image)
+ draw.rectangle((16, 4, 23, 49), fill=(90, 120, 200, 255))
+ draw.rectangle((6, 50, 33, 57), fill=(120, 110, 90, 255))
+ image.save(path)
+ return image
+
+
+def tile(path, size=(24, 16)):
+ image = Image.new("RGBA", size)
+ image.putdata([((x * 37) % 256, (y * 53) % 256, (x * y) % 256, 255) for y in range(size[1]) for x in range(size[0])])
+ image.save(path)
+ return image
+
+
+def element(path, size, color):
+ image = Image.new("RGBA", size, (0, 0, 0, 0))
+ draw = ImageDraw.Draw(image)
+ draw.rectangle((0, 0, size[0] - 1, size[1] - 1), outline=color, width=3)
+ draw.rectangle((3, 3, size[0] - 4, size[1] - 4), fill=(20, 30, 50, 200))
+ image.save(path)
+ return image
+
+
+UI_ELEMENTS = {
+ "panel": ((40, 30), "xy", {"left": 7, "right": 5, "top": 6, "bottom": 3}, {"left": 4, "right": 4, "top": 4, "bottom": 5}),
+ "hp_bar_frame": ((48, 12), "x", {"left": 9, "right": 5, "top": 0, "bottom": 0}, {"left": 10, "right": 6, "top": 3, "bottom": 3}),
+ "timer_badge": ((16, 16), "none", {"left": 0, "right": 0, "top": 0, "bottom": 0}, {"left": 5, "right": 5, "top": 5, "bottom": 5}),
+}
+
+
+def ui_kit_report(directory):
+ directory.mkdir()
+ elements, images = {}, {}
+ for index, (name, (size, stretch, insets, padding)) in enumerate(UI_ELEMENTS.items()):
+ images[name] = element(directory / f"{name}.png", size, (200, 40 * index, 90, 255))
+ elements[name] = {"file": f"{name}.png", "box": {"x": 0, "y": 0, "w": 64, "h": 64},
+ "rect": {"x": 1, "y": 1, "w": size[0], "h": size[1]},
+ "size": {"w": size[0], "h": size[1]}, "stretch": stretch,
+ "insets": insets, "padding": padding, "parts": 1}
+ write_json(directory / "ui-kit.json", {
+ "kind": "sprite-gen-ui-kit", "version": 1, "sheet": "/unused/sheet.png", "sheet_size": [256, 256],
+ "status": "pass", "review_reasons": [], "alpha_cleanup": None, "dropped_parts": 0, "unassigned": [],
+ "elements": elements,
+ })
+ return images
+
+
+def scene_request(tmp_path, **override):
+ prop(tmp_path / "pillar.png")
+ prop(tmp_path / "stone.png", size=(30, 20))
+ tile(tmp_path / "ground.png")
+ Image.new("RGBA", (10, 10), (250, 200, 40, 255)).save(tmp_path / "sword.png")
+ ui_kit_report(tmp_path / "ui")
+ document = {
+ "version": 2,
+ "assets": [{"id": "coin", "source": "sword.png", "display": {"height": 5}}],
+ "images": [
+ {"id": "pillar", "source": "pillar.png", "display": {"height": 30}, "footprint": "base"},
+ {"id": "stone", "source": "stone.png", "display": {"width": 15}, "anchor": [10, 18],
+ "footprint": {"x": 3, "y": 11, "w": 9, "h": 5}},
+ {"id": "plain", "source": "stone.png", "display": {"width": 30}},
+ ],
+ "tiles": [{"id": "ground", "source": "ground.png", "display": {"width": 12}}],
+ "ui": {"kit": "ui/ui-kit.json", "scale": 0.5,
+ "icons": [{"id": "sword", "source": "sword.png", "display": {"height": 20}, "resample": "nearest"}]},
+ }
+ document.update(override)
+ return write_json(tmp_path / "game.json", document)
+
+
+def atlas_frames(result):
+ return {name: (page, record) for page in result["textures"] for name, record in page["frames"].items()}
+
+
+def crop(out, result, name):
+ page, record = atlas_frames(result)[name]
+ rect = record["frame"]
+ with Image.open(out / page["image"]) as image:
+ return image.crop((rect["x"], rect["y"], rect["x"] + rect["w"], rect["y"] + rect["h"])), record
+
+
+def all_ints(value):
+ if isinstance(value, dict):
+ return all(all_ints(v) for v in value.values())
+ if isinstance(value, list):
+ return all(all_ints(v) for v in value)
+ return type(value) is int
+
+
+def test_version_2_manifest_has_exactly_the_documented_sections(tmp_path):
+ out = tmp_path / "out"
+ result = game_pack.pack(scene_request(tmp_path), out)
+ assert json.loads((out / "game-pack.json").read_text()) == result
+ assert result["version"] == 2
+ assert set(result) == {"kind", "version", "textures", "animations", "images", "tiles", "ui"}
+ assert set(result["ui"]) == {"nine_slice", "icons"}
+ assert list(result["images"]) == sorted(result["images"]) == ["pillar", "plain", "stone"]
+ assert "coin" in result["animations"]
+
+
+def test_images_are_atlas_frames_with_anchor_and_footprint_in_stored_pixels(tmp_path):
+ out = tmp_path / "out"
+ result = game_pack.pack(scene_request(tmp_path), out)
+ pillar, stone, plain = (result["images"][key] for key in ("pillar", "stone", "plain"))
+ for entry in (pillar, stone, plain):
+ assert set(entry) == {"frame", "size", "anchor", "footprint"}
+ # height 30 from 60: scale 0.5, a 20 x 30 frame; default anchor is the bottom centre
+ assert pillar["frame"] == "image/pillar"
+ assert pillar["size"] == {"w": 20, "h": 30}
+ assert pillar["anchor"] == [10, 30]
+ # base: opaque bbox rows 4..57 (54 rows), lowest fifth = ceil(54 / 5) = 11 rows (47..57); opaque there:
+ # the pole x 16..23 for rows 47..49 and the slab x 6..33 rows 50..57 -> x 6..33, y 47..57 in source pixels,
+ # scaled outward: x 3..17 (floor 3, ceil 17), y 23..29 (floor 23.5 -> 23, ceil 29) -> {3, 23, 14, 6}
+ assert pillar["footprint"] == {"x": 3, "y": 23, "w": 14, "h": 6}
+ # width 15 from 30: scale 0.5; anchor [10, 18] -> [5, 9]; footprint x 3..12, y 11..16 -> 1..6, 5..8
+ assert stone["size"] == {"w": 15, "h": 10}
+ assert stone["anchor"] == [5, 9]
+ assert stone["footprint"] == {"x": 1, "y": 5, "w": 5, "h": 3}
+ assert plain["footprint"] is None
+ image, record = crop(out, result, "image/pillar")
+ assert image.size == (20, 30)
+ with Image.open(tmp_path / "pillar.png") as source:
+ assert image.tobytes() == resize_cell(source.convert("RGBA"), (20, 30)).tobytes()
+ assert record["pivot"] == {"x": 0.5, "y": 1.0}
+ assert record["trimmed"] is False and record["rotated"] is False
+ _, record = crop(out, result, "image/stone")
+ assert record["pivot"] == {"x": 5 / 15, "y": 9 / 10}
+ assert all_ints([[entry["size"], entry["footprint"] or {}] for entry in result["images"].values()])
+
+
+def test_tiles_are_separate_files_with_stored_and_display_sizes(tmp_path):
+ out = tmp_path / "out"
+ result = game_pack.pack(scene_request(tmp_path), out)
+ ground = result["tiles"]["ground"]
+ assert ground == {"image": "tile-ground.png", "webp": "tile-ground.webp",
+ "size": {"w": 24, "h": 16}, "display_size": {"w": 12, "h": 8}}
+ assert "tile-ground" not in json.dumps(result["textures"])
+ with Image.open(tmp_path / "ground.png") as source, Image.open(out / ground["image"]) as png, \
+ Image.open(out / ground["webp"]) as webp:
+ assert png.format == "PNG" and webp.format == "WEBP"
+ pixels = source.convert("RGBA").tobytes()
+ assert png.convert("RGBA").tobytes() == pixels
+ assert webp.convert("RGBA").tobytes() == pixels
+
+
+def test_ui_nine_slice_insets_and_padding_are_in_stored_frame_pixels(tmp_path):
+ out = tmp_path / "out"
+ result = game_pack.pack(scene_request(tmp_path), out)
+ nine = result["ui"]["nine_slice"]
+ assert list(nine) == sorted(UI_ELEMENTS)
+ for name, (size, stretch, insets, padding) in UI_ELEMENTS.items():
+ entry = nine[name]
+ assert set(entry) == {"frame", "size", "stretch", "insets", "padding"}
+ assert entry["frame"] == f"ui/{name}"
+ stored = (round(size[0] * 0.5), round(size[1] * 0.5))
+ assert entry["size"] == {"w": stored[0], "h": stored[1]}
+ assert entry["stretch"] == stretch
+ # scaled and rounded up: an ornament inside an inset stays inside it, content only shrinks
+ assert entry["insets"] == {side: math.ceil(value * 0.5) for side, value in insets.items()}
+ assert entry["padding"] == {side: math.ceil(value * 0.5) for side, value in padding.items()}
+ assert set(entry["insets"]) == set(entry["padding"]) == {"left", "right", "top", "bottom"}
+ image, record = crop(out, result, entry["frame"])
+ with Image.open(tmp_path / "ui" / f"{name}.png") as source:
+ assert image.tobytes() == resize_cell(source.convert("RGBA"), stored).tobytes()
+ assert record["pivot"] == {"x": 0.5, "y": 0.5}
+ assert nine["hp_bar_frame"]["insets"]["top"] == nine["hp_bar_frame"]["insets"]["bottom"] == 0
+ assert set(nine["timer_badge"]["insets"].values()) == {0}
+ assert all_ints({name: {k: v for k, v in entry.items() if k not in ("frame", "stretch")} for name, entry in nine.items()})
+
+
+def test_ui_icons_are_fixed_atlas_frames(tmp_path):
+ out = tmp_path / "out"
+ result = game_pack.pack(scene_request(tmp_path), out)
+ assert result["ui"]["icons"] == {"sword": {"frame": "icon/sword", "size": {"w": 20, "h": 20}}}
+ image, record = crop(out, result, "icon/sword")
+ assert image.getpixel((7, 7)) == (250, 200, 40, 255)
+ assert record["pivot"] == {"x": 0.5, "y": 0.5}
+
+
+def test_version_2_sections_default_to_empty_and_a_tile_only_pack_has_no_atlas(tmp_path):
+ tile(tmp_path / "ground.png")
+ request = write_json(tmp_path / "game.json", {
+ "version": 2, "tiles": [{"id": "ground", "source": "ground.png", "display": {"height": 32}}]})
+ out = tmp_path / "out"
+ result = game_pack.pack(request, out)
+ assert result["textures"] == [] and result["animations"] == {} and result["images"] == {}
+ assert result["ui"] == {"nine_slice": {}, "icons": {}}
+ assert result["tiles"]["ground"]["display_size"] == {"w": 48, "h": 32}
+ assert sorted(p.name for p in out.iterdir()) == ["game-pack.json", "tile-ground.png", "tile-ground.webp"]
+
+
+def test_version_2_output_is_deterministic(tmp_path):
+ request = scene_request(tmp_path)
+ game_pack.pack(request, tmp_path / "a")
+ game_pack.pack(request, tmp_path / "b")
+ read = lambda d: {p.name: p.read_bytes() for p in d.iterdir()}
+ assert read(tmp_path / "a") == read(tmp_path / "b")
+ assert str(tmp_path) not in (tmp_path / "a" / "game-pack.json").read_text()
+
+
[email protected]("change,message", [
+ ({"version": 1}, "version 2"),
+ ({"version": 3}, "version"),
+ ({"images": [{"id": "pillar", "source": "pillar.png", "display": {"body_height": 30}}]}, "width or height"),
+ ({"images": [{"id": "a", "source": "pillar.png", "display": {"height": 9}},
+ {"id": "a", "source": "stone.png", "display": {"height": 9}}]}, "duplicate"),
+ ({"images": [{"id": "pillar", "source": "pillar.png", "display": {"height": 9}, "footprint": "top"}]}, "footprint"),
+ ({"images": [{"id": "pillar", "source": "pillar.png", "display": {"height": 9},
+ "footprint": {"x": 0, "y": 0, "w": 0, "h": 4}}]}, "footprint"),
+ ({"tiles": [{"id": "ground", "source": "ground.png", "display": {"width": 12, "height": 8}}]}, "width or height"),
+ ({"ui": {"kit": "ui/ui-kit.json", "scale": 0}}, "scale"),
+ ({"ui": {"kit": "ui/ui-kit.json", "scale": 0.5, "extra": 1}}, "ui"),
+ ({"ui": {"kit": "ui/ui-kit.json", "scale": 0.05}}, "inset"),
+])
+def test_bad_version_2_requests_are_refused(tmp_path, change, message):
+ request = scene_request(tmp_path, **change)
+ with pytest.raises(ValueError, match=message):
+ game_pack.pack(request, tmp_path / "out")
+ assert not (tmp_path / "out").exists()
+
+
+def test_an_image_needs_exactly_one_frame(tmp_path):
+ strip = Image.new("RGBA", (8, 4), (255, 0, 0, 255))
+ strip.save(tmp_path / "two.png")
+ write_json(tmp_path / "two.json", {"frames": 2, "w": 4, "h": 4, "delay_ms": 100})
+ request = write_json(tmp_path / "game.json", {
+ "version": 2, "images": [{"id": "two", "source": "two.json", "display": {"height": 4}}]})
+ with pytest.raises(ValueError, match="one frame"):
+ game_pack.pack(request, tmp_path / "out")
+
+
+def test_a_ui_kit_report_must_be_a_ui_kit_report(tmp_path):
+ request = scene_request(tmp_path)
+ report = json.loads((tmp_path / "ui" / "ui-kit.json").read_text())
+ report["elements"]["panel"]["stretch"] = "y"
+ write_json(tmp_path / "ui" / "ui-kit.json", report)
+ with pytest.raises(ValueError, match="stretch"):
+ game_pack.pack(request, tmp_path / "out")
+ report["elements"]["panel"]["stretch"] = "xy"
+ report["kind"] = "sprite-gen-game-pack"
+ write_json(tmp_path / "ui" / "ui-kit.json", report)
+ with pytest.raises(ValueError, match="ui-kit"):
+ game_pack.pack(request, tmp_path / "out")
+
+
+def test_version_1_refuses_the_version_2_sections(tmp_path):
+ tile(tmp_path / "ground.png")
+ for section, value in (("images", []), ("tiles", []), ("ui", {})):
+ request = write_json(tmp_path / "game.json", {
+ "version": 1, "assets": [{"id": "g", "source": "ground.png", "display": {"height": 4}}], section: value})
+ with pytest.raises(ValueError, match="version 2"):
+ game_pack.pack(request, tmp_path / "out")
+
+
+def test_output_directory_must_not_hold_a_ui_kit_element(tmp_path):
+ request = scene_request(tmp_path)
+ with pytest.raises(ValueError, match="source"):
+ game_pack.pack(request, tmp_path / "ui")
+
+
+# A version 1 request, packed by the packer before version 2 existed (sprite-gen 2.44.0): the manifest's
+# exact bytes and each page's decoded pixels. Encoded PNG/WebP bytes depend on the zlib/libwebp build, so
+# the pages are compared as pixels; everything the packer itself decides is frozen.
+V1_MANIFEST_SHA256 = "f0c5d43dcb92d7717de82c7e284a1070dcda3493d80ad8e1e720d053141113de"
+V1_PAGE_PIXELS_SHA256 = ["36a1d358264c2b7c155fe07dac88b9b7d0f6c3d403eea86739cb59bfd6e811fa"]
+
+
+def v1_request(tmp_path):
+ strip = Image.new("RGBA", (36, 20))
+ for index, color in enumerate(((255, 0, 0, 255), (0, 128, 0, 200), (0, 0, 255, 90))):
+ strip.paste(Image.new("RGBA", (12, 20), color), (index * 12, 0))
+ strip.save(tmp_path / "walk.strip.png")
+ write_json(tmp_path / "walk.strip.json", {"frames": 3, "w": 12, "h": 20, "delay_ms": 80, "body_h": 16,
+ "anchor": [4, 18], "events": [{"frame": 1, "name": "impact"}]})
+ prop(tmp_path / "pillar.png")
+ return write_json(tmp_path / "game.json", {"version": 1, "assets": [
+ {"id": "walk", "source": "walk.strip.json", "display": {"body_height": 8}},
+ {"id": "pillar", "source": "pillar.png", "display": {"height": 30}},
+ {"id": "pixel", "source": "pillar.png", "display": {"height": 12}, "resample": "nearest"},
+ ]})
+
+
+def test_version_1_request_keeps_its_manifest_bytes_and_page_pixels(tmp_path):
+ out = tmp_path / "out"
+ game_pack.pack(v1_request(tmp_path), out)
+ manifest = (out / "game-pack.json").read_bytes()
+ assert hashlib.sha256(manifest).hexdigest() == V1_MANIFEST_SHA256
+ result = json.loads(manifest)
+ assert result["version"] == 1 and set(result) == {"kind", "version", "textures", "animations"}
+ pages = []
+ for page in result["textures"]:
+ with Image.open(out / page["image"]) as image:
+ pages.append(hashlib.sha256(image.convert("RGBA").tobytes()).hexdigest())
+ assert pages == V1_PAGE_PIXELS_SHA256
+ assert sorted(p.name for p in out.iterdir()) == ["atlas-000.png", "atlas-000.webp", "game-pack.json"]