qlogicagent 2.18.7 → 2.18.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. package/README.md +382 -382
  2. package/dist/cli.js +1 -1
  3. package/dist/default-project-knowledge/INSTRUCTIONS.md +7 -7
  4. package/dist/default-project-knowledge/rules/project-workflow.md +6 -6
  5. package/dist/index.js +424 -423
  6. package/dist/runtime/infra/mcp-bridge-server.js +275 -275
  7. package/dist/skills/builtin/desktop-screenshot/SKILL.md +62 -62
  8. package/dist/skills/builtin/office-doc-reading/SKILL.md +19 -19
  9. package/dist/types/cli/handlers/turn-handler.d.ts +1 -1
  10. package/dist/types/contracts/structured-planner.d.ts +2 -0
  11. package/dist/types/orchestration/solo-evaluator.d.ts +1 -2
  12. package/dist/vendor/hatch-pet/LICENSE.txt +201 -201
  13. package/dist/vendor/hatch-pet/NOTICE.md +25 -25
  14. package/dist/vendor/hatch-pet/references/animation-rows.md +29 -29
  15. package/dist/vendor/hatch-pet/references/codex-pet-contract.md +35 -35
  16. package/dist/vendor/hatch-pet/references/qa-rubric.md +66 -66
  17. package/dist/vendor/hatch-pet/scripts/compose_atlas.py +169 -169
  18. package/dist/vendor/hatch-pet/scripts/derive_running_left_from_running_right.py +150 -150
  19. package/dist/vendor/hatch-pet/scripts/extract_strip_frames.py +408 -408
  20. package/dist/vendor/hatch-pet/scripts/inspect_frames.py +256 -256
  21. package/dist/vendor/hatch-pet/scripts/make_contact_sheet.py +96 -96
  22. package/dist/vendor/hatch-pet/scripts/prepare_pet_run.py +834 -834
  23. package/dist/vendor/hatch-pet/scripts/render_animation_previews.py +78 -78
  24. package/dist/vendor/hatch-pet/scripts/validate_atlas.py +157 -157
  25. package/package.json +2 -2
@@ -1,25 +1,25 @@
1
- # Vendored: OpenAI Codex Hatch-Pet pipeline
2
-
3
- This directory vendors the deterministic image-processing pipeline from the
4
- OpenAI Skills repository, used by qlogicagent's Petdex forge to produce
5
- Codex-compatible animated pet sprite sheets.
6
-
7
- - **Source:** https://github.com/openai/skills — `skills/.curated/hatch-pet/`
8
- - **License:** Apache License 2.0 (see `LICENSE.txt`)
9
- - **Vendored on:** 2026-06-05
10
-
11
- ## Contents
12
-
13
- - `scripts/*.py` — pipeline scripts (chroma-key frame extraction, frame QA,
14
- atlas composition, atlas validation, contact sheet, animation GIF previews,
15
- running-left mirror derivation, run preparation). Invoked as subprocesses by
16
- `src/runtime/pet/` — qlogicagent does **not** import them.
17
- - `references/*.md` — Codex pet contract / animation-rows / QA rubric, kept for
18
- reference and prompt alignment.
19
- - `LICENSE.txt` — Apache License 2.0.
20
-
21
- ## Modifications
22
-
23
- None. Files are vendored verbatim and executed via a Python subprocess
24
- (Pillow is the only third-party dependency). Any future local change must be
25
- recorded here per the Apache-2.0 NOTICE requirement.
1
+ # Vendored: OpenAI Codex Hatch-Pet pipeline
2
+
3
+ This directory vendors the deterministic image-processing pipeline from the
4
+ OpenAI Skills repository, used by qlogicagent's Petdex forge to produce
5
+ Codex-compatible animated pet sprite sheets.
6
+
7
+ - **Source:** https://github.com/openai/skills — `skills/.curated/hatch-pet/`
8
+ - **License:** Apache License 2.0 (see `LICENSE.txt`)
9
+ - **Vendored on:** 2026-06-05
10
+
11
+ ## Contents
12
+
13
+ - `scripts/*.py` — pipeline scripts (chroma-key frame extraction, frame QA,
14
+ atlas composition, atlas validation, contact sheet, animation GIF previews,
15
+ running-left mirror derivation, run preparation). Invoked as subprocesses by
16
+ `src/runtime/pet/` — qlogicagent does **not** import them.
17
+ - `references/*.md` — Codex pet contract / animation-rows / QA rubric, kept for
18
+ reference and prompt alignment.
19
+ - `LICENSE.txt` — Apache License 2.0.
20
+
21
+ ## Modifications
22
+
23
+ None. Files are vendored verbatim and executed via a Python subprocess
24
+ (Pillow is the only third-party dependency). Any future local change must be
25
+ recorded here per the Apache-2.0 NOTICE requirement.
@@ -1,29 +1,29 @@
1
- # Animation Rows
2
-
3
- The Codex app reads one fixed atlas: 8 columns, 9 rows, 192x208 pixels per cell.
4
-
5
- | Row | State | Used columns | Durations |
6
- | --- | --- | ---: | --- |
7
- | 0 | idle | 0-5 | 280, 110, 110, 140, 140, 320 ms |
8
- | 1 | running-right | 0-7 | 120 ms each, final 220 ms |
9
- | 2 | running-left | 0-7 | 120 ms each, final 220 ms |
10
- | 3 | waving | 0-3 | 140 ms each, final 280 ms |
11
- | 4 | jumping | 0-4 | 140 ms each, final 280 ms |
12
- | 5 | failed | 0-7 | 140 ms each, final 240 ms |
13
- | 6 | waiting | 0-5 | 150 ms each, final 260 ms |
14
- | 7 | running | 0-5 | 120 ms each, final 220 ms |
15
- | 8 | review | 0-5 | 150 ms each, final 280 ms |
16
-
17
- Unused cells after each row's final used column must be fully transparent.
18
-
19
- ## Row Purposes
20
-
21
- - `idle`: calm, low-distraction breathing/blinking loop; use as the reduced-motion first frame. Keep motion subtle and persona-preserving.
22
- - `running-right`: locomotion to the right; 8-frame loop should read directionally.
23
- - `running-left`: mirrored or redrawn locomotion to the left; do not simply reuse right-facing frames unless the design is symmetric, and any mirror derivation must preserve frame order and timing semantics.
24
- - `waving`: greeting or attention gesture; clear start, raised gesture, return.
25
- - `jumping`: anticipation, lift, peak, descent, settle.
26
- - `failed`: error/sad/deflated reaction; readable but not visually noisy.
27
- - `waiting`: blocked-on-user-input state; expectant asking pose for approval, help, or user input.
28
- - `running`: active task work state; focused processing, thinking, scanning, typing, or effortful concentration. This row is not foot-running; avoid jogging, sprinting, treadmill motion, raised knees, long steps, pumping arms, or directional travel.
29
- - `review`: focused/inspecting/thinking loop suitable for review state.
1
+ # Animation Rows
2
+
3
+ The Codex app reads one fixed atlas: 8 columns, 9 rows, 192x208 pixels per cell.
4
+
5
+ | Row | State | Used columns | Durations |
6
+ | --- | --- | ---: | --- |
7
+ | 0 | idle | 0-5 | 280, 110, 110, 140, 140, 320 ms |
8
+ | 1 | running-right | 0-7 | 120 ms each, final 220 ms |
9
+ | 2 | running-left | 0-7 | 120 ms each, final 220 ms |
10
+ | 3 | waving | 0-3 | 140 ms each, final 280 ms |
11
+ | 4 | jumping | 0-4 | 140 ms each, final 280 ms |
12
+ | 5 | failed | 0-7 | 140 ms each, final 240 ms |
13
+ | 6 | waiting | 0-5 | 150 ms each, final 260 ms |
14
+ | 7 | running | 0-5 | 120 ms each, final 220 ms |
15
+ | 8 | review | 0-5 | 150 ms each, final 280 ms |
16
+
17
+ Unused cells after each row's final used column must be fully transparent.
18
+
19
+ ## Row Purposes
20
+
21
+ - `idle`: calm, low-distraction breathing/blinking loop; use as the reduced-motion first frame. Keep motion subtle and persona-preserving.
22
+ - `running-right`: locomotion to the right; 8-frame loop should read directionally.
23
+ - `running-left`: mirrored or redrawn locomotion to the left; do not simply reuse right-facing frames unless the design is symmetric, and any mirror derivation must preserve frame order and timing semantics.
24
+ - `waving`: greeting or attention gesture; clear start, raised gesture, return.
25
+ - `jumping`: anticipation, lift, peak, descent, settle.
26
+ - `failed`: error/sad/deflated reaction; readable but not visually noisy.
27
+ - `waiting`: blocked-on-user-input state; expectant asking pose for approval, help, or user input.
28
+ - `running`: active task work state; focused processing, thinking, scanning, typing, or effortful concentration. This row is not foot-running; avoid jogging, sprinting, treadmill motion, raised knees, long steps, pumping arms, or directional travel.
29
+ - `review`: focused/inspecting/thinking loop suitable for review state.
@@ -1,35 +1,35 @@
1
- # Codex Pet Contract
2
-
3
- ## Sprite Atlas
4
-
5
- - Format: PNG or WebP.
6
- - Dimensions: `1536x1872`.
7
- - Grid: 8 columns x 9 rows.
8
- - Cell: `192x208`.
9
- - Background: transparent.
10
- - Unused cells: fully transparent.
11
-
12
- The webview animation uses CSS background positions from the fixed row and column counts. Do not add labels, gutters, borders, grid lines, shadows outside the cell, or extra frames.
13
-
14
- ## Local Custom Pet Package
15
-
16
- Place files under:
17
-
18
- ```text
19
- ${CODEX_HOME:-$HOME/.codex}/pets/<pet-name>/
20
- ├── pet.json
21
- └── spritesheet.webp
22
- ```
23
-
24
- Manifest shape:
25
-
26
- ```json
27
- {
28
- "id": "pet-name",
29
- "displayName": "Pet Name",
30
- "description": "One short sentence.",
31
- "spritesheetPath": "spritesheet.webp"
32
- }
33
- ```
34
-
35
- The app loads custom pets from the folder name under `${CODEX_HOME:-$HOME/.codex}/pets/`.
1
+ # Codex Pet Contract
2
+
3
+ ## Sprite Atlas
4
+
5
+ - Format: PNG or WebP.
6
+ - Dimensions: `1536x1872`.
7
+ - Grid: 8 columns x 9 rows.
8
+ - Cell: `192x208`.
9
+ - Background: transparent.
10
+ - Unused cells: fully transparent.
11
+
12
+ The webview animation uses CSS background positions from the fixed row and column counts. Do not add labels, gutters, borders, grid lines, shadows outside the cell, or extra frames.
13
+
14
+ ## Local Custom Pet Package
15
+
16
+ Place files under:
17
+
18
+ ```text
19
+ ${CODEX_HOME:-$HOME/.codex}/pets/<pet-name>/
20
+ ├── pet.json
21
+ └── spritesheet.webp
22
+ ```
23
+
24
+ Manifest shape:
25
+
26
+ ```json
27
+ {
28
+ "id": "pet-name",
29
+ "displayName": "Pet Name",
30
+ "description": "One short sentence.",
31
+ "spritesheetPath": "spritesheet.webp"
32
+ }
33
+ ```
34
+
35
+ The app loads custom pets from the folder name under `${CODEX_HOME:-$HOME/.codex}/pets/`.
@@ -1,66 +1,66 @@
1
- # QA Rubric
2
-
3
- Do not accept an atlas until all checks pass.
4
-
5
- ## Geometry
6
-
7
- - Exact `1536x1872` dimensions.
8
- - 8 columns x 9 rows.
9
- - Each frame fits inside its `192x208` cell.
10
- - Unused cells are transparent.
11
- - Fully transparent atlas pixels do not retain non-zero RGB residue after export.
12
- - `qa/review.json` has no errors.
13
- - `frames/frames-manifest.json` records component extraction for production rows unless `stable-slots` was intentionally chosen to preserve row-level playback stability after visual inspection.
14
-
15
- ## Character Consistency
16
-
17
- - Same silhouette and proportions across every row.
18
- - Same face and expression language.
19
- - Same style, material, palette, lighting, and prop design.
20
- - No frame introduces a new unintended character or object.
21
-
22
- ## Pet-Safe Style
23
-
24
- - Art reads as a Codex app pet, not a scene, app icon, logo sheet, or standalone illustration.
25
- - Silhouette is compact and clear enough to read inside a `192x208` cell.
26
- - The chosen style is consistent across every row, including edge treatment, material, lighting, and palette.
27
- - Pixel, plush, clay, sticker, flat vector, 3D toy, painterly mascot, ink, and brand-inspired styles are all acceptable when readable at pet size.
28
- - No tiny accessories, texture detail, logo detail, or text that disappears or becomes noisy at pet size.
29
-
30
- ## Animation Completeness
31
-
32
- - Each row uses the exact expected number of frames.
33
- - The first and last frames can loop without an obvious pop.
34
- - Directional rows read as the intended direction.
35
- - Mirrored directional rows preserve temporal frame order rather than reversing the cadence.
36
- - State-specific actions are recognizable at pet size.
37
- - Poses are generated animation variants, not repeated copies of the same source image.
38
- - Preview GIFs do not show unintended size popping, extraction-induced baseline jumps, or wrong directional facing.
39
-
40
- ## App Fitness
41
-
42
- - First idle frame works as a static reduced-motion pet.
43
- - The `idle` row should be calm and low-distraction; reject it if it reads as waving, walking, running, jumping, talking, working, reviewing, reacting dramatically, changing props, or making large pose/silhouette changes.
44
- - No important detail is too small to read.
45
- - No frame is clipped by the cell.
46
- - Failed/review/waiting states are distinct from ordinary idle.
47
- - Contact sheets must show whole sprite poses inside cells, not cropped tiles from a larger reference image.
48
- - Contact sheets must not be accepted if every used frame is just the reference image with small geometric transforms.
49
- - Used cells must not have white or opaque rectangular backgrounds unless the pet intentionally fills the whole cell and the user accepts that tradeoff.
50
- - The chroma key must be visually absent from the character. If extraction removes character regions, choose a different key and regenerate the affected base/rows.
51
- - Contact sheets must not show edge slivers or partial neighboring sprites inside cells.
52
- - Contact sheets must not show darker/lighter versions of the chroma key as shadows, dust, smears, glows, landing marks, or motion effects. These are background extraction failures and should trigger row repair.
53
- - If `qa/review.json` reports edge pixels, sparse frames, size outliers, or slot-extraction fallback, inspect the row visually and repair it when the issue is visible.
54
- - If `qa/review.json` reports chroma-adjacent non-transparent pixels, repair the row unless those pixels are an intentional character color and the selected key was manually accepted.
55
- - If preview GIFs show size popping even though the generated strip itself had stable scale and placement, rerun extraction with `stable-slots` before regenerating the row.
56
- - If previews show wrong facing direction, reversed cadence, non-alternating gait, or an effectively static idle loop, repair or regenerate the affected row.
57
-
58
- ## Repair Policy
59
-
60
- Repair the smallest failing scope first:
61
-
62
- 1. Single bad frame.
63
- 2. One row.
64
- 3. Full atlas regeneration only when identity or layout is broadly broken.
65
-
66
- The normal production path should regenerate only the affected row and copy the selected replacement into the same decoded output path unless the base character is wrong.
1
+ # QA Rubric
2
+
3
+ Do not accept an atlas until all checks pass.
4
+
5
+ ## Geometry
6
+
7
+ - Exact `1536x1872` dimensions.
8
+ - 8 columns x 9 rows.
9
+ - Each frame fits inside its `192x208` cell.
10
+ - Unused cells are transparent.
11
+ - Fully transparent atlas pixels do not retain non-zero RGB residue after export.
12
+ - `qa/review.json` has no errors.
13
+ - `frames/frames-manifest.json` records component extraction for production rows unless `stable-slots` was intentionally chosen to preserve row-level playback stability after visual inspection.
14
+
15
+ ## Character Consistency
16
+
17
+ - Same silhouette and proportions across every row.
18
+ - Same face and expression language.
19
+ - Same style, material, palette, lighting, and prop design.
20
+ - No frame introduces a new unintended character or object.
21
+
22
+ ## Pet-Safe Style
23
+
24
+ - Art reads as a Codex app pet, not a scene, app icon, logo sheet, or standalone illustration.
25
+ - Silhouette is compact and clear enough to read inside a `192x208` cell.
26
+ - The chosen style is consistent across every row, including edge treatment, material, lighting, and palette.
27
+ - Pixel, plush, clay, sticker, flat vector, 3D toy, painterly mascot, ink, and brand-inspired styles are all acceptable when readable at pet size.
28
+ - No tiny accessories, texture detail, logo detail, or text that disappears or becomes noisy at pet size.
29
+
30
+ ## Animation Completeness
31
+
32
+ - Each row uses the exact expected number of frames.
33
+ - The first and last frames can loop without an obvious pop.
34
+ - Directional rows read as the intended direction.
35
+ - Mirrored directional rows preserve temporal frame order rather than reversing the cadence.
36
+ - State-specific actions are recognizable at pet size.
37
+ - Poses are generated animation variants, not repeated copies of the same source image.
38
+ - Preview GIFs do not show unintended size popping, extraction-induced baseline jumps, or wrong directional facing.
39
+
40
+ ## App Fitness
41
+
42
+ - First idle frame works as a static reduced-motion pet.
43
+ - The `idle` row should be calm and low-distraction; reject it if it reads as waving, walking, running, jumping, talking, working, reviewing, reacting dramatically, changing props, or making large pose/silhouette changes.
44
+ - No important detail is too small to read.
45
+ - No frame is clipped by the cell.
46
+ - Failed/review/waiting states are distinct from ordinary idle.
47
+ - Contact sheets must show whole sprite poses inside cells, not cropped tiles from a larger reference image.
48
+ - Contact sheets must not be accepted if every used frame is just the reference image with small geometric transforms.
49
+ - Used cells must not have white or opaque rectangular backgrounds unless the pet intentionally fills the whole cell and the user accepts that tradeoff.
50
+ - The chroma key must be visually absent from the character. If extraction removes character regions, choose a different key and regenerate the affected base/rows.
51
+ - Contact sheets must not show edge slivers or partial neighboring sprites inside cells.
52
+ - Contact sheets must not show darker/lighter versions of the chroma key as shadows, dust, smears, glows, landing marks, or motion effects. These are background extraction failures and should trigger row repair.
53
+ - If `qa/review.json` reports edge pixels, sparse frames, size outliers, or slot-extraction fallback, inspect the row visually and repair it when the issue is visible.
54
+ - If `qa/review.json` reports chroma-adjacent non-transparent pixels, repair the row unless those pixels are an intentional character color and the selected key was manually accepted.
55
+ - If preview GIFs show size popping even though the generated strip itself had stable scale and placement, rerun extraction with `stable-slots` before regenerating the row.
56
+ - If previews show wrong facing direction, reversed cadence, non-alternating gait, or an effectively static idle loop, repair or regenerate the affected row.
57
+
58
+ ## Repair Policy
59
+
60
+ Repair the smallest failing scope first:
61
+
62
+ 1. Single bad frame.
63
+ 2. One row.
64
+ 3. Full atlas regeneration only when identity or layout is broadly broken.
65
+
66
+ The normal production path should regenerate only the affected row and copy the selected replacement into the same decoded output path unless the base character is wrong.
@@ -1,169 +1,169 @@
1
- #!/usr/bin/env python3
2
- """Compose or normalize a Codex pet spritesheet atlas."""
3
-
4
- from __future__ import annotations
5
-
6
- import argparse
7
- from pathlib import Path
8
-
9
- from PIL import Image
10
-
11
- COLUMNS = 8
12
- ROWS = 9
13
- CELL_WIDTH = 192
14
- CELL_HEIGHT = 208
15
- ATLAS_WIDTH = COLUMNS * CELL_WIDTH
16
- ATLAS_HEIGHT = ROWS * CELL_HEIGHT
17
- ATLAS_ASPECT_RATIO = ATLAS_WIDTH / ATLAS_HEIGHT
18
- ROW_SPECS = [
19
- ("idle", 0, 6),
20
- ("running-right", 1, 8),
21
- ("running-left", 2, 8),
22
- ("waving", 3, 4),
23
- ("jumping", 4, 5),
24
- ("failed", 5, 8),
25
- ("waiting", 6, 6),
26
- ("running", 7, 6),
27
- ("review", 8, 6),
28
- ]
29
- IMAGE_SUFFIXES = {".png", ".webp", ".jpg", ".jpeg"}
30
-
31
-
32
- def image_files(path: Path) -> list[Path]:
33
- return sorted(p for p in path.iterdir() if p.suffix.lower() in IMAGE_SUFFIXES)
34
-
35
-
36
- def find_row_frames(root: Path, state: str, row_index: int) -> list[Path]:
37
- candidates = [
38
- root / state,
39
- root / f"row-{row_index}",
40
- root / f"row{row_index}",
41
- root / f"{row_index}-{state}",
42
- ]
43
- for candidate in candidates:
44
- if candidate.is_dir():
45
- files = image_files(candidate)
46
- if files:
47
- return files
48
- globs = [
49
- f"{state}_*",
50
- f"{state}-*",
51
- f"row{row_index}_*",
52
- f"row-{row_index}-*",
53
- ]
54
- files: list[Path] = []
55
- for pattern in globs:
56
- files.extend(p for p in root.glob(pattern) if p.suffix.lower() in IMAGE_SUFFIXES)
57
- return sorted(set(files))
58
-
59
-
60
- def paste_centered(atlas: Image.Image, source: Image.Image, row: int, column: int) -> None:
61
- frame = source.convert("RGBA")
62
- if frame.size != (CELL_WIDTH, CELL_HEIGHT):
63
- frame.thumbnail((CELL_WIDTH, CELL_HEIGHT), Image.Resampling.LANCZOS)
64
- left = column * CELL_WIDTH + (CELL_WIDTH - frame.width) // 2
65
- top = row * CELL_HEIGHT + (CELL_HEIGHT - frame.height) // 2
66
- atlas.alpha_composite(frame, (left, top))
67
-
68
-
69
- def compose_from_source_atlas(path: Path, resize_source: bool) -> Image.Image:
70
- with Image.open(path) as opened:
71
- source = opened.convert("RGBA")
72
- if source.size != (ATLAS_WIDTH, ATLAS_HEIGHT):
73
- if not resize_source:
74
- raise SystemExit(
75
- f"source atlas must be {ATLAS_WIDTH}x{ATLAS_HEIGHT}; got {source.width}x{source.height}"
76
- )
77
- source_ratio = source.width / source.height
78
- if abs(source_ratio - ATLAS_ASPECT_RATIO) > 0.02:
79
- raise SystemExit(
80
- "refusing to resize source atlas because its aspect ratio does not match "
81
- f"the Codex atlas ratio {ATLAS_ASPECT_RATIO:.3f}; got {source_ratio:.3f}. "
82
- "Generate exact atlas dimensions or use --frames-root."
83
- )
84
- source = source.resize((ATLAS_WIDTH, ATLAS_HEIGHT), Image.Resampling.LANCZOS)
85
-
86
- atlas = Image.new("RGBA", (ATLAS_WIDTH, ATLAS_HEIGHT), (0, 0, 0, 0))
87
- for _state, row, frame_count in ROW_SPECS:
88
- for column in range(frame_count):
89
- left = column * CELL_WIDTH
90
- top = row * CELL_HEIGHT
91
- cell = source.crop((left, top, left + CELL_WIDTH, top + CELL_HEIGHT))
92
- atlas.alpha_composite(cell, (left, top))
93
- return atlas
94
-
95
-
96
- def compose_from_frames(root: Path) -> Image.Image:
97
- atlas = Image.new("RGBA", (ATLAS_WIDTH, ATLAS_HEIGHT), (0, 0, 0, 0))
98
- for state, row, frame_count in ROW_SPECS:
99
- files = find_row_frames(root, state, row)
100
- if len(files) < frame_count:
101
- raise SystemExit(
102
- f"{state} row needs {frame_count} frames, found {len(files)} under {root}"
103
- )
104
- for column, frame_path in enumerate(files[:frame_count]):
105
- with Image.open(frame_path) as frame:
106
- paste_centered(atlas, frame, row, column)
107
- return atlas
108
-
109
-
110
- def clear_transparent_rgb(image: Image.Image) -> Image.Image:
111
- rgba = image.convert("RGBA")
112
- data = bytearray(rgba.tobytes())
113
- for index in range(0, len(data), 4):
114
- if data[index + 3] == 0:
115
- data[index] = 0
116
- data[index + 1] = 0
117
- data[index + 2] = 0
118
- return Image.frombytes("RGBA", rgba.size, bytes(data))
119
-
120
-
121
- def save_outputs(atlas: Image.Image, output: Path, webp_output: Path | None) -> None:
122
- atlas = clear_transparent_rgb(atlas)
123
- output.parent.mkdir(parents=True, exist_ok=True)
124
- atlas.save(output)
125
- if webp_output is not None:
126
- webp_output.parent.mkdir(parents=True, exist_ok=True)
127
- atlas.save(
128
- webp_output,
129
- format="WEBP",
130
- lossless=True,
131
- quality=100,
132
- method=6,
133
- exact=True,
134
- )
135
-
136
-
137
- def main() -> None:
138
- parser = argparse.ArgumentParser(description=__doc__)
139
- source = parser.add_mutually_exclusive_group(required=True)
140
- source.add_argument("--source-atlas")
141
- source.add_argument("--frames-root")
142
- parser.add_argument("--output", required=True)
143
- parser.add_argument("--webp-output")
144
- parser.add_argument(
145
- "--resize-source",
146
- action="store_true",
147
- help="Resize a lower-resolution source atlas only when it already has the Codex atlas aspect ratio.",
148
- )
149
- args = parser.parse_args()
150
-
151
- if args.source_atlas:
152
- atlas = compose_from_source_atlas(
153
- Path(args.source_atlas).expanduser().resolve(), args.resize_source
154
- )
155
- else:
156
- atlas = compose_from_frames(Path(args.frames_root).expanduser().resolve())
157
-
158
- save_outputs(
159
- atlas,
160
- Path(args.output).expanduser().resolve(),
161
- Path(args.webp_output).expanduser().resolve() if args.webp_output else None,
162
- )
163
- print(f"wrote {Path(args.output).expanduser().resolve()}")
164
- if args.webp_output:
165
- print(f"wrote {Path(args.webp_output).expanduser().resolve()}")
166
-
167
-
168
- if __name__ == "__main__":
169
- main()
1
+ #!/usr/bin/env python3
2
+ """Compose or normalize a Codex pet spritesheet atlas."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ from pathlib import Path
8
+
9
+ from PIL import Image
10
+
11
+ COLUMNS = 8
12
+ ROWS = 9
13
+ CELL_WIDTH = 192
14
+ CELL_HEIGHT = 208
15
+ ATLAS_WIDTH = COLUMNS * CELL_WIDTH
16
+ ATLAS_HEIGHT = ROWS * CELL_HEIGHT
17
+ ATLAS_ASPECT_RATIO = ATLAS_WIDTH / ATLAS_HEIGHT
18
+ ROW_SPECS = [
19
+ ("idle", 0, 6),
20
+ ("running-right", 1, 8),
21
+ ("running-left", 2, 8),
22
+ ("waving", 3, 4),
23
+ ("jumping", 4, 5),
24
+ ("failed", 5, 8),
25
+ ("waiting", 6, 6),
26
+ ("running", 7, 6),
27
+ ("review", 8, 6),
28
+ ]
29
+ IMAGE_SUFFIXES = {".png", ".webp", ".jpg", ".jpeg"}
30
+
31
+
32
+ def image_files(path: Path) -> list[Path]:
33
+ return sorted(p for p in path.iterdir() if p.suffix.lower() in IMAGE_SUFFIXES)
34
+
35
+
36
+ def find_row_frames(root: Path, state: str, row_index: int) -> list[Path]:
37
+ candidates = [
38
+ root / state,
39
+ root / f"row-{row_index}",
40
+ root / f"row{row_index}",
41
+ root / f"{row_index}-{state}",
42
+ ]
43
+ for candidate in candidates:
44
+ if candidate.is_dir():
45
+ files = image_files(candidate)
46
+ if files:
47
+ return files
48
+ globs = [
49
+ f"{state}_*",
50
+ f"{state}-*",
51
+ f"row{row_index}_*",
52
+ f"row-{row_index}-*",
53
+ ]
54
+ files: list[Path] = []
55
+ for pattern in globs:
56
+ files.extend(p for p in root.glob(pattern) if p.suffix.lower() in IMAGE_SUFFIXES)
57
+ return sorted(set(files))
58
+
59
+
60
+ def paste_centered(atlas: Image.Image, source: Image.Image, row: int, column: int) -> None:
61
+ frame = source.convert("RGBA")
62
+ if frame.size != (CELL_WIDTH, CELL_HEIGHT):
63
+ frame.thumbnail((CELL_WIDTH, CELL_HEIGHT), Image.Resampling.LANCZOS)
64
+ left = column * CELL_WIDTH + (CELL_WIDTH - frame.width) // 2
65
+ top = row * CELL_HEIGHT + (CELL_HEIGHT - frame.height) // 2
66
+ atlas.alpha_composite(frame, (left, top))
67
+
68
+
69
+ def compose_from_source_atlas(path: Path, resize_source: bool) -> Image.Image:
70
+ with Image.open(path) as opened:
71
+ source = opened.convert("RGBA")
72
+ if source.size != (ATLAS_WIDTH, ATLAS_HEIGHT):
73
+ if not resize_source:
74
+ raise SystemExit(
75
+ f"source atlas must be {ATLAS_WIDTH}x{ATLAS_HEIGHT}; got {source.width}x{source.height}"
76
+ )
77
+ source_ratio = source.width / source.height
78
+ if abs(source_ratio - ATLAS_ASPECT_RATIO) > 0.02:
79
+ raise SystemExit(
80
+ "refusing to resize source atlas because its aspect ratio does not match "
81
+ f"the Codex atlas ratio {ATLAS_ASPECT_RATIO:.3f}; got {source_ratio:.3f}. "
82
+ "Generate exact atlas dimensions or use --frames-root."
83
+ )
84
+ source = source.resize((ATLAS_WIDTH, ATLAS_HEIGHT), Image.Resampling.LANCZOS)
85
+
86
+ atlas = Image.new("RGBA", (ATLAS_WIDTH, ATLAS_HEIGHT), (0, 0, 0, 0))
87
+ for _state, row, frame_count in ROW_SPECS:
88
+ for column in range(frame_count):
89
+ left = column * CELL_WIDTH
90
+ top = row * CELL_HEIGHT
91
+ cell = source.crop((left, top, left + CELL_WIDTH, top + CELL_HEIGHT))
92
+ atlas.alpha_composite(cell, (left, top))
93
+ return atlas
94
+
95
+
96
+ def compose_from_frames(root: Path) -> Image.Image:
97
+ atlas = Image.new("RGBA", (ATLAS_WIDTH, ATLAS_HEIGHT), (0, 0, 0, 0))
98
+ for state, row, frame_count in ROW_SPECS:
99
+ files = find_row_frames(root, state, row)
100
+ if len(files) < frame_count:
101
+ raise SystemExit(
102
+ f"{state} row needs {frame_count} frames, found {len(files)} under {root}"
103
+ )
104
+ for column, frame_path in enumerate(files[:frame_count]):
105
+ with Image.open(frame_path) as frame:
106
+ paste_centered(atlas, frame, row, column)
107
+ return atlas
108
+
109
+
110
+ def clear_transparent_rgb(image: Image.Image) -> Image.Image:
111
+ rgba = image.convert("RGBA")
112
+ data = bytearray(rgba.tobytes())
113
+ for index in range(0, len(data), 4):
114
+ if data[index + 3] == 0:
115
+ data[index] = 0
116
+ data[index + 1] = 0
117
+ data[index + 2] = 0
118
+ return Image.frombytes("RGBA", rgba.size, bytes(data))
119
+
120
+
121
+ def save_outputs(atlas: Image.Image, output: Path, webp_output: Path | None) -> None:
122
+ atlas = clear_transparent_rgb(atlas)
123
+ output.parent.mkdir(parents=True, exist_ok=True)
124
+ atlas.save(output)
125
+ if webp_output is not None:
126
+ webp_output.parent.mkdir(parents=True, exist_ok=True)
127
+ atlas.save(
128
+ webp_output,
129
+ format="WEBP",
130
+ lossless=True,
131
+ quality=100,
132
+ method=6,
133
+ exact=True,
134
+ )
135
+
136
+
137
+ def main() -> None:
138
+ parser = argparse.ArgumentParser(description=__doc__)
139
+ source = parser.add_mutually_exclusive_group(required=True)
140
+ source.add_argument("--source-atlas")
141
+ source.add_argument("--frames-root")
142
+ parser.add_argument("--output", required=True)
143
+ parser.add_argument("--webp-output")
144
+ parser.add_argument(
145
+ "--resize-source",
146
+ action="store_true",
147
+ help="Resize a lower-resolution source atlas only when it already has the Codex atlas aspect ratio.",
148
+ )
149
+ args = parser.parse_args()
150
+
151
+ if args.source_atlas:
152
+ atlas = compose_from_source_atlas(
153
+ Path(args.source_atlas).expanduser().resolve(), args.resize_source
154
+ )
155
+ else:
156
+ atlas = compose_from_frames(Path(args.frames_root).expanduser().resolve())
157
+
158
+ save_outputs(
159
+ atlas,
160
+ Path(args.output).expanduser().resolve(),
161
+ Path(args.webp_output).expanduser().resolve() if args.webp_output else None,
162
+ )
163
+ print(f"wrote {Path(args.output).expanduser().resolve()}")
164
+ if args.webp_output:
165
+ print(f"wrote {Path(args.webp_output).expanduser().resolve()}")
166
+
167
+
168
+ if __name__ == "__main__":
169
+ main()