@forgeax/engine-render 0.1.34 → 0.1.36

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 (273) hide show
  1. package/README.md +69 -3
  2. package/dist/assembly/device-feature-admission.d.ts +2 -2
  3. package/dist/assembly/host-contract.d.ts +3 -2
  4. package/dist/assembly/host-contract.d.ts.map +1 -1
  5. package/dist/assembly/recovery/renderer-recover.d.ts.map +1 -1
  6. package/dist/assembly/render-target-host.d.ts +5 -0
  7. package/dist/assembly/render-target-host.d.ts.map +1 -1
  8. package/dist/assembly/renderer-facade.d.ts.map +1 -1
  9. package/dist/assembly/webgpu-renderer.d.ts +1 -0
  10. package/dist/assembly/webgpu-renderer.d.ts.map +1 -1
  11. package/dist/assembly/webgpu-vertex-layouts.d.ts.map +1 -1
  12. package/dist/authoring.mjs +2 -4
  13. package/dist/authoring.mjs.map +1 -1
  14. package/dist/chunk-2OZAS3WU.mjs +3489 -0
  15. package/dist/chunk-2OZAS3WU.mjs.map +1 -0
  16. package/dist/{chunk-UI5SFODX.mjs → chunk-BZQ4CDRF.mjs} +2338 -1991
  17. package/dist/chunk-BZQ4CDRF.mjs.map +1 -0
  18. package/dist/{chunk-MKDIT2EM.mjs → chunk-CJOV2XLO.mjs} +216 -261
  19. package/dist/chunk-CJOV2XLO.mjs.map +1 -0
  20. package/dist/chunk-D6WSBXJ2.mjs +1842 -0
  21. package/dist/chunk-D6WSBXJ2.mjs.map +1 -0
  22. package/dist/{chunk-HEB564WF.mjs → chunk-DRF6OULX.mjs} +4 -4
  23. package/dist/{chunk-HEB564WF.mjs.map → chunk-DRF6OULX.mjs.map} +1 -1
  24. package/dist/{chunk-OCDLEI6I.mjs → chunk-OB5WAFYH.mjs} +117 -5
  25. package/dist/chunk-OB5WAFYH.mjs.map +1 -0
  26. package/dist/{chunk-ODZWR6JQ.mjs → chunk-OEYKKMXG.mjs} +2042 -27
  27. package/dist/chunk-OEYKKMXG.mjs.map +1 -0
  28. package/dist/chunk-RIPAEGI6.mjs +48 -0
  29. package/dist/chunk-RIPAEGI6.mjs.map +1 -0
  30. package/dist/{chunk-ELJFJ2BU.mjs → chunk-X2KA6WHM.mjs} +29 -4
  31. package/dist/chunk-X2KA6WHM.mjs.map +1 -0
  32. package/dist/{chunk-BLXGONR2.mjs → chunk-XSFB7XXQ.mjs} +51 -4
  33. package/dist/chunk-XSFB7XXQ.mjs.map +1 -0
  34. package/dist/cloud/frame-context.d.ts +2 -2
  35. package/dist/cloud/frame-context.d.ts.map +1 -1
  36. package/dist/construct-renderer.mjs +936 -2140
  37. package/dist/construct-renderer.mjs.map +1 -1
  38. package/dist/device/device-scope.d.ts.map +1 -1
  39. package/dist/device/gpu-residency.d.ts +19 -19
  40. package/dist/device/gpu-residency.d.ts.map +1 -1
  41. package/dist/errors/render.d.ts +3 -2
  42. package/dist/errors/render.d.ts.map +1 -1
  43. package/dist/extract/material-context.d.ts +7 -0
  44. package/dist/extract/material-context.d.ts.map +1 -0
  45. package/dist/features/host.d.ts +5 -0
  46. package/dist/features/host.d.ts.map +1 -1
  47. package/dist/features/particle-mesh-layout.d.ts +19 -0
  48. package/dist/features/particle-mesh-layout.d.ts.map +1 -0
  49. package/dist/features/plan.d.ts +2 -0
  50. package/dist/features/plan.d.ts.map +1 -1
  51. package/dist/features/types.d.ts +8 -0
  52. package/dist/features/types.d.ts.map +1 -1
  53. package/dist/glyph-text-layout-system.d.ts +1 -1
  54. package/dist/glyph-text-layout-system.d.ts.map +1 -1
  55. package/dist/gpu-driven/production-raster.d.ts +1 -1
  56. package/dist/gpu-driven/production-raster.d.ts.map +1 -1
  57. package/dist/gpu-driven/shadow-ownership.d.ts +3 -3
  58. package/dist/gpu-driven/shadow-ownership.d.ts.map +1 -1
  59. package/dist/gpu-driven/shadow-views.d.ts +1 -1
  60. package/dist/gpu-driven/shadow-views.d.ts.map +1 -1
  61. package/dist/gpu-driven/view-gpu.d.ts +1 -1
  62. package/dist/gpu-driven/view-gpu.d.ts.map +1 -1
  63. package/dist/ibl/frame-resources.d.ts.map +1 -1
  64. package/dist/ibl/skylight-bind-group.d.ts +4 -4
  65. package/dist/ibl/skylight-bind-group.d.ts.map +1 -1
  66. package/dist/index.d.ts +3 -0
  67. package/dist/index.d.ts.map +1 -1
  68. package/dist/index.mjs +542 -9
  69. package/dist/index.mjs.map +1 -1
  70. package/dist/instances.d.ts +3 -4
  71. package/dist/instances.d.ts.map +1 -1
  72. package/dist/internal.mjs +7 -8
  73. package/dist/internal.mjs.map +1 -1
  74. package/dist/pbr-pipeline.d.ts +3 -3
  75. package/dist/pbr-pipeline.d.ts.map +1 -1
  76. package/dist/pipeline/standard-output/lut-gpu.d.ts +2 -2
  77. package/dist/pipeline/standard-output/lut-gpu.d.ts.map +1 -1
  78. package/dist/pipeline/standard-output/resources.d.ts +2 -2
  79. package/dist/pipeline/standard-output/resources.d.ts.map +1 -1
  80. package/dist/publication/contract.d.ts +77 -0
  81. package/dist/publication/contract.d.ts.map +1 -0
  82. package/dist/publication/dependencies.d.ts +7 -0
  83. package/dist/publication/dependencies.d.ts.map +1 -0
  84. package/dist/publication/prepare-geometry.d.ts +9 -0
  85. package/dist/publication/prepare-geometry.d.ts.map +1 -0
  86. package/dist/publication/programs.d.ts +5 -0
  87. package/dist/publication/programs.d.ts.map +1 -0
  88. package/dist/publication/publisher.d.ts +34 -0
  89. package/dist/publication/publisher.d.ts.map +1 -0
  90. package/dist/publication/receiver.d.ts +29 -0
  91. package/dist/publication/receiver.d.ts.map +1 -0
  92. package/dist/publication/resource-scope.d.ts +18 -0
  93. package/dist/publication/resource-scope.d.ts.map +1 -0
  94. package/dist/publication/targets.d.ts +33 -0
  95. package/dist/publication/targets.d.ts.map +1 -0
  96. package/dist/publication/video.d.ts +5 -0
  97. package/dist/publication/video.d.ts.map +1 -0
  98. package/dist/record/fold-buckets.d.ts +3 -3
  99. package/dist/record/fold-buckets.d.ts.map +1 -1
  100. package/dist/record/frame-snapshot.d.ts +6 -6
  101. package/dist/record/frame-snapshot.d.ts.map +1 -1
  102. package/dist/record/frame.d.ts +5 -4
  103. package/dist/record/frame.d.ts.map +1 -1
  104. package/dist/record/helpers.d.ts +2 -2
  105. package/dist/record/helpers.d.ts.map +1 -1
  106. package/dist/record/main-pass-geometry.d.ts +2 -2
  107. package/dist/record/main-pass-geometry.d.ts.map +1 -1
  108. package/dist/record/main-pass-material.d.ts +7 -9
  109. package/dist/record/main-pass-material.d.ts.map +1 -1
  110. package/dist/record/main-pass-sprite-draws.d.ts +3 -16
  111. package/dist/record/main-pass-sprite-draws.d.ts.map +1 -1
  112. package/dist/record/main-pass.d.ts.map +1 -1
  113. package/dist/record/prepared-material-bindings.d.ts +2 -3
  114. package/dist/record/prepared-material-bindings.d.ts.map +1 -1
  115. package/dist/record/render-context.d.ts +4 -2
  116. package/dist/record/render-context.d.ts.map +1 -1
  117. package/dist/record/shadow-pass.d.ts +2 -2
  118. package/dist/record/shadow-pass.d.ts.map +1 -1
  119. package/dist/record/sprite-instance-buffer.d.ts +31 -0
  120. package/dist/record/sprite-instance-buffer.d.ts.map +1 -0
  121. package/dist/record/target-capture-graph.d.ts +19 -0
  122. package/dist/record/target-capture-graph.d.ts.map +1 -0
  123. package/dist/record/typed-frame-graph.d.ts +2 -13
  124. package/dist/record/typed-frame-graph.d.ts.map +1 -1
  125. package/dist/record/view-ubo.d.ts.map +1 -1
  126. package/dist/record/volume-params.d.ts +2 -2
  127. package/dist/record/volume-params.d.ts.map +1 -1
  128. package/dist/recovery/render-system-candidate.d.ts +5 -12
  129. package/dist/recovery/render-system-candidate.d.ts.map +1 -1
  130. package/dist/render-contract.d.ts +4 -1
  131. package/dist/render-contract.d.ts.map +1 -1
  132. package/dist/render-system-extract-tail.d.ts.map +1 -1
  133. package/dist/render-system-extract.d.ts +2 -0
  134. package/dist/render-system-extract.d.ts.map +1 -1
  135. package/dist/render-system-presentation.d.ts +2 -2
  136. package/dist/render-system-presentation.d.ts.map +1 -1
  137. package/dist/render-system-projections.d.ts +3 -2
  138. package/dist/render-system-projections.d.ts.map +1 -1
  139. package/dist/render-system-residency.d.ts +2 -2
  140. package/dist/render-system-residency.d.ts.map +1 -1
  141. package/dist/render-system.d.ts +3 -7
  142. package/dist/render-system.d.ts.map +1 -1
  143. package/dist/scene/render-scene.d.ts +8 -4
  144. package/dist/scene/render-scene.d.ts.map +1 -1
  145. package/dist/scene/render-source.d.ts +42 -0
  146. package/dist/scene/render-source.d.ts.map +1 -0
  147. package/dist/scene/source-systems.d.ts +6 -0
  148. package/dist/scene/source-systems.d.ts.map +1 -0
  149. package/dist/systems/skin-palette-allocator.d.ts.map +1 -1
  150. package/dist/systems/skin-palette-types.d.ts +10 -0
  151. package/dist/systems/skin-palette-types.d.ts.map +1 -1
  152. package/dist/systems/transparent-dispatch.d.ts +2 -2
  153. package/dist/systems/transparent-dispatch.d.ts.map +1 -1
  154. package/dist/systems/transparent-sort-config.d.ts +2 -1
  155. package/dist/systems/transparent-sort-config.d.ts.map +1 -1
  156. package/dist/temporal/index.mjs +6 -7
  157. package/dist/typed-shadow-passes.d.ts.map +1 -1
  158. package/package.json +21 -21
  159. package/src/__tests__/auto-exposure-transaction.integration.test.ts +4 -9
  160. package/src/__tests__/device-feature-admission.unit.test.ts +3 -2
  161. package/src/__tests__/device-scope-lifecycle.unit.test.ts +26 -0
  162. package/src/__tests__/gpu-driven-pbr.dawn.test.ts +3 -4
  163. package/src/__tests__/gpu-driven-production.integration.test.ts +18 -1
  164. package/src/__tests__/gpu-driven-shadow-views.unit.test.ts +23 -0
  165. package/src/__tests__/ktx2-basis-gpu-consumer.dawn.test.ts +4 -1
  166. package/src/__tests__/main-pass-material-medium-selection.unit.test.ts +0 -1
  167. package/src/__tests__/material-vertex-texture.browser.test.ts +7 -0
  168. package/src/__tests__/material-vertex-texture.dawn.test.ts +7 -0
  169. package/src/__tests__/material-vertex-texture.fixture.ts +31 -0
  170. package/src/__tests__/materials-standard-contract.unit.test.ts +0 -1
  171. package/src/__tests__/physical-clearcoat.integration.test.ts +23 -23
  172. package/src/__tests__/physical-material-budget.unit.test.ts +40 -0
  173. package/src/__tests__/recovery-candidate-prepare.contract.test.ts +5 -0
  174. package/src/__tests__/render-error-code-owner.test-d.ts +1 -0
  175. package/src/__tests__/renderer-factory-material-contract.unit.test.ts +107 -5
  176. package/src/__tests__/runtime-material-program.integration.test.ts +79 -0
  177. package/src/__tests__/vertex-layouts-ssot.unit.test.ts +23 -3
  178. package/src/assembly/device-feature-admission.ts +2 -2
  179. package/src/assembly/host-contract.ts +5 -2
  180. package/src/assembly/recovery/renderer-recover.ts +9 -0
  181. package/src/assembly/render-target-host.ts +57 -47
  182. package/src/assembly/renderer-facade.ts +3 -1
  183. package/src/assembly/webgpu-ready.ts +1 -1
  184. package/src/assembly/webgpu-renderer.ts +101 -70
  185. package/src/assembly/webgpu-vertex-layouts.ts +2 -9
  186. package/src/cloud/frame-context.ts +2 -2
  187. package/src/device/device-scope.ts +3 -0
  188. package/src/device/gpu-residency.ts +26 -25
  189. package/src/errors/render.ts +3 -1
  190. package/src/extract/material-context.ts +21 -0
  191. package/src/features/host.ts +13 -5
  192. package/src/features/particle-mesh-layout.ts +25 -0
  193. package/src/features/plan.ts +2 -0
  194. package/src/features/types.ts +8 -0
  195. package/src/glyph-text-layout-system.ts +2 -2
  196. package/src/gpu-driven/production-raster.ts +9 -3
  197. package/src/gpu-driven/shadow-ownership.ts +3 -3
  198. package/src/gpu-driven/shadow-views.ts +27 -2
  199. package/src/gpu-driven/view-gpu.ts +5 -0
  200. package/src/ibl/frame-resources.ts +0 -1
  201. package/src/ibl/skylight-bind-group.ts +13 -25
  202. package/src/index.ts +9 -0
  203. package/src/instances.ts +9 -6
  204. package/src/pbr-pipeline.ts +15 -18
  205. package/src/pipeline/standard-output/lut-gpu.ts +3 -3
  206. package/src/pipeline/standard-output/resources.ts +2 -2
  207. package/src/publication/__tests__/derived-geometry.integration.test.ts +177 -0
  208. package/src/publication/__tests__/features.integration.test.ts +173 -0
  209. package/src/publication/__tests__/programs.unit.test.ts +25 -0
  210. package/src/publication/__tests__/publication.integration.test.ts +415 -0
  211. package/src/publication/__tests__/targets.integration.test.ts +120 -0
  212. package/src/publication/__tests__/video.browser.test.ts +50 -0
  213. package/src/publication/contract.ts +104 -0
  214. package/src/publication/dependencies.ts +54 -0
  215. package/src/publication/prepare-geometry.ts +94 -0
  216. package/src/publication/programs.ts +45 -0
  217. package/src/publication/publisher.ts +645 -0
  218. package/src/publication/receiver.ts +297 -0
  219. package/src/publication/resource-scope.ts +31 -0
  220. package/src/publication/targets.ts +182 -0
  221. package/src/publication/video.ts +33 -0
  222. package/src/record/__tests__/material-bg-cache.unit.test.ts +15 -1
  223. package/src/record/__tests__/prepared-runtime-material.integration.test.ts +134 -0
  224. package/src/record/__tests__/sprite-material-abi.unit.test.ts +8 -10
  225. package/src/record/__tests__/video-texture-view.unit.test.ts +9 -9
  226. package/src/record/fold-buckets.ts +8 -5
  227. package/src/record/frame-snapshot.ts +6 -6
  228. package/src/record/frame.ts +87 -28
  229. package/src/record/helpers.ts +2 -2
  230. package/src/record/main-pass-geometry.ts +21 -2
  231. package/src/record/main-pass-material.ts +37 -33
  232. package/src/record/main-pass-sprite-draws.ts +6 -152
  233. package/src/record/main-pass.ts +8 -7
  234. package/src/record/prepared-material-bindings.ts +16 -37
  235. package/src/record/render-context.ts +4 -2
  236. package/src/record/shadow-pass.ts +65 -7
  237. package/src/record/sprite-instance-buffer.ts +155 -0
  238. package/src/record/target-capture-graph.ts +258 -0
  239. package/src/record/typed-frame-graph.ts +11 -207
  240. package/src/record/view-ubo.ts +1 -1
  241. package/src/record/volume-params.ts +6 -6
  242. package/src/recovery/render-system-candidate.ts +10 -18
  243. package/src/render-contract.ts +6 -1
  244. package/src/render-system-extract-tail.ts +48 -23
  245. package/src/render-system-extract.ts +11 -2
  246. package/src/render-system-presentation.ts +2 -2
  247. package/src/render-system-projections.ts +3 -2
  248. package/src/render-system-residency.ts +2 -2
  249. package/src/render-system.ts +82 -54
  250. package/src/scene/render-scene.ts +110 -100
  251. package/src/scene/render-source.ts +90 -0
  252. package/src/scene/source-systems.ts +33 -0
  253. package/src/systems/skin-palette-allocator.ts +1 -0
  254. package/src/systems/skin-palette-types.ts +11 -0
  255. package/src/systems/transparent-dispatch.ts +2 -2
  256. package/src/systems/transparent-sort-config.ts +3 -1
  257. package/src/typed-shadow-passes.ts +36 -5
  258. package/dist/chunk-BLXGONR2.mjs.map +0 -1
  259. package/dist/chunk-ELJFJ2BU.mjs.map +0 -1
  260. package/dist/chunk-ILQ5MEZF.mjs +0 -32
  261. package/dist/chunk-ILQ5MEZF.mjs.map +0 -1
  262. package/dist/chunk-MKDIT2EM.mjs.map +0 -1
  263. package/dist/chunk-OCDLEI6I.mjs.map +0 -1
  264. package/dist/chunk-ODZWR6JQ.mjs.map +0 -1
  265. package/dist/chunk-RXZ3RGOU.mjs +0 -53
  266. package/dist/chunk-RXZ3RGOU.mjs.map +0 -1
  267. package/dist/chunk-SHFUFJ5N.mjs +0 -1781
  268. package/dist/chunk-SHFUFJ5N.mjs.map +0 -1
  269. package/dist/chunk-UI5SFODX.mjs.map +0 -1
  270. package/dist/chunk-UINHLCZA.mjs +0 -2389
  271. package/dist/chunk-UINHLCZA.mjs.map +0 -1
  272. package/dist/chunk-WEX45HKH.mjs +0 -1524
  273. package/dist/chunk-WEX45HKH.mjs.map +0 -1
@@ -0,0 +1,90 @@
1
+ import { RuntimeMaterialValue, RuntimeMeshVertices } from '@forgeax/engine-assets-runtime';
2
+ import type { Component, EntityHandle, Query, World } from '@forgeax/engine-ecs';
3
+ import { createStateProjection } from '@forgeax/engine-ecs/projection';
4
+ import { ChildOf, GlobalTransform, MorphWeights, Transform } from '@forgeax/engine-scene';
5
+ import { Skin } from '@forgeax/engine-skinning';
6
+ import {
7
+ Instances,
8
+ Layer,
9
+ Lines,
10
+ MeshFilter,
11
+ MeshRenderer,
12
+ Points,
13
+ SortKey,
14
+ SpriteInstances,
15
+ SpriteRegionOverride,
16
+ Visibility,
17
+ } from '../components';
18
+ export type GlobalTransformChangeQuery = Query<readonly [typeof GlobalTransform]>;
19
+
20
+ // Retained geometry consumes these component changes. Camera, lighting and
21
+ // environment facts are freshly extracted by deriveFramePlan on every draw;
22
+ // their edits must not recreate unrelated geometry or its submission history.
23
+ export const RENDERABLE_SOURCE_COMPONENTS = [
24
+ ChildOf,
25
+ MeshFilter,
26
+ MeshRenderer,
27
+ Instances,
28
+ SpriteInstances,
29
+ SpriteRegionOverride,
30
+ Skin,
31
+ Layer,
32
+ Visibility,
33
+ MorphWeights,
34
+ Points,
35
+ Lines,
36
+ SortKey,
37
+ ] as const;
38
+ export function createGlobalTransformChangeQuery(world: World): GlobalTransformChangeQuery {
39
+ const result = world.query({ read: [GlobalTransform], changed: [GlobalTransform] });
40
+ if (!result.ok) throw result.error;
41
+ const query = result.value as GlobalTransformChangeQuery;
42
+ for (const _span of query.spans().unwrap()) {
43
+ // The full rebuild consumed these values; establish the observation baseline.
44
+ }
45
+ return query;
46
+ }
47
+
48
+ export function createRenderSourceState(world: World, additional: readonly Component[] = []) {
49
+ // Numerical poses already have one span reader. Keep their table membership
50
+ // in this projection, without scanning their changed rows a second time.
51
+ const components = [
52
+ ...RENDERABLE_SOURCE_COMPONENTS,
53
+ RuntimeMaterialValue,
54
+ RuntimeMeshVertices,
55
+ ...additional,
56
+ ];
57
+ const projection = createStateProjection(world, components, [
58
+ ...components,
59
+ Transform,
60
+ GlobalTransform,
61
+ ]);
62
+ const entities = new Map<number, EntityHandle>();
63
+ const contentHandles = new Map<number, readonly number[]>();
64
+ const batch = projection.read();
65
+ for (const index of batch.indices) {
66
+ const entity = projection.entity(index);
67
+ if (entity !== undefined) {
68
+ entities.set(index, entity);
69
+ const handles: number[] = [];
70
+ const material = world.hasComponent(entity, RuntimeMaterialValue)
71
+ ? world.get(entity, RuntimeMaterialValue)
72
+ : undefined;
73
+ const mesh = world.hasComponent(entity, RuntimeMeshVertices)
74
+ ? world.get(entity, RuntimeMeshVertices)
75
+ : undefined;
76
+ if (material?.ok) handles.push(Number(material.value.asset));
77
+ if (mesh?.ok) handles.push(Number(mesh.value.asset));
78
+ if (handles.length > 0) contentHandles.set(index, handles);
79
+ }
80
+ }
81
+ return { projection, entities, contentHandles, batch };
82
+ }
83
+
84
+ export function isRenderableMember(world: World, entity: number): boolean {
85
+ return (
86
+ world.hasComponent(entity as EntityHandle, MeshRenderer) &&
87
+ world.hasComponent(entity as EntityHandle, Transform) &&
88
+ world.hasComponent(entity as EntityHandle, MeshFilter)
89
+ );
90
+ }
@@ -0,0 +1,33 @@
1
+ import type { AssetRegistry } from '@forgeax/engine-assets-runtime';
2
+ import { Update, type World } from '@forgeax/engine-ecs';
3
+ import { registerPropagateTransforms } from '@forgeax/engine-scene';
4
+ import type { GpuResidencyCache } from '../device/gpu-residency';
5
+ import { glyphTextLayoutSystem } from '../glyph-text-layout-system';
6
+ import { tilemapChunkExtractSystem } from '../tilemap-chunk-extract-system';
7
+
8
+ let nextId = 0;
9
+ /** Derived authoring stays beside World; only completed mesh data reaches the Renderer. */
10
+ export function registerRenderSourceSystems(
11
+ world: World,
12
+ assets: AssetRegistry,
13
+ meshes: Pick<GpuResidencyCache, 'updateMesh'>,
14
+ ): () => void {
15
+ const releaseTransforms = registerPropagateTransforms(world);
16
+ const name = `renderDerived:${++nextId}`;
17
+ const result = world.addSystem(Update, {
18
+ name,
19
+ queries: [],
20
+ fn: (world) => {
21
+ tilemapChunkExtractSystem(world, (guid) => assets.lookup(guid));
22
+ glyphTextLayoutSystem(world, meshes).unwrap();
23
+ },
24
+ });
25
+ if (!result.ok) {
26
+ releaseTransforms();
27
+ throw result.error;
28
+ }
29
+ return () => {
30
+ world.removeSystem(Update, name).unwrap();
31
+ releaseTransforms();
32
+ };
33
+ }
@@ -460,6 +460,7 @@ export function createSkinPaletteAllocator(
460
460
  }
461
461
 
462
462
  function releasePersistentSlice(identity: string): void {
463
+ frameSeenPersistent.delete(identity);
463
464
  const allocation = persistent.get(identity);
464
465
  persistent.delete(identity);
465
466
  pendingDirty.delete(identity);
@@ -1,3 +1,4 @@
1
+ import type { Mat4 } from '@forgeax/engine-math';
1
2
  import type { Buffer } from '@forgeax/engine-rhi';
2
3
 
3
4
  /**
@@ -29,3 +30,13 @@ export interface SkinPaletteReceipt extends SkinPaletteSlice {
29
30
  readonly uploadBytes: number;
30
31
  readonly retiredByteOffset?: number;
31
32
  }
33
+
34
+ /** Frozen source facts; GPU addresses are assigned only by the consuming Renderer. */
35
+ export interface SkinPose {
36
+ readonly identity: string;
37
+ readonly generation: number;
38
+ readonly jointCount: number;
39
+ readonly bounds?: Float32Array;
40
+ readonly inverseBindMatrices: readonly Float32Array[];
41
+ readonly jointWorlds: readonly Mat4[];
42
+ }
@@ -1,5 +1,5 @@
1
- import type { World } from '@forgeax/engine-ecs';
2
1
  import { RenderQueue } from '@forgeax/engine-types';
2
+ import type { RenderResourceScope } from '../publication/resource-scope';
3
3
  import type { CameraSnapshot } from '../render-contract';
4
4
  import type { DispatchEntry, RenderableSnapshot } from '../render-system-extract';
5
5
  import {
@@ -16,7 +16,7 @@ import {
16
16
  */
17
17
  export function sortTransparentDispatch(
18
18
  dispatch: DispatchEntry[],
19
- world: World,
19
+ world: RenderResourceScope,
20
20
  cameras: readonly CameraSnapshot[],
21
21
  renderables: readonly RenderableSnapshot[],
22
22
  ): DispatchEntry[] {
@@ -1,3 +1,4 @@
1
+ import type { RenderResourceScope } from '../publication/resource-scope';
1
2
  // @forgeax/engine-runtime - TransparentSortConfig KV resource + helpers.
2
3
  //
3
4
  // feat-20260520-2d-sprite-layer-mvp M-2 w14 / requirements AC-08 + AC-18
@@ -168,7 +169,8 @@ const HINT_MODE = '0=layer-z, 1=layer-y, 2=layer-yz, 3=distance';
168
169
  * const cfg = getTransparentSortConfig(world);
169
170
  * // cfg.mode === 1, cfg.yzAlpha === 1.0 (yzAlpha ignored by mode=1).
170
171
  */
171
- export function getTransparentSortConfig(world: World): TransparentSortConfig {
172
+ export function getTransparentSortConfig(world: RenderResourceScope): TransparentSortConfig {
173
+ if ('resolveAsset' in world) return world.transparentSort;
172
174
  if (!world.hasResource(TRANSPARENT_SORT_CONFIG_KEY)) {
173
175
  return DEFAULT_CONFIG;
174
176
  }
@@ -109,6 +109,13 @@ export function addTypedShadowPasses(
109
109
  index: cascade,
110
110
  });
111
111
  if (shadowProjection !== undefined && !shadowProjection.ok) return shadowProjection;
112
+ // Every pass in this freshly compiled graph owns a newly allocated
113
+ // raster target. Populate it once even when the producer cache hits or
114
+ // the GPU shadow projection is not admitted on this frame. The encoder
115
+ // receives the same one-shot fence so its cache-hit fast path cannot
116
+ // return before setting the atlas viewport and recording the casters.
117
+ let forceRasterPending = true;
118
+ let forceRasterEncodePending = false;
112
119
  const added = recordShadowPass(
113
120
  graph,
114
121
  `shadowCascade${cascade}`,
@@ -128,10 +135,20 @@ export function addTypedShadowPasses(
128
135
  shadowFeatures === undefined
129
136
  ? undefined
130
137
  : (view) => shadowFeatures.encode(pass, frame, resources, view),
138
+ forceRasterEncodePending,
131
139
  ),
132
- (frame) =>
133
- shadowFeatures !== undefined ||
134
- !shadowViewCacheReuse(frame, { kind: 'directional', index: cascade }),
140
+ (frame) => {
141
+ forceRasterEncodePending = false;
142
+ if (forceRasterPending) {
143
+ forceRasterPending = false;
144
+ forceRasterEncodePending = true;
145
+ return true;
146
+ }
147
+ return (
148
+ shadowFeatures !== undefined ||
149
+ !shadowViewCacheReuse(frame, { kind: 'directional', index: cascade })
150
+ );
151
+ },
135
152
  [
136
153
  ...(shadowProjection?.ok === true && shadowProjection.value?.graphResources !== undefined
137
154
  ? shadowViewRasterAccesses(shadowProjection.value.graphResources)
@@ -197,6 +214,7 @@ export function addTypedShadowPasses(
197
214
  face,
198
215
  });
199
216
  if (shadowProjection !== undefined && !shadowProjection.ok) return shadowProjection;
217
+ let forceRasterPending = true;
200
218
  const identity = { kind: 'point' as const, index: pointIndex, face };
201
219
  const cacheReuse = (frame: RenderPipelineFrame): boolean =>
202
220
  shadowViewCacheReuse(frame, identity);
@@ -228,7 +246,13 @@ export function addTypedShadowPasses(
228
246
  ? undefined
229
247
  : (view) => shadowFeatures.encode(pass, frame, resources, view),
230
248
  ),
231
- (frame) => shadowFeatures !== undefined || !cacheReuse(frame),
249
+ (frame) => {
250
+ if (forceRasterPending) {
251
+ forceRasterPending = false;
252
+ return true;
253
+ }
254
+ return shadowFeatures !== undefined || !cacheReuse(frame);
255
+ },
232
256
  [
233
257
  ...(shadowProjection?.ok === true &&
234
258
  shadowProjection.value?.graphResources !== undefined
@@ -250,6 +274,7 @@ export function addTypedShadowPasses(
250
274
  for (let spotIndex = 0; spotIndex < Math.max(1, topology.shadow.spotCount); spotIndex += 1) {
251
275
  const shadowProjection = projectGpuDrivenShadow?.({ kind: 'spot', index: spotIndex });
252
276
  if (shadowProjection !== undefined && !shadowProjection.ok) return shadowProjection;
277
+ let forceRasterPending = true;
253
278
  const identity = { kind: 'spot' as const, index: spotIndex };
254
279
  const cacheReuse = (frame: RenderPipelineFrame): boolean =>
255
280
  shadowViewCacheReuse(frame, identity);
@@ -267,7 +292,13 @@ export function addTypedShadowPasses(
267
292
  ? undefined
268
293
  : (view) => shadowFeatures.encode(pass, frame, resources, view),
269
294
  ),
270
- (frame) => shadowFeatures !== undefined || !cacheReuse(frame),
295
+ (frame) => {
296
+ if (forceRasterPending) {
297
+ forceRasterPending = false;
298
+ return true;
299
+ }
300
+ return shadowFeatures !== undefined || !cacheReuse(frame);
301
+ },
271
302
  [
272
303
  ...(shadowProjection?.ok === true && shadowProjection.value?.graphResources !== undefined
273
304
  ? shadowViewRasterAccesses(shadowProjection.value.graphResources)
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/assembly/material/surface-projection.ts","../src/materials.ts"],"names":["pass"],"mappings":";;;;;AAQO,IAAM,wBAAA,GAA2B,4BAAA;AAsBxC,SAAS,IAAA,CACP,IAAA,EACA,OAAA,EACA,aAAA,EACc;AACd,EAAA,MAAM,aAAA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AAe,OAAO,CAAA;AAChG;AAEO,IAAM,SAAA,GAAY,EAAE,KAAA,EAAO,QAAA,EAAU,IAAA","file":"chunk-BLXGONR2.mjs","sourcesContent":["import { DEFAULT_STANDARD_SURFACE_MODULE } from '@forgeax/engine-shader';\nimport type {\n MaterialPass,\n MaterialRenderState,\n MaterialValue,\n StandardLayerPlan,\n} from '@forgeax/engine-types';\n\nexport const STANDARD_MATERIAL_MODULE = 'forgeax_material::standard';\nexport { DEFAULT_STANDARD_SURFACE_MODULE };\n\nexport type StandardSurfacePassName = 'forward' | 'deferred' | 'shadow-caster';\nexport type StandardSurfaceGeometryVariant = 'rigid' | 'skinned' | 'instanced';\nexport type StandardSurfaceLightingLane = 'direct' | 'clustered';\nexport type StandardSurfaceKind = 'standard' | 'full-custom';\n\nexport interface StandardSurfaceProjectionOptions {\n readonly surfaceModule: string;\n readonly values: Readonly<Record<string, MaterialValue | null>>;\n readonly renderState?: MaterialRenderState;\n readonly castShadow?: boolean;\n readonly queue?: number;\n readonly geometryVariant?: StandardSurfaceGeometryVariant;\n readonly lightingLane?: StandardSurfaceLightingLane;\n readonly alphaClip?: boolean;\n readonly surfaceKind?: StandardSurfaceKind;\n readonly declaredPasses?: readonly StandardSurfacePassName[];\n readonly layerPlan?: StandardLayerPlan;\n}\n\nfunction pass(\n name: StandardSurfacePassName,\n options: StandardSurfaceProjectionOptions,\n fragmentEntry: string,\n): MaterialPass {\n const authoredState = options.renderState ?? {};\n const authoredRecord = authoredState as Readonly<Record<string, unknown>>;\n const tags = (authoredRecord.tags ?? {}) as Readonly<Record<string, string>>;\n const lightMode =\n name === 'shadow-caster' ? 'ShadowCaster' : name === 'forward' ? 'Forward' : 'Deferred';\n return {\n name,\n program: {\n module:\n name === 'shadow-caster' ? 'forgeax::default-shadow-caster' : STANDARD_MATERIAL_MODULE,\n fragmentEntry,\n moduleSlots: { surface: options.surfaceModule },\n },\n renderState: {\n ...authoredState,\n tags:\n options.surfaceModule === DEFAULT_STANDARD_SURFACE_MODULE\n ? { LightMode: lightMode, ...tags }\n : {\n ...tags,\n LightMode: lightMode,\n SurfaceModule: options.surfaceModule,\n SurfaceKind: options.surfaceKind ?? 'standard',\n GeometryVariant: options.geometryVariant ?? 'rigid',\n LightingLane: options.lightingLane ?? 'direct',\n AlphaClip: options.alphaClip === true ? 'enabled' : 'disabled',\n },\n ...(options.queue === undefined ? {} : { queue: options.queue }),\n },\n };\n}\n\n/** Project one custom or default Surface into the existing Standard pass family. */\nexport function projectStandardSurfacePasses(\n options: StandardSurfaceProjectionOptions,\n): [MaterialPass, ...MaterialPass[]] {\n const authoredPasses = options.declaredPasses;\n const passNames: StandardSurfacePassName[] =\n options.surfaceKind === 'full-custom' && authoredPasses !== undefined\n ? [...authoredPasses]\n : (['forward'] as StandardSurfacePassName[]);\n if (authoredPasses === undefined || options.surfaceKind !== 'full-custom') {\n const blended = options.renderState?.blend !== undefined;\n if (!blended && options.layerPlan?.mode !== 'physical') passNames.push('deferred');\n if (options.castShadow !== false) passNames.push('shadow-caster');\n }\n const entries = passNames.map((name) =>\n pass(\n name,\n options,\n name === 'forward' ? 'fs_main' : name === 'deferred' ? 'fs_gbuffer' : 'fs_shadow',\n ),\n );\n const passes = entries as [MaterialPass, ...MaterialPass[]];\n return passes;\n}\n","import { color } from '@forgeax/engine-math';\nimport { DEFAULT_STANDARD_PBR_PARAM_SCHEMA } from '@forgeax/engine-shader';\nimport type {\n MaterialAsset,\n MaterialColorSpace,\n MaterialParameter,\n MaterialPass,\n MaterialRenderState,\n MaterialValue,\n} from '@forgeax/engine-types';\nimport { deriveStandardLayerPlan, standardSurfaceParameters } from '@forgeax/engine-types';\nimport {\n DEFAULT_STANDARD_SURFACE_MODULE,\n projectStandardSurfacePasses,\n} from './assembly/material/surface-projection';\n\nexport type MaterialTransmissionValidationReason =\n | 'non-finite'\n | 'range'\n | 'shape'\n | 'blend'\n | 'depth-write';\n\nexport type MaterialAuthoringValidationReason = 'non-finite' | 'range';\n\n/** Structured authoring failure for a built-in Standard material parameter. */\nexport class MaterialAuthoringContractError extends Error {\n readonly code = 'material-authoring-contract-invalid' as const;\n readonly expected =\n 'Standard material authoring values are finite and within their declared ranges';\n readonly hint =\n 'repair the named Standard material parameter alphaCutoff before publishing the material';\n readonly detail: {\n readonly code: 'material-authoring-contract-invalid';\n readonly material: 'Standard';\n readonly parameter: 'alphaCutoff';\n readonly reason: MaterialAuthoringValidationReason;\n readonly actual?: unknown;\n };\n\n constructor(reason: MaterialAuthoringValidationReason, actual?: unknown) {\n super(`Materials.standard: alphaCutoff violates the authoring contract (${reason})`);\n this.name = 'MaterialAuthoringContractError';\n this.detail = {\n code: 'material-authoring-contract-invalid',\n material: 'Standard',\n parameter: 'alphaCutoff',\n reason,\n ...(actual === undefined ? {} : { actual }),\n };\n }\n}\n\n/** Structured authoring failure for the Standard transmission contract. */\nexport class MaterialTransmissionContractError extends Error {\n readonly code = 'material-transmission-contract-invalid' as const;\n readonly expected = 'transmission material values satisfy finite ranges and Forward depth rules';\n readonly hint =\n 'repair the named transmission value or pass state before publishing the material';\n readonly detail: {\n readonly code: 'material-transmission-contract-invalid';\n readonly material: 'Standard';\n readonly parameter:\n | 'transmission'\n | 'ior'\n | 'thickness'\n | 'attenuationColor'\n | 'attenuationDistance';\n readonly reason: MaterialTransmissionValidationReason;\n readonly actual?: unknown;\n };\n\n constructor(\n parameter: (typeof MaterialTransmissionContractError.prototype.detail)['parameter'],\n reason: MaterialTransmissionValidationReason,\n actual?: unknown,\n ) {\n super(`Materials.standard: ${parameter} violates the transmission contract (${reason})`);\n this.name = 'MaterialTransmissionContractError';\n this.detail = {\n code: 'material-transmission-contract-invalid',\n material: 'Standard',\n parameter,\n reason,\n ...(actual === undefined ? {} : { actual }),\n };\n }\n}\n\nexport const SPRITE_PREMULTIPLIED_ALPHA_BLEND: GPUBlendState = {\n color: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha', operation: 'add' },\n alpha: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha', operation: 'add' },\n};\n\nconst UNLIT_MODULE = 'forgeax_material::unlit';\nconst SPRITE_MODULE = 'forgeax_material::sprite';\n\nexport type MaterialColorTuple3 = readonly [number, number, number];\nexport type MaterialColorTuple4 = readonly [number, number, number, number];\nexport type MaterialColorInput3 = MaterialColorTuple3 | string | number;\nexport type MaterialColorInput4 = MaterialColorTuple4 | string | number;\n\nfunction colorHexFromNumber(value: number): string {\n if (!Number.isInteger(value) || value < 0 || value > 0xffffff) {\n throw new Error(`material color number must be an integer in [0, 0xffffff], got ${value}`);\n }\n return `#${value.toString(16).padStart(6, '0')}`;\n}\n\nfunction linearColorFromInput(\n input: MaterialColorInput3 | MaterialColorInput4,\n channels: 3 | 4,\n): readonly number[] {\n if (typeof input === 'number' || typeof input === 'string') {\n const parsed = color.create();\n color.fromCss(parsed, typeof input === 'number' ? colorHexFromNumber(input) : input);\n return channels === 3\n ? [parsed[0] as number, parsed[1] as number, parsed[2] as number]\n : Array.from(parsed);\n }\n if (input.length !== channels) {\n throw new Error(`material color tuple must contain ${channels} channels, got ${input.length}`);\n }\n return [...input];\n}\n\n/** Convert an explicit sRGB numeric tuple into the linear tuple factories store. */\nexport function srgb(input: MaterialColorTuple3): MaterialColorTuple3;\nexport function srgb(input: MaterialColorTuple4): MaterialColorTuple4;\nexport function srgb(input: readonly number[]): readonly number[] {\n if (input.length !== 3 && input.length !== 4) {\n throw new Error(`sRGB material color tuple must contain 3 or 4 channels, got ${input.length}`);\n }\n const parsed = color.create(input[0] ?? 0, input[1] ?? 0, input[2] ?? 0, input[3] ?? 1);\n color.srgbToLinear(parsed, parsed);\n return input.length === 3\n ? [parsed[0] as number, parsed[1] as number, parsed[2] as number]\n : [parsed[0] as number, parsed[1] as number, parsed[2] as number, parsed[3] as number];\n}\n\nfunction authoredColorParameter(\n name: string,\n type: 'color' | 'vec3',\n colorSpace: MaterialColorSpace,\n optional = false,\n): MaterialParameter {\n return {\n name,\n type,\n ...(type === 'color' && colorSpace === 'srgb' ? {} : { colorSpace }),\n ...(optional ? { optional: true } : {}),\n };\n}\n\nfunction standardParameters(\n colorSpace: MaterialColorSpace,\n opts: StandardOpts,\n): readonly MaterialParameter[] {\n const physicalNames = new Set<string>();\n const addPhysical = (...names: readonly string[]) => {\n for (const name of names) physicalNames.add(name);\n };\n if (\n opts.clearcoat !== undefined ||\n opts.clearcoatRoughness !== undefined ||\n opts.clearcoatNormalScale !== undefined ||\n opts.clearcoatTexture !== undefined ||\n opts.clearcoatRoughnessTexture !== undefined ||\n opts.clearcoatNormalTexture !== undefined\n ) {\n addPhysical(\n 'clearcoat',\n 'clearcoatRoughness',\n 'clearcoatNormalScale',\n ...(opts.clearcoatTexture === undefined ? [] : ['clearcoatTexture']),\n ...(opts.clearcoatRoughnessTexture === undefined ? [] : ['clearcoatRoughnessTexture']),\n ...(opts.clearcoatNormalTexture === undefined ? [] : ['clearcoatNormalTexture']),\n );\n }\n if (\n opts.anisotropyStrength !== undefined ||\n opts.anisotropyRotation !== undefined ||\n opts.anisotropyTexture !== undefined\n ) {\n addPhysical('anisotropyStrength', 'anisotropyRotation');\n if (opts.anisotropyTexture !== undefined) addPhysical('anisotropyTexture');\n }\n if (\n opts.sheenColor !== undefined ||\n opts.sheenRoughness !== undefined ||\n opts.sheenColorTexture !== undefined ||\n opts.sheenRoughnessTexture !== undefined\n ) {\n addPhysical('sheenColor', 'sheenRoughness');\n if (opts.sheenColorTexture !== undefined) addPhysical('sheenColorTexture');\n if (opts.sheenRoughnessTexture !== undefined) addPhysical('sheenRoughnessTexture');\n }\n if (\n opts.iridescence !== undefined ||\n opts.iridescenceIor !== undefined ||\n opts.iridescenceThicknessMinimum !== undefined ||\n opts.iridescenceThicknessMaximum !== undefined ||\n opts.iridescenceTexture !== undefined ||\n opts.iridescenceThicknessTexture !== undefined\n ) {\n addPhysical(\n 'iridescence',\n 'iridescenceIor',\n 'iridescenceThicknessMinimum',\n 'iridescenceThicknessMaximum',\n ...(opts.iridescenceTexture === undefined ? [] : ['iridescenceTexture']),\n ...(opts.iridescenceThicknessTexture === undefined ? [] : ['iridescenceThicknessTexture']),\n );\n }\n const baseNames = new Set([\n 'baseColor',\n 'metallic',\n 'roughness',\n 'metallicChannel',\n 'roughnessChannel',\n 'aoChannel',\n 'extraChannel',\n 'emissive',\n 'emissiveIntensity',\n 'occlusionStrength',\n 'alphaCutoff',\n 'normalScale',\n 'specular',\n 'specularColor',\n // IOR is part of the always-present dielectric F0 contract. The\n // transmission layer may be absent, but the Standard shader still\n // consumes this scalar for the base reflection path.\n 'ior',\n ]);\n if (opts.specularTexture !== undefined) baseNames.add('specularTexture');\n if (opts.specularColorTexture !== undefined) baseNames.add('specularColorTexture');\n if (\n opts.transmission !== undefined ||\n opts.ior !== undefined ||\n opts.thickness !== undefined ||\n opts.transmissionTexture !== undefined ||\n opts.thicknessTexture !== undefined ||\n opts.attenuationColor !== undefined ||\n opts.attenuationDistance !== undefined\n ) {\n for (const name of [\n 'transmission',\n 'ior',\n 'thickness',\n 'attenuationColor',\n 'attenuationDistance',\n ]) {\n baseNames.add(name);\n }\n }\n // A texture declaration selects its compiled sampling path. Loading state\n // does not: an authored but not-yet-resident slot still needs its fallback.\n for (const parameter of DEFAULT_STANDARD_PBR_PARAM_SCHEMA) {\n if (\n parameter.type === 'texture2d' &&\n opts[parameter.name as keyof StandardOpts] !== undefined\n ) {\n baseNames.add(parameter.name);\n }\n }\n // All Standard fields come from one root schema. Physical fields are\n // projected by the authored option membership above; appending a second\n // physical schema would create a parallel ABI authority.\n const availableSchema = DEFAULT_STANDARD_PBR_PARAM_SCHEMA;\n // Keep the generated Standard UBO's numeric run contiguous before any\n // texture coordinate records. The built-in WGSL places the complete\n // physical root (including clearcoat scalars) after the base numeric run\n // and before all coordinate pairs; appending physical entries after the\n // base texture records would otherwise derive a different ABI.\n const numericSchema = availableSchema.filter((entry) => !entry.type.startsWith('texture'));\n const textureSchema = availableSchema.filter((entry) => entry.type.startsWith('texture'));\n const orderedSchema = [...numericSchema, ...textureSchema];\n return orderedSchema\n .filter((entry) => baseNames.has(entry.name) || physicalNames.has(entry.name))\n .map((entry) => {\n const type = entry.type.startsWith('texture') ? 'texture' : entry.type;\n const isRequired =\n entry.name === 'baseColor' || entry.name === 'metallic' || entry.name === 'roughness';\n const authoredColor =\n entry.type === 'color' || (entry.type === 'vec3' && entry.name !== 'attenuationColor');\n const schemaColorSpace = 'colorSpace' in entry ? entry.colorSpace : undefined;\n const colorSpaceProjection: { colorSpace?: MaterialColorSpace } = {};\n if (authoredColor && !(type === 'color' && colorSpace === 'srgb')) {\n colorSpaceProjection.colorSpace = colorSpace;\n } else if (!authoredColor && schemaColorSpace !== undefined) {\n colorSpaceProjection.colorSpace = schemaColorSpace;\n }\n return {\n name: entry.name,\n type,\n ...colorSpaceProjection,\n ...(isRequired ? {} : { optional: true }),\n } as MaterialParameter;\n });\n}\n\nfunction unlitParameters(colorSpace: MaterialColorSpace): readonly MaterialParameter[] {\n return [\n authoredColorParameter('baseColor', 'color', colorSpace),\n { name: 'alphaCutoff', type: 'f32', optional: true },\n { name: 'baseColorTexture', type: 'texture', optional: true },\n ];\n}\n\nfunction pass(\n name: string,\n module: string,\n renderState: MaterialRenderState | undefined,\n fragmentEntry?: string,\n queue?: number,\n): MaterialPass {\n const lightMode =\n name === 'shadow-caster' ? 'ShadowCaster' : name === 'deferred' ? 'Deferred' : 'Forward';\n const authoredState = (renderState ?? {}) as Readonly<Record<string, unknown>>;\n const authoredTags = authoredState.tags as Readonly<Record<string, string>> | undefined;\n return {\n name,\n program: {\n module,\n ...(fragmentEntry === undefined ? {} : { fragmentEntry }),\n },\n renderState: {\n ...authoredState,\n tags: { LightMode: lightMode, ...authoredTags },\n ...(queue === undefined ? {} : { queue }),\n },\n };\n}\n\nfunction shadowCasterRenderState(\n renderState: MaterialRenderState | undefined,\n): MaterialRenderState | undefined {\n if (renderState?.cullMode === undefined && renderState?.frontFace === undefined) return undefined;\n return {\n ...(renderState.cullMode === undefined ? {} : { cullMode: renderState.cullMode }),\n ...(renderState.frontFace === undefined ? {} : { frontFace: renderState.frontFace }),\n };\n}\n\ninterface UnlitOpts {\n readonly castShadow?: boolean;\n readonly baseColorTexture?: MaterialValue;\n readonly alphaCutoff?: number;\n readonly renderState?: MaterialRenderState;\n readonly queue?: number;\n}\n\nfunction unlit(rgba: MaterialColorInput4, opts?: UnlitOpts): MaterialAsset {\n if (opts?.alphaCutoff !== undefined && (opts.alphaCutoff < 0 || opts.alphaCutoff > 1)) {\n throw new Error(`Materials.unlit: alphaCutoff must be in [0, 1], got ${opts.alphaCutoff}`);\n }\n const values: Record<string, MaterialValue> = { baseColor: linearColorFromInput(rgba, 4) };\n if (opts?.baseColorTexture !== undefined) values.baseColorTexture = opts.baseColorTexture;\n if (opts?.alphaCutoff !== undefined) values.alphaCutoff = opts.alphaCutoff;\n const passes: [MaterialPass, ...MaterialPass[]] = [\n pass('forward', UNLIT_MODULE, opts?.renderState, undefined, opts?.queue),\n ];\n if (opts?.castShadow !== false) {\n passes.push(pass('shadow-caster', UNLIT_MODULE, shadowCasterRenderState(opts?.renderState)));\n }\n return {\n kind: 'material',\n colorSpace: 'linear',\n passes,\n parameters: unlitParameters('linear'),\n values,\n };\n}\n\ninterface StandardOpts {\n /** Numeric tuples are linear; Hex/CSS strings and numbers are sRGB inputs. */\n readonly baseColor: MaterialColorInput4;\n readonly metallic?: number;\n readonly roughness?: number;\n /** Texture channel used for the metallic factor; glTF defaults to B (2). */\n readonly metallicChannel?: number;\n /** Texture channel used for the roughness factor; glTF defaults to G (1). */\n readonly roughnessChannel?: number;\n readonly clearcoat?: number;\n readonly clearcoatRoughness?: number;\n readonly clearcoatTexture?: MaterialValue;\n readonly clearcoatRoughnessTexture?: MaterialValue;\n readonly clearcoatNormalTexture?: MaterialValue;\n readonly clearcoatNormalScale?: number;\n readonly anisotropyStrength?: number;\n readonly anisotropyRotation?: number;\n readonly anisotropyTexture?: MaterialValue;\n readonly sheenColor?: MaterialColorInput3;\n readonly sheenRoughness?: number;\n readonly sheenColorTexture?: MaterialValue;\n readonly sheenRoughnessTexture?: MaterialValue;\n readonly iridescence?: number;\n readonly iridescenceIor?: number;\n readonly iridescenceThicknessMinimum?: number;\n readonly iridescenceThicknessMaximum?: number;\n readonly iridescenceTexture?: MaterialValue;\n readonly iridescenceThicknessTexture?: MaterialValue;\n readonly specular?: number;\n readonly specularColor?: MaterialColorInput3;\n readonly specularTexture?: MaterialValue;\n readonly specularColorTexture?: MaterialValue;\n readonly emissive?: MaterialColorInput3;\n readonly emissiveIntensity?: number;\n readonly emissiveTexture?: MaterialValue;\n readonly baseColorTexture?: MaterialValue;\n readonly metallicRoughnessTexture?: MaterialValue;\n readonly normalTexture?: MaterialValue;\n readonly occlusionTexture?: MaterialValue;\n readonly occlusionStrength?: number;\n readonly alphaCutoff?: number;\n readonly transmission?: number;\n readonly transmissionTexture?: MaterialValue;\n readonly ior?: number;\n readonly thickness?: number;\n readonly thicknessTexture?: MaterialValue;\n readonly attenuationColor?: readonly [number, number, number];\n readonly attenuationDistance?: number;\n readonly renderState?: MaterialRenderState;\n readonly castShadow?: boolean;\n readonly queue?: number;\n}\n\n/** Built-in Standard authoring surface with engine-owned parameter defaults. */\nexport interface DefaultStandardOptions extends StandardOpts {\n readonly surfaceModule?: never;\n readonly parameters?: never;\n readonly values?: never;\n}\n\n/** Import-first Standard Surface authoring; the root parameter contract stays caller-owned. */\nexport interface CustomStandardSurfaceOptions {\n readonly surfaceModule: string;\n readonly parameters: readonly MaterialParameter[];\n readonly values: Readonly<Record<string, MaterialValue>>;\n readonly colorSpace?: MaterialColorSpace;\n readonly renderState?: MaterialRenderState;\n readonly castShadow?: boolean;\n readonly queue?: number;\n readonly baseColor?: never;\n readonly metallic?: never;\n readonly roughness?: never;\n readonly metallicChannel?: never;\n readonly roughnessChannel?: never;\n readonly clearcoat?: never;\n readonly clearcoatRoughness?: never;\n readonly clearcoatTexture?: never;\n readonly clearcoatRoughnessTexture?: never;\n readonly clearcoatNormalTexture?: never;\n readonly clearcoatNormalScale?: never;\n readonly anisotropyStrength?: never;\n readonly anisotropyRotation?: never;\n readonly anisotropyTexture?: never;\n readonly sheenColor?: never;\n readonly sheenRoughness?: never;\n readonly sheenColorTexture?: never;\n readonly sheenRoughnessTexture?: never;\n readonly iridescence?: never;\n readonly iridescenceIor?: never;\n readonly iridescenceThicknessMinimum?: never;\n readonly iridescenceThicknessMaximum?: never;\n readonly iridescenceTexture?: never;\n readonly iridescenceThicknessTexture?: never;\n readonly specular?: never;\n readonly specularColor?: never;\n readonly specularTexture?: never;\n readonly specularColorTexture?: never;\n readonly emissive?: never;\n readonly emissiveIntensity?: never;\n readonly emissiveTexture?: never;\n readonly baseColorTexture?: never;\n readonly metallicRoughnessTexture?: never;\n readonly normalTexture?: never;\n readonly occlusionTexture?: never;\n readonly occlusionStrength?: never;\n readonly alphaCutoff?: never;\n readonly transmission?: never;\n readonly transmissionTexture?: never;\n readonly ior?: never;\n readonly thickness?: never;\n readonly thicknessTexture?: never;\n readonly attenuationColor?: never;\n readonly attenuationDistance?: never;\n}\n\nexport type StandardOptions = DefaultStandardOptions | CustomStandardSurfaceOptions;\n\nfunction validateChannel(\n name: 'metallicChannel' | 'roughnessChannel',\n value: number | undefined,\n): void {\n if (value !== undefined && (!Number.isInteger(value) || value < 0 || value > 3)) {\n throw new Error(`Materials.standard: ${name} must be an integer in [0, 3], got ${value}`);\n }\n}\n\nfunction validateFiniteRange(\n name: 'transmission' | 'ior' | 'thickness' | 'attenuationDistance',\n value: number | undefined,\n minimum: number,\n maximum?: number,\n): void {\n if (value === undefined || !Number.isFinite(value)) {\n if (value === undefined) return;\n throw new MaterialTransmissionContractError(name, 'non-finite', value);\n }\n if (value < minimum || (maximum !== undefined && value > maximum)) {\n throw new MaterialTransmissionContractError(name, 'range', value);\n }\n}\n\nfunction standardDefault(opts: DefaultStandardOptions): MaterialAsset {\n const occlusionStrength = opts.occlusionStrength ?? 1;\n if (occlusionStrength < 0 || occlusionStrength > 1) {\n throw new Error(\n `Materials.standard: occlusionStrength must be in [0, 1], got ${occlusionStrength}`,\n );\n }\n if (opts.alphaCutoff !== undefined && !Number.isFinite(opts.alphaCutoff)) {\n throw new MaterialAuthoringContractError('non-finite', opts.alphaCutoff);\n }\n if (opts.alphaCutoff !== undefined && (opts.alphaCutoff < 0 || opts.alphaCutoff > 1)) {\n throw new MaterialAuthoringContractError('range', opts.alphaCutoff);\n }\n validateChannel('metallicChannel', opts.metallicChannel);\n validateChannel('roughnessChannel', opts.roughnessChannel);\n const transmission = opts.transmission ?? 0;\n const ior = opts.ior ?? 1.5;\n const thickness = opts.thickness ?? 0;\n const attenuationColor = opts.attenuationColor ?? [1, 1, 1];\n validateFiniteRange('transmission', transmission, 0, 1);\n validateFiniteRange('ior', ior, 1);\n validateFiniteRange('thickness', thickness, 0);\n validateFiniteRange('attenuationDistance', opts.attenuationDistance, Number.MIN_VALUE);\n if (\n attenuationColor.length !== 3 ||\n attenuationColor.some((value) => !Number.isFinite(value) || value < 0 || value > 1)\n ) {\n throw new MaterialTransmissionContractError('attenuationColor', 'shape', attenuationColor);\n }\n if (transmission > 0 && opts.renderState?.blend !== undefined) {\n throw new MaterialTransmissionContractError('transmission', 'blend', opts.renderState.blend);\n }\n if (transmission > 0 && opts.renderState?.depthWriteEnabled === true) {\n throw new MaterialTransmissionContractError('transmission', 'depth-write', true);\n }\n const values: Record<string, MaterialValue> = {\n baseColor: linearColorFromInput(opts.baseColor, 4),\n metallic: opts.metallic ?? 0,\n roughness: opts.roughness ?? 0.5,\n occlusionStrength,\n specular: opts.specular ?? 1,\n specularColor:\n opts.specularColor === undefined ? [1, 1, 1] : linearColorFromInput(opts.specularColor, 3),\n transmission,\n ior,\n thickness,\n attenuationColor,\n };\n if (opts.metallicChannel !== undefined) values.metallicChannel = opts.metallicChannel;\n if (opts.roughnessChannel !== undefined) values.roughnessChannel = opts.roughnessChannel;\n if (opts.clearcoat !== undefined) values.clearcoat = opts.clearcoat;\n if (opts.clearcoatRoughness !== undefined) values.clearcoatRoughness = opts.clearcoatRoughness;\n if (opts.clearcoatTexture !== undefined) values.clearcoatTexture = opts.clearcoatTexture;\n if (opts.clearcoatRoughnessTexture !== undefined) {\n values.clearcoatRoughnessTexture = opts.clearcoatRoughnessTexture;\n }\n if (opts.clearcoatNormalTexture !== undefined) {\n values.clearcoatNormalTexture = opts.clearcoatNormalTexture;\n }\n if (opts.clearcoatNormalScale !== undefined)\n values.clearcoatNormalScale = opts.clearcoatNormalScale;\n if (opts.anisotropyStrength !== undefined) values.anisotropyStrength = opts.anisotropyStrength;\n if (opts.anisotropyRotation !== undefined) values.anisotropyRotation = opts.anisotropyRotation;\n if (opts.anisotropyTexture !== undefined) values.anisotropyTexture = opts.anisotropyTexture;\n if (opts.sheenColor !== undefined) values.sheenColor = linearColorFromInput(opts.sheenColor, 3);\n if (opts.sheenRoughness !== undefined) values.sheenRoughness = opts.sheenRoughness;\n if (opts.sheenColorTexture !== undefined) values.sheenColorTexture = opts.sheenColorTexture;\n if (opts.sheenRoughnessTexture !== undefined) {\n values.sheenRoughnessTexture = opts.sheenRoughnessTexture;\n }\n if (opts.iridescence !== undefined) values.iridescence = opts.iridescence;\n if (opts.iridescenceIor !== undefined) values.iridescenceIor = opts.iridescenceIor;\n if (opts.iridescenceThicknessMinimum !== undefined) {\n values.iridescenceThicknessMinimum = opts.iridescenceThicknessMinimum;\n }\n if (opts.iridescenceThicknessMaximum !== undefined) {\n values.iridescenceThicknessMaximum = opts.iridescenceThicknessMaximum;\n }\n if (opts.iridescenceTexture !== undefined) values.iridescenceTexture = opts.iridescenceTexture;\n if (opts.iridescenceThicknessTexture !== undefined) {\n values.iridescenceThicknessTexture = opts.iridescenceThicknessTexture;\n }\n if (opts.emissive !== undefined) values.emissive = linearColorFromInput(opts.emissive, 3);\n if (opts.emissiveIntensity !== undefined) values.emissiveIntensity = opts.emissiveIntensity;\n if (opts.emissiveTexture !== undefined) values.emissiveTexture = opts.emissiveTexture;\n if (opts.baseColorTexture !== undefined) values.baseColorTexture = opts.baseColorTexture;\n if (opts.metallicRoughnessTexture !== undefined) {\n values.metallicRoughnessTexture = opts.metallicRoughnessTexture;\n }\n if (opts.normalTexture !== undefined) values.normalTexture = opts.normalTexture;\n if (opts.occlusionTexture !== undefined) values.occlusionTexture = opts.occlusionTexture;\n if (opts.specularTexture !== undefined) values.specularTexture = opts.specularTexture;\n if (opts.specularColorTexture !== undefined) {\n values.specularColorTexture = opts.specularColorTexture;\n }\n if (opts.alphaCutoff !== undefined) values.alphaCutoff = opts.alphaCutoff;\n if (opts.transmissionTexture !== undefined) values.transmissionTexture = opts.transmissionTexture;\n if (opts.thicknessTexture !== undefined) values.thicknessTexture = opts.thicknessTexture;\n if (opts.attenuationDistance !== undefined) values.attenuationDistance = opts.attenuationDistance;\n const forwardRenderState =\n transmission > 0 ? { ...(opts.renderState ?? {}), depthWriteEnabled: false } : opts.renderState;\n const parameters = standardSurfaceParameters(standardParameters('linear', opts));\n const declaredNames = new Set(parameters.map((parameter) => parameter.name));\n for (const name of Object.keys(values)) {\n if (!declaredNames.has(name)) delete values[name];\n }\n const layerPlan = deriveStandardLayerPlan(parameters);\n const projected = projectStandardSurfacePasses({\n surfaceModule: DEFAULT_STANDARD_SURFACE_MODULE,\n values,\n ...(forwardRenderState === undefined ? {} : { renderState: forwardRenderState }),\n ...(opts.castShadow === undefined ? {} : { castShadow: opts.castShadow }),\n ...(opts.queue === undefined ? {} : { queue: opts.queue }),\n layerPlan,\n });\n const passes = (\n transmission > 0 ? projected.filter((entry) => entry.name !== 'deferred') : projected\n ) as [MaterialPass, ...MaterialPass[]];\n return {\n kind: 'material',\n colorSpace: 'linear',\n passes,\n parameters,\n values,\n };\n}\n\nfunction standardCustom(opts: CustomStandardSurfaceOptions): MaterialAsset {\n const layerPlan = deriveStandardLayerPlan(\n opts.parameters.filter((parameter) => parameter.optional !== true),\n );\n return {\n kind: 'material',\n ...(opts.colorSpace === undefined || opts.colorSpace === 'srgb'\n ? {}\n : { colorSpace: opts.colorSpace }),\n passes: projectStandardSurfacePasses({\n surfaceModule: opts.surfaceModule,\n values: opts.values,\n ...(opts.renderState === undefined ? {} : { renderState: opts.renderState }),\n ...(opts.castShadow === undefined ? {} : { castShadow: opts.castShadow }),\n ...(opts.queue === undefined ? {} : { queue: opts.queue }),\n layerPlan,\n }),\n parameters: standardSurfaceParameters(opts.parameters),\n values: opts.values,\n };\n}\n\nexport function standard(options: StandardOptions): MaterialAsset {\n return options.surfaceModule === undefined ? standardDefault(options) : standardCustom(options);\n}\n\nexport const Materials = { unlit, standard, srgb } as const;\n\nexport { SPRITE_MODULE };\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/components/sprite-animation.ts","../src/components/sprite-instances.ts","../src/components/sprite-region-override.ts","../src/components/tile-layer.ts","../src/components/tilemap.ts","../src/systems/active-camera.ts"],"names":["defineComponent"],"mappings":";;;AAgKO,IAAM,eAAA,GAAkB,gBAAgB,iBAAA,EAAmB;AAAA,EAChE,UAAA,EAAY,EAAE,IAAA,EAAM,KAAA,EAAM;AAAA,EAC1B,aAAA,EAAe,EAAE,IAAA,EAAM,KAAA,EAAM;AAAA,EAC7B,YAAA,EAAc,EAAE,IAAA,EAAM,KAAA,EAAO,WAAW,IAAA,EAAK;AAAA,EAC7C,OAAA,EAAS,EAAE,IAAA,EAAM,KAAA,EAAO,WAAW,IAAA,EAAK;AAAA,EACxC,OAAA,EAAS,EAAE,IAAA,EAAM,YAAA,EAAa;AAAA,EAC9B,YAAA,EAAc,EAAE,IAAA,EAAM,KAAA;AACxB,CAAC;ACdM,IAAM,eAAA,GAAkBA,gBAAgB,iBAAA,EAAmB;AAAA,EAChE,UAAA,EAAY,EAAE,IAAA,EAAM,YAAA,EAAa;AAAA,EACjC,OAAA,EAAS,EAAE,IAAA,EAAM,YAAA;AACnB,CAAC;ACtDM,IAAM,oBAAA,GAAuBA,gBAAgB,sBAAA,EAAwB;AAAA,EAC1E,MAAA,EAAQ,EAAE,IAAA,EAAM,eAAA;A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,OAAc,MAAA,EAAsB;AAClE,EAAA,KAAA,CAAM,cAAA,CAA6B,iBAAA,EAAmB,EAAE,MAAA,EAAQ,CAAA;AAClE;AAiBO,SAAS,uBAAA,CACd,gBACA,YAAA,EACQ;AACR,EAAA,IAAI,YAAA,KAAiB,QAAW,OAAO,EAAA;AACvC,EAAA,OAAO,cAAA,CAAe,QAAQ,YAAY,CAAA;AAC5C","file":"chunk-ELJFJ2BU.mjs","sourcesContent":["// @forgeax/engine-runtime - SpriteAnimation (per-entity frame-tick clock).\n//\n// 6-field schema (1:1 with requirements section 2.3 table; D-5 + D-6\n// vocab keywords locked):\n//\n// frameCount : 'u32' total frames in the cycle (>= 1).\n// frameDuration : 'f32' per-frame seconds (> 0).\n// currentFrame : 'u32' live frame index, in [0, frameCount).\n// accumDt : 'f32' dt accumulator (research F-3 carries\n// fractional residue across ticks).\n// regions : 'array<f32>' flat per-frame UV rectangles\n// [uMin, vMin, uW, vH]; the M4 tick\n// system enforces\n// `regions.length === frameCount * 4`\n// on first observation (AC-09 fail-fast,\n// D-1 path).\n// playbackMode : 'u32' numeric encoding of `SpritePlaybackMode`\n// (0 = SPRITE_PLAYBACK_MODE_LOOP,\n// 1 = SPRITE_PLAYBACK_MODE_CLAMP).\n//\n// Why u32 for playbackMode? research F-2 + F-5: the ECS schema whitelist\n// rejects string-literal unions. The M1 SSOT\n// `packages/runtime/src/components/sprite-playback-mode.ts` carries the\n// numeric constants + the `spritePlaybackModeFromU32` mapper that turns\n// the column value back into a string-literal union at the M4 tick-system\n// seam — same shape as the M1 Tonemap encoding (`tonemap: 'f32'` +\n// TONEMAP_NONE / TONEMAP_REINHARD_EXTENDED + tonemapFromF32). One mental\n// model across all closed-union schema columns; charter P4 consistent\n// abstraction.\n//\n// Why array<f32> (variable) and not array<f32, N> (fixed) for regions?\n// The length `frameCount * 4` is data-dependent: `frameCount` is itself a\n// per-entity column read at runtime, not a schema-time literal. Same\n// shape as the renderer-owned 3D instance collection snapshot whose length\n// depends on the live instance count; the owners remain separate.\n//\n// dt accumulator clock model (requirements section 2.5 q6 + plan-strategy\n// section 2 D-5):\n// accumDt += Time.delta\n// while (accumDt >= frameDuration) { advance currentFrame; accumDt -= frameDuration }\n// The carry-over `accumDt` survives across ticks so frame timing stays\n// stable under jittery dt; M4 T-23 implements the loop. Per-frame UV\n// is materialised by writing the slice\n// `regions[currentFrame*4 .. currentFrame*4 + 4]` into the entity's\n// `SpriteRegionOverride.region` column (T-11 + M4 T-23).\n//\n// Sprite-only consumption (requirements section 5 constraint #2): the\n// M4 tick system + the M3 extract branch read this component only when\n// the entity routes through the sprite bucket. Opaque buckets ignore\n// the component even when present. Naming keeps the `Sprite` prefix per\n// OOS-01 (no premature 3D generalisation); 3D UV animation lands in a\n// separate component in a future feat.\n//\n// 4-step recipe (charter F1 progressive disclosure — minimum walk-cycle\n// host code; full demo lands in M6 hello-sprite-atlas):\n// 1. Build atlas via `forgeax asset atlas --input <glob> --name <prefix> --output <dir> --root <project>`\n// (M5 build-time hook); load the emitted `<name>.atlas.png` plus\n// `<name>.atlas.meta.json` sidecar.\n// 2. Register the sprite material referencing the atlas\n// `TextureAsset` with the initial frame's `region` rectangle (the\n// runtime tick system overrides this region per entity per frame).\n// 3. `world.spawn` an entity with `MeshFilter(HANDLE_QUAD)` +\n// `MeshRenderer(spriteMaterial)` + `Instances(...)` plus this\n// `SpriteAnimation` (frameCount / frameDuration / regions /\n// playbackMode) and `SpriteRegionOverride { region }` (the tick\n// system writes per-frame UV).\n// 4. Add `spriteAnimationTickSystem` (M4 T-23) to the schedule between\n// input/time and `RenderSystem.extract`.\n//\n// @derives `defineComponent` factory (packages/ecs/src/component.ts) —\n// `'u32'` / `'f32'` are scalar tier-1 keywords; `'array<f32>'` is a\n// tier-2 schema-vocab keyword (variable-capacity; M1 feat-20260515\n// buffer-array vocab). Layer-3 default fallback fills missing\n// `currentFrame` / `accumDt` / `playbackMode` with 0\n// (component-default-fallback typeDefault table).\n// @consumes M4 T-23 (`spriteAnimationTickSystem` reads all 6 fields and\n// writes per-frame slice into SpriteRegionOverride).\n//\n// charter mapping: F1 (single-import barrel discovery + 4-step recipe\n// at the JSDoc head); P3 (4 explicit error fields surface via the M4\n// tick-system fail-fast — `regions.length` mismatch / `frameDuration`\n// non-positive routes through SpriteAnimationInvalidError, M1 T-05);\n// P4 (consistent abstraction — same numeric closed-union encoding as\n// Tonemap / TransparentSortConfig.mode); P5 (producer / consumer\n// separation — atlas regions are produced build-time by\n// vite-plugin-image and consumed runtime as a flat Float32Array; AI\n// users never call a packer at runtime).\n//\n// Anchors: plan-strategy section 2 D-5 + D-6 + section 3.1 SAC + section\n// 4 risks R-SCHEMA-1 + R-SCHEMA-2 + R-TIME-1 reaction; plan-tasks.json\n// T-12; research F-2 + F-3 + F-5; requirements section AC-02 + section\n// 2.3 + section 2.5 + section 7 boundary table.\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\n/**\n * Per-entity sprite frame-tick clock.\n *\n * Schema (6 fields, 1:1 with requirements section 2.3):\n * - `frameCount: u32` — total frames (>= 1).\n * - `frameDuration: f32` — seconds per frame (> 0).\n * - `currentFrame: u32` — live frame index (0..frameCount). Layer-3\n * default `0` when omitted at spawn.\n * - `accumDt: f32` — dt residue carried across ticks. Layer-3 default\n * `0` when omitted; lives on the component (not on a system-side\n * resource) so the system stays stateless and AI-user setFrame paths\n * can reset both `currentFrame` and `accumDt` atomically.\n * - `regions: array<f32>` — flat per-frame UV rectangles\n * `[uMin, vMin, uW, vH]`; runtime invariant\n * `regions.length === frameCount * 4` (enforced by the M4 tick system).\n * - `playbackMode: u32` — numeric encoding of `SpritePlaybackMode`;\n * `SPRITE_PLAYBACK_MODE_LOOP = 0` (default) /\n * `SPRITE_PLAYBACK_MODE_CLAMP = 1`.\n *\n * Pair with `SpriteRegionOverride` (T-11) — the tick system writes the\n * per-frame UV slice into the override column, which `render-system-\n * extract` then reads in the sprite bucket branch.\n *\n * @example Spawn a 4-frame walk cycle that loops:\n * import { MeshFilter, MeshRenderer } from '@forgeax/engine-render';\n * import {\n * SpriteAnimation, SpriteRegionOverride, SPRITE_PLAYBACK_MODE_LOOP,\n * } from '@forgeax/engine-render/authoring';\n * import { Transform } from '@forgeax/engine-scene';\n * import { HANDLE_QUAD } from '@forgeax/engine-assets-runtime';\n *\n * // 4 frames packed in an atlas, each 64x64 inside a 256x64 row:\n * const regions = new Float32Array([\n * 0.00, 0, 0.25, 1, // walk-0\n * 0.25, 0, 0.25, 1, // walk-1\n * 0.50, 0, 0.25, 1, // walk-2\n * 0.75, 0, 0.25, 1, // walk-3\n * ]);\n * world.spawn(\n * { component: Transform, data: { pos: [0, 0, 0],\n * quat: [0, 0, 0, 1], scale: [1, 1, 1] } },\n * { component: MeshFilter, data: { assetHandle: HANDLE_QUAD } },\n * { component: MeshRenderer, data: { materials: [spriteMaterial] } },\n * { component: SpriteAnimation,\n * data: {\n * frameCount: 4,\n * frameDuration: 0.1,\n * regions,\n * playbackMode: SPRITE_PLAYBACK_MODE_LOOP,\n * } },\n * { component: SpriteRegionOverride,\n * data: { region: new Float32Array([0, 0, 0.25, 1]) } },\n * );\n *\n * @example Manual setFrame — jump to frame 2 atomically:\n * world.set(entity, SpriteAnimation,\n * { currentFrame: 2, accumDt: 0 }).unwrap();\n *\n * Error path (M4 T-23 routes through `SpriteAnimationInvalidError`,\n * `EcsErrorCode === 'sprite-animation-invalid'`; charter P3):\n * - `regions.length !== frameCount * 4` -> detail.field = 'regions-length',\n * detail carries `regionsLength` + `frameCount`.\n * - `frameDuration <= 0` -> detail.field = 'frame-duration', detail carries\n * `frameDuration`.\n */\nexport const SpriteAnimation = defineComponent('SpriteAnimation', {\n frameCount: { type: 'u32' },\n frameDuration: { type: 'f32' },\n currentFrame: { type: 'u32', transient: true },\n accumDt: { type: 'f32', transient: true },\n regions: { type: 'array<f32>' },\n playbackMode: { type: 'u32' },\n});\n","// @forgeax/engine-runtime - SpriteInstances component (per-entity 2D\n// instanced-draw transforms + per-instance UV region).\n//\n// Schema: 2 array<f32> fields. `transforms` carries packed column-major mat4\n// instance transforms (16 f32 per instance, stride = 16). `regions` carries\n// packed per-instance UV vec4 (4 f32 per instance, stride = 4; layout\n// [uMin, vMin, uW, vH] mirroring SpriteAnimation.regions). The pair share\n// the same instance count; the SSOT invariant is\n// transforms.length / 16 === regions.length / 4\n// enforced through a TWO-LAYER contract:\n//\n// 1. AI user set-site: spawn / `world.set` / `world.push` callers pass two\n// Float32Arrays whose lengths satisfy the stride pair. The set site is\n// the AI user's responsibility — the engine cannot prove column-major\n// mat4 packing or per-instance UV intent without caller declaration.\n// 2. RenderSystem extract entry: `render-system-extract.ts` performs a\n// defensive `transforms.length / 16 === regions.length / 4` check on\n// every `world.get(e, SpriteInstances)` snapshot at frame extract time;\n// violations route a structured `SpriteInstancesCountMismatchError`\n// (`code: 'sprite-instances-count-mismatch'`,\n// `detail: { transformsLength, regionsLength, expectedStride: { transforms: 16, regions: 4 } }`)\n// through the World Layer-3 ErrorHandler and the renderable is skipped.\n// Two further extract-entry checks fire:\n// - `'sprite-instances-requires-sprite-shader'` — MaterialAsset's\n// first pass `shader` must be `'forgeax::sprite'`.\n// - `'sprite-instances-mutually-exclusive-with-instances'` — same\n// entity must not carry both Instances + SpriteInstances.\n// (Error class declarations live in `@forgeax/engine-ecs` errors.ts; the\n// extract-entry fire path is owned by feat M3 w12 / w13.)\n//\n// Peer relation to Instances (charter P4 consistent abstraction):\n// - Instances : 3D scene primitive — per-instance mat4 only (stride 16).\n// - SpriteInstances : 2D scene primitive — per-instance mat4 + per-instance\n// UV region (interleaved 80B per instance: 64B mat4 + 16B region).\n// AI users pick by data shape (does the per-instance carry UV?). Both ride\n// the array-vocab path and route through the same Layer-3 error envelope.\n//\n// Group transform chained semantics (charter proposition 5 mental migration):\n// When the same entity carries both `Transform` (entity_world) and\n// `SpriteInstances` (per-instance local transforms), the vertex shader\n// composes per instance:\n// world_position[i] = entity_world * instances_local[i] * vertex_position\n// `SpriteInstances.transforms[i*16..i*16+15]` is interpreted as a local-\n// space transform under the entity, exactly like `Instances.transforms`.\n// Set the entity's `Transform` to identity to make `instances_local[i]`\n// directly world-space.\n//\n// Uniform / storage buffer cap (research D-R-4 + AC-04): 80B per instance\n// * 128-cap fallback = 10240 B < 16384 B uniform max; the storage-buffer\n// path is uncapped and used by capable backends (RenderSystem record-stage\n// cap-gate).\n//\n// 4-segment minimum contract (read this header before reaching for the\n// source body):\n//\n// ===== (a) single-component import + spawn example =====\n//\n// import {\n// createRenderer,\n// MeshFilter, MeshRenderer, Transform,\n// SpriteInstances, type SpriteInstancesData,\n// } from '@forgeax/engine-render';\n//\n// // 1 entity rendering N instanced sprites (16N transforms f32 + 4N regions f32):\n// const transforms = new Float32Array(N * 16);\n// const regions = new Float32Array(N * 4);\n// // ... fill column-major mat4 columns + [uMin, vMin, uW, vH] per instance ...\n// world.spawn(\n// { component: MeshFilter, data: { assetHandle: HANDLE_QUAD } },\n// { component: MeshRenderer, data: { /* sprite-shaded MaterialAsset */ } },\n// { component: SpriteInstances, data: { transforms, regions } },\n// );\n//\n// ===== (b) packed mat4 + region layout =====\n//\n// const transforms = new Float32Array(N * 16); // column-major mat4 per instance\n// const regions = new Float32Array(N * 4); // [uMin, vMin, uW, vH] per instance\n// // instance i occupies floats:\n// // transforms[i*16 .. i*16+15] — column-major mat4 (translation in m03/m13/m23)\n// // regions [i* 4 .. i* 4+ 3] — uMin, vMin, uW, vH (atlas-normalized UV rect)\n//\n// `transforms.length` MUST be a non-zero multiple of 16; `regions.length`\n// MUST be a non-zero multiple of 4; the per-instance count derived from\n// both MUST agree. AI users gate at the set / push site; the RenderSystem\n// extract entry holds the second defensive (see error path 1 below).\n//\n// ===== (c) error code consumption (typed property access, no message regex) =====\n//\n// // Stride / mutual-exclusion / sprite-shader violations surface through\n// // the engine-ecs Layer-3 ErrorHandler when extract reads a malformed\n// // snapshot:\n// // on('error', (err) => {\n// // switch (err.code) {\n// // case 'sprite-instances-count-mismatch':\n// // // err.detail.transformsLength / regionsLength / expectedStride\n// // break;\n// // case 'sprite-instances-requires-sprite-shader':\n// // // err.detail.entityId / observedMaterialShaderId\n// // break;\n// // case 'sprite-instances-mutually-exclusive-with-instances':\n// // // err.detail.entityId\n// // break;\n// // }\n// // });\n//\n// charter mapping (charter v2 numbering, with round-1 v1 aliases retained\n// in parentheses so reviewers tracking the v1 spec can cross-reference;\n// SSOT for the v2 -> v1 alias map is the AI User Charter — see\n// .claude/skills/forgeax-closed-loop/agents/ai-user-charter.md):\n// F1 (alias: proposition 1) — single import surface\n// `import { SpriteInstances, type SpriteInstancesData } from\n// '@forgeax/engine-render'`;\n// P2 (alias: proposition 3) — machine-readable schema > prose:\n// `{ transforms: 'array<f32>', regions: 'array<f32>' }` is the SSOT,\n// stride pair documented here + enforced at the RenderSystem entry;\n// P3 (alias: proposition 4) — explicit failure: 3 structured EcsError\n// codes route per failure shape, not silent half-row;\n// P4 (alias: proposition 5) — consistent abstraction: SpriteInstances\n// mirrors Instances — both ride the array-vocab path; pick by data\n// shape, not by API.\n//\n// Anchors: requirements AC-01 (component schema), AC-03 (3 error codes),\n// AC-09 (IDE autocomplete + type inference); plan-strategy D-1 (interleaved\n// single binding slot), D-6 (3 codes declared in M1 ecs, fired in M3 render),\n// D-7 (type export location), D-8 (barrel re-export at runtime, not ecs).\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\n/**\n * Per-entity 2D instanced-draw primitive (ECS component).\n *\n * Carries two variable-length `array<f32>` fields:\n * - `transforms` — column-major mat4 per instance (16 f32, stride 16);\n * - `regions` — UV vec4 per instance ([uMin, vMin, uW, vH], 4 f32,\n * stride 4).\n *\n * The pair share the same instance count; the invariant\n * `transforms.length / 16 === regions.length / 4` is enforced at the\n * RenderSystem extract entry (NOT at ECS write paths). The runtime\n * RenderSystem consumer materialises a fresh `Float32Array` snapshot on\n * every `world.get(e, SpriteInstances)` access and uploads an interleaved\n * 80B-per-instance buffer to the GPU in the record stage.\n *\n * @example Spawn an entity rendering 10000 instanced sprites:\n * const transforms = new Float32Array(10000 * 16);\n * const regions = new Float32Array(10000 * 4);\n * // ... fill mat4 columns + [uMin, vMin, uW, vH] ...\n * world.spawn(\n * { component: MeshFilter, data: { assetHandle: HANDLE_QUAD } },\n * { component: MeshRenderer, data: { ... } },\n * { component: SpriteInstances, data: { transforms, regions } },\n * );\n */\nexport const SpriteInstances = defineComponent('SpriteInstances', {\n transforms: { type: 'array<f32>' },\n regions: { type: 'array<f32>' },\n});\n\n/**\n * Type-level hint for `data` at the `SpriteInstances` spawn site.\n *\n * The runtime ECS column shape for `array<f32>` accepts a `Float32Array`\n * payload at spawn / set time (the bytes are copied into the BufferPool\n * slot). Both fields are typed as `Float32Array` so AI-user IDE\n * autocomplete picks up the typed-array shape and the AC-09 inference\n * surfaces without `as` casts inside `world.get(e, SpriteInstances)` and\n * QueryRow access paths.\n *\n * @example\n * import type { SpriteInstancesData } from '@forgeax/engine-render/authoring';\n * const data: SpriteInstancesData = {\n * transforms: new Float32Array(N * 16),\n * regions: new Float32Array(N * 4),\n * };\n */\nexport type SpriteInstancesData = {\n readonly transforms: Float32Array;\n readonly regions: Float32Array;\n};\n","// @forgeax/engine-runtime - SpriteRegionOverride (per-entity UV region\n// override, sprite-only).\n//\n// Schema: 1 fixed-length array column `region: 'array<f32, 4>'` carrying a\n// packed UV sub-rectangle `[uMin, vMin, uW, vH]`. The fixed `4` length is\n// enforced at compile time by the ECS schema-vocab keyword\n// `'array<T, N>'` (D-6: prefer compile-time enforcement over runtime\n// fail-fast for length-bound contracts).\n//\n// Why an entity-side override component instead of a render parameter on\n// MaterialRenderer? Plan-strategy section 1 / requirements section 5\n// constraint #1 (Pipeline Isolation R1, M1 ssot): `AssetRegistry` stays\n// append-only / read-only and `MaterialRenderer` schema is frozen.\n// Per-entity render-parameter overrides ride the same rail as Layer /\n// SortKey — one ECS column per entity, read at extract time, never\n// flowing back to the asset.\n//\n// Sprite-only consumption (requirements section 5 constraint #2 + section\n// 7 boundary line 1): `render-system-extract` reads this component ONLY\n// inside the sprite bucket branch (`pipelineTag === 'sprite'` plus the\n// asset-side sprite discriminant). Opaque (`unlit` / `standard`) buckets\n// ignore the column even when the entity happens to carry it; the M3\n// T-15 grep gate\n// (`packages/runtime/src/__tests__/sprite-only-isolation-grep-gate.test.ts`)\n// asserts this file contains zero substring matches against the asset\n// discriminant identifier as a structural lock (charter P5 producer /\n// consumer separation: the component owner never names the asset\n// discriminant directly).\n//\n// Naming: bare `SpriteRegionOverride` (no `Component` suffix per\n// AGENTS.md section Component naming \"Single-semantic components drop\n// the Component suffix\"). The `Sprite` prefix is intentional — 3D UV\n// region animation lands in a separate component (e.g. future\n// `MaterialRegionOverride`) per OOS-01 to avoid premature 3D\n// generalisation. Plan-strategy section 8 naming convention pins the\n// prefix to make the AC-11 grep gate trivially decidable.\n//\n// @derives `defineComponent` factory (packages/ecs/src/component.ts) —\n// `'array<f32, 4>'` is on the `SchemaVocabKeyword` whitelist (line ~94\n// `array<${ManagedArrayElementType}, ${number}>`).\n// @consumes M3 T-16 (`render-system-extract.ts` sprite bucket branch\n// reads override into `paramSnapshot.region`, post-M3 feat-20260625\n// ablation -- the pre-ablation per-entity hop through the snapshot\n// POD layer collapsed into the generic paramSchema-driven path).\n// @produces M4 T-23 (`spriteAnimationTickSystem` writes per-frame UV\n// slice into `region`).\n//\n// charter mapping: F1 (single-import barrel discovery — joins Layer /\n// SortKey / Transform / SpriteAnimation under a single\n// `from '@forgeax/engine-render'`); P3 (compile-time length=4 lock\n// surfaces mismatched payloads at the TS edge before the column write\n// path observes them); P4 (consistent abstraction — same per-entity\n// override shape AI users already learned for Layer / SortKey).\n//\n// Anchors: plan-strategy section 2 D-6 + section 3.1 SRO + section 4\n// risk R-SCHEMA-2 reaction; plan-tasks.json T-11; research F-5;\n// requirements section AC-01 + section 2.4 + section 5 constraint #2.\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\n/**\n * Per-entity sprite UV region override (sprite-only).\n *\n * Carries a fixed-length `Float32Array(4)` of `[uMin, vMin, uW, vH]` that\n * `render-system-extract` reads in the sprite bucket branch and writes\n * into `paramSnapshot.region`, replacing the asset-side region for\n * this entity only (feat-20260625 M3 ablation: the prior per-entity POD\n * indirection collapsed into the generic paramSchema-driven snapshot).\n * Opaque buckets ignore this component; the AC-11 grep gate keeps the\n * producer / consumer separation structural (this file never names the\n * asset-side sprite discriminant identifier).\n *\n * Pair with `SpriteAnimation` to drive the override per frame\n * (sprite-animation-tick system, M4 T-23). Standalone use (manual region\n * override without animation) is also supported — set the column once and\n * the next extract picks up the new value.\n *\n * Schema-vocab keyword `'array<f32, 4>'` (D-6) — fixed-length 4 is the\n * compile-time enforcement axis. `Float32Array` payloads with length !== 4\n * round-trip fewer / more bytes per the underlying BufferPool slot, but\n * the slot is sized at schema registration time; AI users keep the\n * payload exactly four-floats wide.\n *\n * @example Spawn a sprite entity that displays the right half of an atlas:\n * import { MeshFilter, MeshRenderer } from '@forgeax/engine-render';\n * import { SpriteRegionOverride } from '@forgeax/engine-render/authoring';\n * import { Transform } from '@forgeax/engine-scene';\n * import { HANDLE_QUAD } from '@forgeax/engine-assets-runtime';\n *\n * world.spawn(\n * { component: Transform, data: { pos: [0, 0, 0],\n * quat: [0, 0, 0, 1], scale: [1, 1, 1] } },\n * { component: MeshFilter, data: { assetHandle: HANDLE_QUAD } },\n * { component: MeshRenderer, data: { materials: [spriteMaterial] } },\n * { component: SpriteRegionOverride,\n * data: { region: new Float32Array([0.5, 0, 0.5, 1]) } },\n * );\n *\n * @example Update the override at runtime (e.g. flip-frame test):\n * world.set(entity, SpriteRegionOverride,\n * { region: new Float32Array([0, 0, 1, 1]) }).unwrap();\n */\nexport const SpriteRegionOverride = defineComponent('SpriteRegionOverride', {\n region: { type: 'array<f32, 4>' },\n});\n","// @forgeax/engine-runtime - TileLayer (one render layer of a Tilemap).\n//\n// Schema (4 fields):\n// tiles array<u32> per-cell tile id (packed Tiled .tmj wire form);\n// length == parent.Tilemap.cols * rows.\n// layerOrder i32 render-order key (higher = drawn on top).\n// dirty u8 0 means clean, non-zero means dirty - the next\n// tilemap-chunk-extract-system pass rebuilds derived\n// per-cell entities for this layer.\n// sortScope u8 (TS: 0 = 'layer' (default) - terrain semantics:\n// closed every derived entity in this\n// 'layer' | layer shares one Layer.value\n// 'per-cell' (layerOrder << 20), so the\n// union) whole layer Y-sorts as a single\n// bucket. AI users grep\n// `sortScope: 'layer'` to confirm.\n// 1 = 'per-cell' - object semantics: each derived\n// entity carries its own foot-Y\n// key; preserves per-cell entity\n// derivation for Y-interleave\n// with sprite entities sharing\n// the same Layer.value.\n//\n// Storage rationale (D-V-3 R-NEW-1 fallback / round-2): ECS schema does not\n// yet support `values: ['layer', 'per-cell']` literal-union constraints\n// on a `'string'` column, so the on-disk shape is `u8` (0/1) but every\n// AI-facing TS surface (`TileLayerData.sortScope`) is the closed\n// `'layer' | 'per-cell'` string union. The bridge functions\n// `encodeSortScope` / `decodeSortScope` are the SSOT for the two-way\n// mapping (charter F1 — single grep target).\n//\n// Each TileLayer entity attaches to a Tilemap entity via ChildOf (the parent\n// field carries the Tilemap entity). M0 supports multiple TileLayer entities\n// per Tilemap (each rendered as an independent z-ordered layer).\n//\n// charter mapping: F1 (single-import barrel + single grep target for\n// `sortScope`), P1 (progressive disclosure — `'layer'` / `'per-cell'`\n// reads directly without a magic-number table), P3 (dirty flag is\n// explicit - silent re-extraction is forbidden), P4 (handle-free row\n// schema mirrors MeshFilter / MeshRenderer conventions).\n\nimport { defineComponent, type EcsError, type EntityHandle, type World } from '@forgeax/engine-ecs';\nimport type { Result } from '@forgeax/engine-types';\n\n/**\n * Closed string-literal union for the TileLayer.sortScope field. AI users\n * grep `sortScope` and land on this single SSOT type alias; switch\n * statements over this type are exhaustive without a default arm.\n *\n * - 'layer' - terrain semantics; whole layer shares one Layer.value\n * bucket and Y-sorts together (chunkIndex is folded into 0).\n * - 'per-cell' - object semantics; each derived entity gets its own\n * chunkIndex tiebreak so it can Y-interleave with\n * sprite entities carrying the same Layer.value (e.g. a\n * player sprite riding the same SPRITE_LAYER_VALUE).\n */\nexport type SortScope = 'layer' | 'per-cell';\n\n/** Compact authoring values for the stored u8 sort-scope field. */\nexport const TilemapSort = Object.freeze({\n layer: 0 as const,\n perCell: 1 as const,\n});\n\n/**\n * Bridge: `SortScope` -> on-disk u8. SSOT for the encoding (`'layer'` -> 0,\n * `'per-cell'` -> 1). The compile-time exhaustive switch guards against\n * silent drift if the union ever grows; adding a new literal here without\n * adding its arm fails typecheck (charter P3 — closed unions never default).\n */\nexport function encodeSortScope(scope: SortScope): 0 | 1 {\n switch (scope) {\n case 'layer':\n return TilemapSort.layer;\n case 'per-cell':\n return TilemapSort.perCell;\n }\n}\n\n/**\n * Bridge: on-disk u8 -> `SortScope`. Defaults to `'layer'` for any value\n * outside `{0, 1}` (defensive — the column is typed `u8` so out-of-range\n * values can only appear if a future schema migration loosens the bound;\n * the default preserves terrain semantics which is the safer of the two).\n */\nexport function decodeSortScope(raw: number | undefined): SortScope {\n return raw === 1 ? 'per-cell' : 'layer';\n}\n\n/**\n * Public TileLayer field shape (`world.spawn({ component: TileLayer, data:\n * { ... } })` payload). `sortScope` is the closed string union surfaced to\n * AI users; the runtime row encodes it as `u8` via `encodeSortScope` at\n * spawn time so on-disk storage stays compact.\n *\n * Treat as the `TileLayer` data SSOT — `defineComponent` schema below\n * mirrors it field-for-field with the bridge `sortScope: u8` in place of\n * the union literal.\n */\nexport interface TileLayerData {\n readonly tiles: Uint32Array;\n readonly layerOrder?: number;\n readonly dirty?: number;\n readonly sortScope?: SortScope;\n}\n\n/**\n * TileLayer component (M0 baseline rebuild + round-2 sortScope rename).\n *\n * AI users typically spawn a TileLayer + ChildOf pair pointing at an\n * existing Tilemap entity:\n *\n * @example\n * const tilesArray = new Uint32Array(cols * rows);\n * tilesArray[5 * cols + 7] = 1; // tile id 1 at cell (7, 5)\n * world.spawn(\n * { component: TileLayer, data: { tiles: tilesArray, layerOrder: 0 } },\n * { component: ChildOf, data: { parent: tilemapEntity } },\n * );\n *\n * Object-layer variant (Y-interleave with sprite entities):\n *\n * > NOTE: schema storage is `u8` (ECS schema does not support\n * > string-literal-union column constraints; see R-NEW-2). The\n * > AI-user surface is the closed `SortScope` string union, but\n * > `world.spawn` requires the numeric encoding — pass through\n * > `encodeSortScope('per-cell')` rather than the literal string.\n *\n * @example\n * world.spawn(\n * { component: TileLayer, data: {\n * tiles: objectTiles,\n * layerOrder: 1000,\n * sortScope: encodeSortScope('per-cell'),\n * } },\n * { component: ChildOf, data: { parent: tilemapEntity } },\n * );\n *\n * Defaults: `layerOrder = 0`, `dirty = 0`, `sortScope = 'layer'` (stored\n * as `u8 = 0`, i.e. `encodeSortScope('layer')`). `tiles` has no default -\n * AI users supply the per-cell array at spawn time. To trigger a re-build\n * after mutating tiles in place, call `markTileLayerDirty(world, layer)`.\n */\nexport const TileLayer = defineComponent('TileLayer', {\n tiles: { type: 'array<u32>' },\n layerOrder: { type: 'i32', default: 0 },\n dirty: { type: 'u8', default: 0 },\n sortScope: { type: 'u8', default: 0 },\n});\n\n/**\n * Mark a TileLayer entity dirty so the next `tilemapChunkExtractSystem`\n * pass purges and re-spawns its derived per-cell entities. Use this after\n * mutating `TileLayer.tiles` (e.g. an in-place patch via a column view).\n *\n * Returns the underlying ECS write result - on `err` branch the caller\n * can read `.code` to recover (`'stale-entity'` if the layer was\n * despawned, `'component-not-present'` if the entity is missing the\n * TileLayer column; both kebab-case literals are members of the closed\n * `EcsErrorCode` union).\n */\nexport function markTileLayerDirty(\n world: World,\n layerEntity: EntityHandle,\n): Result<void, EcsError> {\n return world.set(layerEntity, TileLayer, { dirty: 1 });\n}\n","// @forgeax/engine-runtime - Tilemap (grid + tileset reference).\n//\n// Schema (5 fields):\n// cols u32 total grid columns\n// rows u32 total grid rows\n// tileSize array<f32, 2> per-cell world [width, height] (default [1, 1];\n// feat-20260709 M3: collapsed from the tileSizeX\n// / tileSizeY scalar pair into one inline column)\n// chunkSize u32 per-chunk axis-length in cells (default 16)\n// tileset string durable TilesetAsset GUID\n//\n// Naming: single-semantic Tilemap (AGENTS.md §Component naming drops\n// `Component` suffix). One Tilemap entity per grid; TileLayer entities\n// attach via ChildOf relationship and supply the per-cell tile id array\n// for a single render-layer.\n//\n// charter mapping: F1 (single-import barrel from `@forgeax/engine-runtime`),\n// P1 (progressive disclosure - defaults cover the common case), P4 (durable\n// asset identity stays separate from World-local handles).\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\n/**\n * Tilemap component (M0 baseline rebuild).\n *\n * A Tilemap entity carries grid metadata + a single durable `tileset` GUID. The\n * actual per-cell tile id array lives on attached `TileLayer` entities\n * (one per render layer; ChildOf points back to the Tilemap entity).\n *\n * Defaults:\n * - `tileSize = [1, 1]` (unit-cell world coordinates).\n * - `chunkSize = 16` (tilemap-chunk-extract-system chunks 16x16 cells).\n *\n * @example Spawn a 32x32 unit-cell Tilemap referencing a TilesetAsset:\n * const tilemap = world.spawn(\n * { component: Tilemap, data: { cols: 32, rows: 32, tileset } },\n * { component: Transform, data: {} },\n * ).unwrap();\n */\nexport const Tilemap = defineComponent('Tilemap', {\n cols: { type: 'u32', default: 0 },\n rows: { type: 'u32', default: 0 },\n // tileSize carries an explicit layer-2 default [1,1] (unit cell); the array\n // layer-3 fallback is all-zero, so the default MUST be explicit (D-5).\n tileSize: { type: 'array<f32, 2>', default: new Float32Array([1, 1]) },\n chunkSize: { type: 'u32', default: 16 },\n tileset: { type: 'string' },\n});\n","// @forgeax/engine-runtime - ActiveCamera KV resource + selection helper.\n//\n// feat-20260630-viewport-2x2-run-x-display-redesign M2 w12 / plan-strategy D-2.\n//\n// PROBLEM (research Finding 4): the render extract stage selects the camera by\n// archetype-query FIRST-HIT (`cameras[0]`) and fires `render-system-multi-camera`\n// when more than one [Camera, Transform, Entity] entity exists. A single engine\n// world that carries BOTH an editor orbit camera AND a game camera therefore\n// cannot pick which one renders. This module adds the minimum neutral mechanism:\n// an `ActiveCamera { entity }` resource naming the entity to render through.\n//\n// ENGINE-NEUTRAL (requirements OOS-4 / AC-16): the engine knows only entity IDs.\n// It does NOT know which entity is \"editor\" or \"game\" -- the caller (editor side)\n// decides what `ActiveCamera.entity` points at. No editor concept enters this\n// file or the engine layer.\n//\n// BACKWARD COMPATIBLE (plan-strategy D-2): when the resource is ABSENT, or the\n// named entity is not among the queried cameras, selection falls back to the\n// existing first-hit behavior unchanged. Single-camera scenes are unaffected.\n//\n// Surface:\n// - interface ActiveCamera { entity: number }\n// - constant ACTIVE_CAMERA_KEY = 'ActiveCamera'\n// - helper getActiveCamera(world): ActiveCamera | undefined\n// - helper setActiveCamera(world, entity): void\n// - pure selectActiveCameraIndex(cameraEntities, activeEntity): number\n//\n// @new-surface KV resource: ECS has no defineResource factory; the TS POD\n// interface + string KV key form is the minimum-new-surface route, mirroring\n// TransparentSortConfig. The world resource store\n// (insertResource / getResource / hasResource) is reused unchanged.\n// @derives world.hasResource / world.insertResource / world.getResource KV API.\n// @fallback getActiveCamera KV missing returns undefined; no warn; no throw\n// (absent ActiveCamera is a legal state -> first-hit fallback in extract).\n//\n// charter mapping: F1 (single-import barrel + single entity pointer, smallest\n// concept face vs a multi-field priority/enabled scheme) + P4 (consistent\n// abstraction -- same world.{has,get,insert}Resource KV API as every other\n// engine resource consumer).\n\nimport type { World } from '@forgeax/engine-ecs';\n\n// ────────────────────────────────────────────────────────────────────────────\n// POD interface + KV key\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Active-camera pointer (plain-data POD). Lives as a world-level resource keyed\n * by `ACTIVE_CAMERA_KEY`. `entity` is the packed entity id (engine `EntityHandle`\n * is a branded number) of the camera the renderer should use.\n *\n * The engine treats `entity` as an opaque id; whether it names an editor camera\n * or a game camera is a caller-side decision (OOS-4 — engine stays neutral).\n */\nexport interface ActiveCamera {\n readonly entity: number;\n}\n\n/** World resource key for the `ActiveCamera` KV entry. */\nexport const ACTIVE_CAMERA_KEY = 'ActiveCamera' as const;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Helpers\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Read the world's `ActiveCamera` resource.\n *\n * @fallback KV missing returns `undefined` — absent ActiveCamera is a legal\n * state (the renderer falls back to archetype first-hit). NO warn, NO throw.\n * The `hasResource` guard precedes the read so this helper never trips\n * `ResourceNotFoundError` from `world.getResource`.\n *\n * @example\n * const a = getActiveCamera(world); // undefined when not set\n * if (a) { ... a.entity ... }\n */\nexport function getActiveCamera(world: World): ActiveCamera | undefined {\n if (!world.hasResource(ACTIVE_CAMERA_KEY)) return undefined;\n return world.getResource<ActiveCamera>(ACTIVE_CAMERA_KEY);\n}\n\n/**\n * Write the world's `ActiveCamera` resource (idempotent last-write-wins via\n * `world.insertResource`). The renderer will use the camera whose entity id\n * equals `entity`, or fall back to first-hit if that id is not a queried camera.\n *\n * @example\n * setActiveCamera(world, gameCameraEntity); // render through the game camera\n */\nexport function setActiveCamera(world: World, entity: number): void {\n world.insertResource<ActiveCamera>(ACTIVE_CAMERA_KEY, { entity });\n}\n\n/**\n * Pure selection: given the entity ids of every camera surfaced by the extract\n * archetype query (in query order) and the optional active-camera entity id,\n * return the index of the active camera in `cameraEntities`, or `-1` to signal\n * \"no selection — use first-hit fallback\".\n *\n * `-1` is returned when `activeEntity` is `undefined` (resource absent) OR when\n * the id is not present among `cameraEntities` (stale / non-camera entity).\n * Both cases preserve the existing first-hit behavior (plan-strategy D-2).\n *\n * @example\n * selectActiveCameraIndex([10, 20, 30], 20) === 1 // pick the 2nd camera\n * selectActiveCameraIndex([10, 20, 30], undefined) === -1 // first-hit\n * selectActiveCameraIndex([10, 20, 30], 999) === -1 // first-hit\n */\nexport function selectActiveCameraIndex(\n cameraEntities: readonly number[],\n activeEntity: number | undefined,\n): number {\n if (activeEntity === undefined) return -1;\n return cameraEntities.indexOf(activeEntity);\n}\n"]}
@@ -1,32 +0,0 @@
1
- import { defineComponent } from '@forgeax/engine-ecs';
2
-
3
- // src/components/glyph-text.ts
4
- var GlyphText = defineComponent("GlyphText", {
5
- // The layout/render owner re-resolves the font asset on the target world;
6
- // authoring text and style remain portable simulation state.
7
- fontHandle: {
8
- type: "shared<FontAsset>",
9
- default: 0,
10
- simulationTransient: true
11
- },
12
- text: { type: "string", default: "" },
13
- fontSize: { type: "f32", default: 16 },
14
- // color carries an explicit layer-2 default [1,1,1,1] (opaque white); the
15
- // array layer-3 fallback is all-zero, so the default MUST be explicit (D-5).
16
- color: { type: "array<f32, 4>", default: new Float32Array([1, 1, 1, 1]) }
17
- });
18
-
19
- // src/components/sprite-playback-mode.ts
20
- var SPRITE_PLAYBACK_MODE_LOOP = 0;
21
- var SPRITE_PLAYBACK_MODE_CLAMP = 1;
22
- var SpritePlayback = Object.freeze({
23
- loop: SPRITE_PLAYBACK_MODE_LOOP,
24
- clamp: SPRITE_PLAYBACK_MODE_CLAMP
25
- });
26
- function spritePlaybackModeFromU32(value) {
27
- return value === SPRITE_PLAYBACK_MODE_CLAMP ? "clamp" : "loop";
28
- }
29
-
30
- export { GlyphText, SpritePlayback, spritePlaybackModeFromU32 };
31
- //# sourceMappingURL=chunk-ILQ5MEZF.mjs.map
32
- //# sourceMappingURL=chunk-ILQ5MEZF.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/components/glyph-text.ts","../src/components/sprite-playback-mode.ts"],"names":[],"mappings":";;;AAkDO,IAAM,SAAA,GAAY,gBAAgB,WAAA,EAAa;AAAA;AAAA;AAAA,EAGpD,UAAA,EAAY;AAAA,IACV,IAAA,EAAM,mBAAA;AAAA,IACN,OAAA,EAAS,CAAA;AAAA,IACT,mBAAA,EAAqB;AAAA,GACvB;AAAA,EACA,IAAA,EAAM,EAAE,IAAA,EAAM,QAAA,EAAU,SAAS,EAAA,EAAG;AAAA,EACpC,QAAA,EAAU,EAAE,IAAA,EAAM,KAAA,EAAO,SAAS,EAAA,EAAG;AAAA;AAAA;AAAA,EAGrC,KAAA,EAAO,EAAE,IAAA,EAAM,eAAA,EAAiB,OAAA,EAAS,IAAI,YAAA,CAAa,CAAC,CAAA,EAAG,CAAA,EAAG,CAAA,EAAG,CAAC,CAAC,CAAA;AACxE,CAAC;;;ACXM,IAAM,yBAAA,GAA4B,CAAA;AAGlC,IAAM,0BAAA,GAA6B,CAAA;AAGnC,IAAM,cAAA,GAAiB,OAAO,MAAA,CAAO;AAAA,EAC1C,IAAA,EAAM,yBAAA;AAAA,EACN,KAAA,EAAO;AACT,CAAU;AAeH,SAAS,0BAA0B,KAAA,EAAmC;AAC3E,EAAA,OAAO,KAAA,KAAU,6BAA6B,OAAA,GAAU,MAAA;AAC1D","file":"chunk-ILQ5MEZF.mjs","sourcesContent":["// @forgeax/engine-runtime - GlyphText component (feat-20260531-world-space-msdf-text-rendering M4 / w14).\n//\n// `GlyphText` is the authoring source component for world-space MSDF text\n// (requirements AC-06 / §domain model). It carries ONLY authoring data; the\n// glyph quad baking + MeshFilter / MeshRenderer attachment is the job of the\n// `glyphTextLayoutSystem` (plan-strategy D-2: GlyphText is pure authoring\n// data, baking is a system responsibility). There is NO `TextLayoutAsset`\n// intermediate (OOS-5) -- layout output lives directly in a baked MeshAsset.\n//\n// Naming: single-semantic component drops the `Component` suffix\n// (AGENTS.md §Component naming rule #1 -- Transform / Camera / GlyphText).\n//\n// Schema vocab:\n// - `fontHandle: 'shared<FontAsset>'` -> `Handle<'FontAsset', 'shared'>`\n// (u32-stored; AssetRegistry owns the FontAsset lifecycle). AI users\n// obtain the handle via `assets.loadByGuid<FontAsset>(guid)`.\n// - `text: 'string'` -> native JS string (UniqueRefStore-backed, same\n// dispatch as `Name.value`).\n// - `fontSize: 'f32'` -> layout scale applied to the FontAsset metrics.\n// - `color: 'array<f32, 4>'` -> linear-space rgba tint (feat-20260709 M3:\n// collapsed from four `colorR/G/B/A` scalar columns into one inline\n// stride-4 SoA column, mirroring the DirectionalLight direction/color\n// idiom). Explicit layer-2 default [1,1,1,1] (opaque white).\n//\n// charter mapping: P1 (single import surface from `@forgeax/engine-render`,\n// co-located with `glyphTextLayoutSystem` that consumes it) + P3\n// (machine-readable schema literal) + P5 (consistent abstraction: same\n// `'shared<T>'` idiom as MeshFilter.assetHandle / MeshRenderer.materials).\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\n/**\n * Glyph text authoring component (world-space MSDF text).\n *\n * Spawn an entity with a `GlyphText` and the `glyphTextLayoutSystem`\n * (auto-wired by `createRenderer` / `createApp`) lays out the glyph quads,\n * bakes a `MeshAsset`, and attaches `MeshFilter` + `MeshRenderer` on the\n * next frame (Commands-deferred). Mutating `text` / `fontSize` / `color`\n * re-bakes the mesh in place (plan-strategy D-1 updateMesh; registry size\n * unchanged, AC-08).\n *\n * @example Spawn a world-space label:\n * import { GlyphText } from '@forgeax/engine-render/authoring';\n * const font = (await assets.loadByGuid(fontGuid)).unwrap();\n * world.spawn({\n * component: GlyphText,\n * data: { fontHandle: font, text: 'Hello', fontSize: 32,\n * color: [1, 1, 1, 1] },\n * });\n */\nexport const GlyphText = defineComponent('GlyphText', {\n // The layout/render owner re-resolves the font asset on the target world;\n // authoring text and style remain portable simulation state.\n fontHandle: {\n type: 'shared<FontAsset>',\n default: 0 as never,\n simulationTransient: true,\n },\n text: { type: 'string', default: '' },\n fontSize: { type: 'f32', default: 16 },\n // color carries an explicit layer-2 default [1,1,1,1] (opaque white); the\n // array layer-3 fallback is all-zero, so the default MUST be explicit (D-5).\n color: { type: 'array<f32, 4>', default: new Float32Array([1, 1, 1, 1]) },\n});\n","// @forgeax/engine-runtime - SpritePlaybackMode (u32 column encoding + mapper).\n//\n// SSOT for the SpriteAnimation.playbackMode ECS column (M2 T-12) and the\n// runtime tick-system branch selector (M4 T-23). The shape mirrors the M1\n// `Tonemap` block in `./camera.ts:72-90` (TONEMAP_NONE = 0 /\n// TONEMAP_REINHARD_EXTENDED = 1 + `type Tonemap = 'none' |\n// 'reinhard-extended'` + `tonemapFromF32`) for charter P4 consistent\n// abstraction — AI users keep one mental model across all u32-encoded\n// closed-union schema columns.\n//\n// Why `'u32'` + constant + mapper instead of a string-literal column?\n// ECS schema whitelist `SchemaFieldType` (packages/ecs/src/component.ts\n// section schema-field-type) does not accept string-literal unions\n// (research F-2 + F-5). Storing a u32 + translating to a closed\n// `'loop' | 'clamp'` literal union at the tick-system seam preserves\n// AI-user-facing narrowing (`switch (mode) { case 'loop': ... }`)\n// without forcing the ECS column to learn a new field-type vocabulary.\n//\n// Naming convention (plan-strategy section 8.command naming):\n// SPRITE_PLAYBACK_MODE_LOOP / SPRITE_PLAYBACK_MODE_CLAMP mirror M1\n// TONEMAP_* / TRANSPARENT_SORT_MODE_*. `spritePlaybackModeFromU32`\n// mirrors `tonemapFromF32` / `cameraProjectionFromF32`. AI users\n// discover the trio via single-import barrel re-export from\n// `@forgeax/engine-runtime` (wired in by M2 T-13).\n//\n// Anchors: plan-strategy section 2 D-5 + section 3.1 PR block SPM +\n// section 4 risk R-SCHEMA-1 reaction; research F-2 + F-5;\n// requirements section AC-02 + section 2.3 playbackMode row;\n// plan-tasks.json T-07 acceptanceCheck (rg\n// \"SPRITE_PLAYBACK_MODE_LOOP|SPRITE_PLAYBACK_MODE_CLAMP|\n// spritePlaybackModeFromU32\" >= 3 hits in this file).\n\n/**\n * Playback mode discriminator literal union (requirements section AC-02 +\n * section 2.3). Two members for the MVP:\n *\n * `'loop'` — `currentFrame = (currentFrame + 1) % frameCount`; the\n * sprite-animation-tick system wraps the index when\n * `accumDt >= frameDuration` (default for hello-sprite-\n * atlas demo \"100 sprites synchronised walk cycle\").\n * `'clamp'` — `currentFrame = min(currentFrame + 1, frameCount - 1)`;\n * holds the last frame for death / terminator-animation\n * style sequences (requirements section 2.5 q8 lock).\n *\n * Future modes (`'pingpong'`, reverse playback, arbitrary frame index\n * jumps) are deferred per requirements OOS-03. The closed union shape\n * leaves room for additive growth without breaking the u32 enum encoding\n * (plan-strategy section 2 D-5).\n */\nexport type SpritePlaybackMode = 'loop' | 'clamp';\n\n/** Numeric encoding of the loop playback mode (schema value for `playbackMode`). */\nexport const SPRITE_PLAYBACK_MODE_LOOP = 0 as const;\n\n/** Numeric encoding of the clamp playback mode (schema value for `playbackMode`). */\nexport const SPRITE_PLAYBACK_MODE_CLAMP = 1 as const;\n\n/** Grouped authoring values; the numeric ECS encoding stays owner-local. */\nexport const SpritePlayback = Object.freeze({\n loop: SPRITE_PLAYBACK_MODE_LOOP,\n clamp: SPRITE_PLAYBACK_MODE_CLAMP,\n} as const);\n\n/**\n * Map a `SpriteAnimation.playbackMode` numeric column value to the closed\n * `SpritePlaybackMode` string-literal union. The defensive fallback mirrors\n * `cameraProjectionFromF32` / `tonemapFromF32` precedent — a value other\n * than `SPRITE_PLAYBACK_MODE_CLAMP` (1) maps to `'loop'`, so stale or\n * uninitialised entities surface a predictable playback shape through the\n * tick-system query (rather than throwing or returning `undefined`).\n * Validation of `playbackMode` happens at schema-write time, not here.\n *\n * The tick-system in M4 T-23 (`spriteAnimationTickSystem`) consumes the\n * return value via `switch (mode) { case 'loop': ...; case 'clamp': ... }`\n * to pick the per-branch frame-advance arithmetic.\n */\nexport function spritePlaybackModeFromU32(value: number): SpritePlaybackMode {\n return value === SPRITE_PLAYBACK_MODE_CLAMP ? 'clamp' : 'loop';\n}\n"]}