Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
Merge main (sound recipe version 4, version 3 bundles loadable) into the scene art verbs branch
Soohong Kim6aa24af99c73
diff --cc CHANGELOG.mdindex 3c7f180,f62fdc1..80d9b31--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -4,12 -4,7 +4,13 @@@ All notable public changes to `sprite-g## Unreleased+- **New: `background-tile --axis xy` makes one tile seamless in both directions and measures both joins.** It quilts along x, then along y with a cyclic seam: the second seam's two ends, which meet across the x wrap, may differ by one step at most, so the second quilt cannot break the first one's join. The report measures the finished tile on both axes (`axes.x`, `axes.y`, each with its join, quilt seam, `status` and reasons); the top-level `status` is `needs-review` when either axis is, and each reason names its axis. Two separate one-axis runs had no such rule, and the second run's report measured only its own axis. `inspect_tile_xy(image)` measures both joins of any tile ([asset-tools](docs/asset-tools.md#both-axes-a-ground-tile)).+- **New: alpha haze cleanup for transparent sheets (`frames.alpha_floor.clear_haze`).** Pixels at or above a floor, and faint pixels within a few pixels of them (an object's anti-aliased edge), are kept byte for byte; every other faint pixel becomes fully transparent. The report measures the haze share before and after and counts the solid and edge pixels that changed (`0`). Used by `ui-kit` (on by default) and `slice-sheet --alpha-floor N` (off by default; writes `<prefix>alpha-cleanup.json`). `slice-sheet --chroma-key none` cuts a sheet that is already transparent on its own alpha ([sheet-slicing](docs/sheet-slicing.md#transparent-sheets)).+- **New verb: `ui-kit` splits a game UI kit sheet into nine-slice elements.** `gen --layout-guide ui-kit` attaches a fixed square layout (panel, button, pressed button, card frame, HP and XP bar frames, timer badge) and asks for each element in its box. `ui-kit --sheet uikit.png --out-dir ui/` clears the haze, assigns parts to boxes by centroid, and writes each element's PNG and `ui-kit.json`: its rectangle, its stretch (`xy`, `x` for the bars, `none` for the badge), nine-slice insets measured so that every corner ornament and end cap lies in a fixed slice, and the content padding (a bar frame's track, a panel's text area). An ornament in the middle of an edge, an empty box or a stray part is reported or refused ([ui-kit](docs/ui-kit.md)). `--layout-guide` alone is still the one-slot figure guide.+- **New: `game-pack` request and manifest version 2 with `images`, `tiles` and `ui`.** Single images (props) are atlas frames with an anchor and an optional footprint (`"base"` measures where the image meets the ground); tiles are their own PNG and WebP files with their stored and on-screen sizes; `ui.kit` reads a `ui-kit` report into nine-slice entries (frame, size, stretch, insets, padding) and `ui.icons` adds fixed icons. Every number is in pixels of the stored image. A version 1 request is packed byte for byte as before, and a version 1 request naming the new sections is refused ([game-pack](docs/game-pack.md#version-2-images-tiles-and-ui)).+- **Tests** — `tests/background/test_tile_xy.py` (an exact doubly periodic crop, a join that stays visible on one axis names that axis, the cyclic seam), `tests/frames/test_alpha_floor.py` (a haze ring cleared, thin strokes and their anti-aliased edges kept), `tests/frames/test_ui_kit.py` (a synthetic sheet on the layout: insets to the pixel over corner ornaments, a long flourish, a bar's end gem and cap; badge padding inside its ring; a packed kit at four scales keeps ornament fringes out of the stretched middle), `tests/frames/test_slice_sheet_transparent.py`, `tests/compose/test_game_pack_v2.py` (the manifest field by field, refusals, and a version 1 manifest and page pixels frozen from 2.44.0), `tests/compose/test_game_pack_audio.py` (a version 1 pack with sound keeps its file list, manifest bytes and page pixels from 2.44.0; a version 2 pack with sound adds only its tile files) and the `--layout-guide ui-kit` cases in `tests/gen/test_layout_guide.py`.++ - Bump audio processing recipe to version 4, measure BS.1770-4 loudness over normalized PCM frames and gated blocks, support a peak-limited loudness goal, normalize loudnorm-unanalysable short clips via limiter passes instead of refusing them, encode AAC using `-aac_coder fast`, record `normalization.pcm_lufs` and `pcm_true_peak_dbtp` required to load version 4 bundles, keep recipe version 3 bundles loadable in game packs by their own rule (target loudness, decoded files re-measured with loudnorm), reject recipe version 1-2 bundles, and reject recipe version 1-3 output directories in `sprite-gen sound` while reusing cached provider audio.- Bump audio processing recipe to version 3, require `ffprobe` on `PATH`, export M4A with `-movie_timescale 48000`, and validate AAC stream duration with `ffprobe`.- Add bounded one-frame decoded length tolerance, preserving loop duration, trimming one-shots, and rejecting shorter buffers and undersized overlaps at export.- Configure loop playback in `createAudioSource` using an internally cached L+1 guard frame buffer while preserving `prepareAudioBuffer` frame contracts.diff --cc tests/compose/test_game_pack_audio.pyindex 7aabd51,c5d61c9..3c40982--- a/tests/compose/test_game_pack_audio.py+++ b/tests/compose/test_game_pack_audio.py@@@ -75,48 -84,55 +84,102 @@@ def test_broken_audio_cannot_publish_a_assert not (tmp_path/'bad').exists()+# A version 1 pack with sound, packed by 2.44.0 (before request version 2): its file names, the+# manifest's exact bytes and the page's decoded pixels (encoded PNG/WebP bytes depend on the zlib and+# libwebp build). The sound files and the helper are compared byte for byte below.+V1_AUDIO_FILES = ['atlas-000.png', 'atlas-000.webp', 'audio-hit.m4a', 'audio-hit.ogg', 'game-pack.json',+ 'sprite-gen-audio-v2.mjs']+V1_AUDIO_MANIFEST_SHA256 = 'b79d31a4f38982f2c4a97b2aa5ddb4e77b545acee29210dac6a0e6649f9f5b67'+V1_AUDIO_PAGE_PIXELS_SHA256 = '834f7685ed723160d26784bb8ba1153e5f8ae56f5ddc8f51ebb0c54b1a63e067'+++def with_sound(tmp_path):+ path, request, _ = inputs(tmp_path)+ request['audio'] = [{'id': 'hit', 'source': 'audio/sound.json'}]+ path.write_text(json.dumps(request))+ return path, request+++def test_version_1_pack_with_sound_keeps_its_files_and_bytes(tmp_path):+ path, _ = with_sound(tmp_path)+ out = tmp_path/'out'+ result = pack(path, out)+ assert sorted(p.name for p in out.iterdir()) == V1_AUDIO_FILES+ manifest = (out/'game-pack.json').read_bytes()+ assert hashlib.sha256(manifest).hexdigest() == V1_AUDIO_MANIFEST_SHA256+ assert json.loads(manifest)['version'] == 1+ with Image.open(out/'atlas-000.png') as page:+ assert hashlib.sha256(page.convert('RGBA').tobytes()).hexdigest() == V1_AUDIO_PAGE_PIXELS_SHA256+ for fmt in ('ogg', 'm4a'):+ assert (out/f'audio-hit.{fmt}').read_bytes() == f'synthetic-{fmt}'.encode()+ assert hashlib.sha256((out/'sprite-gen-audio-v2.mjs').read_bytes()).hexdigest() == result['audio']['hit']['player']['sha256']+++def test_version_2_pack_with_sound_adds_only_the_tile_files(tmp_path):+ path, request = with_sound(tmp_path)+ pack(path, tmp_path/'v1')+ Image.new('RGBA', (8, 8), 'blue').save(tmp_path/'ground.png')+ request.update(version=2, tiles=[{'id': 'ground', 'source': 'ground.png', 'display': {'width': 16}}])+ path.write_text(json.dumps(request))+ result = pack(path, tmp_path/'v2')+ v1 = {p.name: p.read_bytes() for p in (tmp_path/'v1').iterdir()}+ v2 = {p.name: p.read_bytes() for p in (tmp_path/'v2').iterdir()}+ assert sorted(v2) == sorted([*v1, 'tile-ground.png', 'tile-ground.webp'])+ for name in ('audio-hit.ogg', 'audio-hit.m4a', 'sprite-gen-audio-v2.mjs', 'atlas-000.png', 'atlas-000.webp'):+ assert v2[name] == v1[name], name+ assert result['version'] == 2 and list(result['audio']) == ['hit']+ assert result['tiles']['ground']['image'] == 'tile-ground.png'+++++ def version_3_bundle(tmp_path, lufs=-18., spike=None, timescale=48000, **changes):+ """A sound made by processing version 3: real encodes of a synthetic tone, the file numbers that+ version's loudnorm check recorded, and no PCM loudness record. 48003 frames are no whole+ millisecond, so a millisecond AAC timescale cannot store them."""+ t = np.arange(48003) / 48000+ pcm = np.stack([np.sin(2*np.pi*440*t), np.sin(2*np.pi*440*t + .3)], axis=1)+ pcm *= 10 ** ((lufs - processing.measure(pcm)['lufs']) / 20)+ if spike:+ pcm[24000:24048] = spike+ path, request, manifest = inputs(tmp_path)+ files = {}+ for fmt, codec in (('ogg', ['-c:a', 'libopus', '-b:a', '160k']),+ ('m4a', ['-c:a', 'aac', '-b:a', '192k', '-movflags', '+faststart',+ '-movie_timescale', str(timescale)])):+ file = tmp_path/'audio'/f'sound.{fmt}'+ processing._ffmpeg(['-f', 'f32le', '-ar', '48000', '-ac', '2', '-i', 'pipe:0', *codec, str(file)],+ pcm.astype('<f4').tobytes())+ files[fmt] = {'path':file.name, 'duration_seconds':1.02, 'lufs':-18.6, 'true_peak_dbfs':-2,+ 'encode_passes':1, 'pcm_peak_limit_dbtp':-2,+ 'sha256':hashlib.sha256(file.read_bytes()).hexdigest()}+ manifest['playback']['end_frame'], manifest['duration_seconds'] = 48003, 48003/48000+ manifest.update(files=files, recipe={'processing_version':3},+ normalization={'method':'loudnorm-two-pass', 'peak_limit_dbtp':-2, 'gain_limiter_passes':0})+ for key, value in changes.items():+ manifest[key] = {**manifest[key], **value} if isinstance(value, dict) else value+ request['audio'] = [{'id':'hit','source':'audio/sound.json'}]+ path.write_text(json.dumps(request))+ (tmp_path/'audio'/'sound.json').write_text(json.dumps(manifest))+ return path+++ def test_a_version_3_sound_is_packed_by_the_target_it_was_made_for(tmp_path):+ result = pack(version_3_bundle(tmp_path), tmp_path/'pack')+ for file in result['audio']['hit']['files'].values():+ # its files are measured again over their frames, not taken from its loudnorm-era numbers+ assert abs(file['lufs'] + 18) <= .3 and file['lufs'] != -18.6+ assert -20 < file['true_peak_dbfs'] <= -1+++ @pytest.mark.parametrize('defect', ['quiet', 'peak-limited', 'hot', 'timescale', 'recipe2', 'recipe1'])+ def test_a_version_3_sound_that_misses_its_rule_is_refused(tmp_path, defect):+ path = version_3_bundle(+ tmp_path, lufs=-21.5 if defect in ('quiet', 'peak-limited') else -18.,+ spike=.94 if defect == 'hot' else None, # -0.5 dBTP while its manifest says -2+ timescale=1000 if defect == 'timescale' else 48000, # the millisecond AAC duration of version 2+ **({'normalization':{'pcm_lufs':-21.5, 'pcm_true_peak_dbtp':-2}} if defect == 'peak-limited' else {}),+ **({'recipe':{'processing_version':int(defect[-1])}} if defect.startswith('recipe') else {}))+ with pytest.raises(ValueError, match={'quiet':'does not match', 'peak-limited':'does not match',+ 'hot':'does not match', 'timescale':'container duration',+ 'recipe2':'version 3 or 4', 'recipe1':'version 3 or 4'}[defect]):+ pack(path, tmp_path/'bad')+ assert not (tmp_path/'bad').exists()