Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
feat: ui-kit verb, alpha haze cleanup and game-pack version 2
Soohong Kim4d75c9b23bd9
diff --git a/docs/game-pack.md b/docs/game-pack.mdindex 147c0fe..1c85d4d 100644--- a/docs/game-pack.md+++ b/docs/game-pack.md@@ -256,7 +256,7 @@ What each field means, with no reading left to the consumer:* **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.+* `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`, each inset is the report's inset scaled and rounded up, or, where it is larger, the inset the same [measurement](ui-kit.md#insets) finds on the resized pixels: resampling spreads an ornament's edge a little, and that fringe stays in the fixed slice too. 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}`.diff --git a/docs/gen.md b/docs/gen.mdindex 4265baf..f54bb3a 100644--- a/docs/gen.md+++ b/docs/gen.md@@ -236,7 +236,7 @@ sprite-gen gen \[--quality low|medium|high|xhigh|max|auto] # billed effort; openai takes the range, grok takes auto/low/medium[--resolution 1k|1.5k|2k] # grok output-size tier, priced with --quality[--model ID] \- [--layout-guide] # attach a one-slot layout guide (safe box, crown and floor lines); see below+ [--layout-guide [figure|ui-kit]] # attach a layout guide: the one-slot figure guide (bare flag) or the UI kit layout; see below[--direction side|front|back|front_diagonal|back_diagonal [--facing right|left]] # add the engine's view sentence[--handed "the black smartwatch=left wrist" ...] # with --direction: where an item on one side is in that view[--body-plan quadruped | --body-plan "the horse=quadruped" ...] # with --direction: the view for that body@@ -485,6 +485,13 @@ for `--aspect-ratio` (square without one) and the report records the cell it use`extra.layout_guide` (size, safe margins, `crown_y`, `floor_y`); the report's `refs` arestill the caller's own.+`--layout-guide ui-kit` attaches the UI kit layout instead: one box per element of a game+UI kit (panel, button, pressed button, card frame, two bar frames, timer badge), and a+paragraph naming what to draw in each box, with straight edges between corner ornaments+and empty centres. [`ui-kit`](ui-kit.md) cuts the sheet along the same boxes. It is square+only (`--aspect-ratio 1:1`, or none); `extra.layout_guide` is then `{"kind": "ui-kit",+"width", "height", "boxes"}`.+The guide is an attached image, so it changes the call: openai sends it to`/images/edits` and bills it as image input, grok sends it as a reference, and`--transparent` steps down to chroma keying as it does for any `--ref`. How closely adiff --git a/docs/prompt-assembly.md b/docs/prompt-assembly.mdindex 0d099e3..ed976c3 100644--- a/docs/prompt-assembly.md+++ b/docs/prompt-assembly.md@@ -37,7 +37,7 @@ sentences put in (`tests/gen/test_prompt_assembly.py`).| handed | `--direction --handed` | `handedness.text` || facing | `--ref` with `--facing` | `facing.prompt_suffix` || key background | `--transparent --ref` when `auto` plans a key | `chroma.KEY_BACKGROUND_TEXT` |-| layout guide | `--layout-guide` | `gen.layout_guide_text` |+| layout guide | `--layout-guide` (`ui-kit`: the UI kit layout) | `gen.layout_guide_text`; `frames.ui_kit.guide_text` |A facing correction (`--facing-fix regen`) regenerates with the correction ("CORRECTION REQUIRED: …")said after the first prompt (`facing.prepare_correction`).diff --git a/docs/sheet-slicing.md b/docs/sheet-slicing.mdindex bb9ee3b..bb62c83 100644--- a/docs/sheet-slicing.md+++ b/docs/sheet-slicing.md@@ -53,6 +53,26 @@ $SPRITE_GEN_ROOT/.venv/bin/python $SPRITE_GEN_ROOT/scripts/slice_sheet_cells.pypainted a darker green/magenta than asked still keys cleanly([chroma-alpha.md](chroma-alpha.md)).+## Transparent sheets++A sheet a provider returned with real alpha (`gen --transparent` on a native-alpha route)+has no key to remove: pass `--chroma-key none` and the sheet keeps its own alpha.++Transparent sheets often carry a faint alpha haze around and between the drawn objects. It+joins neighbouring parts and enlarges a figure's measured height. `--alpha-floor N` (1..255;+`64` suits most generated sheets) clears it before parts are measured, with the shared+[alpha cleanup](ui-kit.md#alpha-cleanup): pixels at or above the floor and the faint pixels+within `--alpha-edge` pixels (default 2) of them are kept as they are, every other faint pixel+becomes fully transparent. The run writes the cleanup's report to+`<out-dir>/<prefix>alpha-cleanup.json` (haze share before and after, pixels cleared, and the+count of solid and edge pixels that changed, which is `0`). Without the flag nothing changes:+the default `0` leaves the alpha exactly as extraction made it.++```bash+sprite-gen slice-sheet --sheet props.png --out-dir props/ --chroma-key none --alpha-floor 64 \+ --grid 3x2 --names pillar,statue,shrub,lantern,gravestone,fountain --prefix prop_+```+## Geometry rules (and the field failures they encode)Each rule below exists because the naive version shipped a visible defectdiff --git a/docs/ui-kit.md b/docs/ui-kit.mdindex 9066f6f..98b7900 100644--- a/docs/ui-kit.md+++ b/docs/ui-kit.md@@ -54,9 +54,9 @@ Insets are measured only along the axes the layout lets the element stretch; the2. 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`.+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`. An inset never reaches into the reference band.-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.+So every column with an ornament, a cap, a border line or their anti-aliased edge lies inside a fixed slice, and the stretched middle holds only columns that look like the middle of the element. Two cases make the report `needs-review`, naming the element and the axis: an ornament that reaches the reference band (the band could not grow on that side), and a reference band that is not uniform itself, so an ornament probably sits in the middle of an edge (in some row its largest difference exceeds both 64 and four times the median over the rows). A frame with an ornament in the middle of an edge cannot be nine-sliced; regenerate it.## Padding@@ -68,7 +68,7 @@ Transparent sheets from image models often carry a faint alpha haze: barely visi* 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`).+* Every other faint pixel is haze and becomes fully transparent (`0, 0, 0, 0`). A pixel that was already fully transparent is left as it was.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.@@ -117,6 +117,7 @@ Like every measurement here, `pass` means the numbers found nothing to flag. Loo## 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.ui_kit.split_ui_kit(image, *, alpha_floor=64, alpha_edge=2) -> (elements, report)`: the elements as images by name, and the report as written without `sheet`.+* `sprite_gen.frames.ui_kit.measure_insets(image, stretch) -> (insets, notes)` and `measure_padding(image) -> (padding, notes)`: the measures above on one element image, with the review notes they raise.+* `sprite_gen.frames.ui_kit.boxes(size)`, `draw_guide(path, size)` and `guide_text()`: the layout, the guide image and its prompt paragraph.* `sprite_gen.frames.alpha_floor.clear_haze(image, *, floor=64, edge=2) -> (image, report)`.diff --git a/sprite_gen/_modules.py b/sprite_gen/_modules.pyindex 1caa94b..5b3e913 100644--- a/sprite_gen/_modules.py+++ b/sprite_gen/_modules.py@@ -42,6 +42,8 @@ MODULE_DOMAIN = {'cutout': 'frames','segment': 'frames','slice_sheet': 'frames',+ 'ui_kit': 'frames',+ 'alpha_floor': 'frames','check_visible_magenta': 'frames','unpack_atlas': 'frames','curation': 'curate',@@ -105,8 +107,8 @@ PIPELINES: list[dict[str, object]] = []TOOL_GROUPS: list[dict[str, object]] = [- {"key": "C", "name": "utilities", "verbs": ["cutout", "slice-sheet", "unpack-atlas"],- "chain": "cutout · slice-sheet · unpack-atlas (each stands alone)", "doc": "docs/sheet-slicing.md"},+ {"key": "C", "name": "utilities", "verbs": ["cutout", "slice-sheet", "ui-kit", "unpack-atlas"],+ "chain": "cutout · slice-sheet · ui-kit · unpack-atlas (each stands alone)", "doc": "docs/sheet-slicing.md"},{"key": "D", "name": "post-processing", "verbs": ["recolor", "recolor-palette", "compose-layers", "export-pngs", "export-aseprite"],"chain": "recolor · compose-layers · export-pngs · export-aseprite", "doc": "docs/recolor.md"},{"key": "E", "name": "asset tools", "verbs": ["background-tile", "shadow", "inspect-motion"],diff --git a/sprite_gen/cli.py b/sprite_gen/cli.pyindex 096d3c6..b86cd32 100644--- a/sprite_gen/cli.py+++ b/sprite_gen/cli.py@@ -15,7 +15,7 @@ from sprite_gen.compose import compose_atlas, compose_cycle, compose_gif, composfrom sprite_gen.compose import game_packfrom sprite_gen.qa import correction_loop, inspect, preview, score, motionfrom sprite_gen.qa import handed as handed_check-from sprite_gen.frames import cutout, extract, slice_sheet, unpack_atlas+from sprite_gen.frames import cutout, extract, slice_sheet, ui_kit, unpack_atlasfrom sprite_gen.gen import gen_set, pixel_draw, prepare, videofrom sprite_gen.video import batch as video_batchfrom sprite_gen.video import canvas as video_canvas@@ -177,7 +177,7 @@ def _add_export_pngs(p: argparse.ArgumentParser) -> None:def _add_slice_sheet(p: argparse.ArgumentParser) -> None:p.add_argument("--sheet", required=True, type=Path)p.add_argument("--out-dir", required=True, type=Path)- p.add_argument("--chroma-key", required=True, help="magenta, green, or #RRGGBB")+ p.add_argument("--chroma-key", required=True, help=slice_sheet.CHROMA_KEY_HELP)p.add_argument("--grid", type=_parse_grid, default=(3, 2), help="COLSxROWS, default 3x2")p.add_argument("--names", help="comma-separated output names, one per cell in reading order")p.add_argument("--prefix", default="")@@ -192,6 +192,8 @@ def _add_slice_sheet(p: argparse.ArgumentParser) -> None:p.add_argument("--spill-max-fraction", type=float, default=0.005)p.add_argument("--noise-min", type=int, default=slice_sheet.DEFAULT_NOISE_MIN)p.add_argument("--debris-fraction", type=float, default=slice_sheet.DEFAULT_DEBRIS_FRACTION)+ p.add_argument("--alpha-floor", type=int, default=0, help=slice_sheet.ALPHA_FLOOR_HELP)+ p.add_argument("--alpha-edge", type=int, default=2, help=slice_sheet.ALPHA_EDGE_HELP)def _add_inspect(p: argparse.ArgumentParser) -> None:@@ -309,6 +311,11 @@ COMMANDS: dict[str, tuple[str, Callable[[argparse.ArgumentParser], None], Callab_add_slice_sheet,slice_sheet.run,),+ "ui-kit": (+ "Split a UI kit sheet drawn on the fixed layout into nine-slice elements with measured insets.",+ ui_kit.add_arguments,+ ui_kit.run,+ ),"gen": ("Generate one image via a provider (codex image_gen / grok Imagine on a subscription login, or openai Images API for servers/SaaS, billed per call) into a verified PNG.",_add_gen,diff --git a/sprite_gen/compose/game_pack.py b/sprite_gen/compose/game_pack.pyindex fbc4d8c..e2eb6e4 100644--- a/sprite_gen/compose/game_pack.py+++ b/sprite_gen/compose/game_pack.py@@ -1,10 +1,16 @@# SPDX-License-Identifier: Apache-2.0-"""Resize finished assets and publish an immutable game atlas pack."""+"""Resize finished assets and publish an immutable game atlas pack.++Request version 2 adds painted scene art (docs/game-pack.md "Version 2"): single images with+anchor and footprint, repeating tiles as their own files, and a UI kit of nine-slice elements+and icons. A version 1 request is packed exactly as before.+"""from __future__ import annotationsimport argparsefrom io import BytesIOimport json+import mathimport osfrom pathlib import Pathimport re@@ -15,11 +21,19 @@ from PIL import Imagefrom sprite_gen.audio.manifest import load as load_soundfrom sprite_gen.audio.playback import player as audio_player-from sprite_gen.spec.assets import finite, load_asset_states+from sprite_gen.frames.ui_kit import measure_insets+from sprite_gen._deps import np+from sprite_gen.spec.assets import finite, load_asset, load_asset_statesfrom sprite_gen.util.resample import resize_cellMAX_PAGE_SIZE = 4096MAX_BYTES = 50_000_000+SCENE_SECTIONS = ("images", "tiles", "ui")+UI_KIT_KIND = "sprite-gen-ui-kit"+STRETCHES = ("xy", "x", "none")+SIDES = ("left", "right", "top", "bottom")+# A "base" footprint counts pixels at least this opaque (docs/game-pack.md "Version 2 request").+FOOTPRINT_ALPHA = 128def _integer(value, name, *, maximum=None):@@ -82,12 +96,24 @@ def _display(sequence, entry):return size, anchor, sampling-def _prepare(request, base, page_size):- if not isinstance(request, dict) or request.get("version") != 1:- raise ValueError("game pack request requires version 1")- entries = request.get("assets")- if not isinstance(entries, list) or not entries:+def _version(request):+ if not isinstance(request, dict) or type(request.get("version")) is not int or request["version"] not in (1, 2):+ raise ValueError("game pack request version must be 1 or 2")+ if request["version"] == 1 and any(key in request for key in SCENE_SECTIONS):+ raise ValueError("images, tiles and ui need request version 2")+ return request["version"]+++def _cell(image, size, sampling):+ return image.resize(size, Image.Resampling.NEAREST) if sampling == "nearest" else resize_cell(image, size)+++def _prepare(request, base, page_size, version=1):+ entries = request.get("assets") if version == 1 else request.get("assets", [])+ if version == 1 and (not isinstance(entries, list) or not entries):raise ValueError("assets must be a nonempty list")+ if not isinstance(entries, list):+ raise ValueError("assets must be a list")ids, animations, frames, sources = set(), {}, [], set()for entry in entries:if not isinstance(entry, dict):@@ -112,13 +138,204 @@ def _prepare(request, base, page_size):for index, image in enumerate(sequence.frames):name = f"{key}/{index:06d}"animation["frames"].append(name)- cell = image.resize(size, Image.Resampling.NEAREST) if sampling == "nearest" else resize_cell(image, size)- frames.append((name, cell, anchor))+ frames.append((name, _cell(image, size, sampling), anchor))animations[key] = animationsources.update(sequence.source_files)return dict(sorted(animations.items())), sorted(frames, key=lambda f: f[0]), sources+def _entries(owner, key, allowed):+ """A version 2 list section: objects with a unique id, a source path and only the documented keys."""+ entries = owner.get(key, [])+ if not isinstance(entries, list):+ raise ValueError(f"{key} must be a list")+ ids = set()+ for entry in entries:+ if not isinstance(entry, dict):+ raise ValueError(f"each {key} entry must be an object")+ unknown = sorted(set(entry) - allowed)+ if unknown:+ raise ValueError(f"unknown {key} key(s): {', '.join(unknown)}")+ ident = _name(entry.get("id"))+ if ident in ids:+ raise ValueError(f"duplicate {key} id: {ident}")+ ids.add(ident)+ if not isinstance(entry.get("source"), str) or not entry["source"]:+ raise ValueError(f"each {key} entry requires a source path")+ return entries+++def _still(path, key, anchor=None):+ sequence = load_asset(path, anchor=anchor)+ if len(sequence.frames) != 1:+ raise ValueError(f"{key}: needs exactly one frame, the source has {len(sequence.frames)}")+ return sequence+++def _fixed_display(entry, key):+ display = entry.get("display")+ if not isinstance(display, dict) or len(display) != 1 or not set(display) <= {"width", "height"}:+ raise ValueError(f"{key}: display requires exactly one of width or height")+++def _fits(key, size, page_size):+ if max(size) + 2 > page_size:+ raise ValueError(f"{key}: frame {size} plus padding exceeds page size {page_size}")+++def _footprint(entry, image, size, key):+ value = entry.get("footprint")+ if value is None:+ return None+ width, height = image.size+ if value == "base":+ opaque = np.asarray(image.getchannel("A")) >= FOOTPRINT_ALPHA+ rows = np.flatnonzero(opaque.any(axis=1))+ if not rows.size:+ raise ValueError(f"{key}: no pixel reaches alpha {FOOTPRINT_ALPHA}, so the footprint has no base")+ bottom = int(rows[-1]) + 1+ top = bottom - max(1, math.ceil((bottom - int(rows[0])) / 5))+ band = opaque[top:bottom]+ cols, band_rows = np.flatnonzero(band.any(axis=0)), np.flatnonzero(band.any(axis=1))+ x0, x1 = int(cols[0]), int(cols[-1]) + 1+ y0, y1 = top + int(band_rows[0]), top + int(band_rows[-1]) + 1+ elif isinstance(value, dict) and set(value) == {"x", "y", "w", "h"} and all(type(v) is int for v in value.values()):+ x0, y0 = value["x"], value["y"]+ x1, y1 = x0 + value["w"], y0 + value["h"]+ if value["w"] < 1 or value["h"] < 1 or x0 < 0 or y0 < 0 or x1 > width or y1 > height:+ raise ValueError(f"{key}: footprint must be a nonempty rectangle inside the {width}x{height} source")+ else:+ raise ValueError(f'{key}: footprint must be "base" or integer {{x, y, w, h}} in source pixels')+ # outward to whole stored pixels: left and top down, right and bottom up, inside the frame+ fx0, fy0 = x0 * size[0] // width, y0 * size[1] // height+ fx1, fy1 = min(size[0], -(-x1 * size[0] // width)), min(size[1], -(-y1 * size[1] // height))+ return {"x": fx0, "y": fy0, "w": max(1, fx1 - fx0), "h": max(1, fy1 - fy0)}+++def _scaled_up(value, scale):+ return math.ceil(round(value * scale, 9))+++def _sides(record, field, key):+ sides = record.get(field)+ if not isinstance(sides, dict) or set(sides) != set(SIDES) or any(type(sides[s]) is not int or sides[s] < 0 for s in SIDES):+ raise ValueError(f"{key}: {field} needs non-negative integer left, right, top and bottom")+ return sides+++def _ui_kit(path, scale, page_size):+ """Nine-slice entries and atlas frames from a `ui-kit` report (docs/ui-kit.md "Report")."""+ report = json.loads(path.read_text(encoding="utf-8"))+ if not isinstance(report, dict) or report.get("kind") != UI_KIT_KIND or report.get("version") != 1:+ raise ValueError(f"ui.kit must be a version 1 ui-kit report ({UI_KIT_KIND}): {path.name}")+ elements = report.get("elements")+ if not isinstance(elements, dict) or not elements:+ raise ValueError("ui-kit report lists no elements")+ entries, frames, sources = {}, [], {path}+ for name, record in elements.items():+ key = f"ui/{_name(name)}"+ if not isinstance(record, dict) or record.get("stretch") not in STRETCHES:+ raise ValueError(f"{key}: stretch must be one of {', '.join(STRETCHES)}")+ stretch = record["stretch"]+ insets, padding = _sides(record, "insets", key), _sides(record, "padding", key)+ fixed = {"x": ("top", "bottom"), "none": SIDES}.get(stretch, ())+ if any(insets[side] for side in fixed):+ raise ValueError(f"{key}: stretch {stretch} needs {', '.join(fixed)} insets of 0")+ if not isinstance(record.get("file"), str) or not record["file"]:+ raise ValueError(f"{key}: the report names no file")+ sequence = _still(path.parent / record["file"], key)+ image = sequence.frames[0]+ if record.get("size") != {"w": image.width, "h": image.height}:+ raise ValueError(f"{key}: the report's size does not match {record['file']}")+ size = (max(1, round(image.width * scale)), max(1, round(image.height * scale)))+ _fits(key, size, page_size)+ cell = image if size == image.size else resize_cell(image, size)+ insets = {side: _scaled_up(insets[side], scale) for side in SIDES}+ if cell is not image:+ # Resampling spreads an ornament's edge a little past its scaled place; the stored pixels are+ # measured the way `ui-kit` measured the source, and the larger inset of the two is kept.+ measured, _notes = measure_insets(cell, stretch)+ insets = {side: max(insets[side], measured[side]) for side in SIDES}+ padding = {side: _scaled_up(padding[side], scale) for side in SIDES}+ if (stretch != "none" and insets["left"] + insets["right"] >= size[0]) or (+ stretch == "xy" and insets["top"] + insets["bottom"] >= size[1]):+ raise ValueError(f"{key}: at ui scale {scale} the insets leave no stretchable middle")+ if padding["left"] + padding["right"] >= size[0] or padding["top"] + padding["bottom"] >= size[1]:+ raise ValueError(f"{key}: at ui scale {scale} the padding leaves no content area")+ frames.append((key, cell, (size[0] / 2, size[1] / 2)))+ entries[name] = {"frame": key, "size": {"w": size[0], "h": size[1]}, "stretch": stretch,+ "insets": insets, "padding": padding}+ sources.update(sequence.source_files)+ return entries, frames, sources+++def _encode_image(image, fmt):+ buffer = BytesIO()+ if fmt == "PNG":+ image.save(buffer, format="PNG", compress_level=9)+ else:+ image.save(buffer, format="WEBP", lossless=True, exact=True, method=6)+ return buffer.getvalue()+++def _prepare_scene(request, base, page_size):+ """The version 2 sections: manifest entries, atlas frames, tile files and the sources they read."""+ frames, files, sources = [], {}, set()+ images = {}+ for entry in _entries(request, "images", {"id", "source", "display", "resample", "anchor", "footprint"}):+ key = f"image/{entry['id']}"+ sequence = _still(base / entry["source"], key, anchor=entry.get("anchor"))+ _fixed_display(entry, key)+ size, anchor, sampling = _display(sequence, entry)+ _fits(key, size, page_size)+ frames.append((key, _cell(sequence.frames[0], size, sampling), anchor))+ images[entry["id"]] = {"frame": key, "size": {"w": size[0], "h": size[1]}, "anchor": anchor,+ "footprint": _footprint(entry, sequence.frames[0], size, key)}+ sources.update(sequence.source_files)+ tiles = {}+ for entry in _entries(request, "tiles", {"id", "source", "display"}):+ key = f"tile/{entry['id']}"+ sequence = _still(base / entry["source"], key)+ _fixed_display(entry, key)+ image = sequence.frames[0]+ dimension, value = next(iter(entry["display"].items()))+ target = _integer(value, f"display {dimension}")+ scale = target / (image.width if dimension == "width" else image.height)+ png, webp = f"tile-{entry['id']}.png", f"tile-{entry['id']}.webp"+ files[png], files[webp] = _encode_image(image, "PNG"), _encode_image(image, "WEBP")+ tiles[entry["id"]] = {"image": png, "webp": webp, "size": {"w": image.width, "h": image.height},+ "display_size": {"w": max(1, round(image.width * scale)),+ "h": max(1, round(image.height * scale))}}+ sources.update(sequence.source_files)+ nine_slice, icons = {}, {}+ ui = request.get("ui")+ if ui is not None:+ if not isinstance(ui, dict):+ raise ValueError("ui must be an object")+ unknown = sorted(set(ui) - {"kit", "scale", "icons"})+ if unknown:+ raise ValueError(f"unknown ui key(s): {', '.join(unknown)}")+ scale = finite(ui.get("scale", 1), "ui scale", positive=True)+ if "kit" in ui:+ if not isinstance(ui["kit"], str) or not ui["kit"]:+ raise ValueError("ui.kit must be the path of a ui-kit report")+ nine_slice, kit_frames, kit_sources = _ui_kit((base / ui["kit"]).resolve(), scale, page_size)+ frames += kit_frames+ sources |= kit_sources+ for entry in _entries(ui, "icons", {"id", "source", "display", "resample"}):+ key = f"icon/{entry['id']}"+ sequence = _still(base / entry["source"], key)+ _fixed_display(entry, key)+ size, _anchor, sampling = _display(sequence, entry)+ _fits(key, size, page_size)+ frames.append((key, _cell(sequence.frames[0], size, sampling), (size[0] / 2, size[1] / 2)))+ icons[entry["id"]] = {"frame": key, "size": {"w": size[0], "h": size[1]}}+ sources.update(sequence.source_files)+ sections = {"images": dict(sorted(images.items())), "tiles": dict(sorted(tiles.items())),+ "ui": {"nine_slice": dict(sorted(nine_slice.items())), "icons": dict(sorted(icons.items()))}}+ return sections, frames, files, sources++def _layout(frames, limit):"""Deterministic shelf placement; playback order is independent of texture position."""pages, placed = [], []@@ -151,7 +368,8 @@ def _paste_extruded(sheet, image, x, y):sheet.putpixel((x + dx, y + dy), image.getpixel((sx, sy)))-def _encode(pages, animations, max_bytes):+def _encode(pages, animations, max_bytes, sections=None, files=None):+ """Pages, then any version 2 files, then the manifest; ``sections`` makes it a version 2 manifest."""payloads, textures = {}, []total = 0for index, (width, height, placed) in enumerate(pages):@@ -174,7 +392,15 @@ def _encode(pages, animations, max_bytes):raise ValueError(f"game pack exceeds {max_bytes} bytes (50 MB maximum)")textures.append({"image": png_name, "webp": webp_name, "frames": records,"meta": {"image": png_name, "format": "RGBA8888", "size": {"w": width, "h": height}, "scale": "1"}})+ for name, data in (files or {}).items():+ payloads[name] = data+ total += len(data)+ if total > max_bytes:+ raise ValueError(f"game pack exceeds {max_bytes} bytes (50 MB maximum)")result = {"kind": "sprite-gen-game-pack", "version": 1, "textures": textures, "animations": animations}+ if sections is not None:+ result["version"] = 2+ result.update(sections)payloads["game-pack.json"] = (json.dumps(result, ensure_ascii=False, separators=(",", ":"), allow_nan=False) + "\n").encode()if total + len(payloads["game-pack.json"]) > max_bytes:raise ValueError(f"game pack exceeds {max_bytes} bytes (50 MB maximum, including its manifest)")@@ -215,7 +441,18 @@ def pack(request: Path, out_dir: Path, *, page_size=MAX_PAGE_SIZE, max_bytes=MAXmax_bytes = _integer(max_bytes, "max bytes", maximum=MAX_BYTES)request, out_dir = Path(request).expanduser().resolve(), Path(out_dir).expanduser().resolve()document = json.loads(request.read_text(encoding="utf-8"))- animations, frames, sources = _prepare(document, request.parent, page_size)+ version = _version(document)+ animations, frames, sources = _prepare(document, request.parent, page_size, version)+ sections = files = None+ if version == 2:+ sections, scene_frames, files, scene_sources = _prepare_scene(document, request.parent, page_size)+ frames = sorted(frames + scene_frames, key=lambda f: f[0])+ sources |= scene_sources+ names = [name for name, _image, _anchor in frames]+ if len(set(names)) != len(names):+ raise ValueError("two atlas frames share a name; rename an asset or scene entry")+ if not frames and not files:+ raise ValueError("game pack request declares nothing to pack")audio_entries = document.get("audio", [])if not isinstance(audio_entries, list):raise ValueError("audio must be a list")@@ -238,7 +475,7 @@ def pack(request: Path, out_dir: Path, *, page_size=MAX_PAGE_SIZE, max_bytes=MAXsources.update(paths)if any(path == out_dir or out_dir in path.parents for path in sources | {request}):raise ValueError("output directory must not contain any source file")- result, payloads = _encode(_layout(frames, page_size), animations, max_bytes)+ result, payloads = _encode(_layout(frames, page_size) if frames else [], animations, max_bytes, sections, files)if audio:helper, module = audio_player()audio_payloads[helper["path"]] = modulediff --git a/sprite_gen/frames/alpha_floor.py b/sprite_gen/frames/alpha_floor.pynew file mode 100644index 0000000..385edc9--- /dev/null+++ b/sprite_gen/frames/alpha_floor.py@@ -0,0 +1,81 @@+# SPDX-License-Identifier: Apache-2.0+"""Clear the faint alpha haze of a transparent sheet; keep every object and its anti-aliased edge.++A pixel at or above ``floor`` is solid. A pixel above zero and below the floor is faint. A faint+pixel within ``edge`` pixels of a solid pixel (8-connected: diagonals count) belongs to an+object's anti-aliased edge and is kept as it is. Every other faint pixel is haze and becomes+``(0, 0, 0, 0)``. Nothing is blended or resampled: a pixel is kept byte for byte or cleared.++Shared by `slice-sheet --alpha-floor` and `ui-kit` (docs/ui-kit.md "Alpha cleanup"). The report+measures what changed instead of asserting it.+"""++from __future__ import annotations++from numbers import Integral+from typing import Any++from PIL import Image++from sprite_gen._deps import np++MAX_EDGE = 64+++def _setting(value: Any, name: str, low: int, high: int) -> int:+ if isinstance(value, bool) or not isinstance(value, Integral):+ raise TypeError(f"{name} must be an integer")+ if not low <= int(value) <= high:+ raise ValueError(f"{name} must be between {low} and {high}")+ return int(value)+++def near(mask: Any, reach: int) -> Any:+ """True where a True pixel of ``mask`` lies within ``reach`` pixels, diagonals included."""+ if reach == 0:+ return mask.copy()+ height, width = mask.shape+ padded = np.pad(mask, reach)+ across = np.zeros((height + 2 * reach, width), dtype=bool)+ for dx in range(2 * reach + 1):+ across |= padded[:, dx:dx + width]+ result = np.zeros((height, width), dtype=bool)+ for dy in range(2 * reach + 1):+ result |= across[dy:dy + height]+ return result+++def clear_haze(image: Image.Image, *, floor: int = 64, edge: int = 2) -> tuple[Image.Image, dict[str, Any]]:+ """Return a cleaned RGBA copy of ``image`` and the cleanup report; ``image`` is not changed."""+ floor = _setting(floor, "alpha floor", 1, 255)+ edge = _setting(edge, "alpha edge", 0, MAX_EDGE)+ before = np.array(image.convert("RGBA"))+ pixels = before.copy()+ alpha = before[..., 3]+ solid = alpha >= floor+ faint = (alpha > 0) & ~solid+ by_solid = near(solid, edge)+ haze = faint & ~by_solid+ pixels[haze] = 0+ changed = (pixels != before).any(axis=-1)+ after = pixels[..., 3]+ after_faint = (after > 0) & (after < floor)+ after_haze = after_faint & ~near(after >= floor, edge)+ total = alpha.size++ def share(mask: Any) -> float:+ return float(np.count_nonzero(mask) / total) if total else 0.0++ report = {+ "floor": floor,+ "edge_px": edge,+ "pixels": int(total),+ "faint_fraction_before": share(faint),+ "faint_fraction_after": share(after_faint),+ "haze_fraction_before": share(haze),+ "haze_fraction_after": share(after_haze),+ "cleared_pixels": int(np.count_nonzero(changed & haze)),+ "changed_solid_pixels": int(np.count_nonzero(changed & solid)),+ "changed_edge_pixels": int(np.count_nonzero(changed & faint & by_solid)),+ }+ return Image.fromarray(pixels), reportdiff --git a/sprite_gen/frames/slice_sheet.py b/sprite_gen/frames/slice_sheet.pyindex dfa9860..e408c5d 100644--- a/sprite_gen/frames/slice_sheet.py+++ b/sprite_gen/frames/slice_sheet.py@@ -8,7 +8,10 @@ baseline and a normalized subject height.Alpha truth is `sprite_gen.frames.extract.remove_chroma_background` (the 4-passchain: hard key cut -> key-depth in-band unmix -> soft-alpha unmix ->-trapped-spill despill). This module owns only cell geometry:+trapped-spill despill); a sheet that is already transparent (chroma key+``none``) keeps its own alpha. ``alpha_floor`` then clears faint alpha haze+(`sprite_gen.frames.alpha_floor.clear_haze`) before parts are measured. This+module owns only cell geometry:- whole-sheet connected components assigned to grid cells by centroid, so afigure's own cape/prop keeps its overflow past the cell border while a@@ -32,12 +35,15 @@ the in-cell re-label leaves a neighbour's hair fused to the figure.from __future__ import annotationsimport argparse+import jsonfrom collections import dequefrom pathlib import Pathfrom PIL import Image+from sprite_gen.frames.alpha_floor import clear_hazefrom sprite_gen.frames.extract import remove_chroma_background+from sprite_gen.spec.runio import atomic_write_textfrom sprite_gen.util.hexcolor import parse_hexfrom sprite_gen.util.resample import resize_cell@@ -52,16 +58,23 @@ DEFAULT_FRINGE_DELTA = 18.0DEFAULT_NOISE_MIN = 60DEFAULT_DEBRIS_FRACTION = 0.30MERGED_SPAN_FACTOR = 1.5+CHROMA_KEY_HELP = "magenta, green, #RRGGBB, or none for a sheet that is already transparent"+ALPHA_FLOOR_HELP = ("clear faint alpha haze below this alpha (1..255) before cutting, and write "+ "<prefix>alpha-cleanup.json; 0 (default) leaves the alpha as it is")+ALPHA_EDGE_HELP = "with --alpha-floor: faint pixels this close to a solid pixel are its edge and are kept"-def parse_chroma_key(value: str) -> tuple[int, int, int]:+def parse_chroma_key(value: str) -> tuple[int, int, int] | None:+ """A key colour, or None for ``none``: the sheet is already transparent and keeps its own alpha."""name = value.strip().lower()+ if name == "none":+ return Noneif name in CHROMA_KEYS:return CHROMA_KEYS[name]try:return parse_hex(name)except ValueError:- raise ValueError(f"unsupported chroma key {value!r}; use magenta, green, or #RRGGBB") from None+ raise ValueError(f"unsupported chroma key {value!r}; use magenta, green, #RRGGBB or none") from Nonedef _components(alpha: bytearray, width: int, height: int) -> list[list[int]]:@@ -120,7 +133,7 @@ def _relabel_within_cell(part: list[int], width: int) -> list[list[int]]:def slice_sheet(sheet: Path,out_dir: Path,- chroma_key: tuple[int, int, int],+ chroma_key: tuple[int, int, int] | None,*,grid: tuple[int, int] = (3, 2),names: list[str] | None = None,@@ -135,6 +148,8 @@ def slice_sheet(spill_max_fraction: float = 0.005,noise_min: int = DEFAULT_NOISE_MIN,debris_fraction: float = DEFAULT_DEBRIS_FRACTION,+ alpha_floor: int = 0,+ alpha_edge: int = 2,) -> list[Path]:cols, rows = gridcell_count = cols * rows@@ -143,15 +158,20 @@ def slice_sheet(if target_height > baseline_y:raise ValueError("target height must fit above the feet baseline")- rgba = remove_chroma_background(- Image.open(sheet).convert("RGBA"),- chroma_key,- key_threshold,- fringe_key_threshold,- fringe_delta,- unmix_reach=unmix_reach,- spill_max_fraction=spill_max_fraction,- )+ rgba = Image.open(sheet).convert("RGBA")+ if chroma_key is not None:+ rgba = remove_chroma_background(+ rgba,+ chroma_key,+ key_threshold,+ fringe_key_threshold,+ fringe_delta,+ unmix_reach=unmix_reach,+ spill_max_fraction=spill_max_fraction,+ )+ cleanup = None+ if alpha_floor:+ rgba, cleanup = clear_haze(rgba, floor=alpha_floor, edge=alpha_edge)width, height = rgba.sizepixels = rgba.load()cell_w, cell_h = width / cols, height / rows@@ -212,6 +232,10 @@ def slice_sheet(buckets[cell] = keptout_dir.mkdir(parents=True, exist_ok=True)+ if cleanup is not None:+ atomic_write_text(out_dir / f"{prefix}alpha-cleanup.json", json.dumps(cleanup, indent=2) + "\n")+ print(f"{sheet.name} alpha haze {cleanup['haze_fraction_before']:.2%} -> "+ f"{cleanup['haze_fraction_after']:.2%} (floor {alpha_floor}, cleared {cleanup['cleared_pixels']} px)")written: list[Path] = []for cell in range(cell_count):comps_in = buckets[cell]@@ -272,6 +296,8 @@ def run(spill_max_fraction: float = 0.005,noise_min: int = DEFAULT_NOISE_MIN,debris_fraction: float = DEFAULT_DEBRIS_FRACTION,+ alpha_floor: int = 0,+ alpha_edge: int = 2,) -> int:name_list = [part.strip() for part in names.split(",") if part.strip()] if names else Noneslice_sheet(@@ -291,6 +317,8 @@ def run(spill_max_fraction=spill_max_fraction,noise_min=noise_min,debris_fraction=debris_fraction,+ alpha_floor=alpha_floor,+ alpha_edge=alpha_edge,)return 0@@ -304,7 +332,7 @@ def main(argv: list[str] | None = None) -> int:parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])parser.add_argument("--sheet", required=True, type=Path)parser.add_argument("--out-dir", required=True, type=Path)- parser.add_argument("--chroma-key", required=True, help="magenta, green, or #RRGGBB")+ parser.add_argument("--chroma-key", required=True, help=CHROMA_KEY_HELP)parser.add_argument("--grid", type=_parse_grid, default=(3, 2), help="COLSxROWS, default 3x2")parser.add_argument("--names", help="comma-separated output names, one per cell in reading order")parser.add_argument("--prefix", default="")@@ -319,6 +347,8 @@ def main(argv: list[str] | None = None) -> int:parser.add_argument("--spill-max-fraction", type=float, default=0.005)parser.add_argument("--noise-min", type=int, default=DEFAULT_NOISE_MIN)parser.add_argument("--debris-fraction", type=float, default=DEFAULT_DEBRIS_FRACTION)+ parser.add_argument("--alpha-floor", type=int, default=0, help=ALPHA_FLOOR_HELP)+ parser.add_argument("--alpha-edge", type=int, default=2, help=ALPHA_EDGE_HELP)args = parser.parse_args(argv)return run(**vars(args))diff --git a/sprite_gen/frames/ui_kit.py b/sprite_gen/frames/ui_kit.pynew file mode 100644index 0000000..c9c5f7d--- /dev/null+++ b/sprite_gen/frames/ui_kit.py@@ -0,0 +1,376 @@+# SPDX-License-Identifier: Apache-2.0+"""Split a transparent UI kit sheet drawn on the fixed layout into nine-slice elements.++docs/ui-kit.md is the contract. One table (`LAYOUT`) is the layout: `gen --layout-guide ui-kit`+draws it (`draw_guide`) and says it (`guide_text`), and the splitter cuts along it. The sheet's+alpha haze is cleared first (`alpha_floor.clear_haze`), parts are assigned to boxes by centroid,+and each element's insets and content padding are measured on its own pixels.+"""++from __future__ import annotations++import argparse+import io+import json+from dataclasses import dataclass+from pathlib import Path+from typing import Any++from PIL import Image, ImageDraw++from sprite_gen._deps import np+from sprite_gen.frames.alpha_floor import clear_haze+from sprite_gen.spec.runio import acquire_run_dir_lock, atomic_write_set, release_run_dir_lock++REFERENCE = 1024+GAP = 48+MIN_PART = 16+MARGIN = 2+PADDING_TOLERANCE = 32+GUIDE_BACKGROUND = (0xF6, 0xF6, 0xF6)+GUIDE_BOX = (0x2F, 0x80, 0xED)+STRETCHES = ("xy", "x", "none")+++@dataclass(frozen=True)+class Slot:+ name: str+ box: tuple[int, int, int, int]+ stretch: str+ where: str+ what: str+++LAYOUT = (+ Slot("panel", (48, 48, 576, 400), "xy", "the large box at the top left",+ "a large ornate panel frame with an empty centre"),+ Slot("button", (672, 48, 304, 128), "xy", "the upper box at the top right",+ "a wide button in its normal state"),+ Slot("button_pressed", (672, 224, 304, 128), "xy", "the box below it",+ "the same button pressed in"),+ Slot("card", (704, 400, 272, 576), "xy", "the tall box at the right",+ "a tall card frame with an empty centre"),+ Slot("hp_bar_frame", (48, 496, 608, 112), "x", "the long box at the left below the panel",+ "an empty horizontal health bar frame"),+ Slot("xp_bar_frame", (48, 656, 608, 112), "x", "the long box below it",+ "an empty horizontal experience bar frame"),+ Slot("timer_badge", (48, 816, 160, 160), "none", "the small square box at the bottom left",+ "a small round badge with an empty centre"),+)+++def boxes(size: tuple[int, int]) -> dict[str, tuple[int, int, int, int]]:+ """The layout's boxes as (x, y, w, h) in pixels of a sheet of ``size``, in layout order."""+ width, height = size+ sx, sy = width / REFERENCE, height / REFERENCE+ return {slot.name: (round(slot.box[0] * sx), round(slot.box[1] * sy),+ round(slot.box[2] * sx), round(slot.box[3] * sy)) for slot in LAYOUT}+++def _rect(x: int, y: int, w: int, h: int) -> dict[str, int]:+ return {"x": int(x), "y": int(y), "w": int(w), "h": int(h)}+++def guide_text() -> str:+ """The prompt's half of the guide: what to draw in each box and how, in layout order."""+ places = "; ".join(f"in {slot.where}, {slot.what}" for slot in LAYOUT)+ return (+ "Layout: the last attached image is a layout guide, not part of the artwork. It shows "+ f"{len(LAYOUT)} blue boxes on a grey sheet. Draw exactly one user interface element inside each box, "+ "filling most of its box without touching the box's edges, and leave everything outside the boxes "+ f"empty and transparent: {places}. Every frame, button and bar has straight, even edges between its "+ "corners, so it can be stretched along them: put ornaments only in the corners, and on the bars only "+ "at their two ends. Leave every centre empty: no text, no letters, no numbers, no icons and no fill "+ "inside the bars. Do not reproduce the layout guide itself: no boxes, guide lines, guide colors or the "+ "guide's grey background may appear in the output."+ )+++def draw_guide(path: Path, size: tuple[int, int] = (REFERENCE, REFERENCE)) -> dict[str, Any]:+ """Draw the layout guide at ``path`` and answer its cell: the kind, the size and every box."""+ width, height = size+ image = Image.new("RGB", (width, height), GUIDE_BACKGROUND)+ draw = ImageDraw.Draw(image)+ line = max(2, round(3 * width / REFERENCE))+ scaled = boxes(size)+ for x, y, w, h in scaled.values():+ draw.rectangle((x, y, x + w - 1, y + h - 1), outline=GUIDE_BOX, width=line)+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ image.save(path)+ return {"kind": "ui-kit", "width": width, "height": height,+ "boxes": {name: _rect(*box) for name, box in scaled.items()}}+++def _premultiplied(image: Image.Image) -> Any:+ pixels = np.asarray(image.convert("RGBA")).astype(np.float32)+ pixels[..., :3] *= pixels[..., 3:] / 255+ return pixels+++def _stretch_band(pixels: Any) -> tuple[int, int, list[str]]:+ """Fixed slices before and after the stretch band along dimension 1 (docs/ui-kit.md "Insets")."""+ height, width, _ = pixels.shape+ lo = int(width * 0.4)+ hi = max(int(width * 0.6), lo + 1)+ reference = np.median(pixels[:, lo:hi], axis=1)+ error = np.abs(pixels - reference[:, None, :]).max(axis=-1)+ spread = error[:, lo:hi].max(axis=1)+ plain = ~(error > (2 * spread + 8)[:, None]).any(axis=0)+ start = lo+ while start > 0 and plain[start - 1]:+ start -= 1+ end = hi+ while end < width and plain[end]:+ end += 1+ notes = []+ if spread.max() > max(64.0, 4 * float(np.median(spread))):+ notes.append("the middle of the element is not uniform (an ornament in the middle of an edge?); "+ "stretching would smear it")+ if (start == lo and lo > 0) or (end == hi and hi < width):+ notes.append("an ornament reaches the middle fifth of the element; the insets may not cover it")+ before = min(start + MARGIN, lo) if start > 0 else 0+ after = min(width - end + MARGIN, width - hi) if end < width else 0+ return before, after, notes+++def measure_insets(image: Image.Image, stretch: str) -> tuple[dict[str, int], list[str]]:+ """Nine-slice insets in the element's pixels, measured along the axes ``stretch`` allows, and review notes."""+ if stretch not in STRETCHES:+ raise ValueError(f"stretch must be one of {', '.join(STRETCHES)}")+ pixels = _premultiplied(image)+ insets = {"left": 0, "right": 0, "top": 0, "bottom": 0}+ notes: list[str] = []+ if stretch in ("xy", "x"):+ insets["left"], insets["right"], found = _stretch_band(pixels)+ notes += [f"x: {note}" for note in found]+ if stretch == "xy":+ insets["top"], insets["bottom"], found = _stretch_band(pixels.transpose(1, 0, 2))+ notes += [f"y: {note}" for note in found]+ return insets, notes+++def _interior_run(line: Any, centre: Any, middle: int) -> tuple[int, int]:+ close = np.abs(line - centre).max(axis=-1) <= PADDING_TOLERANCE+ if not close[middle]:+ return middle, middle + 1+ start, end = middle, middle + 1+ while start > 0 and close[start - 1]:+ start -= 1+ while end < len(close) and close[end]:+ end += 1+ return start, end+++def measure_padding(image: Image.Image) -> tuple[dict[str, int], list[str]]:+ """Distances from each edge to the element's empty interior (docs/ui-kit.md "Padding"), and review notes."""+ pixels = _premultiplied(image)+ height, width, _ = pixels.shape+ cy, cx = height // 2, width // 2+ rows, cols = slice(max(0, cy - 2), cy + 3), slice(max(0, cx - 2), cx + 3)+ centre = np.median(pixels[rows, cols].reshape(-1, 4), axis=0)+ x0, x1 = _interior_run(np.median(pixels[rows], axis=0), centre, cx)+ y0, y1 = _interior_run(np.median(pixels[:, cols], axis=1), centre, cy)++ def interior(x: int, y: int) -> bool:+ return bool(np.abs(pixels[y, x] - centre).max() <= PADDING_TOLERANCE)++ shrink = 0+ while True:+ left, top, right, bottom = x0 + shrink, y0 + shrink, x1 - 1 - shrink, y1 - 1 - shrink+ if left >= right or top >= bottom:+ left, right = min(left, cx), max(right, cx)+ top, bottom = min(top, cy), max(bottom, cy)+ break+ if all(interior(x, y) for x, y in ((left, top), (right, top), (left, bottom), (right, bottom))):+ break+ shrink += 1+ padding = {"left": min(left + MARGIN, cx), "right": min(width - 1 - right + MARGIN, width - 1 - cx),+ "top": min(top + MARGIN, cy), "bottom": min(height - 1 - bottom + MARGIN, height - 1 - cy)}+ notes = []+ if 4 * (width - padding["left"] - padding["right"]) < width or 4 * (height - padding["top"] - padding["bottom"]) < height:+ notes.append("the content area is less than a quarter of the element; its centre is probably not empty")+ return padding, notes+++def _runs(mask: Any) -> list[tuple[int, int, int]]:+ runs = []+ for y in np.flatnonzero(mask.any(axis=1)):+ edges = np.diff(np.concatenate(([0], mask[y].astype(np.int8), [0])))+ for x0, x1 in zip(np.flatnonzero(edges == 1), np.flatnonzero(edges == -1)):+ runs.append((int(y), int(x0), int(x1)))+ return runs+++def _parts(mask: Any) -> list[dict[str, Any]]:+ """8-connected parts of ``mask``: their runs, pixel count, bounding box and centroid."""+ runs = _runs(mask)+ parent = list(range(len(runs)))++ def find(index: int) -> int:+ while parent[index] != index:+ parent[index] = parent[parent[index]]+ index = parent[index]+ return index++ previous: list[int] = []+ current: list[int] = []+ row = None+ for index, (y, x0, x1) in enumerate(runs):+ if y != row:+ previous = current if row == y - 1 else []+ current, row = [], y+ for other in previous:+ _, ox0, ox1 = runs[other]+ if ox0 <= x1 and x0 <= ox1: # touching rows; one column apart counts (diagonal)+ parent[find(other)] = find(index)+ current.append(index)+ groups: dict[int, list[int]] = {}+ for index in range(len(runs)):+ groups.setdefault(find(index), []).append(index)+ parts = []+ for members in groups.values():+ spans = [runs[i] for i in members]+ count = sum(x1 - x0 for _, x0, x1 in spans)+ sum_x = sum((x0 + x1 - 1) * (x1 - x0) / 2 for _, x0, x1 in spans)+ sum_y = sum(y * (x1 - x0) for y, x0, x1 in spans)+ x_min, x_max = min(x0 for _, x0, _ in spans), max(x1 for _, _, x1 in spans)+ y_min, y_max = min(y for y, _, _ in spans), max(y for y, _, _ in spans) + 1+ parts.append({"runs": spans, "pixels": count, "centroid": (sum_x / count, sum_y / count),+ "bbox": (x_min, y_min, x_max, y_max)})+ parts.sort(key=lambda part: (part["bbox"][1], part["bbox"][0]))+ return parts+++def split_ui_kit(image: Image.Image, *, alpha_floor: int = 64,+ alpha_edge: int = 2) -> tuple[dict[str, Image.Image], dict[str, Any]]:+ """Cut ``image`` along the layout: element images by name, and the report (without the sheet path)."""+ rgba = image.convert("RGBA")+ width, height = rgba.size+ if abs(width - height) > 0.01 * max(width, height):+ raise ValueError(f"a UI kit sheet must be square (1:1); this one is {width}x{height}")+ cleanup = None+ if alpha_floor:+ rgba, cleanup = clear_haze(rgba, floor=alpha_floor, edge=alpha_edge)+ pixels = np.asarray(rgba)+ scaled = boxes((width, height))+ reach = GAP / 2 * width / REFERENCE+ assigned: dict[str, list[dict[str, Any]]] = {name: [] for name in scaled}+ dropped, unassigned, reasons = 0, [], []+ for part in _parts(pixels[..., 3] > 0):+ if part["pixels"] < MIN_PART:+ dropped += 1+ continue+ cx, cy = part["centroid"]+ owner = next((name for name, (x, y, w, h) in scaled.items()+ if x - reach <= cx < x + w + reach and y - reach <= cy < y + h + reach), None)+ if owner is None:+ x0, y0, x1, y1 = part["bbox"]+ unassigned.append({"rect": _rect(x0, y0, x1 - x0, y1 - y0), "pixels": part["pixels"]})+ reasons.append(f"a part of {part['pixels']} pixels at ({x0}, {y0}) lies in no box")+ continue+ assigned[owner].append(part)+ elements: dict[str, Image.Image] = {}+ records: dict[str, Any] = {}+ for slot in LAYOUT:+ parts = assigned[slot.name]+ if not parts:+ raise ValueError(f"{slot.name}: its box holds no element; generate the sheet again")+ x0 = min(part["bbox"][0] for part in parts)+ y0 = min(part["bbox"][1] for part in parts)+ x1 = max(part["bbox"][2] for part in parts)+ y1 = max(part["bbox"][3] for part in parts)+ cut = np.zeros((y1 - y0, x1 - x0, 4), dtype=np.uint8)+ for part in parts:+ for y, a, b in part["runs"]:+ cut[y - y0, a - x0:b - x0] = pixels[y, a:b]+ element = Image.fromarray(cut)+ insets, inset_notes = measure_insets(element, slot.stretch)+ padding, padding_notes = measure_padding(element)+ reasons += [f"{slot.name}: {note}" for note in inset_notes + padding_notes]+ elements[slot.name] = element+ records[slot.name] = {+ "file": f"{slot.name}.png",+ "box": _rect(*scaled[slot.name]),+ "rect": _rect(x0, y0, x1 - x0, y1 - y0),+ "size": {"w": x1 - x0, "h": y1 - y0},+ "stretch": slot.stretch,+ "insets": insets,+ "padding": padding,+ "parts": len(parts),+ }+ report = {+ "kind": "sprite-gen-ui-kit",+ "version": 1,+ "sheet_size": [width, height],+ "status": "needs-review" if reasons else "pass",+ "review_reasons": reasons,+ "alpha_cleanup": cleanup,+ "dropped_parts": dropped,+ "unassigned": unassigned,+ "elements": records,+ }+ return elements, report+++def _publish(*, sheet: Path, out_dir: Path, alpha_floor: int = 64, alpha_edge: int = 2,+ report: Path | None = None) -> int:+ sheet = Path(sheet).expanduser().resolve()+ out_dir = Path(out_dir).expanduser().resolve()+ report_path = Path(report).expanduser().resolve() if report is not None else out_dir / "ui-kit.json"+ if not sheet.is_file():+ raise ValueError(f"sheet is not a file: {sheet}")+ if out_dir == sheet.parent or out_dir in sheet.parents or report_path == sheet:+ raise ValueError("the output directory must not hold the sheet; choose a new directory")+ with Image.open(sheet) as image:+ if image.format != "PNG" or getattr(image, "n_frames", 1) != 1:+ raise ValueError("--sheet must be a single-frame PNG")+ elements, measured = split_ui_kit(image, alpha_floor=alpha_floor, alpha_edge=alpha_edge)+ written = {"kind": measured["kind"], "version": measured["version"], "sheet": str(sheet)}+ written.update((key, value) for key, value in measured.items() if key not in written)+ payloads: dict[Path, bytes | str] = {}+ for name, element in elements.items():+ png = io.BytesIO()+ element.save(png, format="PNG")+ payloads[out_dir / measured["elements"][name]["file"]] = png.getvalue()+ payloads[report_path] = json.dumps(written, indent=2, allow_nan=False) + "\n"+ locked = []+ try:+ for directory in sorted({out_dir, report_path.parent}):+ directory.mkdir(parents=True, exist_ok=True)+ acquire_run_dir_lock(directory, "ui-kit")+ locked.append(directory)+ atomic_write_set(payloads)+ finally:+ for directory in reversed(locked):+ release_run_dir_lock(directory)+ print(f"ui-kit: {written['status']} — {len(elements)} elements in {out_dir} (report: {report_path})")+ return 0+++def add_arguments(parser: argparse.ArgumentParser) -> None:+ parser.add_argument("--sheet", required=True, type=Path,+ help="transparent square PNG drawn with `gen --layout-guide ui-kit`")+ parser.add_argument("--out-dir", required=True, type=Path,+ help="directory for <element>.png and ui-kit.json; must not hold the sheet")+ parser.add_argument("--alpha-floor", type=int, default=64,+ help="alpha haze cleanup floor, 1..255 (0 turns the cleanup off)")+ parser.add_argument("--alpha-edge", type=int, default=2,+ help="faint pixels this close to a solid pixel are its edge and are kept")+ parser.add_argument("--report", type=Path, help="JSON report (default: <out-dir>/ui-kit.json)")+++def run(**kwargs: Any) -> int:+ try:+ return _publish(**kwargs)+ except (OSError, ValueError, TypeError) as exc:+ raise SystemExit(f"ui-kit: {exc}") from exc+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ add_arguments(parser)+ return run(**vars(parser.parse_args(argv)))+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/sprite_gen/gen/__init__.py b/sprite_gen/gen/__init__.pyindex 20ea717..32bf517 100644--- a/sprite_gen/gen/__init__.py+++ b/sprite_gen/gen/__init__.py@@ -28,7 +28,7 @@ CLI:[--ref REF.png ...] [--transparent [--alpha-mode auto|native|chroma][--chroma-key magenta|green]] [--white-check CHECK.png] [--model ID][--aspect-ratio 1:1] [--quality low|medium|high|xhigh|max|auto]- [--resolution 1k|1.5k|2k] [--layout-guide]+ [--resolution 1k|1.5k|2k] [--layout-guide [figure|ui-kit]][--report REPORT.json] [--keep-session]"""@@ -104,6 +104,9 @@ _CODEX_PROBE_TIMEOUT_SECONDS = 15# in-place motion to bob into; a box alone is read loosely, the lines set the scale.LAYOUT_GUIDE_LONG_EDGE = 1024LAYOUT_GUIDE_NAME = "layout-guide.png"+# `--layout-guide ui-kit` attaches the UI kit layout instead (`sprite_gen.frames.ui_kit`, docs/ui-kit.md):+# one box per element, the boxes `ui-kit` later cuts along. The bare flag is the figure guide.+LAYOUT_GUIDE_KINDS = ("figure", "ui-kit")CROWN_LINE = "#ff7a00"CROWN_MARK = "#ffb15c"FLOOR_LINE = "#00a7a7"@@ -185,6 +188,25 @@ def draw_layout_guide(path: Path, aspect_ratio: str | None) -> dict[str, Any]:return cell+def layout_guide_kind(value: bool | str | None) -> str | None:+ """Which guide `--layout-guide` asks for: True (the bare flag, a Python caller's bool) is the figure guide."""+ if value is True:+ return "figure"+ if value in (None, False):+ return None+ if value not in LAYOUT_GUIDE_KINDS:+ raise SystemExit(f"gen: unknown --layout-guide {value!r}; expected one of {', '.join(LAYOUT_GUIDE_KINDS)}")+ return str(value)+++def ui_kit_guide_size(aspect_ratio: str | None) -> tuple[int, int]:+ """The UI kit guide is square: its boxes are the ones `ui-kit` cuts a square sheet along."""+ width, height = layout_guide_size(aspect_ratio)+ if width != height:+ raise SystemExit(f"gen: the ui-kit layout guide is square; use --aspect-ratio 1:1 (got {aspect_ratio})")+ return width, height++def _make_provider(name: str, *, keep_session: bool):if name == "codex":return CodexProvider(keep_session=keep_session)@@ -367,9 +389,14 @@ def generate_image(keep_session: bool = False,workdir: Path | None = None,decontam: str = "off",- layout_guide: bool = False,+ layout_guide: bool | str | None = False,) -> GenResult:- """Generate one image and return a GenResult. Raises SystemExit on any failure."""+ """Generate one image and return a GenResult. Raises SystemExit on any failure.++ `layout_guide`: "figure" (or True) attaches the one-slot figure guide, "ui-kit" the UI kit layout."""+ guide_kind = layout_guide_kind(layout_guide)+ if guide_kind == "ui-kit":+ ui_kit_guide_size(aspect_ratio)if decontam not in ("off", "auto", "palette"):raise SystemExit(f"gen: unknown --decontam {decontam!r}; expected off|auto|palette")if decontam == "palette" and not transparent:@@ -393,7 +420,7 @@ def generate_image(strategy_source: str | None = Noneif transparent:# The layout guide is an attached image as much as a --ref is: the same step down applies.- attached_for_strategy = [*refs, Path(LAYOUT_GUIDE_NAME)] if layout_guide else refs+ attached_for_strategy = [*refs, Path(LAYOUT_GUIDE_NAME)] if guide_kind else refsstrategy, strategy_source = resolve_transparency_strategy(backend, alpha_mode, refs=attached_for_strategy)if decontam == "palette" and strategy != TRANSPARENCY_CHROMA:# before the provider is called: a paid generation must not end in this refusal@@ -404,7 +431,8 @@ def generate_image(# takes the outline and light fills with it (2026-10-04). A key the prompt already names stays.parts = still_prompt(prompt, view=view, facing=facing, handed=handed, body_plan=body_plan, refs=bool(refs),key=chroma_key if strategy_source == STRATEGY_SOURCE_REFS else None,- layout=layout_guide_cell(aspect_ratio) if layout_guide else None)+ layout=layout_guide_cell(aspect_ratio) if guide_kind == "figure" else None,+ ui_kit_guide=guide_kind == "ui-kit")prompt = parts.textfor line in prompt_parts.note_lines(parts):print(f"[gen] {line}", file=sys.stderr)@@ -428,9 +456,14 @@ def generate_image(try:guide_cell: dict[str, Any] | None = Noneattached = list(refs)- if layout_guide:+ if guide_kind:guide = workdir / LAYOUT_GUIDE_NAME- guide_cell = draw_layout_guide(guide, aspect_ratio)+ if guide_kind == "ui-kit":+ from sprite_gen.frames import ui_kit++ guide_cell = ui_kit.draw_guide(guide, ui_kit_guide_size(aspect_ratio))+ else:+ guide_cell = draw_layout_guide(guide, aspect_ratio)# Last, so "the last attached image" in the prompt is the guide whatever the caller attached.attached.append(guide)request = GenRequest(@@ -576,7 +609,7 @@ def _check_view(view: str | None, facing: str | None, facing_fix: str, handed: ldef still_prompt(prompt: str, *, view: str | None = None, facing: str | None = None,handed: list[handed_mod.Handed] | None = None, body_plan: list[Body] | None = None,refs: bool = False, key: str | None = None,- layout: dict[str, Any] | None = None) -> prompt_parts.Prompt:+ layout: dict[str, Any] | None = None, ui_kit_guide: bool = False) -> prompt_parts.Prompt:"""The prompt a still is drawn from: the caller's text, then the engine's pieces (`prompt_parts.Prompt.add`;without `handed` or `body_plan`, 2.22.0's prompt to the byte). In order:@@ -587,7 +620,8 @@ def still_prompt(prompt: str, *, view: str | None = None, facing: str | None = N- with `refs` and a `facing`: the turn over the reference (`facing.prompt_suffix`);- `key` (green / magenta, a ref run `auto` planned to key): the key background line, unless the promptnames a key background already;- - `layout` (the `--layout-guide` cell): where the guide's lines are.+ - `layout` (the `--layout-guide` cell): where the guide's lines are; `ui_kit_guide`+ (`--layout-guide ui-kit`): what to draw in each box of the UI kit layout."""figures = body_mod.figures(body_plan)parts = prompt_parts.Prompt(prompt, caller=f"{prompt} {figures}" if figures else None)@@ -605,6 +639,10 @@ def still_prompt(prompt: str, *, view: str | None = None, facing: str | None = Nparts.add("key-background", chroma_mod.KEY_BACKGROUND_TEXT[key], key=key)if layout is not None:parts.add("layout", layout_guide_text(layout))+ if ui_kit_guide:+ from sprite_gen.frames import ui_kit++ parts.add("layout", ui_kit.guide_text())return parts@@ -654,7 +692,7 @@ def _run(args: argparse.Namespace) -> int:keep_session=args.keep_session,workdir=args.workdir,decontam=str(getattr(args, "decontam", None) or "off"),- layout_guide=bool(getattr(args, "layout_guide", False)),+ layout_guide=getattr(args, "layout_guide", None),)payload = result.to_dict()# `provider` in the payload is always the backend that actually generated the@@ -757,11 +795,16 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:parser.add_argument("--trim-alpha", action="store_true", help="with --transparent: crop the published PNG to its opaque bbox so the bottom edge is the foot line (margins reported)")parser.add_argument("--layout-guide",- action="store_true",+ nargs="?",+ const="figure",+ choices=LAYOUT_GUIDE_KINDS,+ default=None,help=(- "attach a one-slot layout guide (frame, inner safe area at the row guide's 9.4 %% margin, "- "center line) after any --ref and ask for the whole subject inside the safe area, with room "- "above the head and below the feet; drawn for --aspect-ratio, square without one"+ "attach a layout guide after any --ref. Bare or `figure`: a one-slot guide (frame, inner safe "+ "area at the row guide's 9.4 %% margin, center line) asking for the whole subject inside the "+ "safe area, with room above the head and below the feet; drawn for --aspect-ratio, square "+ "without one. `ui-kit`: the UI kit layout, one box per element, for `sprite-gen ui-kit` "+ "(square only)"),)parser.add_argument("--white-check", type=Path, help="write a white-composite check image")diff --git a/tests/compose/test_game_pack_v2.py b/tests/compose/test_game_pack_v2.pyindex 7fdf780..0f34b8d 100644--- a/tests/compose/test_game_pack_v2.py+++ b/tests/compose/test_game_pack_v2.py@@ -13,6 +13,7 @@ import pytestfrom PIL import Image, ImageDrawfrom sprite_gen.compose import game_pack+from sprite_gen.frames.ui_kit import measure_insetsfrom sprite_gen.util.resample import resize_cell@@ -181,13 +182,16 @@ def test_ui_nine_slice_insets_and_padding_are_in_stored_frame_pixels(tmp_path):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()+ # scaled and rounded up, or what the ui-kit measure finds on the stored pixels if that is larger:+ # an ornament and its resampled fringe stay inside the fixed slices; content only shrinks+ measured, _ = measure_insets(image, stretch)+ assert entry["insets"] == {side: max(math.ceil(value * 0.5), measured[side]) for side, value in insets.items()}+ assert all(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"}assert record["pivot"] == {"x": 0.5, "y": 0.5}assert nine["hp_bar_frame"]["insets"]["top"] == nine["hp_bar_frame"]["insets"]["bottom"] == 0assert set(nine["timer_badge"]["insets"].values()) == {0}@@ -226,7 +230,7 @@ def test_version_2_output_is_deterministic(tmp_path):@pytest.mark.parametrize("change,message", [({"version": 1}, "version 2"),- ({"version": 3}, "version"),+ ({"version": 3}, "version must be 1 or 2"),({"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"),@@ -235,7 +239,7 @@ def test_version_2_output_is_deterministic(tmp_path):"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.5, "extra": 1}}, "unknown ui key"),({"ui": {"kit": "ui/ui-kit.json", "scale": 0.05}}, "inset"),])def test_bad_version_2_requests_are_refused(tmp_path, change, message):diff --git a/tests/frames/test_alpha_floor.py b/tests/frames/test_alpha_floor.pynew file mode 100644index 0000000..c6e8983--- /dev/null+++ b/tests/frames/test_alpha_floor.py@@ -0,0 +1,118 @@+# SPDX-License-Identifier: Apache-2.0+"""Alpha haze cleanup for transparent sheets (`sprite_gen.frames.alpha_floor.clear_haze`).++Synthetic sheets: a solid object wrapped in a faint haze ring, loose haze specks, and thin+strokes with anti-aliased edges. The cleanup must clear the haze and leave every solid pixel+and every edge pixel next to one exactly as it was; the report must measure that.+"""++import numpy as np+import pytest+from PIL import Image++from sprite_gen.frames.alpha_floor import clear_haze+++def hazy_sheet():+ pixels = np.zeros((64, 96, 4), dtype=np.uint8)+ y, x = np.indices((64, 96))+ distance = np.hypot(x - 30, y - 32)+ pixels[..., :3] = (180, 140, 90)+ # a solid disc of radius 12, a one-pixel anti-aliased rim, then a haze ring out to radius 20+ pixels[..., 3] = np.where(distance <= 12, 250, 0)+ rim = (distance > 12) & (distance <= 13)+ pixels[rim, 3] = 120+ tail = (distance > 13) & (distance <= 14)+ pixels[tail, 3] = 40+ ring = (distance > 14) & (distance <= 20)+ pixels[ring, 3] = 24+ # loose specks far from anything+ for sx, sy, a in ((5, 5, 30), (90, 60, 63), (60, 4, 1)):+ pixels[sy, sx] = (200, 200, 200, a)+ return pixels+++def thin_strokes():+ pixels = np.zeros((40, 40, 4), dtype=np.uint8)+ pixels[..., :3] = (230, 230, 255)+ # a one-pixel vertical stroke at full alpha+ pixels[2:38, 5, 3] = 255+ # a hairline at a fractional height: 70 % coverage on one row, 30 % on the next+ pixels[10, 10:38, 3] = 178+ pixels[11, 10:38, 3] = 77+ # a diagonal one pixel wide, anti-aliased onto both sides at low alpha+ for i in range(25):+ pixels[14 + i, 12 + i, 3] = 200+ pixels[14 + i, 13 + i, 3] = 35+ pixels[15 + i, 12 + i, 3] = 20+ # a stroke that just reaches the floor+ pixels[30, 2:20, 3] = 64+ pixels[31, 2:20, 3] = 10+ return pixels+++def test_haze_is_cleared_and_the_object_and_its_edge_are_untouched():+ source = hazy_sheet()+ before = source.copy()+ image, report = clear_haze(Image.fromarray(source), floor=64, edge=2)+ out = np.asarray(image)+ assert np.array_equal(source, before)+ alpha = before[..., 3]+ solid = alpha >= 64+ # every solid pixel and every faint pixel within two pixels of one is kept byte for byte+ near = np.zeros_like(solid)+ for dy in range(-2, 3):+ for dx in range(-2, 3):+ near |= np.roll(np.roll(solid, dy, 0), dx, 1)+ keep = solid | (near & (alpha > 0))+ assert np.array_equal(out[keep], before[keep])+ # haze becomes (0, 0, 0, 0); pixels that were already fully transparent are left as they were+ haze = (alpha > 0) & ~keep+ assert not out[haze].any()+ assert np.array_equal(out[alpha == 0], before[alpha == 0])+ total = alpha.size+ faint = (alpha > 0) & (alpha < 64)+ assert report["floor"] == 64 and report["edge_px"] == 2 and report["pixels"] == total+ assert report["faint_fraction_before"] == pytest.approx(np.count_nonzero(faint) / total)+ assert report["haze_fraction_before"] == pytest.approx(np.count_nonzero(faint & ~near) / total)+ assert report["haze_fraction_after"] == 0+ assert report["faint_fraction_after"] == pytest.approx(np.count_nonzero(faint & near) / total)+ assert report["cleared_pixels"] == np.count_nonzero(faint & ~near)+ assert report["changed_solid_pixels"] == 0 and report["changed_edge_pixels"] == 0+ assert report["haze_fraction_before"] > 0.04+++def test_thin_strokes_and_their_antialiased_edges_survive():+ source = thin_strokes()+ image, report = clear_haze(Image.fromarray(source), floor=64, edge=2)+ assert np.asarray(image).tobytes() == source.tobytes()+ assert report["cleared_pixels"] == 0+ assert report["haze_fraction_before"] == 0+++def test_a_stroke_entirely_below_the_floor_is_haze_and_a_lower_floor_keeps_it():+ pixels = np.zeros((10, 30, 4), dtype=np.uint8)+ pixels[5, 2:28] = (255, 255, 255, 40)+ cleared, _ = clear_haze(Image.fromarray(pixels), floor=64, edge=2)+ assert not np.asarray(cleared)[..., 3].any()+ kept, report = clear_haze(Image.fromarray(pixels), floor=32, edge=2)+ assert np.asarray(kept).tobytes() == pixels.tobytes()+ assert report["cleared_pixels"] == 0+++def test_edge_zero_keeps_only_solid_pixels():+ source = hazy_sheet()+ image, report = clear_haze(Image.fromarray(source), floor=64, edge=0)+ out = np.asarray(image)+ solid = source[..., 3] >= 64+ assert np.array_equal(out[solid], source[solid])+ assert not out[~solid][..., 3].any()+ assert report["faint_fraction_after"] == 0+++def test_rgb_input_and_bad_settings():+ image, report = clear_haze(Image.new("RGB", (4, 4), "red"), floor=64, edge=2)+ assert image.mode == "RGBA" and report["cleared_pixels"] == 0+ for floor, edge in ((0, 2), (256, 2), (64, -1), (64.5, 2), (True, 2)):+ with pytest.raises((ValueError, TypeError)):+ clear_haze(Image.new("RGBA", (4, 4)), floor=floor, edge=edge)diff --git a/tests/frames/test_slice_sheet_transparent.py b/tests/frames/test_slice_sheet_transparent.pynew file mode 100644index 0000000..8412f4a--- /dev/null+++ b/tests/frames/test_slice_sheet_transparent.py@@ -0,0 +1,85 @@+# SPDX-License-Identifier: Apache-2.0+"""`slice-sheet` on a sheet that is already transparent (`--chroma-key none`) and with the+shared alpha haze cleanup (`--alpha-floor`): a hazy ring around each prop would otherwise+join the prop's part and enlarge its measured height."""++from __future__ import annotations++import json+from pathlib import Path++import numpy as np+from PIL import Image++from sprite_gen import cli+from sprite_gen.frames import slice_sheet as slice_module+from sprite_gen.frames.slice_sheet import slice_sheet++PROP = (60, 90, 140, 250)+++def hazy_prop_sheet() -> Image.Image:+ pixels = np.zeros((200, 300, 4), dtype=np.uint8)+ for col in range(3):+ for row in range(2):+ x0, y0 = col * 100 + 30, row * 100 + 20+ pixels[y0:y0 + 60, x0:x0 + 40] = PROP+ solid = pixels[..., 3] > 0+ near = np.zeros_like(solid)+ for dy in range(-6, 7):+ for dx in range(-6, 7):+ near |= np.roll(np.roll(solid, dy, 0), dx, 1)+ pixels[near & ~solid] = (200, 200, 220, 20)+ pixels[3, 3] = (255, 255, 255, 30)+ return Image.fromarray(pixels)+++def opaque_height(path: Path) -> int:+ with Image.open(path) as image:+ alpha = np.asarray(image.convert("RGBA"))[..., 3]+ rows = np.flatnonzero((alpha >= 128).any(axis=1))+ return int(rows[-1] - rows[0] + 1)+++def slice_(tmp_path, name, **kwargs):+ sheet = tmp_path / "props.png"+ hazy_prop_sheet().save(sheet)+ return slice_sheet(sheet, tmp_path / name, None, canvas=(128, 192), baseline_y=180.0,+ target_height=120.0, **kwargs)+++def test_none_keeps_the_sheets_own_alpha(tmp_path):+ written = slice_(tmp_path, "plain")+ assert len(written) == 6+ with Image.open(written[0]) as image:+ alpha = np.asarray(image.convert("RGBA"))[..., 3]+ assert alpha.max() >= 240 and alpha[0, 0] == 0+++def test_alpha_floor_clears_the_haze_ring_before_measuring_parts(tmp_path):+ hazy = slice_(tmp_path, "hazy")+ clean = slice_(tmp_path, "clean", alpha_floor=64)+ # the ring adds 6 px above and below the 60 px prop; cleaned, only the 2 px edge band stays+ assert opaque_height(clean[0]) > opaque_height(hazy[0])+ assert abs(opaque_height(clean[0]) - round(120 * 60 / 64)) <= 1+ report = json.loads((tmp_path / "clean" / "alpha-cleanup.json").read_text())+ assert report["floor"] == 64 and report["edge_px"] == 2+ assert report["haze_fraction_before"] > 0 and report["haze_fraction_after"] == 0+ assert report["changed_solid_pixels"] == 0+ assert not (tmp_path / "hazy" / "alpha-cleanup.json").exists()+++def test_cli_takes_none_and_the_floor(tmp_path):+ sheet = tmp_path / "props.png"+ hazy_prop_sheet().save(sheet)+ out = tmp_path / "out"+ assert cli.main(["slice-sheet", "--sheet", str(sheet), "--out-dir", str(out), "--chroma-key", "none",+ "--alpha-floor", "64", "--prefix", "prop_", "--cell-width", "128", "--cell-height", "192",+ "--baseline-y", "180", "--target-height", "120"]) == 0+ assert (out / "prop_alpha-cleanup.json").is_file()+ assert len(list(out.glob("prop_cell-*.png"))) == 6+++def test_parse_chroma_key_reads_none():+ assert slice_module.parse_chroma_key("none") is None+ assert slice_module.parse_chroma_key("magenta") == (255, 0, 255)diff --git a/tests/frames/test_ui_kit.py b/tests/frames/test_ui_kit.pynew file mode 100644index 0000000..e61608c--- /dev/null+++ b/tests/frames/test_ui_kit.py@@ -0,0 +1,312 @@+# SPDX-License-Identifier: Apache-2.0+"""`ui-kit`: a transparent sheet drawn on the fixed layout becomes nine-slice elements.++The sheet is synthetic and drawn into the layout's own boxes: frames with known corner+ornaments (one with a long thin flourish along its top edge), a bar frame with an end gem+taller than the bar, a round badge, light colour noise, a faint haze ring around every+element and loose specks. Insets are checked to the pixel: every ornament column and row+lies inside a fixed slice, and nothing more than the 2 px margin does.+"""++import json+import math++import numpy as np+import pytest+from PIL import Image++from sprite_gen.compose import game_pack+from sprite_gen.frames import ui_kit++SIZE = 512+BORDER = (200, 200, 220, 255)+ORNAMENT = (120, 220, 200, 255)+FLOURISH = (255, 180, 60, 255)+INTERIOR = (20, 30, 60, 210)+TRACK = (10, 10, 20, 180)+GEM = (220, 40, 80, 255)+++def fill(pixels, x0, y0, x1, y1, color):+ pixels[y0:y1, x0:x1] = color+++def draw_frame(pixels, x, y, w, h, k, flourish=0):+ fill(pixels, x, y, x + w, y + h, BORDER)+ fill(pixels, x + 3, y + 3, x + w - 3, y + h - 3, INTERIOR)+ for cx, cy in ((x, y), (x + w - k, y), (x, y + h - k), (x + w - k, y + h - k)):+ fill(pixels, cx, cy, cx + k, cy + k, ORNAMENT)+ if flourish:+ fill(pixels, x + k, y + 4, x + k + flourish, y + 6, FLOURISH)+++def draw_bar(pixels, x, y, w, h, radius, cap):+ fill(pixels, x + radius, y + 6, x + w, y + h - 6, BORDER)+ fill(pixels, x + radius, y + 9, x + w - 3, y + h - 9, TRACK)+ fill(pixels, x + w - cap, y + 2, x + w, y + h - 2, ORNAMENT)+ yy, xx = np.indices((h, 2 * radius))+ disc = np.hypot(xx - radius + 0.5, yy - h / 2 + 0.5) <= radius+ region = pixels[y:y + h, x:x + 2 * radius]+ region[disc] = GEM+++def draw_badge(pixels, x, y, d):+ yy, xx = np.indices((d, d))+ r = np.hypot(xx - d / 2 + 0.5, yy - d / 2 + 0.5)+ region = pixels[y:y + d, x:x + d]+ region[r <= d / 2] = BORDER+ region[r <= d / 2 - 3] = INTERIOR+++# element -> (offset inside its box, drawing parameters); every element sits 4 px inside its box+PLAN = {"panel": dict(k=18, flourish=60), "button": dict(k=12), "button_pressed": dict(k=12),+ "card": dict(k=16), "hp_bar_frame": dict(radius=20, cap=10), "xp_bar_frame": dict(radius=20, cap=10),+ "timer_badge": dict()}+++def synthetic_sheet(*, haze=True, noise=True, stray=False, missing=None, crest=False):+ pixels = np.zeros((SIZE, SIZE, 4), dtype=np.uint8)+ drawn = {}+ for name, (bx, by, bw, bh) in ui_kit.boxes((SIZE, SIZE)).items():+ if name == missing:+ continue+ x, y, w, h = bx + 4, by + 4, bw - 8, bh - 8+ params = PLAN[name]+ if name.endswith("bar_frame"):+ draw_bar(pixels, x, y, w, h, **params)+ elif name == "timer_badge":+ w = h = min(w, h)+ draw_badge(pixels, x, y, w)+ else:+ draw_frame(pixels, x, y, w, h, **params)+ if crest and name == "card":+ fill(pixels, x + w // 2 - 6, y, x + w // 2 + 6, y + 14, FLOURISH)+ drawn[name] = (x, y, w, h)+ solid = pixels[..., 3] > 0+ if noise:+ rng = np.random.default_rng(3)+ jitter = rng.integers(-4, 5, pixels[..., :3].shape)+ pixels[..., :3] = np.where(solid[..., None], np.clip(pixels[..., :3].astype(int) + jitter, 0, 255), 0)+ if haze:+ near = np.zeros_like(solid)+ for dy in range(-6, 7):+ for dx in range(-6, 7):+ near |= np.roll(np.roll(solid, dy, 0), dx, 1)+ ring = near & ~solid+ pixels[ring] = (150, 150, 170, 22)+ for sx, sy in ((5, 500), (500, 5), (330, 470)):+ pixels[sy, sx] = (200, 200, 200, 40)+ if stray:+ fill(pixels, 250, 410, 270, 430, BORDER)+ return Image.fromarray(pixels), drawn+++def split(**kwargs):+ image, drawn = synthetic_sheet(**kwargs)+ elements, report = ui_kit.split_ui_kit(image)+ return image, drawn, elements, report+++def offset(report, drawn, name):+ rect = report["elements"][name]["rect"]+ x, y, w, h = drawn[name]+ return x - rect["x"], y - rect["y"], rect["x"] + rect["w"] - (x + w), rect["y"] + rect["h"] - (y + h)+++def test_layout_is_the_documented_table_and_scales_with_the_sheet():+ assert [entry.name for entry in ui_kit.LAYOUT] == [+ "panel", "button", "button_pressed", "card", "hp_bar_frame", "xp_bar_frame", "timer_badge"]+ full = ui_kit.boxes((1024, 1024))+ assert full["panel"] == (48, 48, 576, 400)+ assert full["card"] == (704, 400, 272, 576)+ assert full["timer_badge"] == (48, 816, 160, 160)+ assert ui_kit.boxes((512, 512))["card"] == (352, 200, 136, 288)+ assert {e.name: e.stretch for e in ui_kit.LAYOUT} == {+ "panel": "xy", "button": "xy", "button_pressed": "xy", "card": "xy",+ "hp_bar_frame": "x", "xp_bar_frame": "x", "timer_badge": "none"}+ # boxes never touch: 48 px apart at 1024+ names = list(full)+ for i, a in enumerate(names):+ for b in names[i + 1:]:+ ax, ay, aw, ah = full[a]+ bx, by, bw, bh = full[b]+ assert ax + aw + 48 <= bx or bx + bw + 48 <= ax or ay + ah + 48 <= by or by + bh + 48 <= ay+++def test_frame_insets_cover_every_corner_ornament_and_the_long_flourish():+ _, drawn, elements, report = split()+ assert report["status"] == "pass", report["review_reasons"]+ for name in ("panel", "button", "button_pressed", "card"):+ entry = report["elements"][name]+ left, top, right, bottom = offset(report, drawn, name)+ k = PLAN[name]["k"]+ reach = k + PLAN[name].get("flourish", 0)+ assert entry["stretch"] == "xy"+ assert entry["insets"] == {"left": left + reach + 2, "right": right + k + 2,+ "top": top + k + 2, "bottom": bottom + k + 2}, name+ assert elements[name].size == (entry["size"]["w"], entry["size"]["h"])+++def test_bar_insets_cover_the_gem_and_the_cap_and_padding_is_the_track():+ _, drawn, elements, report = split()+ for name in ("hp_bar_frame", "xp_bar_frame"):+ entry = report["elements"][name]+ left, top, right, bottom = offset(report, drawn, name)+ radius, cap = PLAN[name]["radius"], PLAN[name]["cap"]+ assert entry["stretch"] == "x"+ # the cap is taller than the bar, so its kept 2 px anti-aliased edge lies left of it, inside the+ # element: that edge belongs to the cap's fixed slice too+ assert entry["insets"] == {"left": left + 2 * radius + 2, "right": right + cap + 2 + 2, "top": 0, "bottom": 0}+ # the track: right of the gem, left of the cap, inside the border rows (9 px from the drawn top/bottom)+ assert entry["padding"] == {"left": left + 2 * radius + 2, "right": right + cap + 2,+ "top": top + 9 + 2, "bottom": bottom + 9 + 2}+++def test_badge_does_not_stretch_and_its_content_fits_inside_the_ring():+ _, drawn, elements, report = split()+ entry = report["elements"]["timer_badge"]+ assert entry["stretch"] == "none"+ assert entry["insets"] == {"left": 0, "right": 0, "top": 0, "bottom": 0}+ left, top, _, _ = offset(report, drawn, "timer_badge")+ d = drawn["timer_badge"][2]+ centre = (left + d / 2, top + d / 2)+ pad, size = entry["padding"], entry["size"]+ corners = [(pad["left"], pad["top"]), (size["w"] - pad["right"], pad["top"]),+ (pad["left"], size["h"] - pad["bottom"]), (size["w"] - pad["right"], size["h"] - pad["bottom"])]+ for cx, cy in corners:+ assert math.hypot(cx - centre[0], cy - centre[1]) <= d / 2 - 3+ inner = d / 2 - 3+ assert size["w"] - pad["left"] - pad["right"] >= 1.2 * inner+++def test_frame_padding_keeps_text_off_the_border_and_the_ornaments():+ _, drawn, elements, report = split()+ for name in ("panel", "card", "button"):+ entry = report["elements"][name]+ left, top, right, bottom = offset(report, drawn, name)+ pad = entry["padding"]+ k = PLAN[name]["k"]+ for side, edge in (("left", left), ("right", right), ("top", top), ("bottom", bottom)):+ assert edge + k <= pad[side] <= edge + k + 4, (name, side, pad)+++def test_haze_is_cleared_before_cutting_and_reported():+ _, drawn, elements, report = split()+ cleanup = report["alpha_cleanup"]+ assert cleanup["floor"] == 64 and cleanup["edge_px"] == 2+ assert cleanup["haze_fraction_before"] > 0.01 and cleanup["haze_fraction_after"] == 0+ assert cleanup["changed_solid_pixels"] == 0 and cleanup["changed_edge_pixels"] == 0+ assert report["dropped_parts"] == 0+ assert report["unassigned"] == []+ # the element keeps at most its two-pixel anti-aliased edge of haze, never the six-pixel ring+ for name in drawn:+ assert all(0 <= value <= 2 for value in offset(report, drawn, name)), name+++def test_ornament_reaching_the_middle_of_an_edge_is_flagged():+ _, _, _, report = split(crest=True)+ assert report["status"] == "needs-review"+ assert any(reason.startswith("card:") and "x" in reason for reason in report["review_reasons"])+++def test_a_large_part_outside_every_box_is_reported():+ _, _, _, report = split(stray=True)+ assert report["status"] == "needs-review"+ assert report["unassigned"] == [{"rect": {"x": 250, "y": 410, "w": 20, "h": 20}, "pixels": 400}]+++def test_an_empty_box_fails():+ image, _ = synthetic_sheet(missing="button_pressed")+ with pytest.raises(ValueError, match="button_pressed"):+ ui_kit.split_ui_kit(image)+++def test_a_sheet_that_is_not_square_fails():+ with pytest.raises(ValueError, match="square"):+ ui_kit.split_ui_kit(Image.new("RGBA", (512, 400)))+++def test_cli_writes_element_pngs_and_a_report_the_pack_reads(tmp_path):+ image, drawn = synthetic_sheet()+ sheet = tmp_path / "uikit.png"+ image.save(sheet)+ before = sheet.read_bytes()+ out = tmp_path / "ui"+ assert ui_kit.main(["--sheet", str(sheet), "--out-dir", str(out)]) == 0+ assert sheet.read_bytes() == before+ report = json.loads((out / "ui-kit.json").read_text())+ assert report["kind"] == "sprite-gen-ui-kit" and report["version"] == 1+ assert report["sheet"] == str(sheet.resolve()) and report["sheet_size"] == [SIZE, SIZE]+ assert list(report["elements"]) == [entry.name for entry in ui_kit.LAYOUT]+ assert sorted(p.name for p in out.iterdir()) == sorted([f"{e.name}.png" for e in ui_kit.LAYOUT] + ["ui-kit.json"])+ cleaned, _ = ui_kit.clear_haze(image.convert("RGBA"), floor=64, edge=2)+ for name, entry in report["elements"].items():+ assert entry["file"] == f"{name}.png"+ assert entry["box"] == dict(zip("xywh", ui_kit.boxes((SIZE, SIZE))[name]))+ rect = entry["rect"]+ with Image.open(out / entry["file"]) as element:+ assert element.size == (entry["size"]["w"], entry["size"]["h"]) == (rect["w"], rect["h"])+ crop = cleaned.crop((rect["x"], rect["y"], rect["x"] + rect["w"], rect["y"] + rect["h"]))+ assert element.convert("RGBA").tobytes() == crop.tobytes()+ request = tmp_path / "game.json"+ request.write_text(json.dumps({"version": 2, "ui": {"kit": "ui/ui-kit.json"}}))+ result = game_pack.pack(request, tmp_path / "pack")+ for name, entry in report["elements"].items():+ packed = result["ui"]["nine_slice"][name]+ assert packed["insets"] == entry["insets"] and packed["padding"] == entry["padding"]+ assert packed["size"] == entry["size"] and packed["stretch"] == entry["stretch"]+++def test_cli_refuses_to_write_into_the_sheets_directory_over_the_sheet(tmp_path):+ image, _ = synthetic_sheet()+ sheet = tmp_path / "panel.png"+ image.save(sheet)+ with pytest.raises(SystemExit, match="sheet"):+ ui_kit.main(["--sheet", str(sheet), "--out-dir", str(tmp_path)])+++def test_guide_draws_every_box_and_the_text_names_every_element(tmp_path):+ path = tmp_path / "guide.png"+ cell = ui_kit.draw_guide(path, (1024, 1024))+ with Image.open(path) as guide:+ guide = guide.convert("RGB")+ assert guide.size == (1024, 1024)+ for x, y, w, h in ui_kit.boxes((1024, 1024)).values():+ assert guide.getpixel((x + w // 2, y)) == ui_kit.GUIDE_BOX+ assert guide.getpixel((x, y + h // 2)) == ui_kit.GUIDE_BOX+ assert guide.getpixel((x + w // 2, y + h // 2)) == ui_kit.GUIDE_BACKGROUND+ assert cell == {"kind": "ui-kit", "width": 1024, "height": 1024,+ "boxes": {name: dict(zip("xywh", box)) for name, box in ui_kit.boxes((1024, 1024)).items()}}+ text = ui_kit.guide_text()+ positions = [text.index(entry.what) for entry in ui_kit.LAYOUT]+ assert positions == sorted(positions)+ assert "last attached image is a layout guide" in text+ assert "no text" in text++[email protected]("scale", [0.75, 0.5, 0.37, 0.25])+def test_packed_kit_keeps_ornament_fringes_out_of_the_stretched_middle(tmp_path, scale):+ image, _ = synthetic_sheet(noise=False, haze=False)+ sheet = tmp_path / "uikit.png"+ image.save(sheet)+ assert ui_kit.main(["--sheet", str(sheet), "--out-dir", str(tmp_path / "ui")]) == 0+ request = tmp_path / "game.json"+ request.write_text(json.dumps({"version": 2, "ui": {"kit": "ui/ui-kit.json", "scale": scale}}))+ out = tmp_path / "pack"+ result = game_pack.pack(request, out)+ frames = {name: (page, record) for page in result["textures"] for name, record in page["frames"].items()}+ for name, entry in result["ui"]["nine_slice"].items():+ page, record = frames[entry["frame"]]+ box = record["frame"]+ with Image.open(out / page["image"]) as atlas:+ stored = np.asarray(atlas.convert("RGBA").crop(+ (box["x"], box["y"], box["x"] + box["w"], box["y"] + box["h"]))).astype(float)+ stored[..., :3] *= stored[..., 3:] / 255+ insets, (w, h) = entry["insets"], (entry["size"]["w"], entry["size"]["h"])+ if entry["stretch"] in ("xy", "x"):+ band = stored[:, insets["left"]:w - insets["right"]]+ # every stretched column looks like the band's own median column, within 8 of 255+ assert np.abs(band - np.median(band, axis=1)[:, None]).max() <= 8, (name, scale, "x")+ if entry["stretch"] == "xy":+ band = stored[insets["top"]:h - insets["bottom"]]+ assert np.abs(band - np.median(band, axis=0)[None]).max() <= 8, (name, scale, "y")diff --git a/tests/gen/test_layout_guide.py b/tests/gen/test_layout_guide.pyindex f26dc06..8521a65 100644--- a/tests/gen/test_layout_guide.py+++ b/tests/gen/test_layout_guide.py@@ -117,3 +117,37 @@ def test_counts_as_an_attached_image_for_transparency(tmp_path, monkeypatch):def test_refuses_a_ratio_it_cannot_read(tmp_path, monkeypatch):with pytest.raises(SystemExit, match="cannot read aspect ratio"):_run(tmp_path, monkeypatch, layout_guide=True, aspect_ratio="tall")+++def test_ui_kit_guide_attaches_the_kit_layout_and_names_every_element(tmp_path, monkeypatch):+ from sprite_gen.frames import ui_kit++ fake, report = _run(tmp_path, monkeypatch, layout_guide="ui-kit", aspect_ratio="1:1")++ guide = fake.attached[0].convert("RGB")+ assert guide.size == (1024, 1024)+ for x, y, w, h in ui_kit.boxes((1024, 1024)).values():+ assert guide.getpixel((x + w // 2, y)) == ui_kit.GUIDE_BOX+ assert guide.getpixel((x + w // 2, y + h // 2)) == ui_kit.GUIDE_BACKGROUND+ request = fake.requests[0]+ assert request.prompt.startswith("a tall knight, full body\n\n")+ assert request.prompt.endswith(ui_kit.guide_text())+ assert "crown" not in request.prompt+ cell = report["extra"]["layout_guide"]+ assert cell["kind"] == "ui-kit"+ assert cell["boxes"]["panel"] == {"x": 48, "y": 48, "w": 576, "h": 400}+ assert report["refs"] == []+++def test_ui_kit_guide_is_square(tmp_path, monkeypatch):+ with pytest.raises(SystemExit, match="square"):+ _run(tmp_path, monkeypatch, layout_guide="ui-kit", aspect_ratio="16:9")+ fake, _ = _run(tmp_path, monkeypatch, layout_guide="ui-kit")+ assert fake.attached[0].size == (1024, 1024)+++def test_the_flag_alone_is_still_the_figure_guide():+ parser = gen._build_parser()+ assert parser.parse_args(["--out", "x.png", "--layout-guide"]).layout_guide == "figure"+ assert parser.parse_args(["--out", "x.png", "--layout-guide", "ui-kit"]).layout_guide == "ui-kit"+ assert parser.parse_args(["--out", "x.png"]).layout_guide is None