@ignifx/core 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (24) hide show
  1. package/dist/{environment-mr5wp69e.js → environment-BCjfp1jB.js} +2 -2
  2. package/dist/{environment-mr5wp69e.js.map → environment-BCjfp1jB.js.map} +1 -1
  3. package/dist/{ignifx-error-CRh89KUJ.js → ignifx-error-RpK-lWwE.js} +13 -2
  4. package/dist/ignifx-error-RpK-lWwE.js.map +1 -0
  5. package/dist/index.d.ts +1593 -677
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +2376 -238
  8. package/dist/index.js.map +1 -1
  9. package/dist/{material-plugin-BRnhfw7K.js → material-plugin-CWtV7DkH.js} +2 -2
  10. package/dist/{material-plugin-BRnhfw7K.js.map → material-plugin-CWtV7DkH.js.map} +1 -1
  11. package/dist/overlay-CjVgsfrm.js +239 -0
  12. package/dist/overlay-CjVgsfrm.js.map +1 -0
  13. package/dist/{post-effect-compiler-Rce26Eue.js → post-effect-compiler-pOvXae-i.js} +2 -2
  14. package/dist/{post-effect-compiler-Rce26Eue.js.map → post-effect-compiler-pOvXae-i.js.map} +1 -1
  15. package/dist/{shader-material-U6BKZ8D1.js → shader-material-B6wwFCKB.js} +2 -2
  16. package/dist/{shader-material-U6BKZ8D1.js.map → shader-material-B6wwFCKB.js.map} +1 -1
  17. package/dist/{shader-material-BIG3UDyu.js → shader-material-C4VjLTfV.js} +3 -3
  18. package/dist/{shader-material-BIG3UDyu.js.map → shader-material-C4VjLTfV.js.map} +1 -1
  19. package/dist/{shader-pragma-tw6AKaQD.js → shader-pragma-qO9_6sTd.js} +2 -2
  20. package/dist/{shader-pragma-tw6AKaQD.js.map → shader-pragma-qO9_6sTd.js.map} +1 -1
  21. package/dist/{surface-shader-Br17yysO.js → surface-shader-BaR7Kg-F.js} +4 -4
  22. package/dist/{surface-shader-Br17yysO.js.map → surface-shader-BaR7Kg-F.js.map} +1 -1
  23. package/package.json +1 -1
  24. package/dist/ignifx-error-CRh89KUJ.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import { a as CORE_ERROR_MESSAGES, c as THIRD_PARTY_ERROR_PREFIX, i as isIgnifxError, l as isValidErrorCode, n as assertNever, o as CoreErrorCode, r as formatErrorMessage, s as ErrorRange, t as IgnifxError } from "./ignifx-error-CRh89KUJ.js";
1
+ import { a as CORE_ERROR_MESSAGES, c as THIRD_PARTY_ERROR_PREFIX, i as isIgnifxError, l as isValidErrorCode, n as assertNever, o as CoreErrorCode, r as formatErrorMessage, s as ErrorRange, t as IgnifxError } from "./ignifx-error-RpK-lWwE.js";
2
2
  import { _ as smoothStep, a as clamp, c as deltaAngleDegrees, d as lerpAngleDegrees, f as moveTowards, g as sign, h as repeat, i as approximately, l as inverseLerp, m as radToDeg, n as EPSILON, o as clamp01, p as pingPong, r as RAD_TO_DEG, s as degToRad, t as DEG_TO_RAD, u as lerp, v as wrapAngleDegrees } from "./math-utils-BcDnL-gi.js";
3
3
  import { $ as basisToQuatToRef, A as setMeshReceiveShadows, B as localPosition, C as overrideSubtreeMaterials, D as setMeshId, E as setMeshBounds, F as updateMeshPositions$1, G as readWorldMatrix, H as localScale, I as updateMeshUvs$1, J as setNodeSelfVisible, K as reparentKeepingWorld, L as createNode, M as setMeshSubtreeVisible, N as updateMeshColors$1, O as setMeshMaterial, P as updateMeshNormals$1, Q as Mat4, R as disposeNode, S as disposeMeshTemplate, T as removeMeshFromScene, U as parentNode, V as localRotation, W as readNodeTag, X as worldMatrixVersion, Y as tagNode, Z as MAT4_IDENTITY, _ as createMeshFromGeometry, a as VEC3_ONE, b as createTorusMesh, c as VEC3_ZERO, d as cloneMeshUnderNode, f as collectSubtreeMeshes, g as createGroundMesh, h as createCylinderMesh, i as VEC3_LEFT, j as setMeshRenderOrder, k as setMeshPickable, l as Vec3, m as createCapsuleMesh, n as VEC3_DOWN, o as VEC3_RIGHT, p as createBoxMesh, q as setNodeName, r as VEC3_FORWARD, s as VEC3_UP, t as VEC3_BACKWARD, u as addMeshToScene, v as createPlaneMesh, w as recomputeMeshBounds, x as detachMeshBounds, y as createSphereMesh, z as linkParent } from "./vec3-T2PasQZv.js";
4
4
  import { t as Color } from "./color-DrR6GFTd.js";
5
- import { a as readSceneImageProcessing, c as setSceneEnvironmentRotation, l as setSceneFog, n as installSceneEnvironment, o as setSceneClearColor, r as loadSceneEnvironment, s as setSceneEnvironmentBlur, t as TONE_MAPPING_NAMES, u as setSceneImageProcessingOptions } from "./environment-mr5wp69e.js";
6
- import { a as defineMaterialPlugin, c as MATERIAL_ALPHA_MODES, d as createStandardMaterialFromProps, f as markMaterialDirty, g as setPbrMetallicRoughness, h as setPbrBaseColor, i as MATERIAL_PLUGIN_SAMPLER_BUDGET, l as createDefaultMaterial, m as setMaterialAlpha, n as MATERIAL_PLUGIN_DEFAULT_PRIORITY, o as isLiteMaterialPluginPoint, r as MATERIAL_PLUGIN_RESERVED_NAMES, t as LITE_MATERIAL_PLUGIN_POINTS, u as createPbrMaterialFromProps } from "./material-plugin-BRnhfw7K.js";
5
+ import { a as readSceneImageProcessing, c as setSceneEnvironmentRotation, l as setSceneFog, n as installSceneEnvironment, o as setSceneClearColor, r as loadSceneEnvironment, s as setSceneEnvironmentBlur, t as TONE_MAPPING_NAMES, u as setSceneImageProcessingOptions } from "./environment-BCjfp1jB.js";
6
+ import { a as defineMaterialPlugin, c as MATERIAL_ALPHA_MODES, d as createStandardMaterialFromProps, f as markMaterialDirty, g as setPbrMetallicRoughness, h as setPbrBaseColor, i as MATERIAL_PLUGIN_SAMPLER_BUDGET, l as createDefaultMaterial, m as setMaterialAlpha, n as MATERIAL_PLUGIN_DEFAULT_PRIORITY, o as isLiteMaterialPluginPoint, r as MATERIAL_PLUGIN_RESERVED_NAMES, t as LITE_MATERIAL_PLUGIN_POINTS, u as createPbrMaterialFromProps } from "./material-plugin-CWtV7DkH.js";
7
7
  import { a as postEffectValuesCodec, i as declaredTextureBinding, n as POST_EFFECT_FUNCTION, o as asJsonArray, r as customEffect, s as asJsonObject, t as POST_EFFECT_BUILTIN_UNIFORMS } from "./post-effect-C42XJFmo.js";
8
8
  import { a as SHADER_BLEND_MODES, c as SHADER_KINDS, d as SURFACE_HOOK_NAMES, f as SURFACE_UNIFORM_BLOCK, i as SHADER_ATTRIBUTE_NAMES, l as SHADER_TEXTURE_FALLBACKS, o as SHADER_CULL_MODES, r as LITE_SYSTEM_UNIFORM_NAMES, s as SHADER_INSTANCING_MODES, t as IGNIFX_UNIFORM_NAMES, u as SHADER_UNIFORM_TYPES } from "./shader-declaration-5q__jycG.js";
9
9
  import { acquireTexture, addTask, addToScene, buildFrameGraphTask, captureScreenshot, cloneTransformNode, createBloomPostProcessTask, createCopyToTextureTask, createCsmDirectionalShadowGenerator, createDirectionalLight, createEngine, createEsmDirectionalShadowGenerator, createFontFromBuffer, createFreeCamera, createGpuPicker, createHemisphericLight, createImageProcessingTask, createMeshFromData, createNullEngine, createPcfDirectionalShadowGenerator, createPcfSpotlightShadowGenerator, createPointLight, createRenderTarget, createRenderTask, createSceneContext, createSmaaPostProcessTask, createSpotLight, createStorageBuffer, createTexture2DFromPixels, disableOrthographicCamera, disposeEngine, disposePicker, disposeScene, disposeStorageBuffer, enableBoneControl, enableDeviceLostSceneRecovery, enableMaterialPlugins, enableMaterialStencil, enableOrthographicCamera, enablePbrLightmap, enableSkeletonShadows, enableStandardSkeleton, forceWebGpuDeviceLossForTesting, getEffectiveAspectRatio, getFrameGraph, getProjectionMatrix, getRenderTaskGpuTimings, getViewMatrix, getViewProjectionMatrix, isPbrMaterial, isShaderMaterial, loadTexture2D, onBeforeRender, pickAsync, pickWithRay, rebuildSceneRenderables, registerScene, registerSceneWithShadowSupport, releaseTexture, removeFromScene, resizeEngine, resolveCameraViewport, setGpuTimingEnabled, setShadowTaskCasterMeshes, setSubtreeVisible, setSurfaceSize, startEngine, stopEngine, updateStorageBuffer, updateTexture2DFromPixels } from "@babylonjs/lite";
@@ -445,6 +445,11 @@ var AssetHandleImpl = class {
445
445
  interested = 0;
446
446
  /** `true` while the loader is running. */
447
447
  isRunning = false;
448
+ /**
449
+ * How many reloads were asked for. A running reload compares it with the count it last served,
450
+ * so one asked for meanwhile runs once more when the current pass finishes.
451
+ */
452
+ reloadRequests = 0;
448
453
  /** Bytes received so far. */
449
454
  bytesLoaded = 0;
450
455
  /** Bytes expected, from the manifest entry or the response's `Content-Length`; `0` when unknown. */
@@ -1680,14 +1685,19 @@ var AssetsImpl = class {
1680
1685
  * own: it is re-derived from the base's new value when that base is delivered, which is the only
1681
1686
  * order that cannot show a fragment of the old file next to a fragment of the new one.
1682
1687
  *
1688
+ * A call that finds a reload of the handle already running queues one more pass instead of being
1689
+ * dropped, so a second save inside the first reload's window still lands.
1690
+ *
1683
1691
  * @param address - The address that changed on disk, with or without a fragment.
1684
1692
  */
1685
1693
  reload(address) {
1686
1694
  const path = splitFragment(address).path;
1687
1695
  for (const handle of this.#entries.values()) {
1688
1696
  if (handle.address !== address && handle.path !== path) continue;
1689
- if (handle.state !== "loaded" || handle.isRunning) continue;
1697
+ if (handle.state !== "loaded") continue;
1690
1698
  if (handle.fragment !== null && handle.loader.parseFragment !== void 0) continue;
1699
+ handle.reloadRequests += 1;
1700
+ if (handle.isRunning) continue;
1691
1701
  this.#runReload(handle);
1692
1702
  }
1693
1703
  }
@@ -1930,30 +1940,66 @@ var AssetsImpl = class {
1930
1940
  }
1931
1941
  }
1932
1942
  /**
1933
- * Runs one hot-reload attempt.
1943
+ * Runs a hot reload, and again for each reload asked for while it ran, then delivers the newest
1944
+ * value once. Each pass starts from the value the previous pass produced, so the default reload
1945
+ * releases every intermediate value exactly once.
1934
1946
  *
1935
1947
  * @param handle - The loaded handle to refresh.
1936
1948
  */
1937
1949
  async #runReload(handle) {
1938
1950
  const controller = new AbortController();
1939
- const previous = handle.value;
1951
+ let current = handle.value;
1952
+ let isReplaced = false;
1953
+ let served = -1;
1940
1954
  handle.isRunning = true;
1941
1955
  try {
1942
- const value = await this.#invokeLoader(handle, controller.signal, true, previous);
1943
- if (this.#isDisposed) return;
1944
- if (handle.loader.reload === void 0) this.#runUnload(handle, previous);
1945
- this.#enqueueDelivery({
1956
+ while (served !== handle.reloadRequests && handle.state === "loaded") {
1957
+ served = handle.reloadRequests;
1958
+ try {
1959
+ const value = await this.#invokeLoader(handle, controller.signal, true, current);
1960
+ if (this.#isDisposed) return;
1961
+ if (handle.loader.reload === void 0) this.#runUnload(handle, current);
1962
+ current = value;
1963
+ isReplaced = true;
1964
+ } catch (error) {
1965
+ this.#report(this.#reloadError(handle, error, isReplaced));
1966
+ }
1967
+ }
1968
+ if (isReplaced) this.#enqueueDelivery({
1946
1969
  kind: "replaced",
1947
1970
  handle,
1948
- value
1971
+ value: current
1949
1972
  });
1950
- } catch (error) {
1951
- this.#report(error);
1952
1973
  } finally {
1953
1974
  handle.isRunning = false;
1954
1975
  }
1955
1976
  }
1956
1977
  /**
1978
+ * Builds the failure a hot reload reports through `app.onError`.
1979
+ *
1980
+ * @param handle - The handle whose reload failed.
1981
+ * @param error - What the loader threw.
1982
+ * @param isReplaced - Whether an earlier pass of the same reload produced a value, which the
1983
+ * handle keeps instead of the one it held before.
1984
+ * @returns The `IGX-0505` failure, with the loader's error as `cause`.
1985
+ */
1986
+ #reloadError(handle, error, isReplaced) {
1987
+ const kept = isReplaced ? "the last version that loaded" : "its previous value";
1988
+ return new AssetLoadError(CoreErrorCode.assetLoadFailed, `Reloading ${handle.address} from ${handle.url} failed; the asset keeps ${kept}.`, {
1989
+ address: handle.address,
1990
+ url: handle.url,
1991
+ cause: error,
1992
+ context: {
1993
+ asset: handle.address,
1994
+ url: handle.url,
1995
+ attempts: 1,
1996
+ reload: true,
1997
+ kept: isReplaced ? "earlier reload" : "previous"
1998
+ },
1999
+ hint: "Fix the file and save it again; the next save reloads it."
2000
+ });
2001
+ }
2002
+ /**
1957
2003
  * Calls the loader, resolving a `#fragment` address through the base address first.
1958
2004
  *
1959
2005
  * @param handle - The handle being loaded.
@@ -3104,12 +3150,13 @@ function notAttached(component) {
3104
3150
  * costs a call per frame and not defining it costs nothing.
3105
3151
  *
3106
3152
  * **The statics work the same way.** `typeId`, `schema`, `requires`, `allowMultiple`,
3107
- * `executionOrder`, and `updateWhenPaused` are not members of `Component` or `Script` either: a
3108
- * static declared on the base class is an override too, so `static typeId = "mygame/Mover"` would
3109
- * have needed an `override` modifier. Their shape lives on {@link ComponentStatics} and
3110
- * {@link ScriptStatics}, which the class-token types intersect, so a plain `static` on a subclass
3111
- * satisfies them structurally; `ComponentRegistry` reads each one once per class and applies the
3112
- * defaults (`executionOrder` `0`, `updateWhenPaused` `false`).
3153
+ * `executionOrder`, `updateWhenPaused`, and `runInEditMode` are not members of `Component` or
3154
+ * `Script` either: a static declared on the base class is an override too, so
3155
+ * `static typeId = "mygame/Mover"` would have needed an `override` modifier. Their shape lives on
3156
+ * {@link ComponentStatics} and {@link ScriptStatics}, which the class-token types intersect, so a
3157
+ * plain `static` on a subclass satisfies them structurally; `ComponentRegistry` reads each one once
3158
+ * per class and applies the defaults (`executionOrder` `0`, `updateWhenPaused` `false`,
3159
+ * `runInEditMode` `false`).
3113
3160
  *
3114
3161
  * @example
3115
3162
  * ```ts
@@ -3161,6 +3208,8 @@ var Script = class extends Component {
3161
3208
  *
3162
3209
  * @param routine - The generator to drive. Call the generator function: `this.spawnLoop()`.
3163
3210
  * @returns A handle for stopping it or waiting on it.
3211
+ * @throws IgnifxError with code `IGX-0111` in an edit-mode app when the class does not set
3212
+ * `static runInEditMode = true` (ADR-0028).
3164
3213
  *
3165
3214
  * @example
3166
3215
  * ```ts
@@ -3217,6 +3266,7 @@ const TYPE_ID_PATTERN = /^[a-z0-9][a-z0-9\-.@/]*\/[A-Za-z][A-Za-z0-9]*$/u;
3217
3266
  */
3218
3267
  var ComponentRegistry = class {
3219
3268
  #byTypeId = /* @__PURE__ */ new Map();
3269
+ #registrars = /* @__PURE__ */ new Map();
3220
3270
  #info = /* @__PURE__ */ new Map();
3221
3271
  #nextClassIndex = 0;
3222
3272
  /**
@@ -3232,11 +3282,13 @@ var ComponentRegistry = class {
3232
3282
  *
3233
3283
  * @param type - The component class.
3234
3284
  * @param typeId - An explicit id, when the class does not declare one.
3285
+ * @param registrar - Who registers it, for example the extension's `name`; the first registrar of
3286
+ * an id is kept, and {@link ComponentRegistry.registrarOf} reports it.
3235
3287
  * @returns What the registry worked out about the class.
3236
3288
  * @throws IgnifxError with code `IGX-0203` when the id is already registered by another class, or
3237
3289
  * when the id is not `<namespace>/<Name>`.
3238
3290
  */
3239
- register(type, typeId) {
3291
+ register(type, typeId, registrar) {
3240
3292
  const id = typeId ?? readStatics$1(type).typeId ?? null;
3241
3293
  if (id !== null) {
3242
3294
  if (!TYPE_ID_PATTERN.test(id)) throw new IgnifxError(CoreErrorCode.duplicateComponentTypeId, `The component type id ${id} is malformed.`, {
@@ -3252,6 +3304,7 @@ var ComponentRegistry = class {
3252
3304
  owner: existing.prototype.constructor.name
3253
3305
  } });
3254
3306
  this.#byTypeId.set(id, type);
3307
+ if (registrar !== void 0 && !this.#registrars.has(id)) this.#registrars.set(id, registrar);
3255
3308
  }
3256
3309
  return this.describe(type);
3257
3310
  }
@@ -3259,14 +3312,32 @@ var ComponentRegistry = class {
3259
3312
  * Registers several component classes.
3260
3313
  *
3261
3314
  * @param types - The component classes.
3315
+ * @param registrar - Who registers them, as for {@link ComponentRegistry.register}.
3262
3316
  */
3263
- registerAll(types) {
3317
+ registerAll(types, registrar) {
3264
3318
  for (let index = 0; index < types.length; index += 1) {
3265
3319
  const type = types[index];
3266
- if (type !== void 0) this.register(type);
3320
+ if (type !== void 0) this.register(type, void 0, registrar);
3267
3321
  }
3268
3322
  }
3269
3323
  /**
3324
+ * Who registered a type id: the extension `name` an `ExtensionContext` registers under, or
3325
+ * whatever a direct caller of {@link ComponentRegistry.register} passed. A hot-reload
3326
+ * {@link ComponentRegistry.replace} keeps it.
3327
+ *
3328
+ * @param typeId - The namespaced id.
3329
+ * @returns The registrar, or `null` when the id was registered without one (as
3330
+ * `app.registerComponents` does) or is not registered.
3331
+ *
3332
+ * @example
3333
+ * ```ts
3334
+ * app.world.registry.registrarOf("ignifx/Camera"); // "@ignifx/core"
3335
+ * ```
3336
+ */
3337
+ registrarOf(typeId) {
3338
+ return this.#registrars.get(typeId) ?? null;
3339
+ }
3340
+ /**
3270
3341
  * Swaps the class registered under a `typeId` for a replacement, for script hot reload
3271
3342
  * (`docs/architecture/15-devtools-and-diagnostics.md` §5). The previous class's cached info is
3272
3343
  * dropped and the replacement inherits its `classIndex`, so per-class bookkeeping indexed by that
@@ -3470,6 +3541,7 @@ function buildScriptInfo(type) {
3470
3541
  return {
3471
3542
  executionOrder: statics.executionOrder ?? 0,
3472
3543
  updateWhenPaused: statics.updateWhenPaused ?? false,
3544
+ runInEditMode: statics.runInEditMode ?? false,
3473
3545
  callbacks
3474
3546
  };
3475
3547
  }
@@ -3600,6 +3672,7 @@ var CoroutineRecord = class {
3600
3672
  */
3601
3673
  var CoroutineHostImpl = class {
3602
3674
  #frameState;
3675
+ #isEditMode;
3603
3676
  #report;
3604
3677
  #records = [];
3605
3678
  #byOwner = /* @__PURE__ */ new Map();
@@ -3612,6 +3685,7 @@ var CoroutineHostImpl = class {
3612
3685
  */
3613
3686
  constructor(options) {
3614
3687
  this.#frameState = options.frameState;
3688
+ this.#isEditMode = options.editMode;
3615
3689
  this.#report = (error, owner) => {
3616
3690
  options.report(error, owner);
3617
3691
  };
@@ -3631,8 +3705,17 @@ var CoroutineHostImpl = class {
3631
3705
  * @param owner - The script whose enabled state gates the coroutine.
3632
3706
  * @param routine - The generator to drive.
3633
3707
  * @returns A handle for stopping it or waiting on it.
3708
+ * @throws IgnifxError with code `IGX-0111` in edit mode when the owner's class does not set
3709
+ * `static runInEditMode = true`.
3634
3710
  */
3635
3711
  start(owner, routine) {
3712
+ if (this.#isEditMode && componentInternals(owner).info?.script?.runInEditMode !== true) {
3713
+ const script = owner.constructor.name;
3714
+ throw new IgnifxError(CoreErrorCode.coroutineInEditMode, `${script} cannot start a coroutine in edit mode because its class does not run in edit mode.`, {
3715
+ context: { script },
3716
+ hint: "Add `static runInEditMode = true` if the script is meant to run in an editor. Otherwise start the coroutine from a callback such as `start`, which only a game calls."
3717
+ });
3718
+ }
3636
3719
  const record = new CoroutineRecord(owner, routine);
3637
3720
  this.#records.push(record);
3638
3721
  let owned = this.#byOwner.get(owner);
@@ -4614,15 +4697,14 @@ function createServiceKey(name) {
4614
4697
  * `version` (`docs/architecture/04-extensions.md` §1).
4615
4698
  *
4616
4699
  * @remarks
4617
- * The literal is `"0.0.0"` in the repository and is stamped by the release pipeline: Changesets
4618
- * writes the real number into `package.json`, and the build replaces this constant with it
4619
- * (coding standards §12, `release.yml`). Reading the version from `package.json` at run time is not
4620
- * an option — that would be an import-time side effect and a bundler hazard
4700
+ * The build stamps it from `package.json`, where Changesets writes each release's number; code run
4701
+ * from source, such as this repository's tests, sees `"0.0.0"`. Reading `package.json` at run time
4702
+ * is not an option: that would be an import-time side effect and a bundler hazard
4621
4703
  * (`CONSTITUTION.md` §3.5).
4622
4704
  *
4623
4705
  * @public
4624
4706
  */
4625
- const VERSION = "0.0.0";
4707
+ const VERSION = "0.10.0";
4626
4708
  //#endregion
4627
4709
  //#region src/assets/delivery-system.ts
4628
4710
  /**
@@ -5188,37 +5270,89 @@ function raycastScene(scene, ray, options) {
5188
5270
  return pickWithRay(scene, ray, options);
5189
5271
  }
5190
5272
  /**
5191
- * Casts a ray against a scene's renderable meshes, considering only the meshes whose ignifx tag a
5192
- * predicate accepts.
5273
+ * The ignifx tag that owns a node: its own, or the nearest tagged ancestor's.
5274
+ *
5275
+ * @remarks
5276
+ * A `MeshRenderer` tags the mesh it clones, but a `Model` tags only the cloned glTF root, and the
5277
+ * meshes Lite draws are that root's descendants (`render/gpu/model-instance.ts`). Walking up to the
5278
+ * nearest tag resolves both, and any other renderable that parents several Lite nodes under one
5279
+ * tagged node, to the entity and component that created them (editor spike S0.2 §6.1). The walk
5280
+ * stops at the first tag, so an entity parented under a model's bone still owns its own meshes.
5281
+ *
5282
+ * @param node - The picked node, usually a mesh.
5283
+ * @returns The nearest tag, or `null` when no node on the way to the root carries one.
5284
+ *
5285
+ * @internal
5286
+ */
5287
+ function readOwnerTag(node) {
5288
+ for (let current = node; current !== null; current = parentNode(current)) {
5289
+ const tag = readNodeTag(current);
5290
+ if (tag !== null) return tag;
5291
+ }
5292
+ return null;
5293
+ }
5294
+ /**
5295
+ * Casts a ray against a scene's renderable meshes, considering only the meshes a predicate accepts.
5193
5296
  *
5194
5297
  * @remarks
5195
- * The predicate is stated over the *tag* rather than over Lite's `Mesh` so the component layer can
5196
- * filter by entity without naming a Lite type (`CONSTITUTION.md` §3.4). Lite's own
5298
+ * The predicate is stated over the owning *tag* rather than over Lite's `Mesh` so the component
5299
+ * layer can filter by entity without naming a Lite type (`CONSTITUTION.md` §3.4). Lite's own
5197
5300
  * `pickable === false` exclusion still runs first.
5198
5301
  *
5199
5302
  * @param scene - The render scene.
5200
5303
  * @param ray - The ray to cast.
5201
- * @param accept - Decides whether a mesh may be picked, from the ignifx tag its node carries.
5304
+ * @param accept - Decides whether a mesh may be picked, from the ignifx tag that owns it.
5202
5305
  * @returns Lite's picking info.
5203
5306
  *
5204
5307
  * @internal
5205
5308
  */
5206
5309
  function raycastSceneWhere(scene, ray, accept) {
5207
- return pickWithRay(scene, ray, { predicate: (mesh) => accept(readNodeTag(mesh)) });
5310
+ return pickWithRay(scene, ray, { predicate: (mesh) => accept(readOwnerTag(mesh), mesh) });
5208
5311
  }
5209
5312
  /**
5210
5313
  * Resolves a hit back to the ignifx entity and component that own the mesh.
5211
5314
  *
5212
5315
  * @param info - A result from {@link raycastScene}, {@link raycastMeshes}, or the GPU picker.
5213
- * @returns The owning entity's tag, or `null` when the ray missed or the mesh is not one ignifx
5214
- * created (a glTF child node inside a `Model`, for instance, whose tag lives on the model's root).
5316
+ * @returns The owning tag — the picked mesh's own or its nearest tagged ancestor's, so a glTF mesh
5317
+ * inside a `Model` resolves to the model — or `null` when the ray missed or no node on the way to
5318
+ * the root is one ignifx created.
5215
5319
  *
5216
5320
  * @internal
5217
5321
  */
5218
5322
  function readPickedTag(info) {
5219
5323
  const mesh = info.pickedMesh;
5220
5324
  if (mesh === null) return null;
5221
- return readNodeTag(mesh);
5325
+ return readOwnerTag(mesh);
5326
+ }
5327
+ /**
5328
+ * The name of the mesh a hit landed on.
5329
+ *
5330
+ * @param info - A hit.
5331
+ * @returns The Lite mesh's name — for a glTF model, the name the file gives the node or primitive —
5332
+ * or `""` for a miss or an unnamed mesh.
5333
+ *
5334
+ * @internal
5335
+ */
5336
+ function readPickedMeshName(info) {
5337
+ const name = info.pickedMesh?.name;
5338
+ return typeof name === "string" ? name : "";
5339
+ }
5340
+ /**
5341
+ * Reads the identity of a hit, for a later pick to ignore.
5342
+ *
5343
+ * @param info - A hit.
5344
+ * @returns The mesh and thin instance, or `null` for a miss or a hit on something other than a
5345
+ * regular Lite mesh (a Gaussian-splatting mesh, which Lite's `ignore` cannot name).
5346
+ *
5347
+ * @internal
5348
+ */
5349
+ function readPickedIdentity(info) {
5350
+ const mesh = info.pickedMesh;
5351
+ if (mesh === null || !("material" in mesh)) return null;
5352
+ return {
5353
+ mesh,
5354
+ thinInstanceIndex: info.thinInstanceIndex
5355
+ };
5222
5356
  }
5223
5357
  //#endregion
5224
5358
  //#region src/schema/types.ts
@@ -5910,7 +6044,9 @@ const HEADLESS_TARGET_SIZE = 1;
5910
6044
  * @example
5911
6045
  * ```ts
5912
6046
  * const ray = createRay();
5913
- * camera.screenToRay(event.offsetX, event.offsetY, ray);
6047
+ * // A DOM event is in CSS pixels; the camera speaks the canvas's backing-store pixels.
6048
+ * const scale = canvas.width / canvas.clientWidth;
6049
+ * camera.screenToRay(event.offsetX * scale, event.offsetY * scale, ray);
5914
6050
  * ```
5915
6051
  *
5916
6052
  * @public
@@ -6008,7 +6144,9 @@ var Camera = class Camera extends Component {
6008
6144
  * @remarks
6009
6145
  * Coordinates are backing-store pixels — the canvas's `width`/`height`, the space
6010
6146
  * {@link Camera.worldToScreen} answers in and `@ignifx/input` reports `<Pointer>/position` in — not
6011
- * CSS pixels; multiply a DOM event's `offsetX`/`offsetY` by `devicePixelRatio` first.
6147
+ * CSS pixels; multiply a DOM event's `offsetX`/`offsetY` by `canvas.width / canvas.clientWidth`
6148
+ * first (`devicePixelRatio` is that ratio only while `renderer.pixelRatio` and
6149
+ * `renderer.resolutionScale` leave it alone).
6012
6150
  *
6013
6151
  * @param x - The backing-store pixel x, from the canvas's left edge.
6014
6152
  * @param y - The backing-store pixel y, from the canvas's top edge.
@@ -6928,7 +7066,7 @@ let surfaceLayer = null;
6928
7066
  * @internal
6929
7067
  */
6930
7068
  async function loadShaderSupport() {
6931
- const loaded = shaderLayer ?? await import("./shader-material-BIG3UDyu.js").then((n) => n.n);
7069
+ const loaded = shaderLayer ?? await import("./shader-material-C4VjLTfV.js").then((n) => n.n);
6932
7070
  shaderLayer = loaded;
6933
7071
  await loaded.loadShaderMaterialAdapter();
6934
7072
  return loaded;
@@ -6951,7 +7089,7 @@ function shaderSupport() {
6951
7089
  * @internal
6952
7090
  */
6953
7091
  async function loadSurfaceShaderSupport() {
6954
- const loaded = surfaceLayer ?? await import("./surface-shader-Br17yysO.js");
7092
+ const loaded = surfaceLayer ?? await import("./surface-shader-BaR7Kg-F.js");
6955
7093
  surfaceLayer = loaded;
6956
7094
  return loaded;
6957
7095
  }
@@ -7986,6 +8124,42 @@ function buildMeshTemplate(isHeadless, scene, engine, build) {
7986
8124
  engine
7987
8125
  };
7988
8126
  }
8127
+ /**
8128
+ * Copies the ignifx ground options onto Lite's, which types `uvScale` as a mutable tuple.
8129
+ *
8130
+ * @param options - The declared options.
8131
+ * @returns Lite's options.
8132
+ */
8133
+ function toGroundOptions(options) {
8134
+ const result = {};
8135
+ if (options.width !== void 0) result.width = options.width;
8136
+ if (options.height !== void 0) result.height = options.height;
8137
+ if (options.subdivisions !== void 0) result.subdivisions = options.subdivisions;
8138
+ const uvScale = options.uvScale;
8139
+ if (uvScale !== void 0) result.uvScale = [uvScale[0], uvScale[1]];
8140
+ return result;
8141
+ }
8142
+ /**
8143
+ * Builds a primitive's Lite mesh.
8144
+ *
8145
+ * @param engine - The engine that owns the buffers.
8146
+ * @param definition - The primitive and its options.
8147
+ * @returns The template.
8148
+ *
8149
+ * @internal
8150
+ */
8151
+ function buildPrimitiveTemplate(engine, definition) {
8152
+ switch (definition.primitive) {
8153
+ case "box": return buildBoxTemplate(engine, definition.options);
8154
+ case "sphere": return buildSphereTemplate(engine, definition.options);
8155
+ case "plane": return buildPlaneTemplate(engine, definition.options);
8156
+ case "ground": return buildGroundTemplate(engine, toGroundOptions(definition.options));
8157
+ case "cylinder": return buildCylinderTemplate(engine, definition.options);
8158
+ case "capsule": return buildCapsuleTemplate(engine, definition.options);
8159
+ case "torus": return buildTorusTemplate(engine, definition.options);
8160
+ default: return assertNever(definition, "mesh primitive");
8161
+ }
8162
+ }
7989
8163
  //#endregion
7990
8164
  //#region src/render/mesh-asset.ts
7991
8165
  /**
@@ -8009,12 +8183,28 @@ const FLOATS_PER_UV = 2;
8009
8183
  /** Floats per vertex in the colour attribute — Lite's colour attribute is `vec4`. */
8010
8184
  const FLOATS_PER_COLOR$1 = 4;
8011
8185
  /**
8186
+ * The primitive shapes a `MeshAsset` factory and a `.mesh.json` file can build.
8187
+ *
8188
+ * @public
8189
+ */
8190
+ const MESH_PRIMITIVES = [
8191
+ "box",
8192
+ "sphere",
8193
+ "plane",
8194
+ "ground",
8195
+ "cylinder",
8196
+ "capsule",
8197
+ "torus"
8198
+ ];
8199
+ /**
8012
8200
  * A geometry template a `MeshRenderer` draws (`docs/architecture/07-rendering.md` §2.3).
8013
8201
  *
8014
8202
  * @remarks
8015
8203
  * Build one with a primitive factory or {@link MeshAsset.fromData}; each returns the handle the
8016
- * `MeshRenderer.mesh` field takes. A mesh that came from a file arrives as part of a `ModelAsset`
8017
- * instead — a glTF is a tree of meshes, materials, and animations, not one buffer.
8204
+ * `MeshRenderer.mesh` field takes. A `.mesh.json` file loads the same primitives by address
8205
+ * (`app.assets.load("meshes/crate.mesh.json")`), so a scene file can name one. A glTF mesh
8206
+ * arrives as part of a `ModelAsset` instead — a glTF is a tree of meshes, materials, and
8207
+ * animations, not one buffer.
8018
8208
  *
8019
8209
  * @example
8020
8210
  * ```ts
@@ -8270,7 +8460,10 @@ var MeshAsset = class {
8270
8460
  * ```
8271
8461
  */
8272
8462
  static box(app, options) {
8273
- return publish(app, "box", (engine) => buildBoxTemplate(engine, options));
8463
+ return publishPrimitive(app, {
8464
+ primitive: "box",
8465
+ options: options ?? {}
8466
+ });
8274
8467
  }
8275
8468
  /**
8276
8469
  * Creates a sphere template and publishes it.
@@ -8280,7 +8473,10 @@ var MeshAsset = class {
8280
8473
  * @returns The handle, with one holder.
8281
8474
  */
8282
8475
  static sphere(app, options) {
8283
- return publish(app, "sphere", (engine) => buildSphereTemplate(engine, options));
8476
+ return publishPrimitive(app, {
8477
+ primitive: "sphere",
8478
+ options: options ?? {}
8479
+ });
8284
8480
  }
8285
8481
  /**
8286
8482
  * Creates a quad template in the XY plane and publishes it.
@@ -8290,7 +8486,10 @@ var MeshAsset = class {
8290
8486
  * @returns The handle, with one holder.
8291
8487
  */
8292
8488
  static plane(app, options) {
8293
- return publish(app, "plane", (engine) => buildPlaneTemplate(engine, options));
8489
+ return publishPrimitive(app, {
8490
+ primitive: "plane",
8491
+ options: options ?? {}
8492
+ });
8294
8493
  }
8295
8494
  /**
8296
8495
  * Creates a subdivided grid in the XZ plane and publishes it.
@@ -8300,8 +8499,10 @@ var MeshAsset = class {
8300
8499
  * @returns The handle, with one holder.
8301
8500
  */
8302
8501
  static ground(app, options) {
8303
- const lite = toGroundOptions(options);
8304
- return publish(app, "ground", (engine) => buildGroundTemplate(engine, lite));
8502
+ return publishPrimitive(app, {
8503
+ primitive: "ground",
8504
+ options: options ?? {}
8505
+ });
8305
8506
  }
8306
8507
  /**
8307
8508
  * Creates a cylinder template standing along Y and publishes it.
@@ -8311,7 +8512,10 @@ var MeshAsset = class {
8311
8512
  * @returns The handle, with one holder.
8312
8513
  */
8313
8514
  static cylinder(app, options) {
8314
- return publish(app, "cylinder", (engine) => buildCylinderTemplate(engine, options));
8515
+ return publishPrimitive(app, {
8516
+ primitive: "cylinder",
8517
+ options: options ?? {}
8518
+ });
8315
8519
  }
8316
8520
  /**
8317
8521
  * Creates a capsule template standing along Y and publishes it.
@@ -8321,7 +8525,10 @@ var MeshAsset = class {
8321
8525
  * @returns The handle, with one holder.
8322
8526
  */
8323
8527
  static capsule(app, options) {
8324
- return publish(app, "capsule", (engine) => buildCapsuleTemplate(engine, options));
8528
+ return publishPrimitive(app, {
8529
+ primitive: "capsule",
8530
+ options: options ?? {}
8531
+ });
8325
8532
  }
8326
8533
  /**
8327
8534
  * Creates a torus template in the XZ plane and publishes it.
@@ -8331,7 +8538,10 @@ var MeshAsset = class {
8331
8538
  * @returns The handle, with one holder.
8332
8539
  */
8333
8540
  static torus(app, options) {
8334
- return publish(app, "torus", (engine) => buildTorusTemplate(engine, options));
8541
+ return publishPrimitive(app, {
8542
+ primitive: "torus",
8543
+ options: options ?? {}
8544
+ });
8335
8545
  }
8336
8546
  /**
8337
8547
  * Creates a template from raw vertex data and publishes it.
@@ -8381,20 +8591,30 @@ function copyRange(source, target, components, vertexOffset, count) {
8381
8591
  target.set(source.subarray(0, floats), base);
8382
8592
  }
8383
8593
  /**
8384
- * Copies the ignifx ground options onto Lite's, which types `uvScale` as a mutable tuple.
8594
+ * Builds a primitive mesh asset without publishing it. The factories and the `.mesh.json` loader
8595
+ * both go through here, so a primitive is the same whether code or a file asked for it.
8385
8596
  *
8386
- * @param options - The declared options.
8387
- * @returns Lite's options, or `undefined` when the caller declared none.
8597
+ * @param app - The app whose engine uploads the geometry; a headless app uploads nothing.
8598
+ * @param name - A human-readable name.
8599
+ * @param definition - The primitive and its options.
8600
+ * @returns The asset, owned by the caller.
8601
+ *
8602
+ * @internal
8388
8603
  */
8389
- function toGroundOptions(options) {
8390
- if (options === void 0) return;
8391
- const result = {};
8392
- if (options.width !== void 0) result.width = options.width;
8393
- if (options.height !== void 0) result.height = options.height;
8394
- if (options.subdivisions !== void 0) result.subdivisions = options.subdivisions;
8395
- const uvScale = options.uvScale;
8396
- if (uvScale !== void 0) result.uvScale = [uvScale[0], uvScale[1]];
8397
- return result;
8604
+ function createPrimitiveMeshAsset(app, name, definition) {
8605
+ const handles = buildMeshTemplate(app.isHeadless, app.lite.scene, app.lite.engine, (engine) => buildPrimitiveTemplate(engine, definition));
8606
+ return new MeshAsset(name, handles.mesh, handles.scene, null, handles.engine);
8607
+ }
8608
+ /**
8609
+ * Builds a primitive and registers it as an in-memory asset named after the primitive.
8610
+ *
8611
+ * @param app - The app that owns the engine and the asset service.
8612
+ * @param definition - The primitive and its options.
8613
+ * @returns The handle, with one holder.
8614
+ */
8615
+ function publishPrimitive(app, definition) {
8616
+ const asset = createPrimitiveMeshAsset(app, definition.primitive, definition);
8617
+ return app.assets.register(asset, { type: MESH_ASSET_TYPE });
8398
8618
  }
8399
8619
  /**
8400
8620
  * Builds a template — skipping the upload under a headless app — and registers it as an in-memory
@@ -8487,7 +8707,7 @@ function forceDeviceLossForTesting(engine) {
8487
8707
  * @example
8488
8708
  * ```ts
8489
8709
  * const picker = createScenePicker(scene);
8490
- * const hit = await pickScenePixel(picker, event.offsetX, event.offsetY);
8710
+ * const hit = await pickScenePixel(picker, scene, 120, 80, null, []);
8491
8711
  * ```
8492
8712
  *
8493
8713
  * @internal
@@ -8496,44 +8716,116 @@ function createScenePicker(scene) {
8496
8716
  return createGpuPicker(scene);
8497
8717
  }
8498
8718
  /**
8499
- * Picks the object under one CSS pixel of the canvas.
8719
+ * The ratio Lite's picker multiplies a CSS pixel by, on one axis.
8720
+ *
8721
+ * @param backing - The canvas's backing-store size on that axis.
8722
+ * @param client - Its CSS layout size, or `0` when it has none.
8723
+ * @returns `backing / (client || backing)`, exactly as Lite computes it, or `1` for an empty canvas.
8724
+ */
8725
+ function liteScale(backing, client) {
8726
+ const css = client || backing;
8727
+ return css > 0 && backing > 0 ? backing / css : 1;
8728
+ }
8729
+ /**
8730
+ * Converts a backing-store coordinate to the CSS coordinate Lite's picker multiplies back.
8500
8731
  *
8501
8732
  * @remarks
8502
- * Coordinates are in CSS pixels relative to the canvas; Lite scales them by the backing-store ratio
8503
- * itself. The returned info carries `pickedPoint` and `pickedNormal` only when detailed picking is
8504
- * on ({@link enableScenePickerDetail}); without it, `pickedMesh` and `distance` are what a pick
8505
- * yields.
8733
+ * Lite renders its 1×1 target at the exact sub-pixel point it computes (`computePickVP`,
8734
+ * `lib/picking/gpu-picker.js` ~96 and ~224 in 1.34.0), so a whole-number coordinate samples a
8735
+ * pixel **corner**, not a centre; add 0.5 for the centre. The floored value only feeds the viewport
8736
+ * bounds check, the clamp and the discard rule's `fragmentCoord`. `x / scale * scale` can land one
8737
+ * unit in the last place below `x`, which would put a point on the viewport's edge outside it, or
8738
+ * floor to the pixel before; the result is nudged up until Lite's product is not below `x`.
8506
8739
  *
8507
- * @param picker - The picker.
8508
- * @param x - The CSS pixel x, from the canvas's left edge.
8509
- * @param y - The CSS pixel y, from the canvas's top edge.
8510
- * @param options - A mesh filter, identities to ignore, or a WGSL discard rule.
8511
- * @returns The hit. Calls on one picker run one at a time.
8740
+ * @param value - The backing-store coordinate.
8741
+ * @param scale - Lite's ratio on that axis.
8742
+ * @returns The CSS coordinate.
8512
8743
  *
8513
8744
  * @internal
8514
8745
  */
8515
- function pickScenePixel(picker, x, y, options) {
8516
- return pickAsync(picker, x, y, options);
8746
+ function toLitePickCoordinate(value, scale) {
8747
+ if (scale === 1) return value;
8748
+ let css = value / scale;
8749
+ for (let attempt = 0; attempt < 4 && css * scale < value; attempt += 1) css += Math.max(Math.abs(css) * Number.EPSILON, Number.MIN_VALUE);
8750
+ return css;
8517
8751
  }
8518
8752
  /**
8519
- * Picks the object under one CSS pixel, considering only the meshes whose ignifx tag a predicate
8520
- * accepts.
8753
+ * Picks the object under one backing-store pixel of the scene's canvas.
8521
8754
  *
8522
8755
  * @remarks
8523
- * The predicate is stated over the *tag* rather than over Lite's `Mesh` so that the component layer
8524
- * can filter by entity without naming a Lite type (`CONSTITUTION.md` §3.4). A rejected mesh is
8525
- * excluded from the candidate list entirely, so it neither occludes nor returns.
8756
+ * Coordinates are backing-store pixels — `canvas.width`/`height`, the space `Camera.worldToScreen`
8757
+ * and `<Pointer>/position` use. They are converted to the CSS pixels Lite's picker takes (see the
8758
+ * module notes). Meshes `accept` rejects, and the identities in `ignore`, neither occlude nor return.
8526
8759
  *
8527
8760
  * @param picker - The picker.
8528
- * @param x - The CSS pixel x, from the canvas's left edge.
8529
- * @param y - The CSS pixel y, from the canvas's top edge.
8530
- * @param accept - Decides whether a mesh may be picked, from the ignifx tag its node carries.
8531
- * @returns The hit.
8761
+ * @param scene - The scene the picker was created for; its surface's canvas sets the ratio.
8762
+ * @param x - The backing-store pixel x, from the canvas's left edge.
8763
+ * @param y - The backing-store pixel y, from the canvas's top edge.
8764
+ * @param accept - Decides whether a mesh may be picked, from the ignifx tag that owns it, or `null`
8765
+ * to consider every mesh.
8766
+ * @param ignore - Earlier hits to look through; a thin-instance hit skips only that instance.
8767
+ * @returns The hit. Calls on one picker run one at a time.
8768
+ *
8769
+ * @example
8770
+ * ```ts
8771
+ * const picker = createScenePicker(scene);
8772
+ * const hit = await pickScenePixel(picker, scene, 120, 80, null, []);
8773
+ * ```
8532
8774
  *
8533
8775
  * @internal
8534
8776
  */
8535
- function pickScenePixelWhere(picker, x, y, accept) {
8536
- return pickAsync(picker, x, y, { filter: (mesh) => accept(readNodeTag(mesh)) });
8777
+ function pickScenePixel(picker, scene, x, y, accept, ignore) {
8778
+ const canvas = scene.surface.canvas;
8779
+ const clientWidth = "clientWidth" in canvas ? canvas.clientWidth : 0;
8780
+ const clientHeight = "clientHeight" in canvas ? canvas.clientHeight : 0;
8781
+ const cssX = toLitePickCoordinate(x, liteScale(canvas.width, clientWidth));
8782
+ const cssY = toLitePickCoordinate(y, liteScale(canvas.height, clientHeight));
8783
+ const options = {};
8784
+ if (accept !== null) options.filter = (mesh) => accept(readOwnerTag(mesh), mesh);
8785
+ if (ignore.length > 0) options.ignore = toLiteIgnore(ignore);
8786
+ return pickAsync(picker, cssX, cssY, options);
8787
+ }
8788
+ /**
8789
+ * Folds earlier hits into Lite's ignore list, one entry per mesh.
8790
+ *
8791
+ * @remarks
8792
+ * Lite reads only the **first** entry it finds for a mesh (`lib/picking/picking-ignore.js`,
8793
+ * `forMesh`), so several hits on one mesh are merged here: a whole-mesh hit wins, thin instances
8794
+ * that form one contiguous run become a range, and otherwise the lowest index is kept — a Lite
8795
+ * 1.34 limit, which a caller cycling through instances of one renderer can meet.
8796
+ *
8797
+ * @param ignore - The hits to look through.
8798
+ * @returns Lite's entries.
8799
+ */
8800
+ function toLiteIgnore(ignore) {
8801
+ const byMesh = /* @__PURE__ */ new Map();
8802
+ for (const identity of ignore) {
8803
+ const indices = byMesh.get(identity.mesh);
8804
+ if (identity.thinInstanceIndex < 0 || indices === null) byMesh.set(identity.mesh, null);
8805
+ else if (indices === void 0) byMesh.set(identity.mesh, [identity.thinInstanceIndex]);
8806
+ else indices.push(identity.thinInstanceIndex);
8807
+ }
8808
+ const entries = [];
8809
+ for (const [mesh, indices] of byMesh) {
8810
+ if (indices === null) {
8811
+ entries.push({ mesh });
8812
+ continue;
8813
+ }
8814
+ const sorted = [...new Set(indices)].toSorted((a, b) => a - b);
8815
+ const first = sorted[0] ?? 0;
8816
+ const last = sorted.at(-1) ?? first;
8817
+ entries.push(sorted.length === 1 || last - first + 1 !== sorted.length ? {
8818
+ mesh,
8819
+ thinInstanceIndex: first
8820
+ } : {
8821
+ mesh,
8822
+ thinInstanceRange: {
8823
+ start: first,
8824
+ count: sorted.length
8825
+ }
8826
+ });
8827
+ }
8828
+ return entries;
8537
8829
  }
8538
8830
  /**
8539
8831
  * Releases a picker's GPU resources.
@@ -9381,7 +9673,8 @@ function createMaterialCacheResets() {
9381
9673
  return {
9382
9674
  found: /* @__PURE__ */ new Set(),
9383
9675
  seen: /* @__PURE__ */ new WeakSet(),
9384
- unconfirmed: false
9676
+ unconfirmed: false,
9677
+ retries: 0
9385
9678
  };
9386
9679
  }
9387
9680
  /**
@@ -9428,6 +9721,9 @@ function trackMaterialCacheResets(scene, resets) {
9428
9721
  * straight away, so the family's cache reset is known before anything needs it; see
9429
9722
  * {@link MaterialCacheResets}.
9430
9723
  *
9724
+ * The engine frees nothing the rebuild retires until the rebuild has finished; see
9725
+ * `holdGpuRetirements`.
9726
+ *
9431
9727
  * @param scene - The scene to rebuild.
9432
9728
  * @param resets - The scene's record of cache resets.
9433
9729
  * @returns A promise that resolves when the rebuild has finished.
@@ -9435,14 +9731,111 @@ function trackMaterialCacheResets(scene, resets) {
9435
9731
  * @internal
9436
9732
  */
9437
9733
  async function rebuildRenderables(scene, resets) {
9438
- if (resets === void 0) {
9734
+ const release = holdGpuRetirements(scene.surface.engine);
9735
+ try {
9736
+ if (resets === void 0) {
9737
+ await rebuildAcrossMaterialSwaps(scene);
9738
+ return;
9739
+ }
9740
+ trackMaterialCacheResets(scene, resets);
9741
+ takeUnconfirmed(resets);
9742
+ await rebuildAcrossMaterialSwaps(scene, resets);
9743
+ if (takeUnconfirmed(resets)) await rebuildAcrossMaterialSwaps(scene, resets);
9744
+ } finally {
9745
+ release();
9746
+ }
9747
+ }
9748
+ /** How many times {@link rebuildAcrossMaterialSwaps} starts over after a swap broke a rebuild. */
9749
+ const MAX_SWAP_RETRIES = 2;
9750
+ /**
9751
+ * Runs `rebuildSceneRenderables`, and runs it again when a material swap landed during it and made
9752
+ * it throw.
9753
+ *
9754
+ * @remarks
9755
+ * A group builder awaits its shader modules (`import()`) before it reads each mesh's material, and
9756
+ * on a loaded machine that await spans frames. A mesh given a material of another family meanwhile
9757
+ * reaches the old family's builder: the Standard one reads `diffuseColor[0]` off a PBR material and
9758
+ * throws `Cannot read properties of undefined (reading '0')` (`buildStandardMeshRenderables`,
9759
+ * `writeStdMaterialData`, `lib/material/standard/standard-pipeline.js` 278). Lite expects swaps to
9760
+ * land mid-build — it puts the group's old renderables back on a throw, and a rebuild that does not
9761
+ * throw re-sorts the groups and goes round again (`membershipDrifted`, `lib/scene/scene-rebuild.js`)
9762
+ * — but it rethrows, so the rest of the rebuild is skipped. Starting over sorts the groups from the
9763
+ * current materials. A throw with every material unchanged is not this race, and is rethrown.
9764
+ *
9765
+ * @param scene - The scene to rebuild.
9766
+ * @param resets - The scene's record, which counts the restarts.
9767
+ * @param retries - How many more times to start over.
9768
+ * @returns A promise that resolves when a rebuild has finished.
9769
+ */
9770
+ async function rebuildAcrossMaterialSwaps(scene, resets, retries = MAX_SWAP_RETRIES) {
9771
+ const meshes = scene.meshes;
9772
+ const materials = meshes.map((mesh) => mesh.material);
9773
+ try {
9439
9774
  await rebuildSceneRenderables(scene);
9440
- return;
9775
+ } catch (error) {
9776
+ if (!(scene.meshes !== meshes || meshes.some((mesh, index) => mesh.material !== materials[index])) || retries <= 0) throw error;
9777
+ if (resets !== void 0) resets.retries += 1;
9778
+ await rebuildAcrossMaterialSwaps(scene, resets, retries - 1);
9441
9779
  }
9442
- trackMaterialCacheResets(scene, resets);
9443
- takeUnconfirmed(resets);
9444
- await rebuildSceneRenderables(scene);
9445
- if (takeUnconfirmed(resets)) await rebuildSceneRenderables(scene);
9780
+ }
9781
+ /**
9782
+ * Keeps an engine from freeing retired GPU resources until the returned function is called.
9783
+ *
9784
+ * @remarks
9785
+ * `rebuildSceneRenderables` rebuilds one material group at a time and retires each group's old
9786
+ * uniform buffers and bind groups as soon as that group is done, but it only bumps
9787
+ * `_renderableVersion` and re-records the frame graph after the **last** group
9788
+ * (`rebuildSceneGroups`, `lib/scene/scene-rebuild.js`). Until then every frame still draws the old
9789
+ * renderables. Lite frees a retired resource once the next submitted frame has finished
9790
+ * (`flushGpuResourceRetirements`, `lib/engine/gpu-resource-retirement.js`), so when a later group
9791
+ * takes two frames or more to build — a slow machine, or a pipeline to compile — the following
9792
+ * frames submit buffers that are already destroyed, and WebGPU rejects them ("[Buffer] used in
9793
+ * submit while destroyed"). Holding the releases until the whole rebuild has finished means they
9794
+ * are fenced behind the first frame that draws the new renderables.
9795
+ *
9796
+ * While a hold is active, `_flushGpuRetirements` reads as absent, so `renderFrame` skips it and
9797
+ * the retired resources wait in the engine's list. Lite installs the flush with `??=`, so an
9798
+ * assignment it makes meanwhile is kept only when it had none before. Holds nest.
9799
+ *
9800
+ * @param engine - The engine that renders the scene being rebuilt.
9801
+ * @returns A function that ends this hold. Call it once.
9802
+ */
9803
+ function holdGpuRetirements(engine) {
9804
+ const target = engine;
9805
+ let hold = target._igxRetirementHold;
9806
+ if (hold === void 0) {
9807
+ const state = {
9808
+ count: 0,
9809
+ flush: target._flushGpuRetirements
9810
+ };
9811
+ Object.defineProperty(target, "_flushGpuRetirements", {
9812
+ configurable: true,
9813
+ enumerable: true,
9814
+ get: () => state.count > 0 ? void 0 : state.flush,
9815
+ set: (flush) => {
9816
+ state.flush ??= flush;
9817
+ }
9818
+ });
9819
+ Object.defineProperty(target, "_igxRetirementHold", {
9820
+ configurable: true,
9821
+ value: state
9822
+ });
9823
+ hold = state;
9824
+ }
9825
+ const held = hold;
9826
+ held.count += 1;
9827
+ return () => {
9828
+ held.count -= 1;
9829
+ if (held.count === 0) {
9830
+ Object.defineProperty(target, "_flushGpuRetirements", {
9831
+ configurable: true,
9832
+ enumerable: true,
9833
+ writable: true,
9834
+ value: held.flush
9835
+ });
9836
+ delete target._igxRetirementHold;
9837
+ }
9838
+ };
9446
9839
  }
9447
9840
  /**
9448
9841
  * Reads and clears {@link MaterialCacheResets.unconfirmed}.
@@ -9620,18 +10013,35 @@ function createPicker(scene) {
9620
10013
  return createScenePicker(scene);
9621
10014
  }
9622
10015
  /**
9623
- * Picks the object under one CSS pixel, optionally restricted to the meshes a predicate accepts.
10016
+ * Loads the overlay module (`docs/architecture/07-rendering.md` §2.10).
10017
+ *
10018
+ * @remarks
10019
+ * It is loaded on first use, so a game that never opens an overlay ships none of it
10020
+ * (`CONSTITUTION.md` §2.5).
10021
+ *
10022
+ * @returns The function that opens an overlay scene.
10023
+ *
10024
+ * @internal
10025
+ */
10026
+ async function loadOverlayOpener() {
10027
+ return (await import("./overlay-CjVgsfrm.js")).openOverlayScene;
10028
+ }
10029
+ /**
10030
+ * Picks the object under one backing-store pixel, optionally restricted to the meshes a predicate
10031
+ * accepts and looking through earlier hits.
9624
10032
  *
9625
10033
  * @param picker - The app's picker.
9626
- * @param x - The CSS pixel x, from the canvas's left edge.
9627
- * @param y - The CSS pixel y, from the canvas's top edge.
10034
+ * @param scene - The scene the picker belongs to.
10035
+ * @param x - The backing-store pixel x, from the canvas's left edge.
10036
+ * @param y - The backing-store pixel y, from the canvas's top edge.
9628
10037
  * @param accept - The tag predicate, or `null` to consider every mesh.
10038
+ * @param ignore - Earlier hits to look through.
9629
10039
  * @returns Lite's picking info.
9630
10040
  *
9631
10041
  * @internal
9632
10042
  */
9633
- function pickPixel(picker, x, y, accept) {
9634
- return accept === null ? pickScenePixel(picker, x, y) : pickScenePixelWhere(picker, x, y, accept);
10043
+ function pickPixel(picker, scene, x, y, accept, ignore) {
10044
+ return pickScenePixel(picker, scene, x, y, accept, ignore);
9635
10045
  }
9636
10046
  /**
9637
10047
  * Installs one hidden probe per material so their families are compiled at `registerScene`
@@ -10154,6 +10564,13 @@ var RendererImpl = class {
10154
10564
  /** `true` once a light gained or lost a shadow generator, so the next rebuild needs fresh layouts. */
10155
10565
  needsShadowLayoutReset = false;
10156
10566
  /**
10567
+ * `true` from the moment the render sync system queues a renderable rebuild until the last one it
10568
+ * owes has finished. A light waits for it to be `false` before it gains or loses a shadow generator.
10569
+ */
10570
+ isRebuildInFlight = false;
10571
+ /** Scene changes held back until the rebuild in flight has finished; see {@link RendererImpl.afterRebuild}. */
10572
+ #afterRebuild = [];
10573
+ /**
10157
10574
  * The PBR deformation kinds (`PBR_DEFORMER` bits) a full renderable build has already composed on
10158
10575
  * this engine. A kind missing from it gets fresh layouts on its first rebuild (`../lite/pbr-deformers.ts`).
10159
10576
  */
@@ -10178,6 +10595,10 @@ var RendererImpl = class {
10178
10595
  #countersMeshes;
10179
10596
  #countersRebuilds;
10180
10597
  #picker = null;
10598
+ /** The mesh behind each hit this renderer returned, so a later pick can be told to ignore it. */
10599
+ #pickIdentities = /* @__PURE__ */ new WeakMap();
10600
+ /** The open overlays, by their Lite scene. */
10601
+ #overlays = /* @__PURE__ */ new Map();
10181
10602
  #warmUp = null;
10182
10603
  #syncSystem = null;
10183
10604
  /** Adapter chunks a component asked for; `app.start()` waits for them before it reconciles. */
@@ -10190,6 +10611,7 @@ var RendererImpl = class {
10190
10611
  #profileTasks = false;
10191
10612
  #isSceneRegistered = false;
10192
10613
  #isLoopRunning = false;
10614
+ #isDisposed = false;
10193
10615
  /** The clear colour as authored, in sRGB, before image processing. */
10194
10616
  #authoredClear = {
10195
10617
  r: 0,
@@ -10434,14 +10856,14 @@ var RendererImpl = class {
10434
10856
  *
10435
10857
  * @param x - The backing-store pixel x, from the canvas's left edge.
10436
10858
  * @param y - The backing-store pixel y, from the canvas's top edge.
10437
- * @param options - An entity filter.
10859
+ * @param options - An entity filter, and what to look through.
10438
10860
  * @returns What was hit, or `null` for a miss.
10439
10861
  */
10440
10862
  async pickAsync(x, y, options) {
10441
10863
  if (this.isHeadless) return null;
10442
10864
  const picker = this.#picker ??= createPicker(this.scene);
10443
- const filter = options?.filter;
10444
- const info = await pickPixel(picker, x, y, filter === void 0 ? null : (tag) => acceptsEntityTag(this.#app.world, tag, filter));
10865
+ const plan = this.planPick(options);
10866
+ const info = await pickPixel(picker, this.scene, x, y, plan.accept, plan.hits);
10445
10867
  return this.resolvePick(info);
10446
10868
  }
10447
10869
  /**
@@ -10479,6 +10901,61 @@ var RendererImpl = class {
10479
10901
  this.#features[feature] = true;
10480
10902
  }
10481
10903
  /**
10904
+ * Opens an overlay drawn over the finished frame.
10905
+ *
10906
+ * @returns The overlay.
10907
+ * @throws IgnifxError with code `IGX-0728` on a headless app or before the render scene is
10908
+ * registered, and `IGX-0106` when the app is disposed, also while the overlay was opening.
10909
+ */
10910
+ async openOverlay() {
10911
+ this.#assertOverlayAllowed();
10912
+ const open = await loadOverlayOpener();
10913
+ this.#assertOverlayAllowed();
10914
+ const overlays = this.#overlays;
10915
+ let overlay;
10916
+ try {
10917
+ overlay = await open(this.engine, this.scene, {
10918
+ isPeer: (context) => overlays.has(context),
10919
+ onDispose: (scene) => {
10920
+ overlays.delete(scene);
10921
+ },
10922
+ onError: (error) => {
10923
+ this.#app.onError.emit({
10924
+ error,
10925
+ source: "system",
10926
+ phase: null,
10927
+ entity: null,
10928
+ component: null
10929
+ });
10930
+ }
10931
+ });
10932
+ } catch (error) {
10933
+ if (this.#isDisposed) throw overlayAfterDisposeError();
10934
+ throw error;
10935
+ }
10936
+ if (this.#isDisposed) {
10937
+ overlay.dispose();
10938
+ throw overlayAfterDisposeError();
10939
+ }
10940
+ overlays.set(overlay.lite.scene, overlay);
10941
+ return overlay;
10942
+ }
10943
+ /**
10944
+ * Refuses an overlay on a disposed or headless app, or before the render scene is registered.
10945
+ *
10946
+ * @throws IgnifxError with code `IGX-0106` once the app is disposed, `IGX-0728` otherwise.
10947
+ */
10948
+ #assertOverlayAllowed() {
10949
+ if (this.#isDisposed) throw overlayAfterDisposeError();
10950
+ if (this.isHeadless || !this.#isSceneRegistered) throw new IgnifxError(CoreErrorCode.overlayNeedsRenderScene, "openOverlay() needs a canvas-backed app whose render scene is registered.", {
10951
+ context: {
10952
+ member: "app.renderer.openOverlay()",
10953
+ headless: this.isHeadless
10954
+ },
10955
+ hint: this.isHeadless ? "A headless app draws nothing, so it has no overlay. Create the app with a canvas." : "Call it after app.start() has resolved."
10956
+ });
10957
+ }
10958
+ /**
10482
10959
  * Registers a probe that answers whether another rendering context has a camera of its own.
10483
10960
  *
10484
10961
  * @param probe - Answers `true` while the caller has an active camera for the world.
@@ -10547,10 +11024,52 @@ var RendererImpl = class {
10547
11024
  readTargetSizePx(this.engine, out);
10548
11025
  }
10549
11026
  /**
11027
+ * Turns a pick's options into the mesh predicate and the earlier hits Lite looks through.
11028
+ *
11029
+ * @param options - The caller's options.
11030
+ * @returns The predicate — `null` when every mesh may be picked — and the hits to ignore.
11031
+ *
11032
+ * @internal
11033
+ */
11034
+ planPick(options) {
11035
+ const filter = options?.filter;
11036
+ const ignore = options?.ignore;
11037
+ if (ignore === void 0 || ignore.length === 0) {
11038
+ const world = this.#app.world;
11039
+ return {
11040
+ accept: filter === void 0 ? null : (tag) => acceptsEntityTag(world, tag, filter),
11041
+ hits: []
11042
+ };
11043
+ }
11044
+ const world = this.#app.world;
11045
+ const entities = /* @__PURE__ */ new Set();
11046
+ const components = /* @__PURE__ */ new Set();
11047
+ const hits = [];
11048
+ for (const item of ignore) {
11049
+ const identity = this.#pickIdentities.get(item);
11050
+ if (identity !== void 0) hits.push(identity);
11051
+ else if ("children" in item) {
11052
+ if (!item.isDestroyed && world.getEntityByHandle(item.handle) === item) entities.add(item.handle);
11053
+ } else if ("isDestroyed" in item && !item.isDestroyed && world.getComponentByHandle(item.handle) === item) components.add(item.handle);
11054
+ }
11055
+ if (filter === void 0 && entities.size === 0 && components.size === 0) return {
11056
+ accept: null,
11057
+ hits
11058
+ };
11059
+ return {
11060
+ accept: (tag) => {
11061
+ if (tag === null) return filter === void 0;
11062
+ if (entities.has(tag.entity) || tag.component !== void 0 && components.has(tag.component)) return false;
11063
+ return filter === void 0 || acceptsEntityTag(world, tag, filter);
11064
+ },
11065
+ hits
11066
+ };
11067
+ }
11068
+ /**
10550
11069
  * Resolves a Lite pick result back to the entity and component that own the mesh.
10551
11070
  *
10552
11071
  * @param info - Lite's picking info, from the GPU picker or a CPU ray cast.
10553
- * @returns What was hit, or `null` for a miss or a mesh ignifx did not create.
11072
+ * @returns What was hit, or `null` for a miss or a mesh no entity owns.
10554
11073
  *
10555
11074
  * @internal
10556
11075
  */
@@ -10562,13 +11081,19 @@ var RendererImpl = class {
10562
11081
  const entity = world.getEntityByHandle(toEntityHandle(tag.entity));
10563
11082
  if (entity === null) return null;
10564
11083
  const component = tag.component;
10565
- return {
11084
+ const thinInstanceIndex = info.thinInstanceIndex >= 0 ? info.thinInstanceIndex : null;
11085
+ const pick = {
10566
11086
  entity,
10567
11087
  component: component === void 0 ? null : world.getComponentByHandle(toComponentHandle(component)),
10568
11088
  point: info.pickedPoint,
10569
11089
  normal: info.pickedNormalWorld ?? info.pickedNormal,
10570
- distance: info.distance
11090
+ distance: info.distance,
11091
+ meshName: readPickedMeshName(info),
11092
+ thinInstanceIndex
10571
11093
  };
11094
+ const identity = readPickedIdentity(info);
11095
+ if (identity !== null) this.#pickIdentities.set(pick, identity);
11096
+ return pick;
10572
11097
  }
10573
11098
  /**
10574
11099
  * Records the Lite objects the app owns, so the service keeps working while the app is being
@@ -10762,11 +11287,47 @@ var RendererImpl = class {
10762
11287
  counters.set(this.#countersRebuilds, this.renderableRebuilds);
10763
11288
  }
10764
11289
  /**
10765
- * Releases the picker and the warm-up probes. The core extension registers it as a disposer.
11290
+ * Runs a scene change now, or holds it until the render sync system's rebuild has finished when
11291
+ * one is in flight.
11292
+ *
11293
+ * @remarks
11294
+ * For a change a rebuild must not see half-way: one that changes how many shadow generators the
11295
+ * scene has. A rebuild reads them group by group against layouts cached without that number, so
11296
+ * a group built after the change gets a bind group the layout does not match.
11297
+ *
11298
+ * @param change - The change.
11299
+ *
11300
+ * @internal
11301
+ */
11302
+ afterRebuild(change) {
11303
+ if (this.isRebuildInFlight) {
11304
+ this.#afterRebuild.push(change);
11305
+ return;
11306
+ }
11307
+ change();
11308
+ }
11309
+ /**
11310
+ * Takes the changes {@link RendererImpl.afterRebuild} held back. The render sync system runs them
11311
+ * once its rebuild has finished. A disposed renderer hands back none: its scene is gone.
11312
+ *
11313
+ * @returns The changes, oldest first.
11314
+ *
11315
+ * @internal
11316
+ */
11317
+ takeHeldChanges() {
11318
+ const held = this.#afterRebuild.splice(0);
11319
+ return this.#isDisposed ? [] : held;
11320
+ }
11321
+ /**
11322
+ * Releases the open overlays, the picker and the warm-up probes. The core extension registers it
11323
+ * as a disposer.
10766
11324
  *
10767
11325
  * @internal
10768
11326
  */
10769
11327
  dispose() {
11328
+ this.#isDisposed = true;
11329
+ this.#afterRebuild.length = 0;
11330
+ for (const overlay of this.#overlays.values()) overlay.dispose();
10770
11331
  const picker = this.#picker;
10771
11332
  this.#picker = null;
10772
11333
  if (picker !== null) disposeScenePicker(picker);
@@ -10848,6 +11409,14 @@ function rendererInternals(renderer) {
10848
11409
  function forceRendererDeviceLossForTesting(renderer) {
10849
11410
  rendererInternals(renderer).forceDeviceLossForTesting();
10850
11411
  }
11412
+ /**
11413
+ * The error an overlay request gets once the app is disposed.
11414
+ *
11415
+ * @returns `IGX-0106`.
11416
+ */
11417
+ function overlayAfterDisposeError() {
11418
+ return new IgnifxError(CoreErrorCode.appDisposed, "The app has been disposed; app.renderer.openOverlay() is no longer available.", { context: { member: "app.renderer.openOverlay()" } });
11419
+ }
10851
11420
  //#endregion
10852
11421
  //#region src/render/instanced-mesh-renderer.ts
10853
11422
  /**
@@ -10865,9 +11434,9 @@ function forceRendererDeviceLossForTesting(renderer) {
10865
11434
  * abort every other renderable's reconciliation. The LOD pairing's `distance` and `band` are not in
10866
11435
  * that set and are reconciled every frame.
10867
11436
  *
10868
- * `pickable` defaults to `false`, the opposite of `MeshRenderer`: Lite's picker reports
10869
- * `thinInstanceIndex` (`index.d.ts` 8720) but `RenderPick` does not carry it, so a hit would name
10870
- * the entity without saying which instance. Headless, the component keeps its slab, count, colours
11437
+ * `pickable` defaults to `false`, the opposite of `MeshRenderer`: a scatter of thousands of
11438
+ * instances is rarely what a click means. Set it to `true` and `RenderPick.thinInstanceIndex` says
11439
+ * which instance was hit. Headless, the component keeps its slab, count, colours
10871
11440
  * and flags and touches no scene (`docs/architecture/07-rendering.md` §6).
10872
11441
  */
10873
11442
  /** How many floats one instance matrix occupies. */
@@ -11305,7 +11874,7 @@ function instancedMeshRendererSchema() {
11305
11874
  castShadows: bool(true, { tooltip: "Whether the instances are rendered into shadow maps." }),
11306
11875
  receiveShadows: bool(true, { tooltip: "Whether shadow maps darken the instances." }),
11307
11876
  renderOrder: i32(0, { tooltip: "Sort key within the opaque or transparent phase; lower draws first." }),
11308
- pickable: bool(false, { tooltip: "Whether picking considers the instances; a hit names no instance index." }),
11877
+ pickable: bool(false, { tooltip: "Whether picking considers the instances; a hit names the instance it hit." }),
11309
11878
  lod: optional(record({
11310
11879
  mesh: asset(MeshAsset, { tooltip: "The coarse mesh drawn beyond the switch distance." }),
11311
11880
  distance: f32(40, {
@@ -12187,6 +12756,7 @@ var Light = class Light extends Component {
12187
12756
  this.#warnAboutShadows(renderer);
12188
12757
  return false;
12189
12758
  }
12759
+ if (renderer.isRebuildInFlight) return false;
12190
12760
  this.#appliedShadows = wanted;
12191
12761
  if (!wanted) {
12192
12762
  this.#releaseGenerator(renderer);
@@ -12245,12 +12815,21 @@ var Light = class Light extends Component {
12245
12815
  * @param renderer - The rendering service, for the scene.
12246
12816
  */
12247
12817
  #teardown(renderer) {
12248
- this.#releaseGenerator(renderer);
12818
+ const generator = this.#generator;
12249
12819
  const light = this.#light;
12820
+ this.#generator = null;
12250
12821
  this.#light = null;
12251
12822
  this.#appliedType = null;
12252
12823
  this.#appliedShadows = false;
12253
- if (light !== null) removeLightFromScene(renderer.scene, light);
12824
+ const remove = () => {
12825
+ if (generator !== null) {
12826
+ detachShadows(renderer.scene, light, generator);
12827
+ renderer.needsShadowLayoutReset = true;
12828
+ }
12829
+ if (light !== null) removeLightFromScene(renderer.scene, light);
12830
+ };
12831
+ if (generator === null) remove();
12832
+ else renderer.afterRebuild(remove);
12254
12833
  }
12255
12834
  };
12256
12835
  /**
@@ -13289,6 +13868,312 @@ function readDefines(file) {
13289
13868
  return defines;
13290
13869
  }
13291
13870
  //#endregion
13871
+ //#region src/render/mesh-file.ts
13872
+ /**
13873
+ * The `.mesh.json` file format (ADR-0029): one primitive and the options its `MeshAsset` factory
13874
+ * takes, so a scene file can name a primitive by address.
13875
+ *
13876
+ * ```json
13877
+ * { "format": "ignifx.mesh", "formatVersion": 1, "primitive": "box", "options": { "size": 1 } }
13878
+ * ```
13879
+ *
13880
+ * One table, {@link MESH_PRIMITIVE_OPTIONS}, drives the runtime check and the JSON Schema, so the
13881
+ * two cannot drift apart.
13882
+ */
13883
+ /**
13884
+ * The `format` header a `.mesh.json` carries.
13885
+ *
13886
+ * @public
13887
+ */
13888
+ const MESH_FILE_FORMAT = "ignifx.mesh";
13889
+ /**
13890
+ * The only `.mesh.json` `formatVersion` this build reads.
13891
+ *
13892
+ * @public
13893
+ */
13894
+ const MESH_FORMAT_VERSION = 1;
13895
+ /**
13896
+ * The address suffix that selects the mesh loader.
13897
+ *
13898
+ * @public
13899
+ */
13900
+ const MESH_FILE_EXTENSION = ".mesh.json";
13901
+ /**
13902
+ * Every option each primitive takes, and what it holds. The keys are exactly the fields of the
13903
+ * factory's options type (`BoxMeshOptions`, …); the compiler checks that.
13904
+ *
13905
+ * @public
13906
+ */
13907
+ const MESH_PRIMITIVE_OPTIONS = {
13908
+ box: {
13909
+ size: "length",
13910
+ width: "length",
13911
+ height: "length",
13912
+ depth: "length"
13913
+ },
13914
+ sphere: {
13915
+ diameter: "length",
13916
+ segments: "count"
13917
+ },
13918
+ plane: {
13919
+ size: "length",
13920
+ width: "length",
13921
+ height: "length"
13922
+ },
13923
+ ground: {
13924
+ width: "length",
13925
+ height: "length",
13926
+ subdivisions: "count",
13927
+ uvScale: "pair"
13928
+ },
13929
+ cylinder: {
13930
+ height: "length",
13931
+ diameter: "length",
13932
+ diameterTop: "length",
13933
+ diameterBottom: "length",
13934
+ tessellation: "count"
13935
+ },
13936
+ capsule: {
13937
+ height: "length",
13938
+ radius: "length",
13939
+ tessellation: "count"
13940
+ },
13941
+ torus: {
13942
+ diameter: "length",
13943
+ thickness: "length",
13944
+ tessellation: "count"
13945
+ }
13946
+ };
13947
+ /** The top-level fields a mesh file may carry. */
13948
+ const MESH_FILE_FIELDS = Object.freeze({
13949
+ format: true,
13950
+ formatVersion: true,
13951
+ name: true,
13952
+ primitive: true,
13953
+ options: true
13954
+ });
13955
+ /**
13956
+ * Reads and checks a parsed `.mesh.json`.
13957
+ *
13958
+ * @param parsed - The parsed JSON.
13959
+ * @param address - The file's address, for error messages.
13960
+ * @returns The file.
13961
+ * @throws IgnifxError with code `IGX-0709` when the file has no `ignifx.mesh` header, `IGX-0603`
13962
+ * when its format version is not 1, or `IGX-0507` when it names an unknown primitive, an option the
13963
+ * primitive does not take, or a value the option cannot hold.
13964
+ *
13965
+ * @internal
13966
+ */
13967
+ function readMeshFile(parsed, address) {
13968
+ const file = asObject(parsed);
13969
+ if (file === null || file["format"] !== "ignifx.mesh") throw new IgnifxError(CoreErrorCode.invalidAssetFile, `${address} is not an ${MESH_FILE_FORMAT} file.`, {
13970
+ context: {
13971
+ file: address,
13972
+ format: MESH_FILE_FORMAT
13973
+ },
13974
+ hint: `A mesh file starts with { "format": "${MESH_FILE_FORMAT}", "formatVersion": ${String(1)} }.`
13975
+ });
13976
+ const version = file["formatVersion"];
13977
+ if (version !== 1) throw new IgnifxError(CoreErrorCode.unsupportedFormatVersion, `${address} declares format version ${JSON.stringify(version ?? null)}, which this build cannot read.`, {
13978
+ context: {
13979
+ file: address,
13980
+ version: JSON.stringify(version ?? null)
13981
+ },
13982
+ hint: `This build reads ${MESH_FILE_FORMAT} version ${String(1)}.`
13983
+ });
13984
+ for (const key of Object.keys(file)) if (!Object.hasOwn(MESH_FILE_FIELDS, key)) throw invalidMesh(address, `"${key}" is not a mesh file field`);
13985
+ const name = file["name"];
13986
+ if (name !== void 0 && typeof name !== "string") throw invalidMesh(address, "\"name\" must be a string");
13987
+ const primitive = readPrimitive(file["primitive"], address);
13988
+ const definition = {
13989
+ primitive,
13990
+ options: readOptions(file["options"], primitive, address)
13991
+ };
13992
+ return {
13993
+ name: name ?? null,
13994
+ definition
13995
+ };
13996
+ }
13997
+ /**
13998
+ * The JSON Schema `@ignifx/vite-plugin` validates `.mesh.json` files against, built from
13999
+ * {@link MESH_PRIMITIVE_OPTIONS}.
14000
+ *
14001
+ * @returns The schema document.
14002
+ *
14003
+ * @example
14004
+ * ```ts
14005
+ * // vite.config.ts
14006
+ * ignifx({ schemas: { formats: { [MESH_FILE_FORMAT]: meshFileJsonSchema() } } });
14007
+ * ```
14008
+ *
14009
+ * @public
14010
+ */
14011
+ function meshFileJsonSchema() {
14012
+ const branches = [];
14013
+ for (const primitive of MESH_PRIMITIVES) {
14014
+ const properties = {};
14015
+ for (const [option, kind] of Object.entries(MESH_PRIMITIVE_OPTIONS[primitive])) properties[option] = { $ref: `#/$defs/${kind}` };
14016
+ branches.push({ properties: {
14017
+ primitive: { const: primitive },
14018
+ options: {
14019
+ type: "object",
14020
+ additionalProperties: false,
14021
+ properties
14022
+ }
14023
+ } });
14024
+ }
14025
+ return {
14026
+ $schema: "https://json-schema.org/draft/2020-12/schema",
14027
+ $id: `https://ignifx.com/schemas/${MESH_FILE_FORMAT}.v${String(1)}.json`,
14028
+ title: "ignifx mesh file",
14029
+ type: "object",
14030
+ required: [
14031
+ "format",
14032
+ "formatVersion",
14033
+ "primitive"
14034
+ ],
14035
+ additionalProperties: false,
14036
+ properties: {
14037
+ format: { const: MESH_FILE_FORMAT },
14038
+ formatVersion: { const: 1 },
14039
+ name: { type: "string" },
14040
+ primitive: { enum: [...MESH_PRIMITIVES] },
14041
+ options: { type: "object" }
14042
+ },
14043
+ oneOf: branches,
14044
+ $defs: {
14045
+ length: {
14046
+ type: "number",
14047
+ minimum: 0
14048
+ },
14049
+ count: {
14050
+ type: "integer",
14051
+ minimum: 1
14052
+ },
14053
+ pair: {
14054
+ type: "array",
14055
+ items: { type: "number" },
14056
+ minItems: 2,
14057
+ maxItems: 2
14058
+ }
14059
+ }
14060
+ };
14061
+ }
14062
+ /**
14063
+ * Narrows a JSON value to an object.
14064
+ *
14065
+ * @param value - The value.
14066
+ * @returns The object, or `null` when it is not one.
14067
+ */
14068
+ function asObject(value) {
14069
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
14070
+ return value;
14071
+ }
14072
+ /**
14073
+ * Reads the `primitive` field.
14074
+ *
14075
+ * @param value - The field's value.
14076
+ * @param address - The file's address.
14077
+ * @returns The primitive.
14078
+ * @throws IgnifxError with code `IGX-0507` when it is not one of {@link MESH_PRIMITIVES}.
14079
+ */
14080
+ function readPrimitive(value, address) {
14081
+ for (const primitive of MESH_PRIMITIVES) if (value === primitive) return primitive;
14082
+ throw invalidMesh(address, `"primitive" is ${JSON.stringify(value ?? null)}; expected one of ${MESH_PRIMITIVES.join(", ")}`);
14083
+ }
14084
+ /**
14085
+ * Reads and checks the `options` field against one primitive's row of the table.
14086
+ *
14087
+ * @param value - The field's value; missing means every option takes its default.
14088
+ * @param primitive - The primitive the options are for.
14089
+ * @param address - The file's address.
14090
+ * @returns A copy of the options.
14091
+ * @throws IgnifxError with code `IGX-0507` when an option is unknown or holds the wrong value.
14092
+ */
14093
+ function readOptions(value, primitive, address) {
14094
+ if (value === void 0) return {};
14095
+ const options = asObject(value);
14096
+ if (options === null) throw invalidMesh(address, "\"options\" must be an object");
14097
+ const kinds = MESH_PRIMITIVE_OPTIONS[primitive];
14098
+ const result = {};
14099
+ for (const [option, optionValue] of Object.entries(options)) {
14100
+ const kind = Object.hasOwn(kinds, option) ? kinds[option] : void 0;
14101
+ if (kind === void 0) throw invalidMesh(address, `a ${primitive} has no option "${option}"; it takes ${Object.keys(kinds).join(", ")}`);
14102
+ if (!isOptionValue(optionValue, kind)) throw invalidMesh(address, `options.${option} must be ${OPTION_KIND_TEXT[kind]}; got ${JSON.stringify(optionValue)}`);
14103
+ result[option] = optionValue;
14104
+ }
14105
+ return result;
14106
+ }
14107
+ /** How an error message describes each option kind. */
14108
+ const OPTION_KIND_TEXT = {
14109
+ length: "a number of metres, zero or more",
14110
+ count: "a whole number, one or more",
14111
+ pair: "an array of two numbers"
14112
+ };
14113
+ /**
14114
+ * Checks one option value against its kind.
14115
+ *
14116
+ * @param value - The value.
14117
+ * @param kind - What the option holds.
14118
+ * @returns `true` when the value fits.
14119
+ */
14120
+ function isOptionValue(value, kind) {
14121
+ if (kind === "length") return typeof value === "number" && Number.isFinite(value) && value >= 0;
14122
+ if (kind === "count") return typeof value === "number" && Number.isInteger(value) && value >= 1;
14123
+ return Array.isArray(value) && value.length === 2 && value.every((item) => typeof item === "number" && Number.isFinite(item));
14124
+ }
14125
+ /**
14126
+ * Builds the `IGX-0507` failure.
14127
+ *
14128
+ * @param address - The file's address.
14129
+ * @param problem - What is wrong, without a trailing period.
14130
+ * @returns The error to throw.
14131
+ */
14132
+ function invalidMesh(address, problem) {
14133
+ return new IgnifxError(CoreErrorCode.invalidMeshFile, `${address} is not a valid mesh file: ${problem}.`, {
14134
+ context: {
14135
+ file: address,
14136
+ problem
14137
+ },
14138
+ hint: "See MESH_PRIMITIVE_OPTIONS for the options each primitive takes."
14139
+ });
14140
+ }
14141
+ //#endregion
14142
+ //#region src/render/loaders/mesh-loader.ts
14143
+ /**
14144
+ * Builds the `mesh` loader: `.mesh.json` to `MeshAsset` (ADR-0029).
14145
+ *
14146
+ * @remarks
14147
+ * The file names a primitive and its options, and the loader builds it exactly as the matching
14148
+ * `MeshAsset` factory would. The mesh is named after the file's `name`, or its address. A headless
14149
+ * app builds no GPU geometry. A file that is not a mesh file fails the load with `IGX-0709`, a
14150
+ * format version other than 1 with `IGX-0603`, and an unknown primitive or a bad option with
14151
+ * `IGX-0507`. The same `mesh` type still holds the in-memory meshes the factories publish; the
14152
+ * loader's `unload` frees both kinds.
14153
+ *
14154
+ * @returns The loader to register with `ctx.registerAssetLoader`.
14155
+ *
14156
+ * @example
14157
+ * ```ts
14158
+ * ctx.registerAssetLoader(createMeshLoader());
14159
+ * ```
14160
+ *
14161
+ * @public
14162
+ */
14163
+ function createMeshLoader() {
14164
+ return {
14165
+ type: MESH_ASSET_TYPE,
14166
+ extensions: [MESH_FILE_EXTENSION],
14167
+ async load(ctx) {
14168
+ const file = readMeshFile(await ctx.fetchJson(), ctx.address);
14169
+ return createPrimitiveMeshAsset(ctx.app, file.name ?? ctx.address, file.definition);
14170
+ },
14171
+ unload(value) {
14172
+ value.dispose();
14173
+ }
14174
+ };
14175
+ }
14176
+ //#endregion
13292
14177
  //#region src/lite/gpu/gltf.ts
13293
14178
  /** The suffix `cloneTransformNode` appends to every cloned node's name. */
13294
14179
  const CLONE_SUFFIX = "_clone";
@@ -13641,7 +14526,7 @@ let effectLayer = null;
13641
14526
  * @internal
13642
14527
  */
13643
14528
  async function loadPostEffectSupport() {
13644
- const [compiler, effects] = await Promise.all([compilerLayer ?? import("./post-effect-compiler-Rce26Eue.js"), effectLayer ?? import("./effect-task-CMbuO6Kb.js")]);
14529
+ const [compiler, effects] = await Promise.all([compilerLayer ?? import("./post-effect-compiler-pOvXae-i.js"), effectLayer ?? import("./effect-task-CMbuO6Kb.js")]);
13645
14530
  compilerLayer = compiler;
13646
14531
  effectLayer = effects;
13647
14532
  }
@@ -13779,7 +14664,7 @@ function createShaderLoader() {
13779
14664
  type: SHADER_ASSET_TYPE,
13780
14665
  extensions: SHADER_FILE_EXTENSIONS,
13781
14666
  async load(ctx) {
13782
- const [source, pragma] = await Promise.all([ctx.fetchText(), import("./shader-pragma-tw6AKaQD.js")]);
14667
+ const [source, pragma] = await Promise.all([ctx.fetchText(), import("./shader-pragma-qO9_6sTd.js")]);
13783
14668
  const declaration = pragma.parseShaderDeclaration(source, ctx.address);
13784
14669
  await loadShaderSupport();
13785
14670
  if (declaration.kind === "surface") await loadSurfaceShaderSupport();
@@ -16330,7 +17215,6 @@ var RenderSyncSystem = class {
16330
17215
  /** Each world's winning `Environment` last frame, so a change of winner is seen. */
16331
17216
  #lastEnvironment = /* @__PURE__ */ new WeakMap();
16332
17217
  #isRebuildDue = false;
16333
- #isRebuildInFlight = false;
16334
17218
  /** A rebuild asked for while one was already running; it is run once the in-flight one lands. */
16335
17219
  #isRebuildPending = false;
16336
17220
  #areCastersDirty = false;
@@ -16409,13 +17293,13 @@ var RenderSyncSystem = class {
16409
17293
  renderer.refreshClearColor();
16410
17294
  this.#applyStacks(world);
16411
17295
  this.#areCastersDirty = this.#areCastersDirty || castersChanged;
16412
- if (renderer.materialCacheResets.unconfirmed && !this.#isRebuildDue && !this.#isRebuildInFlight) this.#rebuildRenderables();
17296
+ if (renderer.materialCacheResets.unconfirmed && !this.#isRebuildDue && !renderer.isRebuildInFlight) this.#rebuildRenderables();
16413
17297
  if (this.#isRebuildDue && !topologyChanged) {
16414
17298
  this.#isRebuildDue = false;
16415
17299
  this.#rebuildRenderables();
16416
17300
  }
16417
17301
  this.#isRebuildDue = this.#isRebuildDue || topologyChanged;
16418
- if (this.#areCastersDirty && !this.#isRebuildDue && !this.#isRebuildInFlight) {
17302
+ if (this.#areCastersDirty && !this.#isRebuildDue && !renderer.isRebuildInFlight) {
16419
17303
  this.#areCastersDirty = false;
16420
17304
  this.#rebuildCasters(meshes, models, instanced, lights);
16421
17305
  }
@@ -16614,11 +17498,11 @@ var RenderSyncSystem = class {
16614
17498
  renderer.renderableRebuilds += 1;
16615
17499
  renderer.needsCasterRebuild = true;
16616
17500
  if (renderer.isHeadless || !renderer.isSceneRegistered) return;
16617
- if (this.#isRebuildInFlight) {
17501
+ if (renderer.isRebuildInFlight) {
16618
17502
  this.#isRebuildPending = true;
16619
17503
  return;
16620
17504
  }
16621
- this.#isRebuildInFlight = true;
17505
+ renderer.isRebuildInFlight = true;
16622
17506
  queueMicrotask(() => {
16623
17507
  this.#drainRebuilds();
16624
17508
  });
@@ -16677,8 +17561,25 @@ var RenderSyncSystem = class {
16677
17561
  }
16678
17562
  } while (this.#takePendingRebuild());
16679
17563
  } finally {
16680
- this.#isRebuildInFlight = false;
17564
+ renderer.isRebuildInFlight = false;
16681
17565
  this.#isRebuildPending = false;
17566
+ this.#runHeldChanges();
17567
+ }
17568
+ }
17569
+ /** Runs the scene changes `RendererImpl.afterRebuild` held back while the rebuild ran. */
17570
+ #runHeldChanges() {
17571
+ const renderer = this.#renderer;
17572
+ const held = renderer.takeHeldChanges();
17573
+ for (let index = 0; index < held.length; index += 1) try {
17574
+ held[index]?.();
17575
+ } catch (error) {
17576
+ renderer.app.onError.emit({
17577
+ error,
17578
+ source: "system",
17579
+ phase: null,
17580
+ entity: null,
17581
+ component: null
17582
+ });
16682
17583
  }
16683
17584
  }
16684
17585
  /**
@@ -16709,7 +17610,8 @@ var RenderSyncSystem = class {
16709
17610
  * The clock is accumulated here rather than read from `app.time.time` because a system keeps running
16710
17611
  * with a non-zero `dt` while the app is paused and has to check `time.paused` itself
16711
17612
  * (`docs/architecture/01-lifecycle-and-time.md` §7); that is what freezes `time` under
16712
- * `app.pause()` and resumes it without a jump.
17613
+ * `app.pause()` and resumes it without a jump. A held clock (`ctx.isClockHeld`, edit mode) freezes
17614
+ * it the same way.
16713
17615
  */
16714
17616
  /**
16715
17617
  * Where the shader uniform writer sits inside `PreRender`: just before the render sync
@@ -16763,7 +17665,7 @@ var ShaderUniformSystem = class {
16763
17665
  */
16764
17666
  update(ctx) {
16765
17667
  const time = ctx.time;
16766
- const isPaused = time.paused;
17668
+ const isPaused = time.paused || ctx.isClockHeld;
16767
17669
  if (!isPaused) {
16768
17670
  this.#time += time.deltaTime;
16769
17671
  this.#unscaledTime += time.unscaledDeltaTime;
@@ -17718,14 +18620,37 @@ function noReferences() {
17718
18620
  };
17719
18621
  }
17720
18622
  /**
17721
- * Builds the JSON Schema fragment for one field.
18623
+ * Builds the JSON Schema fragment for one field, at any depth: its encoded form plus an
18624
+ * `x-ignifx-*` keyword for each inspector option it declares. JSON Schema validators ignore
18625
+ * keywords they do not know, and the `x-` prefix keeps these clear of any future standard one.
17722
18626
  *
17723
18627
  * @param field - The field to describe.
17724
- * @returns The fragment describing the field's encoded form.
18628
+ * @returns The fragment.
17725
18629
  *
17726
18630
  * @internal
17727
18631
  */
17728
18632
  function fieldJsonSchema(field) {
18633
+ const fragment = { ...kindJsonSchema(field) };
18634
+ const { step, hidden, readonly, group, transient } = field.options;
18635
+ if (step !== void 0) fragment["x-ignifx-step"] = step;
18636
+ if (hidden !== void 0) fragment["x-ignifx-hidden"] = hidden;
18637
+ if (readonly !== void 0) {
18638
+ fragment["x-ignifx-readonly"] = readonly;
18639
+ if (readonly) fragment["readOnly"] = true;
18640
+ }
18641
+ if (group !== void 0) fragment["x-ignifx-group"] = group;
18642
+ if (transient !== void 0) fragment["x-ignifx-transient"] = transient;
18643
+ return fragment;
18644
+ }
18645
+ /**
18646
+ * Builds the JSON Schema fragment for one field's encoded form.
18647
+ *
18648
+ * @param field - The field to describe.
18649
+ * @returns The fragment describing the field's encoded form.
18650
+ *
18651
+ * @internal
18652
+ */
18653
+ function kindJsonSchema(field) {
17729
18654
  const { spec } = field;
17730
18655
  switch (spec.kind) {
17731
18656
  case "f32":
@@ -17766,16 +18691,25 @@ function fieldJsonSchema(field) {
17766
18691
  enum: [...spec.values]
17767
18692
  };
17768
18693
  case "entityRef": return taggedReferenceSchema("$entity");
17769
- case "componentRef": return taggedReferenceSchema("$component");
17770
- case "asset": return { oneOf: [{
17771
- type: "object",
17772
- properties: {
17773
- $asset: { type: "string" },
17774
- type: { type: "string" }
17775
- },
17776
- required: ["$asset"],
17777
- additionalProperties: false
17778
- }, { type: "null" }] };
18694
+ case "componentRef": {
18695
+ const typeId = spec.componentType.typeId;
18696
+ return {
18697
+ ...taggedReferenceSchema("$component"),
18698
+ ...typeId === void 0 ? {} : { "x-ignifx-component-type": typeId }
18699
+ };
18700
+ }
18701
+ case "asset": return {
18702
+ oneOf: [{
18703
+ type: "object",
18704
+ properties: {
18705
+ $asset: { type: "string" },
18706
+ type: { type: "string" }
18707
+ },
18708
+ required: ["$asset"],
18709
+ additionalProperties: false
18710
+ }, { type: "null" }],
18711
+ ...spec.typeName === null ? {} : { "x-ignifx-asset-type": spec.typeName }
18712
+ };
17779
18713
  case "array": return {
17780
18714
  type: "array",
17781
18715
  items: fieldJsonSchema(spec.item)
@@ -17859,14 +18793,18 @@ function schemaJsonSchema(schema) {
17859
18793
  };
17860
18794
  }
17861
18795
  /**
17862
- * Describes a component schema in the shape the documentation harness consumes. A package exports
17863
- * a record of these keyed by `typeId`; `pnpm docs:schemas` reads it from the built entry point and
17864
- * regenerates the format pages and `ignifx.schemas.json` from it
17865
- * (`scripts/README.md`, `docs/architecture/16-docs-harness-and-skill.md` §3).
18796
+ * Describes a component schema in the shape the documentation harness and an external inspector
18797
+ * consume. A package exports a record of these keyed by `typeId`; `pnpm docs:schemas` reads it from
18798
+ * the built entry point and regenerates the format pages and `ignifx.schemas.json` from it
18799
+ * (`scripts/README.md`, `docs/architecture/16-docs-harness-and-skill.md` §3). Each field carries
18800
+ * its inspector options and what its kind declares ({@link SchemaFieldDescription}); to describe
18801
+ * an app's registered components with `allowMultiple` and `package` filled in, use
18802
+ * {@link describeRegisteredSchemas}.
17866
18803
  *
17867
18804
  * @param typeId - The component's namespaced registration id, for example `mygame/Mover`.
17868
18805
  * @param schema - The component's declared fields.
17869
- * @param meta - Overrides for the title, format grouping, and summary.
18806
+ * @param meta - Overrides for the title, format grouping, and summary, and the component's
18807
+ * `allowMultiple`, `package` and `builtIn` when the caller knows them.
17870
18808
  * @returns The description entry.
17871
18809
  *
17872
18810
  * @example
@@ -17879,25 +18817,109 @@ function schemaJsonSchema(schema) {
17879
18817
  * @public
17880
18818
  */
17881
18819
  function describeSchema(typeId, schema, meta) {
17882
- const references = noReferences();
17883
- const fields = {};
17884
- for (const [name, field] of Object.entries(schema)) {
17885
- const { tooltip } = field.options;
17886
- fields[name] = {
17887
- kind: field.kind,
17888
- default: encodeValue(field, field.createDefault(), references),
17889
- ...tooltip === void 0 ? {} : { description: tooltip }
17890
- };
17891
- }
17892
18820
  const derivedTitle = typeId.slice(typeId.lastIndexOf("/") + 1);
17893
18821
  return {
17894
18822
  title: meta?.title ?? derivedTitle,
17895
18823
  format: meta?.format ?? "components",
17896
18824
  ...meta?.description === void 0 ? {} : { description: meta.description },
17897
- fields
18825
+ fields: describeFields(schema, noReferences()),
18826
+ ...meta?.allowMultiple === void 0 ? {} : { allowMultiple: meta.allowMultiple },
18827
+ ...meta?.package === void 0 ? {} : { package: meta.package },
18828
+ ...meta?.builtIn === void 0 ? {} : { builtIn: meta.builtIn }
18829
+ };
18830
+ }
18831
+ /**
18832
+ * Describes every field of a schema, in declaration order.
18833
+ *
18834
+ * @param schema - The fields.
18835
+ * @param references - The encoder for the defaults.
18836
+ * @returns The descriptions, keyed by field name.
18837
+ *
18838
+ * @internal
18839
+ */
18840
+ function describeFields(schema, references) {
18841
+ const fields = {};
18842
+ for (const [name, field] of Object.entries(schema)) fields[name] = describeField(field, references);
18843
+ return fields;
18844
+ }
18845
+ /**
18846
+ * Describes one field: its kind, default and tooltip, its inspector options, and what its kind
18847
+ * declares, recursing into nested fields.
18848
+ *
18849
+ * @param field - The field.
18850
+ * @param references - The encoder for the default.
18851
+ * @returns The description.
18852
+ *
18853
+ * @internal
18854
+ */
18855
+ function describeField(field, references) {
18856
+ const { tooltip } = field.options;
18857
+ return {
18858
+ kind: field.kind,
18859
+ default: encodeValue(field, field.createDefault(), references),
18860
+ ...tooltip === void 0 ? {} : { description: tooltip },
18861
+ ...describeOptions(field.options),
18862
+ ...describeKind(field, references)
18863
+ };
18864
+ }
18865
+ /**
18866
+ * Copies the inspector options a field declares.
18867
+ *
18868
+ * @param options - The field's options.
18869
+ * @returns Only the declared options.
18870
+ *
18871
+ * @internal
18872
+ */
18873
+ function describeOptions(options) {
18874
+ const { min, max, step, hidden, readonly, group, transient } = options;
18875
+ return {
18876
+ ...min === void 0 ? {} : { min },
18877
+ ...max === void 0 ? {} : { max },
18878
+ ...step === void 0 ? {} : { step },
18879
+ ...hidden === void 0 ? {} : { hidden },
18880
+ ...readonly === void 0 ? {} : { readonly },
18881
+ ...group === void 0 ? {} : { group },
18882
+ ...transient === void 0 ? {} : { transient }
17898
18883
  };
17899
18884
  }
17900
18885
  /**
18886
+ * Describes what a field's kind declares beyond the kind itself.
18887
+ *
18888
+ * @param field - The field.
18889
+ * @param references - The encoder for nested defaults.
18890
+ * @returns The kind's members; empty for a kind that declares nothing more.
18891
+ *
18892
+ * @internal
18893
+ */
18894
+ function describeKind(field, references) {
18895
+ const { spec } = field;
18896
+ switch (spec.kind) {
18897
+ case "enum": return { values: [...spec.values] };
18898
+ case "asset": return spec.typeName === null ? {} : { assetType: spec.typeName };
18899
+ case "componentRef": return { componentType: spec.componentType.typeId ?? null };
18900
+ case "array": return { item: describeField(spec.item, references) };
18901
+ case "record": return { fields: describeFields(spec.fields, references) };
18902
+ case "map": return { value: describeField(spec.value, references) };
18903
+ case "optional": return { inner: describeField(spec.inner, references) };
18904
+ case "f32":
18905
+ case "f64":
18906
+ case "i32":
18907
+ case "u32":
18908
+ case "bool":
18909
+ case "str":
18910
+ case "vec2":
18911
+ case "vec3":
18912
+ case "vec4":
18913
+ case "quat":
18914
+ case "color":
18915
+ case "entityRef":
18916
+ case "layerMask":
18917
+ case "curve":
18918
+ case "custom": return {};
18919
+ default: return assertNever(spec, "schema field kind");
18920
+ }
18921
+ }
18922
+ /**
17901
18923
  * Generates the JSON Schema (draft 2020-12) for a component's `props` object. The harness and the
17902
18924
  * Vite plugin assemble these into `ignifx.schemas.json`, which drives build-time validation and
17903
18925
  * editor autocompletion (`docs/architecture/06-serialization-and-scene-format.md` §8).
@@ -18761,15 +19783,14 @@ function readSceneFile(parsed, address, validate) {
18761
19783
  return asSceneFile(parsed);
18762
19784
  }
18763
19785
  /**
18764
- * Loads every asset the file references, in a stable order: `settings` first, then each entity's
19786
+ * Lists every asset the file references, in a stable order: `settings` first, then each entity's
18765
19787
  * `instance.scene`, then each component's `props`
18766
19788
  * (`docs/architecture/06-serialization-and-scene-format.md` §4 step 2).
18767
19789
  *
18768
19790
  * @param file - The parsed file.
18769
- * @param ctx - The loader context.
18770
- * @returns The loaded handles, deduplicated by address, in discovery order.
19791
+ * @returns The references, deduplicated by address, in discovery order.
18771
19792
  */
18772
- async function loadDependencies(file, ctx) {
19793
+ function dependencyRequests(file) {
18773
19794
  const requests = [];
18774
19795
  const seen = /* @__PURE__ */ new Set();
18775
19796
  const add = (address, type) => {
@@ -18786,7 +19807,59 @@ async function loadDependencies(file, ctx) {
18786
19807
  const entity = file.entities[index];
18787
19808
  if (entity !== void 0) collectEntityRefs(entity, add);
18788
19809
  }
18789
- return Promise.all(requests.map(async (request) => ctx.loadDependency(request.address, request.type === null ? void 0 : { type: request.type })));
19810
+ return requests;
19811
+ }
19812
+ /**
19813
+ * Loads every asset the file references through the loader context, which retains each one for
19814
+ * the scene asset being loaded.
19815
+ *
19816
+ * @param file - The parsed file.
19817
+ * @param ctx - The loader context.
19818
+ * @returns The loaded handles, deduplicated by address, in discovery order.
19819
+ */
19820
+ async function loadDependencies(file, ctx) {
19821
+ return Promise.all(dependencyRequests(file).map(async (request) => ctx.loadDependency(request.address, request.type === null ? void 0 : { type: request.type })));
19822
+ }
19823
+ /**
19824
+ * Loads every asset a scene file references — in `settings`, in every component's `props`, and in
19825
+ * every `instance.scene`, recursively through the scenes those pull in — the walk the scene loader
19826
+ * runs before it builds anything (`docs/architecture/06-serialization-and-scene-format.md` §4
19827
+ * step 2).
19828
+ *
19829
+ * @remarks
19830
+ * It is the half of the scene loader a file that is already in memory needs: pass the result to
19831
+ * `createSceneAsset` and the asset can be built synchronously with `instantiateScene`. Each handle
19832
+ * is returned with one holder, which the caller owns: release them all when the scene they serve
19833
+ * is gone. `world.loadSceneFile` does that for a whole scene.
19834
+ *
19835
+ * @param assets - The asset service to load through, normally `app.assets`.
19836
+ * @param file - The scene file.
19837
+ * @param options - Cancellation.
19838
+ * @returns The loaded handles, deduplicated by address, in the loader's order.
19839
+ * @throws Whatever the asset service rejects a load with (an `AssetLoadError`); every handle
19840
+ * loaded by then is released first.
19841
+ *
19842
+ * @example
19843
+ * ```ts
19844
+ * const dependencies = await loadSceneDependencies(app.assets, file);
19845
+ * const asset = await createSceneAsset("memory:scene/draft", file, dependencies);
19846
+ * ```
19847
+ *
19848
+ * @public
19849
+ */
19850
+ async function loadSceneDependencies(assets, file, options) {
19851
+ const signal = options?.signal;
19852
+ const handles = dependencyRequests(file).map((request) => assets.load(request.address, {
19853
+ ...request.type === null ? {} : { type: request.type },
19854
+ ...signal === void 0 ? {} : { signal }
19855
+ }));
19856
+ try {
19857
+ await Promise.all(handles.map(async (handle) => handle.promise));
19858
+ } catch (error) {
19859
+ for (let index = 0; index < handles.length; index += 1) handles[index]?.release();
19860
+ throw error;
19861
+ }
19862
+ return handles;
18790
19863
  }
18791
19864
  /**
18792
19865
  * Collects the asset references of one entity: its `instance.scene` first, so a nested scene is
@@ -21544,17 +22617,11 @@ function registerRendering(ctx) {
21544
22617
  if (value instanceof StorageBufferAsset) value.dispose();
21545
22618
  }
21546
22619
  });
21547
- ctx.registerAssetLoader({
21548
- type: MESH_ASSET_TYPE,
21549
- extensions: [],
21550
- load: () => Promise.reject(noMeshFileFormat()),
21551
- unload: (value) => {
21552
- if (value instanceof MeshAsset) value.dispose();
21553
- }
21554
- });
22620
+ ctx.registerAssetLoader(createMeshLoader());
21555
22621
  ctx.registerSystem(new ShaderUniformSystem(ctx.app), {
21556
22622
  phase: Phase.PreRender,
21557
- order: SHADER_UNIFORM_ORDER
22623
+ order: SHADER_UNIFORM_ORDER,
22624
+ editMode: "hold"
21558
22625
  });
21559
22626
  const sync = new RenderSyncSystem(renderer);
21560
22627
  renderer.attachSyncSystem(sync);
@@ -21567,18 +22634,6 @@ function registerRendering(ctx) {
21567
22634
  });
21568
22635
  }
21569
22636
  /**
21570
- * Builds the failure a `mesh` **address** produces: there is no mesh file format, because geometry
21571
- * arrives either as a primitive built in code or inside a `ModelAsset`.
21572
- *
21573
- * @returns The error to reject with.
21574
- */
21575
- function noMeshFileFormat() {
21576
- return new IgnifxError(CoreErrorCode.assetNoLoader, "There is no mesh file format; build one in code.", {
21577
- context: { type: MESH_ASSET_TYPE },
21578
- hint: "Use MeshAsset.box/sphere/plane/ground/... for primitives, or load a .glb as a model."
21579
- });
21580
- }
21581
- /**
21582
22637
  * Builds the failure a `storagebuffer` **address** produces: there is no storage buffer file
21583
22638
  * format, because the bytes are always written by the game.
21584
22639
  *
@@ -21773,7 +22828,7 @@ var ExtensionContextImpl = class {
21773
22828
  * @param options - An explicit `typeId`, when the class does not declare one.
21774
22829
  */
21775
22830
  registerComponent(type, options) {
21776
- this.#registry.register(type, options?.typeId);
22831
+ this.#registry.register(type, options?.typeId, this.#extension.name);
21777
22832
  }
21778
22833
  /**
21779
22834
  * Registers several component classes.
@@ -21781,7 +22836,7 @@ var ExtensionContextImpl = class {
21781
22836
  * @param types - The component classes.
21782
22837
  */
21783
22838
  registerComponents(types) {
21784
- this.#registry.registerAll(types);
22839
+ this.#registry.registerAll(types, this.#extension.name);
21785
22840
  }
21786
22841
  /**
21787
22842
  * Registers a system in a phase.
@@ -22783,6 +23838,17 @@ function readStatics(type) {
22783
23838
  return type;
22784
23839
  }
22785
23840
  /**
23841
+ * Whether a replacement class declares `static runInEditMode = true`.
23842
+ *
23843
+ * @param type - The component class.
23844
+ * @returns `true` only when the class declares it.
23845
+ *
23846
+ * @internal
23847
+ */
23848
+ function declaresRunInEditMode(type) {
23849
+ return readStatics(type).runInEditMode === true;
23850
+ }
23851
+ /**
22786
23852
  * The policy a class declares, defaulting to `"patch"`.
22787
23853
  *
22788
23854
  * @param type - The component class.
@@ -22991,6 +24057,8 @@ var HotReloadHostImpl = class {
22991
24057
  policy = "recreate";
22992
24058
  this.#log.warn(`${CoreErrorCode.hotReloadSchemaChanged} ${typeId} changed its schema shape under the "patch" policy; its instances were re-created. Declare static hotReload = "recreate" to say so.`);
22993
24059
  }
24060
+ const wasRunInEditMode = previousInfo.script?.runInEditMode ?? false;
24061
+ if (policy === "patch" && this.#app.isEditMode && wasRunInEditMode !== declaresRunInEditMode(next)) policy = "recreate";
22994
24062
  return {
22995
24063
  typeId,
22996
24064
  previous: current,
@@ -24490,6 +25558,9 @@ function updatesWhilePaused(script) {
24490
25558
  * not run" while paused, and a physics system that kept stepping with no `fixedUpdate` in front
24491
25559
  * of it would be worse than either reading alone. Systems of every other phase keep running:
24492
25560
  * rendering, audio, and UI must still work on a pause screen.
25561
+ * - **Edit mode costs a game one comparison per system.** An entry's edit-mode behaviour is
25562
+ * resolved at registration, so in an app that is not in edit mode every entry is `"run"` and the
25563
+ * frame takes the same path it always did (ADR-0028).
24493
25564
  * - **`FrameSample.destroyed` counts entities.** The destroy flush reports no total, and the only
24494
25565
  * world-level signal for a release is `onEntityDestroyed`; a component destroyed on a surviving
24495
25566
  * entity is therefore not counted yet.
@@ -24512,17 +25583,21 @@ var SystemEntry = class {
24512
25583
  order;
24513
25584
  /** Registration serial, the tie-breaker. */
24514
25585
  serial;
25586
+ /** What the system does this app's frames: always `"run"` outside edit mode. */
25587
+ editMode;
24515
25588
  /**
24516
25589
  * Creates an entry.
24517
25590
  *
24518
25591
  * @param system - The system.
24519
25592
  * @param order - Its order within the phase.
24520
25593
  * @param serial - Its registration serial.
25594
+ * @param editMode - What it does in this app's frames.
24521
25595
  */
24522
- constructor(system, order, serial) {
25596
+ constructor(system, order, serial, editMode) {
24523
25597
  this.system = system;
24524
25598
  this.order = order;
24525
25599
  this.serial = serial;
25600
+ this.editMode = editMode;
24526
25601
  }
24527
25602
  };
24528
25603
  /**
@@ -24539,6 +25614,8 @@ var SystemContextImpl = class {
24539
25614
  phase = Phase.EndOfFrame;
24540
25615
  /** Seconds elapsed. */
24541
25616
  dt = 0;
25617
+ /** Whether the running system's clock is held. */
25618
+ isClockHeld = false;
24542
25619
  /**
24543
25620
  * Creates the shared context.
24544
25621
  *
@@ -24563,6 +25640,7 @@ var Scheduler = class {
24563
25640
  #deferred;
24564
25641
  #clock;
24565
25642
  #development;
25643
+ #isEditMode;
24566
25644
  #report;
24567
25645
  /** One system list per phase, kept sorted by `(order, registration serial)`. */
24568
25646
  #systems = [];
@@ -24620,6 +25698,7 @@ var Scheduler = class {
24620
25698
  this.#deferred = options.deferred;
24621
25699
  this.#clock = options.clock;
24622
25700
  this.#development = options.development;
25701
+ this.#isEditMode = options.editMode;
24623
25702
  this.#report = (error, system, phase) => {
24624
25703
  options.report(error, system, phase);
24625
25704
  };
@@ -24648,14 +25727,16 @@ var Scheduler = class {
24648
25727
  * Registers a system in a phase (`docs/architecture/03-scripting-and-components.md` §6).
24649
25728
  *
24650
25729
  * @param system - The system.
24651
- * @param options - The phase and the ascending order within it; `order` defaults to `0`.
25730
+ * @param options - The phase, the ascending order within it (`order` defaults to `0`), and what
25731
+ * it does in edit mode (`editMode` defaults to `"run"`).
24652
25732
  */
24653
25733
  registerSystem(system, options) {
24654
25734
  const phase = options.phase;
24655
25735
  const list = this.#systems[phase];
24656
25736
  if (list === void 0) return;
24657
25737
  this.#serial += 1;
24658
- const entry = new SystemEntry(system, options.order ?? 0, this.#serial);
25738
+ const editMode = this.#isEditMode ? options.editMode ?? "run" : "run";
25739
+ const entry = new SystemEntry(system, options.order ?? 0, this.#serial, editMode);
24659
25740
  let index = list.length;
24660
25741
  while (index > 0) {
24661
25742
  const previous = list[index - 1];
@@ -24747,7 +25828,7 @@ var Scheduler = class {
24747
25828
  const start = this.#now();
24748
25829
  this.#phase = Phase.FixedUpdate;
24749
25830
  this.#internals?.setPhase(Phase.FixedUpdate);
24750
- if (!time.paused) {
25831
+ if (!time.paused && !this.#isEditMode) {
24751
25832
  this.#accumulator = snap(this.#accumulator + time.deltaTime, time.fixedDeltaTime);
24752
25833
  const step = time.fixedDeltaTime;
24753
25834
  this.#stepDt = step;
@@ -24816,18 +25897,35 @@ var Scheduler = class {
24816
25897
  this.#phase = phase;
24817
25898
  this.#internals?.setPhase(phase);
24818
25899
  for (let index = from; index < end; index += 1) {
24819
- const system = list[index]?.system;
24820
- if (system === void 0) continue;
24821
- try {
24822
- system.update?.(context);
24823
- } catch (error) {
24824
- this.#report(error, system, phase);
25900
+ const entry = list[index];
25901
+ if (entry === void 0) continue;
25902
+ if (entry.editMode === "run") this.#runSystem(entry.system, context, phase);
25903
+ else if (entry.editMode === "hold") {
25904
+ context.dt = 0;
25905
+ context.isClockHeld = true;
25906
+ this.#runSystem(entry.system, context, phase);
25907
+ context.dt = dt;
25908
+ context.isClockHeld = false;
24825
25909
  }
24826
25910
  }
24827
25911
  this.#internals?.setPhase(previousPhase);
24828
25912
  this.#phase = previousPhase;
24829
25913
  }
24830
25914
  /**
25915
+ * Runs one system, guarded.
25916
+ *
25917
+ * @param system - The system.
25918
+ * @param context - The shared context, already set for this phase.
25919
+ * @param phase - The phase, for the error report.
25920
+ */
25921
+ #runSystem(system, context, phase) {
25922
+ try {
25923
+ system.update?.(context);
25924
+ } catch (error) {
25925
+ this.#report(error, system, phase);
25926
+ }
25927
+ }
25928
+ /**
24831
25929
  * Walks one callback's sorted dispatch list.
24832
25930
  *
24833
25931
  * @param kind - Which callback.
@@ -25227,10 +26325,19 @@ var SettingsStore = class {
25227
26325
  this.#sections.set(name, {
25228
26326
  schema,
25229
26327
  owner,
26328
+ defaults: base,
25230
26329
  value: Object.freeze(value)
25231
26330
  });
25232
26331
  }
25233
26332
  /**
26333
+ * Every registered section, in registration order, for `describeSettings`.
26334
+ *
26335
+ * @returns The sections, keyed by name.
26336
+ */
26337
+ registrations() {
26338
+ return this.#sections;
26339
+ }
26340
+ /**
25234
26341
  * Reports whether a section has been registered.
25235
26342
  *
25236
26343
  * @param name - The section name.
@@ -27479,6 +28586,11 @@ var Entity = class {
27479
28586
  * The immovability hint: `true` promises that the transform will not change after `awake`, which
27480
28587
  * lets the 2D batcher, physics, and navmesh treat the entity as static.
27481
28588
  *
28589
+ * @remarks
28590
+ * It can be changed only in files or before `awake`; afterwards the setter throws `IGX-0101`. In an
28591
+ * edit-mode app it stays writable, because an editor's inspector edits it on loaded entities
28592
+ * (ADR-0028).
28593
+ *
27482
28594
  * @returns `true` when the entity is marked static.
27483
28595
  */
27484
28596
  get isStatic() {
@@ -27486,7 +28598,7 @@ var Entity = class {
27486
28598
  }
27487
28599
  set isStatic(value) {
27488
28600
  const internals = this.#mutable("isStatic");
27489
- if (internals.hasAwoken) throw new IgnifxError(CoreErrorCode.mutationAfterDestroy, "isStatic is set in files or before awake, and cannot change afterwards.", { context: {
28601
+ if (internals.hasAwoken && !internals.host.app.isEditMode) throw new IgnifxError(CoreErrorCode.mutationAfterDestroy, "isStatic is set in files or before awake, and cannot change afterwards.", { context: {
27490
28602
  entity: internals.uid,
27491
28603
  operation: "isStatic"
27492
28604
  } });
@@ -27663,6 +28775,36 @@ var Entity = class {
27663
28775
  internals.onParentChanged?.emit(parent);
27664
28776
  }
27665
28777
  /**
28778
+ * Moves the entity among its siblings: its parent's children, or its scene's roots when it has no
28779
+ * parent. Sibling order is the order a scene file lists entities in and the order `children`
28780
+ * reports.
28781
+ *
28782
+ * @param index - The entity's new index among its siblings. A value past either end is clamped
28783
+ * to that end, and a fraction is truncated.
28784
+ * @throws IgnifxError with code `IGX-0101` when the entity has been destroyed.
28785
+ *
28786
+ * @example
28787
+ * ```ts
28788
+ * weapon.setSiblingIndex(0); // first child of its parent
28789
+ * ```
28790
+ */
28791
+ setSiblingIndex(index) {
28792
+ const internals = this.#mutable("setSiblingIndex");
28793
+ const parent = internals.parent;
28794
+ const siblings = parent === null ? internals.scene.roots : entityInternals(parent).children;
28795
+ const at = Math.min(Math.max(Math.trunc(Number.isNaN(index) ? 0 : index), 0), siblings.length - 1);
28796
+ if (parent === null) {
28797
+ internals.scene.moveRoot(this, at);
28798
+ return;
28799
+ }
28800
+ const children = entityInternals(parent).children;
28801
+ const from = children.indexOf(this);
28802
+ if (from >= 0 && from !== at) {
28803
+ children.splice(from, 1);
28804
+ children.splice(at, 0, this);
28805
+ }
28806
+ }
28807
+ /**
27666
28808
  * Resolves a path relative to this entity — `"Body/Arm.L"`, `"../Sibling"`, `"/Root/Child"`.
27667
28809
  *
27668
28810
  * @remarks
@@ -28649,6 +29791,8 @@ function compare(item, order, serial) {
28649
29791
  * `awake` waits until the component is effectively enabled. Outside callbacks, enables are queued
28650
29792
  * and disables are immediate; nested changes run synchronously.
28651
29793
  * Destroy children before parents and release each entity's components in attachment order.
29794
+ * In edit mode the one call site is also the gate: a script whose class does not run in edit mode
29795
+ * gets no callback at all, from any path (ADR-0028).
28652
29796
  */
28653
29797
  /** How many callbacks get a sorted dispatch list. */
28654
29798
  const DISPATCH_LIST_COUNT = 15 - FIRST_DISPATCHED_CALLBACK;
@@ -28670,6 +29814,8 @@ var LifecycleQueue = class {
28670
29814
  #doomedComponents = [];
28671
29815
  /** The phase the scheduler says is running, recorded in error reports. */
28672
29816
  #phase = null;
29817
+ /** Whether the app is in edit mode, read once: it is fixed for the app's life. */
29818
+ #isEditMode;
28673
29819
  /**
28674
29820
  * Creates the queue.
28675
29821
  *
@@ -28677,6 +29823,7 @@ var LifecycleQueue = class {
28677
29823
  */
28678
29824
  constructor(host) {
28679
29825
  this.#host = host;
29826
+ this.#isEditMode = host.app.isEditMode;
28680
29827
  for (let index = 0; index < DISPATCH_LIST_COUNT; index += 1) this.#lists.push(new ScriptList());
28681
29828
  }
28682
29829
  /**
@@ -28815,6 +29962,7 @@ var LifecycleQueue = class {
28815
29962
  const state = componentInternals(component);
28816
29963
  const info = state.info;
28817
29964
  if (info === null || !implementsCallback(info.script, kind)) return;
29965
+ if (this.#isEditMode && info.script?.runInEditMode !== true) return;
28818
29966
  const name = SCRIPT_CALLBACK_NAMES[kind];
28819
29967
  if (name === void 0) return;
28820
29968
  const callback = readCallback(component, name);
@@ -28989,7 +30137,7 @@ var LifecycleQueue = class {
28989
30137
  * @param info - Its class's callback mask and ordering, or `null` when it has none.
28990
30138
  */
28991
30139
  #addToDispatch(script, info) {
28992
- if (info === null) return;
30140
+ if (info === null || this.#isEditMode && !info.runInEditMode) return;
28993
30141
  for (let kind = FIRST_DISPATCHED_CALLBACK; kind < 15; kind += 1) if ((info.callbacks & 1 << kind) !== 0) this.#lists[kind - FIRST_DISPATCHED_CALLBACK]?.insert(script, info);
28994
30142
  }
28995
30143
  /**
@@ -28999,7 +30147,7 @@ var LifecycleQueue = class {
28999
30147
  * @param info - Its class's callback mask, or `null` when it has none.
29000
30148
  */
29001
30149
  #removeFromDispatch(script, info) {
29002
- if (info === null) return;
30150
+ if (info === null || this.#isEditMode && !info.runInEditMode) return;
29003
30151
  for (let kind = FIRST_DISPATCHED_CALLBACK; kind < 15; kind += 1) if ((info.callbacks & 1 << kind) !== 0) this.#lists[kind - FIRST_DISPATCHED_CALLBACK]?.remove(script);
29004
30152
  }
29005
30153
  /**
@@ -29222,7 +30370,7 @@ let scratch = null;
29222
30370
  * @param world - The world being picked in, for the handle tables.
29223
30371
  * @param scene - The Lite render scene.
29224
30372
  * @param ray - The ray to cast.
29225
- * @param options - An entity filter.
30373
+ * @param options - An entity filter, and what to look through.
29226
30374
  * @returns What was hit, or `null` for a miss.
29227
30375
  *
29228
30376
  * @internal
@@ -29231,8 +30379,11 @@ function raycastRenderScene(world, scene, ray, options) {
29231
30379
  const renderer = rendererInternals(world.app.renderer);
29232
30380
  const pickRay = scratch ??= createPickRay();
29233
30381
  setPickRay(pickRay, ray.origin.x, ray.origin.y, ray.origin.z, ray.direction.x, ray.direction.y, ray.direction.z, ray.length);
29234
- const filter = options?.filter;
29235
- const info = filter === void 0 ? raycastScene(scene, pickRay) : raycastSceneWhere(scene, pickRay, (tag) => acceptsEntityTag(world, tag, filter));
30382
+ const plan = renderer.planPick(options);
30383
+ const accept = plan.accept;
30384
+ const hits = plan.hits;
30385
+ if (accept === null && hits.length === 0) return renderer.resolvePick(raycastScene(scene, pickRay));
30386
+ const info = raycastSceneWhere(scene, pickRay, (tag, mesh) => (accept === null || accept(tag, mesh)) && !hits.some((hit) => hit.mesh === mesh));
29236
30387
  return renderer.resolvePick(info);
29237
30388
  }
29238
30389
  //#endregion
@@ -29397,6 +30548,21 @@ var SceneInstance = class {
29397
30548
  if (!this.#roots.includes(entity)) this.#roots.push(entity);
29398
30549
  }
29399
30550
  /**
30551
+ * Moves a root to another place in the root list.
30552
+ *
30553
+ * @param entity - A root of this instance.
30554
+ * @param index - Its new index, already clamped to the list.
30555
+ *
30556
+ * @internal
30557
+ */
30558
+ moveRoot(entity, index) {
30559
+ const from = this.#roots.indexOf(entity);
30560
+ if (from >= 0) {
30561
+ this.#roots.splice(from, 1);
30562
+ this.#roots.splice(index, 0, entity);
30563
+ }
30564
+ }
30565
+ /**
29400
30566
  * Removes an entity from the root list.
29401
30567
  *
29402
30568
  * @param entity - The entity that gained a parent or was destroyed.
@@ -29837,9 +31003,11 @@ function invalidPath(path, reason) {
29837
31003
  function expandScene(asset, options) {
29838
31004
  const entities = [];
29839
31005
  const instances = [];
31006
+ const merged = /* @__PURE__ */ new Map();
29840
31007
  const state = {
29841
31008
  entities,
29842
31009
  instances,
31010
+ merged,
29843
31011
  options,
29844
31012
  counter: 0
29845
31013
  };
@@ -29850,18 +31018,21 @@ function expandScene(asset, options) {
29850
31018
  address: asset.address,
29851
31019
  asset: null,
29852
31020
  scene: asset,
29853
- rootUid: null
31021
+ rootUid: null,
31022
+ root: null
29854
31023
  });
29855
- expandFile(asset, null, key, true, [asset.address], state);
31024
+ expandFile(asset, null, key, true, [asset.address], state, null);
29856
31025
  return {
29857
31026
  entities,
29858
- instances
31027
+ instances,
31028
+ merged
29859
31029
  };
29860
31030
  }
29861
- expandFile(asset, null, null, false, [asset.address], state);
31031
+ expandFile(asset, null, null, false, [asset.address], state, null);
29862
31032
  return {
29863
31033
  entities,
29864
- instances
31034
+ instances,
31035
+ merged
29865
31036
  };
29866
31037
  }
29867
31038
  /**
@@ -29873,16 +31044,17 @@ function expandScene(asset, options) {
29873
31044
  * @param freshUids - `true` mints a new uid per entity and component; `false` keeps the file's own.
29874
31045
  * @param chain - The addresses of the scenes currently being expanded, for the cycle check.
29875
31046
  * @param state - The accumulating output.
31047
+ * @param merge - Where the file's single root merges, or `null` to create every entity.
29876
31048
  * @returns The override targets produced, keyed by the uid each entity carries in `asset`'s own
29877
31049
  * file.
29878
31050
  */
29879
- function expandFile(asset, parentUid, instanceKey, freshUids, chain, state) {
31051
+ function expandFile(asset, parentUid, instanceKey, freshUids, chain, state, merge) {
29880
31052
  const source = asset.file.entities;
29881
31053
  const keys = /* @__PURE__ */ new Map();
29882
31054
  if (freshUids) for (let index = 0; index < source.length; index += 1) {
29883
31055
  const entity = source[index];
29884
31056
  if (entity === void 0) continue;
29885
- keys.set(entity.uid, state.options.nextUid());
31057
+ keys.set(entity.uid, merge !== null && entity.parent === null ? merge.into.uid : state.options.nextUid());
29886
31058
  const components = entity.components ?? [];
29887
31059
  for (let inner = 0; inner < components.length; inner += 1) {
29888
31060
  const component = components[inner];
@@ -29893,6 +31065,11 @@ function expandFile(asset, parentUid, instanceKey, freshUids, chain, state) {
29893
31065
  for (let index = 0; index < source.length; index += 1) {
29894
31066
  const entity = source[index];
29895
31067
  if (entity === void 0) continue;
31068
+ if (merge !== null && entity.parent === null) {
31069
+ produced.set(entity.uid, mergeRoot(entity, merge, keys, state));
31070
+ if (entity.instance !== void 0) expandInstance(asset, entity.instance, merge.into, chain, state);
31071
+ continue;
31072
+ }
29896
31073
  const uid = keys.get(entity.uid) ?? entity.uid;
29897
31074
  const componentSourceUids = /* @__PURE__ */ new Map();
29898
31075
  const data = {
@@ -29921,20 +31098,52 @@ function expandFile(asset, parentUid, instanceKey, freshUids, chain, state) {
29921
31098
  componentSourceUids
29922
31099
  });
29923
31100
  const nested = entity.instance;
29924
- if (nested !== void 0) expandInstance(asset, nested, uid, chain, state);
31101
+ if (nested !== void 0) expandInstance(asset, nested, data, chain, state);
29925
31102
  }
29926
31103
  return produced;
29927
31104
  }
29928
31105
  /**
29929
- * Expands one `instance` entry under the entity that carries it.
31106
+ * Merges an instanced scene's single root into the entity carrying the `instance` entry: the
31107
+ * root's components come first, then the carrier's own. The carrier keeps its own uid, name,
31108
+ * transform, and other entity fields, as `world.instantiate` keeps the placement it is given.
31109
+ *
31110
+ * @param entity - The instanced root's record.
31111
+ * @param merge - The carrier and the component uid table to fill.
31112
+ * @param keys - Source uid to expanded uid for the instanced file.
31113
+ * @param state - The accumulating output.
31114
+ * @returns The override target for the root, which is the carrier.
31115
+ */
31116
+ function mergeRoot(entity, merge, keys, state) {
31117
+ const into = merge.into;
31118
+ const components = cloneComponents(entity, keys, merge.componentSourceUids);
31119
+ into.components = [...components, ...into.components];
31120
+ let merged = state.merged.get(into.uid);
31121
+ if (merged === void 0) {
31122
+ merged = /* @__PURE__ */ new Set();
31123
+ state.merged.set(into.uid, merged);
31124
+ }
31125
+ for (let index = 0; index < components.length; index += 1) {
31126
+ const component = components[index];
31127
+ if (component !== void 0) merged.add(component.uid);
31128
+ }
31129
+ return {
31130
+ data: into,
31131
+ components: reverse(merge.componentSourceUids)
31132
+ };
31133
+ }
31134
+ /**
31135
+ * Expands one `instance` entry on the entity that carries it. A scene with exactly one root merges
31136
+ * that root into the carrier, as `world.instantiate` answers with that root; any other scene's
31137
+ * roots become the carrier's children.
29930
31138
  *
29931
31139
  * @param asset - The scene the entry was declared in, whose dependencies resolve the reference.
29932
31140
  * @param instance - The entry.
29933
- * @param rootUid - The expanded uid of the entity carrying it.
31141
+ * @param carrier - The expanded record of the entity carrying it.
29934
31142
  * @param chain - The addresses currently being expanded.
29935
31143
  * @param state - The accumulating output.
29936
31144
  */
29937
- function expandInstance(asset, instance, rootUid, chain, state) {
31145
+ function expandInstance(asset, instance, carrier, chain, state) {
31146
+ const rootUid = carrier.uid;
29938
31147
  const address = instance.scene.$asset;
29939
31148
  if (chain.includes(address)) throw new IgnifxError(CoreErrorCode.sceneInstanceCycle, `Instantiating ${address} would nest the scene inside itself.`, {
29940
31149
  context: {
@@ -29952,14 +31161,28 @@ function expandInstance(asset, instance, rootUid, chain, state) {
29952
31161
  const recorded = instance.hash;
29953
31162
  if (recorded !== void 0 && recorded !== resolved.value.hash) reportHashMismatch(address, recorded, resolved.value.hash, state.options);
29954
31163
  const key = nextInstanceKey(state);
31164
+ const single = singleRoot(resolved.value);
31165
+ let merge = null;
31166
+ let root = null;
31167
+ if (single !== null) {
31168
+ merge = {
31169
+ into: carrier,
31170
+ componentSourceUids: /* @__PURE__ */ new Map()
31171
+ };
31172
+ root = {
31173
+ sourceUid: single.uid,
31174
+ componentSourceUids: merge.componentSourceUids
31175
+ };
31176
+ }
29955
31177
  state.instances.push({
29956
31178
  key,
29957
31179
  address,
29958
31180
  asset: resolved.handle,
29959
31181
  scene: resolved.value,
29960
- rootUid
31182
+ rootUid,
31183
+ root
29961
31184
  });
29962
- const produced = expandFile(resolved.value, rootUid, key, true, [...chain, address], state);
31185
+ const produced = expandFile(resolved.value, rootUid, key, true, [...chain, address], state, merge);
29963
31186
  const overrides = instance.overrides;
29964
31187
  if (overrides !== void 0 && overrides.length > 0) applyOverrides(overrides, produced, (message) => {
29965
31188
  state.options.report(CoreErrorCode.instanceHashMismatch, `${asset.address}: ${message}`);
@@ -29986,6 +31209,25 @@ function reportHashMismatch(address, recorded, actual, options) {
29986
31209
  options.report(CoreErrorCode.instanceHashMismatch, message);
29987
31210
  }
29988
31211
  /**
31212
+ * The record of a scene's only root.
31213
+ *
31214
+ * @param asset - The scene.
31215
+ * @returns The root's record, or `null` when the scene declares no root or several.
31216
+ *
31217
+ * @internal
31218
+ */
31219
+ function singleRoot(asset) {
31220
+ let found = null;
31221
+ const entities = asset.file.entities;
31222
+ for (let index = 0; index < entities.length; index += 1) {
31223
+ const entity = entities[index];
31224
+ if (entity === void 0 || entity.parent !== null) continue;
31225
+ if (found !== null) return null;
31226
+ found = entity;
31227
+ }
31228
+ return found;
31229
+ }
31230
+ /**
29989
31231
  * Mints the next instance key.
29990
31232
  *
29991
31233
  * @param state - The expansion state.
@@ -30278,6 +31520,7 @@ function instantiateScene(world, asset, options) {
30278
31520
  remap: new UidRemap(),
30279
31521
  report,
30280
31522
  instances: indexInstances(expanded.instances),
31523
+ merged: expanded.merged,
30281
31524
  roots: [],
30282
31525
  built: []
30283
31526
  };
@@ -30380,16 +31623,17 @@ function attachComponents(context) {
30380
31623
  * @param rootEntity - The entity that stands for the outermost instance, when the caller made one.
30381
31624
  */
30382
31625
  function linkInstances(context, handle, rootEntity) {
30383
- const rootOfInstance = /* @__PURE__ */ new Map();
31626
+ const firstMember = /* @__PURE__ */ new Map();
30384
31627
  for (let index = 0; index < context.built.length; index += 1) {
30385
31628
  const built = context.built[index];
30386
31629
  const key = built?.source.instanceKey ?? null;
30387
- if (built === void 0 || key === null || rootOfInstance.has(key)) continue;
30388
- const instance = context.instances.get(key);
30389
- if (instance === void 0) continue;
31630
+ if (built !== void 0 && key !== null && !firstMember.has(key)) firstMember.set(key, built.entity);
31631
+ }
31632
+ const rootOfInstance = /* @__PURE__ */ new Map();
31633
+ for (const instance of context.instances.values()) {
30390
31634
  const declared = instance.rootUid;
30391
- const resolved = declared === null ? rootEntity ?? built.entity : context.remap.entity(declared);
30392
- rootOfInstance.set(key, resolved ?? built.entity);
31635
+ const resolved = declared === null ? rootEntity ?? firstMember.get(instance.key) ?? null : context.remap.entity(declared);
31636
+ if (resolved !== null) rootOfInstance.set(instance.key, resolved);
30393
31637
  }
30394
31638
  const insideOf = /* @__PURE__ */ new Map();
30395
31639
  for (let index = 0; index < context.built.length; index += 1) {
@@ -30400,7 +31644,7 @@ function linkInstances(context, handle, rootEntity) {
30400
31644
  if (root !== void 0 && root !== built.entity) insideOf.set(built.entity, root);
30401
31645
  }
30402
31646
  if (rootEntity !== null) {
30403
- const own = ownedInstance(context, rootEntity, rootOfInstance, handle);
31647
+ const own = ownedInstance(context, rootEntity, null, rootOfInstance, handle);
30404
31648
  if (own !== null) entityInternals(rootEntity).origin = {
30405
31649
  sourceUid: "",
30406
31650
  instanceRoot: null,
@@ -30411,7 +31655,7 @@ function linkInstances(context, handle, rootEntity) {
30411
31655
  for (let index = 0; index < context.built.length; index += 1) {
30412
31656
  const built = context.built[index];
30413
31657
  if (built === void 0) continue;
30414
- const own = ownedInstance(context, built.entity, rootOfInstance, handle);
31658
+ const own = ownedInstance(context, built.entity, built.source, rootOfInstance, handle);
30415
31659
  const inside = insideOf.get(built.entity) ?? null;
30416
31660
  if (own === null && inside === null) continue;
30417
31661
  const origin = {
@@ -30428,11 +31672,12 @@ function linkInstances(context, handle, rootEntity) {
30428
31672
  *
30429
31673
  * @param context - The build state.
30430
31674
  * @param entity - The candidate root.
31675
+ * @param source - The expanded record that produced it, or `null` for a caller's container.
30431
31676
  * @param rootOfInstance - Instance key to its root entity.
30432
31677
  * @param handle - The handle the whole file was loaded through, for `asInstance` builds.
30433
31678
  * @returns The link, or `null` when the entity roots no instance.
30434
31679
  */
30435
- function ownedInstance(context, entity, rootOfInstance, handle) {
31680
+ function ownedInstance(context, entity, source, rootOfInstance, handle) {
30436
31681
  for (const [key, root] of rootOfInstance) {
30437
31682
  if (root !== entity) continue;
30438
31683
  const instance = context.instances.get(key);
@@ -30440,12 +31685,37 @@ function ownedInstance(context, entity, rootOfInstance, handle) {
30440
31685
  return {
30441
31686
  address: instance.address,
30442
31687
  asset: instance.rootUid === null ? handle : instance.asset,
30443
- scene: instance.scene
31688
+ scene: instance.scene,
31689
+ root: instancedRoot(context, instance, source)
30444
31690
  };
30445
31691
  }
30446
31692
  return null;
30447
31693
  }
30448
31694
  /**
31695
+ * What an instance root took from its scene's single root, when it stands for that root rather
31696
+ * than for a container (`docs/architecture/06-serialization-and-scene-format.md` §2).
31697
+ *
31698
+ * @param context - The build state.
31699
+ * @param instance - The instance the entity roots.
31700
+ * @param source - The expanded record that produced the entity, or `null` for a caller's container.
31701
+ * @returns The root's record uid and the components it brought, or `null` for a container.
31702
+ */
31703
+ function instancedRoot(context, instance, source) {
31704
+ if (source === null) return null;
31705
+ const merged = context.merged.get(source.data.uid) ?? /* @__PURE__ */ new Set();
31706
+ if (instance.root !== null) return {
31707
+ sourceUid: instance.root.sourceUid,
31708
+ componentSourceUids: instance.root.componentSourceUids,
31709
+ components: merged
31710
+ };
31711
+ if (instance.rootUid !== null || singleRoot(instance.scene)?.uid !== source.sourceUid) return null;
31712
+ return {
31713
+ sourceUid: source.sourceUid,
31714
+ componentSourceUids: source.componentSourceUids,
31715
+ components: /* @__PURE__ */ new Set([...source.componentSourceUids.keys(), ...merged])
31716
+ };
31717
+ }
31718
+ /**
30449
31719
  * Pass 4: decodes every component's props, resolving `entityRef`/`componentRef` through the now
30450
31720
  * complete uid table (`docs/architecture/06-serialization-and-scene-format.md` §4 step 5).
30451
31721
  *
@@ -30573,6 +31843,90 @@ function sceneAssetResolver(world, asset) {
30573
31843
  return cached !== null && cached.state === "loaded" ? cached : null;
30574
31844
  };
30575
31845
  }
31846
+ /** A decoder that resolves nothing, for a record built without one. */
31847
+ const NO_REFERENCES = Object.freeze({
31848
+ entity: () => null,
31849
+ component: () => null,
31850
+ asset: () => null
31851
+ });
31852
+ /**
31853
+ * Attaches one component to a live entity from its scene file record, the way the scene loader
31854
+ * builds it: the record's registered type, its uid, its `enabled` flag, and its `props` decoded
31855
+ * against the schema (`docs/architecture/06-serialization-and-scene-format.md` §4).
31856
+ *
31857
+ * @remarks
31858
+ * This is the per-component step of {@link instantiateScene} for a world that already exists, which
31859
+ * is what an editor mirroring a document into a live world needs. The component is attached with
31860
+ * `entity.addComponent`, so `awake` follows that method's rules. The record's uid is adopted as is;
31861
+ * keeping it unique within the scene is the caller's job. Decoding never throws: a value that does
31862
+ * not match its field takes the field's default and is reported in `issues`.
31863
+ *
31864
+ * @param entity - The entity to attach to.
31865
+ * @param record - The component record, as a scene file writes it.
31866
+ * @param options - Where it goes among the entity's components, and how references resolve.
31867
+ * @returns The component and the decoding problems.
31868
+ * @throws IgnifxError with code `IGX-0307` when the record's type is not registered, and whatever
31869
+ * `entity.addComponent` throws (`IGX-0202` for a second instance of a single-instance class,
31870
+ * `IGX-0101` for a destroyed entity).
31871
+ *
31872
+ * @example
31873
+ * ```ts
31874
+ * const { component } = addComponentFromRecord(player, { uid: "01J9Z6M7E5S3A0V2Q4R8T1Y6WY", type: "game/Health", props: { max: 120 } });
31875
+ * ```
31876
+ *
31877
+ * @public
31878
+ */
31879
+ function addComponentFromRecord(entity, record, options) {
31880
+ const registry = entity.world.registry;
31881
+ const type = registry.get(record.type);
31882
+ if (type === null) throw new IgnifxError(CoreErrorCode.unknownComponentTypeId, `The component type "${record.type}" is not registered; register it with app.registerComponents or check its typeId.`, { context: {
31883
+ typeId: record.type,
31884
+ entity: entity.uid
31885
+ } });
31886
+ const component = entity.addComponent(type);
31887
+ componentInternals(component).uid = record.uid;
31888
+ if (record.enabled === false) component.enabled = false;
31889
+ if (options?.index !== void 0) moveToFileIndex(entity, component, options.index);
31890
+ const issues = [];
31891
+ const schema = registry.describe(component.constructor).schema;
31892
+ if (schema !== null) applyProps({ report: (code, message) => {
31893
+ issues.push({
31894
+ code,
31895
+ message
31896
+ });
31897
+ } }, options?.references ?? NO_REFERENCES, component, schema, record.props ?? {}, record.uid);
31898
+ return {
31899
+ component,
31900
+ issues
31901
+ };
31902
+ }
31903
+ /**
31904
+ * Moves a component to an index of the entity's component list as a scene file counts it: the
31905
+ * transform, destroyed components, and the components an instanced scene merged in do not count.
31906
+ *
31907
+ * @param entity - The owner.
31908
+ * @param component - One of its components.
31909
+ * @param index - The index in file order; past the end means the end.
31910
+ */
31911
+ function moveToFileIndex(entity, component, index) {
31912
+ const internals = entityInternals(entity);
31913
+ const list = internals.components;
31914
+ const from = list.indexOf(component);
31915
+ if (from < 0) return;
31916
+ list.splice(from, 1);
31917
+ const merged = internals.origin?.instanced?.root?.components ?? null;
31918
+ let counted = 0;
31919
+ for (let at = 0; at < list.length; at += 1) {
31920
+ const other = list[at];
31921
+ if (other === void 0 || other === internals.transform || other.isDestroyed || merged?.has(other.uid) === true) continue;
31922
+ if (counted >= index) {
31923
+ list.splice(at, 0, component);
31924
+ return;
31925
+ }
31926
+ counted += 1;
31927
+ }
31928
+ list.push(component);
31929
+ }
30576
31930
  /**
30577
31931
  * Checks that every scene a file instances — at any depth — is among the loaded dependencies, which
30578
31932
  * is what makes `world.instantiate` safe to be synchronous
@@ -30946,7 +32300,7 @@ var World = class {
30946
32300
  * answer.
30947
32301
  *
30948
32302
  * @param ray - The ray to cast.
30949
- * @param options - An entity filter.
32303
+ * @param options - An entity filter, and what to look through.
30950
32304
  * @returns What was hit, or `null` for a miss.
30951
32305
  *
30952
32306
  * @example
@@ -31090,6 +32444,110 @@ var World = class {
31090
32444
  return instance;
31091
32445
  }
31092
32446
  /**
32447
+ * Builds a scene from a file that is already in memory, the way {@link World.loadScene} builds one
32448
+ * from an address (`docs/architecture/02-scene-graph.md` §2).
32449
+ *
32450
+ * @remarks
32451
+ * Nothing is fetched for the file itself: it is validated, every asset it references is loaded
32452
+ * through `app.assets` (the scene loader's own walk), and it is published there at
32453
+ * `options.address` as a scene asset, so the instance's `asset` and everything that reads it
32454
+ * behave as for a loaded file. Entity and component uids are the file's. The instance holds the
32455
+ * asset and its dependencies and releases them when it is unloaded. The rest is
32456
+ * {@link World.loadScene}'s: the same modes, the same synchronous build, `awake` before the
32457
+ * promise settles, and `onSceneLoaded`.
32458
+ *
32459
+ * This is how a tool builds a scene it holds as an object, such as an editor's open document with
32460
+ * unsaved edits.
32461
+ *
32462
+ * @param file - The scene file object, as `serializeScene` or `JSON.parse` produces it.
32463
+ * @param options - The address to publish it at, the mode, cancellation, and an issue collector.
32464
+ * @returns The instance, once every entity exists, every reference is resolved, and `awake` has
32465
+ * run.
32466
+ * @throws IgnifxError with code `IGX-0308` when the object is not a scene file, `IGX-0603` for a
32467
+ * format version this build cannot read, and `IGX-0608` when it does not match the scene format;
32468
+ * nothing is unloaded then. `IGX-0502` when `options.signal` aborts, `IGX-0307` when the file
32469
+ * names an unregistered component type (the half-built instance is unloaded first), and
32470
+ * whatever the asset system throws for a dependency.
32471
+ *
32472
+ * @example
32473
+ * ```ts
32474
+ * const level = await world.loadSceneFile(file, { address: "levels/level01.scene.json" });
32475
+ * ```
32476
+ */
32477
+ async loadSceneFile(file, options) {
32478
+ const { address, signal } = options;
32479
+ const checked = readSceneFile(file, address, true);
32480
+ const mode = options.mode ?? "single";
32481
+ if (mode === "single") await this.#unloadNonPersistent();
32482
+ const dependencies = await loadSceneDependencies(this.#assets(), checked, signal === void 0 ? void 0 : { signal });
32483
+ const release = () => {
32484
+ for (let index = 0; index < dependencies.length; index += 1) dependencies[index]?.release();
32485
+ };
32486
+ if (signal?.aborted === true) {
32487
+ release();
32488
+ throw new IgnifxError(CoreErrorCode.assetLoadAborted, `Loading ${address} was aborted.`, { context: { asset: address } });
32489
+ }
32490
+ const asset = await createSceneAsset(address, checked, dependencies);
32491
+ const handle = this.#assets().register(asset, {
32492
+ type: SCENE_ASSET_TYPE,
32493
+ address
32494
+ });
32495
+ const instance = new SceneInstance(this.#nextUid(), options.name ?? checked.name, false);
32496
+ instance.setAsset(handle);
32497
+ instance.onUnloading.connect(release, { once: true });
32498
+ instance.setLoaded(false);
32499
+ this.#scenes.push(instance);
32500
+ let built;
32501
+ try {
32502
+ built = instantiateScene(this, asset, {
32503
+ scene: instance,
32504
+ ...options.strictInstanceHashes === void 0 ? {} : { strictInstanceHashes: options.strictInstanceHashes }
32505
+ });
32506
+ } catch (error) {
32507
+ await this.unloadScene(instance);
32508
+ throw error;
32509
+ }
32510
+ instance.setRemap(built.remap);
32511
+ instance.setSettings(checked.settings ?? null);
32512
+ instance.setLoaded(true);
32513
+ this.#reportSceneIssues(address, built.issues);
32514
+ const onIssue = options.onIssue;
32515
+ if (onIssue !== void 0) for (let index = 0; index < built.issues.length; index += 1) {
32516
+ const issue = built.issues[index];
32517
+ if (issue !== void 0) onIssue(issue);
32518
+ }
32519
+ if (options.setActive ?? mode === "single") this.#activeScene = instance;
32520
+ this.#lifecycle.flushAwakeAndEnable();
32521
+ this.#onSceneLoaded.emit(instance);
32522
+ return instance;
32523
+ }
32524
+ /**
32525
+ * Creates an empty scene instance that is built in code rather than loaded from a file
32526
+ * (`docs/architecture/02-scene-graph.md` §3).
32527
+ *
32528
+ * @remarks
32529
+ * Entities join it through `createEntity(name, { scene })` or `moveEntityToScene`. A persistent
32530
+ * instance survives every `"single"` load, so it is where a tool keeps objects that must outlive
32531
+ * the levels it loads: an editor's cameras, grid and gizmo roots. Like any instance other than the
32532
+ * implicit `"default"` one, it can be unloaded with `unloadScene`. Creating it raises no
32533
+ * `onSceneLoaded`, because nothing was loaded; `serializeScene` writes it only when it is passed.
32534
+ *
32535
+ * @param name - The instance's name.
32536
+ * @param options - Whether it is persistent.
32537
+ * @returns The new, empty instance, appended to `scenes`.
32538
+ *
32539
+ * @example
32540
+ * ```ts
32541
+ * const tools = world.createScene("editor", { persistent: true });
32542
+ * const camera = world.createEntity("Editor Camera", { scene: tools });
32543
+ * ```
32544
+ */
32545
+ createScene(name, options) {
32546
+ const instance = new SceneInstance(this.#nextUid(), name, options?.persistent ?? false);
32547
+ this.#scenes.push(instance);
32548
+ return instance;
32549
+ }
32550
+ /**
31093
32551
  * Unloads a scene instance: `onUnloading` fires while its entities are still valid, its roots are
31094
32552
  * destroyed through the normal destroy path (children before parents, `onDisable` then
31095
32553
  * `onDestroy`), and the assets it held are released
@@ -31631,6 +33089,8 @@ var AppImpl = class {
31631
33089
  hotReload;
31632
33090
  /** `true` when the app runs on Lite's null engine with no render surface. */
31633
33091
  isHeadless;
33092
+ /** `true` when the app was created for an editor's scene view. */
33093
+ isEditMode;
31634
33094
  /** The `@ignifx/core` version this app was built from. */
31635
33095
  version = VERSION;
31636
33096
  /** Where the app is running. */
@@ -31684,6 +33144,7 @@ var AppImpl = class {
31684
33144
  this.#clock = options.clock;
31685
33145
  this.#mode = options.mode;
31686
33146
  this.isHeadless = options.canvas === null;
33147
+ this.isEditMode = options.editMode;
31687
33148
  this.platform = options.platform;
31688
33149
  this.storage = new StorageImpl(options.storage);
31689
33150
  const development = options.mode === "development";
@@ -31729,6 +33190,7 @@ var AppImpl = class {
31729
33190
  });
31730
33191
  this.coroutines = new CoroutineHostImpl({
31731
33192
  frameState: this.#frameState,
33193
+ editMode: options.editMode,
31732
33194
  report: (error, owner) => {
31733
33195
  this.#report({
31734
33196
  error,
@@ -31747,6 +33209,7 @@ var AppImpl = class {
31747
33209
  deferred: this.#deferred,
31748
33210
  clock: options.clock,
31749
33211
  development,
33212
+ editMode: options.editMode,
31750
33213
  report: (error, system, phase) => {
31751
33214
  this.log.error(`The system ${system.name} threw in ${PHASE_NAMES[phase] ?? "no phase"}.`, error);
31752
33215
  this.#report({
@@ -32193,7 +33656,8 @@ async function createApp(options = {}) {
32193
33656
  mode: options.mode ?? "development",
32194
33657
  logSink: options.logSink ?? createConsoleSink(),
32195
33658
  logLevel: options.logLevel ?? "info",
32196
- reloadScenes: options.hotReload?.reloadScenes ?? false
33659
+ reloadScenes: options.hotReload?.reloadScenes ?? false,
33660
+ editMode: options.editMode ?? false
32197
33661
  });
32198
33662
  await app.initialize(options.extensions ?? []);
32199
33663
  return app;
@@ -32679,6 +34143,64 @@ var Vec4 = class Vec4 {
32679
34143
  }
32680
34144
  };
32681
34145
  //#endregion
34146
+ //#region src/transform/transform-schema.ts
34147
+ /**
34148
+ * The entity transform as a schema: the fields of a scene file's `transform` block, so an
34149
+ * inspector and its ops can treat the transform like any component
34150
+ * (`docs/architecture/06-serialization-and-scene-format.md` §2).
34151
+ *
34152
+ * @remarks
34153
+ * The schema **describes** the transform; {@link (Transform:class)} does not declare it. The class keeps
34154
+ * no schema because its `position` and `rotation` are world-space getters, while the file, this
34155
+ * schema, and the editor's `setTransform` op all carry **local** values. Every entity has exactly
34156
+ * one transform, which is never in a file's `components` list, so `describeSchemas()` and
34157
+ * `describeRegisteredSchemas()` mark `ignifx/Transform` as `builtIn`: it cannot be added or
34158
+ * removed, and its values are edited as the whole block, not with a per-prop op.
34159
+ *
34160
+ * `rotation` is a `quat` field: files and ops store a unit quaternion, and an inspector shows
34161
+ * intrinsic XYZ Euler angles in degrees (ADR-0011), so its `step` is in degrees.
34162
+ *
34163
+ * @returns A new schema: `position` (`vec3`, origin, step 0.01), `rotation` (`quat`, identity,
34164
+ * step 0.5 degrees), `scale` (`vec3`, one, step 0.01).
34165
+ *
34166
+ * @example
34167
+ * ```ts
34168
+ * const fields = describeSchema("ignifx/Transform", transformSchema()).fields;
34169
+ * fields["rotation"]?.default; // [0, 0, 0, 1]
34170
+ * ```
34171
+ *
34172
+ * @public
34173
+ */
34174
+ function transformSchema() {
34175
+ return defineSchema({
34176
+ position: vec3({
34177
+ x: 0,
34178
+ y: 0,
34179
+ z: 0
34180
+ }, {
34181
+ tooltip: "Local position relative to the parent, in metres.",
34182
+ step: .01
34183
+ }),
34184
+ rotation: quat({
34185
+ x: 0,
34186
+ y: 0,
34187
+ z: 0,
34188
+ w: 1
34189
+ }, {
34190
+ tooltip: "Local rotation relative to the parent: a unit quaternion [x, y, z, w], shown as intrinsic XYZ Euler angles in degrees.",
34191
+ step: .5
34192
+ }),
34193
+ scale: vec3({
34194
+ x: 1,
34195
+ y: 1,
34196
+ z: 1
34197
+ }, {
34198
+ tooltip: "Local scale relative to the parent.",
34199
+ step: .01
34200
+ })
34201
+ });
34202
+ }
34203
+ //#endregion
32682
34204
  //#region src/render/schemas.ts
32683
34205
  /**
32684
34206
  * The documentation harness's view of everything `@ignifx/core` declares
@@ -32695,11 +34217,19 @@ var Vec4 = class Vec4 {
32695
34217
  *
32696
34218
  * The harness requires every key to be a namespaced `<package>/<Name>` type id
32697
34219
  * (`scripts/lib/schema-source.ts` rejects a key with no `/`), and it groups entries onto a page by
32698
- * their `format`. A *file* format is not a component and has no type id, so the three file formats
32699
- * below are keyed `ignifx/scene-file`, `ignifx/material-file`, and `ignifx/environment-file` while
32700
- * declaring `format: "ignifx.scene"`, `"ignifx.material"`, and `"ignifx.environment"`. The wave-1
34220
+ * their `format`. A *file* format is not a component and has no type id, so the file formats
34221
+ * below are keyed `ignifx/scene-file`, `ignifx/material-file`, `ignifx/environment-file`, and
34222
+ * `ignifx/mesh-file` while declaring `format: "ignifx.scene"`, `"ignifx.material"`,
34223
+ * `"ignifx.environment"`, and `"ignifx.mesh"`. The wave-1
32701
34224
  * hand-off asked for the key `"ignifx.scene"`; that key fails the namespacing check, and the
32702
34225
  * grouping — which is what actually decides the page — comes from `format` either way.
34226
+ *
34227
+ * ## The transform
34228
+ *
34229
+ * `ignifx/Transform` is described like a component, from `transformSchema()`, though its class
34230
+ * declares no schema: it is the scene file's per-entity `transform` block. Its entry is the only one
34231
+ * that sets `builtIn` (with `allowMultiple: false` and `package: "@ignifx/core"`), so an editor
34232
+ * shows it with the components but never offers to add or remove it.
32703
34233
  */
32704
34234
  /**
32705
34235
  * Describes every component and file format this package declares, for the documentation harness.
@@ -32716,6 +34246,12 @@ var Vec4 = class Vec4 {
32716
34246
  */
32717
34247
  function describeSchemas() {
32718
34248
  return {
34249
+ "ignifx/Transform": describeSchema("ignifx/Transform", transformSchema(), {
34250
+ description: "The entity's local position, rotation, and scale; every entity has exactly one, stored as its transform block.",
34251
+ allowMultiple: false,
34252
+ package: "@ignifx/core",
34253
+ builtIn: true
34254
+ }),
32719
34255
  "ignifx/Camera": describeSchema("ignifx/Camera", Camera.schema, { description: "The camera an entity renders the world through; the entity's transform is the view." }),
32720
34256
  "ignifx/Light": describeSchema("ignifx/Light", Light.schema, { description: "A directional, point, spot, or hemispheric light, with optional shadow casting." }),
32721
34257
  "ignifx/MeshRenderer": describeSchema("ignifx/MeshRenderer", MeshRenderer.schema, { description: "Draws one clone of a mesh asset with a material." }),
@@ -32725,7 +34261,8 @@ function describeSchemas() {
32725
34261
  "ignifx/PostProcessStack": describeSchema("ignifx/PostProcessStack", PostProcessStack.schema, { description: "Bloom, SMAA, image processing, and custom .post.wgsl effects, inserted into the scene's frame graph." }),
32726
34262
  "ignifx/scene-file": describeSceneFileFormat(),
32727
34263
  "ignifx/material-file": describeMaterialFileFormat(),
32728
- "ignifx/environment-file": describeEnvironmentFileFormat()
34264
+ "ignifx/environment-file": describeEnvironmentFileFormat(),
34265
+ "ignifx/mesh-file": describeMeshFileFormat()
32729
34266
  };
32730
34267
  }
32731
34268
  /**
@@ -32987,6 +34524,48 @@ function describeEnvironmentFileFormat() {
32987
34524
  }
32988
34525
  };
32989
34526
  }
34527
+ /**
34528
+ * Describes the `ignifx.mesh` file format (ADR-0029).
34529
+ *
34530
+ * @returns The description of the top-level file fields.
34531
+ *
34532
+ * @public
34533
+ */
34534
+ function describeMeshFileFormat() {
34535
+ const optionsByPrimitive = MESH_PRIMITIVES.map((primitive) => `${primitive}: ${Object.keys(MESH_PRIMITIVE_OPTIONS[primitive]).join(", ")}`).join("; ");
34536
+ return {
34537
+ title: "Mesh file",
34538
+ format: MESH_FILE_FORMAT,
34539
+ description: "One primitive mesh and the options its MeshAsset factory takes, so a scene file can name it by address. glTF meshes load as models instead.",
34540
+ fields: {
34541
+ format: {
34542
+ kind: "str",
34543
+ default: MESH_FILE_FORMAT,
34544
+ description: `Always "${MESH_FILE_FORMAT}".`
34545
+ },
34546
+ formatVersion: {
34547
+ kind: "u32",
34548
+ default: 1,
34549
+ description: "The file format version; 1 before ignifx 1.0."
34550
+ },
34551
+ name: {
34552
+ kind: "str",
34553
+ default: "",
34554
+ description: "A name for diagnostics; empty uses the file's address."
34555
+ },
34556
+ primitive: {
34557
+ kind: "enum",
34558
+ default: "box",
34559
+ description: `The shape: ${MESH_PRIMITIVES.join(", ")}. Required; an unknown value is rejected with IGX-0507.`
34560
+ },
34561
+ options: {
34562
+ kind: "record",
34563
+ default: {},
34564
+ description: `The factory's options; omitted ones take its defaults. Lengths are metres, zero or more; counts are whole numbers, one or more; uvScale is two numbers. An unknown option or a bad value is IGX-0507. By primitive: ${optionsByPrimitive}.`
34565
+ }
34566
+ }
34567
+ };
34568
+ }
32990
34569
  //#endregion
32991
34570
  //#region src/serialization/serialize.ts
32992
34571
  /**
@@ -33194,7 +34773,7 @@ function writeEntity(planned, references, report) {
33194
34773
  const layerName = entity.world.layers.nameOf(entity.layer);
33195
34774
  const origin = planned.origin;
33196
34775
  const instance = origin === null ? null : writeInstance(entity, origin, references, report);
33197
- const components = writeComponents(entity, references, report);
34776
+ const components = writeComponents(entity, references, report, origin?.instanced?.root?.components ?? null);
33198
34777
  return {
33199
34778
  uid: entity.uid,
33200
34779
  name: entity.name,
@@ -33214,14 +34793,15 @@ function writeEntity(planned, references, report) {
33214
34793
  * @param entity - The entity.
33215
34794
  * @param references - How references resolve.
33216
34795
  * @param report - Receives problems.
34796
+ * @param skip - The uids of components an instanced scene put on the entity, which are not written.
33217
34797
  * @returns The records, in attach order.
33218
34798
  */
33219
- function writeComponents(entity, references, report) {
34799
+ function writeComponents(entity, references, report, skip) {
33220
34800
  const records = [];
33221
34801
  const components = entity.components;
33222
34802
  for (let index = 0; index < components.length; index += 1) {
33223
34803
  const component = components[index];
33224
- if (component === void 0 || component === entity.transform || component.isDestroyed) continue;
34804
+ if (component === void 0 || component === entity.transform || component.isDestroyed || skip?.has(component.uid) === true) continue;
33225
34805
  if (component.world.registry.describe(component.constructor).typeId === null) {
33226
34806
  report(CoreErrorCode.componentTypeIdMissing, `${component.constructor.name} on ${entity.name} has no typeId and cannot be written.`);
33227
34807
  continue;
@@ -33275,7 +34855,7 @@ function writeTransform(transform) {
33275
34855
  function writeInstance(root, origin, references, report) {
33276
34856
  const link = origin.instanced;
33277
34857
  if (link === null) return null;
33278
- const overrides = computeOverrides(root, link.scene, references, report);
34858
+ const overrides = computeOverrides(root, link, references, report);
33279
34859
  return {
33280
34860
  scene: { $asset: link.address },
33281
34861
  hash: link.scene.hash,
@@ -33291,23 +34871,37 @@ function writeInstance(root, origin, references, report) {
33291
34871
  * a third file — so deep edits inside a nested prefab are not written back; `flatten: true` is the
33292
34872
  * escape hatch.
33293
34873
  *
34874
+ * An instance root that stands for its scene's single root is diffed against that root's record
34875
+ * too, but only for the components the scene put on it: its name, transform, and other entity
34876
+ * fields, and the components it gained, are the entry's own.
34877
+ *
33294
34878
  * @param root - The instance root.
33295
- * @param scene - The instanced scene.
34879
+ * @param link - Its link to the instanced scene.
33296
34880
  * @param references - How references resolve.
33297
34881
  * @param report - Receives problems.
33298
34882
  * @returns The overrides, in a stable order: entity records in file order, then per entity its
33299
34883
  * plain properties, then its components.
33300
34884
  */
33301
- function computeOverrides(root, scene, references, report) {
34885
+ function computeOverrides(root, link, references, report) {
33302
34886
  const current = /* @__PURE__ */ new Map();
34887
+ const single = link.root;
34888
+ if (single !== null) current.set(single.sourceUid, root);
33303
34889
  collectDirectMembers(root, root, current);
33304
34890
  const overrides = [];
33305
- const source = scene.file.entities;
34891
+ const source = link.scene.file.entities;
33306
34892
  for (let index = 0; index < source.length; index += 1) {
33307
34893
  const record = source[index];
33308
34894
  if (record === void 0) continue;
33309
34895
  const entity = current.get(record.uid);
33310
34896
  if (entity === void 0) continue;
34897
+ if (entity === root && single !== null) {
34898
+ diffComponents(entity, record, {
34899
+ sourceUids: single.componentSourceUids,
34900
+ from: single.components,
34901
+ inside: true
34902
+ }, overrides, references, report);
34903
+ continue;
34904
+ }
33311
34905
  diffEntity(entity, record, overrides, references, report);
33312
34906
  }
33313
34907
  return overrides;
@@ -33364,7 +34958,13 @@ function diffEntity(entity, record, overrides, references, report) {
33364
34958
  value: tags
33365
34959
  });
33366
34960
  diffTransform(entity, record, uid, overrides);
33367
- diffComponents(entity, record, uid, overrides, references, report);
34961
+ const origin = entityInternals(entity).origin;
34962
+ const nested = origin?.instanced?.root?.components ?? /* @__PURE__ */ new Set();
34963
+ diffComponents(entity, record, {
34964
+ sourceUids: origin?.componentSourceUids ?? /* @__PURE__ */ new Map(),
34965
+ from: nested,
34966
+ inside: false
34967
+ }, overrides, references, report);
33368
34968
  }
33369
34969
  /**
33370
34970
  * Diffs an instanced entity's transform against its file record.
@@ -33395,21 +34995,24 @@ function diffTransform(entity, record, uid, overrides) {
33395
34995
  *
33396
34996
  * @param entity - The runtime entity.
33397
34997
  * @param record - Its file record.
33398
- * @param uid - The record's uid, for paths.
34998
+ * @param diff - Which components to diff, and their record uids.
33399
34999
  * @param overrides - Where patches are appended.
33400
35000
  * @param references - How references resolve.
33401
35001
  * @param report - Receives problems.
33402
35002
  */
33403
- function diffComponents(entity, record, uid, overrides, references, report) {
33404
- const sourceUids = entityInternals(entity).origin?.componentSourceUids ?? /* @__PURE__ */ new Map();
35003
+ function diffComponents(entity, record, diff, overrides, references, report) {
35004
+ const uid = record.uid;
35005
+ const sourceUids = diff.sourceUids;
33405
35006
  const declared = record.components ?? [];
33406
35007
  const seen = /* @__PURE__ */ new Set();
33407
35008
  const components = entity.components;
33408
35009
  for (let index = 0; index < components.length; index += 1) {
33409
35010
  const component = components[index];
33410
35011
  if (component === void 0 || component === entity.transform || component.isDestroyed) continue;
35012
+ if (diff.from.has(component.uid) !== diff.inside) continue;
33411
35013
  if (component.world.registry.describe(component.constructor).typeId === null) continue;
33412
35014
  const sourceUid = sourceUids.get(component.uid);
35015
+ if (sourceUid === void 0 && diff.inside) continue;
33413
35016
  const written = serializeComponent(component, references, (issue) => {
33414
35017
  report(issue.code, issue.message);
33415
35018
  });
@@ -33562,15 +35165,113 @@ function sameNumbers(left, right) {
33562
35165
  return true;
33563
35166
  }
33564
35167
  /**
33565
- * Compares two JSON values structurally. Both sides come out of the same canonical encoder, so
33566
- * comparing their canonical text is exact and cheap.
35168
+ * Compares two JSON values structurally, counting both spellings of one asset reference as equal.
35169
+ *
35170
+ * @remarks
35171
+ * One side is what the instanced file says, written by hand or by any tool; the other comes out of
35172
+ * the encoder. A file may leave out an asset reference's `type`, which the loader then infers from
35173
+ * the address, but the encoder always writes the type of the handle it holds. So
35174
+ * `{ "$asset": a }` and `{ "$asset": a, "type": t }` name the same asset; comparing them as text
35175
+ * would save every terse reference in an instanced prefab as an override.
33567
35176
  *
33568
35177
  * @param left - The first.
33569
35178
  * @param right - The second.
33570
- * @returns `true` when they encode identically.
35179
+ * @returns `true` when they hold the same data.
33571
35180
  */
33572
35181
  function sameJson(left, right) {
33573
- return JSON.stringify(left) === JSON.stringify(right);
35182
+ if (left === right) return true;
35183
+ const leftArray = asJsonArray(left);
35184
+ const rightArray = asJsonArray(right);
35185
+ if (leftArray !== null || rightArray !== null) {
35186
+ if (leftArray === null || rightArray === null || leftArray.length !== rightArray.length) return false;
35187
+ for (let index = 0; index < leftArray.length; index += 1) if (!sameJson(leftArray[index] ?? null, rightArray[index] ?? null)) return false;
35188
+ return true;
35189
+ }
35190
+ const leftObject = asJsonObject(left);
35191
+ const rightObject = asJsonObject(right);
35192
+ if (leftObject === null || rightObject === null) return false;
35193
+ if (typeof leftObject["$asset"] === "string" && typeof rightObject["$asset"] === "string") return sameAssetReference(leftObject, rightObject);
35194
+ const keys = Object.keys(leftObject);
35195
+ if (keys.length !== Object.keys(rightObject).length) return false;
35196
+ for (const key of keys) if (!Object.hasOwn(rightObject, key) || !sameJson(leftObject[key] ?? null, rightObject[key] ?? null)) return false;
35197
+ return true;
35198
+ }
35199
+ /**
35200
+ * Compares two `{ "$asset": … }` references: the same address, and the same type unless one side
35201
+ * leaves the type for the loader to infer.
35202
+ *
35203
+ * @param left - The first reference.
35204
+ * @param right - The second reference.
35205
+ * @returns `true` when they name the same asset.
35206
+ */
35207
+ function sameAssetReference(left, right) {
35208
+ if (left["$asset"] !== right["$asset"]) return false;
35209
+ const leftType = left["type"];
35210
+ const rightType = right["type"];
35211
+ return leftType === void 0 || rightType === void 0 || leftType === rightType;
35212
+ }
35213
+ //#endregion
35214
+ //#region src/schema/describe-registry.ts
35215
+ /**
35216
+ * The package a registered component belongs to: the extension that registered it, or else the
35217
+ * namespace of its type id.
35218
+ *
35219
+ * @param registry - The registry the component is registered in.
35220
+ * @param typeId - The component's type id.
35221
+ * @returns The extension's `name` (`@ignifx/3d`), or everything before the type id's last `/`
35222
+ * (`mygame` for `mygame/Mover`) when no extension registered it.
35223
+ *
35224
+ * @internal
35225
+ */
35226
+ function componentPackage(registry, typeId) {
35227
+ return registry.registrarOf(typeId) ?? typeId.slice(0, Math.max(0, typeId.lastIndexOf("/")));
35228
+ }
35229
+ /**
35230
+ * Describes every component an app has registered, the engine's, its extensions' and the game's,
35231
+ * the way {@link describeSchema} describes one, plus what only the registry knows: whether an
35232
+ * entity may hold more than one (`allowMultiple`) and which package registered it (`package`).
35233
+ * This is what an external inspector, such as the ignifx editor, is generated from.
35234
+ *
35235
+ * @remarks
35236
+ * `package` is the `name` of the extension whose `register(ctx)` registered the class, which is the
35237
+ * npm package name for a published extension (`@ignifx/core`, `@ignifx/3d`). A class the game
35238
+ * registered itself with `app.registerComponents` has no extension, so its `package` is its type
35239
+ * id's namespace: everything before the last `/` (`third-person` for `third-person/Beacon`).
35240
+ *
35241
+ * `ignifx/Transform` declares no schema on its class; it is described with {@link transformSchema}
35242
+ * and marked `builtIn`, because every entity carries exactly one and a scene file stores it as the
35243
+ * entity's `transform` block rather than in its `components`.
35244
+ *
35245
+ * @param registry - The registry to walk, usually `app.world.registry`.
35246
+ * @param curated - Titles, formats and summaries by type id, for example a package's own
35247
+ * `describeSchemas()`; a component without an entry is titled from its type id.
35248
+ * @returns The descriptions, keyed by type id, in registration order.
35249
+ *
35250
+ * @example
35251
+ * ```ts
35252
+ * const schemas = describeRegisteredSchemas(app.world.registry, describeSchemas());
35253
+ * schemas["ignifx/Camera"]?.package; // "@ignifx/core"
35254
+ * schemas["ignifx/Camera"]?.allowMultiple; // false
35255
+ * ```
35256
+ *
35257
+ * @public
35258
+ */
35259
+ function describeRegisteredSchemas(registry, curated) {
35260
+ const described = {};
35261
+ for (const [typeId, type] of registry.registrations()) {
35262
+ const info = registry.describe(type);
35263
+ const meta = curated?.[typeId];
35264
+ const builtIn = type === Transform;
35265
+ described[typeId] = describeSchema(typeId, builtIn ? transformSchema() : info.schema ?? {}, {
35266
+ ...meta?.title === void 0 ? {} : { title: meta.title },
35267
+ ...meta?.format === void 0 ? {} : { format: meta.format },
35268
+ ...meta?.description === void 0 ? {} : { description: meta.description },
35269
+ allowMultiple: info.allowMultiple,
35270
+ package: componentPackage(registry, typeId),
35271
+ ...builtIn ? { builtIn } : {}
35272
+ });
35273
+ }
35274
+ return described;
33574
35275
  }
33575
35276
  //#endregion
33576
35277
  //#region src/script/wait.ts
@@ -33678,6 +35379,443 @@ function waitWhile(predicate) {
33678
35379
  });
33679
35380
  }
33680
35381
  //#endregion
33681
- export { ASSET_DIAGNOSTICS_COUNTERS, ASSET_DIAGNOSTICS_GROUP, ASSET_MANIFEST_FORMAT, ASSET_MANIFEST_VERSION, AssetLoadError, CANVAS_ALPHA_MODES, CORE_ERROR_MESSAGES, Camera, Color, Component, ComponentRegistry, CoreErrorCode, DEFAULT_ASSET_CONCURRENCY, DEFAULT_ASSET_ROOT, DEFAULT_BRDF_LUT_ADDRESS, DEFAULT_LAYER, DEFAULT_MEMORY_SINK_LIMIT, DEFAULT_STORAGE_NAMESPACE, DEG_TO_RAD, Diagnostics, EASINGS, EASING_NAMES, EMPTY_ASSET_MANIFEST, ENVIRONMENT_ASSET_TYPE, ENVIRONMENT_FILE_EXTENSION, ENVIRONMENT_FILE_EXTENSIONS, ENVIRONMENT_FILE_FORMAT, ENVIRONMENT_FORMAT_VERSION, EPSILON, Entity, Environment, EnvironmentAsset, ErrorRange, FOG_MODE_NAMES, FONT_ASSET_TYPE, FONT_FILE_EXTENSIONS, FRAME_HISTORY_LENGTH, FieldKind, FontAsset, IGNIFX_UNIFORM_NAMES, INVALID_HANDLE, IgnifxError, IndexedDbStorageBackend, InstancedMeshRenderer, LIGHT_TYPES, LITE_MATERIAL_PLUGIN_POINTS, LITE_SYSTEM_UNIFORM_NAMES, LOG_LEVEL_SEVERITY, LayerMask, LayerTable, Light, LogLevel, MAT4_IDENTITY, MATERIAL_ALPHA_MODES, MATERIAL_ASSET_TYPE, MATERIAL_FILE_EXTENSION, MATERIAL_FILE_FORMAT, MATERIAL_FORMAT_VERSION, MATERIAL_KINDS, MATERIAL_PLUGIN_DEFAULT_PRIORITY, MATERIAL_PLUGIN_RESERVED_NAMES, MATERIAL_PLUGIN_SAMPLER_BUDGET, MAX_LAYERS, MAX_ULID_TIME_MS, MESH_ASSET_TYPE, MODEL_ASSET_TYPE, MODEL_FILE_EXTENSIONS, Mat4, MaterialAsset, MemoryStorageBackend, MeshAsset, MeshRenderer, Model, ModelAsset, NAMESPACE_SEGMENT_MAX_LENGTH, PBR_TEXTURE_SLOTS, PHASES, PHASE_COUNT, PHASE_NAMES, POST_EFFECT_BUILTIN_UNIFORMS, POST_EFFECT_FUNCTION, PROJECTIONS, Phase, PhysicsCallbackName, PostProcessStack, QUAT_IDENTITY, Quat, RAD_TO_DEG, RENDERING_SETTINGS_SECTION, RENDER_DIAGNOSTICS_COUNTERS, RENDER_DIAGNOSTICS_GROUP, RESERVED_LAYER_NAMES, SCENE_ASSET_TYPE, SCENE_FILE_EXTENSIONS, SCENE_FILE_FORMAT, SCENE_FORMAT_VERSION, SHADER_ASSET_TYPE, SHADER_ATTRIBUTE_NAMES, SHADER_BLEND_MODES, SHADER_CULL_MODES, SHADER_FILE_EXTENSIONS, SHADER_INSTANCING_MODES, SHADER_KINDS, SHADER_TEXTURE_FALLBACKS, SHADER_UNIFORM_TYPES, SHADOW_TECHNIQUES, STANDARD_TEXTURE_SLOTS, STORAGE_BUFFER_ASSET_TYPE, STORAGE_KEY_MAX_LENGTH, SURFACE_HOOK_NAMES, SURFACE_UNIFORM_BLOCK, SceneAssetToken, SceneInstance, SchemaIssueCode, Script, ScriptCallbackKind, ShaderAsset, Signal, StorageBufferAsset, TEXTURE_ASSET_TYPE, THIRD_PARTY_ERROR_PREFIX, TONE_MAPPING_NAMES, TWEEN_LOOP_FOREVER, TWEEN_SYSTEM_ORDER, TWEEN_VALUE_KINDS, TagSet, TextureAsset, Transform, Tween, UidRemap, VEC2_ONE, VEC2_ZERO, VEC3_BACKWARD, VEC3_DOWN, VEC3_FORWARD, VEC3_LEFT, VEC3_ONE, VEC3_RIGHT, VEC3_UP, VEC3_ZERO, VERSION, Vec2, Vec3, Vec4, World, applyInit, approximately, array, assertNever, assertSceneDependenciesLoaded, asset, assetRef, binaryAssetLoader, bool, canonicalizeNumber, clamp, clamp01, color, componentRef, computeSceneHash, coreExtension, createApp, createAssetManifest, createConsoleSink, createCryptoRandom, createDefaults, createDiagnosticsGroup, createEnvironmentLoader, createErrorCodeRegistry, createFileStorageBackend, createFontLoader, createFrameSample, createLayerTable, createLogger, createManualClock, createMaterialAsset, createMaterialLoader, createMemorySink, createModelLoader, createPerformanceClock, createRay, createSceneAsset, createSceneLoader, createSeededRandom, createServiceKey, createShaderLoader, createStorageBufferAsset, createTextureLoader, createUlidFactory, curve, custom, customEffect, decodeProps, decodeValue, defaultRenderingSettings, defineExtension, defineMaterialPlugin, defineSchema, degToRad, deltaAngleDegrees, describeEnvironmentFileFormat, describeMaterialFileFormat, describeSceneFileFormat, describeSchema, describeSchemas, encodeProps, encodeValue, entityRef, enumOf, environmentDefinition, f32, f64, forceRendererDeviceLossForTesting, formatErrorMessage, generateUlid, i32, instantiateScene, inverseLerp, isAssetRef, isIgnifxError, isLiteMaterialPluginPoint, isSceneFileHeader, isUlid, isValidErrorCode, isWebGpuAvailable, jsonAssetLoader, layerMask, lerp, lerpAngleDegrees, map, moveTowards, optional, parseOverridePath, pbrMaterialDefinition, pingPong, platformInternals, quat, radToDeg, record, repeat, resetFrameSample, resolveEase, sceneFileJsonSchema, serializeComponent, serializeEntity, serializeScene, shaderMaterialDefinition, sign, smoothStep, standardMaterialDefinition, storageInternals, str, stringifySceneFile, textAssetLoader, toJsonSchema, u32, validateProps, validateSceneFile, validateValue, vec2, vec3, vec4, waitFixedUpdate, waitSeconds, waitSecondsRealtime, waitUntil, waitWhile, wrapAngleDegrees };
35382
+ //#region src/settings/settings-json.ts
35383
+ /**
35384
+ * The JSON form of project settings. Settings are read as written: `createApp` hands the project's
35385
+ * values to `validateProps` unencoded, so a `vec3` is `{ x, y, z }` and a `color` is
35386
+ * `{ r, g, b, a }`, not the scene file's arrays. Everything here describes that runtime form.
35387
+ */
35388
+ /**
35389
+ * Reports whether a value is a plain bag of named values.
35390
+ *
35391
+ * @param value - The candidate.
35392
+ * @returns `true` for a non-null, non-array object.
35393
+ */
35394
+ function isBag(value) {
35395
+ return typeof value === "object" && value !== null && !Array.isArray(value);
35396
+ }
35397
+ /**
35398
+ * Copies a value made of JSON data, dropping what JSON cannot carry.
35399
+ *
35400
+ * @param value - The value.
35401
+ * @returns The JSON copy, or `undefined` for a function, `undefined`, or a non-finite number.
35402
+ */
35403
+ function plainJson(value) {
35404
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
35405
+ if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
35406
+ if (Array.isArray(value)) return value.map((item) => plainJson(item) ?? null);
35407
+ if (isBag(value)) return entriesToJson(Object.entries(value), plainJson);
35408
+ }
35409
+ /**
35410
+ * Builds a JSON object from entries, leaving out the ones that convert to nothing.
35411
+ *
35412
+ * @param entries - The name and value pairs.
35413
+ * @param convert - How one value converts.
35414
+ * @returns The object.
35415
+ */
35416
+ function entriesToJson(entries, convert) {
35417
+ const object = {};
35418
+ for (const [name, value] of entries) {
35419
+ const converted = convert(value, name);
35420
+ if (converted !== void 0) object[name] = converted;
35421
+ }
35422
+ return object;
35423
+ }
35424
+ /**
35425
+ * Converts a runtime settings value into the JSON a settings file holds for it.
35426
+ *
35427
+ * @param field - The field the value belongs to.
35428
+ * @param value - The runtime value, such as a registered default.
35429
+ * @returns The JSON form, or `undefined` when the value does not fit the field.
35430
+ *
35431
+ * @internal
35432
+ */
35433
+ function settingsValueToJson(field, value) {
35434
+ const { spec } = field;
35435
+ switch (spec.kind) {
35436
+ case "vec2":
35437
+ case "vec3":
35438
+ case "vec4":
35439
+ case "quat": return isBag(value) ? entriesToJson(channelEntries(VECTOR_COMPONENTS.slice(0, spec.components), value), plainJson) : void 0;
35440
+ case "color": return isBag(value) ? entriesToJson(channelEntries(COLOR_CHANNELS, value), plainJson) : void 0;
35441
+ case "array": return Array.isArray(value) ? value.map((item) => settingsValueToJson(spec.item, item) ?? null) : void 0;
35442
+ case "record": {
35443
+ if (!isBag(value)) return;
35444
+ const object = {};
35445
+ for (const [name, sub] of Object.entries(spec.fields)) {
35446
+ const converted = settingsValueToJson(sub, value[name]);
35447
+ if (converted !== void 0) object[name] = converted;
35448
+ }
35449
+ return object;
35450
+ }
35451
+ case "map": return isBag(value) ? entriesToJson(Object.entries(value), (entry) => settingsValueToJson(spec.value, entry)) : void 0;
35452
+ case "optional": return value === null ? null : settingsValueToJson(spec.inner, value);
35453
+ case "entityRef":
35454
+ case "componentRef": return value === null ? null : void 0;
35455
+ case "asset":
35456
+ if (isBag(value) && typeof value["address"] === "string") return typeof value["type"] === "string" ? {
35457
+ address: value["address"],
35458
+ type: value["type"]
35459
+ } : { address: value["address"] };
35460
+ return value === null ? null : void 0;
35461
+ case "f32":
35462
+ case "f64":
35463
+ case "i32":
35464
+ case "u32":
35465
+ case "bool":
35466
+ case "str":
35467
+ case "enum":
35468
+ case "layerMask":
35469
+ case "curve":
35470
+ case "custom": return plainJson(value);
35471
+ default: return assertNever(spec, "schema field kind");
35472
+ }
35473
+ }
35474
+ /**
35475
+ * Pairs each channel name with the value's channel.
35476
+ *
35477
+ * @param names - The channel names.
35478
+ * @param value - The vector or colour.
35479
+ * @returns The pairs, in channel order.
35480
+ */
35481
+ function channelEntries(names, value) {
35482
+ return names.map((name) => [name, value[name]]);
35483
+ }
35484
+ /**
35485
+ * The object schema of channel values, every channel required.
35486
+ *
35487
+ * @param names - The channel names.
35488
+ * @param channel - The schema of one channel.
35489
+ * @returns The fragment.
35490
+ */
35491
+ function channelsSchema(names, channel) {
35492
+ return {
35493
+ type: "object",
35494
+ properties: Object.fromEntries(names.map((name) => [name, channel])),
35495
+ required: [...names]
35496
+ };
35497
+ }
35498
+ /**
35499
+ * Builds the JSON Schema of one settings field in the form `createApp` reads, with its default, its
35500
+ * tooltip, its bounds and the `x-ignifx-*` inspector keywords.
35501
+ *
35502
+ * @param field - The field.
35503
+ * @param defaultValue - The runtime default to annotate it with, or `undefined` for none.
35504
+ * @returns The fragment.
35505
+ *
35506
+ * @internal
35507
+ */
35508
+ function settingsFieldJsonSchema(field, defaultValue) {
35509
+ const fragment = { ...settingsKindJsonSchema(field) };
35510
+ const { tooltip, min, max, step, hidden, readonly, group } = field.options;
35511
+ const annotations = {
35512
+ description: tooltip,
35513
+ minimum: min,
35514
+ maximum: max,
35515
+ "x-ignifx-step": step,
35516
+ "x-ignifx-hidden": hidden,
35517
+ "x-ignifx-readonly": readonly,
35518
+ "x-ignifx-group": group,
35519
+ default: defaultValue === void 0 ? void 0 : settingsValueToJson(field, defaultValue)
35520
+ };
35521
+ for (const [keyword, value] of Object.entries(annotations)) if (value !== void 0) fragment[keyword] = value;
35522
+ return fragment;
35523
+ }
35524
+ /**
35525
+ * Builds the object schema of a group of settings fields: every field optional, no other key.
35526
+ *
35527
+ * @param fields - The fields.
35528
+ * @param defaults - The runtime defaults by field name; a field without one carries no `default`.
35529
+ * @returns The fragment.
35530
+ *
35531
+ * @internal
35532
+ */
35533
+ function settingsObjectJsonSchema(fields, defaults) {
35534
+ const properties = {};
35535
+ for (const [name, field] of Object.entries(fields)) properties[name] = settingsFieldJsonSchema(field, defaults[name]);
35536
+ return {
35537
+ type: "object",
35538
+ properties,
35539
+ additionalProperties: false
35540
+ };
35541
+ }
35542
+ /**
35543
+ * Builds the fragment that constrains a field's runtime form, mirroring `validateProps`.
35544
+ *
35545
+ * @param field - The field.
35546
+ * @returns The fragment, without annotations.
35547
+ */
35548
+ function settingsKindJsonSchema(field) {
35549
+ const { spec } = field;
35550
+ switch (spec.kind) {
35551
+ case "f32":
35552
+ case "f64": return { type: "number" };
35553
+ case "i32": return {
35554
+ type: "integer",
35555
+ minimum: -2147483648,
35556
+ maximum: 2147483647
35557
+ };
35558
+ case "u32": return {
35559
+ type: "integer",
35560
+ minimum: 0,
35561
+ maximum: 4294967295
35562
+ };
35563
+ case "bool": return { type: "boolean" };
35564
+ case "str": return { type: "string" };
35565
+ case "enum": return {
35566
+ type: "string",
35567
+ enum: [...spec.values]
35568
+ };
35569
+ case "vec2":
35570
+ case "vec3":
35571
+ case "vec4":
35572
+ case "quat": return channelsSchema(VECTOR_COMPONENTS.slice(0, spec.components), { type: "number" });
35573
+ case "color": return channelsSchema(COLOR_CHANNELS, {
35574
+ type: "number",
35575
+ minimum: 0,
35576
+ maximum: 1
35577
+ });
35578
+ case "entityRef":
35579
+ case "componentRef": return { oneOf: [{ type: "object" }, { type: "null" }] };
35580
+ case "asset": return { oneOf: [{
35581
+ type: "object",
35582
+ properties: { address: { type: "string" } },
35583
+ required: ["address"]
35584
+ }, { type: "null" }] };
35585
+ case "array": return {
35586
+ type: "array",
35587
+ items: settingsFieldJsonSchema(spec.item, void 0)
35588
+ };
35589
+ case "record": return settingsObjectJsonSchema(spec.fields, {});
35590
+ case "map": return {
35591
+ type: "object",
35592
+ additionalProperties: settingsFieldJsonSchema(spec.value, void 0)
35593
+ };
35594
+ case "optional": return { anyOf: [settingsFieldJsonSchema(spec.inner, void 0), { type: "null" }] };
35595
+ case "layerMask": return {
35596
+ type: "array",
35597
+ items: { type: "string" }
35598
+ };
35599
+ case "curve": return {
35600
+ type: "object",
35601
+ properties: { keys: {
35602
+ type: "array",
35603
+ items: {
35604
+ type: "array",
35605
+ items: { type: "number" },
35606
+ minItems: 4,
35607
+ maxItems: 4
35608
+ }
35609
+ } },
35610
+ required: ["keys"]
35611
+ };
35612
+ case "custom": return {};
35613
+ default: return assertNever(spec, "schema field kind");
35614
+ }
35615
+ }
35616
+ //#endregion
35617
+ //#region src/settings/describe-settings.ts
35618
+ /**
35619
+ * The `format` every settings section description carries, so a consumer that merges settings and
35620
+ * component descriptions can tell them apart.
35621
+ *
35622
+ * @public
35623
+ */
35624
+ const SETTINGS_DESCRIPTION_FORMAT = "settings";
35625
+ /**
35626
+ * Whether a single field of each kind may stand for its whole section: a one-field section may be
35627
+ * written as the field's value (`layers: ["Default"]`) only when that value cannot be mistaken for
35628
+ * the section's object form, so a kind whose runtime form may be an object (a vector or colour is
35629
+ * `{ x, y, z }` or `{ r, g, b, a }` in settings) never qualifies.
35630
+ */
35631
+ const ALLOWS_SHORTHAND = {
35632
+ f32: true,
35633
+ f64: true,
35634
+ i32: true,
35635
+ u32: true,
35636
+ bool: true,
35637
+ str: true,
35638
+ vec2: false,
35639
+ vec3: false,
35640
+ vec4: false,
35641
+ quat: false,
35642
+ color: false,
35643
+ enum: true,
35644
+ array: true,
35645
+ layerMask: true,
35646
+ entityRef: false,
35647
+ componentRef: false,
35648
+ asset: false,
35649
+ record: false,
35650
+ map: false,
35651
+ optional: false,
35652
+ curve: false,
35653
+ custom: false
35654
+ };
35655
+ /**
35656
+ * Reaches the settings table behind `app.settings`.
35657
+ *
35658
+ * @param app - The app.
35659
+ * @returns The table.
35660
+ * @throws IgnifxError with code `IGX-0702` when the app was not created by this copy of core.
35661
+ */
35662
+ function settingsStoreOf(app) {
35663
+ const { settings } = app;
35664
+ if (settings instanceof SettingsStore) return settings;
35665
+ throw new IgnifxError(CoreErrorCode.invalidRuntime, "app.settings was not created by this copy of @ignifx/core.", {
35666
+ context: { member: "app.settings" },
35667
+ hint: "Describe the settings of an app createApp returned."
35668
+ });
35669
+ }
35670
+ /**
35671
+ * Describes one section, with the defaults its owner registered rather than the schema's own field
35672
+ * defaults, because the registered bag is what the project gets for a value it omits.
35673
+ *
35674
+ * @param name - The section name.
35675
+ * @param section - The registered section.
35676
+ * @returns The description.
35677
+ */
35678
+ function describeSection(name, section) {
35679
+ const described = describeSchema(name, section.schema, {
35680
+ title: name,
35681
+ format: SETTINGS_DESCRIPTION_FORMAT,
35682
+ package: section.owner
35683
+ });
35684
+ const fields = {};
35685
+ for (const [fieldName, field] of Object.entries(section.schema)) {
35686
+ const description = described.fields[fieldName];
35687
+ if (description !== void 0) fields[fieldName] = settingsFieldDescription(field, description, section.defaults[fieldName]);
35688
+ }
35689
+ return {
35690
+ ...described,
35691
+ fields
35692
+ };
35693
+ }
35694
+ /**
35695
+ * Rewrites a field description's defaults, at every depth, into the runtime form settings are
35696
+ * written in: `{ x, y, z }` rather than the scene file's `[x, y, z]`.
35697
+ *
35698
+ * @param field - The field.
35699
+ * @param description - Its description, with defaults in the scene-file form.
35700
+ * @param value - The runtime default, or `undefined` to leave `default` off.
35701
+ * @returns The description in the settings form.
35702
+ */
35703
+ function settingsFieldDescription(field, description, value) {
35704
+ const { default: _encoded, item, fields, value: entry, inner, ...rest } = description;
35705
+ const { spec } = field;
35706
+ const converted = value === void 0 ? void 0 : settingsValueToJson(field, value);
35707
+ const nested = {};
35708
+ if (spec.kind === "array" && item !== void 0) nested.item = settingsFieldDescription(spec.item, item, spec.item.createDefault());
35709
+ else if (spec.kind === "map" && entry !== void 0) nested.value = settingsFieldDescription(spec.value, entry, spec.value.createDefault());
35710
+ else if (spec.kind === "optional" && inner !== void 0) nested.inner = settingsFieldDescription(spec.inner, inner, spec.inner.createDefault());
35711
+ else if (spec.kind === "record" && fields !== void 0) {
35712
+ nested.fields = {};
35713
+ for (const [name, sub] of Object.entries(spec.fields)) {
35714
+ const subDescription = fields[name];
35715
+ if (subDescription !== void 0) nested.fields[name] = settingsFieldDescription(sub, subDescription, sub.createDefault());
35716
+ }
35717
+ }
35718
+ return {
35719
+ ...rest,
35720
+ ...converted === void 0 ? {} : { default: converted },
35721
+ ...nested
35722
+ };
35723
+ }
35724
+ /**
35725
+ * Describes every project settings section an app has registered (core's own `layers`,
35726
+ * `sortingLayers`, `time`, `assets` and `rendering`, and every section an extension declared with
35727
+ * `ctx.registerSettings`) in the same shape {@link describeRegisteredSchemas} describes components.
35728
+ * This is what an external settings panel, such as the ignifx editor's, is generated from.
35729
+ *
35730
+ * @remarks
35731
+ * Each entry is keyed and titled by its section name, has `format: "settings"`
35732
+ * ({@link SETTINGS_DESCRIPTION_FORMAT}), and names the extension that registered it as `package`
35733
+ * (`@ignifx/core`, `@ignifx/physics`). A field's `default` is the value the owner registered for it,
35734
+ * which is what the project gets when it omits the field; a field the owner's defaults leave out has
35735
+ * no `default`, because the resolved section has no value for it either.
35736
+ *
35737
+ * Defaults are in the **settings form**, the form `createApp` reads, which differs from the scene
35738
+ * file's for vectors and colours: a `vec3` default is `{ "x": 0, "y": -9.81, "z": 0 }` and a `color`
35739
+ * default is `{ "r": 0, "g": 0, "b": 0, "a": 1 }`, not an array. A tool writes values back in this
35740
+ * form.
35741
+ *
35742
+ * The registration seam is `ctx.registerSettings(section, schema, defaults)`: an extension that
35743
+ * declares a section there is described here with no further work. A section is written in project
35744
+ * settings (`ignifx.settings.json` or `ignifx.config.ts`) as an object of these fields; a section
35745
+ * with exactly one field of a non-object kind (a number, string, enum or array, not a vector or
35746
+ * colour) may also be written as that field's value.
35747
+ *
35748
+ * @param app - The app whose sections to describe; its extensions have all registered by the time
35749
+ * `createApp` resolves.
35750
+ * @returns The descriptions, keyed by section name, in registration order.
35751
+ * @throws IgnifxError with code `IGX-0702` when `app` was not created by this copy of
35752
+ * `@ignifx/core`.
35753
+ *
35754
+ * @example
35755
+ * ```ts
35756
+ * const sections = describeSettings(app);
35757
+ * sections["time"]?.package; // "@ignifx/core"
35758
+ * sections["time"]?.fields["fixedDeltaTime"]?.default; // 0.016666666666666666
35759
+ * ```
35760
+ *
35761
+ * @public
35762
+ */
35763
+ function describeSettings(app) {
35764
+ const described = {};
35765
+ for (const [name, section] of settingsStoreOf(app).registrations()) described[name] = describeSection(name, section);
35766
+ return described;
35767
+ }
35768
+ /**
35769
+ * The JSON Schema of one section as project settings may write it: the object form, or, for a
35770
+ * single field of a non-object kind, also that field's value on its own.
35771
+ *
35772
+ * @param section - The registered section.
35773
+ * @returns The fragment.
35774
+ */
35775
+ function sectionJsonSchema(section) {
35776
+ const { schema, defaults } = section;
35777
+ const objectForm = settingsObjectJsonSchema(schema, defaults);
35778
+ const entries = Object.entries(schema);
35779
+ const [only] = entries;
35780
+ if (entries.length !== 1 || only === void 0 || !ALLOWS_SHORTHAND[only[1].kind]) return objectForm;
35781
+ return { oneOf: [objectForm, settingsFieldJsonSchema(only[1], defaults[only[0]])] };
35782
+ }
35783
+ /**
35784
+ * Generates the JSON Schema (draft 2020-12) of a project's settings object, the content of
35785
+ * `ignifx.settings.json`, from every section the app registered. Pass it to the Vite plugin as
35786
+ * `ignifx({ schemas: { settings } })` to validate the project settings at build time, or associate
35787
+ * it with `ignifx.settings.json` in a text editor.
35788
+ *
35789
+ * @remarks
35790
+ * The schema describes the settings form `createApp` reads (vectors as `{ x, y, z }`, colours as
35791
+ * `{ r, g, b, a }` with every channel required), so a document it accepts also passes `createApp`'s
35792
+ * own validation (`IGX-0408`). Every section is optional and a section omitted takes its defaults.
35793
+ * An unknown key inside a section is a violation. The top level stays open: a section this app did
35794
+ * not register, perhaps one of an extension it lacks, is left to `createApp`, which reports it
35795
+ * (`IGX-0407`), and to the Vite plugin, which warns about it.
35796
+ *
35797
+ * @param app - The app whose sections to describe.
35798
+ * @returns The object schema, one property per section.
35799
+ * @throws IgnifxError with code `IGX-0702` when `app` was not created by this copy of
35800
+ * `@ignifx/core`.
35801
+ *
35802
+ * @example
35803
+ * ```ts
35804
+ * const schema = settingsJsonSchema(app);
35805
+ * Object.keys(schema["properties"] ?? {}); // ["layers", "sortingLayers", "time", "assets", "rendering"]
35806
+ * ```
35807
+ *
35808
+ * @public
35809
+ */
35810
+ function settingsJsonSchema(app) {
35811
+ const properties = {};
35812
+ for (const [name, section] of settingsStoreOf(app).registrations()) properties[name] = sectionJsonSchema(section);
35813
+ return {
35814
+ type: "object",
35815
+ properties
35816
+ };
35817
+ }
35818
+ //#endregion
35819
+ export { ASSET_DIAGNOSTICS_COUNTERS, ASSET_DIAGNOSTICS_GROUP, ASSET_MANIFEST_FORMAT, ASSET_MANIFEST_VERSION, AssetLoadError, CANVAS_ALPHA_MODES, CORE_ERROR_MESSAGES, Camera, Color, Component, ComponentRegistry, CoreErrorCode, DEFAULT_ASSET_CONCURRENCY, DEFAULT_ASSET_ROOT, DEFAULT_BRDF_LUT_ADDRESS, DEFAULT_LAYER, DEFAULT_MEMORY_SINK_LIMIT, DEFAULT_STORAGE_NAMESPACE, DEG_TO_RAD, Diagnostics, EASINGS, EASING_NAMES, EMPTY_ASSET_MANIFEST, ENVIRONMENT_ASSET_TYPE, ENVIRONMENT_FILE_EXTENSION, ENVIRONMENT_FILE_EXTENSIONS, ENVIRONMENT_FILE_FORMAT, ENVIRONMENT_FORMAT_VERSION, EPSILON, Entity, Environment, EnvironmentAsset, ErrorRange, FOG_MODE_NAMES, FONT_ASSET_TYPE, FONT_FILE_EXTENSIONS, FRAME_HISTORY_LENGTH, FieldKind, FontAsset, IGNIFX_UNIFORM_NAMES, INVALID_HANDLE, IgnifxError, IndexedDbStorageBackend, InstancedMeshRenderer, LIGHT_TYPES, LITE_MATERIAL_PLUGIN_POINTS, LITE_SYSTEM_UNIFORM_NAMES, LOG_LEVEL_SEVERITY, LayerMask, LayerTable, Light, LogLevel, MAT4_IDENTITY, MATERIAL_ALPHA_MODES, MATERIAL_ASSET_TYPE, MATERIAL_FILE_EXTENSION, MATERIAL_FILE_FORMAT, MATERIAL_FORMAT_VERSION, MATERIAL_KINDS, MATERIAL_PLUGIN_DEFAULT_PRIORITY, MATERIAL_PLUGIN_RESERVED_NAMES, MATERIAL_PLUGIN_SAMPLER_BUDGET, MAX_LAYERS, MAX_ULID_TIME_MS, MESH_ASSET_TYPE, MESH_FILE_EXTENSION, MESH_FILE_FORMAT, MESH_FORMAT_VERSION, MESH_PRIMITIVES, MESH_PRIMITIVE_OPTIONS, MODEL_ASSET_TYPE, MODEL_FILE_EXTENSIONS, Mat4, MaterialAsset, MemoryStorageBackend, MeshAsset, MeshRenderer, Model, ModelAsset, NAMESPACE_SEGMENT_MAX_LENGTH, PBR_TEXTURE_SLOTS, PHASES, PHASE_COUNT, PHASE_NAMES, POST_EFFECT_BUILTIN_UNIFORMS, POST_EFFECT_FUNCTION, PROJECTIONS, Phase, PhysicsCallbackName, PostProcessStack, QUAT_IDENTITY, Quat, RAD_TO_DEG, RENDERING_SETTINGS_SECTION, RENDER_DIAGNOSTICS_COUNTERS, RENDER_DIAGNOSTICS_GROUP, RESERVED_LAYER_NAMES, SCENE_ASSET_TYPE, SCENE_FILE_EXTENSIONS, SCENE_FILE_FORMAT, SCENE_FORMAT_VERSION, SETTINGS_DESCRIPTION_FORMAT, SHADER_ASSET_TYPE, SHADER_ATTRIBUTE_NAMES, SHADER_BLEND_MODES, SHADER_CULL_MODES, SHADER_FILE_EXTENSIONS, SHADER_INSTANCING_MODES, SHADER_KINDS, SHADER_TEXTURE_FALLBACKS, SHADER_UNIFORM_TYPES, SHADOW_TECHNIQUES, STANDARD_TEXTURE_SLOTS, STORAGE_BUFFER_ASSET_TYPE, STORAGE_KEY_MAX_LENGTH, SURFACE_HOOK_NAMES, SURFACE_UNIFORM_BLOCK, SceneAssetToken, SceneInstance, SchemaIssueCode, Script, ScriptCallbackKind, ShaderAsset, Signal, StorageBufferAsset, TEXTURE_ASSET_TYPE, THIRD_PARTY_ERROR_PREFIX, TONE_MAPPING_NAMES, TWEEN_LOOP_FOREVER, TWEEN_SYSTEM_ORDER, TWEEN_VALUE_KINDS, TagSet, TextureAsset, Transform, Tween, UidRemap, VEC2_ONE, VEC2_ZERO, VEC3_BACKWARD, VEC3_DOWN, VEC3_FORWARD, VEC3_LEFT, VEC3_ONE, VEC3_RIGHT, VEC3_UP, VEC3_ZERO, VERSION, Vec2, Vec3, Vec4, World, addComponentFromRecord, applyInit, approximately, array, assertNever, assertSceneDependenciesLoaded, asset, assetRef, binaryAssetLoader, bool, canonicalizeNumber, clamp, clamp01, color, componentRef, computeSceneHash, coreExtension, createApp, createAssetManifest, createConsoleSink, createCryptoRandom, createDefaults, createDiagnosticsGroup, createEnvironmentLoader, createErrorCodeRegistry, createFileStorageBackend, createFontLoader, createFrameSample, createLayerTable, createLogger, createManualClock, createMaterialAsset, createMaterialLoader, createMemorySink, createMeshLoader, createModelLoader, createPerformanceClock, createRay, createSceneAsset, createSceneLoader, createSeededRandom, createServiceKey, createShaderLoader, createStorageBufferAsset, createTextureLoader, createUlidFactory, curve, custom, customEffect, decodeProps, decodeValue, defaultRenderingSettings, defineExtension, defineMaterialPlugin, defineSchema, degToRad, deltaAngleDegrees, describeEnvironmentFileFormat, describeMaterialFileFormat, describeMeshFileFormat, describeRegisteredSchemas, describeSceneFileFormat, describeSchema, describeSchemas, describeSettings, encodeProps, encodeValue, entityRef, enumOf, environmentDefinition, f32, f64, forceRendererDeviceLossForTesting, formatErrorMessage, generateUlid, i32, instantiateScene, inverseLerp, isAssetRef, isIgnifxError, isLiteMaterialPluginPoint, isSceneFileHeader, isUlid, isValidErrorCode, isWebGpuAvailable, jsonAssetLoader, layerMask, lerp, lerpAngleDegrees, loadSceneDependencies, map, meshFileJsonSchema, moveTowards, optional, parseOverridePath, pbrMaterialDefinition, pingPong, platformInternals, quat, radToDeg, record, repeat, resetFrameSample, resolveEase, sceneFileJsonSchema, serializeComponent, serializeEntity, serializeScene, settingsJsonSchema, shaderMaterialDefinition, sign, smoothStep, standardMaterialDefinition, storageInternals, str, stringifySceneFile, textAssetLoader, toJsonSchema, transformSchema, u32, validateProps, validateSceneFile, validateValue, vec2, vec3, vec4, waitFixedUpdate, waitSeconds, waitSecondsRealtime, waitUntil, waitWhile, wrapAngleDegrees };
33682
35820
 
33683
35821
  //# sourceMappingURL=index.js.map