@pixel-studio/core 0.0.0-stage → 0.2.0-alpha.3

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 (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +201 -2
  3. package/bin/pixel.mjs +326 -0
  4. package/docs/DESIGN.md +118 -0
  5. package/docs/README.md +20 -0
  6. package/docs/SPEC.md +469 -0
  7. package/docs/api.md +1898 -0
  8. package/docs/architecture.md +859 -0
  9. package/docs/cli.md +607 -0
  10. package/docs/figures.md +477 -0
  11. package/docs/getting-started.md +88 -0
  12. package/docs/performance.md +301 -0
  13. package/docs/playground.md +134 -0
  14. package/docs/runtime.md +724 -0
  15. package/docs/stage.md +461 -0
  16. package/examples/fox.json +85 -0
  17. package/examples/goose-base.json +94 -0
  18. package/examples/goose-greylag.json +192 -0
  19. package/examples/goose-kiddie.json +68 -0
  20. package/examples/goose-phreak.json +69 -0
  21. package/examples/goose-root.json +136 -0
  22. package/examples/goose-sudo.json +78 -0
  23. package/examples/moss.json +1715 -0
  24. package/examples/pip.json +74 -0
  25. package/examples/plugins/extras.mjs +53 -0
  26. package/examples/plugins/starfish.json +21 -0
  27. package/examples/robot.json +81 -0
  28. package/examples/slime.json +46 -0
  29. package/figures/blob.json +19 -0
  30. package/figures/chibi.json +43 -0
  31. package/figures/dog.json +60 -0
  32. package/figures/goose-front.json +56 -0
  33. package/figures/goose.json +70 -0
  34. package/figures/human.json +66 -0
  35. package/package.json +56 -4
  36. package/references/CREDITS.md +56 -0
  37. package/references/README.md +92 -0
  38. package/references/dog.json +167 -0
  39. package/references/goose-greylag.json +23 -0
  40. package/references/goose.json +95 -0
  41. package/references/human.json +281 -0
  42. package/references/measurements/bird-adjutant-pl774.json +597 -0
  43. package/references/measurements/bird-cockatoo-pl758.json +746 -0
  44. package/references/measurements/bird-ostrich-pl772.json +503 -0
  45. package/references/measurements/bird-pigeon-pl755.json +424 -0
  46. package/references/measurements/bird-pigeon-pl756.json +433 -0
  47. package/references/measurements/bird-pigeon-pl757.json +460 -0
  48. package/references/measurements/bird-vulture-pl765.json +800 -0
  49. package/references/measurements/bird-vulture-pl768.json +329 -0
  50. package/references/measurements/dog-pl706.json +196 -0
  51. package/references/measurements/dog-pl707.json +234 -0
  52. package/references/measurements/dog-pl708.json +262 -0
  53. package/references/measurements/dog-pl709.json +347 -0
  54. package/references/measurements/dog-pl710.json +325 -0
  55. package/references/measurements/human-pl001.json +1079 -0
  56. package/references/measurements/human-pl006.json +365 -0
  57. package/references/measurements/human-pl013.json +283 -0
  58. package/references/measurements/human-pl060.json +977 -0
  59. package/references/measurements/human-pl062.json +1183 -0
  60. package/references/measurements/human-pl064.json +1133 -0
  61. package/references/measurements/human-pl088.json +887 -0
  62. package/references/measurements/human-pl109.json +1037 -0
  63. package/references/measurements/human-pl111.json +365 -0
  64. package/references/measurements/human-pl152.json +681 -0
  65. package/references/measurements/human-pl159.json +700 -0
  66. package/references/measurements/human-pl161.json +660 -0
  67. package/references/measurements/human-pl162.json +695 -0
  68. package/references/measurements/human-pl236.json +595 -0
  69. package/references/measurements/human-pl249.json +556 -0
  70. package/references/sources.json +794 -0
  71. package/src/core/animate.js +172 -0
  72. package/src/core/ascii.js +22 -0
  73. package/src/core/bundle.js +247 -0
  74. package/src/core/color.js +112 -0
  75. package/src/core/export.js +58 -0
  76. package/src/core/extend.js +161 -0
  77. package/src/core/figure.js +340 -0
  78. package/src/core/image.js +61 -0
  79. package/src/core/index.js +19 -0
  80. package/src/core/internal.js +10 -0
  81. package/src/core/lint.js +56 -0
  82. package/src/core/mix.js +41 -0
  83. package/src/core/motion.js +521 -0
  84. package/src/core/plugins.js +96 -0
  85. package/src/core/png.js +113 -0
  86. package/src/core/render.js +346 -0
  87. package/src/core/rig.js +169 -0
  88. package/src/core/shapes.js +119 -0
  89. package/src/core/spec.js +457 -0
  90. package/src/core/textures.js +60 -0
  91. package/src/node/png.js +9 -0
  92. package/src/runtime.js +3 -0
  93. package/src/stage.js +2 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Pavel Pascari
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,202 @@
1
- # Temporary Holding Version
1
+ # Pixel Studio
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Agents describe characters; the engine draws them as pixel art at every level of detail; websites play them with one tag.**
4
+
5
+ ```
6
+ agent ──JSON rig──▶ engine (SDF raster + pixel-art shader) ──▶ bundle (16/32/64 px sheets) ──▶ <pixel-sprite>
7
+ ▲ │
8
+ └──────────── preview PNG / ASCII / validation errors ◀──┘
9
+ ```
10
+
11
+ Plain ES modules, no build step. Node ≥ 20 for the CLI; any current browser for the runtime. MIT licensed.
12
+ Two packages, always released with the same version:
13
+
14
+ - **`@pixel-studio/core`** (this one): the engine, the `pixel` CLI, the figure library, examples and docs. Its only
15
+ dependency is the runtime.
16
+ - **[`@pixel-studio/runtime`](https://www.npmjs.com/package/@pixel-studio/runtime)**: `<pixel-sprite>` and
17
+ `<pixel-stage>`, the web components that play finished sprites. No dependencies; a site that only shows sprites
18
+ installs just this.
19
+
20
+ Docs and live demos: **[pixel-studio.sh](https://pixel-studio.sh)**.
21
+
22
+ > **Status: alpha.** The engine, CLI and web components work and are tested, and every page of pixel-studio.sh runs
23
+ > on them. The spec and bundle formats may still change before 1.0; each change is listed in the
24
+ > [changelog](https://pixel-studio.sh/changelog/).
25
+
26
+ ## Five minutes to a goose on your page
27
+
28
+ ```bash
29
+ npm i @pixel-studio/core # brings @pixel-studio/runtime, nothing else
30
+ ```
31
+
32
+ Make a character by changing an example (`my-goose.json`):
33
+
34
+ ```json
35
+ { "extends": "./node_modules/@pixel-studio/core/examples/goose-base.json",
36
+ "name": "Marigold",
37
+ "materials": { "feather": { "color": "#e8b04a" }, "beak": { "color": "#d94b32" } } }
38
+ ```
39
+
40
+ ```bash
41
+ npx pixel validate my-goose.json # errors with JSON paths and did-you-mean
42
+ npx pixel preview my-goose.json --out my-goose.png # every animation at 16, 32 and 64 px
43
+ npx pixel bundle my-goose.json --out my-goose.bundle.json
44
+ ```
45
+
46
+ ```html
47
+ <script type="module" src="node_modules/@pixel-studio/runtime/src/pixel-sprite.js"></script>
48
+ <pixel-sprite src="my-goose.bundle.json" anim="idle" size="128" hover-anim="waddle" click-anim="honk"></pixel-sprite>
49
+ ```
50
+
51
+ The full walk-through is [docs/getting-started.md](docs/getting-started.md).
52
+
53
+ Characters can also live on the page itself: walk along cards, jump between them, climb their sides, sit on edges
54
+ and hide behind things ([docs/stage.md](docs/stage.md)):
55
+
56
+ ```html
57
+ <script type="module" src="pixel-stage.js"></script>
58
+ <article class="card" data-pixel-surface data-pixel-climbable>…</article>
59
+ <pixel-stage><pixel-actor src="goose.bundle.json" size="64"></pixel-actor></pixel-stage>
60
+ ```
61
+
62
+ ## The CLI: the agent's hands and eyes
63
+
64
+ ```bash
65
+ npx pixel validate examples/fox.json
66
+ npx pixel preview examples/fox.json --out fox.png # every animation × 16/32/64 px
67
+ npx pixel ascii examples/fox.json --res 24 --anim walk # text view for agents without vision
68
+ npx pixel where examples/goose-root.json --anim honk # world positions of pivots, per frame
69
+ npx pixel resolve examples/goose-sudo.json # a variant merged with its base
70
+ npx pixel bundle examples/fox.json --out fox.bundle.json
71
+ npx pixel export examples/fox.json --res 32 --out game/ # PNG + Aseprite JSON (Phaser, PixiJS)
72
+ npx pixel figures # the skeleton library
73
+ npx pixel brief # the agent brief (system prompt)
74
+ ```
75
+
76
+ (In a clone of the repository, run `node bin/pixel.mjs` from `packages/pixel-studio/` instead of `npx pixel`, and
77
+ the example paths work as written. Working on Pixel Studio itself: see
78
+ [CONTRIBUTING.md](../../CONTRIBUTING.md).)
79
+
80
+ ## Documentation
81
+
82
+ Start with [docs/getting-started.md](docs/getting-started.md), or read everything on
83
+ [pixel-studio.sh](https://pixel-studio.sh/docs/). The reference docs, also in this package's `docs/`:
84
+
85
+ | doc | covers |
86
+ |---|---|
87
+ | [docs/getting-started.md](docs/getting-started.md) | Install, write a character, preview, bundle, put it on a page. |
88
+ | [docs/SPEC.md](docs/SPEC.md) | The character spec. It doubles as the agent brief. |
89
+ | [docs/figures.md](docs/figures.md) | Figures, motion models, follow-through, writing a new figure. |
90
+ | [docs/runtime.md](docs/runtime.md) | `<pixel-sprite>`, the bundle format, events, attachment points, state machines, skins, moving sprites on a page. |
91
+ | [docs/stage.md](docs/stage.md) | `<pixel-stage>`: characters that walk, jump, climb, sit and hide on a real page. |
92
+ | [docs/performance.md](docs/performance.md) | What characters cost a page: sizes, load impact, time per frame, memory, measured. |
93
+ | [docs/cli.md](docs/cli.md) | Every CLI command and flag. |
94
+ | [docs/api.md](docs/api.md) | The JavaScript API. |
95
+ | [docs/playground.md](docs/playground.md) | The playground page: a character set up entirely by its URL, for people and browser agents. |
96
+ | [docs/architecture.md](docs/architecture.md) | How the engine works inside, and how to extend it. |
97
+ | [docs/DESIGN.md](docs/DESIGN.md) | Why it is designed this way. |
98
+
99
+ ## What's in this package
100
+
101
+ | Path | What |
102
+ |---|---|
103
+ | `src/core/` | The isomorphic engine: spec validation (JSON paths + did-you-mean), figures and motion models, rig maths and IK, variants, SDF shapes, the rasterizer and pixel-art shader (hue-shifted ramps, lighting, textures, dither, outlines, inner lines, contact shadows), sheets, bundles, export, ASCII, plug-ins. |
104
+ | `src/node/png.js` | The Node PNG encoder the CLI uses. |
105
+ | `src/runtime.js`, `src/stage.js` | `@pixel-studio/core/runtime` and `@pixel-studio/core/stage`: re-export [`@pixel-studio/runtime`](https://www.npmjs.com/package/@pixel-studio/runtime), the web components. |
106
+ | `bin/pixel.mjs` | The CLI. `--plugin` loads plug-ins (shapes, textures, motion models; see `examples/plugins/`). |
107
+ | `figures/` | The **figure library**: `goose` (and `goose-front` for its front and back views), `human`, `dog`, `chibi` (front-facing), `blob` (soft body). |
108
+ | `examples/` | Characters: `goose-base` and its variants `goose-root`, `-sudo`, `-phreak`, `-kiddie`, `-greylag`; `pip`; `fox`, `slime`, `robot` (written by a separate agent that only had `SPEC.md` and the CLI); `moss`. |
109
+ | `references/` | Where motion data comes from: every source cited, every measured value and frame logged ([references/README.md](references/README.md), credits in [references/CREDITS.md](references/CREDITS.md)). |
110
+ | `docs/` | The reference docs above. |
111
+
112
+ The studio (live JSON editor, onion skin, all detail levels at once, an **Agent** tab), the figure viewer, the
113
+ playground and the demo pages live in the [repository](https://github.com/pavelpascari/pixel-studio) and run on
114
+ [pixel-studio.sh](https://pixel-studio.sh/gallery/).
115
+
116
+ ## Levels of detail and texture
117
+
118
+ The same spec renders at any resolution. The detail tier changes how it is drawn:
119
+
120
+ | tier | default at | tones | texture | dither | outline | extras |
121
+ |---|---|---|---|---|---|---|
122
+ | 1 icon | ≤ 20 px | 2 | off | off | dark | brighter ambient, only `minDetail: 1` shapes |
123
+ | 2 sprite | 21–40 px | 3 | 60% | off | selective | contact shadows |
124
+ | 3 portrait | > 40 px | 5 | 100% | on | selective | inner lines between overlapping parts |
125
+
126
+ Textures: `noise fur scales stripes checker cloth bricks spots metal`. They are evaluated in each part's local space, so they stick to moving limbs. Materials can also carry `shine`, `flat`, and `outline: false`. Every knob can be overridden per spec (`style`) or live in the studio.
127
+
128
+ ## The agent loop, tested
129
+
130
+ To check the premise, I gave a fresh agent only `docs/SPEC.md` and the CLI and asked for three characters. It produced `fox`, `slime` and `robot` through about three preview-and-revise rounds each. Its friction report drove these engine fixes:
131
+
132
+ - Eyes and other detail parts cast contact shadows that looked like tears. Fixed: flat and `outline:false` materials no longer cast them.
133
+ - Seams appeared where same-material shapes overlapped. Fixed: they are now lit as one surface (union SDF).
134
+ - Typos like `minDetal` were ignored silently. Fixed: unknown keys produce warnings with did-you-mean.
135
+ - `sx`/`sy` waves centred on 0. Fixed: they now oscillate around 1.
136
+ - The icon tier was too dark. Fixed: it gets an ambient boost.
137
+ - The brief was missing several things: a style-key table, pivot = scale origin, pixel-grid alignment for tiny features, and no small head rotations.
138
+
139
+ Still open: tiny features are at the mercy of the pixel grid (at 16 px the fox's four legs merge), and there is no
140
+ alpha or glow.
141
+
142
+ ## Authoring helpers (added while building the goose flock)
143
+
144
+ Each one came from a specific problem building the geese:
145
+
146
+ | problem | feature |
147
+ |---|---|
148
+ | Four geese were four copied 700-line files that drifted apart | **`extends` variants**: a base rig plus about 45 lines of differences per goose (patch/add/remove parts, merge materials and animations, `materialMap`) |
149
+ | Getting the beak onto the keyboard meant guessing three joint angles per frame | **`reach` constraints**: name the chain, the tip point and an animatable target (optionally the head's `aim`); the engine solves the angles each frame |
150
+ | A honk pushed the head off-canvas and I only noticed in previews | **Bounds warnings**: "`head` goes 8.2 units past the right edge in frames 2–7" from `validate`, the CLI and the studio status bar |
151
+ | Unreachable targets fail silently | **Reach warnings**: by how much, which frames, and what to relax |
152
+ | Hard to tell where a joint actually is mid-animation | `pixel where` on the CLI and the **rig** toggle in the studio (pivots, bones, reach targets turning red when missed) |
153
+
154
+ ## Figures and motion models
155
+
156
+ Skeletons are dots and lines with realistic motion models. A character picks a figure (`"figure": "goose"`), dresses its bones with shapes, and gets its motions:
157
+
158
+ - **gait** (walk, run, trot, sneak). Feet are planted with IK and swing on real paths. The hips rise and fall with the legs, a four-legged figure's back pitches, and the head keeps its gaze steady. Each gait exports a `speed`, so a page that moves the sprite at that speed gets no foot sliding. The flock uses this.
159
+ - **idle**: breathing and weight shifting over planted feet.
160
+ - **pose**: your keyframes drive the body and the feet stay planted.
161
+ - **hop**: a gravity arc with volume-preserving squash and stretch, a lean into the jump, and a ground shadow that shrinks in the air.
162
+ - **Front view** (`chibi`): walking toward the viewer, the hips shift over the standing foot and lifted legs foreshorten.
163
+ - **Follow-through**: `"follow"` springs make tails, ears, hoods and straps lag, overshoot and settle.
164
+ - **For life on a page**: `jump` (crouch, launch, tuck, land), `climb` (feet holding a wall, with a `speedY`), `fall`,
165
+ `sit` on an edge, and `duck`/`peek` presets. Motions report events (`footstep`, `launch`, `land`), and figures define
166
+ attachment points (`beak`, `head`, hands) and the foot line, all baked into bundles.
167
+
168
+ Author tracks layer on top of the motion. **Every example is dressed on a figure:** the geese on `goose`, Ember on `dog`
169
+ (fitted: shorter neck, bushy tail), Pip and Bolt on `chibi` (Bolt fitted to its boxier proportions, with a springy antenna),
170
+ and Gloop on `blob`. phreak's sneak is the `sneak` preset plus a floppy disk, and honks, headbangs and waves are `pose` motions.
171
+
172
+ ```bash
173
+ npx pixel figures # list the library
174
+ npx pixel preview dog # a bare figure: its skeleton, every motion
175
+ ```
176
+
177
+ ## Agent tab (Claude in the browser)
178
+
179
+ In the studio, in the [repository](https://github.com/pavelpascari/pixel-studio) (`npm run studio`).
180
+
181
+ Describe a character, then **Generate**: Claude writes the spec, the studio validates it, and any validation errors go back to Claude for a fix. **Look & refine** renders a contact sheet (16/32/64 × every animation), sends the image back, and asks Claude to critique it like a pixel artist and return a revised spec.
182
+
183
+ - Your API key is stored only in `localStorage`. Requests go directly from the browser to the API (`dangerouslyAllowBrowser`), which is fine for a local prototype but not for a hosted app. A hosted version needs a small server-side proxy.
184
+ - The default model is `claude-opus-5-5`, with adaptive thinking at effort `medium`. The server-side fallback beta is on (`fallbacks: "default"`), so a safety-classifier refusal is routed to a fallback model instead of failing. To turn it off, remove `betas`/`fallbacks` in `studio/agent.js`.
185
+ - The SDK loads from esm.sh on first use, so the rest of the studio works offline.
186
+ - **This path has not been run end-to-end yet; it needs your key.** The extraction and validation-repair logic is exercised; the live API call isn't.
187
+
188
+ ## Known limitations and out of scope
189
+
190
+ - The spec and bundle formats are not frozen until 1.0.
191
+ - Parts are rigid: no mesh deformation, no pixel-level touch-up layers, no palette constraints across characters.
192
+ - No GIF/APNG export; PNG sheets, Aseprite JSON and bundles only.
193
+ - The studio's Agent tab is a local prototype (see above).
194
+
195
+ See [docs/DESIGN.md](docs/DESIGN.md) and the research notes in the repository's [docs/research/](../../docs/research/).
196
+
197
+ ## Contributing and license
198
+
199
+ See [CONTRIBUTING.md](../../CONTRIBUTING.md). Pixel Studio is released under the [MIT License](LICENSE).
200
+ Motion data comes only from public-domain and openly licensed sources (Muybridge's plates, published measurements);
201
+ each is credited in [references/CREDITS.md](references/CREDITS.md).
202
+ The studio's optional Agent tab loads the Anthropic SDK (MIT) from esm.sh at runtime; nothing third-party is bundled.
package/bin/pixel.mjs ADDED
@@ -0,0 +1,326 @@
1
+ #!/usr/bin/env node
2
+ // Pixel Studio CLI — the agent's hands and eyes.
3
+ //
4
+ // pixel validate <spec.json> check a spec, print errors with JSON paths
5
+ // pixel preview <spec.json> [--out p.png] [--res 16,32,64] [--cell 128] [--anim a,b]
6
+ // contact sheet: every animation (or those named) × every LOD tier
7
+ // pixel ascii <spec.json> [--res 24] [--anim idle] [--frame 0|all]
8
+ // a frame as text (for agents without vision)
9
+ // pixel render <spec.json> [--res 32] [--out dir] [--lod 1|2|3] [--tones n] [--texture 0..1] ...
10
+ // sprite sheet PNG + JSON metadata
11
+ // pixel export <spec.json> [--res 32] [--out dir] [--format aseprite]
12
+ // sheet PNG + Aseprite JSON (Phaser, PixiJS)
13
+ // pixel bundle <spec.json> [--res 16,32,64] [--views front,back|all] [--anims idle,walk|stage] [--external]
14
+ // [--out file.bundle.json] self-contained web bundle for <pixel-sprite> (all skins);
15
+ // side view only unless --views; --anims keeps only those
16
+ // animations (stage: what <pixel-stage> uses);
17
+ // --external writes the sheets as PNG files beside it
18
+ // pixel resolve <variant.json> [--out full.json] print a variant ("extends") merged with its base
19
+ // pixel where <spec.json> [--anim a] [--frame f] [--part id --point x,y]
20
+ // world positions of part pivots (or of a point on a part)
21
+ // pixel figures list the figure library (skeletons + motions)
22
+ // pixel preview goose any command takes a bare figure name instead of a spec
23
+ //
24
+ // --skin <name> (preview, ascii, render, export, where): use one of the spec's skins
25
+ // style flags (preview, ascii, render, export, bundle): --lod 1|2|3 --tones n --texture 0..1 --dither true|false
26
+ // --outline dark|selective|none --light deg --flip
27
+ // pixel brief print the agent brief (spec format docs)
28
+ // pixel help this text
29
+ //
30
+ // --plugin ./a.mjs,./b.mjs (any command): register plug-in shapes, textures and motion models first
31
+ // errors print as one line and exit 1; PIXEL_DEBUG=1 adds the stack trace
32
+ import { readFileSync, writeFileSync, mkdirSync, readdirSync } from 'node:fs';
33
+ import { basename, dirname, join, resolve } from 'node:path';
34
+ import { fileURLToPath, pathToFileURL } from 'node:url';
35
+ import {
36
+ validate, compile, renderSheet, renderAnimation, renderFrame, resolveStyle,
37
+ contactSheet, frameToAscii, buildBundle, exportSheet, usePlugin, registeredPlugins, DETAIL_NAMES, resolveSpec, checkBounds, MAX_RES,
38
+ } from '../src/core/index.js';
39
+ import { samplePose, worldMatrices } from '../src/core/internal.js';
40
+ import { encodePNG } from '../src/node/png.js';
41
+
42
+ const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
43
+
44
+ const BOOLEAN_FLAGS = new Set(['flip', 'external']); // never take the next argument as their value
45
+
46
+ function parseArgs(argv) {
47
+ const args = { _: [] };
48
+ for (let i = 0; i < argv.length; i++) {
49
+ const a = argv[i];
50
+ if (a.startsWith('--')) {
51
+ const eq = a.indexOf('='), k = eq < 0 ? a.slice(2) : a.slice(2, eq), v = eq < 0 ? undefined : a.slice(eq + 1);
52
+ args[k] = v ?? (!BOOLEAN_FLAGS.has(k) && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[++i] : true);
53
+ } else args._.push(a);
54
+ }
55
+ return args;
56
+ }
57
+
58
+ function readJSON(path) {
59
+ let text;
60
+ try { text = readFileSync(path, 'utf8'); } catch (e) { fail(`cannot read ${path}: ${e.message}`); }
61
+ try { return JSON.parse(text); } catch (e) { fail(`${path} is not valid JSON: ${e.message}`); }
62
+ }
63
+
64
+ /** Load a spec, resolve its "extends" chain (paths relative to the file that names them) and its "figure". */
65
+ async function loadSpec(path) {
66
+ if (!path) fail('missing <spec.json>');
67
+ // A bare figure name ("goose") previews that figure's skeleton.
68
+ const spec = !path.endsWith('.json') && figureNames().includes(path) ? { figure: path } : readJSON(path);
69
+ const absOf = new Map();
70
+ try {
71
+ return await resolveSpec(spec, {
72
+ loadRef: (ref, from) => {
73
+ const abs = resolve(dirname(from ? absOf.get(from) : resolve(path)), ref);
74
+ absOf.set(ref, abs);
75
+ return JSON.parse(readFileSync(abs, 'utf8'));
76
+ },
77
+ loadFigure: (name) => JSON.parse(readFileSync(join(ROOT, 'figures', `${name}.json`), 'utf8')),
78
+ warn: (p, m) => console.error(`warning ${p}: ${m}`),
79
+ });
80
+ } catch (e) { fail(`${path}: ${e.message}`); }
81
+ }
82
+ const figureNames = () => readdirSync(join(ROOT, 'figures')).filter((f) => f.endsWith('.json')).map((f) => f.slice(0, -5));
83
+
84
+ function printBounds(c, log = console.error) {
85
+ const w = checkBounds(c);
86
+ for (const x of w) log(`warning ${x.path}: ${x.message}`);
87
+ return w;
88
+ }
89
+
90
+ function fail(msg) { console.error(`error: ${msg}`); process.exit(1); }
91
+
92
+ function compileOrExit(spec) {
93
+ const { errors, warnings } = validate(spec);
94
+ for (const w of warnings) console.error(`warning ${w.path}: ${w.message}`);
95
+ if (errors.length) {
96
+ for (const e of errors) console.error(`error ${e.path}: ${e.message}`);
97
+ process.exit(1);
98
+ }
99
+ let c = compile(spec);
100
+ if (args.skin && cmd !== 'bundle') {
101
+ // Preview, render or inspect one skin (bundle always bakes all of them).
102
+ if (!c.skins?.[args.skin]) { console.error(`error unknown skin "${args.skin}" (skins: ${Object.keys(c.skins ?? {}).join(', ') || 'none'})`); process.exit(1); }
103
+ c = c.skins[args.skin];
104
+ }
105
+ printBounds(c);
106
+ return c;
107
+ }
108
+
109
+ /** A numeric flag, or a clear error naming what was typed. */
110
+ const numFlag = (a, k) => {
111
+ if (a[k] == null) return undefined;
112
+ const n = Number(a[k]);
113
+ if (a[k] === true || !Number.isFinite(n)) fail(`--${k} must be a number (got "${a[k] === true ? '' : a[k]}")`);
114
+ return n;
115
+ };
116
+ const overridesFrom = (a) => ({
117
+ lod: a.lod ? numFlag(a, 'lod') : undefined,
118
+ tones: numFlag(a, 'tones'),
119
+ texture: numFlag(a, 'texture'),
120
+ dither: a.dither != null ? a.dither !== 'false' : undefined,
121
+ outline: a.outline === true ? fail('--outline needs a value: dark, selective or none') : a.outline,
122
+ light: numFlag(a, 'light'),
123
+ flip: a.flip && a.flip !== 'false' ? true : undefined,
124
+ });
125
+
126
+ const resList = (v, d) => {
127
+ const list = String(v ?? d).split(',').map(Number);
128
+ if (!list.length || list.some((n) => !Number.isInteger(n) || n <= 0 || n > MAX_RES)) fail(`--res must be whole numbers 1..${MAX_RES}, e.g. 16,32,64 (got "${v}")`);
129
+ return list;
130
+ };
131
+ const oneRes = (v, d) => {
132
+ if (v != null && String(v).includes(',')) fail(`--res takes one resolution here (got "${v}"); use bundle or preview for several`);
133
+ return resList(v, d)[0];
134
+ };
135
+ /** --frame n, wrapped into 0..frames-1 (so -1 is the last frame). */
136
+ const frameIndex = (v, frames) => { const n = Math.trunc(Number(v) || 0); return ((n % frames) + frames) % frames; };
137
+ function animOrExit(c, name) {
138
+ const key = name ?? Object.keys(c.animations)[0];
139
+ if (!c.animations[key]) fail(`no animation "${name}" (have: ${Object.keys(c.animations).join(', ')})`);
140
+ return key;
141
+ }
142
+ const stem = (p) => basename(p).replace(/\.json$/, '');
143
+ const pngDataURL = (w, h, rgba) => 'data:image/png;base64,' + encodePNG(w, h, rgba).toString('base64');
144
+
145
+ // Anything that throws becomes one line on stderr and exit code 1 (PIXEL_DEBUG=1 shows the stack).
146
+ // A closed pipe (`pixel ascii … | head`) is not an error, and the handler must never run twice: writing the
147
+ // message to a closed stderr would throw again.
148
+ let crashing = false;
149
+ const crash = (e) => {
150
+ if (e?.code === 'EPIPE') process.exit(0);
151
+ if (crashing) process.exit(1);
152
+ crashing = true;
153
+ try { console.error(`error: ${e?.message ?? e}`); if (process.env.PIXEL_DEBUG) console.error(e?.stack); } finally { process.exit(1); }
154
+ };
155
+ process.on('uncaughtException', crash);
156
+ process.on('unhandledRejection', crash);
157
+
158
+ const [cmd, ...rest] = process.argv.slice(2);
159
+ const args = parseArgs(rest);
160
+ // Plug-ins (--plugin ./a.mjs,./b.mjs): register shapes, textures and motion models before anything runs.
161
+ if (args.plugin) {
162
+ for (const p of String(args.plugin).split(',')) {
163
+ try { await usePlugin(await import(pathToFileURL(resolve(p.trim())).href)); }
164
+ catch (e) { fail(`--plugin ${p}: ${e.message}`); }
165
+ }
166
+ }
167
+
168
+ switch (cmd) {
169
+ case 'figures': {
170
+ for (const n of figureNames()) {
171
+ const f = JSON.parse(readFileSync(join(ROOT, 'figures', `${n}.json`), 'utf8'));
172
+ console.log(`${n.padEnd(8)} ${f.bones.length} bones motions: ${Object.entries(f.motions ?? {}).map(([k, m]) => `${k}(${m.model ?? 'gait'})`).join(' ')}`);
173
+ if (f.description) console.log(` ${f.description}`);
174
+ console.log(` bones: ${f.bones.map((b) => b.id).join(' ')}`);
175
+ }
176
+ break;
177
+ }
178
+ case 'validate': {
179
+ const spec = await loadSpec(args._[0]);
180
+ const { errors, warnings } = validate(spec);
181
+ for (const w of warnings) console.log(`warning ${w.path}: ${w.message}`);
182
+ for (const e of errors) console.log(`error ${e.path}: ${e.message}`);
183
+ if (errors.length) process.exit(1);
184
+ const c = compile(spec);
185
+ printBounds(c, console.log);
186
+ const anims = Object.values(c.animations).map((a) => `${a.name}(${a.frames}f@${a.fps}fps)`).join(' ');
187
+ console.log(`ok: "${c.name}" ${c.parts.length} parts, ${Object.keys(c.materials).length} materials, animations: ${anims}`);
188
+ break;
189
+ }
190
+ case 'preview': {
191
+ const c = compileOrExit(await loadSpec(args._[0]));
192
+ const ov = overridesFrom(args);
193
+ const previewAnims = args.anim ? String(args.anim).split(',').map((n) => animOrExit(c, n.trim())) : Object.keys(c.animations);
194
+ const blocks = resList(args.res, '16,32,64').map((res) => ({
195
+ res,
196
+ rows: previewAnims.map((n) => ({ name: n, frames: renderAnimation(c, n, res, ov).frames })),
197
+ }));
198
+ const img = contactSheet(blocks, { cellH: Number(args.cell) || 128 });
199
+ const out = args.out || `${stem(args._[0])}.preview.png`;
200
+ mkdirSync(dirname(resolve(out)), { recursive: true });
201
+ writeFileSync(out, encodePNG(img.w, img.h, img.rgba));
202
+ console.log(`wrote ${out} (${img.w}x${img.h})`);
203
+ console.log(`blocks top→bottom: ${blocks.map((b) => `${b.res}px [${DETAIL_NAMES[resolveStyle(c, b.res, ov).lod]}]`).join(', ')}`);
204
+ console.log(`rows per block: ${previewAnims.join(', ')}`);
205
+ break;
206
+ }
207
+ case 'ascii': {
208
+ const c = compileOrExit(await loadSpec(args._[0]));
209
+ const res = oneRes(args.res, 24);
210
+ const anim = animOrExit(c, args.anim);
211
+ const frames = args.frame === 'all'
212
+ ? [...Array(c.animations[anim].frames).keys()]
213
+ : [frameIndex(args.frame, c.animations[anim].frames)];
214
+ const style = resolveStyle(c, res, overridesFrom(args));
215
+ for (const f of frames) {
216
+ const fr = renderFrame(c, { res, anim, frame: f, style });
217
+ const { text, legend } = frameToAscii(fr);
218
+ console.log(`${anim} frame ${f} @${res}px legend: ${Object.entries(legend).map(([k, v]) => `${v}=${k}`).join(' ')} #=outline .=empty`);
219
+ console.log(text + '\n');
220
+ }
221
+ break;
222
+ }
223
+ case 'render': {
224
+ const c = compileOrExit(await loadSpec(args._[0]));
225
+ const res = oneRes(args.res, 32);
226
+ const sheet = renderSheet(c, res, overridesFrom(args));
227
+ const dir = args.out || '.';
228
+ mkdirSync(dir, { recursive: true });
229
+ const base = `${stem(args._[0])}.${res}`;
230
+ writeFileSync(join(dir, `${base}.png`), encodePNG(sheet.width, sheet.height, sheet.rgba));
231
+ writeFileSync(join(dir, `${base}.json`), JSON.stringify({ name: c.name, image: `${base}.png`, ...sheet.meta }, null, 2));
232
+ console.log(`wrote ${join(dir, base)}.png (${sheet.width}x${sheet.height}) + .json`);
233
+ break;
234
+ }
235
+ case 'export': {
236
+ // Aseprite-format JSON (Phaser) with a PixiJS animations map, plus the PNG sheet.
237
+ const c = compileOrExit(await loadSpec(args._[0]));
238
+ const res = oneRes(args.res, 32);
239
+ if ((args.format ?? 'aseprite') !== 'aseprite') { console.error('error --format: only "aseprite" (also read by Phaser and PixiJS)'); process.exit(1); }
240
+ const dir = args.out || '.';
241
+ mkdirSync(dir, { recursive: true });
242
+ const base = `${stem(args._[0])}${args.skin ? `.${args.skin}` : ''}.${res}`;
243
+ const ex = exportSheet(c, res, { image: `${base}.png`, overrides: overridesFrom(args) });
244
+ writeFileSync(join(dir, `${base}.png`), encodePNG(ex.width, ex.height, ex.rgba));
245
+ writeFileSync(join(dir, `${base}.json`), JSON.stringify(ex.json, null, 2));
246
+ console.log(`wrote ${join(dir, base)}.png (${ex.width}x${ex.height}) + .json (${Object.keys(ex.json.frames).length} frames, ${ex.json.meta.frameTags.length} tags, ${ex.json.meta.slices.length} slices)`);
247
+ break;
248
+ }
249
+ case 'bundle': {
250
+ const c = compileOrExit(await loadSpec(args._[0]));
251
+ // --views front | front,back | all | none: which extra views (front, back, …) to ship; default none (the side
252
+ // view only): they are for <pixel-stage> turning a character to the reader, and each about doubles the sheets.
253
+ const has = [...new Set(Object.keys(c.animations).filter((n) => n.startsWith('turn@')).map((n) => n.slice(5)))];
254
+ if (args.views === true) fail('--views needs a value: front, back, all or none');
255
+ const asked = args.views == null ? 'none' : String(args.views).trim();
256
+ const views = asked === 'all' ? undefined : asked === 'none' ? [] : asked.split(',').map((s) => s.trim()).filter(Boolean);
257
+ for (const v of views ?? []) if (!has.includes(v)) fail(`--views: no view "${v}" (${has.length ? `views: ${has.join(', ')}, all or none` : 'this character has only the side view'})`);
258
+ if (args.views == null && has.length) console.error(`note: side view only; --views all (or ${has.join(', ')}) adds the character's other views`);
259
+ // --anims idle,waddle | stage: only those animations, with their views, turns and transitions.
260
+ if (args.anims === true) fail('--anims needs a list, e.g. --anims idle,walk (or --anims stage)');
261
+ const animations = args.anims == null ? undefined : String(args.anims).split(',').map((s) => s.trim()).filter(Boolean);
262
+ const bundle = await buildBundle(c, { resolutions: resList(args.res, '16,32,64'), overrides: overridesFrom(args), encode: pngDataURL, views, animations });
263
+ const dropped = Object.keys(c.states?.nodes ?? {}).filter((n) => !bundle.states?.nodes[n]);
264
+ if (dropped.length) console.error(`note: states: ${bundle.states ? `dropped node${dropped.length > 1 ? 's' : ''} ${dropped.join(', ')} (no animation left to play)` : 'dropped the state machine (no node has an animation left)'}`);
265
+ const out = args.out || `${stem(args._[0])}.bundle.json`;
266
+ mkdirSync(dirname(resolve(out)), { recursive: true });
267
+ // --external: sheets as PNG files next to the bundle, so a page downloads only the one it shows.
268
+ if (args.external) {
269
+ const name = basename(out).replace(/\.bundle\.json$|\.json$/, '');
270
+ for (const v of bundle.variants) for (const key of ['image', 'overlay']) {
271
+ if (typeof v[key] !== 'string' || !v[key].startsWith('data:image/png;base64,')) continue;
272
+ // Skin names come from the spec: keep them to a safe slug so the file stays beside the bundle.
273
+ const slug = (x) => String(x).replace(/[^A-Za-z0-9_-]+/g, '_');
274
+ const file = `${slug(name)}.${Number(v.res)}${v.skin ? `.${slug(v.skin)}` : ''}${key === 'overlay' ? '.overlay' : ''}.png`;
275
+ const dir = dirname(resolve(out)), target = resolve(dir, file);
276
+ if (basename(file) !== file || dirname(target) !== dir) fail(`--external: refusing to write ${file} outside ${dir}`);
277
+ writeFileSync(target, Buffer.from(v[key].slice(22), 'base64'));
278
+ v[key] = file;
279
+ }
280
+ }
281
+ const json = JSON.stringify(bundle);
282
+ writeFileSync(out, json);
283
+ console.log(`wrote ${out} (${(json.length / 1024).toFixed(1)} KB, variants: ${bundle.variants.map((v) => v.skin ? `${v.res} (${v.skin})` : v.res).join(', ')})`);
284
+ break;
285
+ }
286
+ case 'resolve': {
287
+ const json = JSON.stringify(await loadSpec(args._[0]), null, 2);
288
+ if (args.out) { writeFileSync(args.out, json + '\n'); console.log(`wrote ${args.out}`); } else console.log(json);
289
+ break;
290
+ }
291
+ case 'where': {
292
+ const c = compileOrExit(await loadSpec(args._[0]));
293
+ const anim = c.animations[animOrExit(c, args.anim)];
294
+ const frame = frameIndex(args.frame, anim.frames);
295
+ const pose = samplePose(c, anim, frame);
296
+ const { world, visible } = worldMatrices(c.parts, pose);
297
+ const at = (m, [x, y]) => [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]].map((v) => +v.toFixed(1));
298
+ console.log(`${anim.name} frame ${frame} (canvas ${c.size.join('x')} units)`);
299
+ if (args.part) {
300
+ const p = c.parts.find((q) => q.id === args.part);
301
+ if (!p) fail(`no part "${args.part}"`);
302
+ const pt = args.point ? String(args.point).split(',').map(Number) : p.pivot;
303
+ console.log(`${p.id} [${pt}] (rest) → [${at(world.get(p.id), pt)}] rot ${pose.get(p.id).rot.toFixed(1)}°`);
304
+ } else {
305
+ for (const p of c.parts) {
306
+ const t = pose.get(p.id);
307
+ console.log(`${p.id.padEnd(12)} pivot [${p.pivot}] → [${at(world.get(p.id), p.pivot)}] rot ${t.rot.toFixed(1)}°${visible.get(p.id) ? '' : ' (hidden)'}`);
308
+ }
309
+ }
310
+ break;
311
+ }
312
+ case 'brief': {
313
+ process.stdout.write(readFileSync(join(ROOT, 'docs/SPEC.md'), 'utf8'));
314
+ const extra = registeredPlugins();
315
+ if (extra.length) process.stdout.write(`\n## Plug-ins loaded for this project\n\n${extra.map((p) => `- ${p.kind} \`${p.name}\`${p.describe ? `: ${p.describe}` : ''}`).join('\n')}\n`);
316
+ break;
317
+ }
318
+ case 'help': case '--help': case '-h': case undefined:
319
+ default:
320
+ {
321
+ const lines = readFileSync(fileURLToPath(import.meta.url), 'utf8').split('\n').slice(1); // skip the #! line
322
+ const header = lines.slice(0, lines.findIndex((l) => !l.startsWith('//')));
323
+ console.log(header.map((l) => l.slice(3)).join('\n'));
324
+ }
325
+ process.exit(!cmd || ['help', '--help', '-h'].includes(cmd) ? 0 : 1);
326
+ }