pixelkiln 0.139.3 → 0.141.0

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.
package/dist/cli.js CHANGED
@@ -68,7 +68,7 @@ function exitCodeFor(err) {
68
68
 
69
69
  // src/cli/main.ts
70
70
  import { existsSync as existsSync59 } from "fs";
71
- import { readFile as readFile52 } from "fs/promises";
71
+ import { readFile as readFile53 } from "fs/promises";
72
72
 
73
73
  // src/cli/args.ts
74
74
  import path from "path";
@@ -254,6 +254,7 @@ var COMMANDS = [
254
254
  "ui",
255
255
  "asset",
256
256
  "talk",
257
+ "parallax",
257
258
  "help",
258
259
  "--help",
259
260
  "-h",
@@ -273,6 +274,7 @@ var MUSIC_SUBCOMMANDS = ["make", "style", "lyrics"];
273
274
  var TALK_SUBCOMMANDS = ["visemes", "gif", "plan"];
274
275
  var ASSET_SUBCOMMANDS = ["canvas", "mirror", "import", "save", "expand", "review", "export"];
275
276
  var UI_SUBCOMMANDS = ["show", "split", "states", "nine-slice", "pull"];
277
+ var PARALLAX_SUBCOMMANDS = ["preview", "export"];
276
278
  function parseArgs(argv) {
277
279
  const [command = "help"] = argv;
278
280
  if (!COMMANDS.includes(command)) {
@@ -420,6 +422,14 @@ function parseArgs(argv) {
420
422
  throw new UsageError(`Unknown music subcommand "${subcommand}". Known: ${MUSIC_SUBCOMMANDS.join(", ")}`);
421
423
  }
422
424
  if (rest[0] === subcommand) rest = rest.slice(1);
425
+ } else if (command === "parallax") {
426
+ subcommand = rest[0]?.startsWith("-") || rest[0] === void 0 ? "preview" : rest[0];
427
+ if (!PARALLAX_SUBCOMMANDS.includes(subcommand)) {
428
+ throw new UsageError(`Unknown parallax subcommand "${subcommand}". Known: ${PARALLAX_SUBCOMMANDS.join(", ")}`);
429
+ }
430
+ if (rest[0] === subcommand) rest = rest.slice(1);
431
+ target = rest[0]?.startsWith("-") ? void 0 : rest[0];
432
+ if (target !== void 0) rest = rest.slice(1);
423
433
  } else if (command === "refine") {
424
434
  subcommand = rest[0]?.startsWith("-") || rest[0] === void 0 ? "run" : rest[0];
425
435
  if (!REFINE_SUBCOMMANDS.includes(subcommand)) {
@@ -511,7 +521,7 @@ function parseArgs(argv) {
511
521
  }
512
522
  const manifest = get("--manifest") ?? "pixelkiln.manifest.json";
513
523
  const rawFormat = get("--format");
514
- const formats = command === "export" ? ["generic", "tiled", "godot", "ldtk"] : command === "asset" ? ["zip", "spritesheet", "aseprite", "gif"] : ["generic", "aseprite", "godot"];
524
+ const formats = command === "export" ? ["generic", "tiled", "godot", "ldtk"] : command === "parallax" ? ["tiled", "godot", "ldtk"] : command === "asset" ? ["zip", "spritesheet", "aseprite", "gif"] : ["generic", "aseprite", "godot"];
515
525
  if (rawFormat && !formats.includes(rawFormat)) {
516
526
  throw new UsageError(`--format must be ${formats.slice(0, -1).join(", ")}, or ${formats.at(-1)}, got "${rawFormat}"`);
517
527
  }
@@ -706,6 +716,10 @@ Commands
706
716
  mount Write a style's sprites into their declared cells of an existing
707
717
  sheet, leaving every other pixel untouched. Offline.
708
718
  export Build a tile atlas, engine metadata, and offline provenance record.
719
+ parallax A manifest's parallax sets. parallax preview [set] writes a page
720
+ that scrolls the set and a strip of frames; parallax export [set]
721
+ writes a Tiled map, a Godot scene and an LDtk project (or one,
722
+ with --format) with the layer pictures. Offline.
709
723
  purge Delete objects previously tagged discard. Irreversible; asks first.
710
724
  prune Drop lock entries the manifest no longer declares. Offline; asks
711
725
  first. Local art is untouched.
@@ -814,6 +828,7 @@ Options
814
828
  --inputs <path> pack/quality snapshot: JSON input list; needs --out
815
829
  --format <format> export: generic (default), tiled, godot (TileSet), or ldtk
816
830
  pack/mount: generic (default), aseprite, or godot (SpriteFrames)
831
+ parallax export: tiled, godot, or ldtk (default: all three)
817
832
  --output-role <r> pack: include only this output role (repeatable)
818
833
  --primary-only pack: include only unambiguous primary/single outputs
819
834
  --max-distance <n> audit: maximum palette distance
@@ -883,6 +898,7 @@ Options
883
898
  --style-weight <n> music: how closely to follow the style, 0-1
884
899
  --frames <n> estimate-skeleton: poses to scaffold, 3-15;
885
900
  normal-map: equal frames in the --from strip, 1-32
901
+ parallax preview: frames in the strip, 3-15 (default 3)
886
902
  --convention <c> normal-map: opengl (green up, default) or directx (green down)
887
903
  --preset <name> vfx: start from a whole-effect preset (vfx presets lists them)
888
904
  --recipe <file> vfx: render a recipe or an earlier run's .vfx.json record
@@ -1454,10 +1470,10 @@ function normalizeHex(value) {
1454
1470
  function sha256(data) {
1455
1471
  return createHash("sha256").update(data).digest("hex");
1456
1472
  }
1457
- async function sha256File(path77) {
1473
+ async function sha256File(path79) {
1458
1474
  return new Promise((resolve, reject) => {
1459
1475
  const hash = createHash("sha256");
1460
- const stream = createReadStream(path77);
1476
+ const stream = createReadStream(path79);
1461
1477
  stream.on("data", (chunk2) => hash.update(chunk2));
1462
1478
  stream.on("error", reject);
1463
1479
  stream.on("end", () => resolve(hash.digest("hex")));
@@ -3191,7 +3207,7 @@ var AssetDeriveSchema = z.object({
3191
3207
  /** key-skin: how far a pixel may sit from a `skin` colour. despeckle: how near a reference colour must be to vouch for a pixel. */
3192
3208
  tolerance: z.number().min(0).max(442).optional()
3193
3209
  }).strict().superRefine((derive, context) => {
3194
- const issue = (message6, path77) => context.addIssue({ code: z.ZodIssueCode.custom, message: message6, path: [path77] });
3210
+ const issue = (message6, path79) => context.addIssue({ code: z.ZodIssueCode.custom, message: message6, path: [path79] });
3195
3211
  if (Boolean(derive.from) === Boolean(derive.file)) {
3196
3212
  issue("name exactly one source: `from` (an asset in this style) or `file` (a committed PNG)", derive.from ? "file" : "from");
3197
3213
  }
@@ -3506,6 +3522,88 @@ var AssetSchema = z.object({
3506
3522
  });
3507
3523
  var DEFAULT_HISTORY_LIMIT = 5;
3508
3524
  var HistoryLimitSchema = z.number().int().min(0).max(100);
3525
+ var ParallaxRunSpriteSchema = z.object({
3526
+ asset: z.string().min(1).optional(),
3527
+ /** The style the asset was generated under, when it was generated under more than one. */
3528
+ style: z.string().min(1).optional(),
3529
+ file: z.string().min(1).optional()
3530
+ }).strict().superRefine((sprite, ctx) => {
3531
+ if (sprite.asset === void 0 === (sprite.file === void 0)) {
3532
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "a run sprite needs exactly one of asset or file" });
3533
+ }
3534
+ if (sprite.style !== void 0 && sprite.asset === void 0) {
3535
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["style"], message: "style only applies to an asset sprite" });
3536
+ }
3537
+ });
3538
+ var RUN_ONLY = ["seed", "step", "gap", "jitter", "width"];
3539
+ var ParallaxLayerSchema = z.object({
3540
+ /** Names the layer in exports; defaults to the asset id, the file name, or "sky". */
3541
+ name: z.string().regex(/^[A-Za-z][A-Za-z0-9_-]*$/, "letters, digits, - and _, starting with a letter").optional(),
3542
+ /** A manifest asset, read from the lockfile once generated. */
3543
+ asset: z.string().min(1).optional(),
3544
+ /** The style the asset was generated under, when it was generated under more than one. */
3545
+ style: z.string().min(1).optional(),
3546
+ /** A picture on disk, relative to the manifest: a layer finished by hand or by script. */
3547
+ file: z.string().min(1).optional(),
3548
+ /** Flat colour bands, top to bottom, with a dithered step between neighbours. */
3549
+ sky: z.array(HexColorSchema).min(1).max(64).optional(),
3550
+ /**
3551
+ * Isolated silhouettes laid left to right in an overlapping run, each
3552
+ * flipped at random and never the same one twice in a row, so a long
3553
+ * level never shows the same stretch twice.
3554
+ */
3555
+ run: z.array(ParallaxRunSpriteSchema).min(1).max(32).optional(),
3556
+ /** Seeds a run's layout; the same seed lays the same run. Defaults to one taken from the layer's name. */
3557
+ seed: z.number().int().min(0).max(2 ** 32 - 1).optional(),
3558
+ /** How far across one sprite the next starts, as a fraction of its width; 0.72 by default. */
3559
+ step: z.number().min(0.1).max(2).optional(),
3560
+ /** Up to this many more pixels between sprites, at random; 16 by default. */
3561
+ gap: z.number().int().min(0).max(4096).optional(),
3562
+ /** Moves each sprite's foot up or down by up to this many pixels; 0 by default. */
3563
+ jitter: z.number().int().min(0).max(256).optional(),
3564
+ /** The run's length in pixels; by default as much as the camera sees of the layer. */
3565
+ width: z.number().int().min(1).max(1e5).optional(),
3566
+ speed: z.number().min(0).max(4),
3567
+ /** Vertical speed; 1, moving with the level, when the set does not climb. */
3568
+ speedY: z.number().min(0).max(4).optional(),
3569
+ /** Left edge on the set's canvas, whose origin is the view's top-left at the start. */
3570
+ x: z.number().int().min(-1e5).max(1e5).optional(),
3571
+ /** The canvas row the layer's bottom edge sits on; the view's height when absent. */
3572
+ bottom: z.number().int().min(-1e5).max(1e5).optional(),
3573
+ /**
3574
+ * Repeat the bottom row downward: true to the foot of the view, or this
3575
+ * many rows. A far range extended this way gives nearer
3576
+ * layers' feet distant land to dissolve into instead of floating.
3577
+ */
3578
+ extend: z.union([z.boolean(), z.number().int().min(1).max(4096)]).optional(),
3579
+ /** Repeat sideways (the default) so the layer loops. */
3580
+ repeat: z.boolean().optional(),
3581
+ /** Repeat vertically, for an endless climb. */
3582
+ repeatY: z.boolean().optional()
3583
+ }).strict().superRefine((layer, ctx) => {
3584
+ const sources = [layer.asset, layer.file, layer.sky, layer.run].filter((value) => value !== void 0).length;
3585
+ if (sources !== 1) {
3586
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "a layer needs exactly one of asset, file, sky, or run" });
3587
+ }
3588
+ if (layer.run === void 0) {
3589
+ for (const key3 of RUN_ONLY) {
3590
+ if (layer[key3] !== void 0) ctx.addIssue({ code: z.ZodIssueCode.custom, path: [key3], message: `${key3} only applies to a run layer` });
3591
+ }
3592
+ }
3593
+ if (layer.style !== void 0 && layer.asset === void 0) {
3594
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["style"], message: "style only applies to an asset layer" });
3595
+ }
3596
+ });
3597
+ var ParallaxSetSchema = z.object({
3598
+ /** The game's view in pixels, [width, height]. */
3599
+ view: z.tuple([z.number().int().min(8).max(4096), z.number().int().min(8).max(4096)]),
3600
+ /** How far the camera moves sideways across the level, in pixels. */
3601
+ travel: z.number().int().min(0).max(1e5).optional(),
3602
+ /** How far the camera climbs, in pixels. */
3603
+ climb: z.number().int().min(0).max(1e5).optional(),
3604
+ layers: z.array(ParallaxLayerSchema).min(1).max(32)
3605
+ }).strict();
3606
+ var ParallaxSetIdSchema = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/, "a set id is letters, digits, - and _, starting with a letter or digit");
3509
3607
  var ManifestSchema = z.object({
3510
3608
  $schema: z.string().optional(),
3511
3609
  name: z.string(),
@@ -3514,7 +3612,9 @@ var ManifestSchema = z.object({
3514
3612
  /** Replaced generations kept per asset for this project; overrides PIXELKILN_HISTORY. 0 keeps none. */
3515
3613
  history: HistoryLimitSchema.optional(),
3516
3614
  styles: z.record(StyleSchema),
3517
- assets: z.record(AssetSchema)
3615
+ assets: z.record(AssetSchema),
3616
+ /** Parallax backgrounds built from the assets, by set id. */
3617
+ parallax: z.record(ParallaxSetIdSchema, ParallaxSetSchema).optional()
3518
3618
  }).strict();
3519
3619
  var ManifestInputSchema = z.object({
3520
3620
  $schema: z.string().optional(),
@@ -3522,7 +3622,8 @@ var ManifestInputSchema = z.object({
3522
3622
  provider: z.string().min(1).default("pixellab"),
3523
3623
  history: HistoryLimitSchema.optional(),
3524
3624
  styles: z.record(StyleInputSchema),
3525
- assets: z.record(AssetSchema)
3625
+ assets: z.record(AssetSchema),
3626
+ parallax: z.record(ParallaxSetIdSchema, ParallaxSetSchema).optional()
3526
3627
  }).strict();
3527
3628
  var LockOutputSchema = z.object({
3528
3629
  path: z.string(),
@@ -9197,9 +9298,9 @@ var PixelLabClient = class {
9197
9298
  apiKey;
9198
9299
  http;
9199
9300
  /** Retries transport failures, 429, and 5xx; see http.ts for the policy. */
9200
- async request(path77, init) {
9301
+ async request(path79, init) {
9201
9302
  const auth = this.apiKey.startsWith("Bearer ") ? this.apiKey : `Bearer ${this.apiKey}`;
9202
- const res = await this.http(`${BASE}${path77}`, {
9303
+ const res = await this.http(`${BASE}${path79}`, {
9203
9304
  ...init,
9204
9305
  headers: {
9205
9306
  Authorization: auth,
@@ -9210,13 +9311,13 @@ var PixelLabClient = class {
9210
9311
  const text = await res.text();
9211
9312
  if (!res.ok) {
9212
9313
  const hint = res.status === 500 && text.includes("Failed to start any animation jobs") ? '; a skeleton-v3 loop needs a character with a stored 3D skeleton (a v3 base), use mode: "template" on a standard one' : "";
9213
- throw new PixelLabError(`${init?.method ?? "GET"} ${path77} \u2192 ${res.status}${hint}${refusalReason(res.status, text)}`, res.status, text);
9314
+ throw new PixelLabError(`${init?.method ?? "GET"} ${path79} \u2192 ${res.status}${hint}${refusalReason(res.status, text)}`, res.status, text);
9214
9315
  }
9215
9316
  if (!text) return {};
9216
9317
  try {
9217
9318
  return JSON.parse(text);
9218
9319
  } catch {
9219
- throw new Error(`${init?.method ?? "GET"} ${path77} returned invalid JSON`);
9320
+ throw new Error(`${init?.method ?? "GET"} ${path79} returned invalid JSON`);
9220
9321
  }
9221
9322
  }
9222
9323
  async balance() {
@@ -9763,10 +9864,10 @@ var PixelLabClient = class {
9763
9864
  const palette = args.paletteSwatchBase64 ? { color_image: { type: "base64", base64: args.paletteSwatchBase64, format: "png" }, force_colors: true } : {};
9764
9865
  const encode = (image) => ({ type: "base64", base64: image.base64, format: image.format });
9765
9866
  const south = args.reference?.south;
9766
- let path77;
9867
+ let path79;
9767
9868
  let body;
9768
9869
  if (args.mode === "v3") {
9769
- path77 = "/create-character-v3";
9870
+ path79 = "/create-character-v3";
9770
9871
  body = {
9771
9872
  description: args.description,
9772
9873
  image_size: imageSize,
@@ -9780,7 +9881,7 @@ var PixelLabClient = class {
9780
9881
  ...args.enhancePrompt ? { enhance_prompt: true } : {}
9781
9882
  };
9782
9883
  } else if (args.mode === "pro-flash") {
9783
- path77 = "/create-character-pro-flash";
9884
+ path79 = "/create-character-pro-flash";
9784
9885
  const traits = args.styleTraits;
9785
9886
  body = {
9786
9887
  description: args.description,
@@ -9804,7 +9905,7 @@ var PixelLabClient = class {
9804
9905
  } : {}
9805
9906
  };
9806
9907
  } else if (args.mode === "pro") {
9807
- path77 = "/create-character-pro";
9908
+ path79 = "/create-character-pro";
9808
9909
  body = {
9809
9910
  description: args.description,
9810
9911
  image_size: imageSize,
@@ -9818,7 +9919,7 @@ var PixelLabClient = class {
9818
9919
  ...!south && args.styleCharacterId ? { style_character_id: args.styleCharacterId } : {}
9819
9920
  };
9820
9921
  } else {
9821
- path77 = args.directions === 4 ? "/create-character-with-4-directions" : "/create-character-with-8-directions";
9922
+ path79 = args.directions === 4 ? "/create-character-with-4-directions" : "/create-character-with-8-directions";
9822
9923
  body = {
9823
9924
  description: args.description,
9824
9925
  image_size: imageSize,
@@ -9836,8 +9937,8 @@ var PixelLabClient = class {
9836
9937
  };
9837
9938
  }
9838
9939
  if (args.mode === "pro" || args.mode === "pro-flash") Object.assign(body, targetPaletteBody(args.targetPalette));
9839
- const raw = await this.request(path77, { method: "POST", body: JSON.stringify(body) });
9840
- return validateResponse(CharacterSubmitSchema, raw, path77.slice(1));
9940
+ const raw = await this.request(path79, { method: "POST", body: JSON.stringify(body) });
9941
+ return validateResponse(CharacterSubmitSchema, raw, path79.slice(1));
9841
9942
  }
9842
9943
  /** A text edit of an existing character, applied to every direction and stored as a sibling. */
9843
9944
  async createCharacterState(args) {
@@ -15233,9 +15334,9 @@ var RetroDiffusionClient = class {
15233
15334
  if (!response.ok) throw new ProviderError("retrodiffusion", `Retro Diffusion download failed (${response.status})`, { status: response.status });
15234
15335
  return Buffer.from(await response.arrayBuffer());
15235
15336
  }
15236
- async call(path77, init = {}) {
15337
+ async call(path79, init = {}) {
15237
15338
  if (!this.token) throw new Error("RD_API_KEY is not set");
15238
- const response = await this.request(`${this.baseUrl}${path77}`, {
15339
+ const response = await this.request(`${this.baseUrl}${path79}`, {
15239
15340
  ...init,
15240
15341
  headers: {
15241
15342
  "Content-Type": "application/json",
@@ -16517,6 +16618,28 @@ ${issues}`);
16517
16618
  connectVisited.add(assetId);
16518
16619
  };
16519
16620
  for (const assetId of Object.keys(parsed.data.assets)) visitConnections(assetId);
16621
+ for (const [setId, set] of Object.entries(parsed.data.parallax ?? {})) {
16622
+ const names = /* @__PURE__ */ new Set();
16623
+ set.layers.forEach((layer, index) => {
16624
+ const at2 = `parallax.${setId}.layers.${index}`;
16625
+ const checkAsset = (where, ref) => {
16626
+ if (ref.asset === void 0) return;
16627
+ const asset = parsed.data.assets[ref.asset];
16628
+ if (!asset) unknownReferences.push(`${where}.asset: unknown asset "${ref.asset}"`);
16629
+ else if (ref.style !== void 0 && !asset.styles.includes(ref.style)) {
16630
+ unknownReferences.push(`${where}.style: asset "${ref.asset}" is not generated under style "${ref.style}"`);
16631
+ } else if (ref.style === void 0 && asset.styles.length > 1) {
16632
+ unknownReferences.push(`${where}.style: asset "${ref.asset}" has ${asset.styles.length} styles; name one`);
16633
+ }
16634
+ };
16635
+ checkAsset(at2, layer);
16636
+ layer.run?.forEach((sprite, n) => checkAsset(`${at2}.run.${n}`, sprite));
16637
+ if (layer.name !== void 0) {
16638
+ if (names.has(layer.name)) unknownReferences.push(`${at2}.name: "${layer.name}" is used twice`);
16639
+ names.add(layer.name);
16640
+ }
16641
+ });
16642
+ }
16520
16643
  if (unknownReferences.length) {
16521
16644
  throw new ProjectError(`Manifest at ${abs} is invalid:
16522
16645
  ${unknownReferences.map((i) => ` ${i}`).join("\n")}`);
@@ -18546,10 +18669,10 @@ function isSha256Hash(value) {
18546
18669
  function parseCache(value) {
18547
18670
  return HashCacheSchema.parse(value);
18548
18671
  }
18549
- async function loadCache(path77) {
18550
- if (!existsSync18(path77)) return { version: 1, hashes: {} };
18672
+ async function loadCache(path79) {
18673
+ if (!existsSync18(path79)) return { version: 1, hashes: {} };
18551
18674
  try {
18552
- const parsed = HashCacheSchema.safeParse(JSON.parse(await readFile13(path77, "utf8")));
18675
+ const parsed = HashCacheSchema.safeParse(JSON.parse(await readFile13(path79, "utf8")));
18553
18676
  if (!parsed.success) return { version: 1, hashes: {} };
18554
18677
  return {
18555
18678
  version: 1,
@@ -18561,18 +18684,18 @@ async function loadCache(path77) {
18561
18684
  return { version: 1, hashes: {} };
18562
18685
  }
18563
18686
  }
18564
- async function saveCache(path77, cache) {
18687
+ async function saveCache(path79, cache) {
18565
18688
  const sorted = {};
18566
18689
  for (const key3 of Object.keys(cache.hashes).sort()) {
18567
18690
  const hash = cache.hashes[key3];
18568
18691
  if (!isSha256Hash(hash)) throw new Error(`Refusing to cache invalid SHA-256 for ${key3}`);
18569
18692
  sorted[key3] = hash;
18570
18693
  }
18571
- await mkdir9(pathModule.dirname(pathModule.resolve(path77)), { recursive: true });
18572
- const tmp = `${path77}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
18694
+ await mkdir9(pathModule.dirname(pathModule.resolve(path79)), { recursive: true });
18695
+ const tmp = `${path79}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
18573
18696
  try {
18574
18697
  await writeFile9(tmp, JSON.stringify({ version: 1, hashes: sorted }, null, 2) + "\n");
18575
- await rename7(tmp, path77);
18698
+ await rename7(tmp, path79);
18576
18699
  } finally {
18577
18700
  await rm5(tmp, { force: true });
18578
18701
  }
@@ -22847,13 +22970,13 @@ function poseNodes(document, pose) {
22847
22970
  const posed = /* @__PURE__ */ new Map();
22848
22971
  for (const channel of animation.channels) {
22849
22972
  const node = channel.target.node;
22850
- const path77 = channel.target.path;
22851
- if (node === void 0 || !["translation", "rotation", "scale"].includes(path77)) continue;
22973
+ const path79 = channel.target.path;
22974
+ if (node === void 0 || !["translation", "rotation", "scale"].includes(path79)) continue;
22852
22975
  const sampler = animation.samplers[channel.sampler];
22853
22976
  if (!sampler) continue;
22854
22977
  const times = readAccessor(document, sampler.input).data;
22855
22978
  const values = readAccessor(document, sampler.output);
22856
- const width = path77 === "rotation" ? 4 : 3;
22979
+ const width = path79 === "rotation" ? 4 : 3;
22857
22980
  const cubic = sampler.interpolation === "CUBICSPLINE";
22858
22981
  const valueAt = (key4) => Array.from(values.data.subarray((cubic ? key4 * 3 + 1 : key4) * width, (cubic ? key4 * 3 + 1 : key4) * width + width));
22859
22982
  const last = times.length - 1;
@@ -22865,16 +22988,16 @@ function poseNodes(document, pose) {
22865
22988
  const span = times[key3 + 1] - times[key3];
22866
22989
  const f = span > 0 ? (time - times[key3]) / span : 0;
22867
22990
  const next = valueAt(key3 + 1);
22868
- const sign = path77 === "rotation" && value.reduce((sum, v, k) => sum + v * next[k], 0) < 0 ? -1 : 1;
22991
+ const sign = path79 === "rotation" && value.reduce((sum, v, k) => sum + v * next[k], 0) < 0 ? -1 : 1;
22869
22992
  value = value.map((v, k) => v * (1 - f) + next[k] * sign * f);
22870
22993
  }
22871
- if (path77 === "rotation") {
22994
+ if (path79 === "rotation") {
22872
22995
  const length = Math.hypot(...value) || 1;
22873
22996
  value = value.map((v) => v / length);
22874
22997
  }
22875
22998
  const base = posed.get(node) ?? { ...document.json.nodes?.[node] ?? {} };
22876
22999
  if (base.matrix) delete base.matrix;
22877
- base[path77] = value;
23000
+ base[path79] = value;
22878
23001
  posed.set(node, base);
22879
23002
  }
22880
23003
  return posed;
@@ -35501,13 +35624,804 @@ async function runAnchors(args) {
35501
35624
  }
35502
35625
  }
35503
35626
 
35504
- // src/cli/commands/redraw.ts
35627
+ // src/cli/commands/parallax.ts
35505
35628
  import path74 from "path";
35506
35629
 
35630
+ // src/pipeline/parallax.ts
35631
+ import { createHash as createHash9 } from "crypto";
35632
+ import { readFile as readFile50 } from "fs/promises";
35633
+ import path73 from "path";
35634
+ var PARALLAX_FORMATS = ["tiled", "godot", "ldtk"];
35635
+ var SEAM_WARN_RATIO = 2;
35636
+ function layerFiles(layer) {
35637
+ if (layer.source.kind === "sky") return [];
35638
+ if (layer.source.kind === "run") return layer.source.sprites.map((sprite) => sprite.path);
35639
+ return [layer.source.path];
35640
+ }
35641
+ var BAYER4 = [
35642
+ [0, 8, 2, 10],
35643
+ [12, 4, 14, 6],
35644
+ [3, 11, 1, 9],
35645
+ [15, 7, 13, 5]
35646
+ ];
35647
+ function skyBands(width, height, colors, blend = 8) {
35648
+ const rgb = colors.map((color) => parseHex(color));
35649
+ const n = rgb.length;
35650
+ const pixels = Buffer.alloc(width * height * 4);
35651
+ for (let y = 0; y < height; y++) {
35652
+ const band = Math.min(Math.floor(y / height * n), n - 1);
35653
+ const rowsLeft = (band + 1) * height / n - y;
35654
+ const share = band < n - 1 && rowsLeft <= blend ? 1 - rowsLeft / (blend + 1) : 0;
35655
+ for (let x = 0; x < width; x++) {
35656
+ const next = share > 0 && BAYER4[y % 4][x % 4] < share * 16;
35657
+ const color = rgb[next ? band + 1 : band];
35658
+ const at2 = (y * width + x) * 4;
35659
+ pixels[at2] = color.r;
35660
+ pixels[at2 + 1] = color.g;
35661
+ pixels[at2 + 2] = color.b;
35662
+ pixels[at2 + 3] = 255;
35663
+ }
35664
+ }
35665
+ return { width, height, pixels };
35666
+ }
35667
+ function transpose(png) {
35668
+ const pixels = Buffer.alloc(png.pixels.length);
35669
+ for (let y = 0; y < png.height; y++) {
35670
+ for (let x = 0; x < png.width; x++) png.pixels.copy(pixels, (x * png.height + y) * 4, (y * png.width + x) * 4, (y * png.width + x) * 4 + 4);
35671
+ }
35672
+ return { width: png.height, height: png.width, pixels };
35673
+ }
35674
+ function columnDiff(png, a, b) {
35675
+ let sum = 0;
35676
+ for (let y = 0; y < png.height; y++) {
35677
+ const pa = (y * png.width + a) * 4;
35678
+ const pb = (y * png.width + b) * 4;
35679
+ const alphaA = png.pixels[pa + 3];
35680
+ const alphaB = png.pixels[pb + 3];
35681
+ for (let c = 0; c < 3; c++) {
35682
+ sum += Math.abs(Math.floor(png.pixels[pa + c] * alphaA / 255) - Math.floor(png.pixels[pb + c] * alphaB / 255));
35683
+ }
35684
+ sum += Math.abs(alphaA - alphaB);
35685
+ }
35686
+ return sum / (png.height * 4);
35687
+ }
35688
+ function seamRatio(png) {
35689
+ if (png.width < 3) return 0;
35690
+ const inner = [];
35691
+ for (let x = 0; x < png.width - 1; x++) {
35692
+ const step = columnDiff(png, x, x + 1);
35693
+ if (step > 0) inner.push(step);
35694
+ }
35695
+ const seam = columnDiff(png, png.width - 1, 0);
35696
+ if (!inner.length) return seam > 0 ? Infinity : 0;
35697
+ inner.sort((a, b) => a - b);
35698
+ return seam / inner[Math.floor(inner.length / 2)];
35699
+ }
35700
+ function layerName(layer, index) {
35701
+ if (layer.name) return layer.name;
35702
+ const base = layer.asset ?? (layer.file ? path73.basename(layer.file, path73.extname(layer.file)) : layer.run ? "run" : "sky");
35703
+ const slug3 = base.replace(/[^A-Za-z0-9_-]+/g, "_").replace(/^[^A-Za-z]+/, "");
35704
+ return slug3 || `layer${index + 1}`;
35705
+ }
35706
+ async function resolveParallaxSet(manifest, manifestDir, lock, setId) {
35707
+ const set = manifest.parallax?.[setId];
35708
+ if (!set) {
35709
+ const known = Object.keys(manifest.parallax ?? {});
35710
+ throw new Error(`No parallax set "${setId}". ${known.length ? `Known: ${known.join(", ")}` : "The manifest has no parallax sets."}`);
35711
+ }
35712
+ const [viewW, viewH] = set.view;
35713
+ const travel = set.travel ?? viewW * 2;
35714
+ const climb = set.climb ?? 0;
35715
+ const warnings = [];
35716
+ const layers = [];
35717
+ const taken = /* @__PURE__ */ new Set();
35718
+ for (const [index, layer] of set.layers.entries()) {
35719
+ let name = layerName(layer, index);
35720
+ for (let n = 2; taken.has(name); n++) name = `${layerName(layer, index)}_${n}`;
35721
+ taken.add(name);
35722
+ const speedY = layer.speedY ?? (climb > 0 ? layer.speed : 1);
35723
+ let png;
35724
+ let source;
35725
+ if (layer.sky) {
35726
+ png = skyBands(viewW, viewH + Math.ceil(climb * speedY), layer.sky);
35727
+ source = { kind: "sky", colors: layer.sky };
35728
+ } else if (layer.run) {
35729
+ const sprites = await Promise.all(layer.run.map((sprite) => readPicture(manifest, manifestDir, lock, setId, name, sprite, warnings)));
35730
+ const seed = layer.seed ?? seedFromName(name);
35731
+ const loop = layer.repeat ?? true;
35732
+ const width = layer.width ?? Math.max(1, viewW + Math.ceil(travel * layer.speed) - (loop ? 0 : layer.x ?? 0));
35733
+ png = layRun(sprites.map((sprite) => sprite.png), width, { seed, step: layer.step, gap: layer.gap, jitter: layer.jitter, loop });
35734
+ source = { kind: "run", seed, sprites: sprites.map((sprite) => sprite.source) };
35735
+ } else {
35736
+ const picture = await readPicture(manifest, manifestDir, lock, setId, name, layer, warnings);
35737
+ png = picture.png;
35738
+ source = picture.source;
35739
+ }
35740
+ const repeat = layer.repeat ?? true;
35741
+ let bottom = (layer.bottom ?? viewH) + (layer.run ? layer.jitter ?? 0 : 0);
35742
+ if (layer.extend) {
35743
+ const rows = layer.extend === true ? Math.max(0, viewH - bottom) : layer.extend;
35744
+ png = extendDown(png, rows);
35745
+ bottom += rows;
35746
+ }
35747
+ const image = {
35748
+ name,
35749
+ png,
35750
+ speed: layer.speed,
35751
+ speedY,
35752
+ x: layer.x ?? 0,
35753
+ y: bottom - png.height,
35754
+ repeat,
35755
+ repeatY: layer.repeatY ?? false,
35756
+ source
35757
+ };
35758
+ if (repeat && source.kind !== "sky" && source.kind !== "run") {
35759
+ image.seamRatio = seamRatio(png);
35760
+ if (travel * layer.speed > 0 && image.seamRatio > SEAM_WARN_RATIO) {
35761
+ warnings.push(
35762
+ `${name}: its sideways join is ${image.seamRatio.toFixed(1)} times rougher than the picture's own steps; loop it first (research/scripts/parallax.py loop) or set repeat: false`
35763
+ );
35764
+ }
35765
+ }
35766
+ if (image.repeatY && source.kind !== "sky") {
35767
+ image.seamRatioY = seamRatio(transpose(png));
35768
+ if (climb * speedY > 0 && image.seamRatioY > SEAM_WARN_RATIO) {
35769
+ warnings.push(`${name}: its vertical join is ${image.seamRatioY.toFixed(1)} times rougher than the picture's own steps`);
35770
+ }
35771
+ }
35772
+ if (climb > 0 && !image.repeatY && png.width >= viewW && image.y <= 0) {
35773
+ const shown2 = Math.round(climb * speedY);
35774
+ if (image.y + shown2 > 0) {
35775
+ warnings.push(`${name}: fills the top of the view at the start, but ${image.y + shown2} empty row(s) show above it at the top of the climb; draw it taller or set repeatY`);
35776
+ }
35777
+ }
35778
+ if (!repeat && png.width >= viewW) {
35779
+ const needed = viewW + Math.ceil(travel * layer.speed);
35780
+ if (image.x > 0 || image.x + png.width < needed) {
35781
+ warnings.push(`${name}: does not repeat and covers columns ${image.x}..${image.x + png.width}; the camera shows 0..${needed} of it`);
35782
+ }
35783
+ }
35784
+ layers.push(image);
35785
+ }
35786
+ return { id: setId, view: [viewW, viewH], travel, climb, layers, warnings };
35787
+ }
35788
+ async function readPicture(manifest, manifestDir, lock, setId, name, ref, warnings) {
35789
+ if (ref.file) {
35790
+ const file2 = path73.resolve(manifestDir, ref.file);
35791
+ return { png: decodePng(await readFile50(file2)), source: { kind: "file", path: file2 } };
35792
+ }
35793
+ const assetId = ref.asset;
35794
+ const style = ref.style ?? manifest.assets[assetId].styles[0];
35795
+ const entry = lock.entries[lockKey(style, assetId)];
35796
+ if (!entry) throw new Error(`parallax ${setId}: ${style}/${assetId} has not been generated; run gen first`);
35797
+ const output = entry.outputs.find((candidate) => /\.png$/i.test(candidate.path)) ?? entry.outputs[0];
35798
+ if (!output) throw new Error(`parallax ${setId}: ${style}/${assetId} has no output in the lockfile`);
35799
+ const file = path73.resolve(manifestDir, output.path);
35800
+ if (entry.outputs.length > 1) warnings.push(`${name}: ${style}/${assetId} has ${entry.outputs.length} outputs; using ${output.path}`);
35801
+ return { png: decodePng(await readFile50(file)), source: { kind: "asset", style, asset: assetId, path: file } };
35802
+ }
35803
+ function seedFromName(name) {
35804
+ return createHash9("sha256").update(name).digest().readUInt32BE(0);
35805
+ }
35806
+ function seededRandom(seed) {
35807
+ let a = seed >>> 0;
35808
+ return () => {
35809
+ a = a + 1831565813 >>> 0;
35810
+ let t = a;
35811
+ t = Math.imul(t ^ t >>> 15, t | 1);
35812
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
35813
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
35814
+ };
35815
+ }
35816
+ function layRun(sprites, width, options) {
35817
+ const step = options.step ?? 0.72;
35818
+ const gap = options.gap ?? 16;
35819
+ const jitter = options.jitter ?? 0;
35820
+ const random = seededRandom(options.seed);
35821
+ const tallest = Math.max(...sprites.map((sprite) => sprite.height));
35822
+ const height = tallest + 2 * jitter;
35823
+ if (options.loop) {
35824
+ const widest = Math.max(...sprites.map((sprite) => sprite.width));
35825
+ if (width < widest) throw new Error(`a looping run must be at least as wide as its widest sprite (${widest} px); it is ${width}`);
35826
+ }
35827
+ const placed = [];
35828
+ let x = options.loop ? 0 : -Math.floor(random() * 32);
35829
+ let last = -1;
35830
+ while (x < width) {
35831
+ let pick = Math.floor(random() * sprites.length);
35832
+ if (sprites.length > 1 && pick === last) pick = (pick + 1) % sprites.length;
35833
+ last = pick;
35834
+ const sprite = sprites[pick];
35835
+ const flip = random() < 0.5;
35836
+ const shift = jitter ? Math.floor(random() * (2 * jitter + 1)) - jitter : 0;
35837
+ placed.push({ sprite: pick, flip, x, y: height - jitter - sprite.height + shift });
35838
+ x += Math.max(1, Math.floor(sprite.width * step + random() * gap));
35839
+ }
35840
+ const copies = options.loop ? [-width, 0, width] : [0];
35841
+ const stamps = placed.flatMap((p) => copies.map((dx) => ({ ...p, x: p.x + dx }))).sort((a, b) => a.x - b.x);
35842
+ const pixels = Buffer.alloc(width * height * 4);
35843
+ for (const p of stamps) {
35844
+ const sprite = sprites[p.sprite];
35845
+ for (let sy = 0; sy < sprite.height; sy++) {
35846
+ const y = p.y + sy;
35847
+ if (y < 0 || y >= height) continue;
35848
+ for (let sx = 0; sx < sprite.width; sx++) {
35849
+ const tx = p.x + sx;
35850
+ if (tx < 0 || tx >= width) continue;
35851
+ const from = (sy * sprite.width + (p.flip ? sprite.width - 1 - sx : sx)) * 4;
35852
+ if (sprite.pixels[from + 3] === 0) continue;
35853
+ sprite.pixels.copy(pixels, (y * width + tx) * 4, from, from + 4);
35854
+ }
35855
+ }
35856
+ }
35857
+ return { width, height, pixels };
35858
+ }
35859
+ function extendDown(png, rows) {
35860
+ if (rows <= 0) return png;
35861
+ const height = png.height + rows;
35862
+ const pixels = Buffer.alloc(png.width * height * 4);
35863
+ png.pixels.copy(pixels, 0);
35864
+ const last = png.pixels.subarray((png.height - 1) * png.width * 4, png.height * png.width * 4);
35865
+ for (let y = png.height; y < height; y++) last.copy(pixels, y * png.width * 4);
35866
+ return { width: png.width, height, pixels };
35867
+ }
35868
+ function layerScreenOffset(layer, camX, camY) {
35869
+ return { dx: Math.round(-Math.round(camX) * layer.speed), dy: Math.round(Math.round(camY) * layer.speedY) };
35870
+ }
35871
+ function composeParallaxFrame(set, camX, camY) {
35872
+ const [w, h] = set.view;
35873
+ const out = { width: w, height: h, pixels: Buffer.alloc(w * h * 4) };
35874
+ for (const layer of set.layers) {
35875
+ const { dx, dy } = layerScreenOffset(layer, camX, camY);
35876
+ drawLayer(out, layer, layer.x + dx, layer.y + dy);
35877
+ }
35878
+ return out;
35879
+ }
35880
+ function drawLayer(out, layer, left, top) {
35881
+ const { width: w, height: h } = out;
35882
+ const lw = layer.png.width;
35883
+ const lh = layer.png.height;
35884
+ for (let sy = 0; sy < h; sy++) {
35885
+ let ly = sy - top;
35886
+ if (layer.repeatY) ly = (ly % lh + lh) % lh;
35887
+ else if (ly < 0 || ly >= lh) continue;
35888
+ for (let sx = 0; sx < w; sx++) {
35889
+ let lx = sx - left;
35890
+ if (layer.repeat) lx = (lx % lw + lw) % lw;
35891
+ else if (lx < 0 || lx >= lw) continue;
35892
+ const src = (ly * lw + lx) * 4;
35893
+ const alpha = layer.png.pixels[src + 3] / 255;
35894
+ if (alpha === 0) continue;
35895
+ const dst = (sy * w + sx) * 4;
35896
+ const below = out.pixels[dst + 3] / 255;
35897
+ const outAlpha = alpha + below * (1 - alpha);
35898
+ for (let c = 0; c < 3; c++) {
35899
+ out.pixels[dst + c] = Math.round((layer.png.pixels[src + c] * alpha + out.pixels[dst + c] * below * (1 - alpha)) / outAlpha);
35900
+ }
35901
+ out.pixels[dst + 3] = Math.round(outAlpha * 255);
35902
+ }
35903
+ }
35904
+ }
35905
+ function cameraPath(set, frames) {
35906
+ return Array.from({ length: frames }, (_, i) => {
35907
+ const t = frames === 1 ? 0 : i / (frames - 1);
35908
+ const e = (1 - Math.cos(t * Math.PI)) / 2;
35909
+ return [Math.round(e * set.travel), Math.round(e * set.climb)];
35910
+ });
35911
+ }
35912
+ function layerPngs(set, base) {
35913
+ return set.layers.map((layer) => ({
35914
+ layer,
35915
+ file: `${path73.basename(base)}-${layer.name}.png`,
35916
+ png: encodeRgbaPng(layer.png.width, layer.png.height, layer.png.pixels)
35917
+ }));
35918
+ }
35919
+ function exportTiled(set, base) {
35920
+ const [vw, vh] = set.view;
35921
+ const grid = 16;
35922
+ const mapW = vw + set.travel;
35923
+ const mapH = vh + set.climb;
35924
+ const pictures = layerPngs(set, base);
35925
+ const layers = pictures.map(({ layer, file }, index) => ({
35926
+ id: index + 1,
35927
+ name: layer.name,
35928
+ type: "imagelayer",
35929
+ image: file,
35930
+ imagewidth: layer.png.width,
35931
+ imageheight: layer.png.height,
35932
+ offsetx: tiledNumber(layer.x - (1 - layer.speed) * (vw / 2)),
35933
+ offsety: tiledNumber(layer.y + set.climb - (1 - layer.speedY) * (set.climb + vh / 2)),
35934
+ parallaxx: layer.speed,
35935
+ parallaxy: layer.speedY,
35936
+ repeatx: layer.repeat,
35937
+ repeaty: layer.repeatY,
35938
+ opacity: 1,
35939
+ visible: true,
35940
+ x: 0,
35941
+ y: 0
35942
+ }));
35943
+ const map = {
35944
+ type: "map",
35945
+ version: "1.10",
35946
+ tiledversion: "1.11.0",
35947
+ orientation: "orthogonal",
35948
+ renderorder: "right-down",
35949
+ infinite: false,
35950
+ width: Math.ceil(mapW / grid),
35951
+ height: Math.ceil(mapH / grid),
35952
+ tilewidth: grid,
35953
+ tileheight: grid,
35954
+ nextlayerid: layers.length + 1,
35955
+ nextobjectid: 1,
35956
+ compressionlevel: -1,
35957
+ tilesets: [],
35958
+ layers,
35959
+ properties: [
35960
+ { name: "pixelkiln_view", type: "string", value: `${vw}x${vh}` },
35961
+ { name: "pixelkiln_start", type: "string", value: `0,${set.climb}` }
35962
+ ]
35963
+ };
35964
+ return {
35965
+ files: [{ path: `${base}.tmj`, data: JSON.stringify(map, null, 2) + "\n" }, ...pictures.map((p) => ({ path: path73.join(path73.dirname(base), p.file), data: p.png }))],
35966
+ options: { format: "tiled", start: [0, set.climb] }
35967
+ };
35968
+ }
35969
+ function tiledNumber(value) {
35970
+ return Number(value.toFixed(6));
35971
+ }
35972
+ function godotNumber(value) {
35973
+ return Number.isInteger(value) ? String(value) : String(Number(value.toFixed(6)));
35974
+ }
35975
+ function exportGodot(set, base) {
35976
+ const [vw, vh] = set.view;
35977
+ const pictures = layerPngs(set, base);
35978
+ const lines = [`[gd_scene load_steps=${pictures.length + 1} format=3]`, ""];
35979
+ pictures.forEach(({ file }, index) => {
35980
+ lines.push(`[ext_resource type="Texture2D" path=${JSON.stringify(`./${file}`)} id="${index + 1}_layer"]`);
35981
+ });
35982
+ lines.push("", `[node name=${JSON.stringify(path73.basename(base))} type="Node2D"]`, "texture_filter = 1");
35983
+ pictures.forEach(({ layer }, index) => {
35984
+ lines.push("", `[node name=${JSON.stringify(layer.name)} type="Parallax2D" parent="."]`);
35985
+ lines.push(`scroll_scale = Vector2(${godotNumber(layer.speed)}, ${godotNumber(layer.speedY)})`);
35986
+ const offsetY = -set.climb * (1 - layer.speedY);
35987
+ if (offsetY !== 0) lines.push(`scroll_offset = Vector2(0, ${godotNumber(offsetY)})`);
35988
+ if (layer.repeat || layer.repeatY) {
35989
+ lines.push(`repeat_size = Vector2(${layer.repeat ? layer.png.width : 0}, ${layer.repeatY ? layer.png.height : 0})`);
35990
+ const reach = (view, size) => 2 * (Math.ceil(view / size) + 1) - 1;
35991
+ const times = Math.max(layer.repeat ? reach(vw, layer.png.width) : 1, layer.repeatY ? reach(vh, layer.png.height) : 1);
35992
+ lines.push(`repeat_times = ${times}`);
35993
+ }
35994
+ lines.push("", `[node name="Sprite2D" type="Sprite2D" parent=${JSON.stringify(layer.name)}]`);
35995
+ lines.push(`texture = ExtResource("${index + 1}_layer")`, "centered = false");
35996
+ const mod = (value, size) => (value % size + size) % size;
35997
+ const px = layer.repeat ? mod(layer.x, layer.png.width) : layer.x;
35998
+ const py = layer.repeatY ? mod(layer.y + set.climb, layer.png.height) : layer.y + set.climb;
35999
+ lines.push(`position = Vector2(${px}, ${py})`);
36000
+ });
36001
+ return {
36002
+ files: [{ path: `${base}.tscn`, data: lines.join("\n") + "\n" }, ...pictures.map((p) => ({ path: path73.join(path73.dirname(base), p.file), data: p.png }))],
36003
+ options: { format: "godot", start: [0, set.climb] }
36004
+ };
36005
+ }
36006
+ function uuid(...parts) {
36007
+ const hex2 = createHash9("sha256").update(parts.join("\0")).digest("hex");
36008
+ return `${hex2.slice(0, 8)}-${hex2.slice(8, 12)}-4${hex2.slice(13, 16)}-8${hex2.slice(17, 20)}-${hex2.slice(20, 32)}`;
36009
+ }
36010
+ var LDTK_GRID = 16;
36011
+ function exportLdtk(set, base) {
36012
+ const [vw, vh] = set.view;
36013
+ const grid = LDTK_GRID;
36014
+ const levelW = vw + set.travel;
36015
+ const levelH = vh + set.climb;
36016
+ const name = path73.basename(base);
36017
+ const files = [];
36018
+ const warnings = [];
36019
+ const identifiers = /* @__PURE__ */ new Set();
36020
+ const layerDefs = [];
36021
+ const tilesets = [];
36022
+ const layerInstances = [];
36023
+ const levelUid = 1e3;
36024
+ let uid = 1;
36025
+ for (const [index, layer] of set.layers.entries()) {
36026
+ const factorX = 1 - layer.speed;
36027
+ const factorY = 1 - layer.speedY;
36028
+ const x0 = 0;
36029
+ const x1 = vw + Math.ceil(set.travel * layer.speed);
36030
+ const y0 = -Math.ceil(set.climb * layer.speedY);
36031
+ const y1 = vh;
36032
+ const place = (canvas, start, extent2, factor) => {
36033
+ let best = { off: 0, rounded: 0, frac: Infinity };
36034
+ for (let off = 0; off < grid; off++) {
36035
+ const shift = off + (start - (extent2 - off) / 2) * factor;
36036
+ const frac = Math.abs(shift - Math.round(shift));
36037
+ if (frac < best.frac - 1e-9) best = { off, rounded: Math.round(shift), frac };
36038
+ }
36039
+ const pad = ((canvas - best.rounded) % grid + grid) % grid;
36040
+ return { off: best.off, pad, cell: (canvas - best.rounded - pad) / grid, cells: Math.ceil((extent2 - best.off) / grid) };
36041
+ };
36042
+ const px = place(x0, vw / 2, levelW, factorX);
36043
+ const py = place(y0 + set.climb, levelH - vh / 2, levelH, factorY);
36044
+ const offX = px.off;
36045
+ const offY = py.off;
36046
+ const cols = Math.ceil((px.pad + x1 - x0) / grid);
36047
+ const rows = Math.ceil((py.pad + y1 - y0) / grid);
36048
+ const span = { width: cols * grid, height: rows * grid, pixels: Buffer.alloc(cols * grid * rows * grid * 4) };
36049
+ drawLayer(span, layer, px.pad + layer.x - x0, py.pad + layer.y - y0);
36050
+ const file = `${name}-${layer.name}.png`;
36051
+ files.push({ path: path73.join(path73.dirname(base), file), data: encodeRgbaPng(span.width, span.height, span.pixels) });
36052
+ const tilesetUid = uid++;
36053
+ const layerUid = uid++;
36054
+ let identifier2 = layer.name.replace(/[^A-Za-z0-9_]/g, "_");
36055
+ for (let n = 2; identifiers.has(identifier2); n++) identifier2 = `${layer.name.replace(/[^A-Za-z0-9_]/g, "_")}_${n}`;
36056
+ identifiers.add(identifier2);
36057
+ tilesets.push({
36058
+ __cWid: cols,
36059
+ __cHei: rows,
36060
+ identifier: `${identifier2}_tiles`,
36061
+ uid: tilesetUid,
36062
+ relPath: file,
36063
+ embedAtlas: null,
36064
+ pxWid: span.width,
36065
+ pxHei: span.height,
36066
+ tileGridSize: grid,
36067
+ spacing: 0,
36068
+ padding: 0,
36069
+ tags: [],
36070
+ tagsSourceEnumUid: null,
36071
+ enumTags: [],
36072
+ customData: [],
36073
+ savedSelections: [],
36074
+ cachedPixelData: null
36075
+ });
36076
+ layerDefs.push({
36077
+ __type: "Tiles",
36078
+ identifier: identifier2,
36079
+ type: "Tiles",
36080
+ uid: layerUid,
36081
+ doc: `Moves ${layer.speed} of the camera's speed sideways and ${layer.speedY} vertically.`,
36082
+ uiColor: null,
36083
+ gridSize: grid,
36084
+ guideGridWid: 0,
36085
+ guideGridHei: 0,
36086
+ displayOpacity: 1,
36087
+ inactiveOpacity: 1,
36088
+ hideInList: false,
36089
+ hideFieldsWhenInactive: true,
36090
+ canSelectWhenInactive: true,
36091
+ renderInWorldView: true,
36092
+ pxOffsetX: 0,
36093
+ pxOffsetY: 0,
36094
+ parallaxFactorX: Number(factorX.toFixed(6)),
36095
+ parallaxFactorY: Number(factorY.toFixed(6)),
36096
+ parallaxScaling: false,
36097
+ requiredTags: [],
36098
+ excludedTags: [],
36099
+ autoTilesKilledByOtherLayerUid: null,
36100
+ uiFilterTags: [],
36101
+ useAsyncRender: false,
36102
+ intGridValues: [],
36103
+ intGridValuesGroups: [],
36104
+ autoRuleGroups: [],
36105
+ autoSourceLayerDefUid: null,
36106
+ tilesetDefUid: tilesetUid,
36107
+ tilePivotX: 0,
36108
+ tilePivotY: 0,
36109
+ biomeFieldUid: null
36110
+ });
36111
+ const cellsWide = px.cells;
36112
+ const cellsHigh = py.cells;
36113
+ const gridTiles = [];
36114
+ let dropped = 0;
36115
+ for (let r = 0; r < rows; r++) {
36116
+ for (let c = 0; c < cols; c++) {
36117
+ const cx = px.cell + c;
36118
+ const cy = py.cell + r;
36119
+ if (tileEmpty(span, c * grid, r * grid, grid)) continue;
36120
+ if (cx < 0 || cy < 0 || cx >= cellsWide || cy >= cellsHigh) {
36121
+ dropped++;
36122
+ continue;
36123
+ }
36124
+ gridTiles.push({ px: [cx * grid, cy * grid], src: [c * grid, r * grid], f: 0, t: r * cols + c, d: [cy * cellsWide + cx], a: 1 });
36125
+ }
36126
+ }
36127
+ if (dropped) {
36128
+ warnings.push(
36129
+ `${layer.name}: ${dropped} tile(s) fall past the level's edge, which LDtk does not draw` + (layer.speed > 1 || layer.speedY > 1 ? "; a layer faster than the camera shows more than the level holds" : "")
36130
+ );
36131
+ }
36132
+ layerInstances.unshift({
36133
+ __identifier: identifier2,
36134
+ __type: "Tiles",
36135
+ __cWid: cellsWide,
36136
+ __cHei: cellsHigh,
36137
+ __gridSize: grid,
36138
+ __opacity: 1,
36139
+ __pxTotalOffsetX: offX,
36140
+ __pxTotalOffsetY: offY,
36141
+ __tilesetDefUid: tilesetUid,
36142
+ __tilesetRelPath: file,
36143
+ iid: uuid(name, "layer", index),
36144
+ levelId: levelUid,
36145
+ layerDefUid: layerUid,
36146
+ pxOffsetX: offX,
36147
+ pxOffsetY: offY,
36148
+ visible: true,
36149
+ optionalRules: [],
36150
+ intGridCsv: [],
36151
+ autoLayerTiles: [],
36152
+ seed: 1e3 + index,
36153
+ overrideTilesetUid: null,
36154
+ gridTiles,
36155
+ entityInstances: []
36156
+ });
36157
+ }
36158
+ layerDefs.reverse();
36159
+ const project2 = {
36160
+ __header__: {
36161
+ fileType: "LDtk Project JSON",
36162
+ app: "LDtk",
36163
+ doc: "https://ldtk.io/json",
36164
+ schema: "https://ldtk.io/files/JSON_SCHEMA.json",
36165
+ appAuthor: "Sebastien 'deepnight' Benard",
36166
+ appVersion: LDTK_JSON_VERSION,
36167
+ url: "https://ldtk.io"
36168
+ },
36169
+ iid: uuid(name, "project"),
36170
+ jsonVersion: LDTK_JSON_VERSION,
36171
+ appBuildId: 473702,
36172
+ nextUid: Math.max(uid, levelUid + 1),
36173
+ identifierStyle: "Capitalize",
36174
+ toc: [],
36175
+ worldLayout: "Free",
36176
+ worldGridWidth: 256,
36177
+ worldGridHeight: 256,
36178
+ defaultLevelWidth: levelW,
36179
+ defaultLevelHeight: levelH,
36180
+ defaultPivotX: 0,
36181
+ defaultPivotY: 0,
36182
+ defaultGridSize: grid,
36183
+ defaultEntityWidth: grid,
36184
+ defaultEntityHeight: grid,
36185
+ bgColor: "#40465B",
36186
+ defaultLevelBgColor: "#000000",
36187
+ minifyJson: false,
36188
+ externalLevels: false,
36189
+ exportTiled: false,
36190
+ simplifiedExport: false,
36191
+ imageExportMode: "None",
36192
+ exportLevelBg: true,
36193
+ pngFilePattern: null,
36194
+ backupOnSave: false,
36195
+ backupLimit: 10,
36196
+ backupRelPath: null,
36197
+ levelNamePattern: "Level_%idx",
36198
+ tutorialDesc: null,
36199
+ customCommands: [],
36200
+ flags: ["ExportOldTableOfContentData", "UseMultilinesType"],
36201
+ defs: { layers: layerDefs, entities: [], tilesets, enums: [], externalEnums: [], levelFields: [] },
36202
+ levels: [{
36203
+ identifier: "Parallax",
36204
+ iid: uuid(name, "level"),
36205
+ uid: levelUid,
36206
+ worldX: 0,
36207
+ worldY: 0,
36208
+ worldDepth: 0,
36209
+ pxWid: levelW,
36210
+ pxHei: levelH,
36211
+ __bgColor: "#000000",
36212
+ bgColor: null,
36213
+ useAutoIdentifier: false,
36214
+ bgRelPath: null,
36215
+ bgPos: null,
36216
+ bgPivotX: 0.5,
36217
+ bgPivotY: 0.5,
36218
+ __smartColor: "#ADADB5",
36219
+ __bgPos: null,
36220
+ externalRelPath: null,
36221
+ fieldInstances: [],
36222
+ layerInstances,
36223
+ __neighbours: []
36224
+ }],
36225
+ worlds: [],
36226
+ dummyWorldIid: uuid(name, "world")
36227
+ };
36228
+ return {
36229
+ files: [{ path: `${base}.ldtk`, data: JSON.stringify(project2, null, 2) + "\n" }, ...files],
36230
+ options: { format: "ldtk", grid, start: [0, set.climb], warnings }
36231
+ };
36232
+ }
36233
+ function tileEmpty(png, x0, y0, grid) {
36234
+ for (let y = y0; y < y0 + grid; y++) {
36235
+ for (let x = x0; x < x0 + grid; x++) {
36236
+ if (png.pixels[(y * png.width + x) * 4 + 3] !== 0) return false;
36237
+ }
36238
+ }
36239
+ return true;
36240
+ }
36241
+ function exportParallax(set, format, base) {
36242
+ if (format === "tiled") return exportTiled(set, base);
36243
+ if (format === "godot") return exportGodot(set, base);
36244
+ return exportLdtk(set, base);
36245
+ }
36246
+ function previewHtml(set, scale2 = 3) {
36247
+ const [vw, vh] = set.view;
36248
+ const layers = set.layers.map((layer) => ({
36249
+ name: layer.name,
36250
+ src: `data:image/png;base64,${encodeRgbaPng(layer.png.width, layer.png.height, layer.png.pixels).toString("base64")}`,
36251
+ w: layer.png.width,
36252
+ h: layer.png.height,
36253
+ x: layer.x,
36254
+ y: layer.y,
36255
+ speed: layer.speed,
36256
+ speedY: layer.speedY,
36257
+ repeat: layer.repeat,
36258
+ repeatY: layer.repeatY
36259
+ }));
36260
+ const data = JSON.stringify({ view: [vw, vh], travel: set.travel, climb: set.climb, layers }).replace(/</g, "\\u003c");
36261
+ return `<!doctype html>
36262
+ <html lang="en">
36263
+ <head>
36264
+ <meta charset="utf-8">
36265
+ <meta name="viewport" content="width=device-width, initial-scale=1">
36266
+ <title>${set.id.replace(/[&<>"]/g, (c) => `&#${c.charCodeAt(0)};`)} parallax</title>
36267
+ <style>
36268
+ :root { color-scheme: dark; }
36269
+ body { margin: 0; background: #111318; color: #d8dae0; font: 14px/1.4 system-ui, sans-serif; display: grid; place-items: center; min-height: 100vh; }
36270
+ main { display: grid; gap: 12px; padding: 16px; max-width: 100%; }
36271
+ canvas { image-rendering: pixelated; width: ${vw * scale2}px; max-width: 100%; height: auto; background: #000; }
36272
+ label { display: flex; gap: 8px; align-items: center; }
36273
+ input[type=range] { flex: 1; }
36274
+ table { border-collapse: collapse; font-variant-numeric: tabular-nums; }
36275
+ td, th { padding: 2px 10px 2px 0; text-align: left; }
36276
+ </style>
36277
+ </head>
36278
+ <body>
36279
+ <main>
36280
+ <canvas id="view" width="${vw}" height="${vh}"></canvas>
36281
+ <label><button id="play" type="button">Pause</button> camera <input id="cam" type="range" min="0" max="1000" value="0"> <output id="pos"></output></label>
36282
+ <table><thead><tr><th>Layer</th><th>speed</th><th>speedY</th><th>repeat</th></tr></thead><tbody id="rows"></tbody></table>
36283
+ </main>
36284
+ <script>
36285
+ const set = ${data};
36286
+ const ctx = document.getElementById("view").getContext("2d");
36287
+ ctx.imageSmoothingEnabled = false;
36288
+ const images = set.layers.map((layer) => Object.assign(new Image(), { src: layer.src }));
36289
+ const rows = document.getElementById("rows");
36290
+ for (const layer of set.layers) {
36291
+ const tr = rows.insertRow();
36292
+ for (const value of [layer.name, layer.speed, layer.speedY, [layer.repeat && "x", layer.repeatY && "y"].filter(Boolean).join(" ") || "no"]) tr.insertCell().textContent = value;
36293
+ }
36294
+ const slider = document.getElementById("cam");
36295
+ const pos = document.getElementById("pos");
36296
+ let playing = true;
36297
+ let t0 = performance.now();
36298
+ document.getElementById("play").onclick = (event) => {
36299
+ playing = !playing;
36300
+ event.target.textContent = playing ? "Pause" : "Play";
36301
+ t0 = performance.now() - (slider.value / 1000) * 6000;
36302
+ };
36303
+ slider.oninput = () => { playing = false; document.getElementById("play").textContent = "Play"; };
36304
+ function draw(u) {
36305
+ const e = (1 - Math.cos(u * Math.PI)) / 2;
36306
+ const camX = Math.round(e * set.travel);
36307
+ const camY = Math.round(e * set.climb);
36308
+ pos.textContent = camX + ", " + camY;
36309
+ ctx.clearRect(0, 0, set.view[0], set.view[1]);
36310
+ set.layers.forEach((layer, i) => {
36311
+ const left = layer.x + Math.round(-camX * layer.speed);
36312
+ const top = layer.y + Math.round(camY * layer.speedY);
36313
+ const xs = layer.repeat ? [] : [left];
36314
+ if (layer.repeat) for (let x = ((left % layer.w) + layer.w) % layer.w - layer.w; x < set.view[0]; x += layer.w) xs.push(x);
36315
+ const ys = layer.repeatY ? [] : [top];
36316
+ if (layer.repeatY) for (let y = ((top % layer.h) + layer.h) % layer.h - layer.h; y < set.view[1]; y += layer.h) ys.push(y);
36317
+ for (const y of ys) for (const x of xs) ctx.drawImage(images[i], x, y);
36318
+ });
36319
+ }
36320
+ function frame(now) {
36321
+ if (playing) {
36322
+ const u = ((now - t0) % 12000) / 6000;
36323
+ const v = u <= 1 ? u : 2 - u;
36324
+ slider.value = Math.round(v * 1000);
36325
+ }
36326
+ draw(slider.value / 1000);
36327
+ requestAnimationFrame(frame);
36328
+ }
36329
+ Promise.all(images.map((image) => image.decode())).then(() => requestAnimationFrame(frame));
36330
+ </script>
36331
+ </body>
36332
+ </html>
36333
+ `;
36334
+ }
36335
+
36336
+ // src/cli/commands/parallax.ts
36337
+ async function runParallax(args) {
36338
+ const { loaded, lock } = await openProject2(args);
36339
+ const manifestDir = path74.dirname(path74.resolve(args.manifest));
36340
+ const ids = Object.keys(loaded.manifest.parallax ?? {});
36341
+ if (!ids.length) throw new Error('The manifest has no parallax sets. Add one under "parallax"; see docs/PARALLAX.md.');
36342
+ const wanted = args.target ? [args.target] : ids;
36343
+ if (args.out && wanted.length > 1) {
36344
+ throw new Error(`--out names one set; this manifest has ${ids.length} (${ids.join(", ")}). Name the set: pixelkiln parallax ${args.subcommand} <set>`);
36345
+ }
36346
+ for (const id of wanted) {
36347
+ const set = await resolveParallaxSet(loaded.manifest, manifestDir, lock, id);
36348
+ const root = path74.resolve(args.out ?? path74.join(manifestDir, "parallax", id));
36349
+ const sources = [
36350
+ await provenanceFile("$manifest", args.manifest),
36351
+ await provenanceFile("$lock", args.lock),
36352
+ ...await Promise.all(
36353
+ set.layers.flatMap(
36354
+ (layer) => layerFiles(layer).map((file, n, all) => provenanceFile(all.length > 1 || layer.source.kind === "run" ? `layer:${layer.name}:${n + 1}` : `layer:${layer.name}`, file))
36355
+ )
36356
+ )
36357
+ ];
36358
+ const describe2 = setOptions(set);
36359
+ if (args.subcommand === "export") {
36360
+ const formats = args.format ? [args.format] : [...PARALLAX_FORMATS];
36361
+ for (const format of formats) {
36362
+ const base = path74.join(root, format, id);
36363
+ const result = exportParallax(set, format, base);
36364
+ const outputs = result.files.map((file) => ({ path: file.path, data: typeof file.data === "string" ? Buffer.from(file.data) : file.data }));
36365
+ await writeManagedArtifactBundle(`${base}.pixelkiln.json`, outputs, {
36366
+ kind: "parallax",
36367
+ sources,
36368
+ options: { set: id, ...describe2, ...result.options }
36369
+ }, { force: args.force });
36370
+ log(` ${id} (${format}): ${path74.relative(process.cwd(), result.files[0].path)} + ${result.files.length - 1} picture(s)`);
36371
+ for (const warning of result.options.warnings ?? []) log(` warning: ${warning}`);
36372
+ }
36373
+ } else {
36374
+ const frames = args.frames ?? 3;
36375
+ const strip = joinStripPng(
36376
+ cameraPath(set, frames).map(([x, y]) => {
36377
+ const frame = composeParallaxFrame(set, x, y);
36378
+ return encodeRgbaPng(frame.width, frame.height, frame.pixels);
36379
+ })
36380
+ );
36381
+ const base = path74.join(root, `${id}.preview`);
36382
+ await writeManagedArtifactBundle(`${base}.pixelkiln.json`, [
36383
+ { path: `${base}.html`, data: Buffer.from(previewHtml(set)) },
36384
+ { path: `${base}.png`, data: strip }
36385
+ ], {
36386
+ kind: "parallax",
36387
+ sources,
36388
+ options: { set: id, ...describe2, preview: { frames } }
36389
+ }, { force: args.force });
36390
+ log(` ${id}: ${path74.relative(process.cwd(), base)}.html (scrolls in a browser) + .png (${frames} frames, start to end)`);
36391
+ }
36392
+ for (const layer of set.layers) {
36393
+ const seam = (layer.seamRatio === void 0 ? "" : `, seam ${layer.seamRatio.toFixed(1)}`) + (layer.seamRatioY === void 0 ? "" : `, vertical seam ${layer.seamRatioY.toFixed(1)}`);
36394
+ log(` ${layer.name}: ${layer.png.width}x${layer.png.height} at ${layer.x},${layer.y}, speed ${layer.speed}/${layer.speedY}${seam}`);
36395
+ }
36396
+ for (const warning of set.warnings) log(` warning: ${warning}`);
36397
+ }
36398
+ }
36399
+ function setOptions(set) {
36400
+ return {
36401
+ view: set.view,
36402
+ travel: set.travel,
36403
+ climb: set.climb,
36404
+ layers: set.layers.map((layer) => ({
36405
+ name: layer.name,
36406
+ speed: layer.speed,
36407
+ speedY: layer.speedY,
36408
+ x: layer.x,
36409
+ y: layer.y,
36410
+ repeat: layer.repeat,
36411
+ repeatY: layer.repeatY,
36412
+ ...layer.source.kind === "sky" ? { sky: layer.source.colors } : {},
36413
+ ...layer.source.kind === "run" ? { run: { seed: layer.source.seed, sprites: layer.source.sprites.length, width: layer.png.width } } : {}
36414
+ }))
36415
+ };
36416
+ }
36417
+
36418
+ // src/cli/commands/redraw.ts
36419
+ import path76 from "path";
36420
+
35507
36421
  // src/pipeline/redraw.ts
35508
36422
  import { existsSync as existsSync56 } from "fs";
35509
- import { mkdir as mkdir26, readFile as readFile50, rename as rename15, writeFile as writeFile31 } from "fs/promises";
35510
- import path73 from "path";
36423
+ import { mkdir as mkdir26, readFile as readFile51, rename as rename15, writeFile as writeFile31 } from "fs/promises";
36424
+ import path75 from "path";
35511
36425
  function redrawRoles(spec, lock) {
35512
36426
  return (lock.entries[lockKey(spec.styleId, spec.assetId)]?.outputs ?? []).map((output) => output.role ?? "");
35513
36427
  }
@@ -35549,7 +36463,7 @@ async function redrawLayerFrames(spec, lock, painter, opts) {
35549
36463
  const still = source.spec.character?.kind !== "animation";
35550
36464
  for (const [index, output] of sourceEntry.outputs.entries()) {
35551
36465
  if (!still && !owners.includes(source.assetId)) continue;
35552
- const png = await readFile50(currentEntryOutputPath(sourceEntry, source.spec, index));
36466
+ const png = await readFile51(currentEntryOutputPath(sourceEntry, source.spec, index));
35553
36467
  if (still) stills.push(png);
35554
36468
  if (!owners.includes(source.assetId)) continue;
35555
36469
  const role = output.role ?? String(index).padStart(2, "0");
@@ -35588,18 +36502,18 @@ async function redrawLayerFrames(spec, lock, painter, opts) {
35588
36502
  continue;
35589
36503
  }
35590
36504
  const pair = offset?.per && offset.per[source.assetId] || offset;
35591
- const png = await readFile50(file);
36505
+ const png = await readFile51(file);
35592
36506
  layers.push(pair ? shiftPixels(png, -pair.x, -pair.y).png : png);
35593
36507
  }
35594
36508
  const prepared = redrawSheet(built, layers, redraw);
35595
36509
  const size = decodePng(prepared.keyed);
35596
36510
  const cost = proTierCost(size.width, size.height);
35597
- const workDir = path73.join(layerWorkDir(spec), "redraw");
36511
+ const workDir = path75.join(layerWorkDir(spec), "redraw");
35598
36512
  const result = { roles, guides, sheet: { width: size.width, height: size.height }, cost, billed: null, written: [], workDir };
35599
36513
  if (opts.dryRun) return result;
35600
36514
  await mkdir26(workDir, { recursive: true });
35601
- await writeFile31(path73.join(workDir, "keyed.png"), prepared.keyed);
35602
- await writeFile31(path73.join(workDir, "mask.png"), prepared.mask);
36515
+ await writeFile31(path75.join(workDir, "keyed.png"), prepared.keyed);
36516
+ await writeFile31(path75.join(workDir, "mask.png"), prepared.mask);
35603
36517
  const count = roles.length;
35604
36518
  const description = `${spec.prompt}. Every figure but ${count === 1 ? "one" : count} already wears it. Dress the unfinished figure${count === 1 ? "" : "s"} in exactly the same thing, the same colours and details, seen from the side ${count === 1 ? "that figure faces" : "each of those figures faces"}.`;
35605
36519
  const jobId = await painter.paintSheet({ description, keyed: prepared.keyed, mask: prepared.mask, seed: opts.seed ?? spec.seed });
@@ -35617,13 +36531,13 @@ async function redrawLayerFrames(spec, lock, painter, opts) {
35617
36531
  if (Date.now() > deadline) throw new Error(`${label}: redraw job ${jobId} did not finish in time; nothing was changed`);
35618
36532
  await new Promise((resolve) => setTimeout(resolve, opts.pollMs ?? 3e3));
35619
36533
  }
35620
- await writeFile31(path73.join(workDir, "result.png"), painted);
36534
+ await writeFile31(path75.join(workDir, "result.png"), painted);
35621
36535
  const returned = decodePng(painted);
35622
36536
  if (returned.width !== size.width || returned.height !== size.height) {
35623
36537
  throw new Error(`${label}: redraw job ${jobId} returned a ${returned.width}x${returned.height} image for a ${size.width}x${size.height} sheet`);
35624
36538
  }
35625
36539
  const cut = cutLayerFrames(painted, { keyed: prepared.keyed, mask: prepared.mask, frames: built.frames }, { key: layer.key, region: layer.region });
35626
- const cacheDir = path73.resolve(opts.cacheDir ?? path73.join(path73.dirname(opts.lockPath), ".pixelkiln", "cache"));
36540
+ const cacheDir = path75.resolve(opts.cacheDir ?? path75.join(path75.dirname(opts.lockPath), ".pixelkiln", "cache"));
35627
36541
  const outputs = [...entry.outputs];
35628
36542
  const renames = [];
35629
36543
  for (const [index, at2] of targets) {
@@ -35632,7 +36546,7 @@ async function redrawLayerFrames(spec, lock, painter, opts) {
35632
36546
  const empty = !decodePng(raw).pixels.some((value, i) => i % 4 === 3 && value > 0);
35633
36547
  if (empty) throw new Error(`${label}: the redraw of ${role} came back with nothing drawn; nothing was changed. Run it again, or with another --seed`);
35634
36548
  const target = currentEntryOutputPath(entry, spec, at2);
35635
- if (existsSync56(target)) await cacheMedia(cacheDir, await readFile50(target), MediaType.PNG);
36549
+ if (existsSync56(target)) await cacheMedia(cacheDir, await readFile51(target), MediaType.PNG);
35636
36550
  await cacheMedia(cacheDir, raw, MediaType.PNG);
35637
36551
  const processed = applyPostprocess(raw, MediaType.PNG, entry.postprocess, [], role);
35638
36552
  await cacheMedia(cacheDir, processed.bytes, MediaType.PNG);
@@ -35681,7 +36595,7 @@ async function runRedraw(args) {
35681
36595
  const painter = args.dryRun ? { paintSheet: never, paintedSheet: never } : new PixelLabProvider(clientFromEnv());
35682
36596
  const result = await redrawLayerFrames(spec, project2.lock, painter, {
35683
36597
  frames: args.redrawFrames,
35684
- lockPath: path74.resolve(args.lock),
36598
+ lockPath: path76.resolve(args.lock),
35685
36599
  seed: args.seed,
35686
36600
  dryRun: args.dryRun,
35687
36601
  onProgress: log
@@ -35692,16 +36606,16 @@ async function runRedraw(args) {
35692
36606
  log(` would redraw ${frames} (${result.roles.join(", ")}) beside ${result.guides} dressed, on a ${sheet} sheet: about ${result.cost} generations`);
35693
36607
  return;
35694
36608
  }
35695
- for (const file of result.written) log(` wrote ${path74.relative(process.cwd(), file)}`);
36609
+ for (const file of result.written) log(` wrote ${path76.relative(process.cwd(), file)}`);
35696
36610
  const billed = result.billed ? `${result.billed.amount} ${result.billed.unit} billed` : `about ${result.cost} generations`;
35697
- log(` redrew ${frames} of ${target} (${billed}); the sheet and result are in ${path74.relative(process.cwd(), result.workDir)}`);
36611
+ log(` redrew ${frames} of ${target} (${billed}); the sheet and result are in ${path76.relative(process.cwd(), result.workDir)}`);
35698
36612
  log(` look at ${result.written.length === 1 ? "it" : "them"}, then run pixelkiln gen to rebuild anything made from this layer`);
35699
36613
  }
35700
36614
 
35701
36615
  // src/cli/commands/skeleton.ts
35702
- import path75 from "path";
36616
+ import path77 from "path";
35703
36617
  import { existsSync as existsSync57 } from "fs";
35704
- import { readFile as readFile51, writeFile as writeFile32 } from "fs/promises";
36618
+ import { readFile as readFile52, writeFile as writeFile32 } from "fs/promises";
35705
36619
 
35706
36620
  // src/skeleton-preview.ts
35707
36621
  var RIGHT = [255, 140, 40, 255];
@@ -35822,12 +36736,12 @@ var Canvas = class {
35822
36736
  async function runEstimateSkeleton(args) {
35823
36737
  const image = args.target;
35824
36738
  if (!image) throw new UsageError("estimate-skeleton needs an image path: pixelkiln estimate-skeleton <image> [--out keypoints.json]");
35825
- if (args.out && existsSync57(path75.resolve(args.out)) && !args.force) {
36739
+ if (args.out && existsSync57(path77.resolve(args.out)) && !args.force) {
35826
36740
  throw new UsageError(`${args.out} already exists; pass --force to replace it`);
35827
36741
  }
35828
- loadEnvFiles(path75.dirname(path75.resolve(args.manifest)));
36742
+ loadEnvFiles(path77.dirname(path77.resolve(args.manifest)));
35829
36743
  loadEnvFiles(process.cwd());
35830
- const bytes = await readFile51(path75.resolve(image));
36744
+ const bytes = await readFile52(path77.resolve(image));
35831
36745
  const metadata = imageMetadata(bytes);
35832
36746
  if (!metadata) throw new UsageError(`${image} is not a readable PNG or JPEG`);
35833
36747
  if (args.custom) return estimateCustom(args, image, bytes, metadata);
@@ -35840,7 +36754,7 @@ async function runEstimateSkeleton(args) {
35840
36754
  const frames = args.frames ?? DEFAULT_SCAFFOLD_FRAMES;
35841
36755
  const json2 = JSON.stringify(scaffoldSkeletonSet(res.keypoints, frames), null, 2);
35842
36756
  if (args.out) {
35843
- await writeFile32(path75.resolve(args.out), json2 + "\n");
36757
+ await writeFile32(path77.resolve(args.out), json2 + "\n");
35844
36758
  log(` wrote ${args.out}: the estimated pose and ${frames} frames to edit`);
35845
36759
  log(` preview it with: pixelkiln skeleton-preview ${args.out} --from ${image}`);
35846
36760
  } else {
@@ -35875,7 +36789,7 @@ async function estimateCustom(args, image, bytes, metadata) {
35875
36789
  const json2 = JSON.stringify(scaffoldSkeletonSet(res.keypoints, frames, { rig: res.rig, kind: res.kind }), null, 2);
35876
36790
  const extra = res.rig.filter((joint) => !joint.estimate).map((joint) => joint.name);
35877
36791
  if (args.out) {
35878
- await writeFile32(path75.resolve(args.out), json2 + "\n");
36792
+ await writeFile32(path77.resolve(args.out), json2 + "\n");
35879
36793
  log(` wrote ${args.out}: a ${res.kind ?? "custom"} rig of ${res.rig.length} joints and ${frames} frames to edit`);
35880
36794
  if (extra.length) log(` joints beyond the 18: ${extra.slice(0, 12).join(", ")}${extra.length > 12 ? ", \u2026" : ""}`);
35881
36795
  log(` preview it with: pixelkiln skeleton-preview ${args.out} --from ${image}`);
@@ -35889,8 +36803,8 @@ async function runSkeletonPreview(args) {
35889
36803
  let sourceFile;
35890
36804
  let label;
35891
36805
  if (target.endsWith(".json")) {
35892
- keypointsFile = path75.resolve(target);
35893
- sourceFile = args.from ? path75.resolve(args.from) : void 0;
36806
+ keypointsFile = path77.resolve(target);
36807
+ sourceFile = args.from ? path77.resolve(args.from) : void 0;
35894
36808
  label = target;
35895
36809
  } else {
35896
36810
  const loaded = await loadManifest(args.manifest);
@@ -35902,13 +36816,13 @@ async function runSkeletonPreview(args) {
35902
36816
  );
35903
36817
  }
35904
36818
  keypointsFile = spec.revision.keypointsFile;
35905
- sourceFile = args.from ? path75.resolve(args.from) : spec.revision.sourceFile;
36819
+ sourceFile = args.from ? path77.resolve(args.from) : spec.revision.sourceFile;
35906
36820
  label = `${spec.styleId}/${spec.assetId}`;
35907
36821
  }
35908
36822
  if (!existsSync57(keypointsFile)) throw new UsageError(`Keypoints file does not exist yet: ${keypointsFile}`);
35909
36823
  let json2;
35910
36824
  try {
35911
- json2 = JSON.parse(await readFile51(keypointsFile, "utf8"));
36825
+ json2 = JSON.parse(await readFile52(keypointsFile, "utf8"));
35912
36826
  } catch (error) {
35913
36827
  throw new UsageError(`${keypointsFile} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
35914
36828
  }
@@ -35918,15 +36832,15 @@ async function runSkeletonPreview(args) {
35918
36832
  if (!existsSync57(sourceFile)) {
35919
36833
  log(` source image does not exist yet, drawing on a plain ground: ${sourceFile}`);
35920
36834
  } else {
35921
- const bytes = await readFile51(sourceFile);
36835
+ const bytes = await readFile52(sourceFile);
35922
36836
  if (imageMetadata(bytes)?.format !== "png") throw new UsageError(`${sourceFile} must be a PNG to preview over`);
35923
36837
  source = decodePng(bytes);
35924
36838
  }
35925
36839
  }
35926
- const out = path75.resolve(args.out ?? keypointsFile.replace(/\.json$/, "") + ".preview.png");
36840
+ const out = path77.resolve(args.out ?? keypointsFile.replace(/\.json$/, "") + ".preview.png");
35927
36841
  await writeFile32(out, renderSkeletonSheet(set, { source }));
35928
36842
  log(` ${label}: ${set.frames.length} frames after the starting pose`);
35929
- const shown2 = path75.relative(process.cwd(), out);
36843
+ const shown2 = path77.relative(process.cwd(), out);
35930
36844
  log(` wrote ${shown2.startsWith("..") ? out : shown2}`);
35931
36845
  }
35932
36846
 
@@ -35972,15 +36886,15 @@ async function runTools(args) {
35972
36886
  }
35973
36887
 
35974
36888
  // src/cli/commands/workspace.ts
35975
- import path76 from "path";
36889
+ import path78 from "path";
35976
36890
  import { existsSync as existsSync58 } from "fs";
35977
36891
  async function runWorkspace(args) {
35978
- const workspacePath = path76.resolve(args.workspace ?? "pixelkiln.workspace.json");
35979
- const dir = path76.dirname(workspacePath);
36892
+ const workspacePath = path78.resolve(args.workspace ?? "pixelkiln.workspace.json");
36893
+ const dir = path78.dirname(workspacePath);
35980
36894
  if (args.subcommand === "add") {
35981
- const manifestPath = path76.resolve(args.target);
36895
+ const manifestPath = path78.resolve(args.target);
35982
36896
  const loadedTarget = await loadManifest(manifestPath);
35983
- const lockPath = args.explicitLock ? path76.resolve(args.explicitLock) : path76.join(path76.dirname(manifestPath), "pixelkiln.lock.json");
36897
+ const lockPath = args.explicitLock ? path78.resolve(args.explicitLock) : path78.join(path78.dirname(manifestPath), "pixelkiln.lock.json");
35984
36898
  const ws = await loadWorkspace(workspacePath);
35985
36899
  const id = args.name ?? loadedTarget.manifest.name;
35986
36900
  if (ws.projects.some((p) => p.id === id)) {
@@ -36000,7 +36914,7 @@ async function runWorkspace(args) {
36000
36914
  ...args.account ? { account: args.account } : {}
36001
36915
  };
36002
36916
  await saveWorkspace(workspacePath, { version: 1, projects: [...ws.projects, project2] });
36003
- log(` registered "${id}" in ${path76.relative(process.cwd(), workspacePath)}`);
36917
+ log(` registered "${id}" in ${path78.relative(process.cwd(), workspacePath)}`);
36004
36918
  log(` manifest: ${project2.manifest}`);
36005
36919
  log(` lock: ${project2.lock}`);
36006
36920
  if (!existsSync58(lockPath)) {
@@ -36012,7 +36926,7 @@ async function runWorkspace(args) {
36012
36926
  }
36013
36927
  if (args.subcommand === "remove") {
36014
36928
  const ws = await loadWorkspace(workspacePath);
36015
- const resolvedTarget = path76.resolve(args.target);
36929
+ const resolvedTarget = path78.resolve(args.target);
36016
36930
  const match = ws.projects.find(
36017
36931
  (p) => p.id === args.target || resolveProject(dir, p).manifestPath === resolvedTarget
36018
36932
  );
@@ -36023,7 +36937,7 @@ async function runWorkspace(args) {
36023
36937
  version: 1,
36024
36938
  projects: ws.projects.filter((p) => p !== match)
36025
36939
  });
36026
- log(` removed "${match.id}" from ${path76.relative(process.cwd(), workspacePath)}`);
36940
+ log(` removed "${match.id}" from ${path78.relative(process.cwd(), workspacePath)}`);
36027
36941
  return;
36028
36942
  }
36029
36943
  if (args.subcommand === "list") {
@@ -36035,9 +36949,9 @@ async function runWorkspace(args) {
36035
36949
  if (args.json) {
36036
36950
  log(JSON.stringify({ version: 1, workspace: workspacePath, projects: ws.projects, diagnostics }, null, 2));
36037
36951
  } else if (!ws.projects.length) {
36038
- log(` no projects registered in ${path76.relative(process.cwd(), workspacePath)}`);
36952
+ log(` no projects registered in ${path78.relative(process.cwd(), workspacePath)}`);
36039
36953
  } else {
36040
- log(` ${ws.projects.length} project(s) in ${path76.relative(process.cwd(), workspacePath)}:`);
36954
+ log(` ${ws.projects.length} project(s) in ${path78.relative(process.cwd(), workspacePath)}:`);
36041
36955
  for (const p of ws.projects) {
36042
36956
  log(` ${p.id.padEnd(24)} ${p.manifest.padEnd(40)} (${p.provider}${p.account ? `, ${p.account}` : ""})`);
36043
36957
  }
@@ -36055,7 +36969,7 @@ async function runWorkspace(args) {
36055
36969
  if (args.json) {
36056
36970
  log(JSON.stringify({ ...report, workspace: workspacePath }, null, 2));
36057
36971
  } else {
36058
- log(` workspace: ${path76.relative(process.cwd(), workspacePath)}`);
36972
+ log(` workspace: ${path78.relative(process.cwd(), workspacePath)}`);
36059
36973
  for (const p of report.projects) {
36060
36974
  if (p.error) {
36061
36975
  log(`
@@ -36110,7 +37024,7 @@ async function runVersion() {
36110
37024
  for (const up of ["../package.json", "../../package.json"]) {
36111
37025
  const url = new URL(up, import.meta.url);
36112
37026
  if (!existsSync59(url)) continue;
36113
- const pkg = JSON.parse(await readFile52(url, "utf8"));
37027
+ const pkg = JSON.parse(await readFile53(url, "utf8"));
36114
37028
  if (pkg.name === "pixelkiln") {
36115
37029
  log(`${pkg.name} ${pkg.version}`);
36116
37030
  return;
@@ -36169,7 +37083,8 @@ var RUNNERS = {
36169
37083
  sfx: runSfx,
36170
37084
  ui: runUi,
36171
37085
  asset: runAsset,
36172
- talk: runTalk
37086
+ talk: runTalk,
37087
+ parallax: runParallax
36173
37088
  };
36174
37089
  async function main(argv = process.argv.slice(2)) {
36175
37090
  const args = parseArgs(argv);