@i7r.tech/moveby 0.0.21-ywc → 0.21.1-ywc

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/bin/moveby.js CHANGED
@@ -7278,7 +7278,30 @@ var atlas_schema_default = {
7278
7278
  cols: { type: "integer", minimum: 1, maximum: 65536 },
7279
7279
  rows: { type: "integer", minimum: 1, maximum: 65536 },
7280
7280
  pxWidth: { type: "integer", minimum: 1, maximum: 4294967295 },
7281
- pxHeight: { type: "integer", minimum: 1, maximum: 4294967295 }
7281
+ pxHeight: { type: "integer", minimum: 1, maximum: 4294967295 },
7282
+ cells: {
7283
+ type: "array",
7284
+ items: { $ref: "#/$defs/cell" },
7285
+ description: "The images that the build packs into this atlas, one per entry. With this key, `moveby build` writes the atlas image itself, `pxWidth` by `pxHeight` pixels, beside the track: `sprites.png` for `sprites`, `fields.png` for `fields`. A cell with no entry is transparent. A cell is a whole number of pixels: `pxWidth` is a multiple of `cols`, and `pxHeight` of `rows`. Neither side of an atlas that the build writes is past 16384 pixels."
7286
+ }
7287
+ }
7288
+ },
7289
+ cell: {
7290
+ description: "One image in one cell of an atlas.",
7291
+ type: "object",
7292
+ additionalProperties: false,
7293
+ required: ["cell", "image"],
7294
+ properties: {
7295
+ cell: {
7296
+ type: "integer",
7297
+ minimum: 0,
7298
+ description: "The number of the cell, counted from 0, row by row from the top left. It is the number that `asset()` and road.json take. Each cell has one entry at most."
7299
+ },
7300
+ image: {
7301
+ type: "string",
7302
+ minLength: 1,
7303
+ description: "A PNG file with 8 bits per channel, not interlaced. The path is relative to the folder of this file. The image scales to fit the cell, keeps its aspect, and sits at the bottom centre. An image of `fields` has the aspect of its cell, because the ground is opaque."
7304
+ }
7282
7305
  }
7283
7306
  }
7284
7307
  }
@@ -7392,8 +7415,38 @@ function readAtlas(json) {
7392
7415
  throw new AtlasError("ATLAS_SCHEMA", fault.path, fault.message);
7393
7416
  }
7394
7417
  const { sprites, fields, font } = json;
7418
+ checkCells("sprites", sprites);
7419
+ checkCells("fields", fields);
7395
7420
  return { sprites, fields, font };
7396
7421
  }
7422
+ var MAX_SHEET_SIDE = 16384;
7423
+ function checkCells(name, grid) {
7424
+ if (grid?.cells === undefined)
7425
+ return;
7426
+ const { cols, rows, pxWidth, pxHeight, cells } = grid;
7427
+ for (const [key, side] of Object.entries({ pxWidth, pxHeight })) {
7428
+ if (side > MAX_SHEET_SIDE) {
7429
+ throw new AtlasError("ATLAS_CELLS", `/${name}/${key}`, `${key} ${side} is past ${MAX_SHEET_SIDE}, the longest side of an atlas that the build writes`);
7430
+ }
7431
+ }
7432
+ const entryOfCell = new Map;
7433
+ for (const [index, { cell }] of cells.entries()) {
7434
+ const fail = (message) => {
7435
+ throw new AtlasError("ATLAS_CELLS", `/${name}/cells/${index}`, message);
7436
+ };
7437
+ if (pxWidth % cols !== 0)
7438
+ fail(`pxWidth ${pxWidth} is not a multiple of cols ${cols}`);
7439
+ if (pxHeight % rows !== 0)
7440
+ fail(`pxHeight ${pxHeight} is not a multiple of rows ${rows}`);
7441
+ if (cell >= cols * rows) {
7442
+ fail(`names cell ${cell}: a grid of ${cols} × ${rows} has the cells 0 to ${cols * rows - 1}`);
7443
+ }
7444
+ const first = entryOfCell.get(cell);
7445
+ if (first !== undefined)
7446
+ fail(`names cell ${cell}, which entry ${first} already holds`);
7447
+ entryOfCell.set(cell, index);
7448
+ }
7449
+ }
7397
7450
  function readFont(json) {
7398
7451
  const fault = shapeFault(validateFont, json, "does not match font.schema.json");
7399
7452
  if (fault) {
@@ -7417,6 +7470,317 @@ function encodeTrack(road, parts) {
7417
7470
  return encode_track_bytes(road.route, road.laneRecords, road.fieldRecords, fields.cols, fields.rows, fields.pxWidth, fields.pxHeight, gridNumbers(parts.sprites), parts.font ?? new Float32Array);
7418
7471
  }
7419
7472
 
7473
+ // ../moveby-build/src/png.ts
7474
+ import { deflateSync, inflateSync } from "node:zlib";
7475
+
7476
+ class PngError extends Error {
7477
+ code = "ATLAS_IMAGE";
7478
+ constructor(message) {
7479
+ super(message);
7480
+ this.name = "PngError";
7481
+ }
7482
+ }
7483
+ var SIGNATURE = Uint8Array.of(137, 80, 78, 71, 13, 10, 26, 10);
7484
+ var GREY = 0;
7485
+ var TRUECOLOUR = 2;
7486
+ var INDEXED = 3;
7487
+ var GREY_ALPHA = 4;
7488
+ var TRUECOLOUR_ALPHA = 6;
7489
+ var BYTES_PER_PIXEL = new Map([
7490
+ [GREY, 1],
7491
+ [TRUECOLOUR, 3],
7492
+ [INDEXED, 1],
7493
+ [GREY_ALPHA, 2],
7494
+ [TRUECOLOUR_ALPHA, 4]
7495
+ ]);
7496
+ function decodePng(bytes) {
7497
+ const { header, palette, transparency, data } = readChunks(bytes);
7498
+ const { width, height, colourType, bytesPerPixel } = readHeader(header);
7499
+ const rowBytes = width * bytesPerPixel;
7500
+ const filtered = inflate(Buffer.concat(data));
7501
+ if (filtered.length !== height * (rowBytes + 1)) {
7502
+ throw new PngError(`holds ${filtered.length} bytes of image data, not the ${height * (rowBytes + 1)} that its size needs`);
7503
+ }
7504
+ const samples = unfilter(filtered, height, rowBytes, bytesPerPixel);
7505
+ return { width, height, rgba: toRgba(samples, colourType, palette, transparency) };
7506
+ }
7507
+ function readChunks(bytes) {
7508
+ if (SIGNATURE.some((byte, at2) => bytes[at2] !== byte)) {
7509
+ throw new PngError("is not a PNG file");
7510
+ }
7511
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
7512
+ let header;
7513
+ let palette;
7514
+ let transparency;
7515
+ const data = [];
7516
+ let at = SIGNATURE.length;
7517
+ for (;; ) {
7518
+ if (at + 12 > bytes.length)
7519
+ throw new PngError("ends before its IEND chunk");
7520
+ const length = view.getUint32(at);
7521
+ const type = String.fromCharCode(...bytes.subarray(at + 4, at + 8));
7522
+ const end = at + 8 + length;
7523
+ if (end + 4 > bytes.length)
7524
+ throw new PngError(`ends inside its ${type} chunk`);
7525
+ const body = bytes.subarray(at + 8, end);
7526
+ if (header === undefined) {
7527
+ if (type !== "IHDR")
7528
+ throw new PngError(`starts with a ${type} chunk, not IHDR`);
7529
+ header = body;
7530
+ } else if (type === "IEND") {
7531
+ return { header, palette, transparency, data };
7532
+ } else if (type === "PLTE") {
7533
+ palette = body;
7534
+ } else if (type === "tRNS") {
7535
+ transparency = body;
7536
+ } else if (type === "IDAT") {
7537
+ data.push(body);
7538
+ }
7539
+ at = end + 4;
7540
+ }
7541
+ }
7542
+ function readHeader(header) {
7543
+ if (header.length !== 13)
7544
+ throw new PngError("has an IHDR chunk of the wrong length");
7545
+ const view = new DataView(header.buffer, header.byteOffset, header.byteLength);
7546
+ const width = view.getUint32(0);
7547
+ const height = view.getUint32(4);
7548
+ const bitDepth = header[8];
7549
+ const colourType = header[9];
7550
+ const compression = header[10];
7551
+ const filtering = header[11];
7552
+ const interlace = header[12];
7553
+ if (width === 0 || height === 0)
7554
+ throw new PngError("has no pixels");
7555
+ if (bitDepth !== 8)
7556
+ throw new PngError(`has ${bitDepth} bits per sample: only 8 is read`);
7557
+ const bytesPerPixel = BYTES_PER_PIXEL.get(colourType);
7558
+ if (bytesPerPixel === undefined)
7559
+ throw new PngError(`has the unknown colour type ${colourType}`);
7560
+ if (compression !== 0 || filtering !== 0) {
7561
+ throw new PngError("names a compression or filter method that PNG does not define");
7562
+ }
7563
+ if (interlace !== 0)
7564
+ throw new PngError("is interlaced: save it without interlace");
7565
+ return { width, height, colourType, bytesPerPixel };
7566
+ }
7567
+ function inflate(data) {
7568
+ try {
7569
+ return inflateSync(data);
7570
+ } catch (error) {
7571
+ throw new PngError(`has broken image data: ${error instanceof Error ? error.message : String(error)}`);
7572
+ }
7573
+ }
7574
+ function unfilter(filtered, height, rowBytes, bytesPerPixel) {
7575
+ const samples = new Uint8Array(height * rowBytes);
7576
+ for (let row = 0;row < height; row++) {
7577
+ const filter = filtered[row * (rowBytes + 1)];
7578
+ for (let column = 0;column < rowBytes; column++) {
7579
+ const at = row * rowBytes + column;
7580
+ const hasLeft = column >= bytesPerPixel;
7581
+ const left = hasLeft ? samples[at - bytesPerPixel] : 0;
7582
+ const up = row > 0 ? samples[at - rowBytes] : 0;
7583
+ const upLeft = hasLeft && row > 0 ? samples[at - rowBytes - bytesPerPixel] : 0;
7584
+ samples[at] = filtered[at + row + 1] + predict(filter, left, up, upLeft);
7585
+ }
7586
+ }
7587
+ return samples;
7588
+ }
7589
+ function predict(filter, left, up, upLeft) {
7590
+ switch (filter) {
7591
+ case 0:
7592
+ return 0;
7593
+ case 1:
7594
+ return left;
7595
+ case 2:
7596
+ return up;
7597
+ case 3:
7598
+ return left + up >> 1;
7599
+ case 4:
7600
+ return paeth(left, up, upLeft);
7601
+ default:
7602
+ throw new PngError(`has a row with the unknown filter ${filter}`);
7603
+ }
7604
+ }
7605
+ function paeth(left, up, upLeft) {
7606
+ const estimate = left + up - upLeft;
7607
+ const toLeft = Math.abs(estimate - left);
7608
+ const toUp = Math.abs(estimate - up);
7609
+ const toUpLeft = Math.abs(estimate - upLeft);
7610
+ if (toLeft <= toUp && toLeft <= toUpLeft)
7611
+ return left;
7612
+ return toUp <= toUpLeft ? up : upLeft;
7613
+ }
7614
+ function toRgba(samples, colourType, palette, transparency) {
7615
+ if (colourType === TRUECOLOUR_ALPHA)
7616
+ return samples;
7617
+ if (colourType === INDEXED && palette === undefined) {
7618
+ throw new PngError("uses a palette and has no PLTE chunk");
7619
+ }
7620
+ const bytesPerPixel = BYTES_PER_PIXEL.get(colourType);
7621
+ const rgba = new Uint8Array(samples.length / bytesPerPixel * 4);
7622
+ for (let from = 0, to = 0;from < samples.length; from += bytesPerPixel, to += 4) {
7623
+ const first = samples[from];
7624
+ switch (colourType) {
7625
+ case GREY:
7626
+ rgba.fill(first, to, to + 3);
7627
+ rgba[to + 3] = transparency !== undefined && first === transparency[1] ? 0 : 255;
7628
+ break;
7629
+ case GREY_ALPHA:
7630
+ rgba.fill(first, to, to + 3);
7631
+ rgba[to + 3] = samples[from + 1];
7632
+ break;
7633
+ case TRUECOLOUR: {
7634
+ const green = samples[from + 1];
7635
+ const blue = samples[from + 2];
7636
+ const keyed = transparency !== undefined && first === transparency[1] && green === transparency[3] && blue === transparency[5];
7637
+ rgba[to] = first;
7638
+ rgba[to + 1] = green;
7639
+ rgba[to + 2] = blue;
7640
+ rgba[to + 3] = keyed ? 0 : 255;
7641
+ break;
7642
+ }
7643
+ default: {
7644
+ if (first * 3 + 3 > palette.length) {
7645
+ throw new PngError(`names palette entry ${first}, which the palette does not have`);
7646
+ }
7647
+ rgba.set(palette.subarray(first * 3, first * 3 + 3), to);
7648
+ rgba[to + 3] = transparency?.[first] ?? 255;
7649
+ }
7650
+ }
7651
+ }
7652
+ return rgba;
7653
+ }
7654
+ function encodePng(width, height, rgba) {
7655
+ const header = Buffer.alloc(13);
7656
+ header.writeUInt32BE(width, 0);
7657
+ header.writeUInt32BE(height, 4);
7658
+ header[8] = 8;
7659
+ header[9] = TRUECOLOUR_ALPHA;
7660
+ const rowBytes = width * 4;
7661
+ const filtered = Buffer.alloc(height * (rowBytes + 1));
7662
+ for (let row = 0;row < height; row++) {
7663
+ filtered.set(rgba.subarray(row * rowBytes, (row + 1) * rowBytes), row * (rowBytes + 1) + 1);
7664
+ }
7665
+ return Buffer.concat([
7666
+ SIGNATURE,
7667
+ chunk("IHDR", header),
7668
+ chunk("IDAT", deflateSync(filtered, { level: 9 })),
7669
+ chunk("IEND", new Uint8Array)
7670
+ ]);
7671
+ }
7672
+ function chunk(type, data) {
7673
+ const bytes = Buffer.alloc(12 + data.length);
7674
+ bytes.writeUInt32BE(data.length, 0);
7675
+ bytes.write(type, 4, "latin1");
7676
+ bytes.set(data, 8);
7677
+ bytes.writeUInt32BE(crc32(bytes.subarray(4, 8 + data.length)), 8 + data.length);
7678
+ return bytes;
7679
+ }
7680
+ var CRC_TABLE = Uint32Array.from({ length: 256 }, (_, byte) => {
7681
+ let value = byte;
7682
+ for (let bit = 0;bit < 8; bit++) {
7683
+ value = value & 1 ? 3988292384 ^ value >>> 1 : value >>> 1;
7684
+ }
7685
+ return value >>> 0;
7686
+ });
7687
+ function crc32(bytes) {
7688
+ let crc = 4294967295;
7689
+ for (const byte of bytes) {
7690
+ crc = CRC_TABLE[(crc ^ byte) & 255] ^ crc >>> 8;
7691
+ }
7692
+ return (crc ^ 4294967295) >>> 0;
7693
+ }
7694
+
7695
+ // ../moveby-build/src/pack.ts
7696
+ function fitRect(cellWidth, cellHeight, imageWidth, imageHeight) {
7697
+ const scale = Math.min(cellWidth / imageWidth, cellHeight / imageHeight);
7698
+ const width = Math.max(1, Math.round(imageWidth * scale));
7699
+ const height = Math.max(1, Math.round(imageHeight * scale));
7700
+ return { x: Math.floor((cellWidth - width) / 2), y: cellHeight - height, width, height };
7701
+ }
7702
+ function packGrid(name, grid, images) {
7703
+ const sheet = new Uint8Array(grid.pxWidth * grid.pxHeight * 4);
7704
+ const cellWidth = grid.pxWidth / grid.cols;
7705
+ const cellHeight = grid.pxHeight / grid.rows;
7706
+ for (const [index, { cell, image }] of (grid.cells ?? []).entries()) {
7707
+ const fail = (message) => {
7708
+ throw new AtlasError("ATLAS_IMAGE", `/${name}/cells/${index}/image`, message);
7709
+ };
7710
+ const picture = readImage(image, images.get(image), fail);
7711
+ if (name === "fields" && picture.width * cellHeight !== picture.height * cellWidth) {
7712
+ fail(`the file ${image} is ${picture.width} × ${picture.height}: a field tile has the aspect of its cell, ${cellWidth} × ${cellHeight}`);
7713
+ }
7714
+ const rect = fitRect(cellWidth, cellHeight, picture.width, picture.height);
7715
+ const smaller = rect.width < picture.width || rect.height < picture.height;
7716
+ const scaled = smaller ? shrink(picture, rect.width, rect.height) : enlarge(picture, rect.width, rect.height);
7717
+ const left = cell % grid.cols * cellWidth + rect.x;
7718
+ const top = Math.floor(cell / grid.cols) * cellHeight + rect.y;
7719
+ for (let row = 0;row < rect.height; row++) {
7720
+ sheet.set(scaled.subarray(row * rect.width * 4, (row + 1) * rect.width * 4), ((top + row) * grid.pxWidth + left) * 4);
7721
+ }
7722
+ }
7723
+ return sheet;
7724
+ }
7725
+ function readImage(image, bytes, fail) {
7726
+ if (bytes === undefined)
7727
+ return fail(`the file ${image} was not read`);
7728
+ try {
7729
+ return decodePng(bytes);
7730
+ } catch (error) {
7731
+ if (!(error instanceof PngError))
7732
+ throw error;
7733
+ return fail(`the file ${image} ${error.message}`);
7734
+ }
7735
+ }
7736
+ function shrink(source, width, height) {
7737
+ const result = new Uint8Array(width * height * 4);
7738
+ for (let y = 0;y < height; y++) {
7739
+ const top = y * source.height / height;
7740
+ const bottom = (y + 1) * source.height / height;
7741
+ for (let x = 0;x < width; x++) {
7742
+ const left = x * source.width / width;
7743
+ const right = (x + 1) * source.width / width;
7744
+ let red = 0;
7745
+ let green = 0;
7746
+ let blue = 0;
7747
+ let alpha = 0;
7748
+ for (let row = Math.floor(top);row < bottom; row++) {
7749
+ const rowShare = Math.min(bottom, row + 1) - Math.max(top, row);
7750
+ for (let column = Math.floor(left);column < right; column++) {
7751
+ const area = rowShare * (Math.min(right, column + 1) - Math.max(left, column));
7752
+ const at = (row * source.width + column) * 4;
7753
+ const weight = area * source.rgba[at + 3];
7754
+ red += weight * source.rgba[at];
7755
+ green += weight * source.rgba[at + 1];
7756
+ blue += weight * source.rgba[at + 2];
7757
+ alpha += weight;
7758
+ }
7759
+ }
7760
+ if (alpha === 0)
7761
+ continue;
7762
+ const to = (y * width + x) * 4;
7763
+ result[to] = Math.round(red / alpha);
7764
+ result[to + 1] = Math.round(green / alpha);
7765
+ result[to + 2] = Math.round(blue / alpha);
7766
+ result[to + 3] = Math.round(alpha / ((right - left) * (bottom - top)));
7767
+ }
7768
+ }
7769
+ return result;
7770
+ }
7771
+ function enlarge(source, width, height) {
7772
+ const result = new Uint8Array(width * height * 4);
7773
+ for (let y = 0;y < height; y++) {
7774
+ const row = Math.floor((y + 0.5) * source.height / height);
7775
+ for (let x = 0;x < width; x++) {
7776
+ const column = Math.floor((x + 0.5) * source.width / width);
7777
+ const at = (row * source.width + column) * 4;
7778
+ result.set(source.rgba.subarray(at, at + 4), (y * width + x) * 4);
7779
+ }
7780
+ }
7781
+ return result;
7782
+ }
7783
+
7420
7784
  // ../moveby-build/src/road.ts
7421
7785
  var import__20202 = __toESM(require_2020(), 1);
7422
7786
  // ../moveby-build/road.schema.json
@@ -8158,6 +8522,7 @@ function reasonOf(error) {
8158
8522
  }
8159
8523
 
8160
8524
  // ../moveby-build/src/build.ts
8525
+ var SHEET_FILES = { sprites: "sprites.png", fields: "fields.png" };
8161
8526
  var ASSET_GROUP2 = "moveby.asset.";
8162
8527
  async function build(inputs, compiler) {
8163
8528
  const scene = await compileScene(inputs.scene, compiler);
@@ -8189,12 +8554,14 @@ async function build(inputs, compiler) {
8189
8554
  } catch (error) {
8190
8555
  throw new InputFault(engineRefusal(error, inputs));
8191
8556
  }
8557
+ const sheets = atlasFile ? packSheets(atlasFile, atlas, inputs.images ?? new Map) : {};
8192
8558
  return {
8193
8559
  ok: true,
8194
8560
  files: {
8195
8561
  "track.bin": track,
8196
8562
  "scene.wasm": scene.scene.bytes,
8197
- "track.d.ts": scene.scene.types
8563
+ "track.d.ts": scene.scene.types,
8564
+ ...sheets
8198
8565
  },
8199
8566
  read
8200
8567
  };
@@ -8204,6 +8571,17 @@ async function build(inputs, compiler) {
8204
8571
  return { ok: false, diagnostics: [error.diagnostic], read };
8205
8572
  }
8206
8573
  }
8574
+ function packSheets(atlasFile, atlas, images) {
8575
+ const sheets = {};
8576
+ for (const name of Object.keys(SHEET_FILES)) {
8577
+ const grid = atlas[name];
8578
+ if (grid?.cells === undefined)
8579
+ continue;
8580
+ const rgba = readPart(atlasFile, () => packGrid(name, grid, images));
8581
+ sheets[SHEET_FILES[name]] = encodePng(grid.pxWidth, grid.pxHeight, rgba);
8582
+ }
8583
+ return sheets;
8584
+ }
8207
8585
  function missingPart(needs) {
8208
8586
  const { scene, road, roadJson, atlas, files } = needs;
8209
8587
  const need = (what, key, file, where) => ({
@@ -8294,9 +8672,10 @@ function diagnosticLine(diagnostic) {
8294
8672
  // ../moveby-build/src/shell.ts
8295
8673
  async function buildOnce(command, io, compiler) {
8296
8674
  const started = performance.now();
8675
+ const folder = command.out ?? dirname(command.paths.scene);
8297
8676
  let read;
8298
8677
  try {
8299
- read = await readInputs(command.paths, io.cwd);
8678
+ read = await readInputs(command.paths, folder, io.cwd);
8300
8679
  } catch (error) {
8301
8680
  if (!(error instanceof UsageError))
8302
8681
  throw error;
@@ -8309,11 +8688,10 @@ async function buildOnce(command, io, compiler) {
8309
8688
  const sceneFiles = result.read.flatMap((uri) => uri.startsWith("file:") ? [fileURLToPath(uri)] : []);
8310
8689
  if (!result.ok)
8311
8690
  return { code: 1, read: [...read.files, ...sceneFiles] };
8312
- const folder = command.out ?? dirname(command.paths.scene);
8313
8691
  await mkdir(folder, { recursive: true });
8314
- await writeAtomically(join(folder, "track.bin"), result.files["track.bin"]);
8315
- await writeAtomically(join(folder, "scene.wasm"), result.files["scene.wasm"]);
8316
- await writeAtomically(join(folder, "track.d.ts"), result.files["track.d.ts"]);
8692
+ for (const [name, content] of Object.entries(result.files)) {
8693
+ await writeAtomically(join(folder, name), content);
8694
+ }
8317
8695
  return { code: 0, read: [...read.files, ...sceneFiles] };
8318
8696
  }
8319
8697
 
@@ -8326,7 +8704,7 @@ class UsageError extends Error {
8326
8704
  this.files = files;
8327
8705
  }
8328
8706
  }
8329
- async function readInputs(paths, cwd) {
8707
+ async function readInputs(paths, folder, cwd) {
8330
8708
  const named = [paths.scene, paths.road, paths.atlas].filter((path) => path !== undefined);
8331
8709
  const texts = new Map;
8332
8710
  for (const path of named) {
@@ -8352,6 +8730,8 @@ async function readInputs(paths, cwd) {
8352
8730
  }), 1, [...named, fontFile]);
8353
8731
  }
8354
8732
  }
8733
+ const beforeImages = [...named, ...fontFile === undefined ? [] : [fontFile]];
8734
+ const { images, files: imageFiles } = paths.atlas === undefined ? { images: new Map, files: [] } : await readImages(texts.get(paths.atlas), paths.atlas, folder, cwd, beforeImages);
8355
8735
  return {
8356
8736
  inputs: {
8357
8737
  scene: {
@@ -8361,11 +8741,52 @@ async function readInputs(paths, cwd) {
8361
8741
  },
8362
8742
  road: file(paths.road),
8363
8743
  atlas: paths.atlas === undefined ? undefined : file(paths.atlas),
8364
- font
8744
+ font,
8745
+ images
8365
8746
  },
8366
- files: [...named, ...fontFile === undefined ? [] : [fontFile]]
8747
+ files: [...beforeImages, ...imageFiles]
8367
8748
  };
8368
8749
  }
8750
+ async function readImages(atlasText, atlasPath, folder, cwd, before) {
8751
+ const { written, named } = cellsOf(atlasText);
8752
+ const files = named.map((image) => resolve(dirname(atlasPath), image));
8753
+ const outputs = new Set(written.map((sheet) => join(folder, SHEET_FILES[sheet]).toLowerCase()));
8754
+ const images = new Map;
8755
+ for (const [index, image] of named.entries()) {
8756
+ const path = files[index];
8757
+ const fault = (message) => new UsageError(diagnosticLine({ code: "ATLAS_IMAGE", file: shown(path, cwd), message }), 1, [...before, ...files]);
8758
+ if (outputs.has(path.toLowerCase())) {
8759
+ throw fault("the build writes this file: give the source image another name, or use --out");
8760
+ }
8761
+ try {
8762
+ images.set(image, await readFile(path));
8763
+ } catch (error) {
8764
+ throw fault(`cannot read the file: ${reasonOf2(error)}`);
8765
+ }
8766
+ }
8767
+ return { images, files };
8768
+ }
8769
+ function cellsOf(atlasText) {
8770
+ let atlas;
8771
+ try {
8772
+ atlas = JSON.parse(atlasText);
8773
+ } catch {
8774
+ return { written: [], named: [] };
8775
+ }
8776
+ const written = [];
8777
+ const named = [];
8778
+ for (const sheet of Object.keys(SHEET_FILES)) {
8779
+ const cells = atlas?.[sheet]?.cells;
8780
+ if (!Array.isArray(cells))
8781
+ continue;
8782
+ written.push(sheet);
8783
+ for (const entry of cells) {
8784
+ if (typeof entry?.image === "string" && entry.image !== "")
8785
+ named.push(entry.image);
8786
+ }
8787
+ }
8788
+ return { written, named };
8789
+ }
8369
8790
  function fontPathOf(atlasText) {
8370
8791
  try {
8371
8792
  const font = JSON.parse(atlasText).font;
@@ -21,28 +21,23 @@ export class Engine {
21
21
  /**
22
22
  * The live viewport aspect (canvasW / canvasH), for the scenery vertex shader's `u_aspect` — the
23
23
  * ONLY place project-in-shader lets aspect enter the scenery projection (never baked into
24
- * `camera_basis`, so a stray second divide can't creep in). JS already knows this value locally (it
24
+ * the camera that `fill_camera` writes, so a stray second divide can't creep in). JS already knows this value locally (it
25
25
  * computed it to call `set_aspect`); this getter exists so the scenery pass can read it back the
26
26
  * same way every other per-frame uniform is read, off `&self`.
27
27
  */
28
28
  aspect(): number;
29
- /**
30
- * The per-frame camera basis for the scenery vertex shader's projection: `[pos.x,y,z, forward.x,y,z]`
31
- * (6 floats — NOT the 12 a naive `{pos,forward,right,up}` flattening would send). `right` and
32
- * world-`up` are deliberately NOT included: `Camera::right()` DERIVES right from forward
33
- * (`(forward.z, 0, −forward.x)`, camera.rs) rather than storing it, and `Camera::project`'s `cy` is
34
- * just `ray.y` (world-up is the constant (0,1,0), never dotted). Sending only the minimal
35
- * independent basis means the GLSL `project()` must derive `right` the same way — which is exactly
36
- * what keeps it an auditable line-for-line mirror of `Camera::project` (camera.rs) rather than a
37
- * second copy that could silently drift out of orthogonality.
38
- */
39
- camera_basis(): Float32Array;
40
29
  /**
41
30
  * The focal length (`CAMERA_DEPTH`, consts.rs) for the scenery vertex shader's `u_cameraDepth`
42
31
  * uniform — sent so a FOV change in Rust can't silently desync from a hardcoded GLSL literal (OQ4,
43
32
  * project-in-shader.md; the same precedent `depth_bounds` already set for `u_scaleNear/Far`).
44
33
  */
45
34
  camera_depth(): number;
35
+ /**
36
+ * The byte address of the camera scratch in WebAssembly memory: six `f32`, written by `fill_camera`.
37
+ * A query (`&self`). The address does not move for the life of the engine, so JavaScript reads it
38
+ * once.
39
+ */
40
+ camera_ptr(): number;
46
41
  /**
47
42
  * The JS entry of the frame's value block (lib-value-entry): check the staging block that
48
43
  * `value_view` handed out; on success copy it into the live block and seat the camera from its
@@ -73,6 +68,8 @@ export class Engine {
73
68
  * `[u0, v0, u1, v1, start_vertex, count]` per bucket (the sub-rect as a per-draw `u_cellRect` uniform +
74
69
  * the vertex range). The renderer draws these with the fract-tile program on the SHARED atlas (NEAREST/
75
70
  * no-mips). CACHED like `field_draw_ranges` — valid only after this frame's `fill_field_*`, empty before.
71
+ *
72
+ * A VIEW, like `field_draw_ranges`: valid until the next call into WebAssembly.
76
73
  */
77
74
  field_atlas_draw_ranges(): Float32Array;
78
75
  /**
@@ -83,9 +80,29 @@ export class Engine {
83
80
  * field-sized buffer every frame, the GC churn zero-copy kills): the CURRENT frame's buckets only
84
81
  * after this frame's fill, **empty before the first fill**. Per-frame order:
85
82
  * `seek → fill_field_and_view → bufferSubData → field_draw_ranges → bind+draw`.
83
+ *
84
+ * A VIEW of the cached list, not a copy (frame-static-memory): it aliases WebAssembly memory and is
85
+ * valid until the next call into WebAssembly. Read it at once, and take no engine call while a loop
86
+ * reads it. The Rust name has `_view` because the `cargo test` seam `EngineTestExt::field_draw_ranges`
87
+ * keeps the plain name and returns a `Vec`.
86
88
  */
87
89
  field_draw_ranges(): Uint32Array;
88
90
  fill_and_view(): Float32Array;
91
+ /**
92
+ * The per-frame camera basis for the scenery vertex shader's projection: `[pos.x,y,z, forward.x,y,z]`
93
+ * (6 floats — NOT the 12 a naive `{pos,forward,right,up}` flattening would send). `right` and
94
+ * world-`up` are deliberately NOT included: `Camera::right()` DERIVES right from forward
95
+ * (`(forward.z, 0, −forward.x)`, camera.rs) rather than storing it, and `Camera::project`'s `cy` is
96
+ * just `ray.y` (world-up is the constant (0,1,0), never dotted). Sending only the minimal
97
+ * independent basis means the GLSL `project()` must derive `right` the same way — which is exactly
98
+ * what keeps it an auditable line-for-line mirror of `Camera::project` (camera.rs) rather than a
99
+ * second copy that could silently drift out of orthogonality.
100
+ *
101
+ * This writes the six floats into the engine's own scratch; it returns nothing. JavaScript reads
102
+ * them through two views over that scratch (`camera_ptr`, `wasm_memory`), and calls this once per
103
+ * frame, after the frame's position is set. The views stay valid until WebAssembly memory grows.
104
+ */
105
+ fill_camera(): void;
89
106
  fill_field_and_view(): Float32Array;
90
107
  fill_scenery_and_view(): Float32Array;
91
108
  fill_text_and_view(): Float32Array;
@@ -197,6 +214,8 @@ export class Engine {
197
214
  * `field_draw_ranges` idiom — re-emitting would re-allocate a text-sized buffer every frame): valid only
198
215
  * after THIS frame's `fill_text_*`, **empty before the first fill**. Per-frame order:
199
216
  * `seek → fill_text_and_view → bufferSubData → text_draw_ranges → draw`.
217
+ *
218
+ * A VIEW, like `field_draw_ranges`: valid until the next call into WebAssembly.
200
219
  */
201
220
  text_draw_ranges(): Float32Array;
202
221
  /**
@@ -214,6 +233,13 @@ export class Engine {
214
233
  * the view allocates nothing in WebAssembly memory.
215
234
  */
216
235
  value_view(): Float32Array;
236
+ /**
237
+ * The memory of the WebAssembly module that this engine lives in. JavaScript builds views over its
238
+ * `buffer` (`camera_ptr`); the `buffer` is replaced when the memory grows, and the views of the old one
239
+ * then have length 0. A method, not a free function, so a scene reads it from the engine it was
240
+ * given and imports no module.
241
+ */
242
+ wasm_memory(): WebAssembly.Memory;
217
243
  }
218
244
 
219
245
  /**
@@ -266,14 +292,15 @@ export interface InitOutput {
266
292
  readonly __wbg_engine_free: (a: number, b: number) => void;
267
293
  readonly __wbg_rows_free: (a: number, b: number) => void;
268
294
  readonly engine_aspect: (a: number) => number;
269
- readonly engine_camera_basis: (a: number) => [number, number];
270
295
  readonly engine_camera_depth: (a: number) => number;
296
+ readonly engine_camera_ptr: (a: number) => number;
271
297
  readonly engine_commit_value_block: (a: number) => number;
272
298
  readonly engine_dash_anchor: (a: number) => number;
273
299
  readonly engine_depth_bounds: (a: number) => [number, number];
274
- readonly engine_field_atlas_draw_ranges: (a: number) => [number, number];
275
- readonly engine_field_draw_ranges: (a: number) => [number, number];
300
+ readonly engine_field_atlas_draw_ranges: (a: number) => any;
301
+ readonly engine_field_draw_ranges: (a: number) => any;
276
302
  readonly engine_fill_and_view: (a: number) => any;
303
+ readonly engine_fill_camera: (a: number) => void;
277
304
  readonly engine_fill_field_and_view: (a: number) => any;
278
305
  readonly engine_fill_scenery_and_view: (a: number) => any;
279
306
  readonly engine_fill_text_and_view: (a: number) => any;
@@ -292,9 +319,10 @@ export interface InitOutput {
292
319
  readonly engine_set_aspect: (a: number, b: number) => void;
293
320
  readonly engine_set_camera_offset: (a: number, b: number, c: number) => void;
294
321
  readonly engine_sky_parallax: (a: number) => number;
295
- readonly engine_text_draw_ranges: (a: number) => [number, number];
322
+ readonly engine_text_draw_ranges: (a: number) => any;
296
323
  readonly engine_track_length: (a: number) => number;
297
324
  readonly engine_value_view: (a: number) => any;
325
+ readonly engine_wasm_memory: (a: number) => any;
298
326
  readonly rows_asset: (a: number, b: number, c: number, d: number) => void;
299
327
  readonly rows_image: (a: number, b: number) => void;
300
328
  readonly rows_new: () => number;