@bendyline/molen-tooling 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.md +4 -4
  2. package/dist/capture/harness.js +222 -222
  3. package/dist/capture/worldgen-preview.js +288 -288
  4. package/dist/cli.mjs +162 -10
  5. package/dist/docs-src/guide/3d-model-assets.md +35 -3
  6. package/dist/docs-src/guide/adaptive-performance.md +4 -0
  7. package/dist/docs-src/guide/agent-loop.md +6 -6
  8. package/dist/docs-src/guide/aircraft.md +28 -7
  9. package/dist/docs-src/guide/ambient-life.md +389 -0
  10. package/dist/docs-src/guide/audio.md +247 -0
  11. package/dist/docs-src/guide/browser-mount.md +8 -1
  12. package/dist/docs-src/guide/building-interiors.md +5 -4
  13. package/dist/docs-src/guide/capability-authoring.md +5 -0
  14. package/dist/docs-src/guide/determinism.md +35 -27
  15. package/dist/docs-src/guide/earth-view.md +492 -0
  16. package/dist/docs-src/guide/entities.md +9 -1
  17. package/dist/docs-src/guide/examples.md +6 -2
  18. package/dist/docs-src/guide/figures.md +3 -0
  19. package/dist/docs-src/guide/game-samples.md +22 -5
  20. package/dist/docs-src/guide/graphics-performance.md +40 -8
  21. package/dist/docs-src/guide/input.md +9 -0
  22. package/dist/docs-src/guide/markers.md +55 -0
  23. package/dist/docs-src/guide/materials.md +10 -3
  24. package/dist/docs-src/guide/navigation.md +150 -0
  25. package/dist/docs-src/guide/project.md +1 -1
  26. package/dist/docs-src/guide/quickstart.md +2 -2
  27. package/dist/docs-src/guide/recognizable-places.md +3 -2
  28. package/dist/docs-src/guide/scripting.md +4 -2
  29. package/dist/docs-src/guide/sky.md +16 -0
  30. package/dist/docs-src/guide/source-bundles.md +0 -1
  31. package/dist/docs-src/guide/structure-library.md +2 -2
  32. package/dist/docs-src/guide/surface-rendering.md +4 -3
  33. package/dist/docs-src/guide/terrain.md +52 -2
  34. package/dist/docs-src/guide/vehicles.md +32 -10
  35. package/dist/docs-src/guide/worldgen.md +3 -3
  36. package/dist/docs-src/llms.txt +14 -5
  37. package/dist/docs-src/schemas/README.md +4 -0
  38. package/dist/docs-src/schemas/archive-set.md +175 -0
  39. package/dist/docs-src/schemas/components.md +1634 -2
  40. package/dist/docs-src/schemas/matgraph.md +6 -0
  41. package/dist/docs-src/schemas/scene.md +105 -0
  42. package/dist/docs-src/schemas/soundbank.md +251 -0
  43. package/dist/docs-src/schemas/structure-placements.md +496 -0
  44. package/dist/docs-src/schemas/terrain-package.md +120 -0
  45. package/dist/docs-src/schemas/transport-network.md +351 -0
  46. package/dist/index.d.mts +49 -2
  47. package/dist/index.mjs +81 -4
  48. package/dist/{mcp-AOfIp89b.mjs → mcp-BtuworIW.mjs} +88 -3
  49. package/dist/{ops-C4BvDgP-.mjs → ops-DMGcWoL2.mjs} +1204 -93
  50. package/dist/templates/city-courier/README.md +14 -1
  51. package/dist/templates/city-courier/delivery-run.replay.json +151 -151
  52. package/dist/templates/city-courier/gen/molen-types.ts +223 -5
  53. package/dist/templates/city-courier/package.json +2 -0
  54. package/dist/templates/city-courier/scene.json +142 -246
  55. package/dist/templates/city-courier/scripts/game.ts +7 -15
  56. package/dist/templates/city-courier/scripts/molen-scripts.d.ts +252 -16
  57. package/dist/templates/city-courier/src/audio.ts +96 -0
  58. package/dist/templates/city-courier/src/game-shell.css +8 -0
  59. package/dist/templates/city-courier/src/main.ts +3 -0
  60. package/dist/templates/city-courier/src/worker.ts +3 -1
  61. package/dist/templates/city-courier/test/headless.test.ts +3 -2
  62. package/dist/templates/data-viz/README.md +1 -1
  63. package/dist/templates/index.json +22 -1
  64. package/dist/templates/skybound/README.md +13 -0
  65. package/dist/templates/skybound/first-leap.replay.json +152 -152
  66. package/dist/templates/skybound/gen/molen-types.ts +223 -5
  67. package/dist/templates/skybound/package.json +1 -0
  68. package/dist/templates/skybound/scene.json +40 -0
  69. package/dist/templates/skybound/scripts/game.ts +8 -5
  70. package/dist/templates/skybound/scripts/molen-scripts.d.ts +248 -5
  71. package/dist/templates/skybound/src/audio.ts +96 -0
  72. package/dist/templates/skybound/src/game-shell.css +8 -0
  73. package/dist/templates/skybound/src/main.ts +3 -0
  74. package/dist/templates/skybound/test/headless.test.ts +1 -1
  75. package/dist/templates/terrain-flyover/README.md +2 -2
  76. package/dist/templates/top-down-arena/README.md +15 -2
  77. package/dist/templates/top-down-arena/arena-skirmish.replay.json +152 -152
  78. package/dist/templates/top-down-arena/package.json +1 -0
  79. package/dist/templates/top-down-arena/scene.json +20 -0
  80. package/dist/templates/top-down-arena/scripts/combat.ts +1 -0
  81. package/dist/templates/top-down-arena/scripts/molen-scripts.d.ts +248 -5
  82. package/dist/templates/top-down-arena/src/audio.ts +96 -0
  83. package/dist/templates/top-down-arena/src/gen/molen-types.ts +223 -5
  84. package/dist/templates/top-down-arena/src/main.ts +3 -0
  85. package/dist/templates/top-down-arena/test/headless.test.ts +1 -1
  86. package/package.json +13 -12
@@ -1,29 +1,31 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { access, copyFile, mkdir, mkdtemp, open, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
3
- import { basename, delimiter, dirname, extname, isAbsolute, join, normalize, posix, relative, resolve, sep } from "node:path";
4
3
  import { PNG } from "pngjs";
4
+ import { basename, delimiter, dirname, extname, isAbsolute, join, normalize, posix, relative, resolve, sep } from "node:path";
5
5
  import { applyUvPaint, bakeMatGraph, bakePalette, bakePixelGrid, bakeSvg } from "@bendyline/molen-materials";
6
+ import { TransportNetwork, ambientCapability, ambientOf, networkToDocument } from "@bendyline/molen-ambient/kernel";
6
7
  import { FIGURE_PRESET_IDS, deriveRig, descriptorKey, figuresScriptApi, generateFigureBody, installFigures, resolveFigureDescriptor, strideRateFor } from "@bendyline/molen-figures/kernel";
7
- import { heightfieldFromPng, terrainPyramidTileOrigin, terrainPyramidTileSize, wgs84ToWebMercatorTile } from "@bendyline/molen-terrain/kernel";
8
+ import { heightfieldFromPng, terrainPyramidTileOrigin, terrainPyramidTileSize, wgs84ToWebMercatorTile, worldToWgs84 } from "@bendyline/molen-terrain/kernel";
8
9
  import { createLandmarkLibrary, encodeGlb, generateLandmarkModel, generateWorldgenBatch, groundSamplerForBatch, resolveStylePackDocuments, stylePackAssetIndex, stylePackMaterialRefs, validateStylePackBundle } from "@bendyline/molen-worldgen/kernel";
9
10
  import { createPlacesContent, createRegionResolver, semanticTileToBatch, tileGroundSampler, worldgenTileBudgetForQuality } from "@bendyline/molen-worldgen-earth/kernel";
10
11
  import { evaluateCameraTrack, registerCameraTrackSchema } from "@bendyline/molen-client/camera-track";
11
12
  import { createReadStream, watch } from "node:fs";
12
13
  import { createServer } from "node:http";
13
- import { buildTypeIndex, checkTypes, componentMapIssues, componentNames, createComponentRegistry, decodeCollisionTrimesh, detectKind, encodeCollisionTrimesh, formatIssues, getComponent, getSchema, listComponents, listSchemas, namespaceCovers, registerSchema, resolveAllTypes, sceneTypeRefIssues, schemaKinds, validate, validateByKind } from "@bendyline/molen-schema";
14
+ import { audioSignalIssues, audioSignalRefs, audioSoundRefs, buildTypeIndex, checkTypes, componentMapIssues, componentNames, createComponentRegistry, decodeCollisionTrimesh, detectKind, encodeCollisionTrimesh, formatIssues, getComponent, getSchema, listComponents, listSchemas, namespaceCovers, nearestWithDistance, registerSchema, resolveAllTypes, sceneTypeRefIssues, schemaKinds, validate, validateByKind, weatherProfile } from "@bendyline/molen-schema";
14
15
  import { z } from "zod";
15
16
  import { createHash, randomUUID } from "node:crypto";
16
17
  import { Node, NodeIO, getBounds } from "@gltf-transform/core";
17
18
  import { ALL_EXTENSIONS, KHRTextureBasisu } from "@gltf-transform/extensions";
18
- import { dedup, getTextureColorSpace, listTextureSlots, prune, quantize, weld } from "@gltf-transform/functions";
19
+ import { dedup, getTextureColorSpace, listTextureInfoByMaterial, listTextureSlots, prune, quantize, weld } from "@gltf-transform/functions";
19
20
  import { fileURLToPath, pathToFileURL } from "node:url";
20
21
  import { stripScriptTypes } from "@bendyline/molen-client/vite";
21
- import { ENGINE_VERSION, STATE_FORMAT, World, applyKeyframeTo, buildWorld, contentDrift, dmath, installGameplay, isExperience, keyframeStateFormat, stateHash, takeKeyframe, worldFromKeyframe } from "@bendyline/molen-kernel";
22
+ import { ENGINE_VERSION, STATE_FORMAT, World, applyKeyframeTo, buildWorld, contentDrift, dmath, installGameplay, isExperience, keyframeStateFormat, quatRotateVec3, stateHash, takeKeyframe, worldFromKeyframe } from "@bendyline/molen-kernel";
22
23
  import { homedir, tmpdir } from "node:os";
23
24
  import { createTypeLibrary } from "@bendyline/molen-kernel/content";
24
25
  import { createPackSet, openPack, sha256 } from "@bendyline/molen-pack";
25
- import { PACK_SOURCE_FILE, buildPack, extractPack, openPackAt } from "@bendyline/molen-pack/node";
26
+ import { PACK_SOURCE_FILE, buildPack, extractPack, openPackAt, recordInPackIndex } from "@bendyline/molen-pack/node";
26
27
  import { installTerrain, terrainScriptApi } from "@bendyline/molen-kernel/terrain";
28
+ import { AudioDirector, entitySourceFromWorld, mergeSoundbanks } from "@bendyline/molen-client/audio";
27
29
  import { diffKeyframes, firstDivergentTick, formatAssertionResults, perTickHashes, runAssertions, runHeadless } from "@bendyline/molen-kernel/testing";
28
30
  import { hashJson } from "@bendyline/molen-kernel/determinism";
29
31
  import { PMTiles } from "pmtiles";
@@ -1061,6 +1063,67 @@ function buildStats(doc, sizeBytes) {
1061
1063
  };
1062
1064
  }
1063
1065
  const NODE_CAP = 128;
1066
+ /** Only the explicit, supported extras contract makes unused UV0 meaningful at runtime. */
1067
+ function sharedSurfaceRef(material) {
1068
+ const value = material?.getExtras().molenSurface;
1069
+ if (value === null || typeof value !== "object") return void 0;
1070
+ const surface = value;
1071
+ return surface.uv === "repeats" && typeof surface.ref === "string" && surface.ref.trim().length > 0 && typeof surface.slot === "string" && [
1072
+ "wall",
1073
+ "roof",
1074
+ "trim",
1075
+ "foundation",
1076
+ "window",
1077
+ "door"
1078
+ ].includes(surface.slot) ? surface.ref : void 0;
1079
+ }
1080
+ /** Keep opted-in UV0 across pruning without retaining unused attributes on other primitives. */
1081
+ async function prunePreservingSharedSurfaceUvs(doc) {
1082
+ const saved = /* @__PURE__ */ new Map();
1083
+ for (const mesh of doc.getRoot().listMeshes()) for (const primitive of mesh.listPrimitives()) {
1084
+ const uv = primitive.getAttribute("TEXCOORD_0");
1085
+ if (sharedSurfaceRef(primitive.getMaterial()) === void 0 || uv === null) continue;
1086
+ let semantic = "_MOLEN_SHARED_UV0";
1087
+ while (primitive.getAttribute(semantic) !== null) semantic += "_";
1088
+ primitive.setAttribute(semantic, uv);
1089
+ saved.set(primitive, semantic);
1090
+ }
1091
+ await doc.transform(prune());
1092
+ const groups = /* @__PURE__ */ new Map();
1093
+ for (const mesh of doc.getRoot().listMeshes()) for (const primitive of mesh.listPrimitives()) {
1094
+ const material = primitive.getMaterial();
1095
+ if (material === null || sharedSurfaceRef(material) === void 0) continue;
1096
+ const group = groups.get(material) ?? [];
1097
+ group.push(primitive);
1098
+ groups.set(material, group);
1099
+ }
1100
+ for (const [material, primitives] of groups) {
1101
+ if (primitives.some((primitive) => {
1102
+ const semantic = saved.get(primitive);
1103
+ const uv = primitive.getAttribute("TEXCOORD_0");
1104
+ return uv !== null && (semantic === void 0 || uv !== primitive.getAttribute(semantic));
1105
+ })) {
1106
+ const shiftUvs = (primitive) => {
1107
+ const coordinates = primitive.listSemantics().filter((semantic) => /^TEXCOORD_\d+$/.test(semantic)).map((semantic) => Number(semantic.slice(9))).sort((a, b) => b - a);
1108
+ for (const index of coordinates) {
1109
+ primitive.setAttribute(`TEXCOORD_${index + 1}`, primitive.getAttribute(`TEXCOORD_${index}`));
1110
+ primitive.setAttribute(`TEXCOORD_${index}`, null);
1111
+ }
1112
+ };
1113
+ for (const primitive of primitives) {
1114
+ shiftUvs(primitive);
1115
+ for (const target of primitive.listTargets()) shiftUvs(target);
1116
+ }
1117
+ for (const info of listTextureInfoByMaterial(material)) info.setTexCoord(info.getTexCoord() + 1);
1118
+ }
1119
+ for (const primitive of primitives) {
1120
+ const semantic = saved.get(primitive);
1121
+ if (semantic === void 0) continue;
1122
+ primitive.setAttribute("TEXCOORD_0", primitive.getAttribute(semantic));
1123
+ primitive.setAttribute(semantic, null);
1124
+ }
1125
+ }
1126
+ }
1064
1127
  /**
1065
1128
  * Pick the project.json an import registers into. The source file's surrounding project is NOT a
1066
1129
  * safe default: `molen asset import ../otherproj/models/key.glb` used to write the asset into
@@ -1091,6 +1154,23 @@ async function resolveImportProject(input, sourcePath) {
1091
1154
  async function importAsset(input) {
1092
1155
  const warnings = [];
1093
1156
  try {
1157
+ if (input.assetDir !== void 0 && input.outDir !== void 0) return {
1158
+ ok: false,
1159
+ error: "assetDir and outDir are mutually exclusive; choose an exact bundle directory or an assets root"
1160
+ };
1161
+ if (input.assetDir !== void 0 && input.assetDir.trim().length === 0) return {
1162
+ ok: false,
1163
+ error: "assetDir must not be empty"
1164
+ };
1165
+ if (input.assetDir?.includes("\0")) return {
1166
+ ok: false,
1167
+ error: "assetDir must not contain a null byte"
1168
+ };
1169
+ const id = slug$2(input.id ?? basename(input.path, extname(input.path)));
1170
+ if (id.length === 0) return {
1171
+ ok: false,
1172
+ error: "asset id is empty after slugging"
1173
+ };
1094
1174
  const sourcePath = resolve(input.path);
1095
1175
  const resolved = await resolveImportProject(input, sourcePath);
1096
1176
  if (resolved.error !== void 0) return {
@@ -1099,6 +1179,47 @@ async function importAsset(input) {
1099
1179
  };
1100
1180
  const projectPath = resolved.projectPath;
1101
1181
  if (resolved.warning !== void 0) warnings.push(resolved.warning);
1182
+ let registeredAssets = {};
1183
+ if (projectPath !== void 0) {
1184
+ const project = validate("project", parseJson(await readFile(projectPath, "utf8")));
1185
+ if (!project.ok) return {
1186
+ ok: false,
1187
+ error: project.formatted
1188
+ };
1189
+ registeredAssets = project.value.assets;
1190
+ }
1191
+ const registeredSidecar = input.assetDir === void 0 && input.outDir === void 0 ? registeredAssets[id] : void 0;
1192
+ const assetsRoot = input.outDir ?? (projectPath !== void 0 ? join(dirname(projectPath), "assets") : resolve(input.cwd ?? process.cwd(), "assets"));
1193
+ const dir = input.assetDir !== void 0 ? resolve(input.cwd ?? process.cwd(), input.assetDir) : registeredSidecar !== void 0 && projectPath !== void 0 ? dirname(resolve(dirname(projectPath), registeredSidecar)) : join(assetsRoot, id.replaceAll(".", "/"));
1194
+ const sidecarPath = registeredSidecar !== void 0 && projectPath !== void 0 ? resolve(dirname(projectPath), registeredSidecar) : join(dir, "asset.json");
1195
+ if (projectPath !== void 0) {
1196
+ for (const [registeredId, path] of Object.entries(registeredAssets)) if (registeredId !== id && relative(resolve(dir), dirname(resolve(dirname(projectPath), path))) === "") return {
1197
+ ok: false,
1198
+ error: `${dir} belongs to asset "${registeredId}"; refusing to overwrite it with "${id}"`
1199
+ };
1200
+ }
1201
+ try {
1202
+ if (!(await stat(dir)).isDirectory()) return {
1203
+ ok: false,
1204
+ error: `${dir} is not a directory`
1205
+ };
1206
+ if (input.force !== true) return {
1207
+ ok: false,
1208
+ error: `${dir} already exists; choose another id or pass force: true to replace it`
1209
+ };
1210
+ let existing;
1211
+ try {
1212
+ existing = parseJson(await readFile(sidecarPath, "utf8"));
1213
+ } catch (error) {
1214
+ if (error.code !== "ENOENT" && !(error instanceof SyntaxError)) throw error;
1215
+ }
1216
+ if (existing !== null && typeof existing === "object" && "id" in existing && typeof existing.id === "string" && existing.id !== id) return {
1217
+ ok: false,
1218
+ error: `${dir} belongs to asset "${existing.id}"; refusing to overwrite it with "${id}"`
1219
+ };
1220
+ } catch (error) {
1221
+ if (error.code !== "ENOENT") throw error;
1222
+ }
1102
1223
  const sourceBytes = new Uint8Array(await readFile(sourcePath));
1103
1224
  const io = await createAssetIO();
1104
1225
  let doc;
@@ -1112,7 +1233,13 @@ async function importAsset(input) {
1112
1233
  };
1113
1234
  }
1114
1235
  doc.setLogger(gltfLogger);
1115
- if (input.optimize !== false) await doc.transform(dedup(), prune(), weld(), quantize());
1236
+ const sharedSurfaces = [...new Set(doc.getRoot().listMaterials().map(sharedSurfaceRef).filter((ref) => ref !== void 0))].sort();
1237
+ if (sharedSurfaces.length > 0) warnings.push(`shared surfaces are external runtime dependencies: ${sharedSurfaces.join(", ")}; hosts without these surfaces render the embedded PBR fallback`);
1238
+ if (input.optimize !== false) {
1239
+ await doc.transform(dedup());
1240
+ await prunePreservingSharedSurfaceUvs(doc);
1241
+ await doc.transform(weld(), quantize());
1242
+ }
1116
1243
  const root = doc.getRoot();
1117
1244
  const extensionsUsed = root.listExtensionsUsed().map((e) => e.extensionName);
1118
1245
  const nodeName = (node, i) => {
@@ -1202,21 +1329,6 @@ async function importAsset(input) {
1202
1329
  alphaMode: m.getAlphaMode()
1203
1330
  };
1204
1331
  });
1205
- const id = slug$2(input.id ?? basename(sourcePath, extname(sourcePath)));
1206
- if (id.length === 0) return {
1207
- ok: false,
1208
- error: "asset id is empty after slugging"
1209
- };
1210
- const dir = join(input.outDir ?? (projectPath !== void 0 ? join(dirname(projectPath), "assets") : resolve(input.cwd ?? process.cwd(), "assets")), id.replaceAll(".", "/"));
1211
- try {
1212
- await stat(dir);
1213
- if (input.force !== true) return {
1214
- ok: false,
1215
- error: `${dir} already exists; choose another id or pass force: true to replace it`
1216
- };
1217
- } catch (error) {
1218
- if (error.code !== "ENOENT") throw error;
1219
- }
1220
1332
  await mkdir(dir, { recursive: true });
1221
1333
  const glb = await io.writeBinary(doc);
1222
1334
  await writeFile(join(dir, "model.glb"), glb);
@@ -1279,7 +1391,6 @@ async function importAsset(input) {
1279
1391
  ok: false,
1280
1392
  error: `sidecar failed self-validation:\n${checked.formatted}`
1281
1393
  };
1282
- const sidecarPath = join(dir, "asset.json");
1283
1394
  await writeFile(sidecarPath, `${JSON.stringify(checked.value, null, 2)}\n`);
1284
1395
  try {
1285
1396
  await stat(sidecarPath);
@@ -1338,6 +1449,17 @@ async function loadSceneTerrain(sceneDir, manifest) {
1338
1449
  };
1339
1450
  }
1340
1451
  /**
1452
+ * Load the transport network a scene's `ambient.network` path names (scene-file-relative),
1453
+ * validated. Undefined when the scene has no ambient block or its network is inline.
1454
+ */
1455
+ async function loadSceneAmbient(sceneDir, manifest) {
1456
+ const network = manifest.ambient?.network;
1457
+ if (typeof network !== "string") return void 0;
1458
+ const result = validateByKind("transport-network", parseJson(await readFile(join(sceneDir, network), "utf8")));
1459
+ if (!result.ok) throw new Error(result.formatted);
1460
+ return { [network]: result.value };
1461
+ }
1462
+ /**
1341
1463
  * Everything a loaded scene needs to build its world: registry types, physics shape resolvers
1342
1464
  * (rapier scenes in a project), and the terrain ground field. The one preamble every scene op
1343
1465
  * shares (sim run, shot, drive, frames).
@@ -1349,6 +1471,8 @@ async function sceneBuildOptionsFor(loaded) {
1349
1471
  if (loaded.project !== void 0 && loaded.manifest.physics?.engine === "rapier") opts.resolvers = await collisionResolvers(loaded.project);
1350
1472
  const terrain = await loadSceneTerrain(dirname(loaded.scenePath), loaded.manifest);
1351
1473
  if (terrain !== void 0) opts.terrain = terrain;
1474
+ const networks = await loadSceneAmbient(dirname(loaded.scenePath), loaded.manifest);
1475
+ if (networks !== void 0) opts.ambientNetworks = networks;
1352
1476
  return opts;
1353
1477
  }
1354
1478
  /** The rapier heightfield resolver convention: `collider3d.shape = { type: 'heightfield', ref: 'scene' }`. */
@@ -1365,7 +1489,10 @@ async function prepareSceneBuilder(manifest, setup, opts) {
1365
1489
  registry: opts?.registry,
1366
1490
  ...opts?.types !== void 0 ? { types: opts.types } : {},
1367
1491
  ...opts?.content !== void 0 ? { content: opts.content } : {},
1368
- capabilities: [(world) => ({ figures: figuresScriptApi(installFigures(world)) })],
1492
+ capabilities: [(world) => ({ figures: figuresScriptApi(installFigures(world)) }), ambientCapability({
1493
+ ...opts?.ambientNetworks !== void 0 ? { networks: opts.ambientNetworks } : {},
1494
+ ...terrain !== void 0 ? { ground: (x, z) => terrain.heightfield.sampleHeight(x, z) } : {}
1495
+ })],
1369
1496
  ...terrain !== void 0 ? { terrain: (world) => ({ terrain: terrainScriptApi(installTerrain(world, terrain.heightfield)) }) } : {}
1370
1497
  };
1371
1498
  if (manifest.physics?.engine !== "rapier") return () => buildWorld(manifest, setup, buildOpts);
@@ -2090,6 +2217,684 @@ async function stageAssetsImpl(input) {
2090
2217
  };
2091
2218
  }
2092
2219
  //#endregion
2220
+ //#region src/audio-probe.ts
2221
+ function ascii(b, at, len) {
2222
+ return String.fromCharCode(...b.subarray(at, at + len));
2223
+ }
2224
+ function probeWav(b, v) {
2225
+ let at = 12;
2226
+ let byteRate = 0;
2227
+ let sampleRate;
2228
+ let channels;
2229
+ while (at + 8 <= b.length) {
2230
+ const id = ascii(b, at, 4);
2231
+ const size = v.getUint32(at + 4, true);
2232
+ if (id === "fmt ") {
2233
+ channels = v.getUint16(at + 10, true);
2234
+ sampleRate = v.getUint32(at + 12, true);
2235
+ byteRate = v.getUint32(at + 16, true);
2236
+ } else if (id === "data" && byteRate > 0) return {
2237
+ format: "wav",
2238
+ durationS: Math.min(size, b.length - at - 8) / byteRate,
2239
+ ...sampleRate !== void 0 ? { sampleRate } : {},
2240
+ ...channels !== void 0 ? { channels } : {}
2241
+ };
2242
+ at += 8 + size + (size & 1);
2243
+ }
2244
+ return { format: "wav" };
2245
+ }
2246
+ function probeOgg(b, v) {
2247
+ let rate;
2248
+ let channels;
2249
+ let preSkip = 0;
2250
+ let opus = false;
2251
+ const head = ascii(b, 0, Math.min(b.length, 256));
2252
+ const vorbis = head.indexOf("vorbis");
2253
+ const opusHead = head.indexOf("OpusHead");
2254
+ if (vorbis >= 0) {
2255
+ channels = b[vorbis + 11];
2256
+ rate = v.getUint32(vorbis + 12, true);
2257
+ } else if (opusHead >= 0) {
2258
+ opus = true;
2259
+ channels = b[opusHead + 9];
2260
+ preSkip = v.getUint16(opusHead + 10, true);
2261
+ rate = 48e3;
2262
+ }
2263
+ for (let at = b.length - 27; at >= 0; at--) if (b[at] === 79 && ascii(b, at, 4) === "OggS") {
2264
+ const granule = Number(v.getBigUint64(at + 6, true));
2265
+ if (rate && granule > 0) return {
2266
+ format: "ogg",
2267
+ durationS: (granule - (opus ? preSkip : 0)) / rate,
2268
+ sampleRate: opus ? v.getUint32(opusHead + 12, true) || 48e3 : rate,
2269
+ ...channels !== void 0 ? { channels } : {}
2270
+ };
2271
+ break;
2272
+ }
2273
+ return { format: "ogg" };
2274
+ }
2275
+ const MP3_BITRATES_V1 = [
2276
+ 0,
2277
+ 32,
2278
+ 40,
2279
+ 48,
2280
+ 56,
2281
+ 64,
2282
+ 80,
2283
+ 96,
2284
+ 112,
2285
+ 128,
2286
+ 160,
2287
+ 192,
2288
+ 224,
2289
+ 256,
2290
+ 320
2291
+ ];
2292
+ const MP3_BITRATES_V2 = [
2293
+ 0,
2294
+ 8,
2295
+ 16,
2296
+ 24,
2297
+ 32,
2298
+ 40,
2299
+ 48,
2300
+ 56,
2301
+ 64,
2302
+ 80,
2303
+ 96,
2304
+ 112,
2305
+ 128,
2306
+ 144,
2307
+ 160
2308
+ ];
2309
+ const MP3_RATES = {
2310
+ 3: [
2311
+ 44100,
2312
+ 48e3,
2313
+ 32e3
2314
+ ],
2315
+ 2: [
2316
+ 22050,
2317
+ 24e3,
2318
+ 16e3
2319
+ ],
2320
+ 0: [
2321
+ 11025,
2322
+ 12e3,
2323
+ 8e3
2324
+ ]
2325
+ };
2326
+ function probeMp3(b, v) {
2327
+ let at = 0;
2328
+ if (ascii(b, 0, 3) === "ID3") at = 10 + ((b[6] ?? 0) << 21 | (b[7] ?? 0) << 14 | (b[8] ?? 0) << 7 | (b[9] ?? 0));
2329
+ for (; at + 4 < b.length; at++) {
2330
+ if (b[at] !== 255 || ((b[at + 1] ?? 0) & 224) !== 224) continue;
2331
+ const h = v.getUint32(at, false);
2332
+ const version = h >>> 19 & 3;
2333
+ const layer = h >>> 17 & 3;
2334
+ const bitrateIndex = h >>> 12 & 15;
2335
+ const rateIndex = h >>> 10 & 3;
2336
+ if (version === 1 || layer !== 1 || bitrateIndex === 0 || bitrateIndex === 15 || rateIndex === 3) continue;
2337
+ const sampleRate = MP3_RATES[version][rateIndex];
2338
+ const mono = (h >>> 6 & 3) === 3;
2339
+ const v1 = version === 3;
2340
+ const samplesPerFrame = v1 ? 1152 : 576;
2341
+ const sideInfo = v1 ? mono ? 17 : 32 : mono ? 9 : 17;
2342
+ const tag = ascii(b, at + 4 + sideInfo, 4);
2343
+ const channels = mono ? 1 : 2;
2344
+ if (tag === "Xing" || tag === "Info") {
2345
+ if (v.getUint32(at + 8 + sideInfo, false) & 1) return {
2346
+ format: "mp3",
2347
+ durationS: v.getUint32(at + 12 + sideInfo, false) * samplesPerFrame / sampleRate,
2348
+ sampleRate,
2349
+ channels
2350
+ };
2351
+ }
2352
+ const kbps = (v1 ? MP3_BITRATES_V1 : MP3_BITRATES_V2)[bitrateIndex] * 1e3;
2353
+ return {
2354
+ format: "mp3",
2355
+ durationS: (b.length - at) * 8 / kbps,
2356
+ sampleRate,
2357
+ channels
2358
+ };
2359
+ }
2360
+ return { format: "mp3" };
2361
+ }
2362
+ /** Probe a clip's header for duration, sample rate and channel count. */
2363
+ function probeAudio(bytes) {
2364
+ const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
2365
+ if (bytes.length >= 12 && ascii(bytes, 0, 4) === "RIFF" && ascii(bytes, 8, 4) === "WAVE") return probeWav(bytes, v);
2366
+ if (bytes.length >= 27 && ascii(bytes, 0, 4) === "OggS") return probeOgg(bytes, v);
2367
+ if (bytes.length >= 4 && (ascii(bytes, 0, 3) === "ID3" || bytes[0] === 255 && ((bytes[1] ?? 0) & 224) === 224)) return probeMp3(bytes, v);
2368
+ return { format: "unknown" };
2369
+ }
2370
+ //#endregion
2371
+ //#region src/ops/audio-check.ts
2372
+ const fail$3 = (error) => ({
2373
+ ok: false,
2374
+ sounds: 0,
2375
+ clips: 0,
2376
+ bytes: 0,
2377
+ licenses: {},
2378
+ issues: [],
2379
+ error
2380
+ });
2381
+ /** Validate a sound bank and every clip it names: present, hash, duration, loop points. */
2382
+ function checkSoundbank(input) {
2383
+ return guardOp(fail$3, () => checkSoundbankImpl(input));
2384
+ }
2385
+ async function checkSoundbankImpl(input) {
2386
+ const bankPath = resolve(input.bankPath);
2387
+ const v = validate("soundbank", parseJson(await readFile(bankPath, "utf8")));
2388
+ if (!v.ok) return fail$3(v.formatted);
2389
+ const bank = v.value;
2390
+ const dir = dirname(bankPath);
2391
+ const issues = [];
2392
+ const licenses = {};
2393
+ let clips = 0;
2394
+ let bytes = 0;
2395
+ for (const [id, entry] of Object.entries(bank.sounds)) {
2396
+ const at = `/sounds/${id}`;
2397
+ licenses[entry.source.license] = (licenses[entry.source.license] ?? 0) + 1;
2398
+ if (!entry.description) issues.push({
2399
+ path: at,
2400
+ message: "no description (agents choose sounds by it)",
2401
+ severity: "notice"
2402
+ });
2403
+ if (!entry.source.url && !entry.source.prompt && !entry.source.site) issues.push({
2404
+ path: `${at}/source`,
2405
+ message: "no origin: add url, site or prompt",
2406
+ severity: "notice"
2407
+ });
2408
+ for (const [i, clip] of entry.clips.entries()) {
2409
+ let data;
2410
+ try {
2411
+ data = new Uint8Array(await readFile(join(dir, clip)));
2412
+ } catch {
2413
+ issues.push({
2414
+ path: `${at}/clips/${i}`,
2415
+ message: `missing file ${clip}`,
2416
+ severity: "error"
2417
+ });
2418
+ continue;
2419
+ }
2420
+ clips++;
2421
+ bytes += data.length;
2422
+ if (i === 0 && entry.hash) {
2423
+ if (`sha256:${createHash("sha256").update(data).digest("hex")}` !== entry.hash) issues.push({
2424
+ path: `${at}/hash`,
2425
+ message: `${clip} changed since import`,
2426
+ severity: "error"
2427
+ });
2428
+ }
2429
+ const probe = probeAudio(data);
2430
+ if (i === 0 && entry.durationS !== void 0 && probe.durationS !== void 0) {
2431
+ if (Math.abs(probe.durationS - entry.durationS) > .1) issues.push({
2432
+ path: `${at}/durationS`,
2433
+ message: `durationS ${entry.durationS} but ${clip} is ${probe.durationS.toFixed(3)}s`,
2434
+ severity: "error"
2435
+ });
2436
+ }
2437
+ if (entry.loopEnd !== void 0 && probe.durationS !== void 0 && entry.loopEnd > probe.durationS + .01) issues.push({
2438
+ path: `${at}/loopEnd`,
2439
+ message: `loopEnd ${entry.loopEnd} is past the end of ${clip} (${probe.durationS.toFixed(3)}s)`,
2440
+ severity: "error"
2441
+ });
2442
+ }
2443
+ }
2444
+ return {
2445
+ ok: !issues.some((i) => i.severity === "error"),
2446
+ id: bank.id,
2447
+ sounds: Object.keys(bank.sounds).length,
2448
+ clips,
2449
+ bytes,
2450
+ licenses,
2451
+ issues
2452
+ };
2453
+ }
2454
+ //#endregion
2455
+ //#region src/ops/audio-import.ts
2456
+ const fail$2 = (error) => ({
2457
+ ok: false,
2458
+ bankPath: "",
2459
+ warnings: [],
2460
+ error
2461
+ });
2462
+ /** Add a clip to a sound bank: copy it beside the bank, hash and probe it, record provenance. */
2463
+ function importSound(input) {
2464
+ return guardOp(fail$2, () => importSoundImpl(input));
2465
+ }
2466
+ async function importSoundImpl(input) {
2467
+ const warnings = [];
2468
+ const bankPath = resolve(input.bankPath);
2469
+ const bankDir = dirname(bankPath);
2470
+ let bank;
2471
+ try {
2472
+ bank = parseJson(await readFile(bankPath, "utf8"));
2473
+ } catch (e) {
2474
+ if (e.code !== "ENOENT") throw e;
2475
+ bank = {
2476
+ format: "molen/soundbank@1",
2477
+ id: basename(bankDir),
2478
+ sounds: {}
2479
+ };
2480
+ warnings.push(`created ${bankPath}`);
2481
+ }
2482
+ const src = resolve(input.file);
2483
+ const bytes = new Uint8Array(await readFile(src));
2484
+ const inside = !relative(bankDir, src).startsWith("..") && !isAbsolute(relative(bankDir, src));
2485
+ let clip;
2486
+ if (inside) clip = relative(bankDir, src).split(sep).join("/");
2487
+ else {
2488
+ const dir = input.copyTo ?? "audio";
2489
+ clip = `${dir}/${basename(src)}`;
2490
+ await mkdir(join(bankDir, dir), { recursive: true });
2491
+ await copyFile(src, join(bankDir, clip));
2492
+ }
2493
+ const probe = probeAudio(bytes);
2494
+ if (probe.format === "unknown") warnings.push(`${basename(src)}: unrecognized audio format`);
2495
+ if (probe.format !== "mp3" && probe.format !== "unknown") warnings.push(`${basename(src)} is ${probe.format}; MP3 is the one format every browser decodes`);
2496
+ const durationS = input.durationS ?? probe.durationS;
2497
+ const hash = `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
2498
+ const previous = bank.sounds[input.id];
2499
+ const source = {
2500
+ license: input.license,
2501
+ ...input.site !== void 0 ? { site: input.site } : {},
2502
+ ...input.source !== void 0 ? { url: input.source } : {},
2503
+ ...input.author !== void 0 ? { author: input.author } : {},
2504
+ ...input.prompt !== void 0 ? { prompt: input.prompt } : {},
2505
+ ...input.generator !== void 0 ? { generator: input.generator } : {}
2506
+ };
2507
+ let entry;
2508
+ if (input.append && previous) {
2509
+ if (previous.clips.includes(clip)) return {
2510
+ ...fail$2(`${clip} is already a clip of ${input.id}`),
2511
+ bankPath
2512
+ };
2513
+ entry = {
2514
+ ...previous,
2515
+ clips: [...previous.clips, clip]
2516
+ };
2517
+ } else {
2518
+ entry = {
2519
+ clips: [clip],
2520
+ ...input.description !== void 0 ? { description: input.description } : {},
2521
+ ...input.loop !== void 0 ? { loop: input.loop } : {},
2522
+ ...input.loopStart !== void 0 ? { loopStart: input.loopStart } : {},
2523
+ ...input.loopEnd !== void 0 ? { loopEnd: input.loopEnd } : {},
2524
+ ...input.gain !== void 0 ? { gain: input.gain } : {},
2525
+ ...input.bus !== void 0 ? { bus: input.bus } : {},
2526
+ ...durationS !== void 0 ? { durationS: Math.round(durationS * 1e3) / 1e3 } : {},
2527
+ hash,
2528
+ source
2529
+ };
2530
+ if (previous) warnings.push(`replaced existing sound ${input.id}`);
2531
+ }
2532
+ if (durationS === void 0) warnings.push("duration unknown; pass --duration for music tracks");
2533
+ const next = {
2534
+ ...bank,
2535
+ sounds: {
2536
+ ...bank.sounds,
2537
+ [input.id]: entry
2538
+ }
2539
+ };
2540
+ const checked = validate("soundbank", next);
2541
+ if (!checked.ok) return {
2542
+ ...fail$2(checked.formatted),
2543
+ bankPath
2544
+ };
2545
+ await writeFile(bankPath, `${JSON.stringify(next, null, 2)}\n`);
2546
+ return {
2547
+ ok: true,
2548
+ bankPath,
2549
+ id: input.id,
2550
+ clip,
2551
+ entry,
2552
+ warnings
2553
+ };
2554
+ }
2555
+ //#endregion
2556
+ //#region src/ops/audio-plan.ts
2557
+ const fail$1 = (error) => ({
2558
+ ok: false,
2559
+ ticks: 0,
2560
+ tickRate: 0,
2561
+ banks: [],
2562
+ voices: [],
2563
+ oneShots: [],
2564
+ events: [],
2565
+ issues: [],
2566
+ warnings: [],
2567
+ timeline: "",
2568
+ error
2569
+ });
2570
+ /** Run a scene headlessly and report the sounds it would play, tick by tick. */
2571
+ function planAudio(input) {
2572
+ return guardOp(fail$1, () => planAudioImpl(input));
2573
+ }
2574
+ function vec(v) {
2575
+ return Array.isArray(v) && v.length === 3 && v.every((x) => typeof x === "number") ? v : void 0;
2576
+ }
2577
+ function towards(from, to) {
2578
+ if (!to) return [
2579
+ 0,
2580
+ 0,
2581
+ -1
2582
+ ];
2583
+ const d = [
2584
+ to[0] - from[0],
2585
+ to[1] - from[1],
2586
+ to[2] - from[2]
2587
+ ];
2588
+ const len = Math.hypot(...d);
2589
+ return len > 1e-9 ? [
2590
+ d[0] / len,
2591
+ d[1] / len,
2592
+ d[2] / len
2593
+ ] : [
2594
+ 0,
2595
+ 0,
2596
+ -1
2597
+ ];
2598
+ }
2599
+ function transformOf(world, id) {
2600
+ const t = world.get(id, { name: "transform" });
2601
+ return {
2602
+ ...vec(t?.pos) ? { pos: vec(t?.pos) } : {},
2603
+ ...Array.isArray(t?.rot) ? { rot: t?.rot } : {}
2604
+ };
2605
+ }
2606
+ /** Where the ears are for a headless run: a named entity, else the scene camera. */
2607
+ function listenerFor(world, manifest, entity) {
2608
+ if (entity !== void 0) {
2609
+ const { pos, rot } = transformOf(world, entity);
2610
+ if (!pos) return {};
2611
+ return {
2612
+ position: pos,
2613
+ forward: rot ? quatRotateVec3(rot, [
2614
+ 0,
2615
+ 0,
2616
+ -1
2617
+ ]) : [
2618
+ 0,
2619
+ 0,
2620
+ -1
2621
+ ],
2622
+ up: [
2623
+ 0,
2624
+ 1,
2625
+ 0
2626
+ ]
2627
+ };
2628
+ }
2629
+ const c = manifest.camera;
2630
+ if (!c) return { position: [
2631
+ 0,
2632
+ 0,
2633
+ 0
2634
+ ] };
2635
+ if (c.mode === "top-down-ortho") return {
2636
+ position: [
2637
+ c.center[0],
2638
+ c.cameraHeight ?? 50,
2639
+ c.center[1]
2640
+ ],
2641
+ forward: [
2642
+ 0,
2643
+ -1,
2644
+ 0
2645
+ ],
2646
+ up: [
2647
+ 0,
2648
+ 0,
2649
+ -1
2650
+ ]
2651
+ };
2652
+ if (c.mode === "follow") {
2653
+ const { pos } = transformOf(world, c.entity);
2654
+ if (!pos) return {};
2655
+ const eye = [
2656
+ pos[0] + c.offset[0],
2657
+ pos[1] + c.offset[1],
2658
+ pos[2] + c.offset[2]
2659
+ ];
2660
+ return {
2661
+ position: eye,
2662
+ forward: towards(eye, [
2663
+ pos[0] + c.lookOffset[0],
2664
+ pos[1] + c.lookOffset[1],
2665
+ pos[2] + c.lookOffset[2]
2666
+ ]),
2667
+ up: [
2668
+ 0,
2669
+ 1,
2670
+ 0
2671
+ ]
2672
+ };
2673
+ }
2674
+ return {
2675
+ position: c.position,
2676
+ forward: towards(c.position, c.lookAt),
2677
+ up: [
2678
+ 0,
2679
+ 1,
2680
+ 0
2681
+ ]
2682
+ };
2683
+ }
2684
+ async function loadBanks(paths, project) {
2685
+ const inputs = [];
2686
+ const labels = [];
2687
+ if (paths && paths.length > 0) {
2688
+ for (const path of paths) {
2689
+ const v = validate("soundbank", parseJson(await readFile(path, "utf8")));
2690
+ if (!v.ok) return `${path}:\n${v.formatted}`;
2691
+ inputs.push({
2692
+ doc: v.value,
2693
+ base: relative(process.cwd(), dirname(resolve(path)))
2694
+ });
2695
+ labels.push(path);
2696
+ }
2697
+ return {
2698
+ inputs,
2699
+ labels
2700
+ };
2701
+ }
2702
+ const set = project?.packs ?? await openProjectPacks(void 0);
2703
+ for (const { pack, path } of set.provided("soundbank")) {
2704
+ const v = validate("soundbank", await pack.readJson(path));
2705
+ if (!v.ok) return `${pack.manifest.id}/${path}:\n${v.formatted}`;
2706
+ const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/") + 1) : "";
2707
+ inputs.push({
2708
+ doc: v.value,
2709
+ base: `pack:${pack.manifest.id}/${dir}`
2710
+ });
2711
+ labels.push(`${pack.manifest.id}@${pack.manifest.version}:${path}`);
2712
+ }
2713
+ if (inputs.length === 0) return "no sound bank: pass --bank <file>, add a pack providing \"soundbank\" to project.json, or set MOLEN_PACKS";
2714
+ return {
2715
+ inputs,
2716
+ labels
2717
+ };
2718
+ }
2719
+ async function planAudioImpl(input) {
2720
+ let manifest;
2721
+ let types;
2722
+ let project;
2723
+ let buildOpts = {};
2724
+ if (input.scene !== void 0) {
2725
+ const v = validate("scene", input.scene);
2726
+ if (!v.ok) return fail$1(v.formatted);
2727
+ manifest = v.value;
2728
+ } else {
2729
+ if (input.scenePath === void 0) return fail$1("planAudio: provide scenePath or scene");
2730
+ const loaded = await loadSceneDocument(input.scenePath, { ...input.projectPath !== void 0 ? { projectPath: input.projectPath } : {} });
2731
+ manifest = loaded.manifest;
2732
+ types = loaded.project?.resolvedTypes;
2733
+ project = loaded.project;
2734
+ buildOpts = await sceneBuildOptionsFor(loaded);
2735
+ }
2736
+ let commands = input.commands ?? [];
2737
+ if (input.commandsPath !== void 0) {
2738
+ const raw = parseJson(await readFile(input.commandsPath, "utf8"));
2739
+ const list = Array.isArray(raw) ? raw : raw.commands;
2740
+ if (!Array.isArray(list)) return fail$1(`${input.commandsPath}: expected an array of commands`);
2741
+ commands = [];
2742
+ for (const [i, c] of list.entries()) {
2743
+ const v = validate("command", c);
2744
+ if (!v.ok) return fail$1(`command[${i}] invalid:\n${v.formatted}`);
2745
+ commands.push(v.value);
2746
+ }
2747
+ }
2748
+ let setup;
2749
+ const setupModule = resolveSetupModule(input.setupModule, project);
2750
+ if (setupModule !== void 0) setup = await loadSetupLike(setupModule);
2751
+ const banks = await loadBanks(input.bankPaths, project);
2752
+ if (typeof banks === "string") return fail$1(banks);
2753
+ const bank = mergeSoundbanks(banks.inputs);
2754
+ const warnings = [];
2755
+ const director = new AudioDirector({
2756
+ bank,
2757
+ onWarning: (m) => warnings.push(m)
2758
+ });
2759
+ const build = await prepareSceneBuilder(manifest, setup, {
2760
+ ...buildOpts,
2761
+ ...types !== void 0 ? { types } : {}
2762
+ });
2763
+ let weather = void 0;
2764
+ if (input.weather !== void 0) try {
2765
+ weather = weatherProfile(input.weather);
2766
+ } catch {
2767
+ return fail$1(`unknown weather profile "${input.weather}" (sunny, partly-cloudy, overcast, rain, snow, fog)`);
2768
+ }
2769
+ const issues = [];
2770
+ const voices = /* @__PURE__ */ new Map();
2771
+ const done = [];
2772
+ const oneShots = [];
2773
+ const events = [];
2774
+ let tickRate = 30;
2775
+ let detach;
2776
+ let lastTick = 0;
2777
+ const record = (cmds, tick) => {
2778
+ for (const cmd of cmds) if (cmd.op === "start") if (cmd.loop || cmd.voice.startsWith("music:")) {
2779
+ const entity = cmd.voice.startsWith("src:") ? cmd.voice.slice(4, cmd.voice.lastIndexOf("~")) : void 0;
2780
+ voices.set(cmd.voice, {
2781
+ voice: cmd.voice,
2782
+ sound: cmd.sound,
2783
+ bus: cmd.bus,
2784
+ startTick: tick,
2785
+ peakGain: cmd.gain,
2786
+ pitch: [cmd.pitch, cmd.pitch],
2787
+ ...entity !== void 0 ? { entity } : {}
2788
+ });
2789
+ } else oneShots.push({
2790
+ tick,
2791
+ sound: cmd.sound,
2792
+ bus: cmd.bus,
2793
+ ...cmd.spatial ? { position: cmd.spatial.position } : {}
2794
+ });
2795
+ else if (cmd.op === "set") {
2796
+ const v = voices.get(cmd.voice);
2797
+ if (v && cmd.gain !== void 0) v.peakGain = Math.max(v.peakGain, cmd.gain);
2798
+ if (v && cmd.pitch !== void 0) v.pitch = [Math.min(v.pitch[0], cmd.pitch), Math.max(v.pitch[1], cmd.pitch)];
2799
+ } else if (cmd.op === "stop") {
2800
+ const v = voices.get(cmd.voice);
2801
+ if (v) {
2802
+ voices.delete(cmd.voice);
2803
+ done.push({
2804
+ ...v,
2805
+ stopTick: tick
2806
+ });
2807
+ }
2808
+ }
2809
+ };
2810
+ const staticCheck = (world) => {
2811
+ const source = entitySourceFromWorld(world);
2812
+ for (const component of [
2813
+ "audioSource",
2814
+ "audioZone",
2815
+ "audioEnvironment"
2816
+ ]) for (const [id, data] of source.each(component)) {
2817
+ for (const ref of audioSoundRefs(component, data)) {
2818
+ if (bank.resolve(ref.sound)) continue;
2819
+ const near = nearestWithDistance(ref.sound, [...bank.ids()]);
2820
+ issues.push({
2821
+ path: `/entities/${id}/components/${component}${ref.path}`,
2822
+ message: `unknown sound "${ref.sound}"${near ? `; did you mean "${near.candidate}"?` : ""}`
2823
+ });
2824
+ }
2825
+ for (const ref of audioSignalRefs(component, data)) for (const issue of audioSignalIssues(ref.signal)) issues.push({
2826
+ path: `/entities/${id}/components/${component}${ref.path}`,
2827
+ message: `${issue.message}${issue.hint ? `; ${issue.hint}` : ""}`
2828
+ });
2829
+ }
2830
+ };
2831
+ runHeadless(build, {
2832
+ commands,
2833
+ ticks: input.ticks,
2834
+ onTick(world) {
2835
+ if (!detach) {
2836
+ tickRate = world.tickRate;
2837
+ const source = entitySourceFromWorld(world);
2838
+ director.setBank(bank);
2839
+ detach = source.onEvent?.((event, tick) => {
2840
+ director.handleEvent(event, tick);
2841
+ if (event.type.startsWith("audio.")) events.push({
2842
+ tick,
2843
+ type: event.type,
2844
+ payload: event.payload
2845
+ });
2846
+ });
2847
+ staticCheck(world);
2848
+ }
2849
+ lastTick = world.tick;
2850
+ const listener = listenerFor(world, manifest, input.listener);
2851
+ record(director.update({
2852
+ nowMs: world.tick * 1e3 / world.tickRate,
2853
+ listener: {
2854
+ ...listener,
2855
+ ...input.mode !== void 0 ? { mode: input.mode } : {}
2856
+ },
2857
+ source: entitySourceFromWorld(world),
2858
+ signals: {
2859
+ ...weather ? { weather } : {},
2860
+ ...input.daylight !== void 0 ? { sky: { daylight: input.daylight } } : {}
2861
+ }
2862
+ }), world.tick);
2863
+ }
2864
+ });
2865
+ detach?.();
2866
+ const all = [...done, ...voices.values()].sort((a, b) => a.startTick - b.startTick);
2867
+ const lines = [];
2868
+ lines.push(`${input.ticks} ticks at ${tickRate} Hz, banks: ${banks.labels.join(", ")}`);
2869
+ lines.push(all.length > 0 ? "loops:" : "loops: none");
2870
+ for (const v of all) {
2871
+ const span = `[${v.startTick} → ${v.stopTick ?? "end"}]`.padEnd(14);
2872
+ const at = v.entity !== void 0 ? ` @${v.entity}` : "";
2873
+ const pitch = v.pitch[0] === v.pitch[1] ? v.pitch[0].toFixed(2) : `${v.pitch[0].toFixed(2)}–${v.pitch[1].toFixed(2)}`;
2874
+ lines.push(` ${span} ${v.sound}${at} bus ${v.bus} peak ${v.peakGain.toFixed(2)} pitch ${pitch}`);
2875
+ }
2876
+ lines.push(oneShots.length > 0 ? `one-shots (${oneShots.length}):` : "one-shots: none");
2877
+ for (const s of oneShots.slice(0, 200)) {
2878
+ const at = s.position ? ` at [${s.position.map((x) => Math.round(x * 10) / 10).join(", ")}]` : "";
2879
+ lines.push(` t=${String(s.tick).padEnd(6)} ${s.sound}${at} (${s.bus})`);
2880
+ }
2881
+ if (oneShots.length > 200) lines.push(` … ${oneShots.length - 200} more`);
2882
+ for (const i of issues) lines.push(`✗ ${i.path}: ${i.message}`);
2883
+ for (const w of warnings) lines.push(`! ${w}`);
2884
+ return {
2885
+ ok: issues.length === 0 && !warnings.some((w) => w.startsWith("unknown sound")),
2886
+ ticks: lastTick,
2887
+ tickRate,
2888
+ banks: banks.labels,
2889
+ voices: all,
2890
+ oneShots,
2891
+ events,
2892
+ issues,
2893
+ warnings,
2894
+ timeline: lines.join("\n")
2895
+ };
2896
+ }
2897
+ //#endregion
2093
2898
  //#region src/ops/camera.ts
2094
2899
  /**
2095
2900
  * The camera a capture uses: an explicit override wins; otherwise the scene's own `camera`
@@ -2132,6 +2937,14 @@ function literal(value) {
2132
2937
  if (typeof value !== "string") return String(value);
2133
2938
  return `'${value.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;
2134
2939
  }
2940
+ /** True when a node prints as a top-level `a | b` union. */
2941
+ function isUnion(node) {
2942
+ if (node === void 0 || node.const !== void 0) return false;
2943
+ if (node.enum !== void 0) return node.enum.length > 1;
2944
+ const union = node.anyOf ?? node.oneOf;
2945
+ if (union !== void 0) return union.length > 1;
2946
+ return Array.isArray(node.type) && node.type.length > 1;
2947
+ }
2135
2948
  /** Print a JSON Schema node as a TS type expression. Unknown constructs degrade to `unknown`. */
2136
2949
  function schemaToTsType(schema, indent = "") {
2137
2950
  const node = schema;
@@ -2155,7 +2968,7 @@ function schemaToTsType(schema, indent = "") {
2155
2968
  if (node.prefixItems !== void 0) return `[${node.prefixItems.map((p) => schemaToTsType(p, indent)).join(", ")}]`;
2156
2969
  const item = node.items !== void 0 ? schemaToTsType(node.items, indent) : "unknown";
2157
2970
  if (node.minItems !== void 0 && node.minItems === node.maxItems && node.minItems > 0 && node.minItems <= 8) return `[${Array.from({ length: node.minItems }, () => item).join(", ")}]`;
2158
- return `${item}[]`;
2971
+ return isUnion(node.items) ? `(${item})[]` : `${item}[]`;
2159
2972
  }
2160
2973
  case "object": {
2161
2974
  const props = node.properties ?? {};
@@ -2217,7 +3030,8 @@ const CAPABILITY_DOC = {
2217
3030
  physics: "Rapier queries: raycast / overlapSphere / velocityOf (see guide/physics.md).",
2218
3031
  terrain: "Terrain sampling: heightAt / normalAt / slopeAt / raycast (see guide/terrain.md).",
2219
3032
  figures: "Figure verbs: mount / dismount / socket / … (see guide/figures.md).",
2220
- worldgen: "Worldgen queries: buildingAt / … (see guide/worldgen.md)."
3033
+ worldgen: "Worldgen queries: buildingAt / … (see guide/worldgen.md).",
3034
+ ambient: "Ambient life: stats / laneAt / agentsNear / setObserver / addRoad / … (see guide/ambient-life.md)."
2221
3035
  };
2222
3036
  function quote$1(value) {
2223
3037
  return `'${value.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;
@@ -2421,6 +3235,29 @@ function renderScriptTypes(input) {
2421
3235
  "",
2422
3236
  ...renderMath(),
2423
3237
  "",
3238
+ "/** Options for `molen.audio.play`. Omit entity and position for a non-positional sound. */",
3239
+ "interface MolenAudioPlayOptions {",
3240
+ " /** Play at (and follow) this entity's transform. */",
3241
+ " entity?: MolenEntityId;",
3242
+ " /** Play at a fixed world position. */",
3243
+ " position?: MolenVec3;",
3244
+ " gain?: number;",
3245
+ " pitch?: number;",
3246
+ " bus?: string;",
3247
+ " /** Loop until stopped; default the sound's own loop flag. */",
3248
+ " loop?: boolean;",
3249
+ "}",
3250
+ "",
3251
+ "/** `molen.audio`: each call emits an `audio.*` event the client plays (guide/audio.md). */",
3252
+ "interface MolenAudioApi {",
3253
+ " /** Play a sound-bank id; returns a handle for `stop`. */",
3254
+ " play(sound: string, opts?: MolenAudioPlayOptions): string;",
3255
+ " /** Stop by handle, or every voice matching an entity and/or sound. */",
3256
+ " stop(target: string | { entity?: MolenEntityId; sound?: string }, fadeS?: number): void;",
3257
+ " /** Switch background music to a track or playlist; null stops it. */",
3258
+ " music(playlist: string | string[] | null, opts?: { crossfadeS?: number }): void;",
3259
+ "}",
3260
+ "",
2424
3261
  "/** The verb set injected into every scene-data script as `molen`. */",
2425
3262
  "interface MolenApi {",
2426
3263
  " /** Spawn from a component map. */",
@@ -2477,6 +3314,8 @@ function renderScriptTypes(input) {
2477
3314
  " handler: (payload: MolenCommands[T], ctx: MolenTickContext, command: MolenCommand) => void,",
2478
3315
  " ): MolenUnsubscribe;",
2479
3316
  " emit(type: string, payload?: MolenJsonValue): void;",
3317
+ " /** Sound: play/stop one-shots and loops, switch music. Never affects the simulation. */",
3318
+ " readonly audio: MolenAudioApi;",
2480
3319
  " raycast(origin: MolenVec3, dir: MolenVec3, maxDist: number, mask?: number): MolenRayHit | null;",
2481
3320
  " overlapCircle(center: MolenVec3, radius: number, mask?: number): string[];",
2482
3321
  " /** Emit `event` after `ticks` ticks (snapshot-safe world timer). Returns the timer id. */",
@@ -2556,6 +3395,7 @@ function capabilitiesFor(manifest) {
2556
3395
  const caps = ["figures"];
2557
3396
  if (manifest.physics?.engine === "rapier") caps.push("physics");
2558
3397
  if (manifest.terrain !== void 0) caps.push("terrain");
3398
+ if (manifest.ambient !== void 0) caps.push("ambient");
2559
3399
  return caps;
2560
3400
  }
2561
3401
  function componentsFor(registry) {
@@ -2684,7 +3524,7 @@ async function loadTypeScript(projectDir) {
2684
3524
  */
2685
3525
  function typescriptNotFoundError(projectDir) {
2686
3526
  return [
2687
- "typescript not found — molen scripts check compiles with the project's own TypeScript",
3527
+ "typescript not found — molen scripts check compiles with the project's own TypeScript",
2688
3528
  ` install it in ${projectDir}:`,
2689
3529
  " npm install # the scaffold lists typescript as a devDependency",
2690
3530
  " or add it directly:",
@@ -2723,7 +3563,7 @@ function diagnosticsFor(ts, target, projectDir) {
2723
3563
  }
2724
3564
  const { line, character } = d.file.getLineAndCharacterOfPosition(d.start);
2725
3565
  out.push({
2726
- file: relative(projectDir, d.file.fileName),
3566
+ file: relative(projectDir, d.file.fileName).replaceAll("\\", "/"),
2727
3567
  line: line + 1,
2728
3568
  column: character + 1,
2729
3569
  code: `TS${d.code}`,
@@ -2758,7 +3598,7 @@ async function checkScripts(input) {
2758
3598
  ok: false,
2759
3599
  stale,
2760
3600
  ungenerated,
2761
- error: `script declarations are ${stale.length > 0 ? "stale" : "missing"} — run: molen types gen`
3601
+ error: `script declarations are ${stale.length > 0 ? "stale" : "missing"} — run: molen types gen`
2762
3602
  };
2763
3603
  const ts = await loadTypeScript(project.dir);
2764
3604
  if (ts === void 0) return {
@@ -3090,7 +3930,7 @@ const OPS_CATALOG = [
3090
3930
  },
3091
3931
  {
3092
3932
  name: "fetch_pack",
3093
- summary: "Download content packs (a pack URL, or a molen/pack-index@1 URL) into the project and pin them in project.json `packs` with their contentHash, so the project runs offline.",
3933
+ summary: "Download content packs (a pack URL, or a molen/pack-index@1 URL) into the project, list them in index.json in the download directory (so a page can open them), and pin them in project.json `packs` with their contentHash, so the project runs offline.",
3094
3934
  cli: "molen pack fetch <url> [ids…] [--out-dir <d>] [--project <path>]",
3095
3935
  mcpTool: "fetch_pack",
3096
3936
  params: [
@@ -3101,6 +3941,57 @@ const OPS_CATALOG = [
3101
3941
  cwdParam()
3102
3942
  ]
3103
3943
  },
3944
+ {
3945
+ name: "plan_audio",
3946
+ summary: "Run a scene headlessly and list the sounds it would play: looping voices with start/stop ticks, peak gain and pitch range, one-shots by tick, audio.* script events, and unknown sound ids or signals. Hear a scene's audio annotations without a browser.",
3947
+ cli: "molen audio plan <scene|name> --ticks <N> [--bank <bank.json,…>] [--commands <f>] [--setup <m>] [--listener <entity>] [--mode <walk|drive|fly>] [--weather <profile>] [--daylight <0..1>] [--project <project.json>] [--json]",
3948
+ mcpTool: "plan_audio",
3949
+ params: [
3950
+ p("scenePath", "string", true, "Scene file path or project scene name."),
3951
+ p("ticks", "int>0", true, "Ticks to simulate."),
3952
+ p("bankPaths", "string[]", false, "molen/soundbank@1 files (default: every provides.soundbank in the project's packs)."),
3953
+ p("commandsPath", "string", false, "JSON array (or {commands:[...]}) of command envelopes."),
3954
+ p("setupModule", "string", false, "ESM module exporting setup(world, manifest)."),
3955
+ p("listener", "string", false, "Entity whose transform is the listener (default: the scene camera)."),
3956
+ p("mode", "string", false, "listener.mode for rules: walk, drive, fly…"),
3957
+ p("weather", "string", false, "Weather profile: sunny, partly-cloudy, overcast, rain, snow, fog."),
3958
+ p("daylight", "number", false, "sky.daylight 0 (night) – 1 (day); default 1."),
3959
+ projectPathParam()
3960
+ ]
3961
+ },
3962
+ {
3963
+ name: "import_sound",
3964
+ summary: "Add an audio clip to a molen/soundbank@1 file: copy it beside the bank, hash it, probe its duration, and record license and provenance. --append adds a variation to an existing sound.",
3965
+ cli: "molen audio import <file> --id <sound.id> --bank <bank.json> --license <spdx> [--source <url>] [--site s] [--author a] [--prompt p] [--generator g] [--description d] [--loop] [--loop-start s] [--loop-end s] [--bus b] [--gain g] [--duration s] [--append] [--copy-to <dir>]",
3966
+ mcpTool: "import_sound",
3967
+ params: [
3968
+ p("file", "string", true, "Audio file (MP3 recommended; WAV and Ogg accepted)."),
3969
+ p("id", "string", true, "Sound id, e.g. \"ambience.rain.medium\"."),
3970
+ p("bankPath", "string", true, "Sound bank JSON to update (created when missing)."),
3971
+ p("license", "string", true, "SPDX license of the recording, e.g. \"CC0-1.0\"."),
3972
+ p("source", "string", false, "Page of the original recording."),
3973
+ p("site", "string", false, "Origin site: freesound, kenney, opengameart, …"),
3974
+ p("author", "string", false, "Recordist or creator."),
3975
+ p("prompt", "string", false, "Generation prompt, for generated clips."),
3976
+ p("generator", "string", false, "Generator/model name, for generated clips."),
3977
+ p("description", "string", false, "What it sounds like (agents choose sounds by it)."),
3978
+ p("loop", "boolean", false, "Loop the clip (ambience, engines)."),
3979
+ p("loopStart", "number", false, "Loop start in seconds."),
3980
+ p("loopEnd", "number", false, "Loop end in seconds."),
3981
+ p("bus", "string", false, "Default bus: music, ambience, sfx, ui, voice."),
3982
+ p("gain", "number", false, "Base gain (default 1)."),
3983
+ p("durationS", "number", false, "Duration in seconds; overrides the probed value."),
3984
+ p("append", "boolean", false, "Add as another variation of an existing sound."),
3985
+ p("copyTo", "string", false, "Directory under the bank for copied files (default audio).")
3986
+ ]
3987
+ },
3988
+ {
3989
+ name: "check_soundbank",
3990
+ summary: "Check a molen/soundbank@1 file and every clip it names: files present, hashes unchanged, durations and loop points consistent, provenance recorded; prints a license summary.",
3991
+ cli: "molen audio check <bank.json>",
3992
+ mcpTool: "check_soundbank",
3993
+ params: [p("bankPath", "string", true, "Sound bank JSON.")]
3994
+ },
3104
3995
  {
3105
3996
  name: "test_types",
3106
3997
  summary: "Smoke-test every registry type standalone: resolved shape validates, spawns, and survives N simulated ticks.",
@@ -3129,14 +4020,15 @@ const OPS_CATALOG = [
3129
4020
  {
3130
4021
  name: "import_asset",
3131
4022
  summary: "Import a glTF/GLB: normalize, extract bounds + collision (hulls/trimesh), write the asset sidecar, register in project.json.",
3132
- cli: "molen asset import <file.glb> [--id <asset-id>] [--trimesh] [--no-optimize] [--out-dir <d>] [--project <project.json>] [--force]",
4023
+ cli: "molen asset import <file.glb> [--id <asset-id>] [--trimesh] [--no-optimize] [--out-dir <d>] [--asset-dir <d>] [--project <project.json>] [--force]",
3133
4024
  mcpTool: "import_asset",
3134
4025
  params: [
3135
4026
  p("path", "string", true, "Source .glb/.gltf file."),
3136
4027
  p("id", "string", false, "Asset id (default: slugged filename; dotted ids join a namespace)."),
3137
4028
  p("trimesh", "boolean", false, "Also extract a whole-asset collision trimesh (collision.bin)."),
3138
4029
  p("optimize", "boolean", false, "Normalize pass dedup/prune/weld/quantize (default true)."),
3139
- p("outDir", "string", false, "Assets root override (default: <project dir>/assets)."),
4030
+ p("outDir", "string", false, "Assets root override; retains root/id layout. Mutually exclusive with assetDir."),
4031
+ p("assetDir", "string", false, "Exact bundle directory, relative to cwd. Mutually exclusive with outDir. Omit both to preserve an existing project asset directory."),
3140
4032
  p("projectPath", "string", false, "project.json to register into. Required when the source file sits in a different project than the cwd."),
3141
4033
  cwdParam(),
3142
4034
  p("force", "boolean", false, "Replace an existing asset directory (default false).")
@@ -3288,6 +4180,21 @@ const OPS_CATALOG = [
3288
4180
  p("dumpPath", "string", false, "Write the adapted molen/worldgen-batch@1 here.")
3289
4181
  ]
3290
4182
  },
4183
+ {
4184
+ name: "network_bake",
4185
+ summary: "Bake the roads, railways and paths of a local terrain package into a molen/transport-network@1 document for ambient traffic in scenes without map tiles.",
4186
+ cli: "molen network bake <terrain-package.json> (--tile z/x/y [--radius n] | --bbox w,s,e,n) --out network.json [--classes road,rail,path] [--heights] [--json]",
4187
+ mcpTool: "network_bake",
4188
+ params: [
4189
+ p("packagePath", "string", true, "terrain-package.json path (local PMTiles archives)."),
4190
+ p("tile", "string", false, "Centre tile \"z/x/y\" at the finest features level."),
4191
+ p("radius", "number", false, "Tiles around the centre tile to include (default 0)."),
4192
+ p("bbox", "number[4]", false, "Area [west, south, east, north] in degrees, instead of tile."),
4193
+ p("classes", "string[]", false, "Classes to keep: 'road', 'rail', 'path' (default all)."),
4194
+ p("outPath", "string", true, "Write the transport-network document here."),
4195
+ p("heights", "boolean", false, "Include surface heights from the elevation (default flat).")
4196
+ ]
4197
+ },
3291
4198
  {
3292
4199
  name: "mcp_server",
3293
4200
  summary: "Start the MCP server over stdio (exposes every mcpTool in this catalog).",
@@ -4226,6 +5133,210 @@ async function generateTypes(input) {
4226
5133
  }
4227
5134
  }
4228
5135
  //#endregion
5136
+ //#region src/ops/pmtiles-node.ts
5137
+ /**
5138
+ * PMTiles over a local file for Node ops. The `pmtiles` package ships fetch and browser File
5139
+ * sources only; this range source reads through one file handle so the terrain package
5140
+ * adapters (elevation pyramid, semantic sidecars) work unchanged off disk.
5141
+ */
5142
+ var NodeFileRangeSource = class {
5143
+ path;
5144
+ handle;
5145
+ constructor(path) {
5146
+ this.path = path;
5147
+ }
5148
+ getKey() {
5149
+ return this.path;
5150
+ }
5151
+ async getBytes(offset, length) {
5152
+ this.handle ??= open(this.path, "r");
5153
+ const handle = await this.handle;
5154
+ const buffer = new Uint8Array(length);
5155
+ const { bytesRead } = await handle.read(buffer, 0, length, offset);
5156
+ return { data: buffer.buffer.slice(0, bytesRead) };
5157
+ }
5158
+ async close() {
5159
+ if (this.handle === void 0) return;
5160
+ const handle = await this.handle;
5161
+ this.handle = void 0;
5162
+ await handle.close();
5163
+ }
5164
+ };
5165
+ /** Open a local PMTiles archive; `archive` satisfies the terrain `TerrainTileArchive` seam. */
5166
+ function openNodePmtiles(path) {
5167
+ const source = new NodeFileRangeSource(path);
5168
+ return {
5169
+ archive: new PMTiles(source),
5170
+ source,
5171
+ close: () => source.close()
5172
+ };
5173
+ }
5174
+ //#endregion
5175
+ //#region src/ops/network-bake.ts
5176
+ /**
5177
+ * Bake the roads, railways and paths of a local terrain package into a
5178
+ * `molen/transport-network@1` document, so a scene without streamed map tiles can run ambient
5179
+ * traffic on real streets. Tiles load at the features sidecar's finest level, stitch across their
5180
+ * borders, and are recentred on the baked area (its geographic centre is recorded as `origin`).
5181
+ */
5182
+ const MAX_TILES = 64;
5183
+ function archivePath$1(source) {
5184
+ if (source.kind === "pmtiles-set" || !("path" in source)) throw new Error("network bake reads single local PMTiles archives only");
5185
+ return source.path;
5186
+ }
5187
+ function parseTile$1(text) {
5188
+ const parts = text.split("/").map(Number);
5189
+ if (parts.length !== 3 || parts.some((value) => !Number.isSafeInteger(value) || value < 0)) throw new Error(`tile must be "z/x/y", got "${text}"`);
5190
+ return {
5191
+ level: parts[0],
5192
+ x: parts[1],
5193
+ z: parts[2]
5194
+ };
5195
+ }
5196
+ /** Bake a terrain package's transport features into a transport-network document. */
5197
+ function bakeNetwork(input) {
5198
+ return guardOp((error) => ({
5199
+ ok: false,
5200
+ error
5201
+ }), () => bakeNetworkImpl(input));
5202
+ }
5203
+ async function bakeNetworkImpl(input) {
5204
+ const packagePath = resolve(input.packagePath);
5205
+ const parsed = validateByKind("terrain-package", parseJson(await readFile(packagePath, "utf8")));
5206
+ if (!parsed.ok) return {
5207
+ ok: false,
5208
+ error: parsed.formatted
5209
+ };
5210
+ const pkg = parsed.value;
5211
+ if (pkg.features === void 0) return {
5212
+ ok: false,
5213
+ error: "the package has no features sidecar"
5214
+ };
5215
+ if (input.tile === void 0 && input.bbox === void 0) return {
5216
+ ok: false,
5217
+ error: "pass tile (z/x/y) or bbox (west,south,east,north)"
5218
+ };
5219
+ const dir = dirname(packagePath);
5220
+ const terrain = await import("@bendyline/molen-terrain/client");
5221
+ const elevation = openNodePmtiles(resolve(dir, archivePath$1(pkg.elevation.source)));
5222
+ const featuresPath = resolve(dir, archivePath$1(pkg.features.source));
5223
+ const features = openNodePmtiles(featuresPath);
5224
+ const landcoverPath = pkg.landcover !== void 0 ? resolve(dir, archivePath$1(pkg.landcover.source)) : void 0;
5225
+ const landcover = landcoverPath === void 0 ? void 0 : landcoverPath === featuresPath ? features : openNodePmtiles(landcoverPath);
5226
+ const warnings = [];
5227
+ try {
5228
+ const pyramid = await terrain.openTerrainPackagePyramid(pkg, { archive: elevation.archive });
5229
+ const sidecar = (await terrain.openTerrainPackageSemantics(pkg, {
5230
+ decoder: terrain.createProtomapsTerrainMvtDecoder(),
5231
+ featuresArchive: features.archive,
5232
+ ...landcover !== void 0 ? { landcoverArchive: landcover.archive } : {}
5233
+ })).features;
5234
+ if (sidecar === void 0) return {
5235
+ ok: false,
5236
+ error: "the features sidecar did not open"
5237
+ };
5238
+ const level = sidecar.maxLevel;
5239
+ const addresses = [];
5240
+ if (input.tile !== void 0) {
5241
+ const centre = parseTile$1(input.tile);
5242
+ if (centre.level !== level) warnings.push(`tile level ${centre.level} is not the finest features level ${level}`);
5243
+ const r = Math.max(0, Math.floor(input.radius ?? 0));
5244
+ for (let dz = -r; dz <= r; dz++) for (let dx = -r; dx <= r; dx++) addresses.push({
5245
+ level: centre.level,
5246
+ x: centre.x + dx,
5247
+ z: centre.z + dz
5248
+ });
5249
+ } else {
5250
+ const [west, south, east, north] = input.bbox;
5251
+ const a = wgs84ToWebMercatorTile(west, north, level);
5252
+ const b = wgs84ToWebMercatorTile(east, south, level);
5253
+ for (let z = Math.min(a.y, b.y); z <= Math.max(a.y, b.y); z++) for (let x = Math.min(a.x, b.x); x <= Math.max(a.x, b.x); x++) addresses.push({
5254
+ level,
5255
+ x,
5256
+ z
5257
+ });
5258
+ }
5259
+ if (addresses.length > MAX_TILES) return {
5260
+ ok: false,
5261
+ error: `${addresses.length} tiles requested; at most ${MAX_TILES}`
5262
+ };
5263
+ const descriptor = pyramid.descriptor;
5264
+ const origins = addresses.map((address) => terrainPyramidTileOrigin(descriptor, address));
5265
+ const sizes = addresses.map((address) => terrainPyramidTileSize(descriptor, address.level));
5266
+ let minX = Number.POSITIVE_INFINITY;
5267
+ let minZ = Number.POSITIVE_INFINITY;
5268
+ let maxX = Number.NEGATIVE_INFINITY;
5269
+ let maxZ = Number.NEGATIVE_INFINITY;
5270
+ origins.forEach((o, i) => {
5271
+ minX = Math.min(minX, o[0]);
5272
+ minZ = Math.min(minZ, o[1]);
5273
+ maxX = Math.max(maxX, o[0] + sizes[i]);
5274
+ maxZ = Math.max(maxZ, o[1] + sizes[i]);
5275
+ });
5276
+ const cx = (minX + maxX) / 2;
5277
+ const cz = (minZ + maxZ) / 2;
5278
+ const classes = new Set(input.classes ?? [
5279
+ "road",
5280
+ "rail",
5281
+ "path"
5282
+ ]);
5283
+ const network = new TransportNetwork({ classes: [
5284
+ ...classes.has("road") ? ["road"] : [],
5285
+ ...classes.has("rail") ? ["rail"] : [],
5286
+ ...classes.has("path") ? ["walk"] : []
5287
+ ] });
5288
+ let loaded = 0;
5289
+ for (const [i, address] of addresses.entries()) {
5290
+ const signal = new AbortController().signal;
5291
+ const tile = await sidecar.source.load(address, signal);
5292
+ if (tile === void 0) {
5293
+ warnings.push(`no features at ${address.level}/${address.x}/${address.z}`);
5294
+ continue;
5295
+ }
5296
+ const origin = origins[i];
5297
+ const heightfield = input.heights === true ? await pyramid.source.load(address, signal) : void 0;
5298
+ network.registerTile({
5299
+ key: `${address.level}/${address.x}/${address.z}`,
5300
+ origin: [origin[0] - cx, origin[1] - cz],
5301
+ tileSize: sizes[i],
5302
+ features: tile.transportation,
5303
+ ...tile.pois !== void 0 ? { pois: tile.pois } : {},
5304
+ sidewalks: false,
5305
+ ...heightfield !== void 0 ? { heightAt: (x, z) => heightfield.sampleHeight(x + cx, z + cz) } : {}
5306
+ });
5307
+ loaded++;
5308
+ }
5309
+ const [longitude, latitude] = worldToWgs84(descriptor.metersPerUnit ?? 1, cx, cz);
5310
+ const round = (v) => Math.round(v * 1e6) / 1e6;
5311
+ const origin = {
5312
+ latitude: round(latitude),
5313
+ longitude: round(longitude)
5314
+ };
5315
+ const doc = networkToDocument(network, {
5316
+ name: `${pkg.name} transport network`,
5317
+ origin
5318
+ }, { heights: input.heights === true });
5319
+ const counts = {};
5320
+ for (const way of doc.ways) counts[way.class] = (counts[way.class] ?? 0) + 1;
5321
+ const outPath = resolve(input.outPath);
5322
+ await mkdir(dirname(outPath), { recursive: true });
5323
+ await writeFile(outPath, `${JSON.stringify(doc)}\n`);
5324
+ return {
5325
+ ok: true,
5326
+ path: outPath,
5327
+ tiles: loaded,
5328
+ ways: doc.ways.length,
5329
+ classes: counts,
5330
+ origin,
5331
+ ...warnings.length > 0 ? { warnings } : {}
5332
+ };
5333
+ } finally {
5334
+ await elevation.close();
5335
+ await features.close();
5336
+ if (landcover !== void 0 && landcover !== features) await landcover.close();
5337
+ }
5338
+ }
5339
+ //#endregion
4229
5340
  //#region src/ops/pack.ts
4230
5341
  async function buildContentPack(input) {
4231
5342
  return guardOp((error) => ({
@@ -4433,6 +5544,15 @@ async function fetchContentPack(input) {
4433
5544
  size: bytes.length
4434
5545
  });
4435
5546
  }
5547
+ for (const pack of fetched) {
5548
+ const { file, version, contentHash, size } = pack;
5549
+ await recordInPackIndex(outDir, pack.id, {
5550
+ file,
5551
+ version,
5552
+ contentHash,
5553
+ size
5554
+ });
5555
+ }
4436
5556
  if (projectPath !== void 0) await updateProjectFile(projectPath, (manifest) => {
4437
5557
  for (const pack of fetched) {
4438
5558
  const file = relative(dirname(projectPath), join(outDir, pack.file));
@@ -4455,45 +5575,6 @@ async function fetchContentPack(input) {
4455
5575
  });
4456
5576
  }
4457
5577
  //#endregion
4458
- //#region src/ops/pmtiles-node.ts
4459
- /**
4460
- * PMTiles over a local file for Node ops. The `pmtiles` package ships fetch and browser File
4461
- * sources only; this range source reads through one file handle so the terrain package
4462
- * adapters (elevation pyramid, semantic sidecars) work unchanged off disk.
4463
- */
4464
- var NodeFileRangeSource = class {
4465
- path;
4466
- handle;
4467
- constructor(path) {
4468
- this.path = path;
4469
- }
4470
- getKey() {
4471
- return this.path;
4472
- }
4473
- async getBytes(offset, length) {
4474
- this.handle ??= open(this.path, "r");
4475
- const handle = await this.handle;
4476
- const buffer = new Uint8Array(length);
4477
- const { bytesRead } = await handle.read(buffer, 0, length, offset);
4478
- return { data: buffer.buffer.slice(0, bytesRead) };
4479
- }
4480
- async close() {
4481
- if (this.handle === void 0) return;
4482
- const handle = await this.handle;
4483
- this.handle = void 0;
4484
- await handle.close();
4485
- }
4486
- };
4487
- /** Open a local PMTiles archive; `archive` satisfies the terrain `TerrainTileArchive` seam. */
4488
- function openNodePmtiles(path) {
4489
- const source = new NodeFileRangeSource(path);
4490
- return {
4491
- archive: new PMTiles(source),
4492
- source,
4493
- close: () => source.close()
4494
- };
4495
- }
4496
- //#endregion
4497
5578
  //#region src/ops/project-ops.ts
4498
5579
  async function resolveProjectPath(input) {
4499
5580
  return input.projectPath ?? await findProjectFile(input.cwd ?? process.cwd());
@@ -4938,9 +6019,11 @@ async function locateTemplates() {
4938
6019
  async function loadTemplateBundle() {
4939
6020
  const root = await locateTemplates();
4940
6021
  if (root === void 0) throw new Error("Molen template bundle is missing; reinstall @bendyline/molen-tooling (in the engine repository, build the tooling package)");
6022
+ const index = JSON.parse(await readFile(join(root, "index.json"), "utf8"));
4941
6023
  return {
4942
6024
  root,
4943
- templates: JSON.parse(await readFile(join(root, "index.json"), "utf8")).templates
6025
+ templates: index.templates,
6026
+ versions: index.versions
4944
6027
  };
4945
6028
  }
4946
6029
  /** The sample templates `molen new --template <id>` can scaffold. */
@@ -5313,6 +6396,7 @@ export function project() {
5313
6396
  }
5314
6397
  `;
5315
6398
  const WORKER_TS = `/// <reference lib="webworker" />
6399
+ import { ambientCapability } from '@bendyline/molen-ambient/kernel';
5316
6400
  import { figuresScriptApi, installFigures } from '@bendyline/molen-figures/kernel';
5317
6401
  import { startKernelWorker } from '@bendyline/molen-kernel';
5318
6402
  // import { hardenScripts } from '@bendyline/molen-kernel';
@@ -5333,10 +6417,12 @@ startKernelWorker({
5333
6417
  ...project(),
5334
6418
  setup,
5335
6419
  // Figures (people and animals) are available to every scene: molen.figures.* in scripts.
5336
- capabilities: [(w) => ({ figures: figuresScriptApi(installFigures(w)) })],
6420
+ // Ambient traffic runs when the scene has an \`ambient\` block (molen.ambient.* in scripts).
6421
+ capabilities: [(w) => ({ figures: figuresScriptApi(installFigures(w)) }), ambientCapability()],
5337
6422
  });
5338
6423
  `;
5339
- const MAIN_TS = `import { mountExperience } from '@bendyline/molen-client';
6424
+ const MAIN_TS = `import { ambientVehicleKind } from '@bendyline/molen-ambient/client';
6425
+ import { mountExperience } from '@bendyline/molen-client';
5340
6426
  import { figureKind } from '@bendyline/molen-figures/client';
5341
6427
  import { project } from './project';
5342
6428
 
@@ -5350,7 +6436,7 @@ const { client } = await mountExperience({
5350
6436
  scene: project().scene,
5351
6437
  canvas,
5352
6438
  clearColor: '#11131a',
5353
- kinds: [figureKind()],
6439
+ kinds: [figureKind(), ambientVehicleKind()],
5354
6440
  });
5355
6441
 
5356
6442
  // A HUD from mirrored state: no wire-protocol parsing.
@@ -5398,9 +6484,19 @@ const TSCONFIG = `{
5398
6484
  "include": ["src", "setup.mjs"]
5399
6485
  }
5400
6486
  `;
5401
- function packageJson(name) {
5402
- const engine = `^${ENGINE_VERSION}`;
5403
- return `${JSON.stringify({
6487
+ /**
6488
+ * The range a new project declares for a Molen package: the version released with this CLI. Each
6489
+ * package has its own version line, and on 0.x a minor bump may break, so the caret pins the
6490
+ * project to the release it was generated from.
6491
+ */
6492
+ function molenRange(versions, name) {
6493
+ const version = versions[name];
6494
+ if (version === void 0) throw new Error(`the template bundle records no version for ${name}; rebuild the tooling`);
6495
+ return `^${version}`;
6496
+ }
6497
+ function packageJson(name, versions) {
6498
+ const molen = (pkg) => molenRange(versions, `@bendyline/molen-${pkg}`);
6499
+ const pkg = {
5404
6500
  name,
5405
6501
  private: true,
5406
6502
  type: "module",
@@ -5410,19 +6506,21 @@ function packageJson(name) {
5410
6506
  typecheck: "tsc -p tsconfig.json && tsc -p scenes/scripts/tsconfig.json"
5411
6507
  },
5412
6508
  dependencies: {
5413
- "@bendyline/molen-client": engine,
5414
- "@bendyline/molen-figures": engine,
5415
- "@bendyline/molen-kernel": engine,
5416
- "@bendyline/molen-schema": engine,
6509
+ "@bendyline/molen-ambient": molen("ambient"),
6510
+ "@bendyline/molen-client": molen("client"),
6511
+ "@bendyline/molen-figures": molen("figures"),
6512
+ "@bendyline/molen-kernel": molen("kernel"),
6513
+ "@bendyline/molen-schema": molen("schema"),
5417
6514
  three: "^0.184.0"
5418
6515
  },
5419
6516
  devDependencies: {
5420
- "@bendyline/molen-tooling": engine,
6517
+ "@bendyline/molen-tooling": molen("tooling"),
5421
6518
  "@types/three": "^0.184.0",
5422
6519
  typescript: "^6.0.3",
5423
6520
  vite: "^6.0.7"
5424
6521
  }
5425
- }, null, 2)}\n`;
6522
+ };
6523
+ return `${JSON.stringify(pkg, null, 2)}\n`;
5426
6524
  }
5427
6525
  function readme(name) {
5428
6526
  return `# ${name}
@@ -5607,15 +6705,15 @@ function templateLoop(template, scriptsCheck) {
5607
6705
  ...template.tests ? ["npm test"] : []
5608
6706
  ];
5609
6707
  }
5610
- /** The template's manifest as the new project's: its name, engine deps on this CLI's version line. */
5611
- function templatePackageJson(source, name) {
6708
+ /** The template's manifest as the new project's: its name, Molen deps released with this CLI. */
6709
+ function templatePackageJson(source, name, versions) {
5612
6710
  const { name: _name, ...manifest } = JSON.parse(source);
5613
- const onEngineLine = (deps) => deps === void 0 ? void 0 : Object.fromEntries(Object.entries(deps).map(([dep, spec]) => [dep, spec.startsWith("workspace:") ? `^${ENGINE_VERSION}` : spec]));
6711
+ const released = (deps) => deps === void 0 ? void 0 : Object.fromEntries(Object.entries(deps).map(([dep, spec]) => [dep, spec.startsWith("workspace:") ? molenRange(versions, dep) : spec]));
5614
6712
  const pkg = {
5615
6713
  name,
5616
6714
  ...manifest,
5617
- dependencies: onEngineLine(manifest.dependencies),
5618
- devDependencies: onEngineLine(manifest.devDependencies)
6715
+ dependencies: released(manifest.dependencies),
6716
+ devDependencies: released(manifest.devDependencies)
5619
6717
  };
5620
6718
  return `${JSON.stringify(pkg, null, 2)}\n`;
5621
6719
  }
@@ -5630,7 +6728,7 @@ async function scaffoldTemplate(input, dir) {
5630
6728
  const files = [];
5631
6729
  for (const rel of template.files) {
5632
6730
  const source = await readFile(join(bundle.root, template.id, rel));
5633
- files.push([rel, rel === "package.json" ? templatePackageJson(source.toString("utf8"), input.name) : source]);
6731
+ files.push([rel, rel === "package.json" ? templatePackageJson(source.toString("utf8"), input.name, bundle.versions) : source]);
5634
6732
  }
5635
6733
  if (!force) {
5636
6734
  const existing = await existingFiles(dir, [...files.map(([rel]) => rel), AGENTS_MD]);
@@ -5689,6 +6787,7 @@ async function scaffoldExperience(input) {
5689
6787
  ...input,
5690
6788
  template: input.template
5691
6789
  }, dir);
6790
+ const { versions } = await loadTemplateBundle();
5692
6791
  const files = [
5693
6792
  ["project.json", projectJson(input.name)],
5694
6793
  ["scenes/main.scene.json", sceneJson(input.name)],
@@ -5706,7 +6805,7 @@ async function scaffoldExperience(input) {
5706
6805
  ["src/vite-env.d.ts", VITE_ENV_DTS],
5707
6806
  ["vite.config.ts", VITE_CONFIG],
5708
6807
  ["tsconfig.json", TSCONFIG],
5709
- ["package.json", packageJson(input.name)],
6808
+ ["package.json", packageJson(input.name, versions)],
5710
6809
  ["README.md", readme(input.name)]
5711
6810
  ];
5712
6811
  const force = input.force === true;
@@ -6036,8 +7135,10 @@ async function runSimulationImpl(input) {
6036
7135
  ticks: input.ticks
6037
7136
  });
6038
7137
  const assertionResults = assertDoc ? runAssertions(headless.world, assertDoc, { events: headless.events }) : [];
7138
+ const allPass = assertionResults.every((r) => r.pass);
7139
+ const ambient = ambientOf(headless.world)?.stats();
6039
7140
  return {
6040
- ok: assertionResults.every((r) => r.pass),
7141
+ ok: allPass,
6041
7142
  tick: headless.world.tick,
6042
7143
  stateHash: headless.finalHash,
6043
7144
  ...buildOpts.content !== void 0 ? { content: buildOpts.content } : {},
@@ -6046,6 +7147,12 @@ async function runSimulationImpl(input) {
6046
7147
  assertionResults,
6047
7148
  assertionsFormatted: assertionResults.length > 0 ? formatAssertionResults(assertionResults) : void 0,
6048
7149
  ...manifest.physics !== void 0 ? { physics: manifest.physics.engine } : {},
7150
+ ...ambient !== void 0 ? { ambient: {
7151
+ agents: ambient.agents,
7152
+ spawned: ambient.spawned,
7153
+ despawned: ambient.despawned,
7154
+ lanes: ambient.network.lanes
7155
+ } } : {},
6049
7156
  ...notices.length > 0 ? { notices } : {}
6050
7157
  };
6051
7158
  }
@@ -7213,6 +8320,10 @@ join("capture", "worldgen-preview.html");
7213
8320
  */
7214
8321
  /** Local archive path of a package source; remote archives are not read by this Node op. */
7215
8322
  function archivePath(source) {
8323
+ if (source.kind === "pmtiles-set") {
8324
+ const location = "path" in source ? source.path : source.url;
8325
+ throw new Error(`archive set ${location} is not supported; worldgen stats reads single local PMTiles archives`);
8326
+ }
7216
8327
  if ("path" in source) return source.path;
7217
8328
  throw new Error(`archive ${source.url} is remote; worldgen stats reads local packages only`);
7218
8329
  }
@@ -7477,4 +8588,4 @@ function formatWorldgenStats(result) {
7477
8588
  registerCameraTrackSchema();
7478
8589
  registerExperiencePlaySchema();
7479
8590
  //#endregion
7480
- export { assetFileIndex as $, inspectContentPack as A, OPS_CATALOG as B, checkTypesOp as C, buildContentPack as D, reserveNamespace as E, listFigurePresets as F, ASSET_INDEX_FILE as G, formatOp as H, exportFrames as I, formatBytes as J, stageAssets as K, driveScene as L, generateTypes as M, renderTypesModule as N, extractContentPack as O, previewFigure as P, listAssets as Q, locateDocsRoot as R, rasterizeMaterial as S, projectInfo as T, checkScripts as U, describeOps as V, schemaToTsType as W, packAsset as X, formatPacked as Y, inspectAsset as Z, loadComponentRegistry as _, lineupBatchDoc as a, updateProjectFile as at, diffSnapshots as b, validateAsset as c, registerExperiencePlaySchema as ct, runSimulation as d, importAsset as et, screenshotScene as f, listSchemasOp as g, listComponentsOp as h, bakeWorldgen as i, loadSetupLike as it, verifyContentPack as j, fetchContentPack as k, applyUvPaintOp as l, getSchemaOp as m, worldgenStats as n, loadProject as nt, loadStylePackFromDisk as o, parseExperiencePlayScenario as ot, getComponentOp as p, screenshotAsset as q, previewWorldgen as r, loadSceneDocument as rt, simWatch as s, playExperience as st, formatWorldgenStats as t, findProjectFile as tt, testTypes as u, scaffoldExperience as v, listTypes as w, runReplayFile as x, listTemplates as y, searchDocs as z };
8591
+ export { formatPacked as $, inspectContentPack as A, searchDocs as B, checkTypesOp as C, buildContentPack as D, reserveNamespace as E, previewFigure as F, schemaToTsType as G, describeOps as H, listFigurePresets as I, checkSoundbank as J, planAudio as K, exportFrames as L, bakeNetwork as M, generateTypes as N, extractContentPack as O, renderTypesModule as P, formatBytes as Q, driveScene as R, rasterizeMaterial as S, projectInfo as T, formatOp as U, OPS_CATALOG as V, checkScripts as W, stageAssets as X, ASSET_INDEX_FILE as Y, screenshotAsset as Z, loadComponentRegistry as _, lineupBatchDoc as a, findProjectFile as at, diffSnapshots as b, validateAsset as c, loadSetupLike as ct, runSimulation as d, playExperience as dt, packAsset as et, screenshotScene as f, registerExperiencePlaySchema as ft, listSchemasOp as g, listComponentsOp as h, bakeWorldgen as i, importAsset as it, verifyContentPack as j, fetchContentPack as k, applyUvPaintOp as l, updateProjectFile as lt, getSchemaOp as m, worldgenStats as n, listAssets as nt, loadStylePackFromDisk as o, loadProject as ot, getComponentOp as p, importSound as q, previewWorldgen as r, assetFileIndex as rt, simWatch as s, loadSceneDocument as st, formatWorldgenStats as t, inspectAsset as tt, testTypes as u, parseExperiencePlayScenario as ut, scaffoldExperience as v, listTypes as w, runReplayFile as x, listTemplates as y, locateDocsRoot as z };