@forgeax/engine-render 0.1.33 → 0.1.35

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 (624) hide show
  1. package/README.md +1062 -127
  2. package/dist/assembly/backend-contract.d.ts +2 -0
  3. package/dist/assembly/backend-contract.d.ts.map +1 -1
  4. package/dist/assembly/barrel-distortion-inspection.d.ts +3 -0
  5. package/dist/assembly/barrel-distortion-inspection.d.ts.map +1 -0
  6. package/dist/assembly/canvas-draw-guard.d.ts +3 -0
  7. package/dist/assembly/canvas-draw-guard.d.ts.map +1 -0
  8. package/dist/assembly/cloud-shadow-entry.d.ts +4 -0
  9. package/dist/assembly/cloud-shadow-entry.d.ts.map +1 -0
  10. package/dist/assembly/device-feature-admission.d.ts +2 -2
  11. package/dist/assembly/dynamic-geometry-host.d.ts +4 -1
  12. package/dist/assembly/dynamic-geometry-host.d.ts.map +1 -1
  13. package/dist/assembly/dynamic-geometry-runtime.d.ts +1 -1
  14. package/dist/assembly/dynamic-geometry-runtime.d.ts.map +1 -1
  15. package/dist/assembly/factory.d.ts +1 -1
  16. package/dist/assembly/factory.d.ts.map +1 -1
  17. package/dist/assembly/host-contract.d.ts +6 -5
  18. package/dist/assembly/host-contract.d.ts.map +1 -1
  19. package/dist/assembly/material/assembly.d.ts.map +1 -1
  20. package/dist/assembly/material/pipeline-helpers.d.ts +5 -0
  21. package/dist/assembly/material/pipeline-helpers.d.ts.map +1 -1
  22. package/dist/assembly/material-shader-policy.d.ts +16 -2
  23. package/dist/assembly/material-shader-policy.d.ts.map +1 -1
  24. package/dist/assembly/material-shader-prewarm.d.ts.map +1 -1
  25. package/dist/assembly/recovery/device-loss-fanout.d.ts.map +1 -1
  26. package/dist/assembly/recovery/renderer-recover.d.ts +2 -0
  27. package/dist/assembly/recovery/renderer-recover.d.ts.map +1 -1
  28. package/dist/assembly/render-feature-post-processes.d.ts +6 -0
  29. package/dist/assembly/render-feature-post-processes.d.ts.map +1 -0
  30. package/dist/assembly/render-target-host.d.ts +5 -0
  31. package/dist/assembly/render-target-host.d.ts.map +1 -1
  32. package/dist/assembly/renderer-facade.d.ts.map +1 -1
  33. package/dist/assembly/renderer-feature-inspection.d.ts +1 -1
  34. package/dist/assembly/renderer-feature-inspection.d.ts.map +1 -1
  35. package/dist/assembly/renderer-frame-transaction.d.ts +12 -0
  36. package/dist/assembly/renderer-frame-transaction.d.ts.map +1 -1
  37. package/dist/assembly/renderer-inspection.d.ts +11 -0
  38. package/dist/assembly/renderer-inspection.d.ts.map +1 -1
  39. package/dist/assembly/webgpu-pbr-ready.d.ts +1 -0
  40. package/dist/assembly/webgpu-pbr-ready.d.ts.map +1 -1
  41. package/dist/assembly/webgpu-ready-per-pass.d.ts +39 -0
  42. package/dist/assembly/webgpu-ready-per-pass.d.ts.map +1 -0
  43. package/dist/assembly/webgpu-ready.d.ts +1 -1
  44. package/dist/assembly/webgpu-ready.d.ts.map +1 -1
  45. package/dist/assembly/webgpu-renderer-bootstrap.d.ts.map +1 -1
  46. package/dist/assembly/webgpu-renderer-observation-owner.d.ts +35 -0
  47. package/dist/assembly/webgpu-renderer-observation-owner.d.ts.map +1 -0
  48. package/dist/assembly/webgpu-renderer.d.ts +2 -1
  49. package/dist/assembly/webgpu-renderer.d.ts.map +1 -1
  50. package/dist/authoring.mjs +2 -4
  51. package/dist/authoring.mjs.map +1 -1
  52. package/dist/barrel-distortion.d.ts +47 -0
  53. package/dist/barrel-distortion.d.ts.map +1 -0
  54. package/dist/chunk-3XUBWRY2.mjs +1842 -0
  55. package/dist/chunk-3XUBWRY2.mjs.map +1 -0
  56. package/dist/{chunk-OO3DRYK7.mjs → chunk-G6HDNGY7.mjs} +2400 -1767
  57. package/dist/chunk-G6HDNGY7.mjs.map +1 -0
  58. package/dist/{chunk-ZDQWGQW7.mjs → chunk-LM5IE7GF.mjs} +4 -4
  59. package/dist/{chunk-ZDQWGQW7.mjs.map → chunk-LM5IE7GF.mjs.map} +1 -1
  60. package/dist/{chunk-VOZWDM3L.mjs → chunk-LNIUIKQ7.mjs} +1514 -498
  61. package/dist/chunk-LNIUIKQ7.mjs.map +1 -0
  62. package/dist/chunk-MXTWKZO4.mjs +3268 -0
  63. package/dist/chunk-MXTWKZO4.mjs.map +1 -0
  64. package/dist/chunk-MZ4C7EHF.mjs +6942 -0
  65. package/dist/chunk-MZ4C7EHF.mjs.map +1 -0
  66. package/dist/chunk-RIPAEGI6.mjs +48 -0
  67. package/dist/chunk-RIPAEGI6.mjs.map +1 -0
  68. package/dist/{chunk-LEAXOMYJ.mjs → chunk-SGPUJW3F.mjs} +117 -5
  69. package/dist/chunk-SGPUJW3F.mjs.map +1 -0
  70. package/dist/{chunk-PA5DRJNI.mjs → chunk-X2KA6WHM.mjs} +29 -4
  71. package/dist/chunk-X2KA6WHM.mjs.map +1 -0
  72. package/dist/{chunk-BLXGONR2.mjs → chunk-XSFB7XXQ.mjs} +51 -4
  73. package/dist/chunk-XSFB7XXQ.mjs.map +1 -0
  74. package/dist/cloud/density.d.ts +55 -0
  75. package/dist/cloud/density.d.ts.map +1 -0
  76. package/dist/cloud/extract.d.ts +25 -0
  77. package/dist/cloud/extract.d.ts.map +1 -0
  78. package/dist/cloud/feature.d.ts +57 -0
  79. package/dist/cloud/feature.d.ts.map +1 -0
  80. package/dist/cloud/frame-context.d.ts +8 -0
  81. package/dist/cloud/frame-context.d.ts.map +1 -0
  82. package/dist/cloud/inspection.d.ts +59 -0
  83. package/dist/cloud/inspection.d.ts.map +1 -0
  84. package/dist/cloud/optics.d.ts +56 -0
  85. package/dist/cloud/optics.d.ts.map +1 -0
  86. package/dist/cloud/parameters.d.ts +73 -0
  87. package/dist/cloud/parameters.d.ts.map +1 -0
  88. package/dist/cloud/resources.d.ts +60 -0
  89. package/dist/cloud/resources.d.ts.map +1 -0
  90. package/dist/cloud/shadow.d.ts +42 -0
  91. package/dist/cloud/shadow.d.ts.map +1 -0
  92. package/dist/cloud/temporal.d.ts +74 -0
  93. package/dist/cloud/temporal.d.ts.map +1 -0
  94. package/dist/components/barrel-distortion.d.ts +13 -0
  95. package/dist/components/barrel-distortion.d.ts.map +1 -0
  96. package/dist/components/cloud-layer.d.ts +29 -0
  97. package/dist/components/cloud-layer.d.ts.map +1 -0
  98. package/dist/components/index.d.ts +2 -0
  99. package/dist/components/index.d.ts.map +1 -1
  100. package/dist/components/instances.d.ts +20 -6
  101. package/dist/components/instances.d.ts.map +1 -1
  102. package/dist/construct-renderer.d.ts +1 -1
  103. package/dist/construct-renderer.d.ts.map +1 -1
  104. package/dist/construct-renderer.mjs +8406 -5785
  105. package/dist/construct-renderer.mjs.map +1 -1
  106. package/dist/device/gpu-residency.d.ts +19 -19
  107. package/dist/device/gpu-residency.d.ts.map +1 -1
  108. package/dist/dynamic-geometry.d.ts +5 -1
  109. package/dist/dynamic-geometry.d.ts.map +1 -1
  110. package/dist/errors/cloud.d.ts +59 -0
  111. package/dist/errors/cloud.d.ts.map +1 -0
  112. package/dist/errors/render.d.ts +20 -5
  113. package/dist/errors/render.d.ts.map +1 -1
  114. package/dist/examples/single-layer-medium-surface.d.ts +47 -0
  115. package/dist/examples/single-layer-medium-surface.d.ts.map +1 -0
  116. package/dist/extract/camera.d.ts.map +1 -1
  117. package/dist/extract/contracts.d.ts +5 -1
  118. package/dist/extract/contracts.d.ts.map +1 -1
  119. package/dist/extract/material-context.d.ts +7 -0
  120. package/dist/extract/material-context.d.ts.map +1 -0
  121. package/dist/features/barrel-distortion.d.ts +29 -0
  122. package/dist/features/barrel-distortion.d.ts.map +1 -0
  123. package/dist/features/error-reporting.d.ts +6 -2
  124. package/dist/features/error-reporting.d.ts.map +1 -1
  125. package/dist/features/host.d.ts +15 -0
  126. package/dist/features/host.d.ts.map +1 -1
  127. package/dist/features/plan.d.ts +10 -0
  128. package/dist/features/plan.d.ts.map +1 -1
  129. package/dist/features/render-graph-contribution.d.ts +5 -0
  130. package/dist/features/render-graph-contribution.d.ts.map +1 -1
  131. package/dist/features/render-graph-raster.d.ts +1 -0
  132. package/dist/features/render-graph-raster.d.ts.map +1 -1
  133. package/dist/features/targets.d.ts +2 -0
  134. package/dist/features/targets.d.ts.map +1 -1
  135. package/dist/features/types.d.ts +48 -0
  136. package/dist/features/types.d.ts.map +1 -1
  137. package/dist/fullscreen-post-process-pass.d.ts +15 -7
  138. package/dist/fullscreen-post-process-pass.d.ts.map +1 -1
  139. package/dist/glyph-text-layout-system.d.ts +1 -1
  140. package/dist/glyph-text-layout-system.d.ts.map +1 -1
  141. package/dist/gpu-dirty-ranges.d.ts +11 -0
  142. package/dist/gpu-dirty-ranges.d.ts.map +1 -0
  143. package/dist/gpu-driven/batch-topology.d.ts +17 -0
  144. package/dist/gpu-driven/batch-topology.d.ts.map +1 -1
  145. package/dist/gpu-driven/material-artifacts.d.ts +6 -0
  146. package/dist/gpu-driven/material-artifacts.d.ts.map +1 -1
  147. package/dist/gpu-driven/prepared-draw.d.ts.map +1 -1
  148. package/dist/gpu-driven/production-raster-material.d.ts +178 -0
  149. package/dist/gpu-driven/production-raster-material.d.ts.map +1 -0
  150. package/dist/gpu-driven/production-raster.d.ts +47 -3
  151. package/dist/gpu-driven/production-raster.d.ts.map +1 -1
  152. package/dist/gpu-driven/resource-allocation.d.ts +31 -0
  153. package/dist/gpu-driven/resource-allocation.d.ts.map +1 -0
  154. package/dist/gpu-driven/shadow-ownership.d.ts +14 -0
  155. package/dist/gpu-driven/shadow-ownership.d.ts.map +1 -0
  156. package/dist/gpu-driven/view-gpu.d.ts +26 -2
  157. package/dist/gpu-driven/view-gpu.d.ts.map +1 -1
  158. package/dist/gpu-scene.d.ts +5 -0
  159. package/dist/gpu-scene.d.ts.map +1 -1
  160. package/dist/hdrp-buffers.d.ts +2 -2
  161. package/dist/hdrp-buffers.d.ts.map +1 -1
  162. package/dist/ibl/frame-resources.d.ts.map +1 -1
  163. package/dist/ibl/skylight-bind-group.d.ts +14 -5
  164. package/dist/ibl/skylight-bind-group.d.ts.map +1 -1
  165. package/dist/index.d.ts +30 -7
  166. package/dist/index.d.ts.map +1 -1
  167. package/dist/index.mjs +780 -9
  168. package/dist/index.mjs.map +1 -1
  169. package/dist/inspection-types.d.ts +135 -1
  170. package/dist/inspection-types.d.ts.map +1 -1
  171. package/dist/instance-buffer-cache.d.ts +4 -4
  172. package/dist/instance-buffer-cache.d.ts.map +1 -1
  173. package/dist/instances.d.ts +47 -100
  174. package/dist/instances.d.ts.map +1 -1
  175. package/dist/internal.mjs +7 -8
  176. package/dist/internal.mjs.map +1 -1
  177. package/dist/pbr-pipeline.d.ts +22 -4
  178. package/dist/pbr-pipeline.d.ts.map +1 -1
  179. package/dist/pipeline/single-layer-medium-passes.d.ts +73 -0
  180. package/dist/pipeline/single-layer-medium-passes.d.ts.map +1 -0
  181. package/dist/pipeline/standard-forward-lane.d.ts.map +1 -1
  182. package/dist/pipeline/standard-output/graph.d.ts.map +1 -1
  183. package/dist/pipeline/standard-output/lut-gpu.d.ts +2 -2
  184. package/dist/pipeline/standard-output/lut-gpu.d.ts.map +1 -1
  185. package/dist/pipeline/standard-output/resources.d.ts +2 -2
  186. package/dist/pipeline/standard-output/resources.d.ts.map +1 -1
  187. package/dist/pipeline/standard-output/types.d.ts +4 -2
  188. package/dist/pipeline/standard-output/types.d.ts.map +1 -1
  189. package/dist/pipeline/standard-pipeline.d.ts.map +1 -1
  190. package/dist/pipeline/standard-post.d.ts.map +1 -1
  191. package/dist/pipeline-builder.d.ts +1 -1
  192. package/dist/pipeline-builder.d.ts.map +1 -1
  193. package/dist/plugin.d.ts.map +1 -1
  194. package/dist/prepare/prepared-graphics-resolver.d.ts +2 -0
  195. package/dist/prepare/prepared-graphics-resolver.d.ts.map +1 -1
  196. package/dist/publication/contract.d.ts +77 -0
  197. package/dist/publication/contract.d.ts.map +1 -0
  198. package/dist/publication/dependencies.d.ts +7 -0
  199. package/dist/publication/dependencies.d.ts.map +1 -0
  200. package/dist/publication/prepare-geometry.d.ts +9 -0
  201. package/dist/publication/prepare-geometry.d.ts.map +1 -0
  202. package/dist/publication/programs.d.ts +5 -0
  203. package/dist/publication/programs.d.ts.map +1 -0
  204. package/dist/publication/publisher.d.ts +33 -0
  205. package/dist/publication/publisher.d.ts.map +1 -0
  206. package/dist/publication/receiver.d.ts +29 -0
  207. package/dist/publication/receiver.d.ts.map +1 -0
  208. package/dist/publication/resource-scope.d.ts +18 -0
  209. package/dist/publication/resource-scope.d.ts.map +1 -0
  210. package/dist/publication/targets.d.ts +33 -0
  211. package/dist/publication/targets.d.ts.map +1 -0
  212. package/dist/publication/video.d.ts +5 -0
  213. package/dist/publication/video.d.ts.map +1 -0
  214. package/dist/record/barrel-distortion-frame.d.ts +15 -0
  215. package/dist/record/barrel-distortion-frame.d.ts.map +1 -0
  216. package/dist/record/dynamic-geometry-consumption.d.ts +10 -2
  217. package/dist/record/dynamic-geometry-consumption.d.ts.map +1 -1
  218. package/dist/record/fold-buckets.d.ts +95 -0
  219. package/dist/record/fold-buckets.d.ts.map +1 -0
  220. package/dist/record/fold-instance-buffer.d.ts +6 -0
  221. package/dist/record/fold-instance-buffer.d.ts.map +1 -0
  222. package/dist/record/frame-lighting.d.ts +1 -0
  223. package/dist/record/frame-lighting.d.ts.map +1 -1
  224. package/dist/record/frame-snapshot.d.ts +43 -9
  225. package/dist/record/frame-snapshot.d.ts.map +1 -1
  226. package/dist/record/frame.d.ts +15 -65
  227. package/dist/record/frame.d.ts.map +1 -1
  228. package/dist/record/gpu-draw-receipts.d.ts +11 -0
  229. package/dist/record/gpu-draw-receipts.d.ts.map +1 -0
  230. package/dist/record/gpu-timing.d.ts +8 -0
  231. package/dist/record/gpu-timing.d.ts.map +1 -1
  232. package/dist/record/helpers.d.ts +2 -2
  233. package/dist/record/helpers.d.ts.map +1 -1
  234. package/dist/record/main-pass-geometry.d.ts +22 -6
  235. package/dist/record/main-pass-geometry.d.ts.map +1 -1
  236. package/dist/record/main-pass-material.d.ts +14 -10
  237. package/dist/record/main-pass-material.d.ts.map +1 -1
  238. package/dist/record/main-pass-sprite-draws.d.ts +3 -16
  239. package/dist/record/main-pass-sprite-draws.d.ts.map +1 -1
  240. package/dist/record/main-pass.d.ts +13 -2
  241. package/dist/record/main-pass.d.ts.map +1 -1
  242. package/dist/record/motion-blur-receipt.d.ts +11 -0
  243. package/dist/record/motion-blur-receipt.d.ts.map +1 -0
  244. package/dist/record/prepared-material-bindings.d.ts +3 -3
  245. package/dist/record/prepared-material-bindings.d.ts.map +1 -1
  246. package/dist/record/probe-blend-buffer.d.ts +16 -0
  247. package/dist/record/probe-blend-buffer.d.ts.map +1 -0
  248. package/dist/record/recovery-pipeline.d.ts.map +1 -1
  249. package/dist/record/render-context.d.ts +24 -5
  250. package/dist/record/render-context.d.ts.map +1 -1
  251. package/dist/record/shadow-pass.d.ts +2 -0
  252. package/dist/record/shadow-pass.d.ts.map +1 -1
  253. package/dist/record/skybox-post-pass.d.ts +1 -1
  254. package/dist/record/skybox-post-pass.d.ts.map +1 -1
  255. package/dist/record/sprite-instance-buffer.d.ts +31 -0
  256. package/dist/record/sprite-instance-buffer.d.ts.map +1 -0
  257. package/dist/record/target-capture-graph.d.ts +19 -0
  258. package/dist/record/target-capture-graph.d.ts.map +1 -0
  259. package/dist/record/typed-frame-graph.d.ts +24 -15
  260. package/dist/record/typed-frame-graph.d.ts.map +1 -1
  261. package/dist/record/view-ubo.d.ts +11 -3
  262. package/dist/record/view-ubo.d.ts.map +1 -1
  263. package/dist/record/volume-params.d.ts +9 -0
  264. package/dist/record/volume-params.d.ts.map +1 -0
  265. package/dist/recovery/render-system-candidate.d.ts +14 -4
  266. package/dist/recovery/render-system-candidate.d.ts.map +1 -1
  267. package/dist/reflection/record-owner.d.ts.map +1 -1
  268. package/dist/render-contract.d.ts +46 -5
  269. package/dist/render-contract.d.ts.map +1 -1
  270. package/dist/render-graph-primitives.d.ts.map +1 -1
  271. package/dist/render-pipeline.d.ts +103 -2
  272. package/dist/render-pipeline.d.ts.map +1 -1
  273. package/dist/render-system-extract-tail.d.ts +3 -2
  274. package/dist/render-system-extract-tail.d.ts.map +1 -1
  275. package/dist/render-system-extract.d.ts +18 -9
  276. package/dist/render-system-extract.d.ts.map +1 -1
  277. package/dist/render-system-presentation.d.ts +23 -0
  278. package/dist/render-system-presentation.d.ts.map +1 -0
  279. package/dist/render-system-producer-roots.d.ts +10 -0
  280. package/dist/render-system-producer-roots.d.ts.map +1 -0
  281. package/dist/render-system-projections.d.ts +3 -2
  282. package/dist/render-system-projections.d.ts.map +1 -1
  283. package/dist/render-system-residency.d.ts +12 -0
  284. package/dist/render-system-residency.d.ts.map +1 -0
  285. package/dist/render-system.d.ts +22 -21
  286. package/dist/render-system.d.ts.map +1 -1
  287. package/dist/scene/probe-blend.d.ts +27 -0
  288. package/dist/scene/probe-blend.d.ts.map +1 -1
  289. package/dist/scene/render-scene.d.ts +18 -7
  290. package/dist/scene/render-scene.d.ts.map +1 -1
  291. package/dist/scene/render-source.d.ts +42 -0
  292. package/dist/scene/render-source.d.ts.map +1 -0
  293. package/dist/scene/source-systems.d.ts +6 -0
  294. package/dist/scene/source-systems.d.ts.map +1 -0
  295. package/dist/ssao-buffers.d.ts +9 -0
  296. package/dist/ssao-buffers.d.ts.map +1 -1
  297. package/dist/surface/dynamic-input.d.ts +133 -0
  298. package/dist/surface/dynamic-input.d.ts.map +1 -0
  299. package/dist/surface/gpu-driven.d.ts +41 -0
  300. package/dist/surface/gpu-driven.d.ts.map +1 -0
  301. package/dist/surface/submission-observation.d.ts +136 -0
  302. package/dist/surface/submission-observation.d.ts.map +1 -0
  303. package/dist/systems/skin-palette-allocator.d.ts.map +1 -1
  304. package/dist/systems/skin-palette-types.d.ts +10 -0
  305. package/dist/systems/skin-palette-types.d.ts.map +1 -1
  306. package/dist/systems/transparent-dispatch.d.ts +2 -2
  307. package/dist/systems/transparent-dispatch.d.ts.map +1 -1
  308. package/dist/systems/transparent-sort-config.d.ts +2 -1
  309. package/dist/systems/transparent-sort-config.d.ts.map +1 -1
  310. package/dist/temporal/gpu.d.ts +13 -1
  311. package/dist/temporal/gpu.d.ts.map +1 -1
  312. package/dist/temporal/index.mjs +6 -7
  313. package/dist/temporal/inspection.d.ts.map +1 -1
  314. package/dist/temporal/standard-scene-data.d.ts.map +1 -1
  315. package/dist/temporal/target-coverage-attachment.d.ts.map +1 -1
  316. package/dist/transmission/single-layer-medium.d.ts +89 -0
  317. package/dist/transmission/single-layer-medium.d.ts.map +1 -0
  318. package/dist/typed-render-graph-primitives.d.ts +14 -2
  319. package/dist/typed-render-graph-primitives.d.ts.map +1 -1
  320. package/dist/volume/component.d.ts +9 -4
  321. package/dist/volume/component.d.ts.map +1 -1
  322. package/dist/volume/extract.d.ts +1 -1
  323. package/dist/volume/extract.d.ts.map +1 -1
  324. package/dist/volume/inspection.d.ts +2 -0
  325. package/dist/volume/inspection.d.ts.map +1 -1
  326. package/dist/volume/passes.d.ts +4 -1
  327. package/dist/volume/passes.d.ts.map +1 -1
  328. package/dist/volume/resources.d.ts.map +1 -1
  329. package/package.json +22 -21
  330. package/src/__tests__/atmosphere-daylight.dawn.test.ts +72 -0
  331. package/src/__tests__/auto-exposure-transaction.integration.test.ts +4 -9
  332. package/src/__tests__/barrel-distortion-lkg.integration.test.ts +353 -0
  333. package/src/__tests__/barrel-distortion.dawn.test.ts +41 -0
  334. package/src/__tests__/barrel-distortion.unit.test.ts +364 -0
  335. package/src/__tests__/construct-renderer-identity.unit.test.ts +49 -0
  336. package/src/__tests__/detached-recovery-graph.unit.test.ts +277 -0
  337. package/src/__tests__/device-feature-admission.unit.test.ts +3 -2
  338. package/src/__tests__/device-loss-fanout.unit.test.ts +36 -1
  339. package/src/__tests__/docs-gate-green.unit.test.ts +112 -1
  340. package/src/__tests__/factory-contract.integration.test.ts +295 -45
  341. package/src/__tests__/feature-depth-input.dawn.test.ts +129 -2
  342. package/src/__tests__/fullscreen-feature-plan.unit.test.ts +14 -3
  343. package/src/__tests__/gpu-dirty-ranges.unit.test.ts +22 -0
  344. package/src/__tests__/gpu-driven-baseline.characterization.test.ts +16 -3
  345. package/src/__tests__/gpu-driven-batch-topology-pbr.unit.test.ts +12 -0
  346. package/src/__tests__/gpu-driven-material-artifacts.unit.test.ts +143 -0
  347. package/src/__tests__/gpu-driven-pbr.dawn.test.ts +5 -6
  348. package/src/__tests__/gpu-driven-production.integration.test.ts +482 -3
  349. package/src/__tests__/gpu-driven-shadow-views.dawn.test.ts +6 -5
  350. package/src/__tests__/gpu-driven-view-gpu-evidence.ts +94 -6
  351. package/src/__tests__/gpu-driven-view-graph.integration.test.ts +18 -2
  352. package/src/__tests__/gpu-driven-view.browser.test.ts +5 -8
  353. package/src/__tests__/gpu-driven-view.dawn.test.ts +6 -2
  354. package/src/__tests__/gpu-driven-view.unit.test.ts +1 -1
  355. package/src/__tests__/gpu-pass-timing-lifecycle.integration.test.ts +1 -0
  356. package/src/__tests__/gpu-pass-timing.browser.test.ts +6 -4
  357. package/src/__tests__/gpu-pass-timing.rhi-null.unit.test.ts +1 -0
  358. package/src/__tests__/gpu-scene.unit.test.ts +119 -9
  359. package/src/__tests__/instance-allocation-failure.unit.test.ts +57 -0
  360. package/src/__tests__/instances-culling.integration.test.ts +10 -36
  361. package/src/__tests__/instances-store.unit.test.ts +97 -305
  362. package/src/__tests__/instances-world-ownership.integration.test.ts +62 -0
  363. package/src/__tests__/ktx2-basis-gpu-consumer.dawn.test.ts +4 -1
  364. package/src/__tests__/main-pass-material-medium-selection.unit.test.ts +145 -0
  365. package/src/__tests__/material-shader-prewarm.unit.test.ts +59 -0
  366. package/src/__tests__/material-snapshot-mutation.integration.test.ts +39 -1
  367. package/src/__tests__/materials-standard-contract.unit.test.ts +0 -1
  368. package/src/__tests__/morph-culling-reentry.dawn.test.ts +5 -5
  369. package/src/__tests__/morph-visual-evidence.integration.test.ts +8 -7
  370. package/src/__tests__/motion-blur-compute.dawn.test.ts +13 -7
  371. package/src/__tests__/motion-blur.pixel.integration.test.ts +2 -2
  372. package/src/__tests__/nineslice-handle-surface.unit.test.ts +4 -4
  373. package/src/__tests__/pbr-view-layout.unit.test.ts +9 -0
  374. package/src/__tests__/physical-clearcoat.integration.test.ts +66 -8
  375. package/src/__tests__/physical-material-budget.unit.test.ts +40 -0
  376. package/src/__tests__/prepared-graphics-capability.unit.test.ts +66 -2
  377. package/src/__tests__/probe-bindings.unit.test.ts +582 -1
  378. package/src/__tests__/probe-scene-dirty.integration.test.ts +28 -1
  379. package/src/__tests__/receipt-observation-retirement.unit.test.ts +65 -0
  380. package/src/__tests__/recovery-candidate-prepare.contract.test.ts +69 -0
  381. package/src/__tests__/render-error-code-owner.test-d.ts +8 -0
  382. package/src/__tests__/render-feature-diagnostics.unit.test.ts +15 -2
  383. package/src/__tests__/render-feature-error-reporting.unit.test.ts +21 -1
  384. package/src/__tests__/render-feature-prepared-diagnostics.unit.test.ts +10 -1
  385. package/src/__tests__/render-feature-retry.unit.test.ts +12 -1
  386. package/src/__tests__/render-scene-mixed-updates.integration.test.ts +145 -19
  387. package/src/__tests__/render-scene-projection.unit.test.ts +36 -11
  388. package/src/__tests__/render-scene-temporal-retry.unit.test.ts +20 -20
  389. package/src/__tests__/render-target-probe-soak.perf.test.ts +2 -2
  390. package/src/__tests__/render-temporal-environment-consumer.browser.test.ts +3 -3
  391. package/src/__tests__/render-temporal-environment-consumer.dawn.test.ts +5 -2
  392. package/src/__tests__/renderer-factory-material-contract.unit.test.ts +42 -8
  393. package/src/__tests__/renderer-frame-generation-fence.integration.test.ts +16 -0
  394. package/src/__tests__/renderer-frame-transaction.integration.test.ts +26 -10
  395. package/src/__tests__/resource-allocation.unit.test.ts +123 -0
  396. package/src/__tests__/single-layer-medium-passes.unit.test.ts +275 -0
  397. package/src/__tests__/skin-motion-regression.unit.test.ts +70 -1
  398. package/src/__tests__/skin-palette-recycling.dawn.test.ts +97 -0
  399. package/src/__tests__/skinned-shadow-caster.test.ts +15 -0
  400. package/src/__tests__/ssr-carrier-public-contract.unit.test.ts +21 -0
  401. package/src/__tests__/ssr-gpu-dispatch.browser.test.ts +4 -4
  402. package/src/__tests__/ssr-gpu-dispatch.dawn.test.ts +2 -2
  403. package/src/__tests__/ssr-gpu-dispatch.ts +1 -1
  404. package/src/__tests__/ssr-receiver-coverage.dawn.test.ts +6 -2
  405. package/src/__tests__/standard-output-chain-contract.unit.test.ts +28 -0
  406. package/src/__tests__/standard-pbr-artifact-assembly.unit.test.ts +46 -1
  407. package/src/__tests__/standard-pipeline.integration.test.ts +182 -1
  408. package/src/__tests__/surface-dynamic-buffer-lifecycle.unit.test.ts +506 -0
  409. package/src/__tests__/surface-submission-observation.unit.test.ts +812 -0
  410. package/src/__tests__/temporal-history-lifecycle.unit.test.ts +32 -0
  411. package/src/__tests__/temporal-performance.integration.test.ts +3 -3
  412. package/src/__tests__/visibility-instances.integration.test.ts +7 -19
  413. package/src/__tests__/visibility-producer-matrix.integration.test.ts +9 -20
  414. package/src/__tests__/volume-optics-oracle.unit.test.ts +4 -2
  415. package/src/__tests__/volumetric-fog-budget-recovery.integration.test.ts +30 -20
  416. package/src/__tests__/volumetric-fog-errors.unit.test.ts +4 -3
  417. package/src/__tests__/volumetric-fog-multiple.unit.test.ts +55 -0
  418. package/src/__tests__/volumetric-fog-spot-frame-optics.integration.test.ts +1 -1
  419. package/src/__tests__/volumetric-fog-stage-readback.dawn.test.ts +113 -9
  420. package/src/__tests__/volumetric-fog-topology.unit.test.ts +5 -3
  421. package/src/assembly/backend-contract.ts +30 -0
  422. package/src/assembly/barrel-distortion-inspection.ts +22 -0
  423. package/src/assembly/canvas-draw-guard.ts +11 -0
  424. package/src/assembly/cloud-shadow-entry.ts +22 -0
  425. package/src/assembly/device-feature-admission.ts +2 -2
  426. package/src/assembly/dynamic-geometry-host.ts +65 -37
  427. package/src/assembly/dynamic-geometry-runtime.ts +7 -1
  428. package/src/assembly/factory.ts +2 -30
  429. package/src/assembly/host-contract.ts +8 -5
  430. package/src/assembly/material/assembly.ts +25 -13
  431. package/src/assembly/material/pipeline-helpers.ts +53 -12
  432. package/src/assembly/material-shader-policy.ts +55 -0
  433. package/src/assembly/material-shader-prewarm.ts +21 -10
  434. package/src/assembly/recovery/device-loss-fanout.ts +13 -0
  435. package/src/assembly/recovery/renderer-recover.ts +50 -18
  436. package/src/assembly/render-feature-post-processes.ts +54 -0
  437. package/src/assembly/render-target-host.ts +57 -47
  438. package/src/assembly/renderer-facade.ts +7 -2
  439. package/src/assembly/renderer-feature-inspection.ts +8 -2
  440. package/src/assembly/renderer-frame-transaction.ts +23 -0
  441. package/src/assembly/renderer-inspection.ts +28 -0
  442. package/src/assembly/skin-palette-owner.ts +1 -1
  443. package/src/assembly/temporal-post-process-prewarm.ts +3 -3
  444. package/src/assembly/webgpu-pbr-ready.ts +9 -1
  445. package/src/assembly/webgpu-ready-per-pass.ts +104 -0
  446. package/src/assembly/webgpu-ready.ts +116 -62
  447. package/src/assembly/webgpu-renderer-bootstrap.ts +0 -12
  448. package/src/assembly/webgpu-renderer-observation-owner.ts +222 -0
  449. package/src/assembly/webgpu-renderer.ts +303 -313
  450. package/src/assembly/webgpu-vertex-layouts.ts +1 -1
  451. package/src/barrel-distortion.ts +247 -0
  452. package/src/cloud/__tests__/cloud-density-parity.dawn.test.ts +173 -0
  453. package/src/cloud/__tests__/cloud-layer-framebuffer-y.dawn.test.ts +265 -0
  454. package/src/cloud/__tests__/cloud-layer.browser.test.ts +432 -0
  455. package/src/cloud/__tests__/cloud-layer.unit.test.ts +634 -0
  456. package/src/cloud/density.ts +600 -0
  457. package/src/cloud/extract.ts +110 -0
  458. package/src/cloud/feature.ts +1810 -0
  459. package/src/cloud/frame-context.ts +42 -0
  460. package/src/cloud/inspection.ts +130 -0
  461. package/src/cloud/optics.ts +285 -0
  462. package/src/cloud/parameters.ts +255 -0
  463. package/src/cloud/resources.ts +122 -0
  464. package/src/cloud/shadow.ts +167 -0
  465. package/src/cloud/temporal.ts +226 -0
  466. package/src/components/barrel-distortion.ts +46 -0
  467. package/src/components/cloud-layer.ts +47 -0
  468. package/src/components/index.ts +2 -0
  469. package/src/components/instances.ts +18 -45
  470. package/src/components/sprite-instances.ts +1 -1
  471. package/src/construct-renderer.ts +1 -1
  472. package/src/device/gpu-residency.ts +26 -25
  473. package/src/dynamic-geometry.ts +12 -1
  474. package/src/errors/cloud.ts +103 -0
  475. package/src/errors/render.ts +47 -8
  476. package/src/examples/single-layer-medium-surface.ts +59 -0
  477. package/src/extract/camera.ts +15 -1
  478. package/src/extract/contracts.ts +5 -0
  479. package/src/extract/material-context.ts +21 -0
  480. package/src/features/barrel-distortion.ts +172 -0
  481. package/src/features/error-reporting.ts +26 -6
  482. package/src/features/host.ts +128 -19
  483. package/src/features/plan.ts +10 -0
  484. package/src/features/render-graph-contribution.ts +9 -0
  485. package/src/features/render-graph-raster.ts +45 -3
  486. package/src/features/targets.ts +66 -0
  487. package/src/features/types.ts +51 -0
  488. package/src/fullscreen-post-process-pass.ts +41 -9
  489. package/src/glyph-text-layout-system.ts +2 -2
  490. package/src/gpu-dirty-ranges.ts +48 -0
  491. package/src/gpu-driven/batch-topology.ts +53 -0
  492. package/src/gpu-driven/material-artifacts.ts +33 -25
  493. package/src/gpu-driven/prepared-draw.ts +12 -4
  494. package/src/gpu-driven/production-raster-material.ts +1894 -0
  495. package/src/gpu-driven/production-raster.ts +825 -784
  496. package/src/gpu-driven/resource-allocation.ts +142 -0
  497. package/src/gpu-driven/shadow-ownership.ts +71 -0
  498. package/src/gpu-driven/view-gpu.ts +164 -10
  499. package/src/gpu-scene.ts +75 -84
  500. package/src/hdrp-buffers.ts +4 -3
  501. package/src/ibl/frame-resources.ts +0 -1
  502. package/src/ibl/skylight-bind-group.ts +62 -32
  503. package/src/index.ts +205 -9
  504. package/src/inspection-types.ts +162 -0
  505. package/src/instance-buffer-cache.ts +4 -4
  506. package/src/instances.ts +152 -569
  507. package/src/pbr-pipeline.ts +230 -30
  508. package/src/pipeline/single-layer-medium-passes.ts +267 -0
  509. package/src/pipeline/standard-forward-lane.ts +313 -57
  510. package/src/pipeline/standard-output/graph.ts +8 -2
  511. package/src/pipeline/standard-output/lut-gpu.ts +3 -3
  512. package/src/pipeline/standard-output/resources.ts +2 -2
  513. package/src/pipeline/standard-output/types.ts +12 -1
  514. package/src/pipeline/standard-pipeline.ts +291 -18
  515. package/src/pipeline/standard-post.ts +90 -24
  516. package/src/pipeline-builder.ts +1 -1
  517. package/src/plugin.ts +4 -0
  518. package/src/points-lines/__tests__/points-lines.bench.ts +17 -8
  519. package/src/prepare/prepared-graphics-resolver.ts +2 -0
  520. package/src/publication/__tests__/derived-geometry.integration.test.ts +177 -0
  521. package/src/publication/__tests__/features.integration.test.ts +122 -0
  522. package/src/publication/__tests__/programs.unit.test.ts +25 -0
  523. package/src/publication/__tests__/publication.integration.test.ts +370 -0
  524. package/src/publication/__tests__/targets.integration.test.ts +120 -0
  525. package/src/publication/__tests__/video.browser.test.ts +50 -0
  526. package/src/publication/contract.ts +104 -0
  527. package/src/publication/dependencies.ts +54 -0
  528. package/src/publication/prepare-geometry.ts +94 -0
  529. package/src/publication/programs.ts +45 -0
  530. package/src/publication/publisher.ts +618 -0
  531. package/src/publication/receiver.ts +297 -0
  532. package/src/publication/resource-scope.ts +31 -0
  533. package/src/publication/targets.ts +182 -0
  534. package/src/publication/video.ts +33 -0
  535. package/src/record/__tests__/main-pass-geometry.unit.test.ts +30 -0
  536. package/src/record/__tests__/material-bg-cache.unit.test.ts +15 -1
  537. package/src/record/__tests__/sprite-material-abi.unit.test.ts +9 -11
  538. package/src/record/__tests__/temporal-payload.unit.test.ts +1 -1
  539. package/src/record/__tests__/transparent-group2-selection.unit.test.ts +11 -0
  540. package/src/record/__tests__/typed-frame-graph-plan.unit.test.ts +1 -0
  541. package/src/record/__tests__/video-texture-view.unit.test.ts +9 -9
  542. package/src/record/__tests__/view-ubo-layout.unit.test.ts +4 -3
  543. package/src/record/barrel-distortion-frame.ts +110 -0
  544. package/src/record/dynamic-geometry-consumption.ts +39 -9
  545. package/src/record/fold-buckets.ts +855 -0
  546. package/src/record/fold-instance-buffer.ts +51 -0
  547. package/src/record/frame-lighting.ts +36 -2
  548. package/src/record/frame-snapshot.ts +45 -9
  549. package/src/record/frame.ts +258 -1105
  550. package/src/record/gpu-draw-receipts.ts +38 -0
  551. package/src/record/gpu-timing.ts +48 -5
  552. package/src/record/helpers.ts +2 -2
  553. package/src/record/main-pass-geometry.ts +272 -84
  554. package/src/record/main-pass-material.ts +102 -36
  555. package/src/record/main-pass-sprite-draws.ts +13 -217
  556. package/src/record/main-pass.ts +164 -27
  557. package/src/record/motion-blur-receipt.ts +91 -0
  558. package/src/record/prepared-material-bindings.ts +11 -6
  559. package/src/record/probe-blend-buffer.ts +180 -0
  560. package/src/record/recovery-pipeline.ts +35 -3
  561. package/src/record/render-context.ts +41 -5
  562. package/src/record/shadow-pass.ts +30 -4
  563. package/src/record/skybox-post-pass.ts +28 -4
  564. package/src/record/sprite-instance-buffer.ts +155 -0
  565. package/src/record/target-capture-graph.ts +258 -0
  566. package/src/record/typed-frame-graph.ts +776 -340
  567. package/src/record/view-ubo.ts +27 -4
  568. package/src/record/volume-params.ts +225 -0
  569. package/src/recovery/render-system-candidate.ts +243 -50
  570. package/src/reflection/record-owner.ts +7 -3
  571. package/src/render-contract.ts +54 -5
  572. package/src/render-graph-primitives.ts +7 -1
  573. package/src/render-pipeline.ts +130 -0
  574. package/src/render-system-extract-tail.ts +90 -78
  575. package/src/render-system-extract.ts +76 -76
  576. package/src/render-system-presentation.ts +56 -0
  577. package/src/render-system-producer-roots.ts +96 -0
  578. package/src/render-system-projections.ts +3 -2
  579. package/src/render-system-residency.ts +159 -0
  580. package/src/render-system.ts +421 -408
  581. package/src/scene/probe-blend.ts +96 -4
  582. package/src/scene/render-scene.ts +416 -337
  583. package/src/scene/render-source.ts +90 -0
  584. package/src/scene/source-systems.ts +33 -0
  585. package/src/ssao-buffers.ts +95 -2
  586. package/src/surface/__tests__/dynamic-input.unit.test.ts +374 -0
  587. package/src/surface/__tests__/gpu-driven.unit.test.ts +87 -0
  588. package/src/surface/dynamic-input.ts +658 -0
  589. package/src/surface/gpu-driven.ts +147 -0
  590. package/src/surface/submission-observation.ts +517 -0
  591. package/src/systems/skin-palette-allocator.ts +5 -1
  592. package/src/systems/skin-palette-types.ts +11 -0
  593. package/src/systems/transparent-dispatch.ts +2 -2
  594. package/src/systems/transparent-sort-config.ts +3 -1
  595. package/src/temporal/gpu.ts +101 -17
  596. package/src/temporal/inspection.ts +7 -1
  597. package/src/temporal/standard-scene-data.ts +5 -0
  598. package/src/temporal/target-coverage-attachment.ts +4 -0
  599. package/src/transmission/__tests__/single-layer-medium.unit.test.ts +149 -0
  600. package/src/transmission/__tests__/standard-transmission.dawn.test.ts +12 -11
  601. package/src/transmission/single-layer-medium.ts +322 -0
  602. package/src/typed-render-graph-primitives.ts +70 -2
  603. package/src/volume/component.ts +10 -9
  604. package/src/volume/extract.ts +11 -5
  605. package/src/volume/inspection.ts +3 -0
  606. package/src/volume/passes.ts +87 -4
  607. package/src/volume/resources.ts +2 -1
  608. package/dist/chunk-3RTCJTH4.mjs +0 -1610
  609. package/dist/chunk-3RTCJTH4.mjs.map +0 -1
  610. package/dist/chunk-BLXGONR2.mjs.map +0 -1
  611. package/dist/chunk-ILQ5MEZF.mjs +0 -32
  612. package/dist/chunk-ILQ5MEZF.mjs.map +0 -1
  613. package/dist/chunk-LEAXOMYJ.mjs.map +0 -1
  614. package/dist/chunk-NB2S7ZRX.mjs +0 -1783
  615. package/dist/chunk-NB2S7ZRX.mjs.map +0 -1
  616. package/dist/chunk-NNQL7CB3.mjs +0 -1713
  617. package/dist/chunk-NNQL7CB3.mjs.map +0 -1
  618. package/dist/chunk-OO3DRYK7.mjs.map +0 -1
  619. package/dist/chunk-PA5DRJNI.mjs.map +0 -1
  620. package/dist/chunk-PLAXOOX5.mjs +0 -1907
  621. package/dist/chunk-PLAXOOX5.mjs.map +0 -1
  622. package/dist/chunk-RXZ3RGOU.mjs +0 -53
  623. package/dist/chunk-RXZ3RGOU.mjs.map +0 -1
  624. package/dist/chunk-VOZWDM3L.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/components/atmosphere.ts","../src/components/barrel-distortion.ts","../src/components/camera.ts","../src/components/cloud-layer.ts","../src/components/cube-camera.ts","../src/components/depth-of-field.ts","../src/components/directional-shadow-filter.ts","../src/components/directional-light.ts","../src/components/dynamic-resolution.ts","../src/components/fog.ts","../src/components/instances.ts","../src/components/layer.ts","../src/components/light-helpers.ts","../src/components/light-probe.ts","../src/components/lines.ts","../src/components/mesh-filter.ts","../src/components/mesh-renderer.ts","../src/components/motion-blur.ts","../src/components/point-light.ts","../src/components/point-light-shadow.ts","../src/components/points.ts","../src/components/post-process-params.ts","../src/components/rect-area-light.ts","../src/components/reflection-probe.ts","../src/components/scene-instance.ts","../src/components/screen-space-reflection.ts","../src/components/skybox-background.ts","../src/components/skylight.ts","../src/components/sort-key.ts","../src/components/spot-light.ts","../src/components/visibility.ts","../src/barrel-distortion.ts","../src/errors/cloud.ts","../src/cloud/parameters.ts","../src/volume/component.ts","../src/environment/signature.ts","../src/extract/environment.ts","../src/environment/frame.ts","../src/features/depth-of-field/depth-of-field-params.ts","../src/volume/capability.ts","../src/capture/cube-views.ts","../src/mesh-material-bindings.ts","../src/extract/visibility.ts","../src/cloud/extract.ts","../src/volume/extract.ts","../src/extract/directional-shadow-projection.ts","../src/glyph-text-layout-system.ts","../src/instances-derived-bounds.ts","../src/points-lines/bounds.ts","../src/prepare/extended-lighting/spot-modifiers.ts","../src/scene/shadow-visibility.ts","../src/render-system-extract-tail.ts","../src/render-system-extract.ts"],"names":["defineComponent","invalid","err","ok","R_MIN","quality","focalLength","layout","materialId","cameraOwnerFrame","Transform","mat4","SpawnLightInvalidBoundsError","resolveAssetHandle","toShared","lightViewProj","frustum","SpriteInstancesMutuallyExclusiveWithInstancesError","SpriteInstancesRequiresSpriteShaderError","SpriteInstancesCountMismatchError","vec3","routeWorldError","derive","isMissingMaterialProgram","pass","AssetGuid","schema","projectMaterialParameters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,eAAA,EAAiB,aAAA,CAAc,eAAA;AAAgB;AACvD,KACL,CAAA;AAAA,EACH;AAEA,EAAA,IAAI,UAAA,CAAW,MAAA,KAAW,CAAA,EAAG,OAAO,MAAA;AACpC,EAAA,MAAM,SAAA,GAAY,qBAAqB,UAAU,CAAA;AACjD,EAAA,IAAI,CAAC,UAAU,EAAA,EAAI;AACjB,IAAA,aAAA,CAAc,WAAA,CAAY,UAAU,KAAA,EAAO;AAAA,MACzC,UAAU,QAAA,CAAS,KAAA;AAAA,MACnB,UAAA,EAAY;AAAA,KACb,CAAA;AACD,IAAA,OAAO,EAAE,GAAG,OAAA,CAAQ,CAAC,CAAA,EAAG,QAAQ,UAAA,EAAW;AAAA,EAC7C;AACA,EAAA,IAAI,UAAU,KAAA,CAAM,MAAA,KAAW,OAAO,OAAO,EAAE,QAAQ,KAAA,EAAM;AAC7D,EAAA,MAAM,mBAAmB,SAAA,CAAU,KAAA,CAAM,KAAK,GAAA,CAAI,CAAC,KAAK,KAAA,MAAW;AAAA,IACjE,GAAG,QAAQ,KAAK,CAAA;AAAA,IAChB,MAAA,EAAQ,WAAA;AAAA,IACR;AAAA,GACF,CAAE,CAAA;AACF,EAAA,OAAO;AAAA,IACL,MAAA,EAAQ,WAAA;AAAA,IACR,GAAG,iBAAiB,CAAC,CAAA;AAAA,IACrB,UAAA,EAAY,gBAAA,CAAiB,KAAA,CAAM,CAAC;AAAA,GACtC;AACF","file":"chunk-G6HDNGY7.mjs","sourcesContent":["import { defineComponent } from '@forgeax/engine-ecs';\n\n/** Analytic atmosphere authoring facts; the directional light supplies the sun. */\nexport const Atmosphere = defineComponent('Atmosphere', {\n turbidity: { type: 'f32', default: 2 },\n rayleigh: { type: 'f32', default: 1 },\n mieCoefficient: { type: 'f32', default: 0.005 },\n mieDirectionalG: { type: 'f32', default: 0.8 },\n sunAngularRadius: { type: 'f32', default: 0.004675 },\n /** Independent multiplier for the analytic circumsolar lobe. */\n circumsolarStrength: { type: 'f32', default: 1 },\n /** Relative angular width of the analytic circumsolar lobe. */\n circumsolarWidth: { type: 'f32', default: 1 },\n});\n","import { defineComponent, type SchemaOf, type ShapeOf } from '@forgeax/engine-ecs';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport { BarrelDistortionInvalidParameterError } from '../errors/render';\n\n/** Camera companion that applies the bounded first-order barrel model. */\nexport const BarrelDistortion = defineComponent('BarrelDistortion', {\n strength: { type: 'f32', default: 0 },\n centerX: { type: 'f32', default: 0.5 },\n centerY: { type: 'f32', default: 0.5 },\n});\n\nexport type BarrelDistortionData = ShapeOf<SchemaOf<typeof BarrelDistortion>>;\n\nconst DEFAULT_BARREL_DISTORTION: BarrelDistortionData = Object.freeze({\n strength: 0,\n centerX: 0.5,\n centerY: 0.5,\n});\n\nfunction invalid(\n field: 'strength' | 'centerX' | 'centerY',\n value: number,\n expected: string,\n): BarrelDistortionInvalidParameterError {\n return new BarrelDistortionInvalidParameterError({ field, value, expected });\n}\n\n/** Validate and detach camera-owned barrel authoring data. */\nexport function validateBarrelDistortionParameters(\n input: Partial<BarrelDistortionData> | undefined,\n): Result<BarrelDistortionData, BarrelDistortionInvalidParameterError> {\n const value = input ?? {};\n const strength = value.strength ?? DEFAULT_BARREL_DISTORTION.strength;\n const centerX = value.centerX ?? DEFAULT_BARREL_DISTORTION.centerX;\n const centerY = value.centerY ?? DEFAULT_BARREL_DISTORTION.centerY;\n if (!Number.isFinite(strength) || strength < 0 || strength > 0.35) {\n return err(invalid('strength', strength, 'finite and in [0, 0.35]'));\n }\n if (!Number.isFinite(centerX) || centerX < 0 || centerX > 1) {\n return err(invalid('centerX', centerX, 'finite and in [0, 1]'));\n }\n if (!Number.isFinite(centerY) || centerY < 0 || centerY > 1) {\n return err(invalid('centerY', centerY, 'finite and in [0, 1]'));\n }\n return ok(Object.freeze({ strength, centerX, centerY }));\n}\n","// @forgeax/engine-render - Camera (projection variant + ortho extension).\n//\n// Schema: projection, output, Bloom, and lifecycle columns. The view matrix\n// continues to be derived from the entity's Transform (AC-06 case B fires\n// 'render-system-no-camera' when 0 such entities exist).\n//\n// Projection discriminator:\n// projection === 0 → perspective path; RenderSystem builds\n// mat4.perspective(out, fov, aspect, near, far).\n// WebGPU [0, 1] NDC z; perspective reverse-Z hook is\n// a future spin-off path (plan-strategy §R-7) kept\n// outside M3 scope — the short-name mat4.perspective\n// already writes [0, 1] NDC, matching the ortho branch.\n// projection === 1 → orthographic path; RenderSystem builds\n// mat4.orthographic(out, left, right, top, bottom,\n// near, far) (WebGPU [0, 1] NDC; same z convention).\n//\n// Naming convention: forgeax uses the bare `Camera` name (no `Component`\n// suffix) to follow the unity-style flavor for \"individuating\" component\n// names per plan-strategy 7.2 + D-Q5a user lock.\n//\n// Related: requirements §AC-16 (Camera Ortho + Box3 / Sphere);\n// plan-strategy §M3 range + §R-7 risk (single perspective camera\n// in hello-room does NOT trigger depth-func conflict; multi-camera\n// mixed perspective + ortho deferred to feat-future-camera-depth-func);\n// plan-tasks.json w9 acceptanceCheck.\n\nimport { defineComponent, type SchemaOf, type ShapeOf } from '@forgeax/engine-ecs';\nimport { TONEMAP_SHADER_MODE } from '@forgeax/engine-shader';\n\n/**\n * Projection discriminator literal union (AC-16 narrowing surface).\n * Exposed for consumer code that maps `camera.projection` numeric values back\n * to a switch-able string literal (e.g. RenderSystem dispatch / inspector\n * snapshot rendering).\n */\nexport type CameraProjection = 'perspective' | 'orthographic';\n\n/** Numeric encoding of perspective projection (schema value for `projection`). */\nexport const CAMERA_PROJECTION_PERSPECTIVE = 0;\n/** Numeric encoding of orthographic projection (schema value for `projection`). */\nexport const CAMERA_PROJECTION_ORTHOGRAPHIC = 1;\n\n/** Closed public exposure authoring contract shared by all camera routes. */\nexport type CameraExposure =\n | { readonly kind: 'manual'; readonly multiplier: number }\n | {\n readonly kind: 'auto';\n readonly fallback: number;\n readonly compensationEv: number;\n readonly rangeEv: readonly [min: number, max: number];\n readonly rates: readonly [up: number, down: number];\n };\n\n/** Numeric encoding of manual exposure in the Camera SoA column. */\nexport const CAMERA_EXPOSURE_MODE_MANUAL = 0;\n/** Numeric encoding of GPU-adapted exposure in the Camera SoA column. */\nexport const CAMERA_EXPOSURE_MODE_AUTO = 1;\n\n/** Product-supported white-balance temperature range in Kelvin. */\nexport const CAMERA_TEMPERATURE_MIN = 1000;\nexport const CAMERA_TEMPERATURE_MAX = 40000;\n/** Product-supported normalized tint range. */\nexport const CAMERA_TINT_MIN = -1;\nexport const CAMERA_TINT_MAX = 1;\n\n/** Closed validation failures for the Camera authoring/column boundary. */\nexport type CameraErrorCode =\n | 'camera-exposure-invalid'\n | 'camera-color-grading-invalid'\n | 'camera-exposure-mode-invalid'\n | 'camera-tonemap-invalid'\n | 'camera-antialias-invalid'\n | 'camera-bloom-invalid';\n\nexport interface CameraErrorDetail {\n readonly field: string;\n readonly actual: number | string;\n readonly expected: string;\n}\n\n/** Structured Camera error; callers can branch on the closed `code` union. */\nexport class CameraError<Code extends CameraErrorCode = CameraErrorCode> extends Error {\n readonly code: Code;\n readonly expected: string;\n readonly hint: string;\n readonly detail: CameraErrorDetail;\n\n constructor(code: Code, field: string, actual: number | string, expected: string, hint: string) {\n super(`${code}: ${field}=${String(actual)}; expected ${expected}`);\n this.name = 'CameraError';\n this.code = code;\n this.expected = expected;\n this.hint = hint;\n this.detail = Object.freeze({ field, actual, expected });\n }\n}\n\nfunction actualValue(value: unknown): number | string {\n if (typeof value === 'number' || typeof value === 'string') return value;\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nfunction cameraError<Code extends CameraErrorCode>(\n code: Code,\n field: string,\n actual: unknown,\n expected: string,\n hint: string,\n): CameraError<Code> {\n return new CameraError(code, field, actualValue(actual), expected, hint);\n}\n\nfunction finitePositive(value: number): boolean {\n return Number.isFinite(value) && value > 0;\n}\n\n/** Validate the closed exposure union before it is projected into columns. */\nexport function validateCameraExposure(exposure: CameraExposure): CameraExposure {\n if (typeof exposure !== 'object' || exposure === null) {\n throw cameraError(\n 'camera-exposure-invalid',\n 'value',\n exposure,\n 'an object with kind manual or auto',\n 'choose one member of the CameraExposure union',\n );\n }\n if (exposure.kind === 'manual') {\n if (!finitePositive(exposure.multiplier)) {\n throw cameraError(\n 'camera-exposure-invalid',\n 'multiplier',\n exposure.multiplier,\n 'a finite number greater than zero',\n 'set Camera.exposure to a positive finite manual multiplier',\n );\n }\n return exposure;\n }\n if (exposure.kind === 'auto') {\n const [min, max] = exposure.rangeEv;\n const [up, down] = exposure.rates;\n if (\n !finitePositive(exposure.fallback) ||\n !Number.isFinite(exposure.compensationEv) ||\n !Number.isFinite(min) ||\n !Number.isFinite(max) ||\n min > max ||\n !Number.isFinite(up) ||\n !Number.isFinite(down) ||\n up < 0 ||\n down < 0\n ) {\n throw cameraError(\n 'camera-exposure-invalid',\n 'auto',\n JSON.stringify(exposure),\n 'finite fallback/compensation, an ordered range, and non-negative rates',\n 'inspect fallback, compensationEv, rangeEv, and rates before rebuilding the camera',\n );\n }\n return exposure;\n }\n throw cameraError(\n 'camera-exposure-invalid',\n 'kind',\n (exposure as { readonly kind?: unknown }).kind,\n \"'manual' or 'auto'\",\n 'choose one member of the CameraExposure union',\n );\n}\n\n/** Validate the Camera-owned white-balance and LUT authoring fields. */\nexport function validateCameraColorGrading(\n temperature: number,\n tint: number,\n colorLutStrength: number,\n): void {\n if (\n !Number.isFinite(temperature) ||\n temperature < CAMERA_TEMPERATURE_MIN ||\n temperature > CAMERA_TEMPERATURE_MAX\n ) {\n throw cameraError(\n 'camera-color-grading-invalid',\n 'temperature',\n temperature,\n `a finite value in [${CAMERA_TEMPERATURE_MIN}, ${CAMERA_TEMPERATURE_MAX}]`,\n 'set Camera.temperature to a supported Kelvin value',\n );\n }\n if (!Number.isFinite(tint) || tint < CAMERA_TINT_MIN || tint > CAMERA_TINT_MAX) {\n throw cameraError(\n 'camera-color-grading-invalid',\n 'tint',\n tint,\n `a finite value in [${CAMERA_TINT_MIN}, ${CAMERA_TINT_MAX}]`,\n 'set Camera.tint to a normalized value between -1 and 1',\n );\n }\n if (!Number.isFinite(colorLutStrength) || colorLutStrength < 0 || colorLutStrength > 1) {\n throw cameraError(\n 'camera-color-grading-invalid',\n 'colorLutStrength',\n colorLutStrength,\n 'a finite value in [0, 1]',\n 'set Camera.colorLutStrength to zero to disable the LUT or a blend in [0, 1]',\n );\n }\n}\n\n/**\n * Map a `camera.projection` numeric value to the closed `CameraProjection`\n * string-literal union. Values other than 0 / 1 fall back to `'perspective'`\n * (defensive for defaulted / uninitialised entities; charter proposition 4\n * no silent exception).\n */\nexport function cameraProjectionFromF32(value: number): CameraProjection {\n return value === CAMERA_PROJECTION_ORTHOGRAPHIC ? 'orthographic' : 'perspective';\n}\n\n/**\n * Tone-mapping mode discriminator literal union (AC-01 narrowing surface;\n * feat-20260519-tonemap-reinhard-mvp / M1).\n *\n * Two members for the MVP:\n * `'none'` - default; render-target stays `bgra8unorm-srgb`\n * and the geometry pass writes directly to the\n * swap-chain (zero-overhead opt-out path).\n * `'reinhard-extended'` - Forgeax Reinhard 2002 extended (luminance-domain)\n * opt-in;\n * `'reinhard'` - Three r184 per-channel Reinhard opt-in;\n * geometry pass routes through an `rgba16float`\n * HDR target and a fullscreen tonemap pass\n * (`packages/shader/src/tonemap.wgsl`).\n *\n * The remaining members mirror the Three r184 public names and formulas.\n */\nexport type Tonemap =\n | 'none'\n | 'reinhard-extended'\n | 'reinhard'\n | 'linear'\n | 'cineon'\n | 'aces-filmic'\n | 'agx'\n | 'neutral';\n\n/** Numeric encoding of the no-op tonemap path (schema value for `tonemap`). */\nexport const TONEMAP_NONE = TONEMAP_SHADER_MODE.none;\n/**\n * Numeric encoding of the Reinhard-extended tonemap path\n * (schema value for `tonemap`).\n */\nexport const TONEMAP_REINHARD_EXTENDED = TONEMAP_SHADER_MODE.reinhardExtended;\n/** Numeric encoding of the Three r184 per-channel Reinhard path. */\nexport const TONEMAP_REINHARD = TONEMAP_SHADER_MODE.reinhard;\n/** Numeric encoding of the linear (identity after exposure) tonemap path. */\nexport const TONEMAP_LINEAR = TONEMAP_SHADER_MODE.linear;\n/** Numeric encoding of the Cineon (Kodak log) tonemap path. */\nexport const TONEMAP_CINEON = TONEMAP_SHADER_MODE.cineon;\n/** Numeric encoding of the ACES filmic (Narkowicz 2015) tonemap path. */\nexport const TONEMAP_ACES_FILMIC = TONEMAP_SHADER_MODE.acesFilmic;\n/** Numeric encoding of the AgX (Troy Sobotka / Blender 3.x) tonemap path. */\nexport const TONEMAP_AGX = TONEMAP_SHADER_MODE.agx;\n/** Numeric encoding of the Khronos PBR neutral tonemap path. */\nexport const TONEMAP_NEUTRAL = TONEMAP_SHADER_MODE.neutral;\n\n/**\n * Map a `camera.tonemap` numeric value to the closed `Tonemap` string-literal\n * union. Unknown values fall back to `'none'` for defensive schema decoding.\n */\nexport function tonemapFromF32(value: number): Tonemap {\n switch (value) {\n case TONEMAP_REINHARD_EXTENDED:\n return 'reinhard-extended';\n case TONEMAP_REINHARD:\n return 'reinhard';\n case TONEMAP_LINEAR:\n return 'linear';\n case TONEMAP_CINEON:\n return 'cineon';\n case TONEMAP_ACES_FILMIC:\n return 'aces-filmic';\n case TONEMAP_AGX:\n return 'agx';\n case TONEMAP_NEUTRAL:\n return 'neutral';\n default:\n return 'none';\n }\n}\n\n/**\n * Inverse of {@link tonemapFromF32}: map the closed `Tonemap` string-literal\n * union to the u32 mode the tonemap WGSL `params.mode` switch reads. SSOT for\n * the mode encoding shared by the extract-stage built-in tonemap provider\n * (feat-20260621 M-A3 / w13: `Camera.tonemap` -> `forgeax::tonemap` 16B data)\n * and any other consumer. `'none'` maps to 0 (the tonemap pass never dispatches\n * on the LDR path, so 0 is only ever a placeholder).\n */\nexport function tonemapToU32(mode: Tonemap): number {\n switch (mode) {\n case 'reinhard-extended':\n return TONEMAP_REINHARD_EXTENDED;\n case 'reinhard':\n return TONEMAP_REINHARD;\n case 'linear':\n return TONEMAP_LINEAR;\n case 'cineon':\n return TONEMAP_CINEON;\n case 'aces-filmic':\n return TONEMAP_ACES_FILMIC;\n case 'agx':\n return TONEMAP_AGX;\n case 'neutral':\n return TONEMAP_NEUTRAL;\n case 'none':\n return TONEMAP_NONE;\n }\n throw cameraError(\n 'camera-tonemap-invalid',\n 'tonemap',\n mode,\n 'one of the closed Tonemap values',\n 'select a supported Camera tonemap mode',\n );\n}\n\n/**\n * Anti-alias mode discriminator literal union\n * (feat-20260528-fxaa-post-processing / w2;\n * feat-20260604-learn-render-4-10-anti-aliasing-msaa adds `'msaa'`).\n *\n * Four members:\n * `'none'` - default; no anti-aliasing (zero-overhead opt-out path)\n * `'fxaa'` - FXAA 3.11 fullscreen post-processing pass (screen-space, shading-aliasing)\n * `'msaa'` - 4x hardware multi-sample anti-aliasing (geometry-edge coverage).\n * Active on both HDR and LDR-swap-chain paths, so a default Camera\n * (`tonemap='none'`) with `antialias='msaa'` is NOT a silent no-op.\n * `'taa'` - temporal anti-aliasing; renderer temporal projection owns its\n * jitter and successful-submit history contract.\n *\n * MSAA and FXAA are orthogonal: MSAA resolves geometry-edge aliasing, FXAA\n * resolves shading/high-frequency aliasing. TAA is mutually exclusive with both.\n */\nexport type Antialias = 'none' | 'fxaa' | 'msaa' | 'taa';\n\n/** Numeric encoding of anti-alias disabled (schema value for `antialias`). */\nexport const ANTIALIAS_NONE = 0;\n/** Numeric encoding of FXAA anti-aliasing (schema value for `antialias`). */\nexport const ANTIALIAS_FXAA = 1;\n/** Numeric encoding of MSAA multi-sample anti-aliasing (schema value for `antialias`). */\nexport const ANTIALIAS_MSAA = 2;\n/** Numeric encoding of temporal anti-aliasing (schema value for `antialias`). */\nexport const ANTIALIAS_TAA = 3;\n\n/**\n * Map a `camera.antialias` numeric value to the closed `Antialias`\n * string-literal union. Invalid values fail-fast with structured error (charter P3).\n */\nexport function antialiasFromF32(value: number): Antialias {\n if (value === ANTIALIAS_NONE) return 'none';\n if (value === ANTIALIAS_FXAA) return 'fxaa';\n if (value === ANTIALIAS_MSAA) return 'msaa';\n if (value === ANTIALIAS_TAA) return 'taa';\n throw cameraError(\n 'camera-antialias-invalid',\n 'antialias',\n value,\n `${ANTIALIAS_NONE}, ${ANTIALIAS_FXAA}, ${ANTIALIAS_MSAA}, or ${ANTIALIAS_TAA}`,\n 'select a supported Camera antialias mode',\n );\n}\n\n/**\n * Bloom enabled discriminator literal union\n * (feat-20260531-bloom-first-declarative-render-graph-pass / w2).\n *\n * Two members:\n * `'off'` - default; no bloom post-processing (zero-overhead opt-out path)\n * `'on'` - five-level HDR extraction/downsample/tent-upsample pipeline\n *\n * Bloom is a discrete enum (0/1) — illegal values fail-fast with the closed\n * CameraError contract (charter P3), matching antialiasFromF32 precedent.\n */\nexport type BloomEnabled = 'off' | 'on';\n\n/** Numeric encoding of bloom disabled (schema value for `bloom`). */\nexport const BLOOM_DISABLED = 0;\n/** Numeric encoding of bloom enabled (schema value for `bloom`). */\nexport const BLOOM_ENABLED = 1;\n\n/** Bloom intensity is a linear HDR add-back multiplier. */\nexport const CAMERA_BLOOM_INTENSITY_MIN = 0;\nexport const CAMERA_BLOOM_INTENSITY_MAX = 8;\n/** Bloom threshold is expressed in scene-linear Rec.709 luminance. */\nexport const CAMERA_BLOOM_THRESHOLD_MIN = 0;\nexport const CAMERA_BLOOM_THRESHOLD_MAX = 65504;\n/** Soft-knee transition width relative to the threshold. */\nexport const CAMERA_BLOOM_SOFT_KNEE_MIN = 0;\nexport const CAMERA_BLOOM_SOFT_KNEE_MAX = 1;\n/** Coarse pyramid contribution. This is a blend, not a blur radius. */\nexport const CAMERA_BLOOM_SCATTER_MIN = 0;\nexport const CAMERA_BLOOM_SCATTER_MAX = 0.95;\n\n/**\n * Map a `camera.bloom` numeric value to the closed `BloomEnabled` string-literal\n * union. Invalid values fail-fast with structured error (charter P3).\n */\nexport function bloomEnabledFromF32(value: number): BloomEnabled {\n if (value === BLOOM_DISABLED) return 'off';\n if (value === BLOOM_ENABLED) return 'on';\n throw cameraError(\n 'camera-bloom-invalid',\n 'bloom',\n value,\n `${BLOOM_DISABLED} or ${BLOOM_ENABLED}`,\n 'select Camera bloom off or on',\n );\n}\n\nfunction validateBloomRange(field: string, value: number, min: number, max: number): void {\n if (!Number.isFinite(value) || value < min || value > max) {\n throw cameraError(\n 'camera-bloom-invalid',\n field,\n value,\n `a finite value in [${min}, ${max}]`,\n `set Camera.${field} to a finite value in [${min}, ${max}]`,\n );\n }\n}\n\n/** Validate the complete Camera-owned Bloom contract at the extract boundary. */\nexport function validateCameraBloom(\n bloom: number,\n threshold: number,\n intensity: number,\n softKnee: number,\n scatter: number,\n): BloomEnabled {\n const enabled = bloomEnabledFromF32(bloom);\n validateBloomRange(\n 'bloomThreshold',\n threshold,\n CAMERA_BLOOM_THRESHOLD_MIN,\n CAMERA_BLOOM_THRESHOLD_MAX,\n );\n validateBloomRange(\n 'bloomIntensity',\n intensity,\n CAMERA_BLOOM_INTENSITY_MIN,\n CAMERA_BLOOM_INTENSITY_MAX,\n );\n validateBloomRange(\n 'bloomSoftKnee',\n softKnee,\n CAMERA_BLOOM_SOFT_KNEE_MIN,\n CAMERA_BLOOM_SOFT_KNEE_MAX,\n );\n validateBloomRange('bloomScatter', scatter, CAMERA_BLOOM_SCATTER_MIN, CAMERA_BLOOM_SCATTER_MAX);\n return enabled;\n}\n\n/**\n * Camera projection parameters (perspective + orthographic variants) +\n * tonemap trio (mode + exposure + whitePoint).\n *\n * Camera transform comes from the entity's `Transform` (AI users\n * spawn camera entities with both components: see example below).\n *\n * Defaults (do not auto-apply; spawn explicitly for the perspective quartet):\n * fov = pi/4 - 45-degree vertical field of view\n * aspect = 16/9 - widescreen aspect (use canvas.width / canvas.height)\n * near = 0.1\n * far = 100\n * projection = 0 - CAMERA_PROJECTION_PERSPECTIVE (layer-2)\n * left = -1, right = 1, bottom = -1, top = 1 (orthographic; layer-2)\n * tonemap = 0 - TONEMAP_NONE (layer-2; opt-in path stays\n * 0-overhead by default)\n * exposure = 1.0 - layer-2 default for the Reinhard-extended path\n * @applicableWhen tonemap === 'reinhard-extended'\n * whitePoint = 4.0 - layer-2 default for the Reinhard-extended path\n * @applicableWhen tonemap === 'reinhard-extended'\n * @minimum 0 (shader floor `max(Y, 1e-5)` keeps\n * the divisor finite even at 0; D-O3)\n * clearColor = [0, 0, 0, 0]\n * - feat-20260709 M3 / D-3: clear-color is one\n * inline `array<f32,4>` column (collapsed from the\n * feat-20260608 clearR/G/B/A quartet). Defaults to\n * transparent black; an explicit alpha remains\n * visible through this public field.\n *\n * MVP supports a single active camera (the first archetype iteration hit;\n * N>1 fires 'render-system-multi-camera' + uses first). Multi-viewport is\n * OOS (see feat-future-multi-viewport). The orthographic path reuses the\n * same near / far as the perspective path — both variants share the single\n * Camera archetype (30 schema fields, including the Bloom controls, one\n * historyVersion u32 column, the `clearColor` array<f32,4> column, and the\n * `autoAspect` bool column).\n *\n * @example Perspective camera at (0, 0, 3) looking down -Z (zero-config tonemap):\n * world.spawn(\n * { component: Transform, data: {\n * pos: [0, 0, 3],\n * quat: [0, 0, 0, 1],\n * scale: [1, 1, 1],\n * } },\n * { component: Camera, data: {\n * fov: Math.PI / 4, aspect: 16 / 9, near: 0.1, far: 100,\n * } },\n * );\n * // tonemap defaults to 0 (TONEMAP_NONE) - 0-overhead path.\n *\n * @example Opt-in Reinhard-extended tonemap (high-intensity HDR scene):\n * world.spawn(\n * { component: Transform, data: { ... } },\n * { component: Camera, data: {\n * fov: Math.PI / 4, aspect: 16 / 9, near: 0.1, far: 100,\n * tonemap: TONEMAP_REINHARD_EXTENDED,\n * exposure: 1.0,\n * whitePoint: 4.0,\n * } },\n * );\n *\n * @example Orthographic camera spanning [-10, 10]^2 on the near plane:\n * world.spawn(\n * { component: Transform, data: {\n * pos: [0, 0, 5],\n * quat: [0, 0, 0, 1],\n * scale: [1, 1, 1],\n * } },\n * { component: Camera, data: {\n * fov: 0, aspect: 1, near: 0.1, far: 100,\n * projection: CAMERA_PROJECTION_ORTHOGRAPHIC,\n * left: -10, right: 10, bottom: -10, top: 10,\n * } },\n * );\n */\nexport const Camera = defineComponent('Camera', {\n fov: { type: 'f32' },\n aspect: { type: 'f32' },\n near: { type: 'f32' },\n far: { type: 'f32' },\n projection: { type: 'f32', default: 0 },\n left: { type: 'f32', default: -1 },\n right: { type: 'f32', default: 1 },\n bottom: { type: 'f32', default: -1 },\n top: { type: 'f32', default: 1 },\n tonemap: { type: 'f32', default: 0 },\n exposure: { type: 'f32', default: 1.0 },\n exposureMode: { type: 'f32', default: CAMERA_EXPOSURE_MODE_MANUAL },\n compensationEv: { type: 'f32', default: 0 },\n rangeEv: { type: 'array<f32, 2>', default: new Float32Array([-8, 8]) },\n rates: { type: 'array<f32, 2>', default: new Float32Array([3, 1]) },\n whitePoint: { type: 'f32', default: 4.0 },\n temperature: { type: 'f32', default: 6504 },\n tint: { type: 'f32', default: 0 },\n colorLut: { type: 'shared<TextureAsset>', default: 0 as never },\n colorLutStrength: { type: 'f32', default: 0 },\n antialias: { type: 'f32', default: 0 },\n historyVersion: { type: 'u32', default: 0 },\n bloom: { type: 'f32', default: 0 },\n bloomThreshold: { type: 'f32', default: 1.0 },\n bloomIntensity: { type: 'f32', default: 1.0 },\n bloomSoftKnee: { type: 'f32', default: 0.5 },\n bloomScatter: { type: 'f32', default: 0.7 },\n // M1 target camera role: zero means this camera is eligible for display;\n // non-zero shared targets are auxiliary producers whose views and receipt\n // promotion remain owned by Renderer.\n target: { type: 'shared<RenderTarget>', simulationTransient: true },\n // feat-20260709 M3 / D-3: clear-color is one inline `array<f32,4>` column.\n // The earlier 4-scalar form (clearR/G/B/A) was chosen when this was believed\n // to be the only SoA-safe shape; the Transform (pos/quat/scale) and light\n // (direction/color) precedents disprove that -- an `array<f32,N>` IS an\n // inline stride-N SoA column, read on the hot path as `col[i*N+a]` with zero\n // allocation, so collapsing four scalars into one column removes three field\n // names a reader must track without changing the storage layout or read\n // pattern. The default `[0, 0, 0, 0]` is transparent black; explicit alpha\n // stays visible through the same public array field.\n clearColor: { type: 'array<f32, 4>', default: new Float32Array([0, 0, 0, 0]) },\n // feat-20260617-host-engine-contract-and-video-cutscene / M3 / D-4: the\n // aspect-sync sidecar on the createApp(canvas) path writes\n // canvas.width / canvas.height into `aspect` every frame when this flag is\n // true. Reuses the existing `bool` column tier (AnimationPlayer.paused /\n // AudioSource.playing precedent) -- zero ECS infrastructure change. Default\n // true so demos that never touch aspect track the canvas automatically\n // (charter P1 default-is-correct); set false for render-to-texture /\n // split-screen cameras that drive aspect themselves. Read it via\n // world.get (readRow narrows bool -> JS boolean); the query-bundle path\n // returns a raw 0/1 number (the `!== 0` always-true trap).\n autoAspect: { type: 'bool', default: true },\n});\n\n// ─── Camera POD type (derived from Camera token — single source, AC-07) ─────\n//\n// ShapeOf<SchemaOf<typeof Camera>> resolves the 30-field POD from the Camera\n// token's schema, which is itself derived from Camera.fields[k].type (D-A7).\n// This replaces the hand-maintained CameraDataPod interface — the field set\n// lives exclusively in the Camera component definition above.\nexport type CameraData = ShapeOf<SchemaOf<typeof Camera>>;\ntype CameraPod = CameraData;\n\n/** Project the Camera SoA columns back into the public closed union. */\nexport function cameraExposureFromColumns(\n input: Pick<CameraData, 'exposureMode' | 'exposure' | 'compensationEv' | 'rangeEv' | 'rates'>,\n): CameraExposure {\n if (input.exposureMode === CAMERA_EXPOSURE_MODE_MANUAL) {\n return validateCameraExposure({ kind: 'manual', multiplier: input.exposure });\n }\n if (input.exposureMode === CAMERA_EXPOSURE_MODE_AUTO) {\n return validateCameraExposure({\n kind: 'auto',\n fallback: input.exposure,\n compensationEv: input.compensationEv,\n rangeEv: [input.rangeEv[0] ?? -8, input.rangeEv[1] ?? 8],\n rates: [input.rates[0] ?? 3, input.rates[1] ?? 1],\n });\n }\n throw cameraError(\n 'camera-exposure-mode-invalid',\n 'exposureMode',\n input.exposureMode,\n `${CAMERA_EXPOSURE_MODE_MANUAL} or ${CAMERA_EXPOSURE_MODE_AUTO}`,\n 'set Camera.exposureMode to the manual or auto encoding',\n );\n}\n\nfunction cameraExposureColumns(\n exposure: CameraExposure,\n): Pick<CameraData, 'exposureMode' | 'exposure' | 'compensationEv' | 'rangeEv' | 'rates'> {\n const checked = validateCameraExposure(exposure);\n if (checked.kind === 'manual') {\n return {\n exposureMode: CAMERA_EXPOSURE_MODE_MANUAL,\n exposure: checked.multiplier,\n compensationEv: 0,\n rangeEv: new Float32Array([-8, 8]),\n rates: new Float32Array([3, 1]),\n };\n }\n return {\n exposureMode: CAMERA_EXPOSURE_MODE_AUTO,\n exposure: checked.fallback,\n compensationEv: checked.compensationEv,\n rangeEv: new Float32Array(checked.rangeEv),\n rates: new Float32Array(checked.rates),\n };\n}\n\ninterface CameraColorGradingOpts {\n exposure?: CameraExposure;\n temperature?: number;\n tint?: number;\n colorLut?: CameraPod['colorLut'];\n colorLutStrength?: number;\n}\n\nfunction cameraColorGradingColumns(\n opts: CameraColorGradingOpts,\n): ReturnType<typeof cameraExposureColumns> &\n Pick<CameraData, 'temperature' | 'tint' | 'colorLut' | 'colorLutStrength'> {\n const exposure = opts.exposure ?? { kind: 'manual', multiplier: 1 };\n const temperature = opts.temperature ?? 6504;\n const tint = opts.tint ?? 0;\n const colorLutStrength = opts.colorLutStrength ?? 0;\n validateCameraColorGrading(temperature, tint, colorLutStrength);\n return {\n ...cameraExposureColumns(exposure),\n temperature,\n tint,\n colorLut: opts.colorLut ?? (0 as CameraPod['colorLut']),\n colorLutStrength,\n };\n}\n\n// ─── Camera factory functions (w13 SSOT refactoring) ─────────────────────\n//\n// Standalone factory functions that return 29-field CameraPod objects\n// matching the Camera component column shape. Not static methods because\n// TypeScript const-namespace merge is not supported, and Object.assign\n// would break the Camera token's reference identity (archetype columns /\n// queries key off the global owner identity associated with the token).\n//\n// Import as:\n// import { Camera, perspective, orthographic } from '@forgeax/engine-render';\n// world.spawn({ component: Camera, data: perspective({ fov: 60, aspect: 4/3 }) });\n//\n// Charter P1 progressive disclosure: Barrel re-exports put perspective\n// / orthographic next to Camera in IDE autocomplete.\n//\n// D-A4 factory retention reason: perspective() / orthographic() carry\n// required/optional parameter semantics that cannot be derived from\n// the schema. perspective requires fov + aspect (no universal default),\n// orthographic requires left/right/bottom/top. The schema/defaults system\n// only records type + optional default value per field — it has no concept\n// of \"this field MUST be supplied by the caller.\" The factories encode\n// that contract at the TypeScript type level, which schema/defaults alone\n// cannot express. Per AC-07, the factories are kept; only the POD type\n// and default literals are derived from the Camera token (SSOT).\n\ninterface CameraPerspectiveOpts {\n fov: number;\n aspect: number;\n near?: number;\n far?: number;\n /**\n * feat-20260617-host-engine-contract-and-video-cutscene / M3: when true\n * (the schema default), the aspect-sync sidecar on the createApp(canvas)\n * path overwrites `aspect` with `canvas.width / canvas.height` every frame.\n * Omit it for the default-correct behaviour; set `false` to opt out (the\n * factory then leaves `aspect` under your control -- render-to-texture,\n * split-screen). Cameras built on the bare `createRenderer` path never\n * receive aspect-sync regardless of this flag.\n */\n autoAspect?: boolean;\n exposure?: CameraExposure;\n temperature?: number;\n tint?: number;\n colorLut?: CameraPod['colorLut'];\n colorLutStrength?: number;\n}\n\ninterface CameraOrthographicOpts {\n left: number;\n right: number;\n bottom: number;\n top: number;\n near?: number;\n far?: number;\n exposure?: CameraExposure;\n temperature?: number;\n tint?: number;\n colorLut?: CameraPod['colorLut'];\n colorLutStrength?: number;\n}\n\n/**\n * Build a CameraPod base from Camera.fields defaults (per-field SSOT).\n * Fields without a default (fov / aspect / near / far — OOS-5) are left\n * unset; caller fills them from opts or sentinel values.\n */\nfunction cameraPodFromDefaults(): CameraPod {\n const base: Record<string, unknown> = {};\n for (const [key, field] of Object.entries(Camera.fields)) {\n if ('default' in field && field.default !== undefined) {\n base[key] = field.default;\n }\n }\n return base as CameraPod;\n}\n\n/**\n * Convenience factory: perspective CameraData POD.\n *\n * `fov` and `aspect` are required (no sensible universal default).\n * `near` defaults to 0.1, `far` defaults to 100.\n * Orthographic quartet defaults to [-1, 1]x[-1, 1]; tonemap defaults to\n * TONEMAP_NONE (0-overhead path).\n *\n * When `autoAspect` is `true` (the default once shipped in M3), the\n * aspect-sync sidecar on the `createApp(canvas)` path automatically writes\n * `canvas.width / canvas.height` into `Camera.aspect` every frame. Set\n * `autoAspect = false` to opt out (render-to-texture, split-screen).\n * Cameras on the `createRenderer` path do not receive aspect-sync.\n *\n * @see {@link https://github.com/Ubpa/forgeax-engine/blob/main/docs/how-to/2026-06-18-host-engine-contract.md | Host-engine contract SSOT}\n *\n * @example\n * ```ts\n * import { Camera, perspective } from '@forgeax/engine-render';\n * world.spawn(\n * { component: Camera, data: perspective({ fov: Math.PI / 3, aspect: 4 / 3 }) }\n * ).unwrap();\n * ```\n *\n * @example With explicit near/far:\n * ```ts\n * const camData = perspective({ fov: Math.PI / 4, aspect: 16 / 9, near: 0.01, far: 1000 });\n * world.spawn({ component: Camera, data: camData }).unwrap();\n * ```\n *\n * @example With non-default clear color (default is `[0, 0, 0, 0]`).\n * `clearColor` is an inline `array<f32,4>` field on `Camera`; spread the\n * factory then override:\n * ```ts\n * world.spawn({\n * component: Camera,\n * data: { ...perspective({ fov: Math.PI / 3, aspect: 4 / 3 }), clearColor: [0, 1, 0, 1] },\n * }).unwrap();\n * ```\n */\nexport function perspective(opts: CameraPerspectiveOpts): CameraPod {\n return {\n // cameraPodFromDefaults() reads autoAspect's schema default (true), so an\n // omitted opts.autoAspect lands the default-correct value; an explicit\n // false overrides it below (D-4: factory one-step opt-out, charter P1).\n ...cameraPodFromDefaults(),\n fov: opts.fov,\n aspect: opts.aspect,\n near: opts.near ?? 0.1,\n far: opts.far ?? 100,\n projection: CAMERA_PROJECTION_PERSPECTIVE,\n ...(opts.autoAspect !== undefined ? { autoAspect: opts.autoAspect } : {}),\n ...cameraColorGradingColumns(opts),\n };\n}\n\n/**\n * Convenience factory: orthographic CameraData POD.\n *\n * All four ortho bounds (`left` / `right` / `bottom` / `top`) are required.\n * `near` defaults to 0.1, `far` defaults to 100.\n * Perspective fields get sentinel defaults (fov=0, aspect=1) for column\n * alignment with the 12-field schema.\n *\n * @example\n * ```ts\n * import { Camera, orthographic } from '@forgeax/engine-render';\n * world.spawn(\n * { component: Camera, data: orthographic({\n * left: -10, right: 10, bottom: -10, top: 10,\n * }) }\n * ).unwrap();\n * ```\n *\n * @example Screen-aligned orthographic for pixel-unit rendering:\n * ```ts\n * const camData = orthographic({ left: 0, right: 800, bottom: 600, top: 0 });\n * world.spawn({ component: Camera, data: camData }).unwrap();\n * ```\n */\nexport function orthographic(opts: CameraOrthographicOpts): CameraPod {\n return {\n ...cameraPodFromDefaults(),\n fov: 0,\n aspect: 1,\n near: opts.near ?? 0.1,\n far: opts.far ?? 100,\n projection: CAMERA_PROJECTION_ORTHOGRAPHIC,\n left: opts.left,\n right: opts.right,\n bottom: opts.bottom,\n top: opts.top,\n ...cameraColorGradingColumns(opts),\n };\n}\n","import { defineComponent, type SchemaOf, type ShapeOf } from '@forgeax/engine-ecs';\n\n/** Closed quality lane for the renderer-owned procedural cloud producer. */\nexport type CloudQuality = 'low' | 'medium' | 'high';\n\nexport const CloudQualityValue = Object.freeze({\n low: 0,\n medium: 1,\n high: 2,\n} as const);\n\n/**\n * A single World-authored cloud layer.\n *\n * The component contains only source facts. Cache resolution, optical step\n * counts, temporal history and GPU handles are derived by Render and never\n * written back into ECS.\n */\nexport const CloudLayer = defineComponent('CloudLayer', {\n /** Stable integer seed for the periodic 3D density field. */\n seed: { type: 'u32', default: 1337 },\n /** World-space lower edge of the layer, in metres. */\n baseHeight: { type: 'f32', default: 120 },\n /** World-space thickness of the layer, in metres. */\n thickness: { type: 'f32', default: 80 },\n /** Horizontal noise scale, in cycles per metre. */\n scale: { type: 'f32', default: 0.004 },\n /** Coverage threshold in [0, 1]. */\n coverage: { type: 'f32', default: 0.48 },\n /** Extinction multiplier in inverse metres. */\n density: { type: 'f32', default: 1 },\n /** World-space wind velocity in metres per second. */\n wind: { type: 'array<f32, 3>', default: new Float32Array([8, 0, 2]) },\n /** Quality controls cache resolution and bounded ray steps. */\n quality: { type: 'f32', default: CloudQualityValue.medium },\n /** Maximum world-space distance represented by the light-space shadow map. */\n shadowRange: { type: 'f32', default: 512 },\n});\n\nexport type CloudLayerData = ShapeOf<SchemaOf<typeof CloudLayer>>;\n\nexport function cloudQualityFromF32(value: number): CloudQuality | undefined {\n if (value === CloudQualityValue.low) return 'low';\n if (value === CloudQualityValue.medium) return 'medium';\n if (value === CloudQualityValue.high) return 'high';\n return undefined;\n}\n","// @forgeax/engine-render - CubeCamera capture vocabulary.\n//\n// CubeCamera is an ECS capture intent paired with Transform. GPU resources,\n// face views, completed-receipt promotion, and publication remain renderer-owned.\n\nimport { defineComponent, type SchemaOf, type ShapeOf } from '@forgeax/engine-ecs';\nimport { RenderIntentInvalidError } from '../errors/render';\n\nexport const CUBE_CAMERA_UPDATE_ONCE = 0;\nexport const CUBE_CAMERA_UPDATE_ON_DEMAND = 1;\nexport const CUBE_CAMERA_UPDATE_CONTINUOUS = 2;\n\nexport type CubeCameraUpdateIntent = 'once' | 'on-demand' | 'continuous';\n\nexport const CUBE_CAMERA_FACE_ORDER = ['+X', '-X', '+Y', '-Y', '+Z', '-Z'] as const;\nexport type CubeCameraFace = (typeof CUBE_CAMERA_FACE_ORDER)[number];\n\nexport function cubeCameraUpdateIntentFromF32(value: number): CubeCameraUpdateIntent {\n switch (value) {\n case CUBE_CAMERA_UPDATE_ONCE:\n return 'once';\n case CUBE_CAMERA_UPDATE_ON_DEMAND:\n return 'on-demand';\n case CUBE_CAMERA_UPDATE_CONTINUOUS:\n return 'continuous';\n default:\n throw new RenderIntentInvalidError('CubeCamera', value);\n }\n}\n\nexport function cubeCameraUpdateIntentToF32(intent: CubeCameraUpdateIntent): number {\n switch (intent) {\n case 'once':\n return CUBE_CAMERA_UPDATE_ONCE;\n case 'on-demand':\n return CUBE_CAMERA_UPDATE_ON_DEMAND;\n case 'continuous':\n return CUBE_CAMERA_UPDATE_CONTINUOUS;\n }\n}\n\n/** ECS declaration for a bounded, transient six-face capture request. */\nexport const CubeCamera = defineComponent('CubeCamera', {\n target: { type: 'shared<RenderTarget>', simulationTransient: true },\n near: { type: 'f32', default: 0.1 },\n far: { type: 'f32', default: 100 },\n updateIntent: { type: 'f32', default: CUBE_CAMERA_UPDATE_ONCE },\n requestVersion: { type: 'u32', default: 0 },\n faceBudget: { type: 'u32', default: 1 },\n});\n\nexport type CubeCameraData = ShapeOf<SchemaOf<typeof CubeCamera>>;\n","import { defineComponent, type SchemaOf, type ShapeOf } from '@forgeax/engine-ecs';\n\n/** Closed quality budget used by the built-in camera depth-of-field pass. */\nexport type DepthOfFieldQuality = 'low' | 'medium' | 'high';\n\nexport const DepthOfFieldQualityValue = Object.freeze({\n low: 0,\n medium: 1,\n high: 2,\n} as const);\n\n/** Selects which signed circle-of-confusion side contributes to the image. */\nexport type DepthOfFieldSide = 'both' | 'near' | 'far';\n\nexport const DepthOfFieldSideValue = Object.freeze({\n both: 0,\n near: 1,\n far: 2,\n} as const);\n\n/** Active-camera physical depth-of-field authoring data; presence enables it. */\nexport const DepthOfField = defineComponent('DepthOfField', {\n focusDistance: { type: 'f32', default: 8 },\n fStop: { type: 'f32', default: 2.8 },\n sensorHeight: { type: 'f32', default: 0.024 },\n maxRadiusPixels: { type: 'f32', default: 16 },\n quality: { type: 'f32', default: DepthOfFieldQualityValue.medium },\n blurSide: { type: 'f32', default: DepthOfFieldSideValue.both },\n});\n\nexport type DepthOfFieldData = ShapeOf<SchemaOf<typeof DepthOfField>>;\n\nexport function depthOfFieldQualityFromF32(value: number): DepthOfFieldQuality | undefined {\n if (value === DepthOfFieldQualityValue.low) return 'low';\n if (value === DepthOfFieldQualityValue.medium) return 'medium';\n if (value === DepthOfFieldQualityValue.high) return 'high';\n return undefined;\n}\n\nexport function depthOfFieldSideFromF32(value: number): DepthOfFieldSide | undefined {\n if (value === DepthOfFieldSideValue.both) return 'both';\n if (value === DepthOfFieldSideValue.near) return 'near';\n if (value === DepthOfFieldSideValue.far) return 'far';\n return undefined;\n}\n","// @forgeax/engine-render - closed Directional shadow filter vocabulary.\n\n/** Stable serialized labels for Directional shadow filtering. */\nexport const DirectionalShadowFilterValue = Object.freeze({\n pcf1: 1,\n pcf3: 2,\n pcf5: 3,\n pcssMedium: 4,\n pcssHigh: 5,\n} as const);\n\nexport type DirectionalShadowFilterLabel = keyof typeof DirectionalShadowFilterValue;\n\n/**\n * Extract-side semantic projection of the serialized Directional filter.\n * `shadowAngularRadius` is radians and `maxPenumbraTexels` is a finite integer.\n */\nexport type DirectionalShadowQuality =\n | { readonly kind: 'pcf'; readonly kernel: 1 | 3 | 5 }\n | {\n readonly kind: 'pcss';\n readonly preset: 'medium' | 'high';\n readonly angularRadiusRadians: number;\n readonly maxPenumbraTexels: number;\n };\n\n/** Resolve the closed serialized label to the receiver-facing semantic union. */\nexport function directionalShadowQualityFromF32(\n value: number,\n angularRadiusRadians: number,\n maxPenumbraTexels: number,\n): DirectionalShadowQuality | undefined {\n switch (value) {\n case DirectionalShadowFilterValue.pcf1:\n return { kind: 'pcf', kernel: 1 };\n case DirectionalShadowFilterValue.pcf3:\n return { kind: 'pcf', kernel: 3 };\n case DirectionalShadowFilterValue.pcf5:\n return { kind: 'pcf', kernel: 5 };\n case DirectionalShadowFilterValue.pcssMedium:\n return {\n kind: 'pcss',\n preset: 'medium',\n angularRadiusRadians,\n maxPenumbraTexels,\n };\n case DirectionalShadowFilterValue.pcssHigh:\n return {\n kind: 'pcss',\n preset: 'high',\n angularRadiusRadians,\n maxPenumbraTexels,\n };\n default:\n return undefined;\n }\n}\n","// @forgeax/engine-render - DirectionalLight (directional light parameters\n// with merged shadow config).\n//\n// Schema: direction array<f32,3> + color array<f32,3> + intensity f32 + 1 bool\n// castShadow + 8 f32 shadow columns (feat-20260709 M2: direction/color collapsed\n// from 6 per-axis scalar columns to two inline array<f32,3> columns).\n//\n// Direction (xyz, outgoing) + color (rgb, linear space) + intensity in lux.\n// No Transform dependency (directional lights have no position).\n// The public world-unit convention is 1 world unit = 1 meter. Exposure is a\n// camera output concern and is not folded into this light's intensity.\n//\n// 0 DirectionalLight + standard material -> physically correct black render\n// (charter v2 P3/P4); details: AGENTS.md section Breaking changes 2026-05-18.\n//\n// Naming convention: bare entity name aligned with Bevy ECS conventions\n// (feat-20260513-component-naming-bevy-align). Camera / Transform / etc.\n// follow the same single-semantic-entity rule (charter proposition 5).\n//\n// charter mapping: proposition 1 (single import) + proposition 3 (silent\n// failure -> explicit warning; first-frame warn) + proposition 5 (consistent\n// abstraction: lighting parameters mirror GPU-side pbr.wgsl @group(0) view\n// BG light fields).\n//\n// feat-20260621-merge-directionallightshadow-into-directionallight M1:\n// DirectionalLightShadow's 9 shadow fields are merged into DirectionalLight\n// to collapse the dual-component spawn into a single component (D-6 primary\n// decision). castShadow defaults to true so zero-config spawns get shadows\n// by default; set castShadow=false to opt out. D-6 directional stays\n// first-hit-wins -- no ECS cardinality cap. Renderer allocation policy stays\n// with the shadow atlas owner.\n\nimport { defineComponent } from '@forgeax/engine-ecs';\nimport { DirectionalShadowFilterValue } from './directional-shadow-filter';\n\nexport {\n type DirectionalShadowFilterLabel,\n DirectionalShadowFilterValue,\n type DirectionalShadowQuality,\n directionalShadowQualityFromF32,\n} from './directional-shadow-filter';\n\n/**\n * Directional light (sun-like infinite light source) with merged shadow\n * parameters.\n *\n * `direction` @semantics outgoing — points FROM light source TO surface\n * (opposite of Three.js convention; the shader internally negates this\n * vector to obtain the L vector for BRDF evaluation). `color` is\n * linear-space rgb in [0, 1] per channel and `intensity` is lux. Exposure is\n * applied after lighting by the camera output stage; no hidden light\n * multiplier is applied here.\n *\n * castShadow defaults to true — zero-config spawns cast cascaded shadow maps.\n * Set castShadow: false to opt out (shadow fields are still stored but their\n * validation is skipped).\n *\n * Shadow fields (migrated from DirectionalLightShadow, feat-20260621 M1):\n * cascadeCount ∈ {1,2,3,4} — number of cascades (default 4)\n * splitLambda ∈ [0,1] — PSSM split weight (default 0.75)\n * cascadeBlend ∈ [0,0.5] — blend width between cascades (default 0.2)\n * mapSize >= 1 — shadow map resolution (default 2048)\n * depthBias — normalized receiver depth floor (default 0.00001),\n * plus automatic texel/filter/slope coverage\n * normalBias — world-space receiver normal offset (default 0.05)\n * shadowDistance > 0 — how far shadows reach in front of the camera,\n * in world units (default 200). This is the sole\n * coverage knob: the CSM cascades are PSSM-split\n * across [camera near, shadowDistance] and each\n * cascade's orthographic bounds are fit to the\n * camera frustum slice automatically. The near\n * end is derived from the active camera's near\n * plane (no separate near knob — any value other\n * than the camera near either drops near shadows\n * or wastes cascade-0 resolution).\n * shadowFilter ∈ {pcf1, pcf3, pcf5, pcssMedium, pcssHigh} — closed filter profile (default pcf3)\n * shadowAngularRadius ∈ [0.0001, 0.05] radians — PCSS angular light radius (default 0.00465)\n * maxPenumbraTexels ∈ [1, 64], finite integer — PCSS search/filter cap (default 32)\n *\n * @example Spawn a single directional light with default shadows:\n * world.spawn({ component: DirectionalLight, data: {\n * direction: [-0.5, -1, -0.3], // [x, y, z]\n * color: [1, 1, 1], // [r, g, b]\n * intensity: 1,\n * } });\n *\n * @example Opt out of shadows:\n * world.spawn({ component: DirectionalLight, data: {\n * direction: [0, -1, 0], // [x, y, z]\n * castShadow: false,\n * } });\n *\n * @example Explicit shadow config (single-component spawn):\n * world.spawn({ component: DirectionalLight, data: {\n * direction: [0.2, -0.98, 0], // [x, y, z]\n * color: [1, 1, 1], intensity: 1, // color is [r, g, b]\n * cascadeCount: 4, splitLambda: 0.75, cascadeBlend: 0.2,\n * mapSize: 2048, shadowDistance: 200,\n * shadowFilter: DirectionalShadowFilterValue.pcssHigh,\n * shadowAngularRadius: 0.00465, maxPenumbraTexels: 32,\n * } });\n * // shadowFilter uses the numeric DirectionalShadowFilterValue constant,\n * // not the serialized label string 'pcssHigh'.\n *\n * @example 0-light scene must use an unlit shader (standard 0 light = physically correct black):\n * const world = new World();\n * // ... spawn cube + camera, no light ...\n * await renderer.ready;\n * renderer.draw(world); // standard material renders black; switch to an unlit shader (Materials.unlit(...)) for an unlit display\n */\nexport const DirectionalLight = defineComponent('DirectionalLight', {\n // direction is the ONLY field with no default (D-5): omitting it lands the\n // array layer-3 all-zero [0,0,0], which the renderer owner rejects -- there is no\n // universal default direction, so \"default is illegal\" forces an explicit\n // non-zero value. color carries an explicit layer-2 default [1,1,1] (white);\n // the array layer-3 fallback is all-zero, so the default MUST be explicit.\n direction: { type: 'array<f32, 3>' },\n color: { type: 'array<f32, 3>', default: new Float32Array([1, 1, 1]) },\n intensity: { type: 'f32', default: 1 },\n // Shadow opt-out gate: defaults to true so zero-config spawns get shadows.\n castShadow: { type: 'bool', default: true },\n // 9 shadow fields migrated from DirectionalLightShadow (feat-20260621 M1).\n cascadeCount: { type: 'f32', default: 4 },\n splitLambda: { type: 'f32', default: 0.75 },\n cascadeBlend: { type: 'f32', default: 0.2 },\n mapSize: { type: 'f32', default: 2048 },\n depthBias: { type: 'f32', default: 0.00001 },\n normalBias: { type: 'f32', default: 0.05 },\n // Sole shadow coverage knob (feat replaces nearPlane/farPlane). The PSSM\n // near end derives from the active camera near; shadowDistance is the far\n // reach. Default 200 world units (matches UE-style \"dynamic shadow\n // distance\"; the old farPlane default was 50).\n shadowDistance: { type: 'f32', default: 200 },\n shadowFilter: {\n type: 'enum',\n default: DirectionalShadowFilterValue.pcf3,\n labels: DirectionalShadowFilterValue,\n },\n shadowAngularRadius: { type: 'f32', default: 0.00465 },\n maxPenumbraTexels: { type: 'f32', default: 32 },\n});\n","import { defineComponent, type SchemaOf, type ShapeOf } from '@forgeax/engine-ecs';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport {\n type DynamicResolutionError,\n DynamicResolutionInvalidParameterError,\n DynamicResolutionRequiresTaaError,\n} from '../errors/render';\n\n/** Optional Camera companion that enables fixed or adaptive internal scaling. */\nexport const DynamicResolution = defineComponent('DynamicResolution', {\n targetGpuMs: { type: 'f32', default: 16.67 },\n minScale: { type: 'f32', default: 0.67 },\n maxScale: { type: 'f32', default: 1.0 },\n});\n\nexport type DynamicResolutionData = ShapeOf<SchemaOf<typeof DynamicResolution>>;\n\nconst DEFAULT_DYNAMIC_RESOLUTION: DynamicResolutionData = Object.freeze({\n targetGpuMs: 16.67,\n minScale: 0.67,\n maxScale: 1,\n});\n\nfunction invalid(\n field: 'targetGpuMs' | 'minScale' | 'maxScale',\n value: number,\n expected: string,\n): DynamicResolutionInvalidParameterError {\n return new DynamicResolutionInvalidParameterError({ field, value, expected });\n}\n\n/** Validate one detached DynamicResolution authoring POD before graph work. */\nexport function validateDynamicResolutionParameters(\n input: Partial<DynamicResolutionData> | undefined,\n): Result<DynamicResolutionData, DynamicResolutionInvalidParameterError> {\n const value = input ?? {};\n const targetGpuMs = value.targetGpuMs ?? DEFAULT_DYNAMIC_RESOLUTION.targetGpuMs;\n const minScale = value.minScale ?? DEFAULT_DYNAMIC_RESOLUTION.minScale;\n const maxScale = value.maxScale ?? DEFAULT_DYNAMIC_RESOLUTION.maxScale;\n if (!Number.isFinite(targetGpuMs) || targetGpuMs <= 0) {\n return err(invalid('targetGpuMs', targetGpuMs, 'finite and greater than 0'));\n }\n if (!Number.isFinite(minScale) || minScale < 0.5 || minScale > 1) {\n return err(invalid('minScale', minScale, 'finite and in [0.5, 1.0]'));\n }\n if (!Number.isFinite(maxScale) || maxScale < 0.5 || maxScale > 1) {\n return err(invalid('maxScale', maxScale, 'finite and in [0.5, 1.0]'));\n }\n if (minScale > maxScale) {\n return err(invalid('minScale', minScale, 'less than or equal to maxScale'));\n }\n return ok(Object.freeze({ targetGpuMs, minScale, maxScale }));\n}\n\n/** Validate the Camera companion relationship at the extraction boundary. */\nexport function validateDynamicResolutionCamera(\n input: Partial<DynamicResolutionData> | undefined,\n antialias: 'none' | 'fxaa' | 'msaa' | 'taa',\n): Result<DynamicResolutionData | undefined, DynamicResolutionError> {\n if (input === undefined) return ok(undefined);\n const parameters = validateDynamicResolutionParameters(input);\n if (!parameters.ok) return parameters;\n if (antialias !== 'taa') {\n return err(new DynamicResolutionRequiresTaaError({ antialias }));\n }\n return parameters;\n}\n","import { defineComponent } from '@forgeax/engine-ecs';\n\n/** Optional height-aware aerial fog, independent from environment source. */\nexport const Fog = defineComponent('Fog', {\n color: { type: 'array<f32, 3>', default: new Float32Array([0.5, 0.5, 0.5]) },\n density: { type: 'f32', default: 0.01 },\n heightFalloff: { type: 'f32', default: 0 },\n maxOpacity: { type: 'f32', default: 1 },\n});\n","import { defineComponent } from '@forgeax/engine-ecs';\n\n/**\n * World-owned local transforms for one explicit instanced renderable.\n * Packed column-major mat4 values compose as entityWorld * instanceLocal.\n * ECS owns copying, mutation and entity lifetime, including large arrays.\n * Renderer extraction derives its own snapshot and GPU residency; neither\n * authoring nor glTF SceneAsset lowering requires a Renderer identity.\n *\n * @example\n * const transforms = new Float32Array(20_000 * 16);\n * for (let i = 0; i < 20_000; i++) {\n * transforms[i * 16] = transforms[i * 16 + 5] =\n * transforms[i * 16 + 10] = transforms[i * 16 + 15] = 1;\n * }\n * const entity = world.spawn({ component: Instances, data: { transforms } }).unwrap();\n * world.set(entity, Instances, { transforms }).unwrap();\n */\nexport const Instances = defineComponent('Instances', {\n transforms: { type: 'array<f32>' },\n});\n\nexport type InstancesData = { readonly transforms: Float32Array };\n","// @forgeax/engine-render - Layer (render-order layer index, signed 32-bit).\n//\n// Schema: 1 i32 column (value). Signed two's complement so negatives travel\n// through the spawn payload unchanged — background sprites live at negative\n// values (e.g. -100), the default game layer at 0, foreground at 100, UI at\n// 1000. Layer is consumed at sort time by `transparent-sort.ts` (M-3 w23)\n// as the primary key in the (layer asc, sortValue asc) composite ordering.\n//\n// Naming convention: bare entity name (no Component suffix; single-semantic\n// component idiom aligned with Bevy ECS conventions — Transform / Camera /\n// DirectionalLight follow the same shape, see AGENTS.md §Component naming).\n//\n// Layer is a generic ECS renderer component — NOT a 2D-only special. 3D\n// entities may also carry Layer to bias their bucket placement (charter\n// P4 consistent abstraction: same component drives both pipelines).\n//\n// AC-18 path (1): an entity spawned without an explicit Layer reads back\n// 0 via the existing 4-layer spawn fallback chain\n// (feat-20260517-spawn-default-fallback). This feat does NOT introduce a\n// fifth fallback layer; the silent default flows through layer-3\n// `typeDefault('i32') === 0`.\n//\n// @derives defineComponent factory (packages/ecs/src/component.ts) — i32\n// is a legacy scalar type; its intrinsic properties (byteSize / viewCtor\n// / storage) live in TYPE_METADATA['i32'] (feat-20260602 M1).\n// @reuses spawn 4-layer fallback chain (feat-20260517-spawn-default-fallback)\n// — layer-3 typeDefault('i32') returns 0, no fifth layer.\n//\n// charter mapping: F1 (single-import barrel discovery — Layer joins\n// Transform / MeshFilter / MeshRenderer / Camera / DirectionalLight)\n// + P3 (explicit default — 0 surfaces as a read-back value, not undefined)\n// + P4 (consistent abstraction — Layer is a generic render component, not\n// a 2D-only special).\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\n/**\n * Render-order layer index.\n *\n * Convention (non-binding; conveys intent, not enforced):\n * - negative (e.g. -100): background layers (sky / parallax tiles).\n * - 0: default game layer.\n * - positive (e.g. 100): foreground layers (overlays, FX).\n * - 1000+: UI / HUD.\n *\n * Signed i32 (two's complement, range \\u00b12\\u00b3\\u00b9). Negatives round-trip\n * through the spawn payload unchanged — no schema-layer mutate. i32 lives in\n * the CPU sort path (transparent-sort.ts M-3 w23); no GPU-side stride\n * compatibility risk.\n *\n * @example Minimal spawn (defaults to game layer 0):\n * world.spawn({ component: Layer, data: {} }); // yields value=0\n *\n * @example Spawn 4 sprites across the conventional layer band:\n * world.spawn({ component: Layer, data: { value: -100 } }); // background\n * world.spawn({ component: Layer, data: { value: 0 } }); // default\n * world.spawn({ component: Layer, data: { value: 100 } }); // foreground\n * world.spawn({ component: Layer, data: { value: 1000 } }); // UI\n *\n * @example Spawn payload omitting Layer — the 4-layer fallback fills 0:\n * const e = world.spawn(\n * { component: Transform, data: { pos: [0, 0, 0],\n * quat: [0, 0, 0, 1], scale: [1, 1, 1] } },\n * );\n * // Layer is not on the entity; query joins must check membership.\n */\nexport const Layer = defineComponent('Layer', {\n value: { type: 'i32', default: 0 },\n});\n","// @forgeax/engine-render - host-side light helpers (M2 / w12).\n//\n// Pure-function single-shot conversion helpers for the SpotLight + PointLight\n// extract path. Host calls each helper once per light entity per frame; the\n// shader then sees only pre-computed `cos*` / `invRangeSquared` values. The\n// runtime range owner is the revision-pinned Three r184 squared window; KHR\n// values remain an import/reference boundary and are not substituted here.\n//\n// AC anchors: requirements AC-03 (deg -> rad -> cos host two-step\n// conversion) + AC-08 (a + b) (KHR quartic + range = 0 NaN protection\n// boundary).\n//\n// Plan-strategy anchors: D-S2 (cone unit deg API + cos shader optimization\n// transparent to AI users) + D-S5 (Layer 1 host-side range = 0 ->\n// invRangeSquared = 1e8 protects the 0 * Infinity = NaN intermediate).\n\nimport { err, ok, R_MIN, type Result } from '@forgeax/engine-types';\nimport { SpawnLightInvalidBoundsError } from '../errors/ecs-validation';\nimport { ShadowInvalidConfigError } from '../errors/render';\nimport { DirectionalShadowFilterValue } from './directional-shadow-filter';\n\nexport type LightValidationError = SpawnLightInvalidBoundsError | ShadowInvalidConfigError;\nexport type LightValidationResult = Result<void, LightValidationError>;\n\nconst RANGE_ZERO_FALLBACK_INV_R2 = 1e8;\nconst DEG_TO_RAD = Math.PI / 180;\nconst PCSS_RADIUS_MIN = 0.0001;\nconst PCSS_RADIUS_MAX = 0.05;\nconst PCSS_PENUMBRA_MIN = 1;\nconst PCSS_PENUMBRA_MAX = 64;\n\n/**\n * Convert SpotLight cone half-angle (degrees) to its cosine.\n *\n * Single-shot deg -> rad -> cos conversion executed once per spot light\n * entity per frame on the host; the GPU shader sees only `cosInner` /\n * `cosOuter` so its falloff path stays branch-free\n * (`smoothstep(cosOuter, cosInner, dot(L, -lightDir))`).\n *\n * @param deg cone half-angle in degrees (component schema field\n * `innerConeDeg` / `outerConeDeg`)\n * @returns `cos(deg * pi / 180)`\n */\nexport function degToCos(deg: number): number {\n return Math.cos(deg * DEG_TO_RAD);\n}\n\n/**\n * Convert PointLight / SpotLight `range` (meters) to `1 / range^2`.\n *\n * Three-branch fold supplies `1 / range^2` for the Three r184 finite-range\n * window `clamp(1 - (d / range)^4, 0, 1)^2`:\n *\n * - `range = +Infinity` -> `0` (no truncation; quartic factor collapses\n * to `1`, falloff reduces to plain `1 / d^2`).\n * - `range = 0` -> `1e8` (host safety boundary; glTF `range: 0` is mapped\n * to the no-cutoff `Infinity` value before this helper is called).\n * - `range > 0` -> `1 / (range * range)` (standard quartic factor).\n *\n * @param range meters (component schema field `range`); `+Infinity` is the\n * KHR no-truncation default\n * @returns `1 / range^2` with three-branch NaN protection\n */\nexport function computeInvRangeSquared(range: number): number {\n if (range === Number.POSITIVE_INFINITY) return 0;\n if (range === 0) return RANGE_ZERO_FALLBACK_INV_R2;\n return 1 / (range * range);\n}\n\n/**\n * feat-20260709 M2 / D-1: shared zero/missing-direction validate for\n * DirectionalLight + SpotLight. `direction` has no layer-2 default, so an\n * omitted direction lands the array layer-3 all-zero -- the same illegal state\n * as an explicit zero vector. SSOT for the rejection so the two lights cannot\n * drift. Returns the structured error to reject, or `null` when the direction\n * is a valid non-zero vector.\n */\nexport function validateDirection(\n componentName: 'DirectionalLight' | 'SpotLight',\n direction: ArrayLike<number> | undefined,\n): SpawnLightInvalidBoundsError | null {\n const dir = direction;\n if (dir === undefined || ((dir[0] ?? 0) === 0 && (dir[1] ?? 0) === 0 && (dir[2] ?? 0) === 0)) {\n return new SpawnLightInvalidBoundsError(\n componentName,\n 'direction',\n dir === undefined ? [0, 0, 0] : [dir[0] ?? 0, dir[1] ?? 0, dir[2] ?? 0],\n );\n }\n return null;\n}\n\n/** Validate directional-light payloads at the render owner boundary. */\nexport function validateDirectionalLightData(\n data: Readonly<Record<string, unknown>>,\n): LightValidationResult {\n const directionError = validateDirection(\n 'DirectionalLight',\n data.direction as ArrayLike<number> | undefined,\n );\n if (directionError !== null) return err(directionError);\n if (data.castShadow === false) return ok(undefined);\n\n const mapSize = (data.mapSize as number | undefined) ?? 2048;\n if (mapSize < 1) {\n return err(new ShadowInvalidConfigError('mapSize', mapSize, 1));\n }\n const cascadeCount = (data.cascadeCount as number | undefined) ?? 4;\n if (cascadeCount < 1 || cascadeCount > 4 || !Number.isInteger(cascadeCount)) {\n return err(new ShadowInvalidConfigError('cascadeCount', cascadeCount, 1, 4));\n }\n const splitLambda = (data.splitLambda as number | undefined) ?? 0.75;\n if (splitLambda < 0 || splitLambda > 1) {\n return err(new ShadowInvalidConfigError('splitLambda', splitLambda, 0, 1));\n }\n const cascadeBlend = (data.cascadeBlend as number | undefined) ?? 0.2;\n if (cascadeBlend < 0 || cascadeBlend > 0.5) {\n return err(new ShadowInvalidConfigError('cascadeBlend', cascadeBlend, 0, 0.5));\n }\n const shadowDistance = (data.shadowDistance as number | undefined) ?? 200;\n if (shadowDistance <= 0) {\n return err(new ShadowInvalidConfigError('shadowDistance', shadowDistance, 0, '>'));\n }\n const shadowFilter =\n (data.shadowFilter as number | undefined) ?? DirectionalShadowFilterValue.pcf3;\n const allowedFilters = Object.values(DirectionalShadowFilterValue);\n if (!Number.isFinite(shadowFilter) || !allowedFilters.includes(shadowFilter as never)) {\n return err(\n new ShadowInvalidConfigError(\n 'shadowFilter',\n shadowFilter,\n { kind: 'allowed-values', values: allowedFilters },\n undefined,\n 'one of [pcf1, pcf3, pcf5, pcssMedium, pcssHigh]',\n ),\n );\n }\n if (\n shadowFilter === DirectionalShadowFilterValue.pcssMedium ||\n shadowFilter === DirectionalShadowFilterValue.pcssHigh\n ) {\n const shadowAngularRadius = (data.shadowAngularRadius as number | undefined) ?? 0.00465;\n if (!Number.isFinite(shadowAngularRadius)) {\n return err(\n new ShadowInvalidConfigError('shadowAngularRadius', shadowAngularRadius, {\n kind: 'range',\n min: PCSS_RADIUS_MIN,\n max: PCSS_RADIUS_MAX,\n }),\n );\n }\n // ECS stores this field as f32; both authored endpoints round outward.\n // Accept their stored representations, but not the adjacent out-of-range f32.\n if (\n shadowAngularRadius < Math.fround(PCSS_RADIUS_MIN) ||\n shadowAngularRadius > Math.fround(PCSS_RADIUS_MAX)\n ) {\n return err(\n new ShadowInvalidConfigError('shadowAngularRadius', shadowAngularRadius, {\n kind: 'range',\n min: PCSS_RADIUS_MIN,\n max: PCSS_RADIUS_MAX,\n }),\n );\n }\n const maxPenumbraTexels = (data.maxPenumbraTexels as number | undefined) ?? 32;\n if (\n !Number.isFinite(maxPenumbraTexels) ||\n !Number.isInteger(maxPenumbraTexels) ||\n maxPenumbraTexels < PCSS_PENUMBRA_MIN ||\n maxPenumbraTexels > PCSS_PENUMBRA_MAX\n ) {\n return err(\n new ShadowInvalidConfigError(\n 'maxPenumbraTexels',\n maxPenumbraTexels,\n { kind: 'range', min: PCSS_PENUMBRA_MIN, max: PCSS_PENUMBRA_MAX },\n undefined,\n 'a finite integer in [1, 64]',\n ),\n );\n }\n }\n return ok(undefined);\n}\n\n/** Validate spot-light payloads at the render owner boundary. */\nexport function validateSpotLightData(\n data: Readonly<Record<string, unknown>>,\n): LightValidationResult {\n const directionError = validateDirection(\n 'SpotLight',\n data.direction as ArrayLike<number> | undefined,\n );\n if (directionError !== null) return err(directionError);\n if (data.castShadow === false) return ok(undefined);\n\n const range = (data.range as number | undefined) ?? 10;\n if (typeof range !== 'number' || Number.isNaN(range) || range < 0) {\n return err(new SpawnLightInvalidBoundsError('SpotLight', 'range', range));\n }\n const innerConeDeg = (data.innerConeDeg as number | undefined) ?? 0;\n const outerConeDeg = (data.outerConeDeg as number | undefined) ?? 45;\n if (outerConeDeg > 90) {\n return err(new SpawnLightInvalidBoundsError('SpotLight', 'outerNinety', outerConeDeg));\n }\n if (outerConeDeg <= innerConeDeg) {\n return err(new SpawnLightInvalidBoundsError('SpotLight', 'innerOuter', outerConeDeg));\n }\n const mapSize = (data.mapSize as number | undefined) ?? 2048;\n if (mapSize < 1) return err(new ShadowInvalidConfigError('mapSize', mapSize, 1));\n const nearPlane = data.nearPlane as number | undefined;\n const farPlane = data.farPlane as number | undefined;\n if (nearPlane !== undefined && farPlane !== undefined && farPlane <= nearPlane) {\n return err(new ShadowInvalidConfigError('farPlane', farPlane, nearPlane));\n }\n const pcfKernelSize = (data.pcfKernelSize as number | undefined) ?? 3;\n if (pcfKernelSize < 1 || pcfKernelSize % 2 === 0) {\n return err(\n new ShadowInvalidConfigError(\n 'pcfKernelSize',\n pcfKernelSize,\n { kind: 'lower-bound', operator: '>=', value: 1 },\n undefined,\n 'an odd integer >= 1',\n ),\n );\n }\n const shadowIntensity = (data.shadowIntensity as number | undefined) ?? 1;\n if (!Number.isFinite(shadowIntensity) || shadowIntensity < 0 || shadowIntensity > 1) {\n return err(new ShadowInvalidConfigError('shadowIntensity', shadowIntensity, 0, 1));\n }\n return ok(undefined);\n}\n\n/** Validate point-light payloads at the render owner boundary. */\nexport function validatePointLightData(\n data: Readonly<Record<string, unknown>>,\n): LightValidationResult {\n const range = (data.range as number | undefined) ?? 10;\n if (typeof range !== 'number' || Number.isNaN(range) || range < 0) {\n return err(new SpawnLightInvalidBoundsError('PointLight', 'range', range));\n }\n return ok(undefined);\n}\n\n/** Validate point-light shadow payloads at the render owner boundary. */\nexport function validatePointLightShadowData(\n data: Readonly<Record<string, unknown>>,\n): LightValidationResult {\n const mapSize = (data.mapSize as number | undefined) ?? 512;\n if (mapSize < 1) return err(new ShadowInvalidConfigError('mapSize', mapSize, 1));\n const nearPlane = (data.nearPlane as number | undefined) ?? 0.1;\n const farPlane = (data.farPlane as number | undefined) ?? 25;\n if (farPlane <= nearPlane) {\n return err(new ShadowInvalidConfigError('farPlane', farPlane, nearPlane));\n }\n const pcfKernelSize = (data.pcfKernelSize as number | undefined) ?? 3;\n if (pcfKernelSize < 1 || pcfKernelSize % 2 === 0) {\n return err(\n new ShadowInvalidConfigError(\n 'pcfKernelSize',\n pcfKernelSize,\n { kind: 'lower-bound', operator: '>=', value: 1 },\n undefined,\n 'an odd integer >= 1',\n ),\n );\n }\n return ok(undefined);\n}\n\n/** Validate rectangular area-light authoring facts before renderer admission. */\nexport function validateRectAreaLightData(\n data: Readonly<Record<string, unknown>>,\n): LightValidationResult {\n const intensity = (data.intensity as number | undefined) ?? 1;\n if (typeof intensity !== 'number' || !Number.isFinite(intensity) || intensity < 0) {\n return err(new SpawnLightInvalidBoundsError('RectAreaLight', 'intensity', intensity));\n }\n const color = (data.color as ArrayLike<number> | undefined) ?? [1, 1, 1];\n if (\n color.length !== 3 ||\n Array.from(color).some(\n (value) => typeof value !== 'number' || !Number.isFinite(value) || value < 0,\n )\n ) {\n return err(new SpawnLightInvalidBoundsError('RectAreaLight', 'color', Array.from(color)));\n }\n for (const field of ['width', 'height', 'range'] as const) {\n const value = (data[field] as number | undefined) ?? (field === 'range' ? 10 : 1);\n if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {\n return err(new SpawnLightInvalidBoundsError('RectAreaLight', field, value));\n }\n }\n return ok(undefined);\n}\n\n/** Validate the fixed 27-value SH payload and minimum finite radius. */\nexport function validateLightProbeData(\n data: Readonly<Record<string, unknown>>,\n): LightValidationResult {\n const irradiance = data.irradiance as ArrayLike<number> | undefined;\n if (\n irradiance === undefined ||\n irradiance.length !== 27 ||\n Array.from(irradiance).some((value) => typeof value !== 'number' || !Number.isFinite(value))\n ) {\n return err(\n new SpawnLightInvalidBoundsError(\n 'LightProbe',\n 'irradiance',\n irradiance === undefined ? [] : Array.from(irradiance),\n ),\n );\n }\n const radius = (data.radius as number | undefined) ?? R_MIN;\n if (typeof radius !== 'number' || !Number.isFinite(radius) || radius < R_MIN) {\n return err(new SpawnLightInvalidBoundsError('LightProbe', 'radius', radius));\n }\n return ok(undefined);\n}\n","// @forgeax/engine-render - local diffuse LightProbe authoring facts.\n\nimport { defineComponent } from '@forgeax/engine-ecs';\nimport { R_MIN } from '@forgeax/engine-types';\n\n/**\n * Local diffuse irradiance probe. Transform supplies position; the 27 SH\n * values are nine RGB groups in the fixed real-SH order.\n */\nexport const LightProbe = defineComponent('LightProbe', {\n irradiance: { type: 'array<f32, 27>' },\n radius: { type: 'f32', default: R_MIN },\n});\n","import { defineComponent } from '@forgeax/engine-ecs';\n\n/** Screen-space independent line segment style. */\nexport const Lines = defineComponent(\n 'Lines',\n {\n widthPx: { type: 'f32', default: 1 },\n },\n {\n meta: {\n quickStart: 'Attach Lines to render line-list MeshAsset pairs in screen pixels.',\n diagnostics: 'Inspect widthPx at the points-lines admission boundary.',\n recovery: 'Use points-lines-invalid-style for non-finite or non-positive widthPx values.',\n boundaries:\n 'Lines owns raster width only; MeshFilter and MeshRenderer own geometry and material.',\n },\n },\n);\n","// @forgeax/engine-render - MeshFilter (mesh asset reference).\n//\n// Schema: `{ assetHandle: 'shared<MeshAsset>' }`. The schema-vocab\n// `'shared<T>'` keyword stores a u32 column and type-derives to\n// `Handle<'MeshAsset', 'shared'>` (engine-ecs Handle<T,M> twoParam\n// phantom; `'shared'` mode = ref-counted retain on set / release on\n// clear, lifecycle owned by `SharedRefStore` per feat-20260614).\n// The brand prevents cross-asset assignment at compile time (e.g.\n// `Handle<'TextureAsset','shared'>` is not assignable to `assetHandle`).\n//\n// AI users spawn with the assets-runtime constants `HANDLE_CUBE` /\n// `HANDLE_TRIANGLE` (now branded `Handle<'MeshAsset','shared'>` to\n// match the schema-derived shape). A loaded or custom MeshAsset payload is\n// bound by allocating a World shared reference before publishing this field.\n//\n// Naming flavor: unity-style \"MeshFilter / MeshRenderer\" pair, but the forgeax\n// pair does NOT mirror Unity's filter-toggle semantics - MeshFilter only\n// carries the geometry ref, MeshRenderer only carries the material handle;\n// the pair is independently composable. D-Q7 default-material policy\n// (feat-20260517-merge-mesh-renderer-material-renderer plan-strategy §2.2):\n// case A (entity carries MeshFilter without MeshRenderer) -> archetype\n// query never matches -> entity is silently absent from the\n// RenderableSnapshot[] (NO default-material fallback, NO onError fire);\n// case B (MeshRenderer.material omitted at spawn) -> mid-grey\n// defaultMaterialSnapshot fallback (no onError); an unbound scalar shared<T>\n// field (slot 0) is also not a renderable; case C (non-zero material handle\n// unresolved) -> RhiError 'asset-not-registered' (mirrors the\n// MeshFilter.assetHandle dangling-ref path).\n//\n// charter mapping: proposition 1 (single import) + proposition 4 (explicit\n// failure: a non-zero unregistered handle fires onError 'asset-not-registered'\n// with .detail = { assetHandle } + cross-asset brand mismatch is a TS\n// compile-time error) + proposition 5 (consistent abstraction: the schema\n// vocab `'shared<T>'` is the SSOT for AssetRegistry-owned handles across\n// the engine).\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\n/**\n * Mesh filter (geometry asset reference).\n *\n * `assetHandle` carries a `Handle<'MeshAsset', 'shared'>` (u32-stored)\n * pointing to a mesh payload in the current World shared-reference / builtin\n * handle namespace. An omitted field defaults to slot `0`, the unbound\n * sentinel; an entity with that value is not emitted as a renderable. Use the\n * predefined constants `HANDLE_CUBE` / `HANDLE_TRIANGLE` for builtins and\n * allocate a World shared reference for a loaded mesh payload.\n *\n * Error path: if a non-zero handle is not registered at draw time, RenderSystem\n * fires `Renderer.onError` with\n * `RhiError({ code: 'asset-not-registered', detail: { assetHandle } })`\n * and skips this entity (other entities continue rendering; charter\n * proposition 9 graceful degradation).\n *\n * @example Spawn an entity referencing the builtin cube mesh:\n * import { MeshFilter } from '@forgeax/engine-render';\n * import { HANDLE_CUBE } from '@forgeax/engine-assets-runtime';\n * world.spawn({ component: MeshFilter, data: { assetHandle: HANDLE_CUBE } });\n */\nexport const MeshFilter = defineComponent('MeshFilter', {\n assetHandle: { type: 'shared<MeshAsset>' },\n});\n","// @forgeax/engine-render - MeshRenderer (multi-material array slot).\n//\n// feat-20260608-mesh-multi-section-primitive-multi-material-slot M2 / w7:\n// the single `material` field is replaced with `materials` — an\n// `array<shared<MaterialAsset>>` indexed by MeshAsset.materialSlots. Entries\n// are sparse positional overrides: a missing/zero entry inherits the Mesh\n// slot default, while a defaultless slot inherits the neutral engine material.\n//\n// The schema-vocab keyword `'array<shared<MaterialAsset>>'` (feat-20260614\n// M5 -- migrated from `'array<handle<MaterialAsset>>'`) stores as a u32\n// column slot array; the brand prevents cross-asset assignment at compile\n// time. The `'shared<T>'` arm routes element retain/release through\n// SharedRefStore (M4 / w13) on overwrite / archetype migration.\n//\n// charter mapping: proposition 1 (single import — `MeshRenderer` is the\n// only material-binding component AI users see); proposition 3\n// (machine-readable schema > prose); proposition 4 (explicit failure: the\n// TS brand on `Handle<'MaterialAsset','shared'>` rejects cross-variant\n// assignment at compile time); proposition 5 (consistent abstraction:\n// shading model classification (`'unlit'` / `'standard'`) lives ONLY on\n// the asset discriminant, NOT on the component name).\n//\n// RenderSystem consumption: `render-system-extract.ts` runs ONE archetype\n// query (`world.query(MeshRenderer)`) and routes per entity by\n// `mat.materialShaderId` (shader identity) to the unlit.wgsl or pbr.wgsl\n// pipeline tag.\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\n/**\n * Mesh renderer (ECS component, multi-material array).\n *\n * Stores `materials: readonly Handle<'MaterialAsset','shared'>[]`\n * (u32-stored array, indexed by MeshAsset.materialSlots). Submeshes point to\n * those stable slots through `Submesh.materialSlot`. The asset's `passes[].shader`\n * identity is the SSOT for which pipeline RenderSystem routes the entity\n * to (record stage dispatches on `materialShaderId`).\n *\n * Defaults map carries `materials: []`: every slot inherits its Mesh-owned\n * default, or the neutral engine material when that slot is intentionally\n * defaultless.\n *\n * @example Spawn while inheriting every Mesh slot default:\n * world.spawn({ component: MeshRenderer, data: {} });\n *\n * @example Spawn an unlit-targeted entity:\n * import { MeshRenderer, Materials } from '@forgeax/engine-render';\n * const matPayload = engine.assets.catalog(matGuid, Materials.unlit([1, 0, 0, 1])).value;\n * const matHandle = world.allocSharedRef('MaterialAsset', matPayload);\n * world.spawn({ component: MeshRenderer, data: { materials: [matHandle] } });\n *\n * @example Spawn a standard (PBR) entity:\n * const matPayload = engine.assets.catalog(matGuid, Materials.standard({\n * baseColor: [0.5, 0.5, 0.5, 1], metallic: 0, roughness: 0.4,\n * })).value;\n * const matHandle = world.allocSharedRef('MaterialAsset', matPayload);\n * world.spawn({ component: MeshRenderer, data: { materials: [matHandle] } });\n */\nexport const MeshRenderer = defineComponent('MeshRenderer', {\n materials: { type: 'array<shared<MaterialAsset>>', default: [] },\n});\n","import { defineComponent } from '@forgeax/engine-ecs';\n\n/** Active-camera motion blur authoring data; presence enables the feature. */\nexport const MotionBlur = defineComponent('MotionBlur', {\n shutterAngle: { type: 'f32', default: 180 },\n maxRadiusPixels: { type: 'f32', default: 32 },\n sampleCount: { type: 'f32', default: 8 },\n targetFps: { type: 'f32', default: 60 },\n});\n","// @forgeax/engine-render - PointLight (omnidirectional point-light parameters).\n//\n// Schema: color array<f32,3> + intensity f32 + range f32 (feat-20260709 M2:\n// color collapsed from 3 per-axis scalar columns to one inline array<f32,3>).\n// `position` comes from the Transform component; PointLight requires a\n// companion Transform on the same entity (ECS query: `[Transform, PointLight]`).\n// `range` units are meters; defaults to `10.0`. Runtime finite-range\n// attenuation is the Three r184 squared window; the KHR unsquared curve is an\n// import/reference boundary only. See `light-helpers.ts` for the host-side\n// range projection.\n//\n// 0 light + standard material -> physically correct black render\n// (feat-20260518-pbr-direct-lighting-mvp). The runtime once-warn channel\n// (M5 / w25) collapses to \"directionalCount + pointCount + spotCount === 0\";\n// see packages/runtime/README.md section Common pitfalls for the AI-user\n// guidance after the M5 docs land.\n//\n// Naming convention: bare entity name aligned with Bevy ECS conventions\n// (feat-20260513-component-naming-bevy-align). DirectionalLight / SpotLight\n// follow the same single-semantic-entity rule (charter proposition 5).\n//\n// charter mapping: proposition 1 (single import + IDE autocomplete on\n// payload.range) + proposition 3 (silent failure -> explicit failure;\n// spawn-time fail-fast on range<0 / NaN with structured EcsError) +\n// proposition 5 (consistent abstraction: shared payload shape with\n// SpotLight; `range` semantics aligned with KHR_lights_punctual).\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\n/**\n * Omnidirectional point light (KHR_lights_punctual `point` type).\n *\n * `position` source: the companion `Transform` component on the same entity.\n * Spawn via `world.spawn({ component: Transform, data: ... }, { component: PointLight, data: ... })`\n * so the render system extract path can join the two via the\n * `[Transform, PointLight]` ECS query.\n *\n * `color` is linear-space rgb in `[0, 1]` per channel; `intensity` is candela;\n * `range` is in meters and defaults to `10.0`\n * (KHR convention; `+Infinity` is the KHR no-truncation value, retained\n * for KHR_lights_punctual `range: 0` bridging via `light-helpers.ts`).\n * The runtime window is `clamp(1 - (d / range)^4, 0, 1)^2`; its no-cutoff\n * boundary uses inverse-square decay with the shader safety floor. Exposure is\n * applied after lighting and never multiplied into intensity.\n *\n * @example Spawn a single point light at (5, 3, 5):\n * world.spawn(\n * { component: Transform, data: { pos: [5, 3, 5] } },\n * { component: PointLight, data: { intensity: 8, range: 25 } },\n * );\n *\n * @example Minimal spawn -- defaults give neutral white at full strength, range 10m:\n * world.spawn(\n * { component: Transform, data: { pos: [0, 1, 0] } },\n * { component: PointLight, data: {} },\n * );\n * // resolves to color=[1, 1, 1], intensity=1, range=10.0.\n */\nexport const PointLight = defineComponent('PointLight', {\n // color carries an explicit layer-2 default [1,1,1] (white); the array\n // layer-3 fallback is all-zero, so the default MUST be explicit (D-5).\n color: { type: 'array<f32, 3>', default: new Float32Array([1, 1, 1]) },\n intensity: { type: 'f32', default: 1 },\n range: { type: 'f32', default: 10.0 },\n});\n","// @forgeax/engine-runtime — PointLightShadow (omnidirectional point-light\n// shadow mapping parameters; cube-array atlas variant).\n//\n// Schema: 6 f32 columns — mapSize (u32, stored as f32), depthBias, normalBias,\n// nearPlane, farPlane, pcfKernelSize (u32, stored as f32). No fixed-extent\n// field — cube map uses fov=90 perspective, not ortho.\n//\n// Atlas capacity is a renderer policy; ECS does not enforce a component\n// cardinality bound.\n// Co-located with DirectionalLight in components/ (research L1.2).\n//\n// Naming convention: bare entity name (AGENTS.md §Component naming), no\n// Component suffix. Same defineComponent pattern and ShadowInvalidConfigError\n// surface as the shadow fields merged into DirectionalLight (feat-20260621 M1).\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\n/**\n * Omnidirectional point-light shadow mapping parameters.\n *\n * The renderer may batch this component into a bounded atlas, but the ECS\n * component remains a plain storage schema and carries no cardinality policy.\n *\n * @example Spawn a point light with default shadow config:\n * world.spawn(\n * { component: Transform, data: { pos: [0, 4, 0] } },\n * { component: PointLight, data: { range: 25 } },\n * { component: PointLightShadow, data: {} }, // 6 fields filled from defaults\n * );\n *\n * @example Spawn with explicit map size and bias:\n * world.spawn(\n * { component: PointLightShadow, data: { mapSize: 1024, depthBias: 0.01 } },\n * );\n */\nexport const PointLightShadow = defineComponent('PointLightShadow', {\n mapSize: { type: 'f32', default: 512 },\n depthBias: { type: 'f32', default: 0.005 },\n normalBias: { type: 'f32', default: 0.05 },\n nearPlane: { type: 'f32', default: 0.1 },\n farPlane: { type: 'f32', default: 25 },\n pcfKernelSize: { type: 'f32', default: 3 },\n});\n","import { defineComponent } from '@forgeax/engine-ecs';\n\n/** Public point raster shapes backed by the ECS enum column. */\nexport type PointShape = keyof typeof PointShapeValue;\n\n/** Numeric labels stored by the public Points shape enum field. */\nexport const PointShapeValue = Object.freeze({\n square: 0,\n circle: 1,\n} as const);\n\n/** Decode the Points shape column without treating an unknown value as valid. */\nexport function pointShapeFromU32(value: number): PointShape | undefined {\n switch (value) {\n case PointShapeValue.square:\n return 'square';\n case PointShapeValue.circle:\n return 'circle';\n default:\n return undefined;\n }\n}\n\n/** Screen-space point style. Geometry and material remain on their own owners. */\nexport const Points = defineComponent(\n 'Points',\n {\n sizePx: { type: 'f32', default: 4 },\n shape: { type: 'enum', default: PointShapeValue.square, labels: PointShapeValue },\n },\n {\n meta: {\n quickStart: 'Attach Points to render point-list MeshAsset vertices in screen pixels.',\n diagnostics: 'Inspect sizePx and decode shape with pointShapeFromU32.',\n recovery: 'Use points-lines-invalid-style for non-finite or non-positive sizePx values.',\n boundaries:\n 'Points owns raster size and shape only; MeshFilter and MeshRenderer own geometry and material.',\n },\n },\n);\n","// @forgeax/engine-render - PostProcessParams component.\n//\n// Schema: { shader: 'string', data: 'buffer' }.\n//\n// `shader` identifies the fullscreen post-process shader (the same id as passed to\n// the feature host registers for `id`). `data` carries the per-frame params\n// bytes as a variable-byte ECS managed buffer slot. The write side (world.spawn /\n// world.set) accepts every AllowSharedBufferSource (Float32Array / ArrayBuffer /\n// Uint8Array / typed array) and the ECS normalizes it to Uint8Array bytes\n// (feat-20260621 V2 / AC-A4); the read side (world.get) returns Uint8Array, which\n// satisfies AllowSharedBufferSource for GPU queue.writeBuffer ingestion.\n//\n// Single-semantic component — drops the `Component` suffix\n// (AGENTS.md §Component naming rule #1). The `data` field uses the ECS 'buffer'\n// vocab keyword (plan-strategy D-7) for variable-byte storage.\n//\n// Data flow (plan-strategy D-1):\n// extract -> iterate PostProcessParams-bearing entities ->\n// collect into Map<shaderId, AllowSharedBufferSource> snapshot ->\n// dispatchFullscreenPass picks up per-shader data -> writeBuffer to eager UBO.\n//\n// Decision anchors:\n// - requirements AC-A2 (data-driven, no imperative renderer.setParams mutator)\n// - requirements AC-A4 (AllowSharedBufferSource type on the data field)\n// - plan-strategy D-1 (new single-semantic ECS component for params)\n// - plan-strategy D-7 (ECS 'buffer' vocab keyword for variable-byte storage)\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\nconst schema = {\n shader: 'string',\n data: 'buffer',\n} as const;\n\nexport const PostProcessParams = defineComponent('PostProcessParams', schema);\n","// @forgeax/engine-render - single-sided rectangular area-light authoring facts.\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\n/**\n * Single-sided rectangular area light. Transform supplies the center and\n * world orientation; width and height remain authored emitter dimensions.\n */\nexport const RectAreaLight = defineComponent('RectAreaLight', {\n color: { type: 'array<f32, 3>', default: new Float32Array([1, 1, 1]) },\n intensity: { type: 'f32', default: 1 },\n width: { type: 'f32', default: 1 },\n height: { type: 'f32', default: 1 },\n range: { type: 'f32', default: 10 },\n});\n","// @forgeax/engine-render - local reflection probe vocabulary.\n//\n// A ReflectionProbe is an ECS authoring fact. The renderer owns its six-face\n// capture, PMREM output, box selection, and Skylight fallback; this component\n// never carries a GPU handle or an authored material reference.\n\nimport { defineComponent, type SchemaOf, type ShapeOf } from '@forgeax/engine-ecs';\nimport { RenderIntentInvalidError } from '../errors/render';\n\nexport const REFLECTION_PROBE_UPDATE_ONCE = 0;\nexport const REFLECTION_PROBE_UPDATE_ON_CHANGE = 1;\nexport const REFLECTION_PROBE_UPDATE_CONTINUOUS = 2;\n\nexport type ReflectionProbeUpdateIntent = 'once' | 'on-change' | 'continuous';\n\nexport function reflectionProbeUpdateIntentFromF32(value: number): ReflectionProbeUpdateIntent {\n switch (value) {\n case REFLECTION_PROBE_UPDATE_ONCE:\n return 'once';\n case REFLECTION_PROBE_UPDATE_ON_CHANGE:\n return 'on-change';\n case REFLECTION_PROBE_UPDATE_CONTINUOUS:\n return 'continuous';\n default:\n throw new RenderIntentInvalidError('ReflectionProbe', value);\n }\n}\n\nexport function reflectionProbeUpdateIntentToF32(intent: ReflectionProbeUpdateIntent): number {\n switch (intent) {\n case 'once':\n return REFLECTION_PROBE_UPDATE_ONCE;\n case 'on-change':\n return REFLECTION_PROBE_UPDATE_ON_CHANGE;\n case 'continuous':\n return REFLECTION_PROBE_UPDATE_CONTINUOUS;\n }\n}\n\nexport const ReflectionProbe = defineComponent('ReflectionProbe', {\n halfExtents: { type: 'array<f32, 3>', default: new Float32Array([1, 1, 1]) },\n priority: { type: 'f32', default: 0 },\n boxProjection: { type: 'bool', default: false },\n intensity: { type: 'f32', default: 1 },\n resolution: { type: 'u32', default: 256 },\n updateIntent: { type: 'f32', default: REFLECTION_PROBE_UPDATE_ONCE },\n invalidationVersion: { type: 'u32', default: 0 },\n});\n\nexport type ReflectionProbeData = ShapeOf<SchemaOf<typeof ReflectionProbe>>;\n","// @forgeax/engine-runtime - SceneInstance component (feat-20260608-\n// scene-nesting-ecs-fication M2 / w16).\n//\n// Single ECS fat component carrying everything that used to live on the\n// old `SceneInstance` + `SceneInstanceContainer` pair (deleted\n// in M3). Schema fits the ECS schema vocab (3 single-identifier fields):\n//\n// { source: 'shared<SceneAsset>',\n// mapping: 'array<entity>',\n// state: 'unique<SceneInstanceState>' }\n//\n// `source` carries the SceneAsset handle the synthetic root entity was\n// instantiated from (Tier-A AssetUnion handle, AGENTS.md §Assets submodule).\n// `mapping` is the LocalEntityId -> Entity table indexed positionally\n// (mapping[localId] = spawned Entity); the ECS variable-array column gives\n// us a SoA-friendly read path for query<SceneInstance> scans without\n// touching the dynamic Map/Set state.\n// `state` is a `ref<SceneInstanceState>` slot — World holds the live\n// SceneInstanceState payload in its UniqueRefStore and World despawn\n// auto-releases the ref u32 (the same path used by audio / physics\n// payloads, plan-strategy §D-2). Each instantiateScene call calls\n// `world.allocUniqueRef('SceneInstanceState', state)` once and stores the\n// returned u32 in this column.\n//\n// Decision anchors:\n// - plan-strategy §D-2 (single ref wraps SceneInstanceState dynamic\n// structure; ECS schema vocab `\\w+` rejects `ref<Map<...>>`)\n// - plan-strategy §3.2 sequence (sequence diagram step 'set ... state:\n// {entityToLocalId, detached, overrides, rootEntities}')\n// - AGENTS.md §Component naming rule #1 (single-semantic component drops\n// `Component` suffix)\n// - charter F1 (single-import barrel: SceneInstance lives in\n// `@forgeax/engine-render` next to Transform / Camera / DirectionalLight)\n// - charter P3 (machine-readable schema: 3 closed fields)\n// - charter P4 (consistent abstraction: instance == entity carrying\n// SceneInstance — same `world.query({ read: [SceneInstance] })` /\n// `world.get(root, SceneInstance)` path as another component)\n\nimport { defineComponent, type EntityHandle } from '@forgeax/engine-ecs';\nimport type { MountOverride } from '@forgeax/engine-scene';\nimport type { LocalEntityId } from '@forgeax/engine-types';\n\n/**\n * Per-component, per-field override record carried in `SceneInstanceState`.\n *\n * Composite key `<componentName>:<fieldName>` keeps the override map flat\n * (single Map nesting level) so AI users walking `state.overrides` see one\n * iteration depth — D-2 prefers a single SSOT over multi-Map nesting that\n * would make iteration order ambiguous (charter F1: single mental model).\n *\n * The value is `unknown` because the per-component schema vocab lives in the\n * ECS layer; runtime fail-fast via `EcsErrorCode = 'scene-override-type-\n * mismatch'` (plan-strategy §D-9) catches type drift on the apply path.\n *\n * @internal Surface from `state.overrides` only; AI users never construct a\n * record directly. Use `world.setSceneOverride(root, member, comp,\n * field, value)` to write and `world.removeSceneOverride(root, member,\n * comp, field)` to roll back to the source SceneAsset value.\n */\nexport interface SceneInstanceOverrideRecord {\n readonly comp: string;\n /**\n * Component-granular add-or-patch discriminant (feat-20260713 M1 / w4):\n * present -> this record patches a single field; absent -> it adds/upserts\n * the whole `comp` (M2 apply semantics). Mirrors `MountOverride.field`.\n */\n readonly field?: string;\n readonly value: unknown;\n}\n\n/**\n * Dynamic state payload for one SceneInstance — held in the World's\n * UniqueRefStore behind a `ref<SceneInstanceState>` slot on the synthetic\n * root entity. Mirrors the old class-based layout (plan-strategy §D-2 +\n * design doc §11.2 internal-state-table) but flattened into plain JS Maps/Sets so\n * AI users can iterate without indirection.\n *\n * Lifecycle:\n * - allocated by `world.instantiateScene(handle, parent?)` — the W in\n * `world.allocUniqueRef('SceneInstanceState', state)` returns the u32\n * slot id stored in the SceneInstance.state column;\n * - released by `world.despawn(root)` (the standard `ref<T>` release loop)\n * or explicitly via `world.despawnScene(root)` / `world.despawnDescendants(root)`.\n *\n * AI users typically reach this struct only through the read path\n * `world.get(root, SceneInstance).state.overrides.get(<comp>:<field>)` for\n * inspection; mutation happens through the 8 World methods.\n */\nexport interface SceneInstanceState {\n /**\n * SceneAsset handle the instance was instantiated from. Mirrors the\n * SceneInstance.source column for AI users who already have a\n * SceneInstanceState in hand and want the source handle without a second\n * `world.get` round-trip.\n */\n readonly source: import('@forgeax/engine-types').Handle<'SceneAsset', 'shared'>;\n\n /** Author scene identity used by instance-relative SceneEntityRef resolution. */\n readonly sceneSourceKey?: string;\n\n /** Stable author bindingKey to live Entity mapping for this concrete instance. */\n readonly bindings: Map<string, EntityHandle>;\n\n /**\n * Reverse mapping (live `Entity` -> source `LocalEntityId`). Used by\n * `world.setSceneOverride` to validate the member entity belongs to this\n * instance + by `world.detachSceneMember` / `world.reattachSceneMember`\n * to translate caller-side Entity values back to their authored localId.\n */\n readonly entityToLocalId: Map<EntityHandle, LocalEntityId>;\n\n /**\n * LocalEntityIds of members the AI user marked detached via\n * `world.detachSceneMember(root, member)`. The member entities stay\n * alive in the World; only the bookkeeping marker moves so\n * `world.despawnDescendants(root, { keepDetached: true })` can skip them.\n * Detach is idempotent (set semantics).\n */\n readonly detachedLocalIds: Set<LocalEntityId>;\n\n /**\n * Per-member runtime overrides keyed by `<localId>` -> `<comp>:<field>`\n * -> override record. mount-time overrides (authored on the SceneAsset's\n * `mounts[].overrides`) populate this map at instantiate-time so AI\n * users see them via the same read path as runtime\n * `setSceneOverride` writes (single SSOT).\n */\n readonly overrides: Map<LocalEntityId, Map<string, SceneInstanceOverrideRecord>>;\n\n /**\n * Top-level root entities of the materialised tree (members without a\n * ChildOf parent at instantiate time). The synthetic root entity that\n * carries the SceneInstance component itself is NOT in this list — it is\n * the parent of every member entity (plan-strategy §3.2 sequence step 7).\n */\n readonly rootEntities: EntityHandle[];\n\n /** Synthetic roots of recursively mounted SceneAssets owned by this instance. */\n readonly mountRoots: EntityHandle[];\n\n /**\n * Total slot count `entities.length + sum(mounts[].memberCount)` —\n * captured at instantiate-time so cycle / count consistency checks\n * (e.g. `world.getSceneAssetForInstance(root)` symmetry) can compare\n * against the live SceneInstance.mapping column without re-reading the\n * SceneAsset.\n */\n readonly totalSlots: number;\n\n /**\n * Mount-time override authored on the parent SceneAsset's `mounts[]`\n * record. Captured at instantiate-time so `world.removeSceneOverride`\n * can fall back to the mount-time value before going to the source\n * SceneAsset value (plan-strategy §D-2).\n */\n readonly mountTimeOverrides: readonly MountOverride[];\n}\n\n/**\n * SceneInstance ECS component — synthetic root entity payload for one\n * materialised SceneAsset (instance == entity carrying SceneInstance,\n * charter P4).\n *\n * AI users discover the component via IDE autocomplete on\n * `@forgeax/engine-render` (single-import barrel; AGENTS.md §Components):\n *\n * ```ts\n * import { SceneInstance } from '@forgeax/engine-render';\n * for (const row of world.query({ read: [SceneInstance] }).unwrap()) {\n * console.log(`root=${row.entity} source=${row.get(SceneInstance).source}`);\n * }\n *\n * const inst = world.get(root, SceneInstance).value;\n * const memberEntity = inst.mapping[localId]; // Uint32Array snapshot\n * for (const detached of inst.state.detachedLocalIds) { /* ... *\\/ }\n * ```\n *\n * The component does not register a relationship — synthetic root +\n * members are wired through the standard `ChildOf` (member -> root) so\n * the existing `world.iterDescendants(root)` / Children mirror code paths\n * apply unchanged (plan-strategy §D-5).\n *\n * @example Materialise + inspect a SceneAsset:\n * const { root, diagnostics } = world.instantiateScene(handle).value;\n * const inst = world.get(root, SceneInstance).value;\n * // inst.source === handle, inst.mapping is Uint32Array(totalSlots)\n * // inst.state holds entityToLocalId / detachedLocalIds / overrides /\n * // rootEntities / mountRoots / totalSlots / mountTimeOverrides.\n */\nexport const SceneInstance = defineComponent(\n 'SceneInstance',\n {\n source: { type: 'shared<SceneAsset>' },\n mapping: { type: 'array<entity>' },\n // The unique slot is the ECS storage seam for the instance's structured\n // runtime payload; keep the nested semantic visible to schema consumers.\n state: { type: 'unique<SceneInstanceState>', shape: 'nested' },\n },\n { transient: true },\n);\n","// @forgeax/engine-render - ScreenSpaceReflection authoring component.\n//\n// The component is an opt-in camera effect. It carries only the three\n// bounded authoring values; all graph, resource, history, and backend state\n// remains renderer-owned.\n\nimport { defineComponent, type SchemaOf, type ShapeOf } from '@forgeax/engine-ecs';\n\n/**\n * Schema-derived ScreenSpaceReflection authoring data.\n *\n * The defaults are conservative and are validated against the active camera\n * view range before a spatial candidate is admitted.\n */\nexport const ScreenSpaceReflection = defineComponent('ScreenSpaceReflection', {\n maxDistance: { type: 'f32', default: 40 },\n thickness: { type: 'f32', default: 0.2 },\n maxRoughness: { type: 'f32', default: 0.6 },\n});\n\nexport type ScreenSpaceReflectionData = ShapeOf<SchemaOf<typeof ScreenSpaceReflection>>;\n","// @forgeax/engine-runtime - SkyboxBackground (environment cubemap render background).\n//\n// Schema: 3 fields -- equirect (Handle<EquirectAsset>, u32-stored handle)\n// + mode (f32 enum column, discriminator) + rotation (quaternion xyzw,\n// default identity). Naming convention follows the\n// single-semantic component rule: no Component suffix (AGENTS.md rule #1).\n//\n// feat-20260630-equirect-kind-internalized-ibl-declarative-skyligh M3 / w16:\n// the field is `equirect: shared<EquirectAsset>` (the retired\n// `cubemap: shared<CubeTextureAsset>` is gone). The skybox reuses the same\n// equirect handle as the Skylight; the cubemap projection is internal and\n// driven by the render-system record arm (no user upload call).\n//\n// Plan-strategy D-5: mode is a f32 enum column (ECS columns are POD, no\n// string unions in archetype storage). Consumer-facing type safety is\n// provided by the `SkyboxMode` literal union + `skyboxModeFromF32` mapper\n// (same pattern as cameraProjectionFromF32 in camera.ts:51,105,145,221-237).\n//\n// OOS-1: `mode: 'atmosphere'` implementation is deferred -- the union\n// shape leaves room for additive growth without breaking the f32 enum\n// encoding.\n//\n// AI user minimum spawn (charter P4):\n// world.spawn({ component: SkyboxBackground, data: { equirect, mode: 0 } });\n//\n// Single component activates the skybox render pass transparently when a\n// Skylight + tonemap active camera is present (skybox reuses the same\n// equirect handle as Skylight).\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\n/**\n * Skybox mode literal union (AC-02 narrowing surface).\n * Currently only 'cubemap' -- future 'atmosphere' deferred per OOS-1.\n */\nexport type SkyboxMode = 'cubemap';\n\n/** Numeric encoding of cubemap skybox mode (schema value for `mode`). */\nexport const SKYBOX_MODE_CUBEMAP = 0;\n\n/**\n * Map a `SkyboxBackground.mode` numeric value to the closed `SkyboxMode`\n * string-literal union. Only member currently is 'cubemap'; the exhaustive\n * switch is ready for future mode additions (e.g. 'atmosphere', OOS-1).\n */\nexport function skyboxModeFromF32(value: number): SkyboxMode {\n switch (value) {\n case SKYBOX_MODE_CUBEMAP:\n return 'cubemap';\n // Future: case SKYBOX_MODE_ATMOSPHERE: return 'atmosphere';\n }\n // Unrecognised value: fall back to 'cubemap' (charter P3 -- no silent\n // exception; the fallback preserves rendering on stale numerics while\n // the exhaustive switch shape ensures AI users catch new members at\n // compile time when a mode is added).\n return 'cubemap';\n}\n\n/**\n * SkyboxBackground: full-screen environment cubemap background.\n *\n * Renders a fullscreen triangle that reconstructs world-space view\n * direction from the camera's inverseViewProj matrix (View UBO),\n * samples a cubemap with the view direction, and writes an HDR color\n * to the hdrColor render target (before the main geometry pass).\n *\n * The skybox pass is automatically activated when a SkyboxBackground\n * entity exists, a Skylight entity provides the equirect source, and the\n * active Camera has tonemap active. The skybox reuses the same equirect\n * handle as the Skylight entity -- two independent components sharing the\n * same GPU resource (the internally-projected cubemap).\n *\n * `equirect` is a `Handle<EquirectAsset>` resolved from a vite pack-index\n * GUID via `engine.assets.loadByGuid<EquirectAsset>(guid)`. The cubemap\n * projection is internal and driven by the render-system record arm; there\n * is no user upload call.\n *\n * `mode` is a numeric discriminator column (`'f32'`). Use\n * `SKYBOX_MODE_CUBEMAP` for the cubemap render path.\n *\n * `rotation` is an environment-space quaternion in `[x, y, z, w]` order.\n * It rotates the sampled cubemap without changing the camera or rebaking the\n * source equirectangular asset.\n *\n * @example Minimum spawn (defaults mode=0):\n * // equirectHandle resolved from loadByGuid<EquirectAsset> (same handle as\n * // the Skylight).\n * world.spawn({ component: SkyboxBackground, data: { equirect: equirectHandle } });\n *\n * @example Single handle shared between Skylight (IBL) and SkyboxBackground:\n * const hdrRes = await engine.assets.loadByGuid<EquirectAsset>(guid);\n * if (!hdrRes.ok) throw hdrRes.error;\n * world.spawn({ component: Skylight, data: { equirect: hdrRes.value } });\n * world.spawn({ component: SkyboxBackground, data: { equirect: hdrRes.value } });\n */\nexport const SkyboxBackground = defineComponent('SkyboxBackground', {\n // The GPU skybox projection is render-owned presentation state; restore\n // keeps the portable mode/rotation controls and lets the owner re-resolve\n // the environment asset on the target world.\n equirect: { type: 'shared<EquirectAsset>', simulationTransient: true },\n mode: { type: 'f32', default: SKYBOX_MODE_CUBEMAP },\n rotation: { type: 'array<f32, 4>', default: new Float32Array([0, 0, 0, 1]) },\n});\n","// @forgeax/engine-runtime - Skylight (ambient environment light).\n//\n// Schema: 4 fields -- equirect (Handle<EquirectAsset>, u32-stored handle,\n// OPTIONAL) + color (array<f32,3>, default [1,1,1] = white) + intensity (f32,\n// default 1.0) + rotation (quaternion xyzw, default identity). feat-20260709 M2 collapsed colorR/G/B into one inline\n// array<f32,3> column. Naming convention follows the DirectionalLight / PointLight /\n// SpotLight family: no Component suffix (AGENTS.md rule #1).\n//\n// Plan-strategy D-6: Skylight component schema is registered but no\n// independent ECS system is created. All Skylight processing happens inside\n// RenderSystem's extract/record phases.\n//\n// AI user minimum spawn (AC-13, charter P4):\n// world.spawn({ component: Skylight, data: {} }); // instant white ambient\n//\n// A single Skylight activates ambient lighting transparently. The `equirect`\n// field is OPTIONAL: omit it for a constant solid-color ambient that needs NO\n// async GPU precompute -- the engine binds a 1x1 white irradiance cube, so\n// ambient = color * intensity * albedo is live on the very first frame (this\n// is the fix for the downstream \"scene is black until the async IBL cubemap\n// finishes uploading\" gap). Supply an equirect to upgrade to full image-based\n// lighting (diffuse irradiance + specular prefilter); `color` * `intensity`\n// still scales the IBL result, so both are live dynamic dials either way.\n//\n// feat-20260630-equirect-kind-internalized-ibl-declarative-skyligh M3 / w16:\n// the field is `equirect: shared<EquirectAsset>` (the retired\n// `cubemap: shared<CubeTextureAsset>` is gone). AI users declare the equirect\n// source directly; the render-system record arm projects the cubemap + IBL\n// chain internally and lazily (no user upload call) -- there is no\n// uploadCubemapFromEquirect on the public surface.\n//\n// Edge cases handled by w18 / w19:\n// - Multi-Skylight: first archetype hit wins, console.warn in dev+prod\n// - intensity=0: ambient term = 0, mathematically valid, no warn\n// - No equirect: solid-color ambient via the white fallback cube (no async)\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\n/**\n * Skylight ambient environment light.\n *\n * A single Skylight entity provides ambient lighting for all StandardMaterial\n * surfaces. When Atmosphere is selected and equirect is omitted, the same sky\n * cube supplies diffuse and roughness-filtered specular IBL. Color/intensity\n * still scale the result; without Atmosphere the solid-color behavior applies.\n * Two authored inputs share one component:\n *\n * - **Solid-color ambient (no equirect).** Omit `equirect` for a constant\n * ambient = `color` * `intensity` applied immediately, with no async GPU\n * precompute. The engine samples a built-in 1x1 white irradiance cube, so a\n * freshly-loaded scene is lit on its first frame instead of being black\n * until an IBL upload finishes.\n * - **Image-based lighting (with equirect).** Supply `equirect` to upgrade to\n * diffuse irradiance + specular prefilter IBL. The engine runs the full\n * precompute (equirect->cubemap, irradiance convolution, prefilter mip\n * chain, BRDF LUT) transparently inside the render-system record arm;\n * `color` * `intensity` then scale the IBL ambient.\n *\n * `equirect` is an OPTIONAL `Handle<EquirectAsset>` resolved from a vite\n * pack-index GUID via `engine.assets.loadByGuid<EquirectAsset>(guid)`. The\n * cubemap projection is internal and idempotent: the same equirect source\n * always resolves to the same GPU cubemap (no user upload call).\n *\n * `color` is the linear-space ambient tint (default white [1, 1, 1]).\n * `intensity` is a linear multiplier (default 1.0; 0 disables ambient). Both\n * are read every frame, so they are live dynamic dials.\n *\n * `rotation` is an environment-space quaternion in `[x, y, z, w]` order.\n * The default identity quaternion leaves the source orientation unchanged;\n * changing it rotates the IBL at sample time without rebaking the source.\n *\n * @example Instant white ambient (no asset, no async):\n * world.spawn({ component: Skylight, data: {} });\n *\n * @example Dim warm ambient:\n * world.spawn({ component: Skylight, data: { color: [1, 0.9, 0.8], intensity: 0.3 } }); // color is [r, g, b]\n *\n * @example Full IBL from an HDR equirect (declarative -- no upload call):\n * // 1. resolve GUID from vite pack-index (see forgeax-engine-vite-plugin-pack)\n * import { AssetGuid } from '@forgeax/engine-pack/guid';\n * const guidRes = AssetGuid.parse('019e4a26-3c29-7420-af5d-20f2724a16b0');\n * if (!guidRes.ok) throw guidRes.error;\n * // 2. load the HDR equirect via the GUID-addressed pack route\n * const hdrRes = await engine.assets.loadByGuid<EquirectAsset>(guidRes.value);\n * if (!hdrRes.ok) throw hdrRes.error;\n * // 3. spawn the Skylight — the equirect handle activates the full IBL path;\n * // the cubemap + IBL precompute happen lazily inside the record arm.\n * world.spawn({ component: Skylight, data: { equirect: hdrRes.value } });\n */\nexport const Skylight = defineComponent('Skylight', {\n // The GPU equirect-to-cubemap projection is render-owned presentation\n // state. Record/restore preserves the portable lighting controls while the\n // render owner resolves this asset again on the target world.\n equirect: { type: 'shared<EquirectAsset>', simulationTransient: true },\n // color carries an explicit layer-2 default [1,1,1] (white); the array\n // layer-3 fallback is all-zero, so the default MUST be explicit (D-5).\n color: { type: 'array<f32, 3>', default: new Float32Array([1, 1, 1]) },\n intensity: { type: 'f32', default: 1.0 },\n rotation: { type: 'array<f32, 4>', default: new Float32Array([0, 0, 0, 1]) },\n});\n","// @forgeax/engine-render - SortKey (per-entity transparent sort override, f32).\n//\n// Schema: 1 f32 column (value). Entity-level sort override consumed by\n// `transparent-sort.ts` (M-3 w23): when present, SortKey.value REPLACES\n// the mode-formula result for this entity in the (layer, sortValue)\n// composite ordering. Override priority is higher than every\n// TransparentSortConfig mode computation (horizontal-z / Y-sort /\n// Y-Z-blend) so AI users can pin a single entity above / below the\n// procedural ordering without reshaping the entire scene.\n//\n// Like Layer, SortKey is a generic ECS renderer component — NOT a\n// 2D-only special. 3D entities may also carry SortKey to bias their\n// position inside the transparent bucket (charter P4 consistent\n// abstraction: same component drives both pipelines).\n//\n// AC-19 derivation audit row (4) names this file as the\n// `defineComponent` factory derivation. JSDoc surfaces the override\n// priority via @derives (ECS factory) annotation; the consumer side\n// of the override behaviour is implemented + verified in M-3 w16 +\n// w23, not here.\n//\n// @derives defineComponent factory (packages/ecs/src/component.ts) —\n// f32 is a legacy scalar type; its intrinsic properties (byteSize / viewCtor\n// / storage) live in TYPE_METADATA['f32'] (feat-20260602 M1).\n//\n// charter mapping: F1 (single-import barrel - joins Layer / Transform\n// / MeshFilter / MeshRenderer / Camera / DirectionalLight) +\n// P3 (explicit default 0.0 surfaces via the 4-layer fallback chain) +\n// P4 (consistent abstraction — generic render component, not 2D-only).\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\n/**\n * Per-entity transparent-sort override.\n *\n * When attached to an entity inside the transparent bucket (M-3 w22),\n * `SortKey.value` REPLACES the result of `TransparentSortConfig.mode`\n * formula evaluation for this entity. Sort key range is the host's\n * choice — typical use is small (e.g. -10 ... +10) to keep the\n * composite (layer asc, sortValue asc) ordering predictable; large\n * magnitudes work but cross-layer biasing should usually go through\n * `Layer` instead.\n *\n * Override priority (M-3 w23 transparent-sort algorithm):\n *\n * if (world.has(entity, SortKey)) {\n * sortValue = world.get(entity, SortKey).value;\n * } else {\n * sortValue = modeFormula(mode, transform, sprite);\n * }\n *\n * SortKey lives alongside Layer in the (layer, sortValue) composite\n * key — Layer remains the primary key, SortKey replaces the secondary\n * key. This means a `Layer { value: 100 }` foreground entity with\n * `SortKey { value: -99 }` still draws AFTER a `Layer { value: 0 }`\n * background entity; SortKey biases WITHIN a layer, not ACROSS layers.\n *\n * @example Minimal spawn (no override, use mode formula):\n * world.spawn({ component: SortKey, data: {} }); // yields value=0\n *\n * @example Bias one sprite above the JRPG Y-sort formula:\n * world.spawn(\n * { component: Transform, data: { pos: [0, 1, 0],\n * quat: [0, 0, 0, 1], scale: [1, 1, 1] } },\n * { component: Layer, data: { value: 0 } },\n * { component: SortKey, data: { value: -100 } },\n * );\n *\n * @example Spawn payload omitting SortKey — the 4-layer fallback fills 0:\n * // entity reads back SortKey only if explicitly attached;\n * // otherwise the mode-formula path is taken by transparent-sort.ts.\n */\nexport const SortKey = defineComponent('SortKey', {\n value: { type: 'f32', default: 0 },\n});\n","// @forgeax/engine-render - SpotLight (cone-restricted spot-light parameters).\n//\n// Schema: direction array<f32,3> + color array<f32,3> + intensity + range +\n// innerConeDeg + outerConeDeg (feat-20260709 M2: direction/color collapsed from\n// 6 per-axis scalar columns to two inline array<f32,3> columns). `position`\n// comes from the\n// Transform component; SpotLight requires a companion Transform on the same\n// entity (ECS query: `[Transform, SpotLight]`). Cone units are degrees on\n// the Component API surface (charter F1 prior-knowledge alignment with\n// Three.js); the host-side extract step pre-converts to `cosInner` /\n// `cosOuter` before GPU upload (plan-strategy section 8.2 naming convention\n// + D-3 host-side cone conversion).\n//\n// `range` units are meters; defaults to `10.0`. Runtime finite-range\n// attenuation is the Three r184 squared window; the KHR unsquared curve is an\n// import/reference boundary only. The cone falloff is layered on top with\n// `smoothstep(cosOuter, cosInner, dot(L, -direction))` (plan-strategy D-S4).\n//\n// 0 light + standard material -> physically correct black render. The\n// once-warn channel collapses to \"directionalCount + pointCount +\n// spotCount === 0\" (M5 / w25).\n//\n// feat-20260625-spot-light-shadow-mapping M1 w4: embedded castShadow (default true)\n// + 7 shadow fields (mapSize / depthBias / normalBias / nearPlane / farPlane /\n// pcfKernelSize / shadowIntensity) aligned with DirectionalLight vocabulary (plan-strategy D-6;\n// charter P4 consistent abstraction). Zero-config spawns cast spot shadows;\n// set castShadow:false to opt out (validate short-circuits on false, AC-03).\n// Shadow atlas cap of 4 is enforced at extract stage, not component layer (OOS-5).\n//\n// charter mapping: proposition 1 (single import + IDE autocomplete on\n// payload.outerConeDeg with no `as` cast) + proposition 3 (silent failure\n// -> explicit failure; spawn-time fail-fast on three bound violations) +\n// proposition 5 (consistent abstraction: outgoing direction semantics\n// shared with DirectionalLight; cone deg API + cos shader uniform\n// pre-conversion mirrors directional path's host-side `lightDir x intensity`\n// pre-multiplication).\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\nexport interface SpotLightProjector {\n readonly guid: string;\n readonly generation: number;\n readonly revision: number;\n}\n\nexport interface SpotLightAuthoring {\n /** Optional GUID-backed TextureAsset projector; absent keeps the normal spot path. */\n readonly projector?: SpotLightProjector;\n}\n\n/**\n * Cone-restricted spot light (KHR_lights_punctual `spot` type). Casts shadows\n * by default (castShadow defaults to true) — zero-config spawns project hard\n * PCF shadows through an independent spot depth atlas.\n *\n * `direction` @semantics outgoing -- points FROM light source TO the\n * scene (consistent with `DirectionalLight`; the shader internally negates\n * this vector to obtain the L vector for BRDF evaluation:\n * `let l = normalize(-light.direction)`). Extract owns the single\n * normalization step for the snapshot; URP and HDRP consume that normalized\n * value without re-normalizing. `position` source: the companion\n * `Transform` component on the same entity.\n *\n * `innerConeDeg` is the half-angle of the saturated bright region (cone\n * fully bright at the axis); `outerConeDeg` is the half-angle of the\n * falloff edge (cone fully dark beyond). Unit is **degrees**;\n * `outerConeDeg in (innerConeDeg, 90]` (KHR upper bound; spawn-time\n * validation rejects `outer > 90` and `outer <= inner`). The host-side\n * extract step converts both to `cos*` before GPU upload so the shader\n * only sees pre-computed cosines (plan-strategy D-S2 byte freeze; charter\n * P4 host pre-multiplication parity).\n *\n * `color` is linear-space rgb in `[0, 1]` per channel; `intensity` is candela;\n * `range` is in meters and defaults to `10.0`. Exposure is a camera output\n * operation and does not change the stored intensity.\n *\n * Shadow fields (embedded, aligned with DirectionalLight):\n * castShadow ∈ {true, false} — shadow opt-out gate (default true)\n * mapSize >= 1 — shadow map resolution per tile (default 2048)\n * depthBias — shadow acne bias (default 0.005)\n * normalBias — shadow acne normal offset (default 0.05)\n * nearPlane — shadow-camera near (default 0.1)\n * farPlane — shadow-camera far (default 50)\n * pcfKernelSize odd >= 1 — PCF kernel width (default 3)\n * shadowIntensity in [0,1] — residual light in shadow (default 1)\n *\n * Atlas capacity is capped at 4 castShadow spot lights by the extract stage;\n * the 5th light onward keeps direct illumination but shadowAtlasTile = -1\n * (AC-05: clip is programmatically detectable, light stays visible).\n *\n * @example Spawn a single spot light casting shadows (zero-config):\n * world.spawn(\n * { component: Transform, data: { pos: [0, 5, 0] } },\n * { component: SpotLight, data: { direction: [0, -1, 0] } }, // [x, y, z]\n * );\n *\n * @example Opt out of shadows:\n * world.spawn(\n * { component: Transform, data: { pos: [0, 5, 0] } },\n * { component: SpotLight, data: { direction: [0, -1, 0], castShadow: false } },\n * );\n *\n * @example Explicit shadow config:\n * world.spawn(\n * { component: Transform, data: { pos: [0, 5, 0] } },\n * { component: SpotLight, data: { direction: [0, -1, 0], depthBias: 0.01, normalBias: 0.08, mapSize: 1024 } },\n * );\n *\n * @example Minimal spawn -- defaults give neutral white at full strength, range 10m, KHR pi/4 cone:\n * world.spawn(\n * { component: Transform, data: { pos: [0, 5, 0] } },\n * { component: SpotLight, data: { direction: [0, -1, 0] } }, // [x, y, z]\n * );\n * // resolves to color=[1,1,1], intensity=1, range=10.0,\n * // innerConeDeg=0, outerConeDeg=45 (KHR pi/4 equivalent).\n */\nexport const SpotLight = defineComponent('SpotLight', {\n // direction has no default (D-5): omitting it lands the array layer-3\n // all-zero, which validate() rejects. color carries an explicit layer-2\n // default [1,1,1] (white); the array layer-3 fallback is all-zero.\n direction: { type: 'array<f32, 3>' },\n color: { type: 'array<f32, 3>', default: new Float32Array([1, 1, 1]) },\n intensity: { type: 'f32', default: 1 },\n range: { type: 'f32', default: 10.0 },\n innerConeDeg: { type: 'f32', default: 0 },\n outerConeDeg: { type: 'f32', default: 45 },\n iesProfile: { type: 'shared<IesProfileAsset>' },\n cookie: { type: 'shared<TextureAsset>' },\n rollDeg: { type: 'f32', default: 0 },\n // Shadow opt-out gate: defaults to true so zero-config spawns cast shadows.\n castShadow: { type: 'bool', default: true },\n // 7 shadow fields aligned with the shared light shadow vocabulary.\n mapSize: { type: 'f32', default: 2048 },\n depthBias: { type: 'f32', default: 0.005 },\n normalBias: { type: 'f32', default: 0.05 },\n nearPlane: { type: 'f32', default: 0.1 },\n farPlane: { type: 'f32', default: 50 },\n pcfKernelSize: { type: 'f32', default: 3 },\n // Three's SpotLight.shadow.intensity is the fraction of visibility applied\n // to a shadowed contribution. Keep it in the author-facing [0,1] domain;\n // extract/record transport this one fact to surface and volume consumers.\n shadowIntensity: { type: 'f32', default: 1 },\n // Shared TextureAsset identity; publication and residency remain owned by\n // the existing asset and GPU resource owners.\n projector: { type: 'shared<TextureAsset>', simulationTransient: true },\n});\n","import { defineComponent } from '@forgeax/engine-ecs';\n\n/** Numeric labels stored by the public Visibility enum field. */\nexport const VisibilityStateValue = Object.freeze({\n inherited: 0,\n hidden: 1,\n visible: 2,\n} as const);\n\n/** Author visibility intent accepted by the Visibility component. */\nexport type VisibilityState = keyof typeof VisibilityStateValue;\n\n/**\n * Decode the stored u32 without treating an unknown value as a valid state.\n * Invalid values are rejected at ECS write boundaries; undefined remains an\n * explicit signal for readers that inspect externally corrupted columns.\n */\nexport function visibilityStateFromU32(value: number): VisibilityState | undefined {\n switch (value) {\n case VisibilityStateValue.inherited:\n return 'inherited';\n case VisibilityStateValue.hidden:\n return 'hidden';\n case VisibilityStateValue.visible:\n return 'visible';\n default:\n return undefined;\n }\n}\n\n/**\n * Author intent for render participation. Omitted state is inherited and is\n * therefore visible when no valid parent intent is available.\n */\nexport const Visibility = defineComponent(\n 'Visibility',\n {\n state: {\n type: 'enum',\n default: VisibilityStateValue.inherited,\n labels: VisibilityStateValue,\n },\n },\n {\n meta: {\n quickStart: 'Attach Visibility to author render participation intent.',\n diagnostics: 'Compare the ECS state with resolveVisibility and renderer.visibilityStats.',\n recovery: 'Use structured ECS write errors and repair the owning scene relation.',\n boundaries:\n 'Visibility does not own camera, picking, lifecycle, assets, or VFX shadow policy.',\n },\n },\n);\n","import { err, ok, type Result } from '@forgeax/engine-types';\nimport {\n type BarrelDistortionData,\n validateBarrelDistortionParameters,\n} from './components/barrel-distortion';\nimport { BarrelDistortionInvalidParameterError } from './errors/render';\n\n/** One immutable mapping used by the output pass and display interaction. */\nexport interface BarrelDistortionMapping {\n readonly width: number;\n readonly height: number;\n readonly aspect: number;\n readonly strength: number;\n readonly centerX: number;\n readonly centerY: number;\n readonly radiusSquared: number;\n /** Unjittered camera facts from the submitted frame, when available. */\n readonly camera?: BarrelDistortionCameraFrame;\n}\n\n/** Camera matrices paired with the mapping's accepted render frame. */\nexport interface BarrelDistortionCameraFrame {\n readonly projection: 'perspective' | 'orthographic';\n /** Far plane from the same submitted camera snapshot as the matrices. */\n readonly far: number;\n readonly viewMatrix: ArrayLike<number>;\n readonly projectionMatrix: ArrayLike<number>;\n}\n\n// The equations below are evaluated in JavaScript's binary64 domain. Keep the\n// public input domain strict, then absorb only a handful of binary64 ulps at\n// the computed UV boundary. A real crop miss is orders of magnitude larger\n// and remains rejected.\nconst COMPUTED_UV_BOUNDARY_EPSILON = Number.EPSILON * 16;\n\n/**\n * Detach and deep-freeze a mapping before it crosses a public or realm\n * boundary. Worker structured cloning drops the source object's frozen state,\n * so every receiving boundary must call this helper again.\n */\nexport function freezeBarrelDistortionMapping(\n mapping: BarrelDistortionMapping,\n): BarrelDistortionMapping {\n const camera = mapping.camera;\n return Object.freeze({\n ...mapping,\n ...(camera === undefined\n ? {}\n : {\n camera: Object.freeze({\n projection: camera.projection,\n far: camera.far,\n viewMatrix: Object.freeze(Array.from(camera.viewMatrix)),\n projectionMatrix: Object.freeze(Array.from(camera.projectionMatrix)),\n }),\n }),\n });\n}\n\n/** Attach the unjittered camera facts at the queue-submit publication boundary. */\nexport function attachBarrelDistortionCameraFrame(\n mapping: BarrelDistortionMapping,\n camera: BarrelDistortionCameraFrame,\n): BarrelDistortionMapping {\n return freezeBarrelDistortionMapping({\n ...mapping,\n camera: {\n projection: camera.projection,\n far: camera.far,\n viewMatrix: camera.viewMatrix,\n projectionMatrix: camera.projectionMatrix,\n },\n });\n}\n\n/** Continuous output-viewport pixel coordinate. */\nexport interface DisplayPoint {\n x: number;\n y: number;\n}\n\nfunction invalidExtent(\n field: 'width' | 'height',\n value: number,\n): BarrelDistortionInvalidParameterError {\n return new BarrelDistortionInvalidParameterError({\n field,\n value,\n expected: 'finite and greater than 0',\n });\n}\n\n/** Derive the output-sized mapping, including the auto-crop normalization. */\nexport function createBarrelDistortionMapping(\n width: number,\n height: number,\n input: Partial<BarrelDistortionData> | undefined,\n): Result<BarrelDistortionMapping, BarrelDistortionInvalidParameterError> {\n if (!Number.isFinite(width) || width <= 0) return err(invalidExtent('width', width));\n if (!Number.isFinite(height) || height <= 0) return err(invalidExtent('height', height));\n const parameters = validateBarrelDistortionParameters(input);\n if (!parameters.ok) return parameters;\n const { strength, centerX, centerY } = parameters.value;\n const aspect = width / height;\n const radiusSquared =\n 4 *\n (aspect * aspect * Math.max(centerX, 1 - centerX) ** 2 + Math.max(centerY, 1 - centerY) ** 2);\n return ok(\n Object.freeze({\n width,\n height,\n aspect,\n strength,\n centerX,\n centerY,\n radiusSquared,\n }),\n );\n}\n\nfunction displayToSceneScale(mapping: BarrelDistortionMapping, ux: number, uy: number): number {\n const px = 2 * mapping.aspect * (ux - mapping.centerX);\n const py = 2 * (uy - mapping.centerY);\n const t = (px * px + py * py) / mapping.radiusSquared;\n return (1 - mapping.strength) / (1 - mapping.strength * t);\n}\n\n/**\n * Accept a computed UV only when it is inside the unit interval or within a\n * machine-precision boundary. Inputs are checked before the equation runs;\n * this helper must never turn an out-of-domain caller input into a valid UV.\n */\nfunction normalizeComputedUv(out: DisplayPoint, x: number, y: number): boolean {\n if (!Number.isFinite(x) || !Number.isFinite(y)) return false;\n if (\n x < -COMPUTED_UV_BOUNDARY_EPSILON ||\n x > 1 + COMPUTED_UV_BOUNDARY_EPSILON ||\n y < -COMPUTED_UV_BOUNDARY_EPSILON ||\n y > 1 + COMPUTED_UV_BOUNDARY_EPSILON\n ) {\n return false;\n }\n out.x = Math.min(1, Math.max(0, x));\n out.y = Math.min(1, Math.max(0, y));\n return true;\n}\n\n/** Shared display UV -> source UV equation used by the GPU and CPU paths. */\nexport function mapDisplayUvToSceneUv(\n out: DisplayPoint,\n mapping: BarrelDistortionMapping,\n ux: number,\n uy: number,\n): boolean {\n if (!Number.isFinite(ux) || !Number.isFinite(uy) || ux < 0 || ux > 1 || uy < 0 || uy > 1)\n return false;\n if (mapping.strength === 0) {\n out.x = ux;\n out.y = uy;\n return ux >= 0 && ux <= 1 && uy >= 0 && uy <= 1;\n }\n const scale = displayToSceneScale(mapping, ux, uy);\n return normalizeComputedUv(\n out,\n mapping.centerX + (ux - mapping.centerX) * scale,\n mapping.centerY + (uy - mapping.centerY) * scale,\n );\n}\n\n/** Analytic source UV -> display UV inverse of the shared barrel model. */\nexport function mapSceneUvToDisplayUv(\n out: DisplayPoint,\n mapping: BarrelDistortionMapping,\n ux: number,\n uy: number,\n): boolean {\n if (!Number.isFinite(ux) || !Number.isFinite(uy) || ux < 0 || ux > 1 || uy < 0 || uy > 1)\n return false;\n if (mapping.strength === 0) {\n out.x = ux;\n out.y = uy;\n return ux >= 0 && ux <= 1 && uy >= 0 && uy <= 1;\n }\n const px = 2 * mapping.aspect * (ux - mapping.centerX);\n const py = 2 * (uy - mapping.centerY);\n const sourceRadius = Math.hypot(px, py);\n if (sourceRadius === 0) {\n out.x = mapping.centerX;\n out.y = mapping.centerY;\n return true;\n }\n const discriminant =\n (1 - mapping.strength) ** 2 +\n (4 * mapping.strength * sourceRadius * sourceRadius) / mapping.radiusSquared;\n const displayRadius =\n (2 * sourceRadius) / (1 - mapping.strength + Math.sqrt(Math.max(0, discriminant)));\n const scale = displayRadius / sourceRadius;\n return normalizeComputedUv(\n out,\n mapping.centerX + (ux - mapping.centerX) * scale,\n mapping.centerY + (uy - mapping.centerY) * scale,\n );\n}\n\nfunction validPixel(point: DisplayPoint): boolean {\n return Number.isFinite(point.x) && Number.isFinite(point.y);\n}\n\n/** Map an output display pixel to the unwarped scene pixel. */\nexport function mapDisplayToScene(\n out: DisplayPoint,\n mapping: BarrelDistortionMapping,\n displayX: number,\n displayY: number,\n): boolean {\n if (!Number.isFinite(displayX) || !Number.isFinite(displayY)) return false;\n if (displayX < 0 || displayX > mapping.width || displayY < 0 || displayY > mapping.height) {\n return false;\n }\n const scene = { x: 0, y: 0 };\n if (!mapDisplayUvToSceneUv(scene, mapping, displayX / mapping.width, displayY / mapping.height)) {\n return false;\n }\n out.x = scene.x * mapping.width;\n out.y = scene.y * mapping.height;\n return validPixel(out);\n}\n\n/** Map an unwarped scene pixel to its visible output display pixel. */\nexport function mapSceneToDisplay(\n out: DisplayPoint,\n mapping: BarrelDistortionMapping,\n sceneX: number,\n sceneY: number,\n): boolean {\n if (!Number.isFinite(sceneX) || !Number.isFinite(sceneY)) return false;\n if (sceneX < 0 || sceneX > mapping.width || sceneY < 0 || sceneY > mapping.height) {\n return false;\n }\n const display = { x: 0, y: 0 };\n if (!mapSceneUvToDisplayUv(display, mapping, sceneX / mapping.width, sceneY / mapping.height)) {\n return false;\n }\n out.x = display.x * mapping.width;\n out.y = display.y * mapping.height;\n return validPixel(out);\n}\n","/** Closed errors produced by the CloudLayer authoring and resource route. */\n\nexport interface CloudLayerInvalidParameterDetail {\n readonly field: string;\n readonly value: unknown;\n readonly expected: string;\n}\n\nexport class CloudLayerInvalidParameterError extends Error {\n readonly code = 'cloud-layer-invalid-parameter' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: CloudLayerInvalidParameterDetail;\n\n constructor(field: string, value: unknown, expected: string) {\n super(`CloudLayer.${field} is invalid`);\n this.name = 'CloudLayerInvalidParameterError';\n this.expected = `CloudLayer.${field} must be ${expected}`;\n this.hint = `set CloudLayer.${field} to ${expected}`;\n this.detail = { field, value, expected };\n }\n}\n\nexport interface CloudLayerOwnerConflictDetail {\n readonly count: number;\n}\n\nexport class CloudLayerOwnerConflictError extends Error {\n readonly code = 'cloud-layer-owner-conflict' as const;\n readonly expected = 'at most one CloudLayer owns a World frame';\n readonly hint = 'remove additional CloudLayer owners before extraction';\n readonly detail: CloudLayerOwnerConflictDetail;\n\n constructor(count: number) {\n super(`CloudLayer owner cardinality is ${count}`);\n this.name = 'CloudLayerOwnerConflictError';\n this.detail = { count };\n }\n}\n\nexport interface CloudLayerCacheInvalidDetail {\n readonly sourceKey: string;\n readonly reason: string;\n}\n\nexport class CloudLayerCacheInvalidError extends Error {\n readonly code = 'cloud-layer-cache-invalid' as const;\n readonly expected = 'the density cache payload matches its reconstructible source';\n readonly hint = 'discard the derived cache and rebuild it from CloudLayer source facts';\n readonly detail: CloudLayerCacheInvalidDetail;\n\n constructor(sourceKey: string, reason: string) {\n super(`CloudLayer cache is invalid: ${reason}`);\n this.name = 'CloudLayerCacheInvalidError';\n this.detail = { sourceKey, reason };\n }\n}\n\nexport interface CloudLayerCapabilityMissingDetail {\n readonly capability: string;\n}\n\nexport class CloudLayerCapabilityMissingError extends Error {\n readonly code = 'cloud-layer-capability-missing' as const;\n readonly expected = 'the selected backend exposes the capability required by the cloud lane';\n readonly hint =\n 'inspect the capability report, disable the cloud lane on this backend, or retry on a backend with the required capability';\n readonly detail: CloudLayerCapabilityMissingDetail;\n\n constructor(capability: string) {\n super(`CloudLayer capability is unavailable: ${capability}`);\n this.name = 'CloudLayerCapabilityMissingError';\n this.detail = { capability };\n }\n}\n\nexport interface CloudLayerResourceFailureDetail {\n readonly stage: 'cache' | 'shadow' | 'view' | 'history' | 'retire';\n readonly generation: number;\n readonly cause?: unknown;\n}\n\nexport class CloudLayerResourceFailureError extends Error {\n readonly code = 'cloud-layer-resource-failed' as const;\n readonly expected = 'cloud resources are created, submitted and retired as one generation';\n readonly hint = 'keep the last-known-good cloud generation and retry after recovery';\n readonly detail: CloudLayerResourceFailureDetail;\n\n constructor(detail: CloudLayerResourceFailureDetail) {\n super(`CloudLayer ${detail.stage} resource failed at generation ${detail.generation}`);\n this.name = 'CloudLayerResourceFailureError';\n this.detail = detail;\n }\n}\n\nexport type CloudLayerError =\n | CloudLayerInvalidParameterError\n | CloudLayerOwnerConflictError\n | CloudLayerCacheInvalidError\n | CloudLayerCapabilityMissingError\n | CloudLayerResourceFailureError;\n\nexport type CloudLayerErrorCode = CloudLayerError['code'];\n","import { err, ok, type Result } from '@forgeax/engine-types';\nimport {\n type CloudLayerData,\n type CloudQuality,\n CloudQualityValue,\n cloudQualityFromF32,\n} from '../components/cloud-layer';\nimport { type CloudLayerError, CloudLayerInvalidParameterError } from '../errors/cloud';\n\nexport interface CloudLayerAuthoring {\n readonly seed?: number;\n readonly baseHeight?: number;\n readonly thickness?: number;\n readonly scale?: number;\n readonly coverage?: number;\n readonly density?: number;\n readonly wind?: ArrayLike<number>;\n readonly quality?: CloudQuality | number;\n readonly shadowRange?: number;\n}\n\nexport interface ValidatedCloudLayer {\n readonly seed: number;\n readonly baseHeight: number;\n readonly thickness: number;\n readonly scale: number;\n readonly coverage: number;\n readonly density: number;\n readonly wind: readonly [number, number, number];\n readonly quality: CloudQuality;\n readonly shadowRange: number;\n}\n\nexport interface CloudQualityProfile {\n readonly cacheResolution: number;\n readonly viewSteps: number;\n readonly shadowSteps: number;\n readonly historyWeight: number;\n /** Renderer-owned sky trace domain in world units; independent of Camera.far. */\n readonly viewDistance: number;\n}\n\n/**\n * Quality values are bounded in one place. The values are deliberately\n * renderer policy, while the component stores only the closed quality code.\n */\nexport const CLOUD_QUALITY_PROFILES: Readonly<Record<CloudQuality, CloudQualityProfile>> =\n Object.freeze({\n low: Object.freeze({\n // Preserve low-profile ray counts while keeping separate puffs from\n // collapsing into one bilinear cache smear.\n cacheResolution: 32,\n viewSteps: 40,\n shadowSteps: 12,\n historyWeight: 0.82,\n viewDistance: 1600,\n }),\n medium: Object.freeze({\n cacheResolution: 40,\n viewSteps: 64,\n shadowSteps: 20,\n historyWeight: 0.9,\n viewDistance: 2400,\n }),\n high: Object.freeze({\n cacheResolution: 64,\n viewSteps: 64,\n shadowSteps: 32,\n historyWeight: 0.94,\n viewDistance: 4000,\n }),\n });\n\n/**\n * The spatial cloud-shadow map is intentionally derived from the same quality\n * profile everywhere: graph allocation, light-space projection and inspection\n * must agree on one texel grid. Keep the multiplier here rather than letting\n * each owner invent a resolution.\n */\nexport function cloudShadowResolutionForQuality(qualityValue: CloudQuality): number {\n return CLOUD_QUALITY_PROFILES[qualityValue].cacheResolution * 4;\n}\n\n/**\n * Cloud visibility is a sky-domain concern. It must not inherit the opaque\n * geometry far plane or the finite receiver-shadow footprint: either value is\n * commonly much shorter than a ground-view cloud trace and would turn the\n * distant layer into a flat wall.\n */\nexport function cloudViewDistanceForQuality(qualityValue: CloudQuality): number {\n return CLOUD_QUALITY_PROFILES[qualityValue].viewDistance;\n}\n\n/** rgba16float is four 16-bit channels (8 bytes per texel). */\nexport const CLOUD_SHADOW_BYTES_PER_TEXEL = 8;\n\n/**\n * Authored density is a normalized formation value. Convert it to a bounded\n * per-world-unit extinction coefficient only at integration time; otherwise a\n * long horizon step would become opaque after its first sample and expose\n * marching bands instead of a participating volume.\n */\nexport const CLOUD_EXTINCTION_COEFFICIENT = 0.03;\n\nexport const DEFAULT_CLOUD_LAYER: ValidatedCloudLayer = Object.freeze({\n seed: 1337,\n baseHeight: 120,\n thickness: 80,\n scale: 0.004,\n coverage: 0.48,\n density: 1,\n wind: Object.freeze([8, 0, 2] as [number, number, number]),\n quality: 'medium',\n shadowRange: 512,\n});\n\nfunction invalid(field: string, value: unknown, expected: string): Result<never, CloudLayerError> {\n return err(new CloudLayerInvalidParameterError(field, value, expected));\n}\n\nfunction finiteRange(\n field: string,\n value: unknown,\n min: number,\n max = Number.POSITIVE_INFINITY,\n): Result<number, CloudLayerError> {\n if (typeof value !== 'number' || !Number.isFinite(value) || value < min || value > max) {\n const expected = Number.isFinite(max)\n ? `finite and in [${min}, ${max}]`\n : `finite and >= ${min}`;\n return invalid(field, value, expected);\n }\n return ok(value);\n}\n\nfunction quality(value: unknown): Result<CloudQuality, CloudLayerError> {\n if (typeof value === 'string' && (value === 'low' || value === 'medium' || value === 'high')) {\n return ok(value);\n }\n if (typeof value === 'number') {\n const resolved = cloudQualityFromF32(value);\n if (resolved !== undefined) return ok(resolved);\n }\n return invalid(\n 'quality',\n value,\n `one of low, medium, high (codes ${CloudQualityValue.low}, ${CloudQualityValue.medium}, ${CloudQualityValue.high})`,\n );\n}\n\nfunction wind(value: unknown): Result<readonly [number, number, number], CloudLayerError> {\n if (value === undefined || value === null || typeof value !== 'object') {\n return invalid('wind', value, 'three finite world-space components');\n }\n const source = value as ArrayLike<number>;\n if (source.length !== 3) return invalid('wind', value, 'three finite world-space components');\n const result: [number, number, number] = [\n source[0] ?? Number.NaN,\n source[1] ?? Number.NaN,\n source[2] ?? Number.NaN,\n ];\n if (result.some((entry) => !Number.isFinite(entry) || Math.abs(entry) > 1000)) {\n return invalid('wind', value, 'three finite components in [-1000, 1000]');\n }\n return ok(Object.freeze(result));\n}\n\n/** Validate one detached CloudLayer POD before deriving cache or graph state. */\nexport function validateCloudLayer(\n input: CloudLayerAuthoring | Partial<CloudLayerData> | undefined,\n): Result<ValidatedCloudLayer, CloudLayerError> {\n const value = input ?? {};\n const seed = value.seed ?? DEFAULT_CLOUD_LAYER.seed;\n if (typeof seed !== 'number' || !Number.isInteger(seed) || seed < 0 || seed > 0xffffffff) {\n return invalid('seed', seed, 'an integer in [0, 4294967295]');\n }\n const baseHeight = finiteRange(\n 'baseHeight',\n value.baseHeight ?? DEFAULT_CLOUD_LAYER.baseHeight,\n -100000,\n 1000000,\n );\n if (!baseHeight.ok) return baseHeight;\n const thickness = finiteRange(\n 'thickness',\n value.thickness ?? DEFAULT_CLOUD_LAYER.thickness,\n 0.001,\n 1000000,\n );\n if (!thickness.ok) return thickness;\n const scale = finiteRange('scale', value.scale ?? DEFAULT_CLOUD_LAYER.scale, 0.000001, 10);\n if (!scale.ok) return scale;\n const coverage = finiteRange('coverage', value.coverage ?? DEFAULT_CLOUD_LAYER.coverage, 0, 1);\n if (!coverage.ok) return coverage;\n const density = finiteRange('density', value.density ?? DEFAULT_CLOUD_LAYER.density, 0, 32);\n if (!density.ok) return density;\n const resolvedWind = wind(value.wind ?? DEFAULT_CLOUD_LAYER.wind);\n if (!resolvedWind.ok) return resolvedWind;\n const resolvedQuality = quality(value.quality ?? DEFAULT_CLOUD_LAYER.quality);\n if (!resolvedQuality.ok) return resolvedQuality;\n const shadowRange = finiteRange(\n 'shadowRange',\n value.shadowRange ?? DEFAULT_CLOUD_LAYER.shadowRange,\n 0.001,\n 10000000,\n );\n if (!shadowRange.ok) return shadowRange;\n return ok(\n Object.freeze({\n seed,\n baseHeight: baseHeight.value,\n thickness: thickness.value,\n scale: scale.value,\n coverage: coverage.value,\n density: density.value,\n wind: resolvedWind.value,\n quality: resolvedQuality.value,\n shadowRange: shadowRange.value,\n }),\n );\n}\n\n/** Stable source identity used by cache, history and recovery receipts. */\nexport function cloudLayerSourceKey(params: ValidatedCloudLayer): string {\n return [\n 'cloud-layer-v1',\n params.seed,\n params.baseHeight,\n params.thickness,\n params.scale,\n params.coverage,\n params.density,\n params.wind[0],\n params.wind[1],\n params.wind[2],\n params.quality,\n params.shadowRange,\n ].join(':');\n}\n\n/**\n * Stable identity for the reusable formation bases. Coverage, density and\n * wind are evaluation inputs and deliberately do not rebuild the weather,\n * body or erosion cache when they change continuously.\n */\nexport function cloudLayerFormationKey(params: ValidatedCloudLayer): string {\n return [\n 'cloud-formation-v5',\n params.seed,\n params.baseHeight,\n params.thickness,\n params.scale,\n params.quality,\n ].join(':');\n}\n","import { defineComponent, type EntityHandle } from '@forgeax/engine-ecs';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport {\n VolumeDensityShapeMismatchError,\n type VolumeError,\n VolumeInvalidBoundsError,\n VolumeInvalidParametersError,\n} from '../errors/render';\n\nexport const MAX_VOLUMETRIC_FOG_OWNERS = 8;\nexport const VolumetricFogSamplingValue = { noise: 0, density: 1 } as const;\n\nexport interface VolumeDensityBinding {\n readonly guid: string;\n readonly generation: number;\n readonly shape: {\n readonly viewDimension: '2d' | '2d-array' | '3d';\n readonly extent: {\n readonly width: number;\n readonly height: number;\n readonly depth?: number;\n readonly layers?: number;\n };\n };\n readonly format: string;\n readonly colorSpace?: 'linear' | 'srgb';\n}\n\nexport interface VolumeBounds {\n readonly min: readonly [number, number, number];\n readonly max: readonly [number, number, number];\n}\n\nexport interface VolumetricFogAuthoring {\n /** Invalid authoring reports closed code, expected, hint, and detail fields. */\n /** The selected DirectionalLight or PointLight in this World. */\n readonly light: EntityHandle;\n /** The optional same-World SpotLight paired with a PointLight. */\n readonly spotLight?: EntityHandle;\n readonly density: VolumeDensityBinding;\n readonly bounds: VolumeBounds;\n readonly extinction: readonly [number, number, number];\n readonly albedo: readonly [number, number, number];\n readonly emission: readonly [number, number, number];\n readonly anisotropy: number;\n readonly maxDistance: number;\n /** Noise grain is the atmospheric default; density samples local bounds directly. */\n readonly sampling?: 'noise' | 'density';\n}\n\nexport type VolumetricFogLightSelection =\n | { readonly light: EntityHandle; readonly spotLight?: undefined }\n | { readonly light: EntityHandle; readonly spotLight: EntityHandle };\n\nexport type ValidatedVolumetricFog = VolumetricFogAuthoring;\n\nexport const VolumetricFog = defineComponent('VolumetricFog', {\n light: { type: 'entity' },\n spotLight: { type: 'entity' },\n density: { type: 'shared<TextureAsset>', simulationTransient: true },\n boundsMin: { type: 'array<f32, 3>' },\n boundsMax: { type: 'array<f32, 3>' },\n extinction: { type: 'array<f32, 3>' },\n albedo: { type: 'array<f32, 3>' },\n emission: { type: 'array<f32, 3>' },\n anisotropy: { type: 'f32', default: 0 },\n maxDistance: { type: 'f32', default: 100 },\n sampling: { type: 'enum', labels: VolumetricFogSamplingValue, default: 0 },\n});\n\nfunction finiteVector(value: readonly [number, number, number]): boolean {\n return value.every(Number.isFinite);\n}\n\nfunction validBounds(bounds: VolumeBounds): boolean {\n if (!finiteVector(bounds.min) || !finiteVector(bounds.max)) return false;\n return bounds.max.every((value, index) => value > (bounds.min[index] ?? value));\n}\n\nfunction validRange(\n value: readonly [number, number, number],\n min: number,\n max = Infinity,\n): boolean {\n return value.every((entry) => Number.isFinite(entry) && entry >= min && entry <= max);\n}\n\nexport function validateVolumetricFog(\n input: VolumetricFogAuthoring,\n): Result<ValidatedVolumetricFog, VolumeError> {\n if (input.density.shape.viewDimension !== '3d' || input.density.colorSpace === 'srgb') {\n return err(\n new VolumeDensityShapeMismatchError(input.density.guid, input.density.shape.viewDimension),\n );\n }\n if (!validBounds(input.bounds)) return err(new VolumeInvalidBoundsError(input.bounds));\n if (\n !validRange(input.extinction, 0) ||\n !validRange(input.albedo, 0, 1) ||\n !validRange(input.emission, 0) ||\n !Number.isFinite(input.anisotropy) ||\n input.anisotropy <= -1 ||\n input.anisotropy >= 1 ||\n !Number.isFinite(input.maxDistance) ||\n input.maxDistance <= 0 ||\n (input.sampling !== undefined && input.sampling !== 'noise' && input.sampling !== 'density')\n ) {\n return err(new VolumeInvalidParametersError(input));\n }\n return ok(input);\n}\n","import type { EnvironmentCandidate, FogCandidate } from '../extract/environment';\n\nexport interface EnvironmentSignatureInput {\n readonly environments: readonly EnvironmentCandidate[];\n readonly fogs: readonly FogCandidate[];\n readonly suns: readonly {\n readonly entityKey: number;\n readonly direction: readonly [number, number, number];\n readonly color: readonly [number, number, number];\n readonly intensity: number;\n }[];\n}\n\nexport interface EnvironmentFactSignatures {\n readonly environmentSignature: string;\n readonly fogSignature: string;\n readonly signature: string;\n}\n\nfunction sorted<T extends { readonly entityKey: number }>(items: readonly T[]): readonly T[] {\n return [...items].sort((left, right) => left.entityKey - right.entityKey);\n}\n\n/** Derive a deterministic source signature without retaining GPU objects. */\nexport function environmentSignature(input: EnvironmentSignatureInput): string {\n return JSON.stringify({\n environments: sorted(input.environments),\n fogs: sorted(input.fogs),\n suns: sorted(input.suns),\n });\n}\n\n/** Signature for Environment and Sun facts, excluding the independent Fog channel. */\nexport function environmentOnlySignature(input: EnvironmentSignatureInput): string {\n return JSON.stringify({\n environments: sorted(input.environments),\n suns: sorted(input.suns),\n });\n}\n\n/** Signature for the independent Fog channel. */\nexport function fogOnlySignature(input: Pick<EnvironmentSignatureInput, 'fogs'>): string {\n return JSON.stringify({ fogs: sorted(input.fogs) });\n}\n\n/** Build all frame signatures from one immutable source fact set. */\nexport function environmentFactSignatures(\n input: EnvironmentSignatureInput,\n): EnvironmentFactSignatures {\n return {\n environmentSignature: environmentOnlySignature(input),\n fogSignature: fogOnlySignature(input),\n signature: environmentSignature(input),\n };\n}\n","import type { World } from '@forgeax/engine-ecs';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport { environmentFactSignatures } from '../environment/signature';\nimport {\n AtmosphereInvalidParameterError,\n type AtmosphereParameterRange,\n EnvironmentSourceConflictError,\n FogCardinalityError,\n type RenderError,\n} from '../errors/render';\nimport type { TemporalView } from '../temporal/view';\n\n/** The retained projection's environment extraction owner. */\nexport interface EnvironmentExtractionContext {\n readonly resourceOwner: number;\n readonly world: World;\n}\n\n/** Keep environment reads at the resource-owner frame boundary. */\nexport function createEnvironmentExtractionContext(\n world: World,\n resourceOwner: number,\n): EnvironmentExtractionContext {\n return Object.freeze({ world, resourceOwner });\n}\n\nexport type EnvironmentCandidate =\n | { readonly kind: 'image'; readonly entityKey: number; readonly sourceKey: string }\n | {\n readonly kind: 'atmosphere';\n readonly entityKey: number;\n readonly sourceKey: string;\n readonly atmosphere: AtmosphereParameters;\n };\n\nexport interface AtmosphereParameters {\n readonly turbidity: number;\n readonly rayleigh: number;\n readonly mieCoefficient: number;\n readonly mieDirectionalG: number;\n readonly sunAngularRadius: number;\n readonly circumsolarStrength: number;\n readonly circumsolarWidth: number;\n}\n\n/** Shared CPU contract for values accepted by the atmosphere shaders. */\nexport const ATMOSPHERE_PARAMETER_RANGES: Readonly<\n Record<keyof AtmosphereParameters, AtmosphereParameterRange>\n> = Object.freeze({\n turbidity: Object.freeze({ min: 1, max: 20 }),\n rayleigh: Object.freeze({ min: 0, max: Number.POSITIVE_INFINITY }),\n mieCoefficient: Object.freeze({ min: 0, max: Number.POSITIVE_INFINITY }),\n mieDirectionalG: Object.freeze({ min: 0, max: 0.999 }),\n sunAngularRadius: Object.freeze({ min: 0, max: Number.POSITIVE_INFINITY }),\n circumsolarStrength: Object.freeze({ min: 0, max: 4 }),\n circumsolarWidth: Object.freeze({ min: 0.25, max: 4 }),\n});\n\nexport interface FogCandidate {\n readonly entityKey: number;\n readonly color: readonly [number, number, number];\n readonly density: number;\n readonly heightFalloff: number;\n readonly maxOpacity: number;\n}\n\nexport type EnvironmentSource =\n | { readonly kind: 'none' }\n | {\n readonly kind: 'image';\n readonly entityKey: number;\n readonly sourceKey: string;\n }\n | {\n readonly kind: 'atmosphere';\n readonly entityKey: number;\n readonly sourceKey: string;\n readonly atmosphere: AtmosphereParameters;\n };\n\nexport interface FogFrame extends FogCandidate {}\n\nexport interface FogParameterIssue {\n readonly field: string;\n readonly value: number;\n readonly expected: string;\n}\n\n/** Structured failure retained when an invalid Fog update falls back to LKG. */\nexport interface FogSelectionFailure {\n readonly code: string;\n readonly expected: string;\n readonly hint: string;\n readonly detail: Readonly<Record<string, unknown>>;\n}\n\nexport interface EnvironmentFrame {\n readonly source: EnvironmentSource;\n /** Descriptor of the real environment resource adopted for this frame. */\n readonly resourceDescriptor?: Readonly<{\n readonly width: number;\n readonly height: number;\n readonly bytesPerPixel: number;\n }>;\n readonly fog: FogFrame | undefined;\n readonly environmentSignature: string;\n readonly fogSignature: string;\n readonly signature: string;\n readonly revision: number;\n}\n\nexport interface FramePlan {\n readonly environment: EnvironmentFrame;\n readonly temporal: TemporalView;\n}\n\nfunction freezeFog(candidate: FogCandidate): FogFrame {\n return Object.freeze({\n ...candidate,\n color: Object.freeze([...candidate.color] as unknown as FogFrame['color']),\n });\n}\n\n/** Validate the bounded Fog domain once for every frame-selection producer. */\nexport function validateFogParameters(candidate: FogCandidate): FogParameterIssue | undefined {\n if (candidate.color.length !== 3) {\n return {\n field: 'color',\n value: candidate.color.length,\n expected: 'exactly three finite channels in [0, 1]',\n };\n }\n for (let index = 0; index < candidate.color.length; index += 1) {\n const value = candidate.color[index];\n if (value === undefined || !Number.isFinite(value) || value < 0 || value > 1) {\n return {\n field: `color[${index}]`,\n value: value ?? Number.NaN,\n expected: 'a finite number in [0, 1]',\n };\n }\n }\n if (!Number.isFinite(candidate.density) || candidate.density < 0) {\n return { field: 'density', value: candidate.density, expected: 'a finite number >= 0' };\n }\n if (!Number.isFinite(candidate.heightFalloff) || candidate.heightFalloff < 0) {\n return {\n field: 'heightFalloff',\n value: candidate.heightFalloff,\n expected: 'a finite number >= 0',\n };\n }\n if (\n !Number.isFinite(candidate.maxOpacity) ||\n candidate.maxOpacity < 0 ||\n candidate.maxOpacity > 1\n ) {\n return {\n field: 'maxOpacity',\n value: candidate.maxOpacity,\n expected: 'a finite number in [0, 1]',\n };\n }\n return undefined;\n}\n\nfunction freezeAtmosphere(parameters: AtmosphereParameters): AtmosphereParameters {\n return Object.freeze({ ...parameters });\n}\n\n/** Return the first invalid analytic atmosphere field at the extraction boundary. */\nexport function validateAtmosphereParameters(\n parameters: AtmosphereParameters,\n): AtmosphereInvalidParameterError | undefined {\n for (const field of Object.keys(ATMOSPHERE_PARAMETER_RANGES) as (keyof AtmosphereParameters)[]) {\n const value = parameters[field];\n const range = ATMOSPHERE_PARAMETER_RANGES[field];\n if (!Number.isFinite(value) || value < range.min || value > range.max) {\n return new AtmosphereInvalidParameterError(field, value, range);\n }\n }\n return undefined;\n}\n\n/** Select immutable environment and independent Fog facts at the frame boundary. */\nexport function selectEnvironmentFrame(\n candidates: readonly EnvironmentCandidate[],\n fogCandidates: readonly FogCandidate[],\n): Result<EnvironmentFrame, RenderError> {\n if (candidates.length > 1) {\n return err(\n new EnvironmentSourceConflictError(\n candidates.map(({ kind, entityKey, sourceKey }) => ({ kind, entityKey, sourceKey })),\n ),\n );\n }\n if (fogCandidates.length > 1) return err(new FogCardinalityError(fogCandidates.length));\n const candidate = candidates[0];\n if (candidate?.kind === 'atmosphere') {\n const invalid = validateAtmosphereParameters(candidate.atmosphere);\n if (invalid !== undefined) return err(invalid);\n }\n const source: EnvironmentSource =\n candidate === undefined\n ? { kind: 'none' }\n : candidate.kind === 'atmosphere'\n ? {\n kind: 'atmosphere',\n entityKey: candidate.entityKey,\n sourceKey: candidate.sourceKey,\n atmosphere: freezeAtmosphere(candidate.atmosphere),\n }\n : {\n kind: 'image',\n entityKey: candidate.entityKey,\n sourceKey: candidate.sourceKey,\n };\n const fog = fogCandidates[0] === undefined ? undefined : freezeFog(fogCandidates[0]);\n const signatures = environmentFactSignatures({\n environments: candidate === undefined ? [] : [candidate],\n fogs: fogCandidates,\n suns: [],\n });\n return ok(\n Object.freeze({\n source: Object.freeze(source),\n fog,\n ...signatures,\n revision: 0,\n }),\n );\n}\n","import { err, ok, type Result } from '@forgeax/engine-types';\nimport { EnvironmentSourceConflictError, FogCardinalityError } from '../errors/render';\nimport type {\n EnvironmentCandidate,\n EnvironmentFrame,\n EnvironmentSource,\n FogCandidate,\n FogFrame,\n} from '../extract/environment';\nimport { validateAtmosphereParameters, validateFogParameters } from '../extract/environment';\nimport { environmentFactSignatures } from './signature';\n\nexport type { EnvironmentCandidate, EnvironmentFrame, EnvironmentSource, FogCandidate, FogFrame };\n\n/** Producer-local fallback while replacement environment storage is uninitialized. */\nexport const SKYLIGHT_RECOVERY_FALLBACK = Object.freeze({\n kind: 'skylight',\n active: false,\n} as const);\n\nexport interface SunCandidate {\n readonly entityKey: number;\n readonly direction: readonly [number, number, number];\n readonly color: readonly [number, number, number];\n readonly intensity: number;\n}\n\nexport interface EnvironmentSelectionInput {\n readonly environments: readonly EnvironmentCandidate[];\n readonly fogs: readonly FogCandidate[];\n readonly suns: readonly SunCandidate[];\n readonly lane: 'direct' | 'clustered';\n}\n\nexport interface EnvironmentSelectionParameterDetail {\n readonly field: string;\n readonly value: number;\n}\n\nexport class EnvironmentSelectionParameterError extends Error {\n readonly code = 'environment-selection-invalid' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: EnvironmentSelectionParameterDetail;\n\n constructor(field: string, value: number, expected: string) {\n super(`environment selection field ${field} is invalid`);\n this.name = 'EnvironmentSelectionParameterError';\n this.expected = expected;\n this.hint = `set ${field} to a finite value satisfying ${expected}`;\n this.detail = { field, value };\n }\n}\n\nexport interface SunCardinalityDetail {\n readonly field: 'sun';\n readonly value: number;\n}\n\nexport class SunCardinalityError extends Error {\n readonly code = 'sun-cardinality' as const;\n readonly expected = 'atmosphere has exactly one sun owner';\n readonly hint = 'add exactly one DirectionalLight sun for the atmosphere owner';\n readonly detail: SunCardinalityDetail;\n\n constructor(value: number) {\n super(`atmosphere sun cardinality is ${value}`);\n this.name = 'SunCardinalityError';\n this.detail = { field: 'sun', value };\n }\n}\n\nexport interface EnvironmentSelectionErrorDetail {\n readonly owners?: readonly {\n readonly kind: 'image' | 'atmosphere';\n readonly entityKey: number;\n readonly sourceKey: string;\n }[];\n readonly field?: string;\n readonly value?: number;\n readonly count?: number;\n}\n\nexport interface EnvironmentSelectionError {\n readonly code:\n | 'environment-source-conflict'\n | 'fog-cardinality'\n | 'environment-selection-invalid'\n | 'atmosphere-invalid-parameter'\n | 'sun-cardinality';\n readonly expected: string;\n readonly hint: string;\n readonly detail: EnvironmentSelectionErrorDetail;\n}\n\nexport interface SelectedEnvironmentFrame extends EnvironmentFrame {\n readonly sun: SunCandidate | undefined;\n readonly lane: 'direct' | 'clustered';\n}\n\nfunction freezeCandidate<T extends object>(candidate: T): T {\n return Object.freeze(candidate);\n}\n\nfunction freezeFog(candidate: FogCandidate): FogFrame {\n return Object.freeze({\n ...candidate,\n color: Object.freeze([...candidate.color] as unknown as FogFrame['color']),\n });\n}\n\n/** Select one immutable frame fact set for both Standard lighting lanes. */\nexport function selectEnvironment(\n input: EnvironmentSelectionInput,\n): Result<SelectedEnvironmentFrame, EnvironmentSelectionError> {\n if (input.environments.length > 1) {\n return err(\n new EnvironmentSourceConflictError(\n [...input.environments]\n .sort((left, right) => left.entityKey - right.entityKey)\n .map(({ kind, entityKey, sourceKey }) => ({ kind, entityKey, sourceKey })),\n ),\n );\n }\n if (input.fogs.length > 1) return err(new FogCardinalityError(input.fogs.length));\n const selectedFog = input.fogs[0];\n if (selectedFog !== undefined) {\n const issue = validateFogParameters(selectedFog);\n if (issue !== undefined) {\n return err(new EnvironmentSelectionParameterError(issue.field, issue.value, issue.expected));\n }\n }\n const selected = input.environments[0];\n if (selected?.kind === 'atmosphere') {\n const invalid = validateAtmosphereParameters(selected.atmosphere);\n if (invalid !== undefined) return err(invalid);\n }\n if (selected?.kind === 'atmosphere' && input.suns.length !== 1) {\n return err(new SunCardinalityError(input.suns.length));\n }\n const source: EnvironmentSource =\n selected === undefined\n ? { kind: 'none' }\n : selected.kind === 'atmosphere'\n ? {\n kind: 'atmosphere',\n entityKey: selected.entityKey,\n sourceKey: selected.sourceKey,\n atmosphere: Object.freeze({ ...selected.atmosphere }),\n }\n : {\n kind: 'image',\n entityKey: selected.entityKey,\n sourceKey: selected.sourceKey,\n };\n const sun = input.suns[0] === undefined ? undefined : freezeCandidate({ ...input.suns[0] });\n const fog = selectedFog === undefined ? undefined : freezeFog(selectedFog);\n const signatureInput = {\n environments: selected === undefined ? [] : [selected],\n fogs: selectedFog === undefined ? [] : [selectedFog],\n suns: input.suns,\n };\n const signatures = environmentFactSignatures(signatureInput);\n const result = {\n source: Object.freeze(source),\n fog,\n ...signatures,\n revision: 0,\n sun,\n } as SelectedEnvironmentFrame;\n Object.defineProperty(result, 'lane', { value: input.lane, enumerable: false });\n return ok(Object.freeze(result));\n}\n","import { err, ok, type Result } from '@forgeax/engine-types';\nimport {\n type DepthOfFieldData,\n type DepthOfFieldQuality,\n DepthOfFieldQualityValue,\n type DepthOfFieldSide,\n DepthOfFieldSideValue,\n depthOfFieldQualityFromF32,\n depthOfFieldSideFromF32,\n} from '../../components/depth-of-field';\n\nexport const DEPTH_OF_FIELD_PARAMS_BYTE_SIZE = 64;\n\n// Camera component values cross the UBO boundary as f32. Keep bounds in that\n// same representation so the authored decimal boundary 0.7 remains valid\n// after quantization.\nconst MIN_F_STOP = Math.fround(0.7);\nconst MAX_F_STOP = Math.fround(32);\nconst MAX_LINEAR_DEPTH_RAW = Math.fround(1 - 2 ** -24);\n\nexport interface DepthOfFieldParams {\n readonly focusDistance: number;\n readonly fStop: number;\n readonly sensorHeight: number;\n readonly maxRadiusPixels: number;\n readonly quality: DepthOfFieldQuality;\n readonly blurSide: DepthOfFieldSide;\n readonly focalLength: number;\n}\n\nexport const DEFAULT_DEPTH_OF_FIELD_PARAMS: DepthOfFieldParams = Object.freeze({\n focusDistance: 8,\n fStop: 2.8,\n sensorHeight: 0.024,\n maxRadiusPixels: 16,\n quality: 'medium',\n blurSide: 'both',\n focalLength: 0,\n});\n\nfunction quantizeF32(value: number): number {\n return Math.fround(value);\n}\n\nexport type DepthOfFieldErrorCode =\n | 'depth-of-field-invalid-params'\n | 'depth-of-field-orthographic-unsupported';\n\nexport interface DepthOfFieldInvalidParamsDetail {\n readonly field: string;\n readonly value: unknown;\n readonly expected: string;\n readonly bound?: readonly [number, number] | undefined;\n}\n\nexport interface DepthOfFieldOrthographicDetail {\n readonly projection: 'orthographic';\n}\n\nexport type DepthOfFieldErrorDetail =\n | DepthOfFieldInvalidParamsDetail\n | DepthOfFieldOrthographicDetail;\n\n/** Detached validation facts carried from extract to renderer inspection. */\nexport interface DepthOfFieldRequestFailure {\n readonly code: DepthOfFieldErrorCode;\n readonly detail: DepthOfFieldErrorDetail;\n readonly expected: string;\n readonly hint: string;\n}\n\nexport class DepthOfFieldValidationError extends Error {\n readonly code: DepthOfFieldErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: DepthOfFieldErrorDetail;\n\n constructor(\n code: DepthOfFieldErrorCode,\n detail: DepthOfFieldErrorDetail,\n expected: string,\n hint: string,\n ) {\n super(`${code}: ${expected}`);\n this.name = 'DepthOfFieldValidationError';\n this.code = code;\n this.expected = expected;\n this.hint = hint;\n this.detail = detail;\n }\n}\n\nexport function depthOfFieldRequestFailure(\n error: DepthOfFieldValidationError,\n): DepthOfFieldRequestFailure {\n return Object.freeze({\n code: error.code,\n detail: error.detail,\n expected: error.expected,\n hint: error.hint,\n });\n}\n\n/**\n * Resolve the params used by a frame when authoring validation failed.\n * Invalid/unsupported requests stay visible as errors, but an already\n * accepted DoF graph must keep receiving its last-known-good UBO until the\n * author submits a valid replacement or explicitly removes the component.\n */\nexport function resolveDepthOfFieldFrameParams(\n requested: DepthOfFieldParams | undefined,\n requestFailure: DepthOfFieldRequestFailure | undefined,\n accepted: DepthOfFieldParams | undefined,\n): DepthOfFieldParams | undefined {\n if (requested !== undefined) return requested;\n if (\n requestFailure === undefined ||\n requestFailure.code === 'depth-of-field-orthographic-unsupported'\n ) {\n return undefined;\n }\n return accepted;\n}\n\nexport interface DepthOfFieldCameraInput {\n readonly projection: 'perspective' | 'orthographic';\n readonly fov: number;\n readonly near: number;\n readonly far: number;\n}\n\nfunction invalid(\n field: string,\n value: unknown,\n expected: string,\n bound?: readonly [number, number],\n): DepthOfFieldValidationError {\n return new DepthOfFieldValidationError(\n 'depth-of-field-invalid-params',\n { field, value, expected, ...(bound === undefined ? {} : { bound }) },\n expected,\n `set ${field} to ${expected}`,\n );\n}\n\nfunction focalLength(sensorHeight: number, fov: number): number {\n return sensorHeight / (2 * Math.tan(fov / 2));\n}\n\nfunction opticalCocScale(\n params: Pick<DepthOfFieldParams, 'focalLength' | 'sensorHeight' | 'fStop' | 'focusDistance'>,\n): number {\n // This is evaluated on the CPU once per frame. Keep the ratios separate so\n // the final f32 coefficient does not inherit an avoidable focalLength^2\n // overflow.\n return (\n (params.focalLength / params.sensorHeight / (2 * params.fStop)) *\n (params.focalLength / (params.focusDistance - params.focalLength))\n );\n}\n\nfunction frameCocCoefficient(\n params: Pick<DepthOfFieldParams, 'focalLength' | 'sensorHeight' | 'fStop' | 'focusDistance'>,\n outputHeight: number,\n): number {\n return quantizeF32(quantizeF32(outputHeight) * opticalCocScale(params));\n}\n\ninterface DepthOfFieldFrameValues {\n readonly focusDistance: number;\n readonly fStop: number;\n readonly sensorHeight: number;\n readonly focalLength: number;\n readonly maxRadiusPixels: number;\n readonly outputHeight: number;\n readonly near: number;\n readonly far: number;\n readonly cocCoefficient: number;\n}\n\nfunction resolveDepthOfFieldFrameValues(\n params: DepthOfFieldParams,\n input: {\n readonly outputHeight: number;\n readonly near: number;\n readonly far: number;\n readonly useTemporalDepth: boolean;\n },\n): Result<DepthOfFieldFrameValues, DepthOfFieldValidationError> {\n const focusDistance = quantizeF32(params.focusDistance);\n const fStop = quantizeF32(params.fStop);\n const sensorHeight = quantizeF32(params.sensorHeight);\n const focal = quantizeF32(params.focalLength);\n const maxRadiusPixels = quantizeF32(params.maxRadiusPixels);\n const outputHeight = quantizeF32(input.outputHeight);\n const near = quantizeF32(input.near);\n const far = quantizeF32(input.far);\n const finitePositiveFields: readonly [string, number, number][] = [\n ['focusDistance', focusDistance, params.focusDistance],\n ['sensorHeight', sensorHeight, params.sensorHeight],\n ['focalLength', focal, params.focalLength],\n ['near', near, input.near],\n ['far', far, input.far],\n ];\n for (const [field, value, raw] of finitePositiveFields) {\n if (!Number.isFinite(value) || value <= 0) {\n return err(invalid(field, raw, 'a finite positive f32 value'));\n }\n }\n if (!Number.isFinite(fStop) || fStop < MIN_F_STOP || fStop > MAX_F_STOP) {\n return err(\n invalid('fStop', params.fStop, 'a finite f32 value in [0.7, 32]', [MIN_F_STOP, MAX_F_STOP]),\n );\n }\n if (!Number.isFinite(maxRadiusPixels) || maxRadiusPixels < 0 || maxRadiusPixels > 32) {\n return err(\n invalid('maxRadiusPixels', params.maxRadiusPixels, 'a finite f32 value in [0, 32]', [0, 32]),\n );\n }\n if (!Number.isFinite(outputHeight) || outputHeight <= 0) {\n return err(invalid('outputHeight', input.outputHeight, 'a finite positive f32 value'));\n }\n if (far <= near) {\n return err(invalid('near/far', [input.near, input.far], 'finite f32 near > 0 and far > near'));\n }\n if (focusDistance <= focal) {\n return err(invalid('focusDistance', params.focusDistance, 'greater than focalLength in f32'));\n }\n\n // linearDepth() uses this ratio and denominator order in both WGSL\n // variants. Reject a ratio that disappears at f32 precision, then check the\n // near, mid and largest-valid raw-depth samples for finite denominators and\n // reconstructed distances. The denominator is strictly positive for valid\n // raw depth, so no world-unit epsilon belongs in the shader.\n const depthRatio = quantizeF32(near / far);\n if (!Number.isFinite(depthRatio) || depthRatio <= 0) {\n return err(invalid('near/far ratio', depthRatio, 'a finite positive f32 value'));\n }\n for (const raw of [quantizeF32(2 ** -149), 0.5, MAX_LINEAR_DEPTH_RAW]) {\n const oneMinusRaw = quantizeF32(1 - raw);\n const weightedRatio = quantizeF32(raw * depthRatio);\n const denominator = quantizeF32(oneMinusRaw + weightedRatio);\n const distance = quantizeF32(near / denominator);\n if (\n !Number.isFinite(oneMinusRaw) ||\n oneMinusRaw <= 0 ||\n !Number.isFinite(weightedRatio) ||\n !Number.isFinite(denominator) ||\n denominator <= 0 ||\n !Number.isFinite(distance) ||\n distance <= 0\n ) {\n return err(invalid('linearDepth', distance, 'finite positive f32 reconstruction'));\n }\n }\n\n const cocCoefficient = frameCocCoefficient(\n {\n focusDistance,\n fStop,\n sensorHeight,\n focalLength: focal,\n },\n outputHeight,\n );\n if (!Number.isFinite(cocCoefficient) || cocCoefficient <= 0) {\n return err(\n invalid('cocCoefficient', cocCoefficient, 'a finite positive value representable as f32'),\n );\n }\n // The shader evaluates C * (1 - focus / depth). Check each f32 operation at\n // the projection endpoints before the UBO is written.\n for (const [field, depth] of [\n ['near', near],\n ['far', far],\n ] as const) {\n const focusOverDepth = quantizeF32(focusDistance / depth);\n const depthFactor = quantizeF32(1 - focusOverDepth);\n const radius = quantizeF32(cocCoefficient * depthFactor);\n if (\n !Number.isFinite(focusOverDepth) ||\n !Number.isFinite(depthFactor) ||\n !Number.isFinite(radius)\n ) {\n return err(invalid(`coc.${field}`, radius, 'a finite value representable as f32'));\n }\n }\n\n return ok({\n focusDistance,\n fStop,\n sensorHeight,\n focalLength: focal,\n maxRadiusPixels,\n outputHeight,\n near,\n far,\n cocCoefficient,\n });\n}\n\n/**\n * Validate the values that cross the f32 camera UBO boundary for one frame.\n * Camera and DoF schemas already use f32 columns, but direct callers and\n * synthetic frame tests can still supply wider JS numbers. Quantize first so\n * admission and the WGSL consumer make the same decision.\n */\nexport function validateDepthOfFieldFrameParams(\n params: DepthOfFieldParams,\n input: {\n readonly outputHeight: number;\n readonly near: number;\n readonly far: number;\n readonly useTemporalDepth: boolean;\n },\n): Result<void, DepthOfFieldValidationError> {\n const resolved = resolveDepthOfFieldFrameValues(params, input);\n return resolved.ok ? ok(undefined) : resolved;\n}\n\n/**\n * Validate and derive one camera DoF declaration at the frame admission seam.\n * The returned focal length is a derived fact; callers never author it.\n */\nexport function validateDepthOfFieldParams(\n input: Partial<DepthOfFieldData> | undefined,\n camera?: DepthOfFieldCameraInput,\n): Result<DepthOfFieldParams, DepthOfFieldValidationError> {\n if (camera?.projection === 'orthographic') {\n return err(\n new DepthOfFieldValidationError(\n 'depth-of-field-orthographic-unsupported',\n { projection: 'orthographic' },\n 'DepthOfField requires a perspective Camera',\n 'use a perspective Camera or remove the DepthOfField component',\n ),\n );\n }\n const value = input ?? {};\n const focusDistance = quantizeF32(\n value.focusDistance ?? DEFAULT_DEPTH_OF_FIELD_PARAMS.focusDistance,\n );\n const fStop = quantizeF32(value.fStop ?? DEFAULT_DEPTH_OF_FIELD_PARAMS.fStop);\n const sensorHeight = quantizeF32(\n value.sensorHeight ?? DEFAULT_DEPTH_OF_FIELD_PARAMS.sensorHeight,\n );\n const maxRadiusPixels = quantizeF32(\n value.maxRadiusPixels ?? DEFAULT_DEPTH_OF_FIELD_PARAMS.maxRadiusPixels,\n );\n const qualityValue = quantizeF32(value.quality ?? DepthOfFieldQualityValue.medium);\n const blurSideValue = quantizeF32(value.blurSide ?? DepthOfFieldSideValue.both);\n const quality = depthOfFieldQualityFromF32(qualityValue);\n const blurSide = depthOfFieldSideFromF32(blurSideValue);\n if (!Number.isFinite(focusDistance) || focusDistance <= 0) {\n return err(\n invalid('focusDistance', value.focusDistance ?? focusDistance, 'a finite positive f32 value'),\n );\n }\n if (!Number.isFinite(fStop) || fStop < MIN_F_STOP || fStop > MAX_F_STOP) {\n return err(\n invalid('fStop', value.fStop ?? fStop, 'a finite f32 value in [0.7, 32]', [\n MIN_F_STOP,\n MAX_F_STOP,\n ]),\n );\n }\n if (!Number.isFinite(sensorHeight) || sensorHeight <= 0) {\n return err(\n invalid('sensorHeight', value.sensorHeight ?? sensorHeight, 'a finite positive f32 value'),\n );\n }\n if (!Number.isFinite(maxRadiusPixels) || maxRadiusPixels < 0 || maxRadiusPixels > 32) {\n return err(\n invalid(\n 'maxRadiusPixels',\n value.maxRadiusPixels ?? maxRadiusPixels,\n 'a finite f32 value in [0, 32]',\n [0, 32],\n ),\n );\n }\n if (quality === undefined) {\n return err(invalid('quality', qualityValue, 'DepthOfFieldQualityValue.low, medium, or high'));\n }\n if (blurSide === undefined) {\n return err(invalid('blurSide', blurSideValue, 'DepthOfFieldSideValue.both, near, or far'));\n }\n\n let focal = DEFAULT_DEPTH_OF_FIELD_PARAMS.focalLength;\n if (camera !== undefined) {\n const fov = quantizeF32(camera.fov);\n const near = quantizeF32(camera.near);\n const far = quantizeF32(camera.far);\n if (!Number.isFinite(fov) || fov <= 0 || fov >= Math.PI) {\n return err(invalid('fov', camera.fov, 'a finite f32 value in (0, PI)'));\n }\n if (!Number.isFinite(near) || !Number.isFinite(far) || near <= 0 || far <= near) {\n return err(\n invalid('near/far', [camera.near, camera.far], 'finite f32 near > 0 and far > near'),\n );\n }\n focal = quantizeF32(focalLength(sensorHeight, fov));\n if (!Number.isFinite(focal) || focal <= 0) {\n return err(invalid('focalLength', focal, 'a finite positive f32 value'));\n }\n if (focusDistance < near || focusDistance > far) {\n return err(\n invalid('focusDistance', focusDistance, `a value in [${near}, ${far}]`, [near, far]),\n );\n }\n if (focusDistance <= focal) {\n return err(\n invalid('focusDistance', focusDistance, `greater than focalLength in f32 (${focal})`),\n );\n }\n }\n return ok(\n Object.freeze({\n focusDistance,\n fStop,\n sensorHeight,\n maxRadiusPixels,\n quality,\n blurSide,\n focalLength: focal,\n }),\n );\n}\n\nexport function resolveDepthOfFieldParams(\n input: Partial<DepthOfFieldData> | undefined,\n camera?: DepthOfFieldCameraInput,\n): Result<DepthOfFieldParams | undefined, DepthOfFieldValidationError> {\n if (input === undefined) return ok(undefined);\n return validateDepthOfFieldParams(input, camera);\n}\n\nexport function depthOfFieldTapCount(quality: DepthOfFieldQuality): 16 | 32 | 64 {\n switch (quality) {\n case 'low':\n return 16;\n case 'medium':\n return 32;\n case 'high':\n return 64;\n }\n}\n\nexport function depthOfFieldSideCode(side: DepthOfFieldSide): 0 | 1 | 2 {\n switch (side) {\n case 'both':\n return DepthOfFieldSideValue.both;\n case 'near':\n return DepthOfFieldSideValue.near;\n case 'far':\n return DepthOfFieldSideValue.far;\n }\n}\n\nexport function depthOfFieldQualityCode(quality: DepthOfFieldQuality): 0 | 1 | 2 {\n switch (quality) {\n case 'low':\n return DepthOfFieldQualityValue.low;\n case 'medium':\n return DepthOfFieldQualityValue.medium;\n case 'high':\n return DepthOfFieldQualityValue.high;\n }\n}\n\n/** Signed thin-lens circle-of-confusion radius in final output pixels. */\nexport function signedDepthOfFieldCoC(\n params: Pick<DepthOfFieldParams, 'focalLength' | 'sensorHeight' | 'fStop' | 'focusDistance'> &\n Partial<Pick<DepthOfFieldParams, 'maxRadiusPixels'>>,\n viewDepth: number,\n outputHeight: number,\n): number {\n if (\n !Number.isFinite(viewDepth) ||\n viewDepth <= 0 ||\n !Number.isFinite(outputHeight) ||\n outputHeight <= 0 ||\n !Number.isFinite(params.focalLength) ||\n params.focalLength <= 0 ||\n !Number.isFinite(params.sensorHeight) ||\n params.sensorHeight <= 0 ||\n !Number.isFinite(params.fStop) ||\n params.fStop <= 0 ||\n !Number.isFinite(params.focusDistance) ||\n params.focusDistance <= params.focalLength\n ) {\n return 0;\n }\n const focusDistance = quantizeF32(params.focusDistance);\n const depth = quantizeF32(viewDepth);\n const focalLength = quantizeF32(params.focalLength);\n const sensorHeight = quantizeF32(params.sensorHeight);\n const fStop = quantizeF32(params.fStop);\n const coefficient = frameCocCoefficient(\n { focusDistance, focalLength, sensorHeight, fStop },\n outputHeight,\n );\n const depthFactor = quantizeF32(1 - quantizeF32(focusDistance / depth));\n const radius = quantizeF32(coefficient * depthFactor);\n const limit = Number.isFinite(params.maxRadiusPixels)\n ? quantizeF32(params.maxRadiusPixels as number)\n : Number.POSITIVE_INFINITY;\n return Math.max(-limit, Math.min(limit, Number.isFinite(radius) ? radius : 0));\n}\n\n/** Pack the one renderer-owned per-frame DoF UBO (4 x vec4, 64 bytes). */\nexport function packDepthOfFieldParams(\n params: DepthOfFieldParams,\n input: {\n readonly outputHeight: number;\n readonly near: number;\n readonly far: number;\n readonly useTemporalDepth: boolean;\n },\n): Uint8Array {\n const frameValues = resolveDepthOfFieldFrameValues(params, input);\n if (!frameValues.ok) throw frameValues.error;\n const {\n focusDistance,\n fStop,\n sensorHeight,\n focalLength: focal,\n outputHeight,\n maxRadiusPixels,\n near,\n far,\n cocCoefficient,\n } = frameValues.value;\n const payload = new Float32Array(DEPTH_OF_FIELD_PARAMS_BYTE_SIZE / 4);\n // row3.x is the frame CoC coefficient; the remaining reserved lanes stay\n // zero so the existing 64-byte binding contract remains unchanged.\n payload.set([\n focusDistance,\n fStop,\n sensorHeight,\n focal,\n outputHeight,\n maxRadiusPixels,\n depthOfFieldSideCode(params.blurSide),\n depthOfFieldQualityCode(params.quality),\n near,\n far,\n input.useTemporalDepth ? 1 : 0,\n 0, // row2.w reserved\n cocCoefficient, // row3.x / WGSL reserved.x\n 0,\n 0,\n 0,\n ]);\n return new Uint8Array(payload.buffer);\n}\n","import { Entity, type EntityHandle, type World } from '@forgeax/engine-ecs';\nimport type { RhiCaps } from '@forgeax/engine-rhi';\nimport { Transform } from '@forgeax/engine-scene';\nimport { DirectionalLight } from '../components/directional-light';\nimport { PointLight } from '../components/point-light';\nimport { SpotLight } from '../components/spot-light';\n\n/**\n * The single capability predicate for the authored volumetric-fog producer.\n * Shader sources are part of the device-bound bundle: compute/storage alone\n * is not enough to claim that the three fused graph passes can execute.\n */\nexport function hasVolumetricFogCapability(\n caps: Pick<RhiCaps, 'compute' | 'storageTexture'>,\n shaders: unknown,\n): boolean {\n return caps.compute && caps.storageTexture && shaders !== undefined;\n}\n\nexport type VolumetricFogLightKind = 'directional' | 'point' | 'spot';\n// The exact parity authoring mode is the closed `point-spot` pair.\n\nexport type VolumetricFogLightResolution =\n | {\n readonly status: 'available';\n readonly entity: EntityHandle;\n readonly kind: VolumetricFogLightKind;\n }\n | {\n readonly status: 'unresolved';\n readonly reason: 'missing-entity' | 'wrong-component' | 'ambiguous';\n readonly entity: EntityHandle;\n readonly expected: 'DirectionalLight | PointLight | SpotLight';\n readonly actual: string;\n readonly hint: string;\n };\n\nexport type VolumetricFogLightPairResolution =\n | {\n readonly status: 'available';\n readonly mode: 'point-spot';\n readonly point: EntityHandle;\n readonly spot: EntityHandle;\n }\n | {\n readonly status: 'unresolved';\n readonly reason: 'missing-entity' | 'same-entity' | 'wrong-component';\n readonly point: EntityHandle;\n readonly spot: EntityHandle;\n readonly expected: 'PointLight + SpotLight in the same World';\n readonly actual: string;\n readonly hint: string;\n };\n\n/** Resolve the narrow official Point+Spot pair without creating a light owner. */\nexport function resolveVolumetricFogLightPair(\n world: World,\n point: EntityHandle,\n spot: EntityHandle,\n): VolumetricFogLightPairResolution {\n const expected = 'PointLight + SpotLight in the same World' as const;\n if (!world.get(point, Entity).ok || !world.get(spot, Entity).ok) {\n return {\n status: 'unresolved',\n reason: 'missing-entity',\n point,\n spot,\n expected,\n actual: 'point or spot entity is absent from this World',\n hint: 'assign two live entities from the same World and retry',\n };\n }\n if (point === spot) {\n return {\n status: 'unresolved',\n reason: 'same-entity',\n point,\n spot,\n expected,\n actual: 'PointLight and SpotLight share one EntityHandle',\n hint: 'spawn PointLight and SpotLight on two different entities',\n };\n }\n const pointValid = world.hasComponent(point, PointLight) && world.hasComponent(point, Transform);\n const spotValid = world.hasComponent(spot, SpotLight) && world.hasComponent(spot, Transform);\n if (!pointValid || !spotValid) {\n return {\n status: 'unresolved',\n reason: 'wrong-component',\n point,\n spot,\n expected,\n actual: `pointValid=${pointValid}; spotValid=${spotValid}`,\n hint: 'attach PointLight and SpotLight with Transform to separate same-World entities',\n };\n }\n return { status: 'available', mode: 'point-spot', point, spot };\n}\n\n/**\n * Resolve the required VolumetricFog.light reference in its owning World.\n * PointLight is a valid primary selection for the exact Point+Spot pair.\n * EntityHandle has no portable world tag, so a handle absent from this World\n * (the same World contract) is reported as missing-entity;\n * is reported as missing-entity; callers must not manufacture a light.\n */\nexport function resolveSelectedVolumetricLight(\n world: World,\n entity: EntityHandle,\n): VolumetricFogLightResolution {\n const expected = 'DirectionalLight | PointLight | SpotLight' as const;\n if (!world.get(entity, Entity).ok) {\n return {\n status: 'unresolved',\n reason: 'missing-entity',\n entity,\n expected,\n actual: 'missing or foreign World entity',\n hint: 'assign VolumetricFog.light to a live DirectionalLight or SpotLight in this World',\n };\n }\n const hasDirectional = world.hasComponent(entity, DirectionalLight);\n const hasSpot = world.hasComponent(entity, SpotLight);\n if (hasDirectional && hasSpot) {\n return {\n status: 'unresolved',\n reason: 'ambiguous',\n entity,\n expected,\n actual: 'DirectionalLight + SpotLight',\n hint: 'remove one mutually exclusive light component from the selected entity',\n };\n }\n if (hasDirectional) return { status: 'available', entity, kind: 'directional' };\n if (world.hasComponent(entity, PointLight) && world.hasComponent(entity, Transform)) {\n return { status: 'available', entity, kind: 'point' };\n }\n if (hasSpot && world.hasComponent(entity, Transform)) {\n return { status: 'available', entity, kind: 'spot' };\n }\n const actual = hasSpot\n ? 'SpotLight without Transform'\n : world.hasComponent(entity, PointLight)\n ? 'PointLight'\n : 'other component';\n return {\n status: 'unresolved',\n reason: 'wrong-component',\n entity,\n expected,\n actual,\n hint: 'add exactly one supported light component and a Transform for PointLight or SpotLight in the same World',\n };\n}\n\nexport interface IntegratedVolumeResource {\n /** Logical resolved-volume identity; this is not a physical graph resource. */\n readonly identity: 'volume-integrated';\n readonly format: 'rgba16float';\n readonly stage: 'resolved';\n}\n\nexport type VolumeConsumer = 'opaque' | 'transparent' | 'sprite' | 'vfx' | 'custom';\n\nexport function resolveIntegratedVolumeConsumer(\n resource: IntegratedVolumeResource,\n consumer: VolumeConsumer,\n): { readonly consumer: VolumeConsumer; readonly resource: IntegratedVolumeResource } {\n // The volume owner supplies this prepared logical resource. Consumers only\n // receive its identity and format; they never allocate a view or own the\n // history lifetime here.\n return { consumer, resource };\n}\n","import { type Mat4, mat4, type Vec3Like } from '@forgeax/engine-math';\nimport { CUBE_CAMERA_FACE_ORDER, type CubeCameraFace } from '../components/cube-camera';\n\nexport interface CubeCameraFaceView {\n readonly position: Vec3Like;\n readonly face: CubeCameraFace;\n readonly direction: readonly [number, number, number];\n readonly up: readonly [number, number, number];\n readonly near: number;\n readonly far: number;\n readonly view: Mat4;\n readonly projection: Mat4;\n readonly viewProjection: Mat4;\n}\n\nexport interface CubeCameraFaceViewInput {\n readonly position: Vec3Like;\n readonly near: number;\n readonly far: number;\n}\n\nconst FACE_ORIENTATION: ReadonlyArray<{\n readonly direction: readonly [number, number, number];\n readonly up: readonly [number, number, number];\n}> = [\n { direction: [1, 0, 0], up: [0, 1, 0] },\n { direction: [-1, 0, 0], up: [0, 1, 0] },\n { direction: [0, 1, 0], up: [0, 0, -1] },\n { direction: [0, -1, 0], up: [0, 0, 1] },\n { direction: [0, 0, 1], up: [0, 1, 0] },\n { direction: [0, 0, -1], up: [0, 1, 0] },\n];\n\nfunction assertRange(near: number, far: number): void {\n if (!Number.isFinite(near) || near <= 0 || !Number.isFinite(far) || far <= near) {\n throw new RangeError('CubeCamera requires finite near > 0 and far > near.');\n }\n}\n\n/** Build the only supported +X,-X,+Y,-Y,+Z,-Z cube orientation. */\nexport function buildCubeCameraFaceViews(input: CubeCameraFaceViewInput): CubeCameraFaceView[] {\n assertRange(input.near, input.far);\n const views: CubeCameraFaceView[] = [];\n for (const [index, face] of CUBE_CAMERA_FACE_ORDER.entries()) {\n const orientation = FACE_ORIENTATION[index];\n if (orientation === undefined)\n throw new Error(`CubeCamera face orientation missing at ${index}`);\n const target: Vec3Like = [\n (input.position[0] ?? 0) + orientation.direction[0],\n (input.position[1] ?? 0) + orientation.direction[1],\n (input.position[2] ?? 0) + orientation.direction[2],\n ];\n const view = mat4.lookAt(mat4.create(), input.position, target, orientation.up);\n const projection = mat4.perspective(mat4.create(), Math.PI / 2, 1, input.near, input.far);\n const viewProjection = mat4.multiply(mat4.create(), projection, view);\n views.push({\n position: input.position,\n face,\n direction: orientation.direction,\n up: orientation.up,\n near: input.near,\n far: input.far,\n view,\n projection,\n viewProjection,\n });\n }\n return views;\n}\n","import type { AssetErrorDetail, AssetGuid, MeshAsset } from '@forgeax/engine-types';\n\nexport type MeshMaterialBindingSource = 'renderer-override' | 'mesh-default' | 'engine-default';\n\nexport interface MeshMaterialBindingDiagnostic {\n readonly code:\n | 'mesh-renderer-material-override-invalid'\n | 'mesh-renderer-material-override-overflow';\n readonly slotIndex: number;\n readonly handle?: number;\n /** Structured detail mirrors the renderer error for the active frame. */\n readonly detail?: Readonly<AssetErrorDetail>;\n}\n\n/** Detached final-frame receipt for the Standard material IBL binding chain. */\nexport interface IblBindingResourceInspection {\n readonly viewIdentity: number;\n readonly samplerIdentity: number;\n readonly deviceGeneration: number;\n}\n\nexport interface IblBindingEntryInspection {\n readonly binding: number;\n readonly kind: 'textureView' | 'sampler' | 'buffer';\n readonly resourceIdentity: number;\n}\n\nexport interface IblBindingInspection {\n readonly status: 'binding-chain-consistent' | 'binding-chain-mismatch';\n readonly frameId: number;\n readonly deviceGeneration: number;\n readonly active: 'active' | 'fallback';\n readonly cache: {\n readonly identity: number;\n readonly generation: number;\n readonly prefilterMipCount: number;\n readonly prefilterViewMipCount: number;\n };\n readonly sampler: {\n readonly expected: {\n readonly magFilter: 'linear';\n readonly minFilter: 'linear';\n readonly mipmapFilter: 'linear';\n readonly addressModeU: 'clamp-to-edge';\n readonly addressModeV: 'clamp-to-edge';\n readonly addressModeW: 'clamp-to-edge';\n };\n readonly identities: readonly number[];\n };\n readonly resources: {\n readonly irradiance: IblBindingResourceInspection;\n readonly prefilter: IblBindingResourceInspection;\n readonly brdfLut: IblBindingResourceInspection;\n readonly intensityBufferIdentity: number;\n };\n readonly material?: {\n readonly bindGroupIdentity: number;\n readonly materialBglIdentity: number;\n readonly cache: 'hit' | 'miss';\n readonly skylightBindingStart: number;\n readonly entries: readonly IblBindingEntryInspection[];\n readonly reflectionBindings: readonly number[];\n };\n readonly pipeline?: {\n readonly pipelineIdentity: number;\n readonly effectiveMaterialLayoutIdentity: string | undefined;\n readonly materialBglIdentity: number;\n readonly bindGroupIdentity: number;\n readonly drawFrameId: number;\n };\n readonly errors: readonly string[];\n}\n\nexport interface ResolvedMeshMaterialBinding {\n readonly handle: number;\n readonly source: MeshMaterialBindingSource;\n}\n\n/** Lifecycle values projected from an already prepared resident binding. */\nexport type MeshMaterialBindingReadiness = 'ready' | 'pending' | 'failed' | 'last-known-good';\n\n/** Structured producer failure retained by the renderer's bounded projection. */\nexport interface MeshMaterialBindingPreparationFailure {\n readonly code: string;\n readonly expected: string;\n readonly hint: string;\n readonly detail?: Readonly<Record<string, unknown>>;\n}\n\nexport interface MeshMaterialBindingSamplerObservation {\n readonly handle: number;\n readonly resident: boolean;\n}\n\nexport interface MeshMaterialBindingTextureObservation {\n readonly handle: number;\n readonly mipLevelCount: number;\n}\n\n/**\n * One material-slot's bounded resident projection. The renderer reports only\n * resources it actually resolved for the slot; Pack/AssetRegistry lifecycle\n * records stay owned by the producer and are never copied here.\n */\nexport interface MeshMaterialBindingResidency {\n readonly readiness: MeshMaterialBindingReadiness;\n readonly samplers: readonly MeshMaterialBindingSamplerObservation[];\n readonly textures: readonly MeshMaterialBindingTextureObservation[];\n readonly preparationFailure?: MeshMaterialBindingPreparationFailure;\n}\n\n/** Public read-only observation of the bindings used by the last frame. */\nexport interface MeshMaterialBindingObservation {\n readonly worldId: number;\n /** Stable World identity for cross-world inspection; worldId is only a frame slot. */\n readonly worldIdentity?: string;\n readonly entityKey: number;\n readonly bindings: readonly ResolvedMeshMaterialBinding[];\n readonly diagnostics: readonly MeshMaterialBindingDiagnostic[];\n /** One resident projection per resolved material slot. */\n readonly residency: readonly MeshMaterialBindingResidency[];\n}\n\nexport interface MeshMaterialBindingSummary {\n readonly total: number;\n readonly ready: number;\n readonly pending: number;\n readonly failed: number;\n readonly lastKnownGood: number;\n readonly textureCount: number;\n readonly samplerCount: number;\n}\n\nconst EMPTY_RESIDENCY: MeshMaterialBindingResidency = Object.freeze({\n readiness: 'pending',\n samplers: Object.freeze([]),\n textures: Object.freeze([]),\n});\n\n/**\n * Build the sole renderer observation projection from the resident seam.\n * Missing facts remain `pending`; they are never guessed from a URL, asset\n * name, or authoring field. Slot cardinality is normalized so aggregation is\n * deterministic even while a preparation candidate is incomplete.\n */\nexport function projectMeshMaterialBindingObservation(input: {\n readonly worldId: number;\n readonly worldIdentity?: string;\n readonly entityKey: number;\n readonly bindings: readonly ResolvedMeshMaterialBinding[];\n readonly diagnostics: readonly MeshMaterialBindingDiagnostic[];\n readonly residency?: readonly MeshMaterialBindingResidency[];\n}): MeshMaterialBindingObservation {\n const residency = input.bindings.map((_, index) => {\n const value = input.residency?.[index] ?? EMPTY_RESIDENCY;\n return Object.freeze({\n ...value,\n samplers: Object.freeze(value.samplers.map((sampler) => Object.freeze({ ...sampler }))),\n textures: Object.freeze(value.textures.map((texture) => Object.freeze({ ...texture }))),\n ...(value.preparationFailure === undefined\n ? {}\n : {\n preparationFailure: Object.freeze({\n ...value.preparationFailure,\n ...(value.preparationFailure.detail === undefined\n ? {}\n : { detail: Object.freeze({ ...value.preparationFailure.detail }) }),\n }),\n }),\n });\n });\n return {\n worldId: input.worldId,\n ...(input.worldIdentity === undefined ? {} : { worldIdentity: input.worldIdentity }),\n entityKey: input.entityKey,\n bindings: Object.freeze([...input.bindings]),\n diagnostics: Object.freeze([...input.diagnostics]),\n residency: Object.freeze(residency),\n };\n}\n\n/** Recompute bounded readiness/resource counts from retained observations. */\nexport function summarizeMeshMaterialBindings(\n observations: readonly MeshMaterialBindingObservation[],\n): MeshMaterialBindingSummary {\n let ready = 0;\n let pending = 0;\n let failed = 0;\n let lastKnownGood = 0;\n let textureCount = 0;\n let samplerCount = 0;\n for (const observation of observations) {\n for (const residency of observation.residency) {\n switch (residency.readiness) {\n case 'ready':\n ready += 1;\n break;\n case 'pending':\n pending += 1;\n break;\n case 'failed':\n failed += 1;\n break;\n case 'last-known-good':\n lastKnownGood += 1;\n break;\n }\n textureCount += residency.textures.length;\n samplerCount += residency.samplers.length;\n }\n }\n return {\n total: ready + pending + failed + lastKnownGood,\n ready,\n pending,\n failed,\n lastKnownGood,\n textureCount,\n samplerCount,\n };\n}\n\nexport type ResolveMeshMaterialBindingsResult =\n | {\n readonly ok: true;\n readonly bindings: readonly ResolvedMeshMaterialBinding[];\n readonly diagnostics: readonly MeshMaterialBindingDiagnostic[];\n }\n | {\n readonly ok: false;\n readonly code: 'mesh-material-slots-missing';\n }\n | {\n readonly ok: false;\n readonly code: 'mesh-default-material-not-ready';\n readonly slotIndex: number;\n readonly defaultMaterial: AssetGuid;\n };\n\n/**\n * Single owner of the instance override -> mesh default -> engine default\n * inheritance rule. It resolves once per logical slot; submeshes only project\n * their materialSlot index onto the returned table.\n */\nexport function resolveMeshMaterialBindings(\n mesh: MeshAsset,\n rendererOverrides: ArrayLike<number>,\n deps: {\n readonly isValidOverride: (handle: number) => boolean;\n readonly resolveMeshDefault: (guid: AssetGuid) => number | undefined;\n },\n): ResolveMeshMaterialBindingsResult {\n const bindings: ResolvedMeshMaterialBinding[] = [];\n const diagnostics: MeshMaterialBindingDiagnostic[] = [];\n\n if (!Array.isArray(mesh.materialSlots)) {\n return { ok: false, code: 'mesh-material-slots-missing' };\n }\n\n if (rendererOverrides.length > mesh.materialSlots.length) {\n diagnostics.push({\n code: 'mesh-renderer-material-override-overflow',\n slotIndex: mesh.materialSlots.length,\n });\n }\n\n for (let slotIndex = 0; slotIndex < mesh.materialSlots.length; slotIndex++) {\n const override = rendererOverrides[slotIndex] ?? 0;\n if (override !== 0 && deps.isValidOverride(override)) {\n bindings.push({ handle: override, source: 'renderer-override' });\n continue;\n }\n if (override !== 0) {\n diagnostics.push({\n code: 'mesh-renderer-material-override-invalid',\n slotIndex,\n handle: override,\n });\n }\n const declaredDefault = mesh.materialSlots[slotIndex]?.defaultMaterial;\n if (declaredDefault !== undefined) {\n const handle = deps.resolveMeshDefault(declaredDefault);\n if (handle === undefined) {\n return {\n ok: false,\n code: 'mesh-default-material-not-ready',\n slotIndex,\n defaultMaterial: declaredDefault,\n };\n }\n bindings.push({ handle, source: 'mesh-default' });\n continue;\n }\n bindings.push({ handle: 0, source: 'engine-default' });\n }\n\n return { ok: true, bindings, diagnostics };\n}\n","import type { EntityHandle, World } from '@forgeax/engine-ecs';\nimport {\n projectHierarchy,\n type SceneHierarchyDiagnostic,\n type SceneHierarchySnapshot,\n} from '@forgeax/engine-scene';\nimport {\n Visibility,\n type VisibilityState,\n VisibilityStateValue,\n visibilityStateFromU32,\n} from '../components/visibility';\n\nexport type VisibilitySource = 'default' | 'self' | 'parent';\n\nexport interface VisibilityResolution {\n /** The component value authored on this entity before inheritance. */\n readonly intent: VisibilityState;\n /** The state consumed by render candidates after parent resolution. */\n readonly effective: 'hidden' | 'visible';\n /** Explains whether the effective state came from self, parent, or default. */\n readonly source: VisibilitySource;\n}\n\nexport interface VisibilitySnapshot {\n readonly diagnostics: readonly SceneHierarchyDiagnostic[];\n readonly hasAnyIntent: boolean;\n readonly hasAnyHiddenIntent: boolean;\n get(entity: EntityHandle): VisibilityResolution | undefined;\n /** Resolve effective visibility for a render candidate, including inherited defaults. */\n effective(entity: EntityHandle): 'hidden' | 'visible';\n}\n\ninterface ResolutionState {\n readonly intent: VisibilityState;\n readonly effective: 'hidden' | 'visible';\n readonly source: VisibilitySource;\n}\n\n/**\n * Resolve author intent against the scene-owned valid parent projection.\n * Diagnostics are preserved for callers to repair hierarchy input before retry.\n */\nexport function resolveVisibility(\n world: World,\n hierarchy: SceneHierarchySnapshot = projectHierarchy(world),\n): VisibilitySnapshot {\n // Visibility is an opt-in component. Query only the owning archetypes\n // instead of walking every Entity row with an optional column; the latter\n // made a World with no visibility intents pay a full-scene scan on each\n // extraction. QueryRow.entity is sourced from the essential Entity column,\n // so the required Visibility read retains the same handle and intent\n // semantics while keeping the hot path sparse.\n const query = world.query({ read: [Visibility] });\n const visitVisibilityRows = (visit: (entity: EntityHandle, rawState: number) => void): void => {\n if (!query.ok) return;\n // Dense component spans keep the per-frame summary on typed-array reads\n // instead of allocating a QueryRow facade for every visibility-bearing\n // entity. Keep the row path as a defensive fallback if a future storage\n // mode cannot expose spans.\n const spans = query.value.spans();\n if (spans.ok) {\n for (const span of spans.value) {\n const states = span.get(Visibility).state;\n for (let index = 0; index < span.length; index += 1) {\n visit(span.entities[index] as EntityHandle, states[index] ?? 0);\n }\n }\n return;\n }\n for (const row of query.value) {\n visit(row.entity, row.get(Visibility).state);\n }\n };\n let intentCount = 0;\n let hasAnyHiddenIntent = false;\n visitVisibilityRows((_entity, rawState) => {\n intentCount += 1;\n if (rawState === VisibilityStateValue.hidden) {\n hasAnyHiddenIntent = true;\n }\n });\n\n let resolveEntity: ((entity: EntityHandle) => ResolutionState | undefined) | undefined;\n let hasIntent: ((entity: EntityHandle) => boolean) | undefined;\n const ensureResolver = (): void => {\n if (resolveEntity !== undefined) return;\n const intentByEntity = new Map<EntityHandle, VisibilityState>();\n visitVisibilityRows((entity, rawState) => {\n const intent = visibilityStateFromU32(rawState);\n if (intent !== undefined) {\n intentByEntity.set(entity, intent);\n }\n });\n hasIntent = (entity: EntityHandle): boolean => intentByEntity.has(entity);\n const resolved = new Map<EntityHandle, ResolutionState>();\n const resolving = new Set<EntityHandle>();\n resolveEntity = (entity: EntityHandle): ResolutionState | undefined => {\n const existing = resolved.get(entity);\n if (existing !== undefined) return existing;\n if (resolving.has(entity)) return undefined;\n\n const intent = intentByEntity.get(entity) ?? 'inherited';\n resolving.add(entity);\n\n let result: ResolutionState;\n if (intent === 'hidden') {\n result = { intent, effective: 'hidden', source: 'self' };\n } else if (intent === 'visible') {\n result = { intent, effective: 'visible', source: 'self' };\n } else {\n const parent = hierarchy.getParent(entity);\n const parentResult = parent === undefined ? undefined : resolveEntity?.(parent);\n result =\n parentResult === undefined\n ? { intent, effective: 'visible', source: 'default' }\n : { intent, effective: parentResult.effective, source: 'parent' };\n }\n\n resolving.delete(entity);\n resolved.set(entity, result);\n return result;\n };\n };\n\n const snapshot: VisibilitySnapshot = {\n diagnostics: hierarchy.diagnostics,\n hasAnyIntent: intentCount > 0,\n hasAnyHiddenIntent,\n get(entity: EntityHandle): VisibilityResolution | undefined {\n ensureResolver();\n return hasIntent?.(entity) ? resolveEntity?.(entity) : undefined;\n },\n effective(entity: EntityHandle): 'hidden' | 'visible' {\n ensureResolver();\n return resolveEntity?.(entity)?.effective ?? 'visible';\n },\n };\n return snapshot;\n}\n","import type { EntityHandle, World } from '@forgeax/engine-ecs';\nimport { Time } from '@forgeax/engine-ecs';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport { CloudLayer, type CloudLayerData } from '../components/cloud-layer';\nimport { DirectionalLight } from '../components/directional-light';\nimport { type CloudLayerError, CloudLayerOwnerConflictError } from '../errors/cloud';\nimport { cloudLayerSourceKey, type ValidatedCloudLayer, validateCloudLayer } from './parameters';\n\nexport interface CloudLayerCandidate {\n readonly entityKey: EntityHandle;\n readonly data: CloudLayerData;\n}\n\nexport interface ExtractedCloudLayer {\n readonly status: 'available';\n readonly entityKey: EntityHandle;\n readonly sourceKey: string;\n readonly params: ValidatedCloudLayer;\n readonly worldTimeSeconds: number;\n /** First World-owned sun selected by the same extraction boundary. */\n readonly sunDirection: readonly [number, number, number] | undefined;\n readonly sunRadiance: readonly [number, number, number] | undefined;\n readonly revision: number;\n}\n\n/** Select the one resource owner without creating a second World registry. */\nexport function selectCloudLayerFrame(\n candidates: readonly CloudLayerCandidate[],\n worldTimeSeconds = 0,\n sunDirection: readonly [number, number, number] | undefined = undefined,\n sunRadiance: readonly [number, number, number] | undefined = undefined,\n): Result<ExtractedCloudLayer | undefined, CloudLayerError> {\n if (candidates.length === 0) return ok(undefined);\n if (candidates.length > 1) return err(new CloudLayerOwnerConflictError(candidates.length));\n const candidate = candidates[0];\n if (candidate === undefined) return ok(undefined);\n const validated = validateCloudLayer(candidate.data);\n if (!validated.ok) return validated;\n return ok(\n Object.freeze({\n status: 'available' as const,\n entityKey: candidate.entityKey,\n sourceKey: cloudLayerSourceKey(validated.value),\n params: validated.value,\n worldTimeSeconds: Number.isFinite(worldTimeSeconds) ? Math.max(0, worldTimeSeconds) : 0,\n sunDirection:\n sunDirection === undefined\n ? undefined\n : Object.freeze([...sunDirection] as [number, number, number]),\n sunRadiance:\n sunRadiance === undefined\n ? undefined\n : Object.freeze([...sunRadiance] as [number, number, number]),\n revision: 1,\n }),\n );\n}\n\n/** Read the World-owned component and Time resource at the extraction boundary. */\nexport function extractCloudLayer(\n world: World,\n): Result<ExtractedCloudLayer | undefined, CloudLayerError> {\n const candidates: CloudLayerCandidate[] = [];\n // Older worlds may be rendered without renderComponentsPlugin. The absence\n // of the optional cloud vocabulary is the empty state, not an extraction\n // failure; once the component is registered, query failures remain visible\n // through the surrounding World extraction boundary.\n try {\n const query = world.query({ read: [CloudLayer] });\n if (!query.ok) return ok(undefined);\n for (const row of query.value)\n candidates.push({ entityKey: row.entity, data: row.get(CloudLayer) });\n } catch {\n return ok(undefined);\n }\n let sunDirection: readonly [number, number, number] | undefined;\n let sunRadiance: readonly [number, number, number] | undefined;\n try {\n const query = world.query({ read: [DirectionalLight] });\n if (query.ok) {\n for (const row of query.value) {\n const light = row.get(DirectionalLight);\n const intensity = Number.isFinite(light.intensity) ? Math.max(0, light.intensity) : 0;\n // DirectionalLight stores the outgoing vector (light -> surface),\n // while cloud optical paths integrate from the receiver toward the\n // sun. Keep the extracted cloud direction in that incoming convention\n // so low-sun gating and the GPU `-view.lightDir` path agree.\n sunDirection = [\n -(light.direction[0] ?? 0),\n -(light.direction[1] ?? -1),\n -(light.direction[2] ?? 0),\n ];\n sunRadiance = [\n (light.color[0] ?? 1) * intensity,\n (light.color[1] ?? 1) * intensity,\n (light.color[2] ?? 1) * intensity,\n ];\n break;\n }\n }\n } catch {\n // Optional light vocabulary is absent in camera-only worlds.\n }\n return selectCloudLayerFrame(\n candidates,\n world.getResource(Time).elapsed,\n sunDirection,\n sunRadiance,\n );\n}\n","import { err, ok, type Result } from '@forgeax/engine-types';\nimport { type VolumeError, VolumeOwnerConflictError } from '../errors/render';\nimport {\n MAX_VOLUMETRIC_FOG_OWNERS,\n type ValidatedVolumetricFog,\n type VolumetricFogAuthoring,\n validateVolumetricFog,\n} from './component';\n\nexport type VolumetricFogExtract =\n | { readonly status: 'off' }\n | { readonly status: 'available'; readonly fogs: readonly ValidatedVolumetricFog[] };\n\nexport function extractVolumetricFog(\n inputs: readonly VolumetricFogAuthoring[],\n): Result<VolumetricFogExtract, VolumeError> {\n if (inputs.length === 0) return ok({ status: 'off' });\n if (inputs.length > MAX_VOLUMETRIC_FOG_OWNERS)\n return err(new VolumeOwnerConflictError(inputs.length));\n const fogs: ValidatedVolumetricFog[] = [];\n for (const input of inputs) {\n const validated = validateVolumetricFog(input);\n if (!validated.ok) return validated;\n fogs.push(validated.value);\n }\n return ok({ status: 'available', fogs });\n}\n","// @forgeax/engine-render - Directional CSM projection owner.\n\nimport type { DirectionalShadowQuality } from '../components/directional-shadow-filter';\nimport { directionalShadowQualityFromF32 } from '../components/directional-shadow-filter';\n\n/** Light-space bounds produced by one existing orthographic CSM fit. */\nexport interface DirectionalShadowCascadeFit {\n readonly split: number;\n readonly minX: number;\n readonly maxX: number;\n readonly minY: number;\n readonly maxY: number;\n readonly minZ: number;\n readonly maxZ: number;\n}\n\n/** Host projection sent to the shared View UBO. */\nexport interface DirectionalShadowProjection {\n readonly splitPlanes: Float32Array;\n readonly directionalShadowQuality: DirectionalShadowQuality;\n}\n\n/**\n * Project accepted Directional author facts and the existing CSM fit into the\n * shared split vec4 lanes. `.x` is the split, `.y` is world units per texel,\n * `.z` is the light-space depth span, and `.w` is reserved for the ABI.\n */\nexport function projectDirectionalShadow(\n fits: readonly DirectionalShadowCascadeFit[],\n mapSize: number,\n shadowFilter: number,\n shadowAngularRadius: number,\n maxPenumbraTexels: number,\n): DirectionalShadowProjection | undefined {\n if (!Number.isFinite(mapSize) || mapSize < 1) return undefined;\n const directionalShadowQuality = directionalShadowQualityFromF32(\n shadowFilter,\n shadowAngularRadius,\n maxPenumbraTexels,\n );\n if (directionalShadowQuality === undefined) return undefined;\n\n const splitPlanes = new Float32Array(16);\n for (let index = 0; index < fits.length && index < 4; index += 1) {\n const fit = fits[index];\n if (fit === undefined) continue;\n const width = Math.abs(fit.maxX - fit.minX);\n const height = Math.abs(fit.maxY - fit.minY);\n const depth = Math.abs(fit.maxZ - fit.minZ);\n const worldUnitsPerTexel = Math.max(width, height, Number.EPSILON) / mapSize;\n const lightDepthWorldSpan = Math.max(depth, Number.EPSILON);\n if (!Number.isFinite(worldUnitsPerTexel) || !Number.isFinite(lightDepthWorldSpan)) {\n return undefined;\n }\n const lane = index * 4;\n splitPlanes[lane] = fit.split;\n splitPlanes[lane + 1] = worldUnitsPerTexel;\n splitPlanes[lane + 2] = lightDepthWorldSpan;\n }\n return { splitPlanes, directionalShadowQuality };\n}\n","// @forgeax/engine-runtime - glyphTextLayoutSystem\n// (feat-20260531-world-space-msdf-text-rendering M4 / w18).\n//\n// The named ECS system that turns `GlyphText` authoring data into a rendered\n// world-space label (plan-strategy D-2). A Renderer attaches it to World's\n// internal render-derived phase,\n// so a freshly-spawned `GlyphText` entity gains its `MeshFilter` +\n// `MeshRenderer` before final publication resolves transforms and the same frame's\n// read-only render walk reaches it. Per `GlyphText` entity:\n//\n// 1. First observation (entity has no `MeshFilter`): resolve the FontAsset,\n// run `layoutGlyphText` (w15) + `bakeGlyphMesh` (w17), then attach\n// `MeshFilter` + `MeshRenderer` (AC-07). The attach uses the same\n// immediate `world.addComponent` path as `spriteAnimationTickSystem`'s\n// auto-add (the system runs ahead of the render walk in the same frame).\n// 2. Dirty (text / fontSize / color changed since last bake): re-layout and\n// `updateMesh` IN PLACE (plan-strategy D-1) -- never re-`register`, never\n// re-attach. The AssetRegistry size stays constant (AC-08; avoids the\n// unbounded growth R-1 would otherwise cause).\n//\n// D-8 concurrency: at most 8 distinct FontAsset handles may be active in one\n// frame. The system resets the per-frame tracker (resetFontConcurrency) at the\n// top and tracks each distinct font; the 9th distinct font surfaces a\n// structured `TextError('font-concurrency-exceeded')` (it does NOT silently\n// evict the oldest font).\n//\n// The system does NOT modify `pick.ts` (D-5): the baked mesh carries a local\n// AABB and the entity carries MeshFilter + MeshRenderer + Transform, so the\n// existing `pick()` raycast walk catches it for free.\n\nimport { resolveAssetHandle } from '@forgeax/engine-assets-runtime';\nimport type { EntityHandle, World } from '@forgeax/engine-ecs';\nimport { PROCEDURAL_FLOATS_PER_VERTEX } from '@forgeax/engine-geometry';\nimport {\n bakeGlyphMesh,\n conservativeCubeAabb,\n layoutGlyphText,\n resetFontConcurrency,\n trackFontConcurrency,\n} from '@forgeax/engine-graphics-extras';\nimport type { FontAsset, Handle, MaterialAsset, MeshAsset, Submesh } from '@forgeax/engine-types';\nimport { err, ok, type Result, TextError, toShared, unpackSlot } from '@forgeax/engine-types';\nimport { MeshFilter, MeshRenderer } from './components';\nimport { GlyphText } from './components/glyph-text';\nimport type { GpuResidencyCache } from './device/gpu-residency';\n\n// Per-entity bake bookkeeping: the baked mesh handle id + the authoring\n// signature it was baked from. A WeakMap owns one cache per World and each\n// entry is bounded by entity slot while retaining the full generation-bearing\n// EntityHandle, so slot reuse replaces stale state instead of aliasing it or\n// growing one historical entry per generation.\ninterface BakeRecord {\n readonly meshHandle: Handle<'MeshAsset', 'shared'>;\n signature: string;\n /** The MeshRenderer.material handle assigned on first observation. */\n readonly materialHandle: Handle<'MaterialAsset', 'shared'>;\n}\ninterface BakeCacheEntry {\n readonly handle: EntityHandle;\n readonly record: BakeRecord;\n}\nlet bakeCache = new WeakMap<World, Map<number, BakeCacheEntry>>();\n\n// One current material producer handle per GlyphText entity slot. Continuous\n// tint edits replace and release the previous producer instead of growing a\n// historical color-key cache.\nlet materialCache = new WeakMap<World, Map<number, Handle<'MaterialAsset', 'shared'>>>();\nlet liveGlyphSlots = new WeakMap<World, Set<number>>();\n\nfunction entitySlot(entity: EntityHandle): number {\n return unpackSlot(entity as number);\n}\n\n/** Clear the per-entity bake + per-font material caches (test isolation). */\nexport function resetGlyphBakeCache(): void {\n bakeCache = new WeakMap();\n materialCache = new WeakMap();\n liveGlyphSlots = new WeakMap();\n}\n\nfunction worldBakeCache(world: World): Map<number, BakeCacheEntry> {\n let cache = bakeCache.get(world);\n if (cache === undefined) {\n cache = new Map();\n bakeCache.set(world, cache);\n }\n return cache;\n}\n\nfunction worldMaterialCache(world: World): Map<number, Handle<'MaterialAsset', 'shared'>> {\n let cache = materialCache.get(world);\n if (cache === undefined) {\n cache = new Map();\n materialCache.set(world, cache);\n }\n return cache;\n}\n\n/** Release renderer-derived producer refs at GlyphText removal time. */\nfunction releaseGlyphProducers(world: World, entity: EntityHandle): void {\n const slot = entitySlot(entity);\n const bake = bakeCache.get(world)?.get(slot);\n if (bake?.handle === entity) {\n world.sharedRefs.release(bake.record.meshHandle);\n bakeCache.get(world)?.delete(slot);\n }\n const material = materialCache.get(world)?.get(slot);\n if (material !== undefined) {\n world.sharedRefs.release(material);\n materialCache.get(world)?.delete(slot);\n }\n}\n\n/** Remove stale renderer-derived state when a previously baked font is rejected. */\nfunction clearRejectedGlyphState(world: World, entity: EntityHandle): void {\n const slot = entitySlot(entity);\n const bake = bakeCache.get(world)?.get(slot);\n if (bake?.handle !== entity) return;\n\n // These components are owned by this system only when the matching bake\n // record exists. Removing them before releasing the producer refs leaves no\n // stale draw/material handles and lets the next valid frame take the normal\n // first-observation path.\n if (world.get(entity, MeshFilter).ok) world.removeComponent(entity, MeshFilter);\n if (world.get(entity, MeshRenderer).ok) world.removeComponent(entity, MeshRenderer);\n releaseGlyphProducers(world, entity);\n}\n\n// Premultiplied-alpha blend (mirrors the sprite path, plan D-7). The\n// `forgeax::msdf-text` fragment emits premultiplied RGB so the over-composite\n// math (`dst' = src + dst * (1 - src.a)`) is direct. The pass rides the\n// Transparent queue (3000) so text composites after opaque geometry while\n// honoring depth occlusion (depthCompare less-equal, depthWrite off via the\n// material-shader pipeline render state).\nconst MSDF_TEXT_BLEND = {\n color: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha', operation: 'add' },\n alpha: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha', operation: 'add' },\n} as const;\n\ninterface GlyphTextData {\n readonly fontHandle: number;\n readonly text: string;\n readonly fontSize: number;\n // feat-20260709 M3: color collapsed into one inline array<f32,4>; the\n // world.get read path materialises it as a Float32Array (color[0..3] = rgba).\n readonly color: ArrayLike<number>;\n}\n\n/** @internal archetype-walk view (same shape reached for in render-system-extract). */\n/**\n * Lay out + bake every `GlyphText` entity, attaching MeshFilter + MeshRenderer\n * on first observation and re-baking in place on a text / size / color change.\n *\n * @param world The ECS world holding the GlyphText entities.\n * @returns `ok(void)` on a clean pass, or `err(TextError)` carrying the FIRST\n * structured failure (currently only `font-concurrency-exceeded`). Healthy\n * entities observed before the failing one are still baked.\n */\nexport function glyphTextLayoutSystem(\n world: World,\n gpuStore: Pick<GpuResidencyCache, 'updateMesh'>,\n): Result<void, TextError> {\n resetFontConcurrency();\n\n // No GlyphText entity in this World -> empty query -> no-op pass. The\n // ECS query is the single owner of component presence and entity iteration;\n // the renderer does not reach into archetype storage internals.\n const entities = collectGlyphEntities(world);\n const live = liveGlyphSlots.get(world) ?? new Set<number>();\n live.clear();\n for (const entity of entities) live.add(entitySlot(entity));\n liveGlyphSlots.set(world, live);\n for (const entry of worldBakeCache(world).values()) {\n if (!live.has(entitySlot(entry.handle))) releaseGlyphProducers(world, entry.handle);\n }\n\n let firstError: TextError | null = null;\n for (const entity of entities) {\n const error = processEntity(world, gpuStore, entity);\n if (error !== null && firstError === null) firstError = error;\n }\n\n if (firstError !== null) return err(firstError);\n return ok(undefined);\n}\n\n/** Collect every Entity handle carrying GlyphText (single archetype walk). */\nfunction collectGlyphEntities(world: World): EntityHandle[] {\n const entities: EntityHandle[] = [];\n const query = world.query({ read: [GlyphText] }).unwrap();\n for (const row of query) {\n entities.push(row.entity);\n }\n return entities;\n}\n\n/**\n * Process one GlyphText entity. Returns a TextError when the concurrency limit\n * is exceeded after clearing stale derived state; returns null otherwise.\n */\nfunction processEntity(\n world: World,\n gpuStore: Pick<GpuResidencyCache, 'updateMesh'>,\n entity: EntityHandle,\n): TextError | null {\n const gtRes = world.get(entity, GlyphText);\n if (!gtRes.ok) return null;\n const gt = gtRes.value;\n\n // Unresolved font handle (zero sentinel) -> skip (entity not yet wired).\n if (gt.fontHandle === 0) return null;\n\n // D-8 concurrency: track this distinct font; the 9th throws a TextError.\n try {\n trackFontConcurrency(gt.fontHandle);\n } catch (e) {\n if (e instanceof TextError) {\n clearRejectedGlyphState(world, entity);\n return e;\n }\n throw e;\n }\n\n const fontRes = resolveAssetHandle<FontAsset>(world, asFontHandle(gt.fontHandle));\n if (!fontRes.ok) return null; // font not registered yet -> skip silently\n const font = fontRes.value;\n\n const signature = signatureOf(gt);\n const entityCache = worldBakeCache(world);\n const slot = entitySlot(entity);\n const cachedEntry = entityCache.get(slot);\n if (cachedEntry !== undefined && cachedEntry.handle !== entity) {\n world.sharedRefs.release(cachedEntry.record.meshHandle);\n const staleMaterial = worldMaterialCache(world).get(slot);\n if (staleMaterial !== undefined) {\n world.sharedRefs.release(staleMaterial);\n worldMaterialCache(world).delete(slot);\n }\n entityCache.delete(slot);\n }\n const cached = cachedEntry?.handle === entity ? cachedEntry.record : undefined;\n\n // Dirty path: same entity already baked, but the authoring signature changed.\n if (cached !== undefined) {\n ensureGlyphMeshMaterialSlots(world, cached.meshHandle);\n if (cached.signature === signature) return null; // clean -> nothing to do\n const layout = layoutGlyphText(font, gt.text, gt.fontSize);\n // feat-20260601-device/gpu-residency-extraction M1: in-place GPU mesh update\n // moved to the store. The mesh became GPU-resident on the first render\n // frame's `ensureResident` pull; the dirty re-layout overwrites those\n // buffers in place (a no-op if not yet resident -- the next render's\n // ensureResident then uploads the latest registered POD).\n const meshHandle = cached.meshHandle;\n const submeshes = [\n {\n indexOffset: 0,\n indexCount: layout.indices.length,\n vertexCount: layout.vertices.length / PROCEDURAL_FLOATS_PER_VERTEX,\n topology: 'triangle-list',\n materialSlot: 0,\n },\n ] satisfies readonly Submesh[];\n // A dynamic label can begin empty, so its first bake has a degenerate AABB.\n // Keep the shared MeshAsset's culling/picking bounds in lockstep with the\n // dirty layout; otherwise the GPU buffers update but the render walk still\n // rejects the label as an empty mesh.\n const mesh = world.sharedRefs.resolve<'MeshAsset', MeshAsset>(meshHandle);\n if (mesh.ok) {\n const aabb = conservativeCubeAabb(layout.radius);\n // Keep both sides of the pull boundary coherent. A zero-glyph first\n // bake may have no resident GPU buffers yet, so updating only the GPU\n // store would lose the new text on the next ensureResident pull.\n Object.assign(mesh.value, {\n vertices: layout.vertices,\n indices: layout.indices,\n submeshes,\n materialSlots: [{ slotName: 'Default' }],\n aabb,\n });\n }\n gpuStore.updateMesh(meshHandle, layout.vertices, layout.indices, 0, submeshes);\n // A color change replaces the material payload at this entity's stable\n // derived slot and re-binds the new producer handle in place.\n const materialId = resolveTextMaterial(world, gt, font, slot);\n if (materialId !== cached.materialHandle) {\n world.set(entity, MeshRenderer, {\n materials: [materialId],\n });\n }\n entityCache.set(slot, {\n handle: entity,\n record: {\n meshHandle: cached.meshHandle,\n signature,\n materialHandle: materialId,\n },\n });\n return null;\n }\n\n // First-observation path. If this entity already carries a MeshFilter (e.g.\n // the bake cache was reset between frames), skip without re-baking. `world.get`\n // returns err(component-not-present) (never throws) when the column is absent,\n // so the column probe needs no registration guard (feat-20260602).\n const existingFilter = world.get(entity, MeshFilter);\n if (existingFilter.ok) {\n ensureGlyphMeshMaterialSlots(world, existingFilter.value.assetHandle);\n return null;\n }\n\n const layout = layoutGlyphText(font, gt.text, gt.fontSize);\n const bake = bakeGlyphMesh(world, layout);\n if (!bake.ok) return null; // register fail-fast (should not happen for w15 output)\n\n // F-1: resolve the entity-owned MSDF MaterialAsset so the\n // `forgeax::msdf-text` shader + atlas texture + sampler are bound to this\n // text entity (plan D-7). Without this the MeshRenderer would carry material\n // handle 0 -> default mid-grey unlit, and the atlas would never be sampled.\n const materialId = resolveTextMaterial(world, gt, font, slot);\n\n world.addComponent(entity, {\n component: MeshFilter,\n data: { assetHandle: bake.value.handle },\n });\n world.addComponent(entity, {\n component: MeshRenderer,\n data: { materials: [materialId] },\n });\n entityCache.set(slot, {\n handle: entity,\n record: {\n meshHandle: bake.value.handle,\n signature,\n materialHandle: materialId,\n },\n });\n return null;\n}\n\nexport function ensureGlyphMeshMaterialSlots(\n world: World,\n meshHandle: Handle<'MeshAsset', 'shared'>,\n): void {\n const mesh = world.sharedRefs.resolve<'MeshAsset', MeshAsset>(meshHandle);\n if (mesh.ok && !Array.isArray(mesh.value.materialSlots)) {\n Object.assign(mesh.value, { materialSlots: [{ slotName: 'Default' }] });\n }\n}\n\n/**\n * Build the MSDF text MaterialAsset for one World/entity slot and\n * return its raw unmanaged handle id. The material carries a single\n * Transparent-queue pass on the `forgeax::msdf-text` shader with premultiplied\n * blend, and values binding the tint color, packed atlas distance data, and an\n * embedded atlas texture reference (the record stage supplies the sampler).\n * HDR tint components (>1) flow through unchanged so bloom-enabled cameras\n * pick up bright text (AC-12).\n */\nfunction resolveTextMaterial(\n world: World,\n gt: GlyphTextData,\n font: FontAsset,\n slot: number,\n): Handle<'MaterialAsset', 'shared'> {\n const cache = worldMaterialCache(world);\n const material = {\n kind: 'material',\n passes: [\n {\n name: 'text',\n program: { module: 'forgeax::msdf-text' },\n renderState: {\n ...{\n blend: MSDF_TEXT_BLEND as never,\n cullMode: 'none',\n depthWriteEnabled: false,\n depthCompare: 'less-equal',\n },\n tags: { LightMode: 'Forward' },\n queue: 3000,\n },\n },\n ],\n values: {\n tintColor: [gt.color[0] ?? 1, gt.color[1] ?? 1, gt.color[2] ?? 1, gt.color[3] ?? 1],\n distanceRange: [\n font.common.distanceRange,\n font.common.atlasWidth,\n font.common.atlasHeight,\n 0,\n ],\n baseColorTexture: { texture: font.atlas },\n },\n parameters: [\n { name: 'tintColor', type: 'color', default: [1, 1, 1, 1] },\n { name: 'distanceRange', type: 'vec4', default: [4, 512, 512, 0] },\n { name: 'baseColorTexture', type: 'texture' },\n { name: 'metallicRoughnessTexture', type: 'texture', optional: true },\n { name: 'normalTexture', type: 'texture', optional: true },\n ],\n } satisfies MaterialAsset;\n const id = world.allocSharedRef('MaterialAsset', material);\n const previous = cache.get(slot);\n cache.set(slot, id);\n if (previous !== undefined && previous !== id) {\n world.sharedRefs.release(previous);\n }\n return id;\n}\n\nfunction signatureOf(gt: GlyphTextData): string {\n return `${gt.fontHandle}|${gt.fontSize}|${gt.text}|${gt.color[0]},${gt.color[1]},${gt.color[2]},${gt.color[3]}`;\n}\n\n// Handle bridges: GlyphText.fontHandle / cached mesh ids are packed u32 values;\n// AssetRegistry expects branded Handles. The brand is a compile-time phantom\n// (runtime value is the raw number), so a cast is the canonical bridge\n// (mirrors pick.ts toShared).\nfunction asFontHandle(raw: number): Handle<'FontAsset', 'shared'> {\n return toShared<'FontAsset'>(raw);\n}\n","import type { Mat4Like } from '@forgeax/engine-math';\n\n// `fingerprintNumericArray` runs on every bounds-cache lookup. Keep the bit\n// reinterpretation scratch outside the hot path so a cache hit does not\n// allocate a pair of typed arrays for each retained render slot.\nconst fingerprintScalar = new Float32Array(1);\nconst fingerprintBits = new Uint32Array(fingerprintScalar.buffer);\n\n/**\n * Inputs owned by the render extract/persistent-scene boundary. Bounds are\n * deliberately derived here instead of being added to the author-facing\n * `Instances` component or written back to a Pack asset.\n */\nexport interface DerivedInstancesUnionBoundsInput {\n readonly meshAabb: ArrayLike<number> | undefined;\n readonly entityWorld: ArrayLike<number>;\n readonly transforms: ArrayLike<number> | undefined;\n}\n\n/**\n * Renderer-owned cache key. Each generation is supplied by the owner that can\n * observe that mutation: mesh/AABB publication, entity world transform, and\n * the packed instance matrix array respectively.\n */\nexport interface InstanceBoundsCacheKey {\n /** Optional scene/world scope for composite scenes; omitted for standalone tests. */\n readonly worldId?: number;\n readonly entityKey: number;\n readonly meshGeneration: number;\n readonly transformGeneration: number;\n readonly matrixGeneration: number;\n}\n\nexport type InstanceBoundsCacheInput = InstanceBoundsCacheKey & DerivedInstancesUnionBoundsInput;\n\n/**\n * Stable bitwise fingerprint for detached numeric facts used by the cache.\n * Float32 bits are hashed rather than decimal text so a real matrix/AABB\n * change invalidates the projection without keeping another mutable ledger.\n */\nexport function fingerprintNumericArray(values: ArrayLike<number>): number {\n let hash = 0x811c9dc5;\n for (let index = 0; index < values.length; index += 1) {\n fingerprintScalar[0] = Number(values[index]);\n hash = Math.imul(hash ^ (fingerprintBits[0] ?? 0), 0x01000193) >>> 0;\n }\n return hash >>> 0;\n}\n\nfunction finiteAabb(aabb: ArrayLike<number> | undefined): aabb is ArrayLike<number> {\n if (aabb === undefined || aabb.length < 6) return false;\n const minX = aabb[0] as number;\n const minY = aabb[1] as number;\n const minZ = aabb[2] as number;\n const maxX = aabb[3] as number;\n const maxY = aabb[4] as number;\n const maxZ = aabb[5] as number;\n return (\n Number.isFinite(minX) &&\n Number.isFinite(minY) &&\n Number.isFinite(minZ) &&\n Number.isFinite(maxX) &&\n Number.isFinite(maxY) &&\n Number.isFinite(maxZ) &&\n minX <= maxX &&\n minY <= maxY &&\n minZ <= maxZ\n );\n}\n\nfunction finiteMatrix(matrix: ArrayLike<number>): matrix is Mat4Like {\n if (matrix.length < 16) return false;\n for (let index = 0; index < 16; index += 1) {\n if (!Number.isFinite(matrix[index] as number)) return false;\n }\n return true;\n}\n\nfunction multiplyMat4(\n out: Float32Array,\n left: ArrayLike<number>,\n right: ArrayLike<number>,\n rightOffset = 0,\n): void {\n for (let column = 0; column < 4; column += 1) {\n const rightColumn = rightOffset + column * 4;\n const right0 = Number(right[rightColumn] ?? 0);\n const right1 = Number(right[rightColumn + 1] ?? 0);\n const right2 = Number(right[rightColumn + 2] ?? 0);\n const right3 = Number(right[rightColumn + 3] ?? 0);\n const outOffset = column * 4;\n out[outOffset] =\n Number(left[0] ?? 0) * right0 +\n Number(left[4] ?? 0) * right1 +\n Number(left[8] ?? 0) * right2 +\n Number(left[12] ?? 0) * right3;\n out[outOffset + 1] =\n Number(left[1] ?? 0) * right0 +\n Number(left[5] ?? 0) * right1 +\n Number(left[9] ?? 0) * right2 +\n Number(left[13] ?? 0) * right3;\n out[outOffset + 2] =\n Number(left[2] ?? 0) * right0 +\n Number(left[6] ?? 0) * right1 +\n Number(left[10] ?? 0) * right2 +\n Number(left[14] ?? 0) * right3;\n out[outOffset + 3] =\n Number(left[3] ?? 0) * right0 +\n Number(left[7] ?? 0) * right1 +\n Number(left[11] ?? 0) * right2 +\n Number(left[15] ?? 0) * right3;\n }\n}\n\nfunction finiteMatrixAt(values: ArrayLike<number>, offset: number): boolean {\n if (values.length - offset < 16) return false;\n for (let index = 0; index < 16; index += 1) {\n if (!Number.isFinite(values[offset + index] as number)) return false;\n }\n return true;\n}\n\nfunction isAffine(matrix: ArrayLike<number>): boolean {\n return (\n (matrix[3] as number) === 0 &&\n (matrix[7] as number) === 0 &&\n (matrix[11] as number) === 0 &&\n (matrix[15] as number) === 1\n );\n}\n\nfunction includeBox(\n out: Float32Array,\n candidate: ArrayLike<number>,\n initialized: boolean,\n): boolean {\n const minX = candidate[0] as number;\n const minY = candidate[1] as number;\n const minZ = candidate[2] as number;\n const maxX = candidate[3] as number;\n const maxY = candidate[4] as number;\n const maxZ = candidate[5] as number;\n if (!initialized) {\n out[0] = minX;\n out[1] = minY;\n out[2] = minZ;\n out[3] = maxX;\n out[4] = maxY;\n out[5] = maxZ;\n return true;\n }\n if (minX < (out[0] ?? Number.POSITIVE_INFINITY)) out[0] = minX;\n if (minY < (out[1] ?? Number.POSITIVE_INFINITY)) out[1] = minY;\n if (minZ < (out[2] ?? Number.POSITIVE_INFINITY)) out[2] = minZ;\n if (maxX > (out[3] ?? Number.NEGATIVE_INFINITY)) out[3] = maxX;\n if (maxY > (out[4] ?? Number.NEGATIVE_INFINITY)) out[4] = maxY;\n if (maxZ > (out[5] ?? Number.NEGATIVE_INFINITY)) out[5] = maxZ;\n return true;\n}\n\n/** Transform an AABB without per-instance arrays or corner tuples. */\nfunction transformAabb(\n out: Float32Array,\n local: ArrayLike<number>,\n matrix: ArrayLike<number>,\n): boolean {\n const minX = local[0] as number;\n const minY = local[1] as number;\n const minZ = local[2] as number;\n const maxX = local[3] as number;\n const maxY = local[4] as number;\n const maxZ = local[5] as number;\n const centerX = (minX + maxX) * 0.5;\n const centerY = (minY + maxY) * 0.5;\n const centerZ = (minZ + maxZ) * 0.5;\n const extentX = (maxX - minX) * 0.5;\n const extentY = (maxY - minY) * 0.5;\n const extentZ = (maxZ - minZ) * 0.5;\n\n if (isAffine(matrix)) {\n const centerWorldX =\n (matrix[0] as number) * centerX +\n (matrix[4] as number) * centerY +\n (matrix[8] as number) * centerZ +\n (matrix[12] as number);\n const centerWorldY =\n (matrix[1] as number) * centerX +\n (matrix[5] as number) * centerY +\n (matrix[9] as number) * centerZ +\n (matrix[13] as number);\n const centerWorldZ =\n (matrix[2] as number) * centerX +\n (matrix[6] as number) * centerY +\n (matrix[10] as number) * centerZ +\n (matrix[14] as number);\n const extentWorldX =\n Math.abs(matrix[0] as number) * extentX +\n Math.abs(matrix[4] as number) * extentY +\n Math.abs(matrix[8] as number) * extentZ;\n const extentWorldY =\n Math.abs(matrix[1] as number) * extentX +\n Math.abs(matrix[5] as number) * extentY +\n Math.abs(matrix[9] as number) * extentZ;\n const extentWorldZ =\n Math.abs(matrix[2] as number) * extentX +\n Math.abs(matrix[6] as number) * extentY +\n Math.abs(matrix[10] as number) * extentZ;\n out[0] = centerWorldX - extentWorldX;\n out[1] = centerWorldY - extentWorldY;\n out[2] = centerWorldZ - extentWorldZ;\n out[3] = centerWorldX + extentWorldX;\n out[4] = centerWorldY + extentWorldY;\n out[5] = centerWorldZ + extentWorldZ;\n return finiteAabb(out);\n }\n\n // Projective/non-affine matrices need the reference corner route. A w\n // interval crossing zero is unbounded, so explicitly return no-cull rather\n // than pretending the finite corner samples enclose the volume.\n let minimumW = Number.POSITIVE_INFINITY;\n let maximumW = Number.NEGATIVE_INFINITY;\n for (let corner = 0; corner < 8; corner += 1) {\n const x = (corner & 1) === 0 ? minX : maxX;\n const y = (corner & 2) === 0 ? minY : maxY;\n const z = (corner & 4) === 0 ? minZ : maxZ;\n const w =\n (matrix[3] as number) * x +\n (matrix[7] as number) * y +\n (matrix[11] as number) * z +\n (matrix[15] as number);\n if (!Number.isFinite(w)) return false;\n if (w < minimumW) minimumW = w;\n if (w > maximumW) maximumW = w;\n }\n if (minimumW <= 0 && maximumW >= 0) return false;\n\n let unionMinX = Number.POSITIVE_INFINITY;\n let unionMinY = Number.POSITIVE_INFINITY;\n let unionMinZ = Number.POSITIVE_INFINITY;\n let unionMaxX = Number.NEGATIVE_INFINITY;\n let unionMaxY = Number.NEGATIVE_INFINITY;\n let unionMaxZ = Number.NEGATIVE_INFINITY;\n for (let corner = 0; corner < 8; corner += 1) {\n const x = (corner & 1) === 0 ? minX : maxX;\n const y = (corner & 2) === 0 ? minY : maxY;\n const z = (corner & 4) === 0 ? minZ : maxZ;\n const rawX =\n (matrix[0] as number) * x +\n (matrix[4] as number) * y +\n (matrix[8] as number) * z +\n (matrix[12] as number);\n const rawY =\n (matrix[1] as number) * x +\n (matrix[5] as number) * y +\n (matrix[9] as number) * z +\n (matrix[13] as number);\n const rawZ =\n (matrix[2] as number) * x +\n (matrix[6] as number) * y +\n (matrix[10] as number) * z +\n (matrix[14] as number);\n const w =\n (matrix[3] as number) * x +\n (matrix[7] as number) * y +\n (matrix[11] as number) * z +\n (matrix[15] as number);\n const projectedX = rawX / w;\n const projectedY = rawY / w;\n const projectedZ = rawZ / w;\n if (\n !Number.isFinite(projectedX) ||\n !Number.isFinite(projectedY) ||\n !Number.isFinite(projectedZ)\n ) {\n return false;\n }\n if (projectedX < unionMinX) unionMinX = projectedX;\n if (projectedY < unionMinY) unionMinY = projectedY;\n if (projectedZ < unionMinZ) unionMinZ = projectedZ;\n if (projectedX > unionMaxX) unionMaxX = projectedX;\n if (projectedY > unionMaxY) unionMaxY = projectedY;\n if (projectedZ > unionMaxZ) unionMaxZ = projectedZ;\n }\n out[0] = unionMinX;\n out[1] = unionMinY;\n out[2] = unionMinZ;\n out[3] = unionMaxX;\n out[4] = unionMaxY;\n out[5] = unionMaxZ;\n return finiteAabb(out);\n}\n\n/**\n * Derive the world-space AABB enclosing every instance of a mesh.\n *\n * `undefined` is a conservative signal: the caller must skip CPU culling\n * when an input is missing, malformed, or empty. This prevents an empty\n * `Instances` row from becoming a synthetic identity draw/bounds candidate.\n */\nexport function deriveInstancesUnionBounds(\n input: DerivedInstancesUnionBoundsInput,\n): Float32Array | undefined {\n const { meshAabb, entityWorld, transforms } = input;\n if (!finiteAabb(meshAabb) || !finiteMatrix(entityWorld) || transforms === undefined) {\n return undefined;\n }\n if (transforms.length === 0 || transforms.length % 16 !== 0) return undefined;\n const local = meshAabb;\n const union = new Float32Array(6);\n const composed = new Float32Array(16);\n const transformed = new Float32Array(6);\n let initialized = false;\n for (let offset = 0; offset < transforms.length; offset += 16) {\n if (!finiteMatrixAt(transforms, offset)) return undefined;\n multiplyMat4(composed, entityWorld, transforms, offset);\n if (!finiteMatrix(composed) || !transformAabb(transformed, local, composed)) return undefined;\n initialized = includeBox(union, transformed, initialized);\n }\n return initialized && finiteAabb(union) ? union : undefined;\n}\n\ninterface InstanceBoundsCacheEntry extends InstanceBoundsCacheKey {\n readonly bounds: Float32Array | undefined;\n}\n\nexport interface InstanceBoundsCacheInspection {\n readonly hits: number;\n readonly misses: number;\n readonly derives: number;\n readonly invalidations: number;\n}\n\n/**\n * Small renderer-owned per-entity cache. A changed generation replaces the\n * entry atomically; packed-id reuse is safe when its owner supplies a new\n * generation (the normal RenderScene slot generation contract).\n */\nexport class InstanceBoundsCache {\n private readonly entries = new Map<string, InstanceBoundsCacheEntry>();\n private hits = 0;\n private misses = 0;\n private derives = 0;\n private invalidations = 0;\n\n private key(input: Pick<InstanceBoundsCacheKey, 'worldId' | 'entityKey'>): string {\n return `${input.worldId === undefined ? '' : `${input.worldId}:`}${input.entityKey}`;\n }\n\n get(input: InstanceBoundsCacheInput): Float32Array | undefined {\n const previous = this.entries.get(this.key(input));\n if (\n previous !== undefined &&\n previous.meshGeneration === input.meshGeneration &&\n previous.transformGeneration === input.transformGeneration &&\n previous.matrixGeneration === input.matrixGeneration\n ) {\n this.hits += 1;\n return previous.bounds;\n }\n this.misses += 1;\n this.derives += 1;\n const bounds = deriveInstancesUnionBounds(input);\n this.entries.set(this.key(input), {\n ...(input.worldId === undefined ? {} : { worldId: input.worldId }),\n entityKey: input.entityKey,\n meshGeneration: input.meshGeneration,\n transformGeneration: input.transformGeneration,\n matrixGeneration: input.matrixGeneration,\n bounds,\n });\n return bounds;\n }\n\n invalidate(entityKey?: number, worldId?: number): void {\n if (entityKey === undefined) {\n if (this.entries.size > 0) this.invalidations += this.entries.size;\n this.entries.clear();\n } else {\n if (\n this.entries.delete(this.key({ entityKey, ...(worldId === undefined ? {} : { worldId }) }))\n ) {\n this.invalidations += 1;\n }\n }\n }\n\n inspect(): InstanceBoundsCacheInspection {\n return {\n hits: this.hits,\n misses: this.misses,\n derives: this.derives,\n invalidations: this.invalidations,\n };\n }\n}\n","import type { PointsLinesStyle } from './snapshot';\n\n/**\n * Expands the local culling envelope by the maximum screen-space raster\n * radius. The shader applies the exact physical-pixel offset; this envelope\n * is deliberately conservative so transformed edge primitives are retained.\n */\nexport function expandPointsLinesBounds(\n bounds: ArrayLike<number>,\n style: PointsLinesStyle | undefined,\n): Float32Array {\n if (bounds.length < 6 || style === undefined) return new Float32Array(bounds);\n const marginPx = style.kind === 'points' ? style.sizePx * 0.5 : style.widthPx * 0.5;\n if (!Number.isFinite(marginPx) || marginPx <= 0) return new Float32Array(bounds);\n return new Float32Array([\n (bounds[0] ?? 0) - marginPx,\n (bounds[1] ?? 0) - marginPx,\n (bounds[2] ?? 0) - marginPx,\n (bounds[3] ?? 0) + marginPx,\n (bounds[4] ?? 0) + marginPx,\n (bounds[5] ?? 0) + marginPx,\n ]);\n}\n","import type { TextureAsset } from '@forgeax/engine-types';\nimport { COOKIE_SLICE_SIZE } from './resources';\n\nexport interface SpotModifierFactors {\n readonly brdf: number;\n readonly range: number;\n readonly cone: number;\n readonly ies?: number | undefined;\n readonly cookie?: number | undefined;\n readonly shadow: number;\n}\n\nexport interface IesCoordinates {\n readonly azimuth: number;\n readonly elevation: number;\n}\n\nexport interface CookieUv {\n readonly u: number;\n readonly v: number;\n}\n\n/**\n * The fixed GPU representation consumed by the extended-lighting Cookie\n * array. The matrix is deliberately keyed by Cookie slice rather than by\n * light: it carries only the source texture aspect correction. The shader\n * still owns the light-local basis, roll, and outer-cone projection, so one\n * Cookie can be shared by Spots with different directions or cone angles.\n */\nexport interface CookieProjection {\n readonly data: Uint8Array;\n readonly matrix: Float32Array;\n readonly aspect: number;\n}\n\nconst DEG_TO_RAD = Math.PI / 180;\n\nconst COOKIE_PROJECTION_CACHE = new WeakMap<TextureAsset, CookieProjection | null>();\n\nfunction srgbToLinear(value: number): number {\n return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;\n}\n\nfunction clamp01(value: number): number {\n return Math.min(1, Math.max(0, value));\n}\n\nfunction sourceChannel(asset: TextureAsset, x: number, y: number, channel: number): number {\n const offset = (y * asset.shape.extent.width + x) * 4 + channel;\n const encoded = (asset.data[offset] ?? 0) / 255;\n return channel < 3 && asset.colorSpace === 'srgb' ? srgbToLinear(encoded) : encoded;\n}\n\nfunction sampleSourceChannel(asset: TextureAsset, x: number, y: number, channel: number): number {\n const sourceX = clamp01((x + 0.5) / COOKIE_SLICE_SIZE) * (asset.shape.extent.width - 1);\n const sourceY = clamp01((y + 0.5) / COOKIE_SLICE_SIZE) * (asset.shape.extent.height - 1);\n const x0 = Math.floor(sourceX);\n const y0 = Math.floor(sourceY);\n const x1 = Math.min(asset.shape.extent.width - 1, x0 + 1);\n const y1 = Math.min(asset.shape.extent.height - 1, y0 + 1);\n const tx = sourceX - x0;\n const ty = sourceY - y0;\n const top =\n sourceChannel(asset, x0, y0, channel) * (1 - tx) + sourceChannel(asset, x1, y0, channel) * tx;\n const bottom =\n sourceChannel(asset, x0, y1, channel) * (1 - tx) + sourceChannel(asset, x1, y1, channel) * tx;\n return top * (1 - ty) + bottom * ty;\n}\n\n/**\n * Project a filterable 2D RGBA Cookie into the renderer's fixed linear\n * 256x256 array slice. This is a producer-boundary operation and is cached by\n * the immutable TextureAsset object, so the frame path never decodes or\n * resamples the source repeatedly.\n */\nexport function prepareCookieProjection(asset: TextureAsset): CookieProjection | undefined {\n if (COOKIE_PROJECTION_CACHE.has(asset)) {\n return COOKIE_PROJECTION_CACHE.get(asset) ?? undefined;\n }\n const supportedFormat = asset.format === 'rgba8unorm' || asset.format === 'rgba8unorm-srgb';\n const validDimensions =\n Number.isSafeInteger(asset.shape.extent.width) &&\n Number.isSafeInteger(asset.shape.extent.height) &&\n asset.shape.extent.width > 0 &&\n asset.shape.extent.height > 0;\n const validFormatPair =\n (asset.format === 'rgba8unorm-srgb' && asset.colorSpace === 'srgb') ||\n (asset.format === 'rgba8unorm' && asset.colorSpace === 'linear');\n const validPayload =\n asset.data.byteLength >= asset.shape.extent.width * asset.shape.extent.height * 4;\n if (!supportedFormat || !validDimensions || !validFormatPair || !validPayload) {\n COOKIE_PROJECTION_CACHE.set(asset, null);\n return undefined;\n }\n\n const data = new Uint8Array(COOKIE_SLICE_SIZE * COOKIE_SLICE_SIZE * 4);\n for (let y = 0; y < COOKIE_SLICE_SIZE; y += 1) {\n for (let x = 0; x < COOKIE_SLICE_SIZE; x += 1) {\n const target = (y * COOKIE_SLICE_SIZE + x) * 4;\n data[target] = Math.round(clamp01(sampleSourceChannel(asset, x, y, 0)) * 255);\n data[target + 1] = Math.round(clamp01(sampleSourceChannel(asset, x, y, 1)) * 255);\n data[target + 2] = Math.round(clamp01(sampleSourceChannel(asset, x, y, 2)) * 255);\n // Alpha stays linear and is intentionally preserved: the shader\n // multiplies sampled RGB by this lane as part of Cookie semantics.\n data[target + 3] = Math.round(clamp01(sampleSourceChannel(asset, x, y, 3)) * 255);\n }\n }\n\n // Column-major mat4. The shader multiplies the unprojected local\n // (x/depth, y/depth) pair by this aspect-only matrix, then applies the\n // Spot's outer-cone tangent and the [0,1] translation. Keeping outerCone\n // out of this slice-keyed matrix allows one Cookie to be shared by lights.\n const matrix = new Float32Array(16);\n matrix[0] = asset.shape.extent.height / asset.shape.extent.width;\n matrix[5] = 1;\n matrix[10] = 1;\n matrix[15] = 1;\n const projection = {\n data,\n matrix,\n aspect: asset.shape.extent.width / asset.shape.extent.height,\n };\n COOKIE_PROJECTION_CACHE.set(asset, projection);\n return projection;\n}\n\n/** Create the deterministic identity payload used for unused Cookie slices. */\nexport function createCookieProjectionMatrixData(count: number): Float32Array {\n const data = new Float32Array(count * 16);\n for (let index = 0; index < count; index += 1) {\n const base = index * 16;\n data[base] = 1;\n data[base + 5] = 1;\n data[base + 10] = 1;\n data[base + 15] = 1;\n }\n return data;\n}\n\nfunction normalized(vector: ArrayLike<number>): [number, number, number] | undefined {\n const x = vector[0] ?? 0;\n const y = vector[1] ?? 0;\n const z = vector[2] ?? 0;\n const length = Math.hypot(x, y, z);\n return length > 0 && Number.isFinite(length) ? [x / length, y / length, z / length] : undefined;\n}\n\nexport function spotModifierProduct(factors: SpotModifierFactors): number {\n return (\n factors.brdf *\n factors.range *\n factors.cone *\n (factors.ies ?? 1) *\n (factors.cookie ?? 1) *\n factors.shadow\n );\n}\n\nexport function projectIesCoordinates(\n toPoint: ArrayLike<number>,\n rollDeg: number,\n): IesCoordinates | undefined {\n const direction = normalized(toPoint);\n if (direction === undefined || direction[2] >= 0) return undefined;\n const roll = rollDeg * DEG_TO_RAD;\n const rolledX = direction[0] * Math.cos(roll) - direction[1] * Math.sin(roll);\n const rolledY = direction[0] * Math.sin(roll) + direction[1] * Math.cos(roll);\n return {\n azimuth: (Math.atan2(rolledY, rolledX) + Math.PI * 2) % (Math.PI * 2),\n elevation: Math.acos(Math.min(1, Math.max(-1, -direction[2]))) / Math.PI,\n };\n}\n\nexport function projectCookieUv(\n toPoint: ArrayLike<number>,\n rollDeg: number,\n aspect: number,\n outerConeDeg = 45,\n): CookieUv | undefined {\n const direction = normalized(toPoint);\n if (direction === undefined || direction[2] >= 0 || !Number.isFinite(aspect) || aspect <= 0)\n return undefined;\n const cone = Math.atan2(Math.hypot(direction[0], direction[1]), -direction[2]);\n const outerCone = outerConeDeg * DEG_TO_RAD;\n if (cone > outerCone) return undefined;\n const roll = rollDeg * DEG_TO_RAD;\n const x = direction[0] * Math.cos(roll) - direction[1] * Math.sin(roll);\n const y = direction[0] * Math.sin(roll) + direction[1] * Math.cos(roll);\n const scale = Math.tan(outerCone);\n return {\n u: 0.5 + (x / -direction[2] / scale / aspect) * 0.5,\n v: 0.5 + (y / -direction[2] / scale) * 0.5,\n };\n}\n","import { frustum } from '@forgeax/engine-math';\nimport type { ExtractedLights } from '../render-system-extract';\n\n/** Light visibility is independent of camera visibility, including across Worlds. */\nexport function buildShadowFrusta(lights: ExtractedLights): frustum.Frustum[] {\n const result: frustum.Frustum[] = [];\n const add = (matrix: Float32Array): void => {\n result.push(frustum.fromViewProjection(frustum.create(), matrix));\n };\n for (const matrix of lights.lightViewProj?.slice(0, lights.cascadeCount) ?? []) add(matrix);\n for (const snapshot of lights.pointShadow) {\n if (snapshot.shadowAtlasLayer < 0) continue;\n for (let face = 0; face < 6; face += 1)\n add(snapshot.shadowMatrices.subarray(face * 16, (face + 1) * 16));\n }\n for (const snapshot of lights.spot) {\n if (snapshot.shadowAtlasTile >= 0 && snapshot.lightViewProj !== undefined)\n add(snapshot.lightViewProj);\n }\n return result;\n}\n","import type { AssetRegistry } from '@forgeax/engine-assets-runtime';\nimport {\n resolveAssetHandle,\n walkMaterialPassesOverSharedRefs,\n} from '@forgeax/engine-assets-runtime';\nimport type { EntityHandle, World } from '@forgeax/engine-ecs';\nimport {\n routeWorldError,\n SpawnLightInvalidBoundsError,\n SpriteInstancesCountMismatchError,\n SpriteInstancesMutuallyExclusiveWithInstancesError,\n SpriteInstancesRequiresSpriteShaderError,\n} from '@forgeax/engine-ecs/projection';\nimport { box3, frustum, type Mat4, mat4, type Vec3, vec3 } from '@forgeax/engine-math';\nimport { AssetGuid } from '@forgeax/engine-pack/guid';\nimport type { MaterialCookProgramContext } from '@forgeax/engine-pack/material-cook';\nimport { RhiError } from '@forgeax/engine-rhi';\nimport { GlobalTransform, MorphWeights, Transform } from '@forgeax/engine-scene';\nimport type { MaterialShaderArtifact } from '@forgeax/engine-shader';\nimport {\n JointCountMismatchError,\n JointEntityDanglingError,\n SkeletonResolveFailedError,\n Skin,\n SkinInstancesCoexistForbiddenError,\n} from '@forgeax/engine-skinning';\nimport type {\n Asset,\n Handle,\n IesProfileAsset,\n MeshAsset,\n MeshLodLevel,\n SkeletonAsset,\n TextureAsset,\n} from '@forgeax/engine-types';\nimport {\n ASSET_ERROR_HINTS,\n AssetError,\n derive,\n handleSlot,\n materialValuesToLinearRuntime,\n toShared,\n} from '@forgeax/engine-types';\nimport { type ExtractedCloudLayer, extractCloudLayer } from './cloud/extract';\nimport {\n Atmosphere,\n DirectionalLight,\n Instances,\n Layer,\n LightProbe,\n Lines,\n MeshFilter,\n MeshRenderer,\n PointLight,\n PointLightShadow,\n Points,\n PostProcessParams,\n pointShapeFromU32,\n RectAreaLight,\n SkyboxBackground,\n Skylight,\n SortKey,\n SpotLight,\n SpriteInstances,\n SpriteRegionOverride,\n} from './components';\nimport {\n type DirectionalShadowQuality,\n directionalShadowQualityFromF32,\n} from './components/directional-shadow-filter';\nimport { GlyphText } from './components/glyph-text';\nimport {\n computeInvRangeSquared,\n degToCos,\n type LightValidationError,\n validateDirectionalLightData,\n validateLightProbeData,\n validateRectAreaLightData,\n} from './components/light-helpers';\nimport { selectEnvironment } from './environment/frame';\nimport { MaterialSkinAttrMissingError, SkinMaterialMismatchError } from './errors/render';\nimport type { EnvironmentCandidate, EnvironmentFrame } from './extract/environment';\nimport {\n buildGpuDrivenDraws,\n gpuDrivenShadowDrawKey,\n gpuDrivenSourceDrawItemIndex,\n} from './extract/gpu-driven';\nimport type { VisibilitySnapshot } from './extract/visibility';\nimport { MotionBlurValidationError } from './features/motion-blur/motion-blur-params';\nimport type {\n RenderFeatureHiddenEntityReport,\n RenderFeatureWorldVisibilitySnapshot,\n} from './features/types';\nimport { ensureGlyphMeshMaterialSlots } from './glyph-text-layout-system';\nimport { type InstanceProjectionStore, validateInstanceTransforms } from './instances';\nimport { deriveInstancesUnionBounds } from './instances-derived-bounds';\nimport {\n type MeshMaterialBindingDiagnostic,\n type MeshMaterialBindingSource,\n resolveMeshMaterialBindings,\n} from './mesh-material-bindings';\nimport { isStandardPbrSkinMaterialShader } from './pbr-pipeline';\nimport { expandPointsLinesBounds } from './points-lines/bounds';\nimport type { PointsLinesRetainedSnapshot, PointsLinesStyle } from './points-lines/snapshot';\nimport { COOKIE_SLICE_CAPACITY, IES_SLICE_CAPACITY } from './prepare/extended-lighting/resources';\nimport { prepareCookieProjection } from './prepare/extended-lighting/spot-modifiers';\nimport { worldEntityKey } from './record/frame-snapshot';\nimport { STANDARD_OUTPUT_TRANSFORM_FEATURE_ID } from './render-contract';\nimport type {\n CsmCameraData,\n DirectionalCsmConfig,\n DirectionalLightSnapshot,\n DispatchEntry,\n ExtractedFrame,\n ExtractedLights,\n ExtractFramesOwner,\n ExtractPipelineSurface,\n InstancesSnapshot,\n LightProbeSnapshot,\n MaterialProgramSelection,\n MaterialSnapshot,\n MaterialSnapshotCache,\n MaterialSnapshotCachesByWorld,\n MaterialTextureSourceCache,\n MaterialTextureSourceStats,\n MorphSnapshot,\n PointLightSnapshot,\n PointShadowSnapshot,\n PreparedExtractContext,\n RectAreaDirectLightSnapshot,\n RenderableSnapshot,\n ShadowCasterMembership,\n SkyboxSnapshot,\n SkylightSnapshot,\n SpotLightSnapshot,\n SpriteInstancesSnapshot,\n TransformSnapshot,\n} from './render-system-extract';\nimport {\n appendMaterialDispatchEntries,\n assetReferenceText,\n BUILTIN_USER_REGION_TEXTURE_FIELDS,\n buildPointShadowMatrices,\n buildRectAreaWorldFrame,\n collectAuthoredMaterialSamplerFields,\n collectAuthoredMaterialTextureFields,\n collectCubeCameraSnapshots,\n collectMaterialTextureCoordinates,\n collectMaterialTextureSamplers,\n collectMaterialTextureSources,\n collectReflectionProbeFacts,\n computeDirectionalCsm,\n createWorldInternalView,\n DEFAULT_FORWARD_PASS,\n extractVolumeSnapshot,\n fogState,\n internSharedRefFromGuid,\n isEngineInjectedTextureField,\n materialColorParameterSchema,\n materialNormalScale,\n materialParamSchemaForMaterial,\n materialProgramSelectionsForMaterial,\n materialSceneIndexProgramKeysForMaterial,\n materialStandardTextureMask,\n materialTextureFields,\n materialTextureRef,\n materialTextureSourceFields,\n pipelineRenderState,\n prepareExtractContext,\n pssmSplit,\n readPersistentMaterialSnapshot,\n readStablePersistentMaterialSnapshot,\n resolveMaterialSnapshot,\n resolveVideoFieldHandle,\n runtimeMaterialShaderIdForMaterial,\n Severity,\n selectCameraRoles,\n selectFogFrame,\n shadowCasterCpuReason,\n sortDispatchByQueue,\n storeMaterialSnapshot,\n tonemapParams,\n} from './render-system-extract';\nimport { buildShadowFrusta } from './scene/shadow-visibility';\nimport { SHADOW_ATLAS_DEFAULT_LAYERS } from './shadow-atlas';\nimport type { SkinPaletteReceipt, SkinPose } from './systems/skin-palette-types';\n\nfunction skinPaletteIdentity(world: World, entity: number): string {\n return `skin:${world.identity}:${entity}`;\n}\n\nfunction materialProgramSelectionRequiresSkin(selection: {\n readonly abi?: {\n readonly skinPaletteAddress?: unknown;\n readonly vertexInputs?: readonly { readonly semantic?: unknown }[];\n };\n}): boolean {\n if (selection.abi?.skinPaletteAddress !== undefined) return true;\n const semantics = new Set((selection.abi?.vertexInputs ?? []).map((input) => input.semantic));\n return semantics.has('skinIndex') && semantics.has('skinWeight');\n}\n\nfunction isMissingMaterialProgram(error: unknown): boolean {\n return (\n error !== null &&\n typeof error === 'object' &&\n (error as { readonly code?: unknown }).code === 'material-specialization-not-cooked'\n );\n}\n\nexport function extractFrames(\n worlds: readonly World[],\n owner: number | ExtractFramesOwner,\n assets?: AssetRegistry | null,\n pipelineState?: ExtractPipelineSurface | null,\n materialSnapshotCachesByWorld?: MaterialSnapshotCachesByWorld,\n options: {\n readonly materialContext?: MaterialCookProgramContext;\n readonly cull?: 'normal' | 'none';\n readonly renderables?:\n | 'full'\n | 'none'\n | {\n readonly kind: 'partial';\n readonly entitiesByWorld: readonly (ReadonlySet<number> | undefined)[];\n };\n readonly retainHidden?: boolean;\n readonly getMaterialShaderArtifact?: (\n materialShaderId: string,\n request?: {\n readonly vertexColorAvailable?: boolean;\n readonly deformation?: 'rigid' | 'skin';\n readonly variantSet?: string;\n readonly pass?: 'forward' | 'shadow' | 'depth';\n readonly address?: 'direct' | 'scene-index';\n },\n ) => MaterialShaderArtifact | undefined;\n readonly instanceCollections?: InstanceProjectionStore;\n } = {},\n): ExtractedFrame {\n // w4: normalize the owner argument. A bare number is the legacy single-owner\n // form (cameraOwner === resourceOwner); an object carries the two split\n // indices. When they coincide the code path is byte-identical to the pre-w4\n // single-owner behaviour (w1 contract combination 2).\n const cameraOwner = typeof owner === 'number' ? owner : owner.cameraOwner;\n const resourceOwner = typeof owner === 'number' ? owner : owner.resourceOwner;\n const cameraEntityKey = typeof owner === 'number' ? undefined : owner.cameraEntityKey;\n const renderableRequest = options.renderables ?? 'full';\n const renderableMode = typeof renderableRequest === 'object' ? 'full' : renderableRequest;\n const partialEntitiesByWorld =\n typeof renderableRequest === 'object' ? renderableRequest.entitiesByWorld : undefined;\n const retainHidden = options.retainHidden ?? typeof renderableRequest === 'object';\n\n // ── D-2: frame-level side effects live here ────────────────────────────\n //\n // resetForFrame is called exactly once per frame, at the extractFrames\n // entry. The skinPaletteAllocator cursor is reset before each per-world\n // extract runs, so sequential per-world allocation yields non-overlapping\n // palette slices (AC-08).\n const skinPaletteAllocator = pipelineState?.skinPaletteAllocator ?? null;\n // A partial request is still normalized to the producer's full renderable\n // query, but it is not a full allocator reconciliation. beginFrame/endFrame\n // mark every persistent identity not visited by this selected subset as\n // detached; doing that here would release untouched palettes. Only the\n // explicit full request is allowed to reconcile the identity set.\n const reconcileSkinFrame = renderableRequest === 'full';\n if (skinPaletteAllocator !== null && reconcileSkinFrame) {\n skinPaletteAllocator.beginFrame();\n skinPaletteAllocator.resetForFrame();\n }\n\n const failedWorlds = new Set<World>();\n // Resource-owner selection is a frame-level concern. Select Fog once before\n // per-world extraction so non-owner worlds do not scan their ECS tables for\n // a value that the merge layer will discard.\n const resourceOwnerWorld = worlds[resourceOwner];\n const resourceOwnerFog =\n resourceOwnerWorld === undefined ? null : (selectFogFrame(resourceOwnerWorld) ?? null);\n // ── D-2: per-world extract with error isolation ────────────────────────\n //\n // Each world runs extractFrame over the final state published by\n // world.update(). Failure in one world is caught, routed to that world's\n // _routeError (systemName carries worldId for source identification),\n // and the world's contribution is skipped (AC-09 graceful degradation).\n\n // The camera-owner frame must be extracted first: non-owner worlds do not\n // carry the surfaced camera, but their renderables still need to be tested\n // against that camera's frustum. Frames are placed back into worlds[] order\n // before merge so queue / directional-light / worldId semantics stay stable.\n const succeededFrames: ExtractedFrame[] = [];\n const succeededIndices: number[] = [];\n\n const extractionOrder = Array.from({ length: worlds.length }, (_, wi) => wi).sort((a, b) => {\n if (a === cameraOwner) return -1;\n if (b === cameraOwner) return 1;\n return a - b;\n });\n const framesByWorld = new Map<number, ExtractedFrame>();\n\n for (const wi of extractionOrder) {\n const world = worlds[wi];\n if (world === undefined || failedWorlds.has(world)) continue;\n try {\n if (skinPaletteAllocator !== null && partialEntitiesByWorld !== undefined) {\n for (const entityKey of partialEntitiesByWorld[wi] ?? []) {\n if (!world.hasComponent(entityKey as EntityHandle, Skin)) {\n skinPaletteAllocator.releasePersistentSlice(skinPaletteIdentity(world, entityKey));\n }\n }\n }\n const isCameraOwner = wi === cameraOwner;\n const cameraOwnerFrame = framesByWorld.get(cameraOwner);\n const prepared = prepareExtractContext(world, {\n ...(assets !== undefined ? { assets } : {}),\n ...(pipelineState !== undefined ? { pipelineState } : {}),\n resourceOwnerFog: wi === resourceOwner ? resourceOwnerFog : null,\n ...(materialSnapshotCachesByWorld === undefined\n ? {}\n : {\n materialSnapshotCache:\n materialSnapshotCachesByWorld.get(world) ??\n (() => {\n const cache: MaterialSnapshotCache = new Map();\n materialSnapshotCachesByWorld.set(world, cache);\n return cache;\n })(),\n }),\n ...(options.materialContext === undefined\n ? {}\n : { materialContext: options.materialContext }),\n cull: options.cull === 'none' ? 'none' : isCameraOwner ? 'self' : 'external',\n renderables: renderableMode,\n ...(isCameraOwner && cameraEntityKey !== undefined ? { cameraEntityKey } : {}),\n ...(partialEntitiesByWorld?.[wi] === undefined\n ? {}\n : { renderableEntities: partialEntitiesByWorld[wi] }),\n retainHidden,\n worldId: wi,\n ...(options.getMaterialShaderArtifact === undefined\n ? {}\n : { getMaterialShaderArtifact: options.getMaterialShaderArtifact }),\n ...(options.instanceCollections === undefined\n ? {}\n : { instanceCollections: options.instanceCollections }),\n ...(cameraOwnerFrame === undefined ? {} : { cullCameras: cameraOwnerFrame.cameras }),\n });\n const frame = extractFrame(world, prepared);\n\n framesByWorld.set(wi, frame);\n } catch (err) {\n // Camera effect parameters are part of the public render contract. Keep\n // their typed validation error on the renderer path so draw() can return\n // a RenderError and publish the invalid inspection state; ordinary\n // per-world extraction failures retain the existing world-local route.\n if (err instanceof MotionBlurValidationError) throw err;\n // Per-world failure: route to world's own error handler, skip contribution.\n try {\n createWorldInternalView(world)._routeError(err, {\n severity: Severity.Error,\n systemName: `RenderSystem.extractFrames(world[${wi}])`,\n });\n } catch {\n // If _routeError itself throws, the world already failed — skip silently.\n }\n }\n }\n\n // Reconcile persistent palette identities from the extracted producer\n // projection. Identities absent after a detach are fence-retired by the\n // allocator; surviving identities keep their stable slices.\n if (skinPaletteAllocator !== null && reconcileSkinFrame) {\n skinPaletteAllocator.endFrame();\n }\n\n // Restore the caller's world order after the camera-owner-first extraction.\n for (let wi = 0; wi < worlds.length; wi++) {\n const frame = framesByWorld.get(wi);\n if (frame === undefined) continue;\n succeededFrames.push(frame);\n succeededIndices.push(wi);\n }\n\n // ── D-3: merge semantics ───────────────────────────────────────────────\n\n // AC-04: renderables — concat by worlds[] order, stamp worldId.\n const renderables: RenderableSnapshot[] = [];\n const dispatchEntries: DispatchEntry[] = [];\n const shadowCasterEntityKeys = new Set<number>();\n const shadowCasterDrawKeys = new Set<string>();\n const shadowCasterMembership = new Map<string, ShadowCasterMembership>();\n const visibilitySnapshots: VisibilitySnapshot[] = [];\n const featureVisibilitySnapshots: RenderFeatureWorldVisibilitySnapshot[] = [];\n const hiddenEntityReports: RenderFeatureHiddenEntityReport[] = [];\n\n for (let fi = 0; fi < succeededFrames.length; fi++) {\n const f = succeededFrames[fi];\n const wId = succeededIndices[fi];\n if (f === undefined || wId === undefined) continue;\n\n const base = renderables.length;\n const visibilitySnapshot = f.visibilitySnapshots[0];\n const world = worlds[wId];\n if (visibilitySnapshot !== undefined) {\n visibilitySnapshots.push(visibilitySnapshot);\n if (world !== undefined)\n featureVisibilitySnapshots.push({ world, snapshot: visibilitySnapshot });\n }\n hiddenEntityReports.push(...f.hiddenEntityReports);\n for (const r of f.renderables) {\n renderables.push({\n ...r,\n worldId: wId,\n ...(r.pointsLines === undefined ? {} : { pointsLines: { ...r.pointsLines, worldId: wId } }),\n });\n }\n\n // D-3: dispatch — per-world renderableIndex rebased by base offset.\n for (const d of f.dispatch) {\n dispatchEntries.push({ ...d, renderableIndex: (d.renderableIndex ?? 0) + base });\n }\n for (const key of f.shadowCasterEntityKeys) shadowCasterEntityKeys.add(key);\n for (const key of f.shadowCasterDrawKeys) shadowCasterDrawKeys.add(key);\n for (const membership of f.shadowCasterMembership ?? []) {\n const rebased = { ...membership, renderableIndex: membership.renderableIndex + base };\n const key = gpuDrivenShadowDrawKey(\n rebased.worldEntity,\n rebased.materialHandle,\n rebased.drawItemIndex,\n rebased.passIndex,\n );\n shadowCasterMembership.set(key, rebased);\n }\n }\n\n // Stable sort dispatch by queue value.\n dispatchEntries.sort((a, b) => (a.queue ?? 0) - (b.queue ?? 0));\n\n // AC-04: lights — point[]/spot[] concat; directional first-hit in\n // succeededFrames order (which preserves worlds[] order for successful\n // frames); directionalCount sum.\n const point: PointLightSnapshot[] = [];\n const spot: SpotLightSnapshot[] = [];\n const rect: RectAreaDirectLightSnapshot[] = [];\n let directional: DirectionalLightSnapshot | undefined;\n let directionalCount = 0;\n let lightViewProj: readonly Float32Array[] | undefined;\n let splitPlanes: Float32Array | undefined;\n let cascadeCount: number | undefined;\n let cascadeBlend: number | undefined;\n let shadowMapSize: number | undefined;\n let depthBias: number | undefined;\n let normalBias: number | undefined;\n let directionalShadowQuality: DirectionalShadowQuality | undefined;\n let directionalShadowError: LightValidationError | undefined;\n const pointShadow: PointShadowSnapshot[] = [];\n // bug-20260710-editor-cross-world-shadow: carry the raw CSM config +\n // direction of the first-hit directional so the merge layer can recompute\n // matrices against the SURFACED (cameraOwner) camera — the light and the\n // camera may live in different worlds (editor super-composite).\n let directionalCsmConfig: DirectionalCsmConfig | undefined;\n let directionalCsmDirection: Vec3 | undefined;\n for (let fi = 0; fi < succeededFrames.length; fi += 1) {\n const f = succeededFrames[fi];\n const wId = succeededIndices[fi] ?? 0;\n if (f === undefined) continue;\n for (const p of f.lights.point) point.push({ ...p, worldId: wId });\n for (const s of f.lights.spot) spot.push({ ...s, worldId: wId });\n for (const r of f.lights.rect) rect.push(r);\n for (const ps of f.lights.pointShadow) pointShadow.push({ ...ps, worldId: wId });\n if (directional === undefined && f.lights.directional !== undefined) {\n directional = f.lights.directional;\n // Carry CSM shadow fields from the first-hit directional's world.\n lightViewProj = f.lights.lightViewProj;\n splitPlanes = f.lights.splitPlanes;\n cascadeCount = f.lights.cascadeCount;\n cascadeBlend = f.lights.cascadeBlend;\n shadowMapSize = f.lights.shadowMapSize;\n depthBias = f.lights.depthBias;\n normalBias = f.lights.normalBias;\n directionalShadowQuality = f.lights.directionalShadowQuality;\n directionalShadowError = f.lights.directionalShadowError;\n directionalCsmConfig = f.lights.directionalCsmConfig;\n directionalCsmDirection = f.lights.directionalCsmDirection;\n }\n directionalCount += f.lights.directionalCount;\n }\n\n // AC-05/06 + w4 owner split (D-3 / R-6): cameras come from the cameraOwner\n // world; skylight / skybox / postProcessParams come from the resourceOwner\n // world (holistic snapshot selection). Scan succeededIndices once to locate\n // each owner's surviving frame. When cameraOwner === resourceOwner both\n // resolve to the same frame — byte-identical to the pre-w4 single-owner path.\n let cameraOwnerFrame: ExtractedFrame | undefined;\n let resourceOwnerFrame: ExtractedFrame | undefined;\n for (let fi = 0; fi < succeededFrames.length; fi++) {\n if (succeededIndices[fi] === cameraOwner) cameraOwnerFrame = succeededFrames[fi];\n if (succeededIndices[fi] === resourceOwner) resourceOwnerFrame = succeededFrames[fi];\n }\n const cameras =\n cameraOwnerFrame?.cameras.map((camera) => ({ ...camera, worldId: cameraOwner })) ?? [];\n const auxiliaryCameras =\n cameraOwnerFrame?.auxiliaryCameras.map((camera) => ({ ...camera, worldId: cameraOwner })) ?? [];\n const cubeCameras = cameraOwnerFrame !== undefined ? [...cameraOwnerFrame.cubeCameras] : [];\n\n // bug-20260710-editor-cross-world-shadow: RECOMPUTE directional CSM matrices\n // against the surfaced camera. In a single-world app the per-world extract\n // already produced correct matrices (light+camera share the world), and this\n // recompute uses the same config and camera. In the editor super-composite\n // the directional light's world has NO camera, so\n // its per-world `lightViewProj` is undefined/degenerate; the surfaced camera\n // lives in the cameraOwner world. Pairing them here is the ONLY place both\n // are visible. Point/spot shadows are camera-independent (light-space only)\n // and need no merge-layer fix-up.\n const mergeCam = cameras[0];\n if (directionalCsmConfig !== undefined && directionalCsmDirection !== undefined) {\n const mergeCameraData: CsmCameraData | undefined =\n mergeCam !== undefined\n ? {\n world: mergeCam.world,\n fov: mergeCam.fov,\n aspect: mergeCam.aspect,\n near: mergeCam.near,\n far: mergeCam.far,\n projection: mergeCam.projection,\n orthoLeft: mergeCam.orthoLeft,\n orthoRight: mergeCam.orthoRight,\n orthoBottom: mergeCam.orthoBottom,\n orthoTop: mergeCam.orthoTop,\n }\n : undefined;\n const csm = computeDirectionalCsm(\n directionalCsmDirection,\n directionalCsmConfig,\n mergeCameraData,\n );\n if (csm !== null) {\n lightViewProj = csm.lightViewProj;\n splitPlanes = csm.splitPlanes;\n cascadeCount = csm.cascadeCount;\n cascadeBlend = csm.cascadeBlend;\n shadowMapSize = csm.shadowMapSize;\n directionalShadowQuality = csm.directionalShadowQuality;\n }\n // csm === null (no surfaced camera at all): keep the per-world carry —\n // there is no better data, and a cameraless frame renders nothing anyway.\n }\n\n const lights: ExtractedLights = {\n directional,\n directionalCount,\n point,\n spot,\n rect,\n lightViewProj,\n splitPlanes,\n cascadeCount,\n cascadeBlend,\n shadowMapSize,\n depthBias,\n normalBias,\n directionalShadowQuality,\n directionalShadowError,\n pointShadow,\n directionalCsmConfig,\n directionalCsmDirection,\n };\n\n const volumetricFog = resourceOwnerFrame?.volumetricFog;\n const cloudLayer = resourceOwnerFrame?.cloudLayer;\n const skylight = resourceOwnerFrame?.skylight;\n const skylightCount = resourceOwnerFrame?.skylightCount ?? 0;\n const skybox = resourceOwnerFrame?.skybox;\n const skyboxCount = resourceOwnerFrame?.skyboxCount ?? 0;\n const fog = resourceOwnerFrame?.fog;\n const fogFailure = resourceOwnerFrame?.fogFailure;\n const environment = resourceOwnerFrame?.environment;\n const lightProbes = succeededFrames.flatMap((frame, index) => {\n const worldId = succeededIndices[index] ?? 0;\n return (frame.lightProbes ?? []).map((probe) => ({ ...probe, worldId }));\n });\n // User-authored PostProcessParams entities are singleton scene resources, so\n // they come from the resourceOwner world (holistic snapshot selection).\n const postProcessParams = new Map(resourceOwnerFrame?.postProcessParams);\n // feat-20260709-editor-world-partition ENGINE-fix-round2 (defect 1): the\n // engine built-in Standard tonemap param is NOT a scene resource — the\n // per-world extractFrame bridges it from that world's own `cameras[0]`\n // (Camera.exposure / whitePoint / tonemap is the SSOT). It therefore lives on\n // the CAMERA-owner frame, not the resource-owner frame. In the split-owner\n // editor topology the resourceOwner world has no Camera, so its frame carries\n // no Standard tonemap entry; taking postProcessParams from resourceOwner\n // alone drops it, the tonemap pass's params UBO stays zero-filled\n // (exposure=0 => tonemapped output is uniformly black), and the whole frame\n // reads black even though geometry drew into the HDR target. Overlay the\n // camera-owner frame's tonemap param (its SSOT source) so the surfaced\n // camera's exposure/whitePoint/mode reach the tonemap pass. When\n // cameraOwner === resourceOwner this is a no-op (identical entry). The 'na'\n // Standard tonemap identity mirrors the engine provider key set at the\n // bottom of extractFrame (SSOT: same identity, same 16B layout).\n const OUTPUT_TRANSFORM_PARAM_KEY = STANDARD_OUTPUT_TRANSFORM_FEATURE_ID;\n const cameraTonemapParam = cameraOwnerFrame?.postProcessParams.get(OUTPUT_TRANSFORM_PARAM_KEY);\n if (cameraTonemapParam !== undefined) {\n postProcessParams.set(OUTPUT_TRANSFORM_PARAM_KEY, cameraTonemapParam);\n } else {\n // The camera-owner world produced no tonemap param (no Camera surfaced\n // there this frame); do not leave a stale resource-owner entry that would\n // apply a foreign camera's exposure. Removing it lets the tonemap pass fall\n // back to its param-less zero path only when genuinely no camera exists.\n postProcessParams.delete(OUTPUT_TRANSFORM_PARAM_KEY);\n }\n\n // D-3: frustumStats — culled/total summed across worlds.\n const frustumStats = {\n culled: succeededFrames.reduce((s, f) => s + f.frustumStats.culled, 0),\n total: succeededFrames.reduce((s, f) => s + f.frustumStats.total, 0),\n };\n const visibilityStats = {\n explicitlyHidden: succeededFrames.reduce((s, f) => s + f.visibilityStats.explicitlyHidden, 0),\n };\n const materialTextureSources: MaterialTextureSourceStats = {\n sourceFieldsVisited: 0,\n numericSharedRefProbes: 0,\n sourceCacheHits: 0,\n sourceCacheMisses: 0,\n producerRoutes: {},\n };\n for (const frame of succeededFrames) {\n const stats = frame.materialTextureSources;\n if (stats === undefined) continue;\n materialTextureSources.sourceFieldsVisited += stats.sourceFieldsVisited;\n materialTextureSources.numericSharedRefProbes += stats.numericSharedRefProbes;\n materialTextureSources.sourceCacheHits += stats.sourceCacheHits;\n materialTextureSources.sourceCacheMisses += stats.sourceCacheMisses;\n for (const [route, count] of Object.entries(stats.producerRoutes)) {\n materialTextureSources.producerRoutes[route] =\n (materialTextureSources.producerRoutes[route] ?? 0) + count;\n }\n }\n const reflectionProbes = succeededFrames.flatMap((f, index) => {\n const worldId = succeededIndices[index] ?? 0;\n return (f.reflectionProbes ?? []).map((probe) => ({ ...probe, worldId }));\n });\n\n return {\n cameras,\n auxiliaryCameras,\n cubeCameras,\n reflectionProbes,\n lights,\n ...(volumetricFog === undefined\n ? {}\n : { volumetricFog: { ...volumetricFog, worldId: resourceOwner } }),\n ...(cloudLayer === undefined ? {} : { cloudLayer }),\n renderables,\n dispatch: dispatchEntries,\n shadowCasterEntityKeys,\n shadowCasterDrawKeys,\n ...(shadowCasterMembership.size === 0\n ? {}\n : { shadowCasterMembership: [...shadowCasterMembership.values()] }),\n skylight,\n skylightCount,\n lightProbes,\n skybox,\n skyboxCount,\n fog,\n ...(fogFailure === undefined ? {} : { fogFailure }),\n environment,\n environmentReady: resourceOwnerFrame !== undefined && environment !== undefined,\n frustumStats,\n visibilityStats,\n materialTextureSources,\n postProcessParams,\n visibilitySnapshots,\n featureVisibilitySnapshots,\n hiddenEntityReports,\n };\n}\n\n/**\n * A MeshAsset participates in frustum culling only when its producer supplied\n * the complete finite local-space bounds promised by the asset contract.\n * Missing, malformed, and inverted-infinity empty bounds remain conservative\n * (always visible) so a bad asset cannot turn into a false-negative render;\n * they are not cull candidates and therefore do not inflate frustumStats.\n */\nfunction hasFiniteOrderedLocalAabb(aabb: Float32Array | undefined): aabb is Float32Array {\n if (aabb === undefined || aabb.length !== 6) return false;\n const minX = aabb[0];\n const minY = aabb[1];\n const minZ = aabb[2];\n const maxX = aabb[3];\n const maxY = aabb[4];\n const maxZ = aabb[5];\n if (\n minX === undefined ||\n minY === undefined ||\n minZ === undefined ||\n maxX === undefined ||\n maxY === undefined ||\n maxZ === undefined\n ) {\n return false;\n }\n if (\n !Number.isFinite(minX) ||\n !Number.isFinite(minY) ||\n !Number.isFinite(minZ) ||\n !Number.isFinite(maxX) ||\n !Number.isFinite(maxY) ||\n !Number.isFinite(maxZ)\n ) {\n return false;\n }\n return minX <= maxX && minY <= maxY && minZ <= maxZ;\n}\n\nexport function morphSnapshotFor(\n mesh: Pick<MeshAsset, 'vertices' | 'morphTargets'>,\n weights: ArrayLike<number> | undefined,\n): MorphSnapshot | undefined {\n const targets = mesh.morphTargets;\n if (targets === undefined || targets.length === 0 || weights === undefined) return undefined;\n if (weights.length !== targets.length) return undefined;\n const firstPositions = targets[0]?.position;\n if (\n firstPositions === undefined ||\n firstPositions.length === 0 ||\n firstPositions.length % 3 !== 0\n ) {\n return undefined;\n }\n const vertexCount = firstPositions.length / 3;\n if (mesh.vertices.length % vertexCount !== 0) return undefined;\n for (let targetIndex = 0; targetIndex < targets.length; targetIndex += 1) {\n const target = targets[targetIndex];\n if (target?.position?.length !== firstPositions.length) return undefined;\n }\n const copied = new Float32Array(weights.length);\n for (let index = 0; index < weights.length; index += 1) {\n const weight = weights[index] ?? Number.NaN;\n if (!Number.isFinite(weight)) return undefined;\n copied[index] = weight;\n }\n // Zero weights are the source vertex stream exactly. An authored but idle\n // morph target must not disable skin scene-index admission or dispatch work.\n if (copied.every((weight) => weight === 0)) return undefined;\n return { weights: copied, targetCount: targets.length };\n}\n\nexport function extractFrame(world: World, context: PreparedExtractContext): ExtractedFrame {\n // feat-20260708-composited-multi-world-rendering M2 / D-2: resetForFrame\n // has been lifted to extractFrames (the frame-level entry point).\n // extractFrame is now a pure world->snapshot function with no frame-level\n // side effects. See plan-decisions PD2 for the reviewer ruling.\n const {\n assets,\n pipelineState,\n materialSnapshotCache: persistentMaterialSnapshotCache,\n cull: cullMode,\n resourceOwnerFog,\n getMaterialShaderArtifact,\n instanceCollections,\n renderableEntities,\n retainHidden,\n } = context;\n // Environment reads are owned by the retained resource projection and are\n // established at the frame boundary; record never revisits World state.\n const fog =\n resourceOwnerFog === undefined ? selectFogFrame(world) : (resourceOwnerFog ?? undefined);\n const fogFailure = fogState(world).failure;\n const visibility = context.visibility.hasAnyHiddenIntent ? context.visibility : undefined;\n const skinPaletteAllocator = pipelineState?.skinPaletteAllocator ?? null;\n const materialTextureSourceStats: MaterialTextureSourceStats = {\n sourceFieldsVisited: 0,\n numericSharedRefProbes: 0,\n sourceCacheHits: 0,\n sourceCacheMisses: 0,\n producerRoutes: {},\n };\n const materialTextureSourceCache: MaterialTextureSourceCache = new Map();\n\n const directionalLightQuery = world.query({ read: [DirectionalLight] }).unwrap();\n\n // feat-20260601 D-3: camera / point / spot light world transforms are read\n // through the single resolved `GlobalTransform.world` mat4 (written by\n // propagateTransforms).\n //\n // Each segment routes through a World-owned Query with explicit read and\n // optional roles. The packed entity handle for `readWorldMat4Copy` /\n // `_getArrayView` reads comes from `row.entity` -- the\n // archetype-graph back-door (`graph.archetypes` / `arch.components.some`) is gone.\n // Plan-decisions K-2 sniffing scheme B (archetype-edge sniff once via\n // `row.get(X) !== undefined`); K-3 invariant preserved (`_getArrayView`\n // calls survive untouched, only the entity source changes).\n const worldInternal = createWorldInternalView(world);\n let volumetricFog = extractVolumeSnapshot(world, assets, worldInternal);\n let cloudLayer: ExtractedCloudLayer | undefined;\n const extractedCloudLayer = extractCloudLayer(world);\n if (extractedCloudLayer.ok) {\n cloudLayer = extractedCloudLayer.value;\n } else {\n worldInternal._routeError(extractedCloudLayer.error, {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (cloud-layer)',\n });\n }\n\n const cameraRoles = selectCameraRoles(world, context.cameraEntityKey);\n const cameras = [...cameraRoles.display];\n const auxiliaryCameras = cameraRoles.auxiliary;\n const cubeCameras = collectCubeCameraSnapshots(world);\n const reflectionProbes = collectReflectionProbeFacts(world);\n\n // Three-query union (M2 / w16 / AC-03): directional has no Transform\n // dependency (sun-like infinite-source semantics); point + spot pull\n // position from the companion Transform via the joined queries.\n // Host-side pre-multiplication: color *= intensity (charter P4); cone\n // deg -> cos (D-S2); range -> 1/range^2 (D-S5).\n let directional: DirectionalLightSnapshot | undefined;\n let directionalCount = 0;\n // feat-20260621 M2: capture shadow fields from the first-hit DirectionalLight.\n // castShadow defaults to true; the CSM path is gated on firstHitCastShadow !== false.\n let firstHitCastShadow: boolean | undefined;\n let firstHitShadowFields:\n | {\n cascadeCount: number;\n splitLambda: number;\n cascadeBlend: number;\n mapSize: number;\n depthBias: number;\n normalBias: number;\n shadowDistance: number;\n shadowFilter: number;\n shadowAngularRadius: number;\n maxPenumbraTexels: number;\n }\n | undefined;\n for (const row of directionalLightQuery) {\n const l = row.get(DirectionalLight);\n directionalCount += 1;\n const intensity = l.intensity;\n const snapshot: DirectionalLightSnapshot = {\n kind: 'directional',\n entity: row.entity,\n direction: vec3.create(l.direction[0] ?? 0, l.direction[1] ?? -1, l.direction[2] ?? 0),\n color: vec3.create(\n (l.color[0] ?? 1) * intensity,\n (l.color[1] ?? 1) * intensity,\n (l.color[2] ?? 1) * intensity,\n ),\n intensity,\n };\n if (directional === undefined) {\n // First hit wins; record-stage N>1 fail-fast (M3 / w19) flags duplicates.\n directional = snapshot;\n firstHitCastShadow = l.castShadow;\n firstHitShadowFields = {\n cascadeCount: l.cascadeCount,\n splitLambda: l.splitLambda,\n cascadeBlend: l.cascadeBlend,\n mapSize: l.mapSize,\n depthBias: l.depthBias,\n normalBias: l.normalBias,\n shadowDistance: l.shadowDistance,\n shadowFilter: l.shadowFilter,\n shadowAngularRadius: l.shadowAngularRadius,\n maxPenumbraTexels: l.maxPenumbraTexels,\n };\n }\n }\n\n let directionalShadowError: LightValidationError | undefined;\n if (directional !== undefined && firstHitShadowFields !== undefined) {\n const validation = validateDirectionalLightData({\n direction: directional.direction,\n castShadow: firstHitCastShadow,\n ...firstHitShadowFields,\n });\n if (!validation.ok) {\n directionalShadowError = validation.error;\n worldInternal._routeError(directionalShadowError, {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (directional-shadow)',\n });\n }\n }\n\n const pointSnapshots: PointLightSnapshot[] = [];\n // feat-20260612-point-light-shadows-urp-hdrp M4 / T-M4-4: track entity per\n // pointSnapshots index so the post-extract pointShadow join can stamp\n // `shadowAtlasLayer + shadowNear + shadowFar` onto the matching PointLight.\n const pointSnapshotEntities: number[] = [];\n const pointLightQuery = world\n .query({\n read: [PointLight],\n optional: [Transform, GlobalTransform],\n })\n .unwrap();\n for (const row of pointLightQuery) {\n const p = row.get(PointLight);\n // K-2 scheme B: archetype-edge sniff -- `bundle.Transform` key is absent\n // when the archetype does not carry the Transform column.\n const hasTransform = row.get(GlobalTransform) !== undefined;\n const intensity = p.intensity;\n const range = p.range;\n const entityId = row.entity;\n // Position = world-space translation extracted from GlobalTransform.world.\n // A point light archetype without a Transform column sits at the origin.\n let worldMat: Float32Array | undefined;\n if (hasTransform) {\n const view = worldInternal._getArrayView(entityId, GlobalTransform, 'world');\n if (view !== undefined) worldMat = new Float32Array(view);\n }\n const position =\n worldMat !== undefined ? mat4.getTranslation(vec3.create(), worldMat) : vec3.create(0, 0, 0);\n pointSnapshots.push({\n kind: 'point',\n entity: entityId,\n worldId: context.worldId,\n position,\n color: vec3.create(\n (p.color[0] ?? 1) * intensity,\n (p.color[1] ?? 1) * intensity,\n (p.color[2] ?? 1) * intensity,\n ),\n intensity,\n invRangeSquared: computeInvRangeSquared(range),\n });\n pointSnapshotEntities.push(entityId);\n }\n\n const spotSnapshots: SpotLightSnapshot[] = [];\n const spotLightQuery = world\n .query({\n read: [SpotLight],\n optional: [Transform, GlobalTransform],\n })\n .unwrap();\n // feat-20260625-spot-light-shadow-mapping M1 w5: tile allocation for castShadow spots.\n // Cap = 4 (OOS-5), sentinel -1 = unassigned (plan-strategy D-4).\n // Direction degeneration (near-zero) also skips shadow (requirements $112).\n let spotTileNext = 0;\n const iesSlices = new Map<number, number>();\n const cookieSlices = new Map<number, number>();\n const projectorSlices = new Map<number, number>();\n for (const row of spotLightQuery) {\n const s = row.get(SpotLight);\n const hasTransform = row.get(GlobalTransform) !== undefined;\n const intensity = s.intensity;\n const range = s.range;\n const innerConeDeg = s.innerConeDeg;\n const outerConeDeg = s.outerConeDeg;\n let worldMat: Float32Array | undefined;\n if (hasTransform) {\n const entity = row.entity;\n const view = worldInternal._getArrayView(entity, GlobalTransform, 'world');\n if (view !== undefined) worldMat = new Float32Array(view);\n }\n const position =\n worldMat !== undefined ? mat4.getTranslation(vec3.create(), worldMat) : vec3.create(0, 0, 0);\n const dir = vec3.create(s.direction[0] ?? 0, s.direction[1] ?? -1, s.direction[2] ?? 0);\n\n // Extract is the single direction-normalization owner for direct-light\n // snapshots. URP and HDRP preserve this value downstream.\n const dirLen = Math.sqrt(\n (dir[0] ?? 0) * (dir[0] ?? 0) + (dir[1] ?? 0) * (dir[1] ?? 0) + (dir[2] ?? 0) * (dir[2] ?? 0),\n );\n const EPSILON = 1e-6;\n const hasValidDirection = dirLen > EPSILON;\n if (!hasValidDirection) {\n worldInternal._routeError(\n new SpawnLightInvalidBoundsError('SpotLight', 'direction', [\n dir[0] ?? 0,\n dir[1] ?? 0,\n dir[2] ?? 0,\n ]),\n {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (spot-direction)',\n },\n );\n }\n const dirN = vec3.create(\n hasValidDirection ? (dir[0] ?? 0) / dirLen : (dir[0] ?? 0),\n hasValidDirection ? (dir[1] ?? 0) / dirLen : (dir[1] ?? 0),\n hasValidDirection ? (dir[2] ?? 0) / dirLen : (dir[2] ?? 0),\n );\n\n // ── shadow fields (feat-20260625-spot-light-shadow-mapping M1) ──\n const castShadow = s.castShadow;\n const sMapSize = s.mapSize;\n const sNearPlane = s.nearPlane;\n const sFarPlane = s.farPlane;\n const iesProfileAsset =\n s.iesProfile === undefined\n ? undefined\n : resolveAssetHandle<IesProfileAsset>(world, s.iesProfile);\n const cookieAsset =\n s.cookie === undefined ? undefined : resolveAssetHandle<TextureAsset>(world, s.cookie);\n // Resolve the legacy projector before assigning array slices so the\n // extended-lighting path can reuse its texture transport without losing\n // the old lightViewProj projection semantics.\n const hasProjector = Number(s.projector) > 0;\n let projectorHandle: Handle<'TextureAsset', 'shared'> | undefined;\n let projectorAsset: TextureAsset | undefined;\n let projectorGuid: string | undefined;\n if (hasProjector) {\n const candidate = toShared<'TextureAsset'>(Math.round(Number(s.projector)));\n const resolvedProjector = resolveAssetHandle<TextureAsset>(world, candidate);\n if (!resolvedProjector.ok || resolvedProjector.value.kind !== 'texture') {\n worldInternal._routeError(\n resolvedProjector.ok\n ? new RhiError({\n code: 'asset-not-registered',\n expected: 'SpotLight.projector resolves to a TextureAsset',\n hint: 'load the authored projector TextureAsset before assigning SpotLight.projector',\n detail: { assetHandle: Number(candidate) },\n })\n : resolvedProjector.error,\n { severity: Severity.Error, systemName: 'RenderSystem.extract (spot-projector)' },\n );\n } else {\n projectorHandle = candidate;\n projectorAsset = resolvedProjector.value;\n projectorGuid = assets?.guidOf(projectorAsset) ?? `handle:${Number(candidate)}`;\n }\n }\n const iesProfileData =\n iesProfileAsset?.ok && iesProfileAsset.value.kind === 'ies-profile'\n ? new Uint8Array(iesProfileAsset.value.data)\n : undefined;\n const cookieProjection =\n cookieAsset?.ok && cookieAsset.value.kind === 'texture'\n ? prepareCookieProjection(cookieAsset.value)\n : undefined;\n const cookieData = cookieProjection?.data;\n const projectorProjection =\n projectorAsset === undefined ? undefined : prepareCookieProjection(projectorAsset);\n const projectorData = projectorProjection?.data;\n const iesProfileHandle = s.iesProfile === undefined ? undefined : handleSlot(s.iesProfile);\n const cookieHandle = s.cookie === undefined ? undefined : handleSlot(s.cookie);\n let iesProfileSlice =\n iesProfileHandle === undefined ? undefined : iesSlices.get(iesProfileHandle);\n if (\n iesProfileSlice === undefined &&\n iesProfileHandle !== undefined &&\n iesProfileData !== undefined &&\n iesSlices.size < IES_SLICE_CAPACITY\n ) {\n iesProfileSlice = iesSlices.size;\n iesSlices.set(iesProfileHandle, iesProfileSlice);\n }\n let cookieSlice = cookieHandle === undefined ? undefined : cookieSlices.get(cookieHandle);\n if (\n cookieSlice === undefined &&\n cookieHandle !== undefined &&\n cookieData !== undefined &&\n cookieSlices.size < COOKIE_SLICE_CAPACITY\n ) {\n cookieSlice = cookieSlices.size;\n cookieSlices.set(cookieHandle, cookieSlice);\n }\n let projectorSlice =\n projectorHandle === undefined\n ? undefined\n : (projectorSlices.get(projectorHandle) ?? cookieSlices.get(projectorHandle));\n if (\n projectorSlice === undefined &&\n projectorHandle !== undefined &&\n projectorData !== undefined &&\n cookieSlices.size + projectorSlices.size < COOKIE_SLICE_CAPACITY\n ) {\n projectorSlice = cookieSlices.size + projectorSlices.size;\n projectorSlices.set(projectorHandle, projectorSlice);\n }\n const shadowIntensity = s.shadowIntensity;\n // `shared<T>` columns are u32-backed and zero-filled when the optional\n // field is absent. Treat only a positive handle as an authored projector;\n // checking nullish values alone would turn the zero sentinel into a\n // phantom projector matrix and an avoidable asset-not-found diagnostic.\n let lightViewProj: Float32Array | undefined;\n let shadowAtlasTile = -1;\n\n // A projector needs the same perspective transform even when its SpotLight\n // has no shadow atlas tile. The matrix remains a derived light fact; the\n // shadow tile stays -1 so shadow visibility is still independently gated.\n if ((castShadow || hasProjector) && hasValidDirection) {\n const target = vec3.create(\n (position[0] ?? 0) + (dirN[0] ?? 0),\n (position[1] ?? 0) + (dirN[1] ?? 0),\n (position[2] ?? 0) + (dirN[2] ?? 0),\n );\n // D-1: perspective(outerConeDeg*2, aspect=1, near, far) x lookAt(pos, pos+dir).\n // FOV = outerConeDeg * 2 in degrees; mat4.perspective takes fov in radians.\n const fov = outerConeDeg * 2 * (Math.PI / 180);\n const proj = mat4.create();\n mat4.perspective(proj, fov, 1, sNearPlane, sFarPlane);\n const view = mat4.create();\n mat4.lookAt(view, position, target, vec3.create(0, 1, 0));\n lightViewProj = new Float32Array(16);\n // Reinterpret the Float32Array surface field as a Mat4 out-param; a\n // factory would force a needless alloc+copy. brand-cast-ok\n mat4.multiply(lightViewProj as Mat4, proj, view);\n\n // D-4: allocate tile 0..3; 5th+ = -1 sentinel.\n if (castShadow && spotTileNext < 4) {\n shadowAtlasTile = spotTileNext;\n spotTileNext += 1;\n }\n }\n\n spotSnapshots.push({\n kind: 'spot',\n entity: row.entity,\n worldId: context.worldId,\n // D-6: position reflects world transform; direction stays sourced\n // from SpotLight.direction (NOT rotated by the parent).\n position,\n direction: dirN,\n color: vec3.create(\n (s.color[0] ?? 1) * intensity,\n (s.color[1] ?? 1) * intensity,\n (s.color[2] ?? 1) * intensity,\n ),\n intensity,\n invRangeSquared: computeInvRangeSquared(range),\n cosInner: degToCos(innerConeDeg),\n cosOuter: degToCos(outerConeDeg),\n ...(s.iesProfile === undefined\n ? {}\n : {\n iesProfileHandle: handleSlot(s.iesProfile),\n ...(iesProfileSlice === undefined ? {} : { iesProfileSlice }),\n }),\n ...(s.cookie === undefined\n ? {}\n : {\n cookieHandle: handleSlot(s.cookie),\n ...(cookieSlice === undefined ? {} : { cookieSlice }),\n }),\n ...(iesProfileData === undefined ? {} : { iesProfileData }),\n ...(cookieData === undefined ? {} : { cookieData }),\n ...(cookieProjection === undefined ? {} : { cookieMatrix: cookieProjection.matrix }),\n ...(projectorSlice === undefined ? {} : { projectorSlice }),\n ...(projectorData === undefined ? {} : { projectorData }),\n ...(projectorProjection === undefined ? {} : { projectorMatrix: projectorProjection.matrix }),\n rollDeg: s.rollDeg,\n // ── shadow fields ──\n castShadow,\n lightViewProj,\n mapSize: sMapSize,\n nearPlane: sNearPlane,\n farPlane: sFarPlane,\n shadowAtlasTile,\n shadowIntensity,\n depthBias: s.depthBias,\n normalBias: s.normalBias,\n pcfKernelSize: s.pcfKernelSize,\n ...(projectorHandle === undefined ||\n projectorAsset === undefined ||\n projectorGuid === undefined\n ? {}\n : {\n projectorHandle,\n projectorAsset,\n projectorGuid,\n projectorGeneration: 1,\n projectorRevision: 1,\n }),\n });\n }\n\n const rectSnapshots: RectAreaDirectLightSnapshot[] = [];\n const rectLightQuery = world\n .query({\n read: [RectAreaLight],\n optional: [Transform, GlobalTransform],\n })\n .unwrap();\n for (const row of rectLightQuery) {\n const light = row.get(RectAreaLight);\n const validation = validateRectAreaLightData({\n intensity: light.intensity,\n color: light.color,\n width: light.width,\n height: light.height,\n range: light.range,\n });\n if (!validation.ok) {\n worldInternal._routeError(validation.error, {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (rect-area-light)',\n });\n continue;\n }\n const worldView = row.get(GlobalTransform);\n const worldMat =\n worldView === undefined\n ? undefined\n : new Float32Array(worldInternal._getArrayView(row.entity, GlobalTransform, 'world') ?? []);\n const position =\n worldMat !== undefined ? mat4.getTranslation(vec3.create(), worldMat) : vec3.create(0, 0, 0);\n const frame = buildRectAreaWorldFrame({\n center: position,\n axisX: [worldMat?.[0] ?? 1, worldMat?.[1] ?? 0, worldMat?.[2] ?? 0],\n axisY: [worldMat?.[4] ?? 0, worldMat?.[5] ?? 1, worldMat?.[6] ?? 0],\n width: light.width,\n height: light.height,\n });\n rectSnapshots.push({\n kind: 'rect-area',\n position,\n color: vec3.create(\n (light.color[0] ?? 1) * light.intensity,\n (light.color[1] ?? 1) * light.intensity,\n (light.color[2] ?? 1) * light.intensity,\n ),\n intensity: light.intensity,\n invRangeSquared: computeInvRangeSquared(light.range),\n halfWidth: frame.halfWidth,\n halfHeight: frame.halfHeight,\n axisX: frame.axisX,\n axisY: frame.axisY,\n });\n }\n // The SpotLight is the sole projector owner. Once all light snapshots have\n // been extracted, publish its accepted TextureAsset tuple on the volume\n // snapshot so surface and volume consume the same identity and revision.\n let volumeSpot: SpotLightSnapshot | undefined;\n const extractedFog = volumetricFog;\n if (extractedFog !== undefined) {\n if (extractedFog.spotLightEntity !== undefined) {\n volumeSpot = spotSnapshots.find((light) => light.entity === extractedFog.spotLightEntity);\n } else if (extractedFog.lightKind === 'spot') {\n volumeSpot = spotSnapshots.find((light) => light.entity === extractedFog.lightEntity);\n }\n }\n if (\n volumetricFog !== undefined &&\n volumetricFog.status === 'available' &&\n volumeSpot?.projectorAsset !== undefined &&\n volumeSpot.projectorHandle !== undefined\n ) {\n const projectorHandle = volumeSpot.projectorHandle;\n const projectorAsset = volumeSpot.projectorAsset;\n volumetricFog = {\n ...volumetricFog,\n projector: {\n guid: volumeSpot.projectorGuid ?? `handle:${Number(volumeSpot.projectorHandle)}`,\n generation: volumeSpot.projectorGeneration ?? 1,\n view: '2d',\n sampler: 'linear-clamp-to-edge',\n projection: 'spot-projection',\n revision: volumeSpot.projectorRevision ?? 1,\n },\n projectorHandle,\n projectorAsset,\n };\n }\n\n // bug-20260710-editor-cross-world-shadow: CSM matrices are computed by the\n // shared pure {@link computeDirectionalCsm}, called here per-world with THIS\n // world's own `cameras[0]`. In a single-world app the light and camera share\n // the world, so this per-world result is final. In the editor\n // super-composite the light's world may have no camera → this yields no\n // matrices; {@link extractFrames} then RECOMPUTES at\n // the merge layer using the surfaced (cameraOwner) camera + the raw config\n // carried on ExtractedLights. The raw config + direction are surfaced\n // unconditionally so the merge layer can re-run the builder.\n let lightViewProj: Float32Array[] | undefined;\n let splitPlanes: Float32Array | undefined;\n let cascadeCount: number | undefined;\n let cascadeBlend: number | undefined;\n let shadowMapSize: number | undefined;\n let directionalShadowQuality: DirectionalShadowQuality | undefined;\n let directionalCsmConfig: DirectionalCsmConfig | undefined;\n let directionalCsmDirection: Vec3 | undefined;\n\n // Camera data needed for frustum corner computation (first camera only;\n // multi-camera CSM is OOS-1). Undefined in a cameraless world.\n const cam0 = cameras[0];\n const cameraData: CsmCameraData | undefined =\n cam0 !== undefined\n ? {\n world: cam0.world,\n fov: cam0.fov,\n aspect: cam0.aspect,\n near: cam0.near,\n far: cam0.far,\n projection: cam0.projection,\n orthoLeft: cam0.orthoLeft,\n orthoRight: cam0.orthoRight,\n orthoBottom: cam0.orthoBottom,\n orthoTop: cam0.orthoTop,\n }\n : undefined;\n\n // feat-20260621 M2: CSM computation gated on castShadow from the\n // merged DirectionalLight. castShadow defaults to true (first-hit-wins\n // semantics, D-6 no cardinality cap).\n if (\n directional !== undefined &&\n firstHitCastShadow !== false &&\n directionalShadowError === undefined\n ) {\n const dirSnapshot = directional;\n const sf = firstHitShadowFields;\n if (sf !== undefined) {\n directionalCsmConfig = {\n cascadeCount: sf.cascadeCount,\n splitLambda: sf.splitLambda,\n cascadeBlend: sf.cascadeBlend,\n mapSize: sf.mapSize,\n shadowDistance: sf.shadowDistance,\n shadowFilter: sf.shadowFilter,\n shadowAngularRadius: sf.shadowAngularRadius,\n maxPenumbraTexels: sf.maxPenumbraTexels,\n };\n directionalCsmDirection = dirSnapshot.direction;\n const csm = computeDirectionalCsm(dirSnapshot.direction, directionalCsmConfig, cameraData);\n // Cascade metadata (splitPlanes / count / blend / mapSize) is available\n // even without a camera (splitPlanes needs only near/far); the matrices\n // need the camera. When csm is null (no camera) leave lightViewProj\n // undefined — the merge layer recomputes. Still surface the split/count\n // metadata so a single-world path keeps its prior fields.\n cascadeCount = Math.round(sf.cascadeCount);\n cascadeBlend = sf.cascadeBlend;\n shadowMapSize = sf.mapSize;\n if (csm !== null) {\n lightViewProj = csm.lightViewProj;\n splitPlanes = csm.splitPlanes;\n directionalShadowQuality = csm.directionalShadowQuality;\n } else {\n const sNear = cameraData?.near ?? 0.1;\n const splits = pssmSplit(sNear, sf.shadowDistance, cascadeCount, sf.splitLambda);\n const padded = new Float32Array(16);\n for (let i = 0; i < splits.length; i++) padded[i * 4] = splits[i] ?? 0;\n splitPlanes = padded;\n }\n directionalShadowQuality = directionalShadowQualityFromF32(\n sf.shadowFilter,\n sf.shadowAngularRadius,\n sf.maxPenumbraTexels,\n );\n }\n }\n\n // feat-20260613-csm M3 / w14 (plan-strategy §D-7): pad the up-to-4\n // splitPlanes into a fixed length-4 Float32Array (unused slots = 0) so\n // the View UBO tail keeps a stable layout regardless of the runtime\n // cascadeCount. Host-side correctness invariant: only the first\n // cascadeCount slots are ever read by the WGSL kernel.\n const paddedSplitPlanes = new Float32Array(16);\n if (splitPlanes !== undefined) {\n for (let i = 0; i < splitPlanes.length; i++) {\n paddedSplitPlanes[i] = splitPlanes[i] ?? 0;\n }\n }\n\n // feat-20260612-point-light-shadows-urp-hdrp M1 / T-M1-7 (plan-strategy §D-3,\n // requirements §5.3): query (PointLight + PointLightShadow + Transform)\n // archetype join. For each shadow caster, build 6 face VP matrices and pack\n // into Float32Array(96). Atlas layer is assigned in spawn order while the\n // renderer-owned atlas has capacity; the sentinel -1 is shader-side and\n // applies to non-admitted PointLightShadow requests as well.\n const pointShadowSnapshots: PointShadowSnapshot[] = [];\n {\n const pointShadowQuery = world\n .query({ read: [Transform, GlobalTransform, PointLightShadow], with: [PointLight] })\n .unwrap();\n for (const row of pointShadowQuery) {\n const ps = row.get(PointLightShadow);\n // Read world-space position from GlobalTransform.world (mat4 column-major;\n // translation lives at indices 12..14, mirroring CameraSnapshot.world\n // semantics in this file).\n // feat-20260614 M4 / w13: TypedArrayFor for `array<f32, 16>` now\n // resolves to a concrete `Float32Array` (was `never` pre-w11), which\n // surfaces the row-window slicing -- `t.world` is the stride-16 flat\n // column view; row i lives at `[i*16, (i+1)*16)`. The prior\n // `t.world?.[i]` form silently returned a single element under the\n // `never`-typed bundle path and `wRow[12]` widened to `undefined ?? 0`\n // so light positions clamped to the origin.\n const wRow = row.get(GlobalTransform).world;\n if (wRow === undefined) continue;\n const px = wRow[12] ?? 0;\n const py = wRow[13] ?? 0;\n const pz = wRow[14] ?? 0;\n const lightPos = vec3.create(px, py, pz);\n const mapSize = ps.mapSize;\n const nearPlane = ps.nearPlane;\n const farPlane = ps.farPlane;\n // The renderer, not ECS, owns the atlas budget. Preserve every request\n // for inspection, but emit the shader sentinel for entries that cannot\n // acquire a layer so record never calls faceView outside the atlas.\n const layer =\n pointShadowSnapshots.length < SHADOW_ATLAS_DEFAULT_LAYERS\n ? pointShadowSnapshots.length\n : -1;\n\n const matrices = buildPointShadowMatrices(lightPos, nearPlane, farPlane);\n const packed = new Float32Array(96);\n for (let f = 0; f < 6; f++) {\n const m = matrices[f];\n if (m === undefined) continue;\n for (let k = 0; k < 16; k++) {\n packed[f * 16 + k] = m[k] ?? 0;\n }\n }\n pointShadowSnapshots.push({\n entity: row.entity,\n worldId: context.worldId,\n position: lightPos,\n mapSize,\n nearPlane,\n farPlane,\n depthBias: ps.depthBias,\n normalBias: ps.normalBias,\n shadowAtlasLayer: layer,\n shadowMatrices: packed,\n });\n }\n }\n\n // feat-20260612-point-light-shadows-urp-hdrp M4 / T-M4-4 (plan-strategy §D-8):\n // join pointShadow snapshots into the matching PointLightSnapshot so the\n // record stage threads `shadowAtlasLayer + shadowNear + shadowFar` through\n // the unified direct-light metadata payload.\n // Mutates the freshly-built PointLightSnapshot in place; the snapshot is\n // not exposed elsewhere this frame yet (consumed only by lights.point[]).\n if (pointShadowSnapshots.length > 0) {\n const shadowByEntity = new Map<number, PointShadowSnapshot>();\n for (const ps of pointShadowSnapshots) shadowByEntity.set(ps.entity, ps);\n for (let i = 0; i < pointSnapshots.length; i++) {\n const entityId = pointSnapshotEntities[i] ?? 0;\n const ps = shadowByEntity.get(entityId);\n if (ps !== undefined) {\n pointSnapshots[i] = {\n ...(pointSnapshots[i] as PointLightSnapshot),\n shadowAtlasLayer: ps.shadowAtlasLayer,\n shadowNear: ps.nearPlane,\n shadowFar: ps.farPlane,\n };\n }\n }\n }\n\n const lights: ExtractedLights = {\n directional,\n directionalCount,\n point: pointSnapshots,\n spot: spotSnapshots,\n rect: rectSnapshots,\n lightViewProj,\n splitPlanes: splitPlanes !== undefined ? paddedSplitPlanes : undefined,\n cascadeCount,\n cascadeBlend,\n shadowMapSize,\n depthBias: firstHitCastShadow !== false ? firstHitShadowFields?.depthBias : undefined,\n normalBias: firstHitCastShadow !== false ? firstHitShadowFields?.normalBias : undefined,\n directionalShadowQuality,\n directionalShadowError,\n pointShadow: pointShadowSnapshots,\n // bug-20260710-editor-cross-world-shadow: raw CSM config + light direction\n // so the merge layer can recompute matrices against the surfaced camera.\n directionalCsmConfig,\n directionalCsmDirection,\n };\n\n // A caster may be outside the display camera while still contributing to a\n // light's shadow map. Keep the light-space visibility projection alongside\n // camera culling so the direct extraction path and persistent composition\n // retain the same shadow-only rule.\n const shadowFrusta = cullMode === 'none' ? [] : buildShadowFrusta(lights);\n\n // feat-20260520-skylight-ibl-cubemap M4 / t26+t27: query Skylight entities.\n // First archetype hit wins (mirrors DirectionalLight pattern); multi-Skylight\n // warn in record stage (t27) uses skylightCount.\n const skylightQuery = world.query({ read: [Skylight] }).unwrap();\n let skylight: SkylightSnapshot | undefined;\n let skylightCount = 0;\n for (const row of skylightQuery) {\n const s = row.get(Skylight);\n // equirect is OPTIONAL: an omitted field zero-inits to handle 0, which\n // record treats as \"no equirect\" -> solid-color ambient via the white\n // fallback cube. A Skylight WITHOUT an equirect is still a valid snapshot\n // (the prior `equirectRaw !== undefined` gate dropped color-only\n // skylights, leaving the scene black -- the downstream gap #4).\n const equirectRaw = s.equirect;\n const intensity = s.intensity;\n const colorR = s.color[0] ?? 1.0;\n const colorG = s.color[1] ?? 1.0;\n const colorB = s.color[2] ?? 1.0;\n const rotation: [number, number, number, number] = [\n s.rotation[0] ?? 0,\n s.rotation[1] ?? 0,\n s.rotation[2] ?? 0,\n s.rotation[3] ?? 1,\n ];\n skylightCount += 1;\n if (skylight === undefined) {\n skylight = {\n equirectHandle: equirectRaw !== undefined ? Math.round(equirectRaw) : 0,\n color: [colorR, colorG, colorB],\n intensity,\n rotation,\n // w19: winning entity handle for the multi-Skylight once-warn (F-8).\n entityHandle: row.entity,\n };\n }\n }\n\n const lightProbeQuery = world.query({ read: [LightProbe, GlobalTransform] }).unwrap();\n const lightProbes: LightProbeSnapshot[] = [];\n for (const row of lightProbeQuery) {\n const probe = row.get(LightProbe);\n const validation = validateLightProbeData({\n irradiance: probe.irradiance,\n radius: probe.radius,\n });\n if (!validation.ok) {\n worldInternal._routeError(validation.error, {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (light-probe)',\n });\n continue;\n }\n const transform = row.get(GlobalTransform);\n lightProbes.push({\n identity: String(row.entity),\n worldId: context.worldId,\n position: [transform.world[12] ?? 0, transform.world[13] ?? 0, transform.world[14] ?? 0],\n radius: probe.radius,\n irradiance: new Float32Array(probe.irradiance),\n admitted: true,\n });\n }\n\n // feat-20260531-skybox-env-background M2 / w5: query SkyboxBackground entities.\n // First archetype hit wins (mirrors Skylight pattern); multi-entity\n // once-warn in record stage uses skyboxCount.\n const skyboxQuery = world.query({ read: [SkyboxBackground] }).unwrap();\n let skybox: SkyboxSnapshot | undefined;\n let skyboxCount = 0;\n for (const row of skyboxQuery) {\n const s = row.get(SkyboxBackground);\n const equirectRaw = s.equirect;\n const modeRaw = s.mode;\n const rotation: [number, number, number, number] = [\n s.rotation[0] ?? 0,\n s.rotation[1] ?? 0,\n s.rotation[2] ?? 0,\n s.rotation[3] ?? 1,\n ];\n skyboxCount += 1;\n if (skybox === undefined && equirectRaw !== undefined) {\n skybox = {\n equirectHandle: Math.round(equirectRaw),\n mode: modeRaw,\n rotation,\n // w19: winning entity handle for the multi-SkyboxBackground warn (F-8).\n entityHandle: row.entity,\n };\n }\n }\n\n const environmentCandidates: EnvironmentCandidate[] = [];\n const imageEnvironment =\n skylight?.equirectHandle !== undefined && skylight.equirectHandle > 0\n ? skylight\n : skybox?.equirectHandle !== undefined && skybox.equirectHandle > 0\n ? skybox\n : undefined;\n if (imageEnvironment !== undefined) {\n environmentCandidates.push({\n kind: 'image',\n entityKey: imageEnvironment.entityHandle,\n sourceKey: `equirect:${imageEnvironment.equirectHandle}`,\n });\n }\n const atmosphereQuery = world.query({ read: [Atmosphere] }).unwrap();\n for (const row of atmosphereQuery) {\n const value = row.get(Atmosphere);\n const atmosphere = {\n turbidity: value.turbidity,\n rayleigh: value.rayleigh,\n mieCoefficient: value.mieCoefficient,\n mieDirectionalG: value.mieDirectionalG,\n sunAngularRadius: value.sunAngularRadius,\n circumsolarStrength: value.circumsolarStrength,\n circumsolarWidth: value.circumsolarWidth,\n } as const;\n environmentCandidates.push({\n kind: 'atmosphere',\n entityKey: row.entity,\n sourceKey: `atmosphere:${row.entity}`,\n atmosphere,\n });\n }\n const directionalDirection = directional?.direction;\n const directionalLength =\n directionalDirection === undefined\n ? 0\n : Math.hypot(\n directionalDirection[0] ?? 0,\n directionalDirection[1] ?? 0,\n directionalDirection[2] ?? 0,\n );\n const sunIntensity = directional?.intensity ?? 0;\n const sunColor =\n sunIntensity > 0 && directional !== undefined\n ? ([\n (directional.color[0] ?? 0) / sunIntensity,\n (directional.color[1] ?? 0) / sunIntensity,\n (directional.color[2] ?? 0) / sunIntensity,\n ] as [number, number, number])\n : ([0, 0, 0] as [number, number, number]);\n const sun =\n directional === undefined || directional.entity === undefined || directionalLength <= 1e-6\n ? []\n : [\n {\n entityKey: directional.entity,\n direction: [\n -(directionalDirection?.[0] ?? 0) / directionalLength,\n -(directionalDirection?.[1] ?? 0) / directionalLength,\n -(directionalDirection?.[2] ?? 0) / directionalLength,\n ] as [number, number, number],\n color: sunColor,\n intensity: directional.intensity,\n },\n ];\n const environmentSelection = selectEnvironment({\n environments: environmentCandidates,\n fogs: fog === undefined ? [] : [fog],\n suns: sun,\n lane: 'direct',\n });\n if (!environmentSelection.ok) {\n routeWorldError(world, environmentSelection.error, {\n systemName: 'RenderSystem.extract (environment-selection)',\n });\n throw environmentSelection.error;\n }\n const environment: EnvironmentFrame = environmentSelection.value;\n\n // feat-20260528-frustum-culling M3 / w10: precompute per-camera frustum\n // planes so entities can be tested against all cameras in the inner loop.\n // Cameras with degenerate projection parameters (e.g. zero fov, zero aspect)\n // are skipped — entities are always-visible for those. Frustum plane cache\n // stored as Float32Array[] parallel to the cameras[] array.\n //\n // feat-20260708-composited-multi-world-rendering M2 / D-4: a composite\n // non-owner world uses the camera-owner snapshots, not its own cameras.\n // This keeps culling correct when the surfaced camera and renderables live\n // in different worlds. The explicit 'none' mode remains the always-visible\n // escape hatch for callers that genuinely need it.\n const frustumPlanes: Float32Array[] = [];\n const cullingCameras = cullMode === 'external' ? (context.cullCameras ?? []) : cameras;\n if (cullMode !== 'none') {\n for (const cam of cullingCameras) {\n // feat-20260613 M6 / w20: orthographic cameras have fov=0 by design;\n // the previous degeneracy guard (`fov <= 0`) was rejecting valid ortho\n // cameras and returning the always-visible escape hatch. Only the\n // perspective path needs the fov check.\n if (cam.projection === 'perspective' && (cam.fov <= 0 || cam.aspect <= 0)) {\n frustumPlanes.push(new Float32Array(0)); // degenerate → always-visible\n continue;\n }\n if (cam.near >= cam.far) {\n frustumPlanes.push(new Float32Array(0));\n continue;\n }\n const proj = mat4.create();\n if (cam.projection === 'orthographic') {\n mat4.orthographic(\n proj,\n cam.orthoLeft,\n cam.orthoRight,\n cam.orthoTop,\n cam.orthoBottom,\n cam.near,\n cam.far,\n );\n } else {\n mat4.perspective(proj, cam.fov, cam.aspect, cam.near, cam.far);\n }\n // feat-20260601 D-3: view = invert(camera world mat4). The camera scale is\n // carried in the world basis columns; the cull frustum uses the same view\n // the record stage derives, so cull stays same-source with render (AC-05).\n const view = mat4.create();\n mat4.invert(view, cam.world);\n const vp = mat4.create();\n mat4.multiply(vp, proj, view);\n const f = frustum.create();\n frustum.fromViewProjection(f, vp);\n frustumPlanes.push(f);\n }\n }\n\n const renderables: RenderableSnapshot[] = [];\n // feat-20260528-frustum-culling M3 / w11: frustum culling counters.\n let frustumCulled = 0;\n let frustumTotal = 0;\n const explicitlyHidden = new Set<EntityHandle>();\n // feat-20260520-2d-sprite-layer-mvp M-3 / w22 (@new-surface): three-\n // bucket dispatch arrays. The legacy `materialDispatch` field stays as\n // a back-compat union (opaque + transparent + overlay back-compat\n // entries) so the pre-w25 RenderSystem.draw consumer loop keeps\n // working until M-3 / w25 lands the bucket-aware record. Plan-strategy\n // §6.1 (back-compat field stays until M-4 acceptance round green).\n // M3 / w26: single dispatch list replaces old three-bucket model\n // (plan-strategy D-3). Entries built per-entity per-pass inside the\n // archetype walk, then sorted by queue at the end.\n let dispatch: DispatchEntry[] = [];\n const shadowMembershipEntries: ShadowCasterMembership[] = [];\n // Keep the derived material snapshot and its resolved passes local to this\n // extraction. Shared handles are immutable inputs for the frame, while\n // dispatch entries still need to be rebuilt for each entity.\n const materialSnapshotCache: MaterialSnapshotCache = new Map();\n const skinnedMaterialSnapshotCache: MaterialSnapshotCache = new Map();\n // tweak-20260611 M1: MeshRenderer renderable archetype walk routes\n // through one World-owned Query. K-2 sniffing scheme B\n // (`row.get(X) !== undefined` edge sniff) replaces the prior\n // `arch.components.some` row-internal back-door. K-3 invariant: the\n // variable-length array reads (`MeshRenderer.materials`, SpriteInstances\n // arrays) still flow through `_getArrayView`; explicit Instances bytes come\n // from the renderer-owned collection store.\n //\n // archVersion remains the content fingerprint for SpriteInstances' managed\n // arrays; explicit Instances use the collection revision below and never\n // need an archetype graph access for their matrix bytes.\n // feat-20260521-sprite-atlas-animation M3 / T-16: SpriteRegionOverride\n // column id for the sprite-bucket per-entity region override read\n void SpriteRegionOverride;\n\n const meshRendererQuery =\n context.renderables === 'none'\n ? []\n : world\n .query({\n read: [MeshRenderer],\n optional: [\n Transform,\n GlobalTransform,\n MeshFilter,\n Instances,\n Skin,\n Layer,\n MorphWeights,\n SpriteRegionOverride,\n SpriteInstances,\n Points,\n Lines,\n SortKey,\n ],\n })\n .unwrap();\n // QueryRow deliberately exposes component data, not an archetype version.\n // SpriteInstances still uses a content fingerprint for its managed arrays;\n // explicit Instances use the renderer-owned collection revision below.\n const resolveArchVersion = (entity: EntityHandle): number => {\n const values = [\n worldInternal._getArrayView(entity, SpriteInstances, 'transforms'),\n worldInternal._getArrayView(entity, SpriteInstances, 'regions'),\n ];\n let hash = 2166136261;\n for (const value of values) {\n hash = Math.imul(hash ^ (value?.length ?? 0), 16777619) >>> 0;\n if (value === undefined) continue;\n for (let index = 0; index < value.length; index += 1) {\n hash = Math.imul(hash ^ Math.fround(value[index] ?? 0), 16777619) >>> 0;\n }\n }\n return hash;\n };\n // Pending entries are created with the current renderables.length, which is\n // exactly the slot this entity receives if it survives culling. No other\n // renderable can be pushed between staging and this entity's push, so publish\n // the original fresh entries instead of cloning every submesh descriptor.\n // A culled entity still discards its private pending array unchanged.\n const flushPendingDispatch = (pending: readonly DispatchEntry[]): void => {\n for (const entry of pending) dispatch.push(entry);\n };\n const requestedRows =\n renderableEntities === undefined\n ? meshRendererQuery\n : {\n *[Symbol.iterator]() {\n for (const entity of renderableEntities) {\n const row = meshRendererQuery.at(entity as EntityHandle);\n if (row !== undefined) yield row;\n }\n },\n };\n for (const row of requestedRows) {\n // K-2 archetype-edge sniff (scheme B): a missing optional component\n // surfaces as an absent bundle key, not a row-internal optional chain.\n // Presence-only checks use QueryRow.has so large array-bearing components\n // are not materialised merely to answer a boolean question.\n const hasTransform = row.has(Transform);\n const meshFilter = row.get(MeshFilter);\n const hasInstances = row.has(Instances);\n const skin = row.get(Skin);\n const morphWeightsView = worldInternal._getArrayView(row.entity, MorphWeights, 'weights');\n const hasMeshFilter = meshFilter !== undefined;\n const hasSkin = skin !== undefined;\n // feat-20260625-sprite-instances-and-tilemap-terrain-static-batch M3 / w10:\n // SpriteInstances optional component archetype-edge sniff. Three structured\n // EcsError codes fire at the row-loop entry (D-6 fail-fast at extract):\n // - 'sprite-instances-mutually-exclusive-with-instances'\n // (hasInstances && hasSpriteInstances) — Instances + SpriteInstances peers.\n // - 'sprite-instances-requires-sprite-shading-model'\n // (materialSnap.materialShaderId !== 'forgeax::sprite') — non-sprite material.\n // - 'sprite-instances-count-mismatch'\n // (transforms.length / 16 !== regions.length / 4) — stride pair desync.\n const hasSpriteInstances = row.has(SpriteInstances);\n const points = row.get(Points);\n const lines = row.get(Lines);\n const sortKey = row.get(SortKey)?.value;\n const pointsLinesComponent =\n points !== undefined ? 'Points' : lines !== undefined ? 'Lines' : undefined;\n const isRenderable = hasTransform && hasMeshFilter;\n\n // The resolved world transform is read per-entity from the single\n // `GlobalTransform.world` mat4 (propagateTransforms output) inside the row\n // loop below. Normal structural paths materialize this carrier through\n // Transform's generic ECS requirement; keep the defensive row check because\n // an owner can explicitly remove a required component during recovery.\n const fAssetHandle = meshFilter?.assetHandle;\n // feat-20260520-2d-sprite-layer-mvp M-3 / w22: Layer column read here;\n // value folded into each DispatchEntry so the render-system sort can use\n // it as the primary transparent-sort key without a second ECS round-trip.\n const fLayerValue = row.get(Layer)?.value;\n // feat-20260608-tilemap-object-layer-rendering M3 / m3-t5: tilemap-spawned\n // per-cell render entities (the ones `tilemap-chunk-extract-system`\n // pushes via `spawnDerivedRenderEntities`) reach this loop via the same\n // archetype edge that carries a sprite entity -- they all wear\n // `MeshFilter.assetHandle === HANDLE_QUAD` + a `forgeax::sprite`-shaded\n // material asset + the sprite-bucket `values.region` rectangle.\n // For the per-entity Y-sort path (requirements §AC-12 / §AC-13):\n //\n // sortKey = -(Transform.posY - effectivePivotY * |Transform.scaleY|)\n //\n // with `effectivePivotY = effectivePivotYForTilemapFlip(pivotY, pivotX,\n // flipV, flipDiagonal)` from `tilemap-chunk-extract-system` (the SAME\n // helper drives `spawnDerivedRenderEntities`, so the value the sort\n // uses matches the value baked into `Transform.posY` -- charter P4\n // single SSOT for the post-flip pivot). Sprite entities reuse the same\n // formula but skip the flip composition (their pivot stays raw); both\n // bucket types therefore feed one `transparentSortEntries` argsort\n // step + share the `argsortInPlace` radix LSD primitive (plan-strategy\n // §D-1 / §D-3). The detection lives on the material side -- detect a\n // tilemap-spawned entity by `MeshFilter.assetHandle === HANDLE_QUAD`\n // plus the `forgeax::sprite` shader id on `MeshRenderer.material`'s\n // first pass + non-empty `values.region`; no new public ECS\n // marker component lands (charter F1 minimum surface).\n //\n // Layer.value is now folded into each DispatchEntry.layer (fLayerValue\n // column, read once per archetype pass above). render-system.ts\n // `sortTransparentDispatch` applies (layer ASC, sortValue ASC) for all\n // transparent-sort modes (0/1/2) using posY/pivotY/sizeY from the\n // parallel renderables[] snapshot -- no second ECS round-trip needed.\n // feat-20260527-sprite-nineslice M4 / w17 (AC-14): SpriteRegionOverride\n // per-entity UV sub-rectangle. When the entity carries this component the\n // 4-float `[uMin, vMin, uW, vH]` override displaces the asset-side\n // `values.region` for this entity only — downstream 9-slice logic\n // measures slices against this effective region.zw, so a half-width sub-\n // sprite reduces the anchor budget to 0.5 rather than the asset's 1.0.\n //\n // SpriteRegionOverride.region is a fixed stride-4 value. Per-row reads\n // route through `_getArrayView` for the zero-copy row window\n // row-window slice (consistent with the variable-length array column\n // reads -- K-3 carve-out keeps `_getArrayView` as the row-accessor of\n // record for each non-scalar column).\n const hasSpriteRegionOverride = row.has(SpriteRegionOverride);\n // feat-20260523-skin-skeleton-animation M2 / T-21: Skin component\n // column views for coexistence check + joint despawn fail-fast.\n // `skeleton` holds the packed Handle<SkeletonAsset>; `joints` holds\n // the packed Entity u32 array (N x one u32 each).\n const skinSkeletonView = skin?.skeleton;\n\n let archVersion = 0;\n if (hasInstances || hasSpriteInstances) {\n // All rows in this callback share one archetype. Only these two\n // instance-bearing paths consume the version in their cache key.\n archVersion = resolveArchVersion(row.entity);\n }\n\n {\n // feat-20260608 M2 / w11: read materials array via _getArrayView\n const entity = row.entity;\n const authorVisible = !(isRenderable && visibility?.effective(entity) === 'hidden');\n if (!authorVisible) explicitlyHidden.add(entity);\n if (!authorVisible && !retainHidden) {\n continue;\n }\n // A scalar shared<T> field uses slot 0 as the schema-level unbound\n // sentinel. An entity carrying an unbound MeshFilter is not a\n // renderable yet; keep it out of frame validation. Non-zero handles\n // still follow the normal resolve/error path below.\n if (isRenderable && fAssetHandle === 0) {\n continue;\n }\n const layerVal = fLayerValue ?? 0;\n // bug-20260709-builtin-quad-withoutaabb-disables-sprite-frustum-cu M2.5\n // (carries PR #598 feat-20260703 D-7): dispatch entries for this entity\n // are staged locally and flushed into the shared `dispatch[]` array\n // ONLY when the entity survives the frustum-cull `continue` below —\n // same cull-passed branch as the paired `renderables.push`. Prior to\n // this fix the three `dispatch.push` sites ran before the cull check,\n // so a culled entity left dangling entries whose `renderableIndex`\n // aliased the slot a LATER visible entity occupied — surfacing as the\n // pbr-mesh-array-bgl vs hdrp-unified-bgl-group2 BGL/PL mismatch on\n // the deferred-shading smoke (PR #598 CI). Pure ordering fix; cull\n // logic and MeshRenderer contract unchanged.\n const pendingDispatch: DispatchEntry[] = [];\n const materialsView = worldInternal._getArrayView(entity, MeshRenderer, 'materials') as\n | Uint32Array\n | undefined;\n const materialCount = materialsView?.length ?? 0;\n let materialHandles = Array.from(materialsView ?? []);\n let materialBindingSources: MeshMaterialBindingSource[] = materialHandles.map(\n () => 'renderer-override',\n );\n let materialBindingDiagnostics: MeshMaterialBindingDiagnostic[] = [];\n let gpuDrivenMesh: MeshAsset | undefined;\n\n // Resolve instance overrides against mesh-owned slot defaults once.\n const fAssetHandleVal = fAssetHandle;\n if (\n fAssetHandleVal !== undefined &&\n fAssetHandleVal !== 0 &&\n assets !== undefined &&\n assets !== null\n ) {\n const meshHandle = toShared<'MeshAsset'>(fAssetHandleVal);\n const meshRes = resolveAssetHandle<Asset>(world, meshHandle);\n if (meshRes.ok && meshRes.value.kind === 'mesh') {\n const meshAsset = meshRes.value as MeshAsset;\n const guid = (meshRes.value as { guid?: string }).guid ?? '<no-guid>';\n gpuDrivenMesh = meshAsset;\n // extractFrames is also a public read path and can run before the\n // Renderer.draw pre-render stage. GlyphText proves the derived mesh\n // owns exactly one Default slot; arbitrary meshes still fail closed\n // and never infer slot topology from their submeshes.\n if (!Array.isArray(meshAsset.materialSlots) && world.get(entity, GlyphText).ok) {\n ensureGlyphMeshMaterialSlots(world, meshHandle);\n }\n const resolvedBindings = resolveMeshMaterialBindings(meshAsset, materialsView ?? [], {\n isValidOverride(handle) {\n const resolved = resolveAssetHandle(world, toShared<'MaterialAsset'>(handle));\n return resolved.ok && resolved.value.kind === 'material';\n },\n resolveMeshDefault(defaultGuid) {\n const guidText = AssetGuid.format(defaultGuid);\n if (assets.lookup<Asset>(guidText)?.kind !== 'material') return undefined;\n return internSharedRefFromGuid(world, assets, guidText, 'MaterialAsset') as\n | number\n | undefined;\n },\n });\n if (!resolvedBindings.ok) {\n if (resolvedBindings.code === 'mesh-material-slots-missing') {\n worldInternal._routeError(\n new AssetError({\n code: 'load-failed',\n expected: 'every MeshAsset producer supplies materialSlots[]',\n hint: `fix the MeshAsset producer; renderer inheritance never guesses slot topology (mesh=${guid}, entity=${entity}, vertices=${meshAsset.vertices.length}, indices=${meshAsset.indices?.length ?? 0})`,\n detail: {\n referencedByGuid: guid,\n referencedByKind: 'mesh',\n subAssetGuid: '<material-slots-missing>',\n sourceField: { fieldName: 'materialSlots' },\n },\n }),\n {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (mesh-material-slots-missing)',\n },\n );\n continue;\n }\n const materialGuid = AssetGuid.format(resolvedBindings.defaultMaterial);\n worldInternal._routeError(\n new AssetError({\n code: 'load-failed',\n expected: `MeshAsset materialSlots[${resolvedBindings.slotIndex}] default ${materialGuid} is ready and a MaterialAsset`,\n hint: `loadByGuid(meshGuid) must recursively load the declared default material; mesh=${guid}, slot=${resolvedBindings.slotIndex}, material=${materialGuid}`,\n detail: {\n referencedByGuid: guid,\n referencedByKind: 'mesh',\n subAssetGuid: materialGuid,\n sourceField: {\n fieldName: 'materialSlots',\n arrayIndex: resolvedBindings.slotIndex,\n },\n },\n }),\n {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (mesh-default-not-ready)',\n },\n );\n continue;\n }\n materialHandles = resolvedBindings.bindings.map((binding) => binding.handle);\n materialBindingSources = resolvedBindings.bindings.map((binding) => binding.source);\n materialBindingDiagnostics = resolvedBindings.diagnostics.map((diagnostic) => ({\n ...diagnostic,\n detail:\n diagnostic.code === 'mesh-renderer-material-override-overflow'\n ? {\n expectedCount: meshAsset.materialSlots.length,\n actualCount: materialCount,\n meshAssetGuid: guid,\n }\n : {\n meshAssetGuid: guid,\n slotIndex: diagnostic.slotIndex,\n handle: diagnostic.handle ?? 0,\n },\n }));\n for (const diagnostic of resolvedBindings.diagnostics) {\n worldInternal._routeError(\n new AssetError({\n code: diagnostic.code,\n expected:\n diagnostic.code === 'mesh-renderer-material-override-overflow'\n ? `materials.length <= materialSlots.length (${meshAsset.materialSlots.length})`\n : `materials[${diagnostic.slotIndex}] resolves to a live MaterialAsset`,\n hint: ASSET_ERROR_HINTS[diagnostic.code],\n detail:\n diagnostic.code === 'mesh-renderer-material-override-overflow'\n ? {\n expectedCount: meshAsset.materialSlots.length,\n actualCount: materialCount,\n meshAssetGuid: guid,\n }\n : {\n meshAssetGuid: guid,\n slotIndex: diagnostic.slotIndex,\n handle: diagnostic.handle ?? 0,\n },\n }),\n {\n severity: Severity.Warning,\n systemName: `RenderSystem.extract (${diagnostic.code})`,\n },\n );\n }\n }\n }\n\n if (materialHandles.length === 0) {\n materialHandles = [0];\n materialBindingSources = ['engine-default'];\n }\n\n // Use the first material handle for the entity-level snapshot\n // (shading-model dispatch routing + multi-pass DispatchEntry. Per-\n // submesh materials[i>=1] are resolved by `resolveMaterialSnapshot`\n // below into the `materials[]` array, used by the record stage to\n // upload N material UBO slots and bind the i-th slot before the\n // i-th submesh draw.) -- feat-20260608 M5 amend / w11-a.\n const handleRaw = materialHandles[0] ?? 0;\n\n const cachedMaterial =\n handleRaw !== 0 && !hasSpriteRegionOverride && !hasSkin\n ? materialSnapshotCache.get(handleRaw)\n : undefined;\n\n let materialSnap: MaterialSnapshot;\n let materialProgramSelections: readonly MaterialProgramSelection[] | undefined;\n\n if (cachedMaterial !== undefined) {\n materialSnap = cachedMaterial.snapshot;\n if (isRenderable) {\n appendMaterialDispatchEntries(\n pendingDispatch,\n cachedMaterial.passes,\n entity,\n handleRaw,\n renderables.length,\n layerVal,\n materialSnap.paramSnapshot,\n 0,\n materialSnap.materialProgramKeys,\n );\n }\n } else if (handleRaw === 0 || assets === undefined || assets === null) {\n // case B: missing-spec sentinel -> mid-grey defaultMaterialSnapshot.\n materialSnap = defaultMaterialSnapshot(handleRaw);\n } else {\n const tagged = toShared<'MaterialAsset'>(handleRaw);\n const stablePersistentCached =\n !hasSpriteRegionOverride && !hasSkin\n ? readStablePersistentMaterialSnapshot(\n persistentMaterialSnapshotCache,\n handleRaw,\n assets,\n )\n : undefined;\n if (stablePersistentCached !== undefined) {\n materialSnapshotCache.set(handleRaw, stablePersistentCached);\n materialSnap = stablePersistentCached.snapshot;\n if (isRenderable) {\n appendMaterialDispatchEntries(\n pendingDispatch,\n stablePersistentCached.passes,\n entity,\n handleRaw,\n renderables.length,\n layerVal,\n materialSnap.paramSnapshot,\n 0,\n materialSnap.materialProgramKeys,\n );\n }\n } else {\n const res = resolveAssetHandle(world, tagged);\n if (!res.ok) {\n if (isRenderable) {\n const rhiErr = new RhiError({\n code: 'asset-not-registered',\n expected: 'MeshRenderer.material in AssetRegistry',\n hint: 'catalog the material via assetRegistry.catalog(guid, asset) + world.allocSharedRef before spawn, or remove the material field to fall back to default',\n detail: { assetHandle: handleRaw },\n });\n worldInternal._routeError(rhiErr, {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (material asset-not-registered)',\n });\n }\n continue;\n }\n const asset = res.value;\n if (asset.kind !== 'material') {\n materialSnap = defaultMaterialSnapshot(handleRaw);\n } else {\n // feat-20260529 M3 / w11: material parent chain inheritance via\n // read-through _materialWalk accessor (plan-strategy D-6).\n // The old direct asset.passes / asset.values read never\n // walked the parent chain, causing broken-inheritance (root cause).\n const resolvedResult = walkMaterialPassesOverSharedRefs(world, tagged, assets);\n if (!resolvedResult.ok) {\n // AC-09 / S-7 / q8=A: passes-empty or cycle must fire structured\n // error through _routeError (same routing as asset-not-registered\n // branch above). Silent continue is forbidden because it produces\n // a black screen indistinguishable from a content bug.\n const err = resolvedResult.error;\n switch (err.code) {\n case 'material-parent-not-found':\n case 'material-no-effective-pass':\n case 'material-value-unknown':\n case 'material-value-type-mismatch':\n case 'material-contract-program-mismatch':\n worldInternal._routeError(err, {\n severity: Severity.Error,\n systemName: `RenderSystem.extract (${err.code})`,\n });\n break;\n case 'material-circular-inheritance':\n worldInternal._routeError(err, {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (material-circular-inheritance)',\n });\n break;\n default:\n // Exhaustive guard: unhandled error codes from _materialWalk\n // surface an internal assertion to avoid silent continuation.\n worldInternal._routeError(err, {\n severity: Severity.Error,\n systemName: `RenderSystem.extract (_materialWalk: ${err.code})`,\n });\n }\n continue;\n }\n const resolved = resolvedResult.value;\n const allPasses = resolved.passes;\n const materialContext =\n context.materialContext === undefined\n ? undefined\n : {\n ...context.materialContext,\n geometry: hasSkin ? ('skinned' as const) : context.materialContext.geometry,\n };\n try {\n materialProgramSelections = materialProgramSelectionsForMaterial(\n asset,\n assets,\n materialContext,\n );\n } catch (error) {\n // A standalone mesh can only satisfy a cooked skinned program\n // through a Skin-bearing mesh. Probe that same exact owner\n // selection only when the resolved mesh really lacks the\n // advertised attributes; otherwise retain the producer's exact\n // publication error instead of guessing from module names/order.\n if (isMissingMaterialProgram(error) && materialContext?.geometry === 'mesh') {\n try {\n const skinnedSelections = materialProgramSelectionsForMaterial(asset, assets, {\n ...materialContext,\n geometry: 'skinned',\n });\n if (\n skinnedSelections?.some(materialProgramSelectionRequiresSkin) === true &&\n gpuDrivenMesh !== undefined\n ) {\n const hasSkinIndex = gpuDrivenMesh.attributes.skinIndex !== undefined;\n const hasSkinWeight = gpuDrivenMesh.attributes.skinWeight !== undefined;\n if (!hasSkinIndex || !hasSkinWeight) {\n const missing =\n !hasSkinIndex && !hasSkinWeight\n ? 'both'\n : !hasSkinIndex\n ? 'skinIndex'\n : 'skinWeight';\n worldInternal._routeError(new MaterialSkinAttrMissingError(entity, missing), {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (material-skin-attr-missing)',\n });\n continue;\n }\n }\n } catch {\n // Preserve the original exact-context publication error.\n }\n }\n throw error;\n }\n const materialProgramKeys =\n materialProgramSelections === undefined\n ? undefined\n : Object.fromEntries(\n materialProgramSelections.map(({ pass, specializationKey }) => [\n pass,\n specializationKey,\n ]),\n );\n const materialSceneIndexProgramKeys = materialSceneIndexProgramKeysForMaterial(\n asset,\n assets,\n materialContext,\n );\n const authoredFirstPassShader = runtimeMaterialShaderIdForMaterial(\n allPasses,\n undefined,\n );\n const firstPassShader = runtimeMaterialShaderIdForMaterial(\n allPasses,\n materialProgramKeys,\n );\n const pv = materialValuesToLinearRuntime(\n resolved.values,\n materialColorParameterSchema(resolved.parameters ?? [], firstPassShader, assets),\n resolved.colorSpace,\n ) as Readonly<Record<string, unknown>>;\n\n const baseColorPv = pv.baseColor as readonly number[] | undefined;\n const baseColor = vec3.create(\n baseColorPv?.[0] ?? 1,\n baseColorPv?.[1] ?? 1,\n baseColorPv?.[2] ?? 1,\n );\n const metallicPv = typeof pv.metallic === 'number' ? pv.metallic : 0;\n const roughnessPv = typeof pv.roughness === 'number' ? pv.roughness : 0.5;\n const specularColorPv = pv.specularColor as readonly number[] | undefined;\n const normalScalePv = materialNormalScale(pv);\n\n const paramSnap: Record<string, number | number[] | string> = {};\n for (const [k, v] of Object.entries(pv)) {\n if (typeof v === 'number') paramSnap[k] = v;\n else if (typeof v === 'string') paramSnap[k] = v;\n else if (Array.isArray(v) && v.every((x) => typeof x === 'number')) {\n paramSnap[k] = v as number[];\n }\n }\n\n const materialParamSchema = materialParamSchemaForMaterial(\n resolved.parameters ?? [],\n authoredFirstPassShader,\n allPasses,\n );\n // feat-20260611-fox-skinning-vertex-attribute-chain M4 / w17 (D-5):\n // bidirectional Skin <-> pbr-skin material fail-fast at extract.\n // Skin component without a forgeax::pbr-skin first-pass material\n // would draw with a non-skin shader against the 18-float vertex\n // buffer (joints/weights bytes interpreted as garbage). Conversely\n // a forgeax::pbr-skin material against a 12-float (unskinned) mesh\n // would have @location(4)/@location(5) read uninitialized memory.\n // Both cases route through `_routeError` + `continue` so a single\n // misconfigured entity does NOT abort the whole frame's draw list\n // (charter P3 explicit failure + plan-decisions D-5 over `return err`).\n {\n const hasSkinSkel =\n hasSkin &&\n skinSkeletonView !== undefined &&\n skinSkeletonView !== undefined &&\n skinSkeletonView !== 0;\n const isPbrSkinMaterial =\n materialProgramSelections?.some(materialProgramSelectionRequiresSkin) === true ||\n isStandardPbrSkinMaterialShader(firstPassShader);\n if (hasSkinSkel && !isPbrSkinMaterial) {\n worldInternal._routeError(new SkinMaterialMismatchError(entity, firstPassShader), {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (skin-material-mismatch)',\n });\n continue;\n }\n if (isPbrSkinMaterial && fAssetHandleVal !== undefined && fAssetHandleVal !== 0) {\n const meshHandleForSkinCheck = toShared<'MeshAsset'>(fAssetHandleVal);\n const meshResForSkinCheck = resolveAssetHandle<MeshAsset>(\n world,\n meshHandleForSkinCheck,\n );\n if (meshResForSkinCheck.ok) {\n const meshAttrs = meshResForSkinCheck.value.attributes;\n const hasSkinIdx = meshAttrs.skinIndex !== undefined;\n const hasSkinWt = meshAttrs.skinWeight !== undefined;\n if (!hasSkinIdx || !hasSkinWt) {\n const missing: 'skinIndex' | 'skinWeight' | 'both' =\n !hasSkinIdx && !hasSkinWt ? 'both' : !hasSkinIdx ? 'skinIndex' : 'skinWeight';\n worldInternal._routeError(new MaterialSkinAttrMissingError(entity, missing), {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (material-skin-attr-missing)',\n });\n continue;\n }\n }\n }\n }\n // feat-20260625-refactor-sprite-as-transparent-mesh M3 / w12 (D-3):\n // sprite materials now flow through the same generic paramSchema-\n // driven extract path PBR / unlit use. The narrow `forgeax::sprite`\n // exception block below covers exactly 2 plan-authorised cases:\n // 1. SpriteRegionOverride per-entity region displacement (Q4=a)\n // 2. flipX / flipY -> region fold (plan-strategy D-8)\n // No legacy values field-name shim; demos and SpriteParamValues\n // are UBO-aligned (no `texture` / `baseColor` / `pivot` / `slices`\n // / `sliceMode` keys reaching this code path). AGENTS.md §Change\n // stance: \"no shim layer, no v1/v2 dual-path\".\n //\n // feat-20260624 M1' / t6: `'forgeax::sprite-lit'` walks the same\n // sprite-family vertex path (VsOut byte-identical, paramSchema\n // mirror) so the SAME 2 folds apply — extending `isSprite` to\n // cover both shader ids keeps the narrowing-point count at 1\n // (plan-strategy §1.6 + D-1: mirror sprite, no new branch).\n const isSprite =\n firstPassShader === 'forgeax::sprite' || firstPassShader === 'forgeax::sprite-lit';\n\n // feat-20260613-material-paramschema-driven-binding M4 / w23\n // (D-5 graceful): paramSchema-driven texture-field validation.\n // For each handle-shaped paramValue (typeof === 'number'),\n // verify it actually points at a registered texture asset\n // when the field is declared as a texture in the shader's\n // paramSchema; mis-typed handles (e.g. a scalar f32 stored as\n // int 0 the M4 / w22 graceful fallback resolved to a wrong\n // sub-asset) are dropped here so the record stage falls back\n // to MISSING_TEXTURE_HANDLE (default white) without raising.\n const validateTextureHandle = (\n fieldName: string,\n raw: unknown,\n ): Handle<'TextureAsset', 'shared'> | undefined => {\n // feat-20260614 M8 (D-19): a string value is an embedded texture\n // GUID; resolve it to a column handle via catalog + allocSharedRef\n // before validation. A number is an already-minted column handle.\n let handle: Handle<'TextureAsset', 'shared'>;\n const textureRef = materialTextureRef(raw);\n const textureGuid = assetReferenceText(textureRef);\n if (textureGuid !== undefined) {\n if (assets === null || assets === undefined) return undefined;\n // M4: intern so the GUID mints one stable handle per World\n // instead of a fresh slot every frame (GPU residency relies on\n // a stable handleSlot). onLastRelease -> gpuStore.evictTexture.\n const interned = internSharedRefFromGuid(\n world,\n assets,\n textureGuid,\n 'TextureAsset',\n );\n if (interned === undefined) return undefined;\n handle = interned;\n } else if (typeof textureRef === 'number') {\n handle = toShared<'TextureAsset'>(textureRef);\n } else {\n return undefined;\n }\n if (assets === null || assets === undefined) return handle;\n const declaredFields = materialTextureFields(\n firstPassShader,\n materialParamSchema.length > 0\n ? derive(materialParamSchema).textureFieldNames\n : firstPassShader !== undefined\n ? assets.materialShaderTextureFieldNames(firstPassShader)\n : undefined,\n );\n // Shader not registered (R-4 cross-worktree path) -> trust the\n // raw handle and let the record stage / GPU layer surface each\n // mismatch via MISSING_TEXTURE_HANDLE.\n if (declaredFields === undefined) return handle;\n // Field is not declared as a texture by the shader -> the\n // loader's \"try every int\" fallback misclassified a scalar;\n // drop the slot so the record stage uses the default white.\n if (\n !declaredFields.has(fieldName) &&\n !isEngineInjectedTextureField(firstPassShader, fieldName)\n ) {\n return undefined;\n }\n // Field declared as texture: verify the handle's asset kind.\n const assetRes = resolveAssetHandle(world, handle);\n if (!assetRes.ok) return undefined;\n const kind = (assetRes.value as { kind?: string }).kind;\n if (kind !== 'texture') return undefined;\n return handle;\n };\n // feat-20260614 M8 (D-19): resolve a sampler / texture paramValue\n // that may be an embedded GUID string (catalog + allocSharedRef) or\n // an already-minted column handle (number passthrough).\n const resolveParamHandle = <B extends string>(\n raw: unknown,\n brand: B,\n ): Handle<B, 'shared'> | undefined => {\n const value = materialTextureRef(raw);\n if (typeof value === 'number') return toShared<B>(value);\n const guid = assetReferenceText(value);\n if (guid !== undefined) {\n if (assets === null || assets === undefined) return undefined;\n // M4: intern the GUID -> column-handle resolution (one stable\n // handle per (world, guid, brand), reused across frames).\n return internSharedRefFromGuid(world, assets, guid, brand);\n }\n return undefined;\n };\n // feat-20260621-learn-render-5-5-parallax M2 / w7 (D-3): iterate the\n // shader's derive(paramSchema).textureFieldNames SSOT so the Nth\n // user-region texture (e.g. parallax heightTexture) is validated +\n // carried, replacing the hardcoded 3-field list. validateTextureHandle\n // already drops fields a shader doesn't declare as a texture.\n const userRegionFields =\n materialTextureFields(\n firstPassShader,\n materialParamSchema.length > 0\n ? derive(materialParamSchema).textureFieldNames\n : firstPassShader !== undefined && assets !== null && assets !== undefined\n ? assets.materialShaderTextureFieldNames(firstPassShader)\n : undefined,\n ) ?? BUILTIN_USER_REGION_TEXTURE_FIELDS;\n const authoredTextureFields = collectAuthoredMaterialTextureFields(\n resolved.values,\n firstPassShader,\n materialParamSchema.length > 0 ? materialParamSchema : undefined,\n assets,\n );\n const authoredSamplerFields = collectAuthoredMaterialSamplerFields(\n resolved.values,\n authoredTextureFields,\n );\n const textureHandles = new Map<string, Handle<'TextureAsset', 'shared'>>();\n const videoTextureFields = new Map<string, Handle<'VideoAsset', 'shared'>>();\n for (const field of userRegionFields) {\n // D-5: a video-kind paramValue routes to the transient path\n // (videoTextureFields), NOT validateTextureHandle (which drops\n // kind!=='texture', the R-7 silent-fail path). Static fields fall\n // through to validateTextureHandle unchanged.\n const videoHandle =\n assets !== null && assets !== undefined\n ? resolveVideoFieldHandle(pv[field], world, assets)\n : undefined;\n if (videoHandle !== undefined) {\n videoTextureFields.set(field, videoHandle);\n continue;\n }\n const handle = validateTextureHandle(field, pv[field]);\n if (handle !== undefined) textureHandles.set(field, handle);\n }\n const baseColorTextureHandle = textureHandles.get('baseColorTexture');\n const metallicRoughnessTextureHandle = textureHandles.get('metallicRoughnessTexture');\n const normalTextureHandle = textureHandles.get('normalTexture');\n const samplerHandles = collectMaterialTextureSamplers(pv, (value) =>\n resolveParamHandle(materialTextureRef(value), 'SamplerAsset'),\n );\n const emissiveTextureHandle = validateTextureHandle(\n 'emissiveTexture',\n pv.emissiveTexture,\n );\n const occlusionTextureHandle = validateTextureHandle(\n 'occlusionTexture',\n pv.occlusionTexture,\n );\n const textureCoordinates = collectMaterialTextureCoordinates(pv);\n const textureSources = collectMaterialTextureSources(\n pv,\n world,\n materialTextureSourceFields(\n materialParamSchema.length > 0 ? materialParamSchema : undefined,\n ),\n materialTextureSourceStats,\n materialTextureSourceCache,\n );\n const emissivePv = pv.emissive as readonly number[] | undefined;\n // feat-20260625 M2 / w6: first-pass transparency flag folds into\n // MaterialSnapshot.transparent so the record stage can drive the\n // LDR split + premultiplied-alpha blend decision without\n // re-reading passes[]. feat-20260626-collapse M2: derive from\n // `passes[0].renderState.blend !== undefined` (blend presence is\n // the SSOT after MaterialPass.transparent was dropped).\n // Result is plain boolean (always defined here) — written as-is\n // into the snapshot (`boolean | undefined` field, see L759).\n const firstPassTransparent: boolean = allPasses[0]?.renderState?.blend !== undefined;\n\n // feat-20260625-refactor-sprite-as-transparent-mesh M3 / w12 (D-8):\n // narrow `forgeax::sprite` extract block --- folds the legacy user\n // values format (flipX / flipY / slices / sliceMode + free\n // region / pivot) into the UBO-aligned paramSnapshot vec4 fields\n // (region / pivotAndSize / slicesAndMode + colorTint). Also folds\n // per-entity SpriteRegionOverride (Q4=a). After this block the\n // generic else branch picks up the snapshot via the same writer\n // path PBR / unlit use; no more shadingModel='sprite' arm, no\n // spriteFields POD (AC-02 / AC-07: extract has exactly 2 hard\n // `forgeax::sprite` checks --- this fold + the slices mesh swap on\n // the record side).\n if (isSprite) {\n // SpriteRegionOverride: per-entity per-frame region displacement.\n let overrideRegion: readonly [number, number, number, number] | undefined;\n if (hasSpriteRegionOverride) {\n const overrideView = worldInternal._getArrayView(\n entity,\n SpriteRegionOverride,\n 'region',\n ) as Float32Array | undefined;\n if (overrideView !== undefined && overrideView.length >= 4) {\n overrideRegion = [\n overrideView[0] ?? 0,\n overrideView[1] ?? 0,\n overrideView[2] ?? 1,\n overrideView[3] ?? 1,\n ];\n }\n }\n // Region resolution priority: SpriteRegionOverride > paramSnapshot.\n // region (UBO-aligned user input) > [0,0,1,1] identity.\n const regionPv = paramSnap.region as readonly number[] | undefined;\n let regionX = overrideRegion?.[0] ?? regionPv?.[0] ?? 0;\n let regionY = overrideRegion?.[1] ?? regionPv?.[1] ?? 0;\n let regionZ = overrideRegion?.[2] ?? regionPv?.[2] ?? 1;\n let regionW = overrideRegion?.[3] ?? regionPv?.[3] ?? 1;\n // flipX / flipY fold into region (D-8): the shader does\n // `uv * region.zw + region.xy`, so flipping along U is a sign\n // negation of region.z plus an origin offset.\n const flipXPv = typeof pv.flipX === 'number' ? pv.flipX : 0;\n const flipYPv = typeof pv.flipY === 'number' ? pv.flipY : 0;\n if (flipXPv !== 0) {\n regionX += regionZ;\n regionZ = -regionZ;\n }\n if (flipYPv !== 0) {\n regionY += regionW;\n regionW = -regionW;\n }\n paramSnap.region = [regionX, regionY, regionZ, regionW];\n // Guard: slicesAndMode must be present and zero for non-9-slice\n // sprites so the record-stage UBO writer (applyParamSnapshotToUbo)\n // writes [0,0,0,0] at offset 48 instead of leaving the\n // buildPbrMaterialUboPayload PBR baseline (e.g. occlusionStrength=1\n // at that slot). A non-zero slicesAndMode trips `useSlices=true`\n // in sprite.wgsl, which degenerates HANDLE_QUAD geometry → invisible.\n if (!('slicesAndMode' in paramSnap)) {\n (paramSnap as Record<string, unknown>).slicesAndMode = [0, 0, 0, 0];\n }\n }\n\n // Generic materialShaderId snapshot --- sprite included now flows\n // through this single branch (plan-strategy D-3 / AC-01 / AC-02 /\n // AC-07). The sprite block above only writes paramSnap.region (D-8\n // SpriteRegionOverride + flip fold); the rest of the UBO is filled\n // by the same paramSchema-driven path PBR / unlit use.\n materialSnap = {\n baseColor,\n metallic: metallicPv,\n roughness: roughnessPv,\n ...(resolved.surface?.model === undefined\n ? {}\n : { surfaceModel: resolved.surface.model }),\n deferredPass: allPasses.some(\n (pass) =>\n String(\n (pass.renderState?.tags as Record<string, unknown> | undefined)?.LightMode ??\n pass.name,\n ) === 'Deferred',\n ),\n ...(specularColorPv !== undefined && {\n specularColor: [\n specularColorPv[0] ?? 1,\n specularColorPv[1] ?? 1,\n specularColorPv[2] ?? 1,\n ] as readonly [number, number, number],\n }),\n normalScale: normalScalePv,\n materialShaderId: firstPassShader,\n materialProgramKeys,\n materialSceneIndexProgramKeys,\n materialHandle: handleRaw,\n renderState: pipelineRenderState(allPasses[0]?.renderState),\n paramSnapshot: paramSnap,\n ...(materialParamSchema.length > 0 && { materialParamSchema }),\n standardTextureMask: materialStandardTextureMask(\n resolved.parameters,\n firstPassShader,\n pv,\n ),\n ...(textureCoordinates.size > 0 && { textureCoordinates }),\n ...(authoredTextureFields === undefined ? {} : { authoredTextureFields }),\n ...(samplerHandles.size > 0 && { samplerHandles }),\n ...(authoredSamplerFields === undefined ? {} : { authoredSamplerFields }),\n ...(textureHandles.size > 0 && { textureHandles }),\n ...(textureSources.size > 0 && { textureSources }),\n ...(videoTextureFields.size > 0 && { videoTextureFields }),\n ...(baseColorTextureHandle !== undefined && {\n baseColorTexture: baseColorTextureHandle,\n }),\n ...(metallicRoughnessTextureHandle !== undefined && {\n metallicRoughnessTexture: metallicRoughnessTextureHandle,\n }),\n ...(normalTextureHandle !== undefined && { normalTexture: normalTextureHandle }),\n ...(emissivePv !== undefined && {\n emissive: [emissivePv[0] ?? 0, emissivePv[1] ?? 0, emissivePv[2] ?? 0] as readonly [\n number,\n number,\n number,\n ],\n }),\n ...(typeof pv.emissiveIntensity === 'number' && {\n emissiveIntensity: pv.emissiveIntensity,\n }),\n ...(emissiveTextureHandle !== undefined && {\n emissiveTexture: emissiveTextureHandle,\n }),\n ...(occlusionTextureHandle !== undefined && {\n occlusionTexture: occlusionTextureHandle,\n }),\n ...(typeof pv.occlusionStrength === 'number' && {\n occlusionStrength: pv.occlusionStrength,\n }),\n transparent: firstPassTransparent,\n };\n\n if (!hasSpriteRegionOverride && !hasSkin) {\n const stored = storeMaterialSnapshot(\n materialSnapshotCache,\n handleRaw,\n materialSnap,\n allPasses,\n asset,\n assets,\n );\n if (stored.crossFrameSafe) persistentMaterialSnapshotCache?.set(handleRaw, stored);\n }\n\n // Build dispatch entries from resolved passes.\n if (isRenderable) {\n appendMaterialDispatchEntries(\n pendingDispatch,\n allPasses,\n entity,\n handleRaw,\n renderables.length,\n layerVal,\n paramSnap,\n 0,\n materialProgramKeys,\n );\n }\n }\n }\n }\n\n // feat-20260609 M2/M5 corrective fixup: default-material entities\n // (handleRaw===0 / case-B MeshRenderer{data:{}}) must produce\n // ShadowCaster dispatch entries so the shadow pass includes them.\n // The pre-existing logic only builds dispatch entries from\n // resolved material assets; defaultMaterialSnapshot() (mid-grey unlit)\n // left dispatch empty, causing shadow-m2/m3 test failures.\n // Requirements §10.5: shadow-casting is default behaviour, opt-out\n // via castShadow:false. The default material has no opt-out, so\n // it casts shadows.\n //\n // CHARTER NOTE (feat-20260609 T-005-a): the URP literals\n // `LightMode: 'ShadowCaster'` / `LightMode: 'Forward'` below are a\n // local URP-bridge — they mirror what `Materials.unlit({ castShadow:\n // true })` produces at the asset layer. The default-material\n // handle=0 path bypasses asset registration, so we synthesize the\n // same dispatch shape inline. Follow-up cleanup (F-1 from\n // implement-review R1): thread default materials through the\n // Materials factory so this block can call into the shared\n // passes[] producer.\n // tweak-20260701 M1: `materialSnap.shadingModel === 'unlit'` removed —\n // for handleRaw===0, defaultMaterialSnapshot() was always unlit\n // (the shadingModel check was a tautology); the isRenderable &&\n // handleRaw===0 guard alone preserves the exact same dispatch shape.\n if (isRenderable && handleRaw === 0) {\n const shadowCasterTags: Record<string, string> = { LightMode: 'ShadowCaster' };\n const nextRenderableIndex = renderables.length;\n // M2.5: stage into pendingDispatch; flushed at the renderable push\n // site below only when the entity survives cull.\n pendingDispatch.push({\n entityIndex: entity,\n materialHandle: 0,\n renderableIndex: nextRenderableIndex,\n passIndex: 0,\n queue: 2000,\n layer: layerVal,\n tags: shadowCasterTags,\n renderState: undefined,\n defines: undefined,\n vertexEntry: 'vs_main',\n fragmentEntry: undefined,\n materialShaderId: 'forgeax::default-shadow-caster',\n paramSnapshot: {},\n });\n // Also add a Forward pass entry so the entity renders in the\n // main scene pass (mirrors Materials.unlit default).\n appendMaterialDispatchEntries(\n pendingDispatch,\n [DEFAULT_FORWARD_PASS],\n entity,\n 0,\n nextRenderableIndex,\n layerVal,\n {},\n 1,\n );\n }\n\n if (isRenderable) {\n // feat-20260612 M2 / m2-6: Skin + Instances coexistence + per-joint\n // dangling fail-fast + real palette slice allocation. Replaces the\n // T-21 placeholder ({0,0} discriminator-only sentinel) with full\n // resolve / validate / write chain (D-9 reset already fired at\n // extractFrame entry; per-entity allocate + writeJointPalette here).\n let skinSlice: SkinPaletteReceipt | undefined;\n let skinPose: SkinPose | undefined;\n const skinIdentity = hasSkin ? skinPaletteIdentity(world, entity) : undefined;\n const releaseSkinIdentity = (): void => {\n if (skinIdentity !== undefined) {\n skinPaletteAllocator?.releasePersistentSlice(skinIdentity);\n }\n };\n if (hasSkin) {\n const skeletonHandleRaw = skinSkeletonView;\n if (\n skeletonHandleRaw !== undefined &&\n skeletonHandleRaw !== 0 &&\n assets !== undefined &&\n assets !== null\n ) {\n // Skin + Instances coexistence is forbidden (D-10).\n if (hasInstances) {\n worldInternal._routeError(new SkinInstancesCoexistForbiddenError(entity), {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (skin-instances-coexist)',\n });\n releaseSkinIdentity();\n continue;\n }\n // (a) Resolve skeleton asset; on failure -> skeleton-resolve-failed.\n const skeletonHandle = toShared<'SkeletonAsset'>(skeletonHandleRaw);\n const skeletonRes = resolveAssetHandle<SkeletonAsset>(world, skeletonHandle);\n if (!skeletonRes.ok || skeletonRes.value.kind !== 'skeleton') {\n worldInternal._routeError(new SkeletonResolveFailedError(entity, skeletonHandleRaw), {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (skeleton-resolve-failed)',\n });\n releaseSkinIdentity();\n continue;\n }\n const skeleton = skeletonRes.value;\n // (b) Reuse the Skin row already read for its skeleton handle;\n // the old path repeated a second whole-row world.get here.\n const skinJoints = skin?.joints;\n if (skinJoints === undefined) {\n releaseSkinIdentity();\n continue;\n }\n const jointsLength = skinJoints.length;\n if (jointsLength !== skeleton.jointCount) {\n worldInternal._routeError(\n new JointCountMismatchError(entity, skeleton.jointCount, jointsLength),\n {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (joint-count-mismatch)',\n },\n );\n releaseSkinIdentity();\n continue;\n }\n // (c) Resolve only each joint's GlobalTransform.world column. The\n // transient view is consumed before a structural mutation and\n // therefore preserves the same dangling-joint behavior without\n // constructing every other Transform field.\n // Build mat4 list eagerly so write happens once per entity (no\n // half-written slice on dangling).\n const jointWorlds = new Array<Mat4>(skeleton.jointCount);\n let jointDangling = -1;\n for (let jIdx = 0; jIdx < skeleton.jointCount; jIdx++) {\n const jointEntityRaw = skinJoints[jIdx] ?? 0;\n const jointEntity = jointEntityRaw as EntityHandle;\n const jointWorld = worldInternal._getArrayView(jointEntity, GlobalTransform, 'world');\n if (jointWorld === undefined) {\n jointDangling = jIdx;\n break;\n }\n // The allocator consumes the canonical Mat4 brand. Copy the\n // column view into that owner-created value so the ECS storage\n // view never crosses the math brand boundary by assertion.\n const jointWorldMat = mat4.create();\n jointWorldMat.set(jointWorld);\n jointWorlds[jIdx] = jointWorldMat;\n }\n if (jointDangling >= 0) {\n worldInternal._routeError(new JointEntityDanglingError(entity, jointDangling), {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (joint-entity-dangling)',\n });\n releaseSkinIdentity();\n continue;\n }\n // (d) Slice the IBM flat Float32Array into per-joint Float32Arrays.\n // skeleton.inverseBindMatrices length === jointCount * 16.\n const ibmFlat = skeleton.inverseBindMatrices;\n const ibms: Float32Array[] = new Array<Float32Array>(skeleton.jointCount);\n for (let jIdx = 0; jIdx < skeleton.jointCount; jIdx++) {\n ibms[jIdx] = ibmFlat.subarray(jIdx * 16, jIdx * 16 + 16);\n }\n // (e) Reuse the persistent producer-owned slice for this stable\n // world/entity identity. Missing producer bounds remain explicit:\n // the receipt carries no invented bind-pose AABB and the shadow\n // admission lane can route the caster to CPU.\n if (skinPaletteAllocator !== null) {\n const identity = skinPaletteIdentity(world, entity);\n const generation = (skeletonHandleRaw >>> 0) ^ skeleton.jointCount;\n const bounds = hasFiniteOrderedLocalAabb(skeleton.bounds)\n ? new Float32Array(skeleton.bounds)\n : undefined;\n skinPaletteAllocator.observePersistentJoints(identity, ibms, jointWorlds);\n const receipt = skinPaletteAllocator.allocatePersistentSlice({\n identity,\n generation: generation >>> 0,\n jointCount: skeleton.jointCount,\n ...(bounds === undefined ? {} : { bounds }),\n });\n skinPaletteAllocator.writePersistentJointPalette(receipt, ibms, jointWorlds);\n skinSlice = receipt;\n } else {\n skinPose = {\n identity: skinPaletteIdentity(world, entity),\n generation: ((skeletonHandleRaw >>> 0) ^ skeleton.jointCount) >>> 0,\n jointCount: skeleton.jointCount,\n ...(hasFiniteOrderedLocalAabb(skeleton.bounds)\n ? { bounds: new Float32Array(skeleton.bounds) }\n : {}),\n inverseBindMatrices: ibms,\n jointWorlds,\n };\n }\n }\n }\n\n // A pbr-skin PSO requires the complete three-binding group(2) skin\n // projection. Do not publish a renderable or its staged dispatch when\n // palette extraction was unavailable; the record stage must never\n // reinterpret a skinned vertex stream through an ordinary mesh group.\n if (skinSlice === undefined && skinPose === undefined && hasSkin) {\n releaseSkinIdentity();\n if (\n materialSnap.materialShaderId === 'forgeax::pbr-skin' ||\n materialProgramSelections?.some(materialProgramSelectionRequiresSkin) === true\n ) {\n pendingDispatch.length = 0;\n continue;\n }\n }\n\n // feat-20260601 D-3: read the resolved world mat4 (propagateTransforms\n // output) straight from the GlobalTransform.world column array view. The\n // record stage copies these 16 floats into the mesh SSBO with zero\n // per-snapshot `mat4.compose` (AC-07). A stale slot (generation gone)\n // skips the renderable, mirroring the Instances dangling-row sweep.\n // tweak-20260611 M1 / K-3: `_getArrayView` call survives untouched;\n // only the `entity` source switched to `bundle.Entity.self[i]`.\n const worldView = worldInternal._getArrayView(entity, GlobalTransform, 'world');\n if (worldView === undefined) {\n releaseSkinIdentity();\n continue;\n }\n const worldMat = new Float32Array(worldView);\n const transformSnap: TransformSnapshot = { world: worldMat };\n // feat-20260608 M5 amend / w11-a: per-submesh `materials[]` array\n // aligned 1-1 with `MeshAsset.submeshes[]`. materials[0] === the\n // representative entity-level snapshot already built; materials[i>=1]\n // are resolved via `resolveMaterialSnapshot` (a non-sprite, single-\n // pass-equivalent resolver — sprite per-submesh is OOS-1). When the\n // entity has no materialsView (case-B sentinel) the array is a single\n // mid-grey default mirroring the legacy single-material path so the\n // record stage's per-submesh UBO upload loop trivially writes one\n // slot, no special branch.\n const materialsArr: MaterialSnapshot[] = [materialSnap];\n if (assets !== undefined && assets !== null) {\n for (let mi = 1; mi < materialHandles.length; mi++) {\n const subHandle = materialHandles[mi] ?? 0;\n const subCache = hasSkin ? skinnedMaterialSnapshotCache : materialSnapshotCache;\n const cachedSubmaterial = subCache.get(subHandle);\n materialsArr.push(\n cachedSubmaterial?.snapshot ??\n resolveMaterialSnapshot(\n subHandle,\n world,\n assets,\n subCache,\n hasSkin ? undefined : persistentMaterialSnapshotCache,\n context.materialContext === undefined\n ? undefined\n : {\n ...context.materialContext,\n geometry: hasSkin ? 'skinned' : context.materialContext.geometry,\n },\n materialTextureSourceStats,\n materialTextureSourceCache,\n ),\n );\n }\n }\n if (isRenderable && assets !== undefined && assets !== null) {\n for (let mi = 1; mi < materialHandles.length; mi++) {\n const subHandle = materialHandles[mi] ?? 0;\n if (subHandle === handleRaw) continue;\n const subEntry =\n (hasSkin ? skinnedMaterialSnapshotCache : materialSnapshotCache).get(subHandle) ??\n (hasSkin\n ? undefined\n : readPersistentMaterialSnapshot(\n persistentMaterialSnapshotCache,\n subHandle,\n assets,\n ));\n appendMaterialDispatchEntries(\n pendingDispatch,\n subEntry?.passes ?? (subHandle === 0 ? [DEFAULT_FORWARD_PASS] : []),\n entity,\n subHandle,\n renderables.length,\n layerVal,\n materialsArr[mi]?.paramSnapshot,\n 0,\n materialsArr[mi]?.materialProgramKeys,\n );\n }\n }\n\n // feat-20260625-sprite-instances-and-tilemap-terrain-static-batch M3 /\n // w10: SpriteInstances validation + snapshot materialisation.\n // Three structured EcsError fires at this single point (plan-strategy\n // D-6 \"fail-fast at the render domain entry, not at ECS spawn-time\"):\n let spriteInstancesSnap: SpriteInstancesSnapshot | undefined;\n if (hasSpriteInstances) {\n // (1) mutually exclusive with Instances (peers — pick one).\n if (hasInstances) {\n worldInternal._routeError(\n new SpriteInstancesMutuallyExclusiveWithInstancesError(entity),\n {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (sprite-instances-mutually-exclusive)',\n },\n );\n continue;\n }\n // (2) requires sprite shader — the per-instance UV region is\n // consumed by the sprite vertex shader path only (plan-strategy D-4\n // axis on sprite.wgsl). Post-collapse (PR #520): sprite is no longer\n // a `shadingModel` enum member; identification is via the first-pass\n // `materialShaderId === 'forgeax::sprite'` (OOS-1 path retained).\n //\n // feat-20260624 M1' / t6: `'forgeax::sprite-lit'` also walks the same\n // per-instance UV region vertex path (VsOut byte-identical, paramSchema\n // mirror); accept either shader id.\n if (\n materialSnap.materialShaderId !== 'forgeax::sprite' &&\n materialSnap.materialShaderId !== 'forgeax::sprite-lit'\n ) {\n worldInternal._routeError(\n new SpriteInstancesRequiresSpriteShaderError(\n entity,\n materialSnap.materialShaderId ?? 'undefined',\n ),\n {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (sprite-instances-requires-sprite-shader)',\n },\n );\n continue;\n }\n // (3) count mismatch — transforms.length / 16 === regions.length / 4\n // (transforms.length=0 + regions.length=0 is the zero-instance lawful\n // boundary; both derivations are 0 and equality holds, so no fire).\n const transforms = worldInternal._getArrayView(entity, SpriteInstances, 'transforms');\n const regions = worldInternal._getArrayView(entity, SpriteInstances, 'regions');\n if (transforms !== undefined && regions !== undefined) {\n const transformsLength = transforms.length;\n const regionsLength = regions.length;\n // Stride sanity: transforms must be mod 16, regions must be mod 4.\n // A stride violation expresses as a count mismatch under the\n // canonical derivation transforms/16 vs regions/4 — fire the\n // count-mismatch code (the same code carries detail.expectedStride).\n const tCount = transformsLength / 16;\n const rCount = regionsLength / 4;\n if (transformsLength % 16 !== 0 || regionsLength % 4 !== 0 || tCount !== rCount) {\n worldInternal._routeError(\n new SpriteInstancesCountMismatchError(transformsLength, regionsLength),\n {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (sprite-instances-count-mismatch)',\n },\n );\n continue;\n }\n // Validation passes — build the snapshot. transforms.length === 0\n // is lawful (zero-instance) and produces instanceCount=0; the\n // record stage skips drawIndexed when instanceCount===0.\n const transformsCopy = new Float32Array(transforms);\n const regionsCopy = new Float32Array(regions);\n spriteInstancesSnap = {\n transforms: transformsCopy,\n regions: regionsCopy,\n instanceCount: tCount,\n cacheKey: entity,\n archVersion,\n };\n }\n }\n\n let localAabb: Float32Array | undefined;\n let lods: readonly MeshLodLevel[] | undefined;\n let lodHysteresis: number | undefined;\n let morph: MorphSnapshot | undefined;\n const assetHandleRaw = Math.round(fAssetHandle ?? 0);\n if (assetHandleRaw !== 0) {\n const meshRes = resolveAssetHandle(world, toShared<'MeshAsset'>(assetHandleRaw));\n if (meshRes.ok && meshRes.value.kind === 'mesh') {\n const meshAsset = meshRes.value as MeshAsset;\n lods = meshAsset.lods;\n lodHysteresis = meshAsset.lodHysteresis;\n morph = morphSnapshotFor(meshAsset, morphWeightsView);\n const meshAabb = skinSlice?.bounds ?? meshAsset.aabb;\n // Morph targets can expand the authored bounds. Keep the\n // specialized lane conservative until a target-aware bounds\n // projection is available; a false-positive draw is preferable\n // to culling a valid deformed vertex.\n if (morph === undefined && hasFiniteOrderedLocalAabb(meshAabb)) {\n localAabb = new Float32Array(meshAabb);\n }\n }\n }\n\n const pointsLinesStyle: PointsLinesStyle | undefined =\n points !== undefined\n ? (() => {\n const shape = pointShapeFromU32(points.shape);\n return shape === undefined\n ? undefined\n : { kind: 'points' as const, sizePx: points.sizePx, shape };\n })()\n : lines === undefined\n ? undefined\n : { kind: 'lines' as const, widthPx: lines.widthPx };\n const cullingLocalAabb = expandPointsLinesBounds(localAabb ?? [], pointsLinesStyle);\n const pointsLines =\n pointsLinesComponent === undefined\n ? undefined\n : ({\n worldId: context.worldId,\n entityKey: entity,\n component: pointsLinesComponent,\n meshHandle: assetHandleRaw,\n meshGeneration: assets?.catalogEpoch ?? 0,\n materialHandle: handleRaw,\n materialGeneration: assets?.catalogEpoch ?? 0,\n style: pointsLinesStyle,\n layer: layerVal,\n sortKey,\n visible: true,\n sourceBounds: cullingLocalAabb,\n viewport: { width: 0, height: 0, dpr: 1 },\n projection: identityProjection(),\n } satisfies PointsLinesRetainedSnapshot);\n\n // Instances are snapshotted before the CPU visibility decision so the\n // culling owner can derive the union of every instance's transformed\n // mesh bounds. The same detached snapshot is then carried to record;\n // do not re-read the collection after culling (a mutation must not\n // make the cull and draw disagree within one frame).\n let instancesSnap: InstancesSnapshot | undefined;\n if (hasInstances) {\n const transforms =\n worldInternal._getArrayView(entity, Instances, 'transforms') ?? new Float32Array();\n const invalid = validateInstanceTransforms(transforms);\n if (invalid !== undefined) {\n worldInternal._routeError(invalid, {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (Instances transforms)',\n });\n continue;\n }\n const projected = instanceCollections?.project(world, entity, transforms);\n instancesSnap = {\n transforms: projected?.transforms ?? new Float32Array(transforms),\n instanceCount: transforms.length / 16,\n cacheKey: entity,\n archVersion: projected === undefined ? archVersion : 0,\n ...(projected === undefined\n ? {}\n : {\n collectionId: projected.collectionId,\n revision: projected.revision,\n generations: projected.generations,\n }),\n };\n }\n\n const baseRenderable: RenderableSnapshot = {\n assetHandle: Math.round(fAssetHandle ?? 0),\n transform: transformSnap,\n ...(lods === undefined ? {} : { lods }),\n ...(lodHysteresis === undefined ? {} : { lodHysteresis }),\n ...(localAabb !== undefined ? { localAabb: cullingLocalAabb } : {}),\n material: materialSnap,\n materials: materialsArr,\n materialBindingSources,\n materialBindingDiagnostics,\n worldId: context.worldId,\n entityKey: entity,\n ...(authorVisible ? {} : { authorVisible: false }),\n ...(skinSlice !== undefined ? { skin: skinSlice } : {}),\n ...(skinPose === undefined ? {} : { skinPose }),\n ...(skin?.joints === undefined\n ? {}\n : { skinJointEntities: Array.from(skin.joints, (joint) => Number(joint)) }),\n ...(morph !== undefined ? { morph } : {}),\n ...(instancesSnap !== undefined ? { instances: instancesSnap } : {}),\n ...(spriteInstancesSnap !== undefined ? { spriteInstances: spriteInstancesSnap } : {}),\n ...(pointsLines !== undefined ? { pointsLines } : {}),\n };\n const gpuDrivenDraws =\n skinPose === undefined\n ? buildGpuDrivenDraws({\n mesh: gpuDrivenMesh,\n materials: materialsArr,\n fallbackMaterial: materialSnap,\n baseSnapshot: baseRenderable,\n ...(getMaterialShaderArtifact === undefined ? {} : { getMaterialShaderArtifact }),\n ...(lods === undefined\n ? {}\n : {\n lodMeshes: lods.map((lod) => {\n const lower = assets?.lookup<Asset>(lod.mesh);\n return lower?.kind === 'mesh' ? lower : undefined;\n }),\n }),\n })\n : [];\n for (const draw of gpuDrivenDraws) {\n if (draw.preparationError === undefined) continue;\n worldInternal._routeError(draw.preparationError, {\n severity: Severity.Error,\n systemName: `RenderSystem.extract (gpu-driven-preparation:${draw.preparationError.code})`,\n });\n }\n const renderable =\n morph === undefined && gpuDrivenDraws.length > 0\n ? { ...baseRenderable, gpuDrivenDraws }\n : baseRenderable;\n\n // feat-20260528-frustum-culling M3 / w10: frustum culling check.\n // Skip the entity if a valid AABB exists AND ALL cameras' frusta\n // reject the world-space AABB. Missing or malformed AABBs are\n // conservative always-visible fallbacks; valid culling bounds are\n // producer-owned finite local-space AABBs. Culling is unconditional\n // engine behavior; there is no per-entity opt-out.\n if (localAabb !== undefined) {\n // An empty or malformed Instances payload has no meaningful bounds.\n // Keep it conservative (the draw path later emits zero instances)\n // instead of manufacturing the entity's identity bounds. For a\n // valid payload, derive one world-space union for CPU culling while\n // leaving the mesh-local AABB untouched for GPU per-instance cull.\n const derivedInstancesBounds =\n instancesSnap === undefined || instancesSnap.instanceCount === 0\n ? undefined\n : deriveInstancesUnionBounds({\n meshAabb: cullingLocalAabb,\n entityWorld: transformSnap.world,\n transforms: instancesSnap.transforms,\n });\n if (instancesSnap?.instanceCount === 0) {\n // No instance can contribute a visible bound. The retained\n // snapshot still records instanceCount=0 for the record stage.\n } else if (\n hasInstances &&\n (instancesSnap === undefined || derivedInstancesBounds === undefined)\n ) {\n // Missing/malformed derived facts are a conservative no-cull\n // result. The stride validator above already rejects malformed\n // lengths; this branch covers non-finite producer matrices/AABB.\n } else {\n // feat-20260601 D-3: cull AABB uses the resolved world mat4\n // directly (no compose) -- same source the record stage feeds\n // the mesh SSBO, so cull stays same-source with render (AC-05).\n const worldAabb = box3.create();\n if (derivedInstancesBounds !== undefined) {\n worldAabb[0] = derivedInstancesBounds[0] ?? 0;\n worldAabb[1] = derivedInstancesBounds[1] ?? 0;\n worldAabb[2] = derivedInstancesBounds[2] ?? 0;\n worldAabb[3] = derivedInstancesBounds[3] ?? 0;\n worldAabb[4] = derivedInstancesBounds[4] ?? 0;\n worldAabb[5] = derivedInstancesBounds[5] ?? 0;\n } else {\n box3.transformBox3(worldAabb, cullingLocalAabb, transformSnap.world);\n }\n\n // Test against all cameras. Entity is visible if one camera\n // frustum intersects the world-space AABB (or planes are empty\n // from degenerate projection).\n frustumTotal += 1;\n let visible = frustumPlanes.length === 0;\n for (let ci = 0; ci < frustumPlanes.length; ci++) {\n const planes = frustumPlanes[ci] as Float32Array;\n if (planes.length === 0) {\n visible = true;\n break;\n }\n if (frustum.intersectsBox(planes as frustum.Frustum, worldAabb as box3.Box3Like)) {\n visible = true;\n break;\n }\n }\n if (!visible) {\n frustumCulled += 1;\n const shadowVisible =\n shadowFrusta.length > 0 &&\n pendingDispatch.some((entry) => entry.tags.LightMode === 'ShadowCaster') &&\n shadowFrusta.some((lightPlanes) =>\n frustum.intersectsBox(lightPlanes, worldAabb as box3.Box3Like),\n );\n if (!shadowVisible) continue;\n // Shadow-only renderables stay in the detached snapshot for the\n // depth passes, but must not leak their forward/transparent\n // dispatch entries into the main camera submission.\n for (let i = pendingDispatch.length - 1; i >= 0; i -= 1) {\n if (pendingDispatch[i]?.tags.LightMode !== 'ShadowCaster') {\n pendingDispatch.splice(i, 1);\n }\n }\n }\n }\n }\n\n const localShadowMembershipEntries: ShadowCasterMembership[] = [];\n if (gpuDrivenMesh !== undefined) {\n const worldEntity = worldEntityKey(context.worldId, entity);\n for (const [drawItemIndex, submesh] of gpuDrivenMesh.submeshes.entries()) {\n if (submesh.topology !== 'triangle-list' && submesh.topology !== 'triangle-strip') {\n continue;\n }\n const material = materialsArr[submesh.materialSlot] ?? materialSnap;\n const materialHandle = material.materialHandle ?? -1;\n const shadowEntries = pendingDispatch.filter(\n (entry) =>\n entry.tags.LightMode === 'ShadowCaster' && entry.materialHandle === materialHandle,\n );\n const draw = renderable.gpuDrivenDraws?.find(\n (candidate, compactIndex) =>\n gpuDrivenSourceDrawItemIndex(candidate, compactIndex) === drawItemIndex,\n );\n const cpuReason = shadowCasterCpuReason(\n material,\n draw,\n shadowEntries,\n morph,\n skinSlice,\n );\n for (const entry of shadowEntries) {\n const membership: ShadowCasterMembership = {\n worldEntity,\n renderableIndex: renderables.length,\n drawItemIndex,\n materialHandle,\n passIndex: entry.passIndex,\n ...(entry.materialShaderId === undefined\n ? {}\n : { materialShaderId: entry.materialShaderId }),\n ...(entry.vertexEntry === undefined ? {} : { vertexEntry: entry.vertexEntry }),\n ...(entry.fragmentEntry === undefined\n ? {}\n : { fragmentEntry: entry.fragmentEntry }),\n ...(entry.renderState === undefined ? {} : { renderState: entry.renderState }),\n ...(cpuReason === undefined ? {} : { cpuReason }),\n gpuDrivenEligible: cpuReason === undefined,\n };\n shadowMembershipEntries.push(membership);\n localShadowMembershipEntries.push(membership);\n }\n }\n }\n const shadowCasterPasses = localShadowMembershipEntries.map((membership) => ({\n drawItemIndex: membership.drawItemIndex,\n materialHandle: membership.materialHandle,\n passIndex: membership.passIndex,\n ...(membership.materialShaderId === undefined\n ? {}\n : { materialShaderId: membership.materialShaderId }),\n ...(membership.renderState === undefined ? {} : { renderState: membership.renderState }),\n ...(membership.cpuReason === undefined ? {} : { cpuReason: membership.cpuReason }),\n }));\n const renderableWithShadowPasses =\n shadowCasterPasses.length === 0 ? renderable : { ...renderable, shadowCasterPasses };\n flushPendingDispatch(pendingDispatch);\n renderables.push(renderableWithShadowPasses);\n }\n\n // feat-20260520-2d-sprite-layer-mvp M-3 / w22 + w25: finalise the\n // pending TransparentEntry with the renderableIndex pointing at the\n // RenderableSnapshot we just pushed (when isRenderable === true).\n // The check below also covers a sprite entity that survives the\n // dangling-Instances branch (silent skip with `dispatchEntry !==\n // null` early-continue) — in that case renderableIndex is still set\n // to the just-pushed slot which is correct because materialDispatch\n // already captures the dispatch position.\n }\n }\n\n // M3 / w26: sort dispatch entries by queue (ascending, stable sort)\n // per plan-strategy D-3.\n dispatch = sortDispatchByQueue(dispatch);\n const shadowCasterEntityKeys = new Set<number>();\n const shadowCasterDrawKeys = new Set<string>();\n const shadowCasterMembership = new Map<string, ShadowCasterMembership>();\n for (const entry of dispatch) {\n if (entry.tags.LightMode !== 'ShadowCaster') continue;\n const renderable = renderables[entry.renderableIndex];\n if (renderable !== undefined) {\n const worldEntity = worldEntityKey(renderable.worldId, renderable.entityKey);\n shadowCasterEntityKeys.add(worldEntity);\n }\n }\n for (const membership of shadowMembershipEntries) {\n const key = gpuDrivenShadowDrawKey(\n membership.worldEntity,\n membership.materialHandle,\n membership.drawItemIndex,\n membership.passIndex,\n );\n shadowCasterDrawKeys.add(key);\n shadowCasterMembership.set(key, membership);\n shadowCasterEntityKeys.add(membership.worldEntity);\n }\n\n // D-1: collect PostProcessParams entities into Map<shaderId, Uint8Array>.\n // Last-one-wins when multiple entities bear the same shader id (mirrors\n // Camera.exposure -> CameraSnapshot pattern; extract stage only reads).\n const postProcessParams: Map<string, Uint8Array> = new Map();\n const postProcessParamsQuery = world.query({ with: [PostProcessParams] }).unwrap();\n for (const row of postProcessParamsQuery) {\n const entity = row.entity;\n const read = world.get(entity, PostProcessParams);\n if (!read.ok) continue;\n postProcessParams.set(read.value.shader, read.value.data);\n }\n\n // feat-20260621 M-A3 / w13 (D-5): engine built-in tonemap data-driven\n // provider. The engine bridges the active camera's `Camera.exposure /\n // whitePoint / tonemap` onto the SAME unified params channel custom\n // post-processes use — `Camera.exposure` stays the AI-user-facing SSOT (D-5),\n // the engine itself acts as the provider for the Standard tonemap shader\n // id. The 16B layout keeps the prior recordTonemapPass packing\n // (render-system-record.ts pre-w14): Float32 [exposure, whitePoint, _,\n // ditherEnabled], with the mode u32 occupying the third 4-byte slot via\n // tonemapToU32 (SSOT in camera.ts). The final Output Transform makes a\n // per-pass copy and writes ditherEnabled at byte offset 12; the extracted\n // camera snapshot remains the SSOT. Run AFTER the user-entity collection above so the engine's\n // built-in provider is authoritative for its own reserved key (a user entity\n // can never shadow the Standard tonemap identity. The single active camera mirrors\n // recordFrame's `activeCameras[0]` selection.\n const tonemapCamera = cameras[0];\n if (tonemapCamera !== undefined) {\n postProcessParams.set(STANDARD_OUTPUT_TRANSFORM_FEATURE_ID, tonemapParams(tonemapCamera));\n }\n\n return {\n cameras,\n auxiliaryCameras,\n cubeCameras,\n reflectionProbes,\n lights,\n environment,\n environmentReady: true,\n ...(volumetricFog === undefined ? {} : { volumetricFog }),\n ...(cloudLayer === undefined ? {} : { cloudLayer }),\n renderables,\n dispatch,\n shadowCasterEntityKeys,\n shadowCasterDrawKeys,\n ...(shadowCasterMembership.size === 0\n ? {}\n : { shadowCasterMembership: [...shadowCasterMembership.values()] }),\n skylight,\n skylightCount,\n lightProbes,\n skybox,\n skyboxCount,\n fog,\n ...(fogFailure === undefined ? {} : { fogFailure }),\n frustumStats: { culled: frustumCulled, total: frustumTotal },\n visibilityStats: { explicitlyHidden: explicitlyHidden.size },\n materialTextureSources: materialTextureSourceStats,\n postProcessParams,\n visibilitySnapshots: [context.visibility],\n featureVisibilitySnapshots: [{ world, snapshot: context.visibility }],\n hiddenEntityReports: [...explicitlyHidden].map((entity) => ({ world, entity })),\n };\n}\n\n/** Immutable author-independent default; extraction retains its producer identity. */\nconst DEFAULT_MATERIAL_SNAPSHOT: MaterialSnapshot = Object.freeze({\n baseColor: vec3.create(0.5, 0.5, 0.5),\n metallic: 0,\n roughness: 1,\n materialHandle: 0,\n});\n\nexport function defaultMaterialSnapshot(materialHandle = 0): MaterialSnapshot {\n return materialHandle === 0\n ? DEFAULT_MATERIAL_SNAPSHOT\n : { ...DEFAULT_MATERIAL_SNAPSHOT, materialHandle };\n}\n\nfunction identityProjection(): Float32Array {\n const projection = new Float32Array(16);\n projection[0] = 1;\n projection[5] = 1;\n projection[10] = 1;\n projection[15] = 1;\n return projection;\n}\n","import type { MaterialCookProgramContext } from '@forgeax/engine-pack/material-cook';\n// @forgeax/engine-runtime - RenderSystem Extract stage (D-S2 + plan-strategy R-15\n// fallback split). Pure ECS query phase: walks Camera / DirectionalLight /\n// the merged-MeshRenderer renderable archetype and produces SoA-free snapshot\n// arrays consumed by the Record stage.\n//\n// Carve-out from render-system.ts (review round 1 finding #3 - 505 line cap\n// fallback split into 3 files; main + extract + record). The public API remains\n// limited to the renderer contract; this module is an owner-local\n// implementation seam consumed through relative imports.\n//\n// w15 (feat-20260511-asset-system-v1 M5 / plan-strategy D-P4) +\n// feat-20260513-component-naming-bevy-align M3 / D-2 (merged) +\n// feat-20260517-merge-mesh-renderer-material-renderer M2 / w5 (rename) +\n// M3 / w9 (single-query convergence; this commit):\n// The previous 4-query alpha split (one full-archetype query gating on\n// Transform + MeshFilter + MeshRenderer without Instances; one direct\n// archetype-graph walk for the instanced variant; two fallback queries\n// on Transform+MeshFilter without MeshRenderer / MeshFilter without\n// Transform; one trailing dispatch query gating on MeshRenderer alone)\n// collapses into ONE archetype-graph walk gated on `MeshRenderer`\n// component presence (plan-strategy section 2.2 case A archetype-\n// natural-absence + section 3.2 sequence diagram \"with: [MeshRenderer]\n// (sole)\"). Inside the loop\n// the four D-Q7 dispositions land:\n// - case A (no MeshRenderer) : not in domain; archetype absent. No\n// fire; no renderable; no dispatch.\n// - case B (material === 0) : missing-spec sentinel; defaultMaterial\n// Snapshot fills the slot. No fire.\n// - case C (non-zero handle unresolved): assets.get(handle).err with the entity\n// carrying the full T+MF+MR renderable\n// archetype -> structured RhiError(\n// `asset-not-registered`) routed through\n// the World Layer-3 ErrorHandler + entity\n// skipped from RenderableSnapshot[] +\n// from MaterialDispatchSnapshot[]; with a\n// non-renderable archetype (MeshRenderer\n// only / lacking T or MF) the dangling\n// handle stays a silent skip (charter F1\n// surface minimization: AI users without\n// render intent should not see render\n// errors).\n// - resolved : populated MaterialSnapshot (5 fields)\n// + MaterialDispatchSnapshot dispatch\n// entry (regardless of T+MF presence,\n// preserving the dispatch-only counter\n// semantics).\n//\n// D-Q7 three-tier subtable (SSOT mirrored in `packages/runtime/README.md`\n// §ECS render bridge D-Q7 `MeshRenderer` three-tier subtable +\n// `components/mesh-renderer.ts` head JSDoc; AGENTS.md §Component naming\n// + §Breaking changes 2026-05-17 row references this surface):\n// - case A archetype absent : silent skip; no onError; not in\n// RenderableSnapshot[]; hint literal N/A\n// (charter \"ergonomic omission, not a\n// misuse\"; AC-09).\n// - case B missing-spec : `material === undefined` ->\n// `defaultMaterialSnapshot()` mid-grey\n// unlit; no onError; entity present in\n// RenderableSnapshot[] with default\n// material; hint literal: `'pass\n// undefined or omit field to request\n// default material'` (AC-10).\n// - case C dangling-ref : `assets.get(handle).err` for a non-zero\n// handle (strict path, isRenderable === true) ->\n// `RhiError({ code: 'asset-not-\n// registered', detail: { assetHandle },\n// hint: 'register material via\n// assetRegistry.register(asset) before\n// spawn, or remove the material field\n// to fall back to default' })` routed\n// through World Layer-3 ErrorHandler;\n// entity skipped from\n// RenderableSnapshot[] +\n// MaterialDispatchSnapshot[]; mirrors\n// `MeshFilter.assetHandle` dangling path. A\n// scalar shared<T> slot 0 is the unbound,\n// non-renderable state and is skipped\n// (charter proposition 5; AC-11).\n//\n// World owns Instances.transforms. Extraction borrows the managed array during\n// the read phase and retains a detached projection only when its values change.\n// RenderScene accepts that projection with the source publication; recording\n// owns device residency, upload revisions and backend-specific chunking.\n// SpriteInstances remains the independent 2D component and snapshot contract.\n\nimport type { AssetRegistry } from '@forgeax/engine-assets-runtime';\nimport {\n materialParametersToParamSchema as projectMaterialParametersToParamSchema,\n resolveAssetHandle,\n selectMaterialPassProgram,\n walkMaterialPassesOverSharedRefs,\n} from '@forgeax/engine-assets-runtime';\nimport {\n type Component,\n type ComponentSchema,\n type EntityHandle,\n type Query,\n Time,\n type World,\n} from '@forgeax/engine-ecs';\nimport { readRenderArrayView, routeWorldError } from '@forgeax/engine-ecs/projection';\nimport { type Mat4, mat4, type Vec3, vec3 } from '@forgeax/engine-math';\nimport { AssetGuid, type AssetGuid as AssetGuidBytes } from '@forgeax/engine-pack/guid';\nimport { RhiError } from '@forgeax/engine-rhi';\nimport { GlobalTransform, Transform } from '@forgeax/engine-scene';\nimport {\n DEFAULT_STANDARD_PBR_PARAM_SCHEMA,\n DEFAULT_STANDARD_SURFACE_MODULE,\n type MaterialShaderArtifact,\n STANDARD_PIPELINE_PARAM_SCHEMA,\n standardTextureMask,\n} from '@forgeax/engine-shader';\nimport type {\n Asset,\n Handle,\n MaterialAsset,\n MaterialColorParameterSchema,\n MaterialParameter,\n MaterialPass,\n MaterialProgramAbi,\n MaterialRenderState,\n MaterialSurfaceModel,\n MaterialTextureCoordinates,\n MaterialTextureValue,\n MeshLodLevel,\n ParamSchemaEntry,\n TextureAsset,\n} from '@forgeax/engine-types';\nimport {\n derive,\n materialGuidText,\n materialValuesToLinearRuntime,\n toShared,\n} from '@forgeax/engine-types';\nimport { buildCubeCameraFaceViews } from './capture/cube-views';\nimport {\n antialiasFromF32,\n BarrelDistortion,\n CAMERA_EXPOSURE_MODE_MANUAL,\n Camera,\n CubeCamera,\n cameraExposureFromColumns,\n cameraProjectionFromF32,\n cubeCameraUpdateIntentFromF32,\n DynamicResolution,\n Fog,\n MotionBlur,\n ReflectionProbe,\n reflectionProbeUpdateIntentFromF32,\n ScreenSpaceReflection,\n tonemapFromF32,\n tonemapToU32,\n validateCameraBloom,\n validateDynamicResolutionCamera,\n} from './components';\nimport { validateBarrelDistortionParameters } from './components/barrel-distortion';\nimport { DepthOfField } from './components/depth-of-field';\nimport type { DirectionalShadowQuality } from './components/directional-shadow-filter';\nimport type { LightValidationError } from './components/light-helpers';\nimport { selectEnvironment } from './environment/frame';\nimport { ShadowInvalidConfigError } from './errors/render';\nimport {\n type DirectionalShadowCascadeFit,\n projectDirectionalShadow,\n} from './extract/directional-shadow-projection';\nimport type {\n EnvironmentFrame,\n FogCandidate,\n FogFrame,\n FogSelectionFailure,\n} from './extract/environment';\nimport type { GpuDrivenDrawSnapshot } from './extract/gpu-driven';\nimport { resolveVisibility, type VisibilitySnapshot } from './extract/visibility';\nimport {\n depthOfFieldRequestFailure,\n resolveDepthOfFieldParams,\n} from './features/depth-of-field/depth-of-field-params';\nimport { resolveMotionBlurParams } from './features/motion-blur/motion-blur-params';\nimport type {\n RenderFeatureHiddenEntityReport,\n RenderFeatureWorldVisibilitySnapshot,\n} from './features/types';\nimport type { InstanceCollectionId, InstanceProjectionStore } from './instances';\nimport type {\n MeshMaterialBindingDiagnostic,\n MeshMaterialBindingSource,\n} from './mesh-material-bindings';\nimport { isCanonicalStandardPbrMaterialShader, isStandardPbrMaterialShader } from './pbr-pipeline';\nimport type { PointsLinesRetainedSnapshot } from './points-lines/snapshot';\nimport type { ReflectionProbeFact } from './reflection/projection';\nimport type { CameraSnapshot, CubeCameraSnapshot } from './render-contract';\nimport { defaultMaterialSnapshot } from './render-system-extract-tail';\nimport { getActiveCamera, selectActiveCameraIndex } from './systems/active-camera';\nimport { selectPasses } from './systems/pass-selector';\nimport type { SkinPaletteAllocator } from './systems/skin-palette-allocator';\nimport type { SkinPaletteReceipt } from './systems/skin-palette-types';\nimport type { RenderTarget, RenderTargetTextureSource } from './targets/contracts';\nimport { resolveRenderTargetMaterialSource } from './targets/material-source';\nimport { resolveSelectedVolumetricLight } from './volume/capability';\nimport {\n type ValidatedVolumetricFog,\n type VolumeDensityBinding,\n VolumetricFog,\n type VolumetricFogAuthoring,\n} from './volume/component';\nimport { extractVolumetricFog } from './volume/extract';\nimport type { VolumeProjectorTuple } from './volume/temporal';\n\n/**\n * DirectionalLightSnapshot — sun-like infinite light variant of the\n * `LightSnapshot` discriminated union (M2 / w16 / AC-03). Host pre-multiplies\n * `color * intensity` so the shader sees the radiance term directly (charter\n * P4 host-side parity); `direction` stays in raw outgoing-vector form so the\n * shader can negate it once for BRDF (`let l = normalize(-light.direction)`).\n *\n * Plan-strategy D-S1 (3) (LightSnapshot to GPU buffer bucket 1:1 mapping).\n */\nexport interface DirectionalLightSnapshot {\n readonly kind: 'directional';\n readonly entity?: EntityHandle;\n readonly direction: Vec3;\n readonly color: Vec3;\n readonly intensity: number;\n}\n\n/**\n * PointLightSnapshot — omnidirectional point variant. `position` from the\n * companion Transform; `invRangeSquared = 1 / range^2` host-folded via\n * `computeInvRangeSquared` (range = +Infinity -> 0; range = 0 -> 1e8 NaN\n * protection per D-S5).\n */\nexport interface PointLightSnapshot {\n readonly kind: 'point';\n readonly entity?: EntityHandle | number;\n /** World identity stamped by the composited extract owner. */\n readonly worldId?: number;\n readonly position: Vec3;\n readonly color: Vec3;\n readonly intensity: number;\n readonly invRangeSquared: number;\n /**\n * feat-20260612-point-light-shadows-urp-hdrp M1 / T-M1-8 + M4 / T-M4-4:\n * cube_array atlas layer index for this light's shadow map (0..capacity-1\n * for admitted shadow casters; sentinel `-1` for non-admitted lights).\n * Default `-1` per\n * plan-strategy §D-2 — record stage / shader skips shadow sampling when the\n * lane equals the sentinel. Joined with `pointShadow[]` by entity at the\n * end of extract; HDRP record stage threads `shadowAtlasLayer + shadowNear +\n * shadowFar` through the unified direct-light metadata payload.\n */\n readonly shadowAtlasLayer?: number;\n /**\n * Per-face perspective near plane (matches `PointLightShadow.nearPlane`).\n * Used by HDRP `evalPointShadowed` for depth-ref reconstruction; URP keeps\n * the projection constants in its dedicated shadow-parameter buffer.\n */\n readonly shadowNear?: number;\n /**\n * Per-face perspective far plane (matches `PointLightShadow.farPlane`).\n * It is consumed with the shadow atlas layer through the shared\n * shadow-parameter buffer; DirectLightSlot carries only the layer identity.\n */\n readonly shadowFar?: number;\n}\n\n/**\n * PointShadowSnapshot — extract-stage view of one shadow-casting point light\n * (feat-20260612-point-light-shadows-urp-hdrp M1 / T-M1-7).\n *\n * `entity` is the spawning entity (joins PointLight + PointLightShadow on the\n * same archetype); `position` is the light world-space position resolved from\n * the companion Transform (mirrors PointLightSnapshot.position).\n * `shadowMatrices` is the 96-float packed mat4[6] table (column-major,\n * 6 mat4 * 16 floats = 384 bytes) ready for UBO upload.\n *\n * Plan-strategy §D-3: the record stage allocates a dynamic-offset uniform\n * buffer (384 B per-light, aligned to minUniformBufferOffsetAlignment, WebGPU\n * min 256 -> 512 B stride). Extract owns the host-side `Float32Array(96)`;\n * record owns the GPU `RhiBuffer` lifetime.\n *\n * `mapSize` / `nearPlane` / `farPlane` ride here so record stage can size the\n * cube atlas faces and feed shader the proj constants without re-querying ECS.\n * `shadowAtlasLayer` is assigned by extract in spawn order up to the renderer\n * atlas capacity; over-budget requests retain the sentinel `-1` so the\n * downstream DirectLightSlot packing carries no invalid layer identity.\n */\nexport interface PointShadowSnapshot {\n /** Spawning entity index (joins PointLight + PointLightShadow + Transform). */\n readonly entity: number;\n /** World identity stamped by the composited extract owner. */\n readonly worldId?: number;\n /** World-space light position (sourced from companion Transform). */\n readonly position: Vec3;\n /** PointLightShadow.mapSize (per-face cube square dimension; 512 default). */\n readonly mapSize: number;\n readonly nearPlane: number;\n readonly farPlane: number;\n readonly depthBias: number;\n readonly normalBias: number;\n /**\n * Atlas layer assigned by extract in spawn order while capacity remains.\n * Sentinel -1 is used for a request that cannot be admitted and is\n * reserved by the shader-side DirectLightSlot metadata for no-shadow lights.\n */\n readonly shadowAtlasLayer: number;\n /**\n * 6 view-proj mat4 in face order [+X, -X, +Y, -Y, +Z, -Z] packed into one\n * Float32Array(96). 16 floats per face = 64 B; 6 * 64 = 384 B raw. The\n * record stage pads each slot to 512 B (256 alignment) when packing into\n * the per-light dynamic-offset UBO (plan-strategy §D-3).\n */\n readonly shadowMatrices: Float32Array;\n}\n\n/**\n * SpotLightSnapshot — cone-restricted variant. `position` from companion\n * Transform; `direction` raw outgoing-vector; `cosInner` / `cosOuter` host\n * pre-converted via `degToCos` so the shader sees only cosines (D-S2).\n *\n * feat-20260625-spot-light-shadow-mapping M1 w5: added shadow fields.\n * castShadow (bool) gates shadow projection; lightViewProj is the perspective\n * light-view-projection matrix computed in extract (undefined when castShadow\n * is false, dir degenerates, or the light is clipped). shadowAtlasTile\n * (i32 sentinel -1) is the allocated tile index 0..3 or -1 for unassigned\n * (plan-strategy D-4). mapSize / nearPlane / farPlane are the source\n * component shadow parameters carried through to the record stage. The\n * author-facing `shadowIntensity` remains in [0,1] and is copied unchanged;\n * shader consumers apply it only to shadow visibility, never to candela\n * radiance.\n */\nexport interface SpotLightSnapshot {\n readonly kind: 'spot';\n /** Entity identity is branded in extracted frames; numeric fixtures remain compatible. */\n readonly entity?: EntityHandle | number;\n /** World identity stamped by the composited extract owner. */\n readonly worldId?: number;\n readonly position: Vec3;\n readonly direction: Vec3;\n readonly color: Vec3;\n readonly intensity: number;\n readonly invRangeSquared: number;\n readonly cosInner: number;\n readonly cosOuter: number;\n /** Shared asset identities projected from the authored modifier fields. */\n readonly iesProfileHandle?: number;\n readonly cookieHandle?: number;\n /** Resource-array slice identities; absent means the modifier falls back. */\n readonly iesProfileSlice?: number;\n readonly cookieSlice?: number;\n /** Resolved authored payloads; absent means the renderer keeps identity LKG. */\n readonly iesProfileData?: Uint8Array;\n readonly cookieData?: Uint8Array;\n /** Aspect-only UV matrix paired with `cookieSlice`; upload is dirty-ranged. */\n readonly cookieMatrix?: Float32Array;\n /**\n * Legacy projector payload projected into the shared Cookie array lane when\n * the adapter exposes the extended-lighting topology. The projector keeps\n * its lightViewProj sampling semantics; only the texture transport is\n * shared with authored Cookie resources.\n */\n readonly projectorSlice?: number;\n readonly projectorData?: Uint8Array;\n readonly projectorMatrix?: Float32Array;\n readonly rollDeg?: number;\n // ── shadow fields (feat-20260625-spot-light-shadow-mapping M1) ──\n readonly castShadow: boolean;\n readonly lightViewProj: Float32Array | undefined;\n readonly mapSize: number;\n readonly nearPlane: number;\n readonly farPlane: number;\n readonly shadowAtlasTile: number;\n /** Fraction of sampled shadow visibility to retain; 1 = fully opaque shadow. */\n readonly shadowIntensity?: number;\n readonly depthBias?: number;\n readonly normalBias?: number;\n readonly pcfKernelSize?: number;\n /** Authoritative TextureAsset projector resolved from the SpotLight handle. */\n readonly projectorHandle?: Handle<'TextureAsset', 'shared'>;\n readonly projectorAsset?: TextureAsset;\n readonly projectorGuid?: string;\n readonly projectorGeneration?: number;\n readonly projectorRevision?: number;\n}\n\n/** RectArea direct-light snapshot carried by the unified slot contract. */\nexport interface RectAreaDirectLightSnapshot {\n readonly kind: 'rect-area';\n readonly position: Vec3;\n readonly color: Vec3;\n readonly intensity: number;\n readonly invRangeSquared: number;\n readonly halfWidth: number;\n readonly halfHeight: number;\n readonly axisX: Vec3;\n readonly axisY: Vec3;\n readonly shadowAtlasTile?: number;\n}\n\n/** Normalized world-space frame used by Rect extraction, culling, and BRDF. */\nexport interface RectAreaWorldFrame {\n readonly center: Vec3;\n readonly axisX: Vec3;\n readonly axisY: Vec3;\n readonly normal: Vec3;\n readonly halfWidth: number;\n readonly halfHeight: number;\n}\n\n/** Build the single normalized Rect frame shared by direct and cluster paths. */\nexport function buildRectAreaWorldFrame(input: {\n readonly center: ArrayLike<number>;\n readonly axisX: ArrayLike<number>;\n readonly axisY: ArrayLike<number>;\n readonly width: number;\n readonly height: number;\n}): RectAreaWorldFrame {\n const center = vec3.create(input.center[0] ?? 0, input.center[1] ?? 0, input.center[2] ?? 0);\n const axisX = vec3.normalize(\n vec3.create(),\n vec3.create(input.axisX[0] ?? 0, input.axisX[1] ?? 0, input.axisX[2] ?? 0),\n );\n const axisY = vec3.normalize(\n vec3.create(),\n vec3.create(input.axisY[0] ?? 0, input.axisY[1] ?? 0, input.axisY[2] ?? 0),\n );\n const normal = vec3.normalize(vec3.create(), vec3.cross(vec3.create(), axisX, axisY));\n normal[0] = normal[0] === 0 ? 0 : (normal[0] ?? 0);\n normal[1] = normal[1] === 0 ? 0 : (normal[1] ?? 0);\n normal[2] = normal[2] === 0 ? 0 : (normal[2] ?? 0);\n return {\n center,\n axisX,\n axisY,\n normal,\n halfWidth: Math.max(0, input.width * 0.5),\n halfHeight: Math.max(0, input.height * 0.5),\n };\n}\n\n/** Return true only on the authored front side of a one-sided Rect. */\nexport function rectAreaFacesPoint(frame: RectAreaWorldFrame, point: ArrayLike<number>): boolean {\n const toPoint = vec3.create(\n (point[0] ?? 0) - (frame.center[0] ?? 0),\n (point[1] ?? 0) - (frame.center[1] ?? 0),\n (point[2] ?? 0) - (frame.center[2] ?? 0),\n );\n return vec3.dot(frame.normal, toPoint) > 0;\n}\n\n/** Project a world point onto the finite authored Rect boundary. */\nexport function closestPointOnRectArea(frame: RectAreaWorldFrame, point: ArrayLike<number>): Vec3 {\n const toPoint = vec3.create(\n (point[0] ?? 0) - (frame.center[0] ?? 0),\n (point[1] ?? 0) - (frame.center[1] ?? 0),\n (point[2] ?? 0) - (frame.center[2] ?? 0),\n );\n const localX = Math.min(\n frame.halfWidth,\n Math.max(-frame.halfWidth, vec3.dot(toPoint, frame.axisX)),\n );\n const localY = Math.min(\n frame.halfHeight,\n Math.max(-frame.halfHeight, vec3.dot(toPoint, frame.axisY)),\n );\n return vec3.create(\n (frame.center[0] ?? 0) + (frame.axisX[0] ?? 0) * localX + (frame.axisY[0] ?? 0) * localY,\n (frame.center[1] ?? 0) + (frame.axisX[1] ?? 0) * localX + (frame.axisY[1] ?? 0) * localY,\n (frame.center[2] ?? 0) + (frame.axisX[2] ?? 0) * localX + (frame.axisY[2] ?? 0) * localY,\n );\n}\n\n/**\n * LightSnapshot — discriminated union of the directional and punctual\n * variants. AI users + the record stage perform an exhaustive switch on\n * `kind`; missing arms are caught at compile time (no `default`,\n * `assertNever`-style guards). Plan-strategy R-10.\n */\nexport type LightSnapshot =\n | DirectionalLightSnapshot\n | PointLightSnapshot\n | SpotLightSnapshot\n | RectAreaDirectLightSnapshot;\n\n/**\n * ExtractedLights — three-bucket output of the extractFrame three-query\n * union (M2 / w16 / AC-03). Plan-strategy section 3.1 EXT node:\n * - `directional` — at most one (record-stage N>1 fail-fast lands in M3)\n * - `point[]` — first-slice cap of 4 enforced at record stage (M3)\n * - `spot[]` — first-slice cap of 4 enforced at record stage (M3)\n * `directionalCount` exposes the raw count of DirectionalLight entities the\n * extract observed (so the record stage can fire `render-system-multi-light`\n * when N>1 without re-running the query). M3 / w19 will widen this with\n * pointCount / spotCount fields once the matching record-time fail-fast\n * lands; for M2 the field stays directional-only to keep AC-06 (a) intact.\n */\nexport interface ExtractedLights {\n readonly directional: DirectionalLightSnapshot | undefined;\n readonly directionalCount: number;\n readonly point: readonly PointLightSnapshot[];\n readonly spot: readonly SpotLightSnapshot[];\n readonly rect: readonly RectAreaDirectLightSnapshot[];\n /**\n * feat-20260613-csm-cascaded-shadow-maps M2 / w9: per-cascade light-view-\n * projection matrices (one per cascade, length 4 pre-allocated). Each matrix\n * is a column-major 16-float mat4 with atlas tile UV inset baked in\n * (plan-strategy D-3). cascadeCount < 4: unused slots are zero matrices.\n * Undefined when castShadow=false or no directional light.\n */\n readonly lightViewProj: readonly Float32Array[] | undefined;\n /**\n * feat-20260613-csm-cascaded-shadow-maps M2 / w9: view-space z depths\n * of the PSSM split planes (length 4, Float32Array). cascadeCount < 4:\n * unused slots are 0.0f. Undefined when castShadow=false or no directional\n * light.\n */\n /** Four vec4 lanes: split, worldUnitsPerTexel, lightDepthWorldSpan, reserved. */\n readonly splitPlanes: Float32Array | undefined;\n /**\n * feat-20260613-csm-cascaded-shadow-maps M2 / w9: effective cascade count\n * from the DirectionalLight component (1..4). Undefined when castShadow=false\n * or no directional light.\n */\n readonly cascadeCount: number | undefined;\n /**\n * feat-20260613-csm-cascaded-shadow-maps M2 / w9: cascade blend width\n * from the DirectionalLight component (0..0.5). Undefined when castShadow=false\n * or no directional light.\n */\n readonly cascadeBlend: number | undefined;\n /**\n * feat-20260520-directional-light-shadow-mapping M1c / w8:\n * shadowMapSize from DirectionalLight.mapSize. Drives shadow RT\n * lazy-allocate (idempotency: same size -> no rebuild). Undefined when\n * castShadow=false or no directional light.\n */\n readonly shadowMapSize: number | undefined;\n /**\n * feat-20260621-merge-directionallightshadow-into-directionallight M2:\n * depthBias from the merged DirectionalLight (constant shadow-bias floor).\n * Populated when castShadow=true on the first-hit directional light;\n * undefined otherwise.\n */\n readonly depthBias: number | undefined;\n /**\n * feat-20260621-merge-directionallightshadow-into-directionallight M2:\n * normalBias from the merged DirectionalLight (slope-based shadow-bias\n * coefficient).\n * Populated when castShadow=true on the first-hit directional light;\n * undefined otherwise.\n */\n readonly normalBias: number | undefined;\n /** Accepted closed Directional filter projected from the first query result. */\n readonly directionalShadowQuality: DirectionalShadowQuality | undefined;\n /** Structured author-config failure; the candidate is withheld from record. */\n readonly directionalShadowError: LightValidationError | undefined;\n /**\n * feat-20260612-point-light-shadows-urp-hdrp M1 / T-M1-7:\n * shadow-casting point lights (PointLight + PointLightShadow + Transform\n * archetype join). Each entry carries the per-light 6-face VP matrices and\n * the assigned cube_array atlas layer (0..3 in spawn order; sentinel -1 is\n * reserved by the shader-side DirectLightSlot metadata for no-shadow point\n * lights).\n *\n * Empty array when no PointLightShadow components exist (zero-cost gate per\n * AC-09; record stage skips atlas allocation + shadow pass dispatch).\n */\n readonly pointShadow: readonly PointShadowSnapshot[];\n /**\n * bug-20260710-editor-cross-world-shadow: the RAW directional-shadow config\n * (cascadeCount / splitLambda / cascadeBlend / mapSize / shadowDistance) of\n * the first-hit castShadow DirectionalLight, carried unconditionally of\n * whether this world had a camera. The {@link extractFrames} merge layer\n * re-runs {@link computeDirectionalCsm} with this config + the surfaced\n * camera so directional shadows work when the light and camera live in\n * DIFFERENT worlds (editor editorWorld/sceneWorld super-composite). Undefined\n * when castShadow=false or no directional light. The `lightViewProj` /\n * `splitPlanes` fields above remain the *computed* per-world outputs (correct\n * for single-world; recomputed at merge for cross-world).\n */\n readonly directionalCsmConfig: DirectionalCsmConfig | undefined;\n /**\n * bug-20260710-editor-cross-world-shadow: the light-direction of the\n * first-hit castShadow DirectionalLight, carried so the merge layer can\n * rebuild the light-view matrix. Redundant with `directional.direction` but\n * kept explicit so the CSM recompute reads a single config bundle. Undefined\n * when castShadow=false or no directional light.\n */\n readonly directionalCsmDirection: Vec3 | undefined;\n}\n\n/**\n * SkylightSnapshot -- extract-stage view of one Skylight entity\n * (feat-20260520-skylight-ibl-cubemap M4 / t26).\n *\n * `equirectHandle` carries the packed u32 handle for\n * `Handle<EquirectAsset, 'shared'>`; the record stage drives the internal\n * lazy cubemap projection from it and resolves the projected GPU cubemap via\n * `GpuResidencyCache.getCubemapGpuView(...)` and related helpers\n * (feat-20260630 M3 / w16-w18). The snapshot carries NO projection status\n * field: the status truth lives in the store's CubemapGpuEntry (D-3 SSOT);\n * record queries it once per frame.\n *\n * `intensity` defaults to 1.0 via the Skylight component token defaults\n * (plan-strategy D-6: Skylight data flows through existing extract->record\n * pipeline; no independent ECS system).\n */\nexport interface SkylightSnapshot {\n // 0 = no equirect supplied -> solid-color ambient via the white fallback\n // cube (record falls to fallback resources when no IBL views are cached).\n readonly equirectHandle: number;\n readonly color: readonly [number, number, number];\n readonly intensity: number;\n /** Environment-space quaternion [x, y, z, w], identity by default. */\n readonly rotation: readonly [number, number, number, number];\n // feat-20260630 M3 / w19: the WINNING Skylight entity's packed handle (first\n // archetype hit). Carried so the multi-Skylight once-warn can name which\n // entity is used and which is ignored (F-8: warn carries conflicting entity\n // info). 0 only if the bundle had no live entity (never happens for a hit).\n readonly entityHandle: number;\n}\n\n/** Local diffuse probe facts; specular remains owned by Skylight/ReflectionProbe. */\nexport interface LightProbeSnapshot {\n readonly identity: string;\n /** World identity stamped by the composited extract owner. */\n readonly worldId?: number;\n readonly position: readonly [number, number, number];\n readonly radius: number;\n readonly irradiance: Float32Array;\n readonly admitted: boolean;\n}\n\n/**\n * SkyboxSnapshot -- extract-stage view of one SkyboxBackground entity\n * (feat-20260531-skybox-env-background M2 / w5).\n *\n * `equirectHandle` carries the packed u32 handle for\n * `Handle<EquirectAsset, 'shared'>`; the record stage resolves the projected\n * GPU cubemap via `GpuResidencyCache.getCubemapGpuView(...)`.\n *\n * `mode` carries the raw `f32` column value (`SKYBOX_MODE_CUBEMAP = 0`).\n * First hit wins per plan-strategy D-6; multi-entity once-warn in record stage.\n */\nexport interface SkyboxSnapshot {\n readonly equirectHandle: number;\n readonly mode: number;\n /** Environment-space quaternion [x, y, z, w], identity by default. */\n readonly rotation: readonly [number, number, number, number];\n // feat-20260630 M3 / w19: the WINNING SkyboxBackground entity's packed handle\n // (first archetype hit), so the multi-SkyboxBackground once-warn can name the\n // used entity (F-8 parity with the Skylight warn).\n readonly entityHandle: number;\n}\n\n/**\n * Resource-owner projection for an ECS VolumetricFog collection.\n *\n * The renderer carries the validated authoring facts and the source POD all\n * the way to the record stage. No profile flag or source/catalog byte is\n * allowed to enable the graph: `status: 'available'` is produced only after\n * the ECS component, its shared TextureAsset, and the volume validator all\n * agree on every linear 3D density owner.\n */\nexport interface ExtractedVolumetricFog {\n readonly additional?: readonly ExtractedVolumetricFog[];\n readonly status: 'off' | 'available' | 'degraded';\n readonly fog?: ValidatedVolumetricFog;\n readonly densityHandle?: Handle<'TextureAsset', 'shared'>;\n readonly densityAsset?: TextureAsset;\n readonly guid?: string;\n readonly generation?: number;\n readonly digest?: string;\n readonly worldId?: number;\n /** Canonical simulation time projected from this World for authored medium motion. */\n readonly worldTimeSeconds?: number;\n /** Required same-World light selected by the authoring component. */\n readonly lightEntity?: EntityHandle;\n readonly lightKind?: 'directional' | 'point' | 'spot';\n /** Optional Point+Spot pair identities consumed by the volume integrator. */\n readonly pointLightEntity?: EntityHandle;\n readonly spotLightEntity?: EntityHandle;\n /** Accepted projector tuple shared by surface and volume when authored. */\n readonly projector?: VolumeProjectorTuple;\n /** The resolved projector payload shared with the surface light snapshot. */\n readonly projectorHandle?: Handle<'TextureAsset', 'shared'>;\n readonly projectorAsset?: TextureAsset;\n}\n\nexport interface RenderableSnapshot {\n /** Authored hierarchical visibility; retained hidden rows remain addressable. */\n readonly authorVisible?: boolean;\n readonly assetHandle: number;\n readonly transform: TransformSnapshot;\n /** Producer-authored lower-detail references projected from MeshAsset. */\n readonly lods?: readonly MeshLodLevel[];\n readonly lodHysteresis?: number;\n /** Finite producer-owned local bounds retained for persistent CPU view work. */\n readonly localAabb?: Float32Array;\n /** Indexed single-submesh facts consumed by the first GPU-driven rigid lane. */\n readonly gpuDrivenDraws?: readonly GpuDrivenDrawSnapshot[];\n /**\n * feat-20260608 M5 amend / w11-a: the entity's representative (first)\n * material snapshot, kept as a same-name shorthand for `materials[0]`.\n * Per-entity dispatch (shading model routing, sprite-vs-mesh split, the\n * D-1/D-3 pipeline-tag pick) is uniform across the entity's submeshes\n * today, so the existing 20+ `entry.source.material.X` consumers in the\n * record stage stay unchanged. Per-submesh material data (baseColor /\n * UBO payload / paramSnapshot) lives in `materials[i]`.\n */\n readonly material: MaterialSnapshot;\n /**\n * feat-20260608 M5 amend / w11-a: per-submesh MaterialSnapshot[]\n * positionally aligned with `MeshAsset.submeshes[]` (plan §3.2 sequence\n * step 6 + AC-08). Length always equals the entity's submesh count once\n * the extract stage's count-mismatch validator (M2 / w12) has filtered\n * misaligned spawns. The record stage reads `materials[i]` to upload the\n * i-th material UBO slot before drawing the i-th submesh.\n *\n * Backward-compat: `materials[0] === material` (the legacy mid-grey\n * default-material case-B path also routes through `materials = [default]`,\n * keeping the legacy single-mesh-no-material spawn shape working without\n * a special branch in record).\n */\n readonly materials: readonly MaterialSnapshot[];\n /** Per-slot provenance trace from the shared mesh-material resolver. */\n readonly materialBindingSources: readonly MeshMaterialBindingSource[];\n /** Active structured override diagnostics for this renderable. */\n readonly materialBindingDiagnostics?: readonly MeshMaterialBindingDiagnostic[];\n /**\n * feat-20260708-composited-multi-world-rendering M1 / D-1: the worldId\n * of the world this renderable was extracted from. Defaults to 0 in\n * single-world path (extractFrame always assigns 0). The merge layer\n * (extractFrames in M2) stamps the correct worldId per world before\n * the record stage consumes it. Combined with `entityKey` via\n * `worldEntityKey(worldId, entityKey)` to form per-entity cache keys.\n *\n * Never rewrite `entityKey` itself — consumers that need the real\n * entity handle (video provider, etc.) read the bare `entityKey`.\n */\n readonly worldId: number;\n /**\n * feat-20260531-per-frame-bind-group-cache M1 / w3: packed Entity u32\n * (encodeEntity(indexSlot, generation)) surface'd from the extract\n * stage. Stable per-entity identity for the record stage cache keys\n * (material / instances / per-frame clean-up) without re-querying the\n * World (charter P5 Pipeline Isolation: record stage only consumes\n * snapshot POD). Reuses the encodeEntity calculation already performed\n * at :1293 for the Instances path, and now also computed for plain\n * (non-Instances) renderables.\n *\n * Never rewrite this field — cache keys use `worldEntityKey(worldId, entityKey)`,\n * not the bare entityKey alone (D-1).\n */\n readonly entityKey: number;\n /**\n * feat-20260514 M3 (w15): when the entity carries an `Instances` component\n * the extract stage materialises a fresh `Float32Array` snapshot of the\n * packed mat4 transforms (16 f32 per instance, stride 16) plus a stable\n * `cacheKey` (the entity's packed u32) and the `archVersion` (used by the\n * record stage to invalidate its per-entity GPU buffer cache when the\n * archetype storage grew). Absent (`undefined`) means the record stage\n * falls back to the shared 1-element identity-mat4 storage buffer +\n * `drawIndexed(.., 1, ..)`.\n */\n readonly instances?: InstancesSnapshot;\n /**\n * feat-20260625-sprite-instances-and-tilemap-terrain-static-batch M3 / w10\n * (plan-strategy D-1 + D-9): when the entity carries a `SpriteInstances`\n * component the extract stage materialises a paired snapshot — packed mat4\n * `transforms` (16 f32, stride 16) + per-instance UV `regions` (4 f32,\n * stride 4) — plus the same cache fingerprint pair (`cacheKey` = entity\n * packed u32, `archVersion` = archetype version stamp at snapshot time).\n * The record stage interleaves the two arrays into an 80B-per-instance\n * single GPU buffer routed through `@group(3) @binding(0)` (BGL unchanged,\n * D-1). Absent (`undefined`) means the entity is not a `SpriteInstances`\n * carrier; the record stage falls back to its existing sprite path\n * (material UBO region + identity-instance buffer).\n *\n * Three structured `EcsError` codes fire at extract entry and skip the\n * renderable on violation (charter P3 explicit failure):\n * - `'sprite-instances-mutually-exclusive-with-instances'`\n * - `'sprite-instances-requires-sprite-shading-model'`\n * - `'sprite-instances-count-mismatch'`\n */\n readonly spriteInstances?: SpriteInstancesSnapshot;\n /**\n * feat-20260523-skin-skeleton-animation M2 / T-21: when the entity carries\n * a `Skin` component the extract stage populates this field with the\n * skin palette slice metadata. The record stage uses this to route the\n * draw to `forgeax::pbr-skin` pipeline + set the palette dynamic offset.\n * Absent (`undefined`) means the entity is not skinned.\n */\n readonly skin?: SkinPaletteReceipt;\n /** Source pose waiting for the receiving Renderer to assign a palette. */\n readonly skinPose?: import('./systems/skin-palette-types').SkinPose;\n /** Joint identities consumed by the retained scene dependency index. */\n readonly skinJointEntities?: readonly number[];\n /** Source pass ownership retained with the scene record across view changes. */\n readonly shadowCasterPasses?: readonly Omit<\n ShadowCasterMembership,\n 'worldEntity' | 'renderableIndex'\n >[];\n /**\n * ECS-owned morph weights. Presence selects the Standard Pipeline CPU\n * specialized deformation lane; the asset remains the source of target\n * deltas and the record stage only receives this frozen POD snapshot.\n */\n readonly morph?: MorphSnapshot;\n /** Renderer-owned previous-frame facts attached during temporal projection. */\n readonly temporal?: RenderableTemporalSnapshot;\n /** Detached M2 authoring facts for the optional Points/Lines projection. */\n readonly pointsLines?: PointsLinesRetainedSnapshot;\n /** Renderer-owned per-object probe record uploaded at group(3) binding(1). */\n readonly probeBlendRecord?: import('./scene/probe-blend-record').ProbeBlendRecord;\n}\n\nexport type RenderablePreviousSource = 'last-submitted' | 'current-seed';\nexport type RenderableReactiveReason =\n | 'new-slot'\n | 'generation-reuse'\n | 'reentered'\n | 'geometry-revision'\n | 'material-revision'\n | 'skinning-deformation'\n | 'morph-deformation';\nexport interface RenderableTemporalSnapshot {\n readonly previousEpoch: number | undefined;\n readonly previousSource: RenderablePreviousSource;\n /** True only when current and previous geometry belong to one stable source identity. */\n readonly motionValid: boolean;\n /** Color-history invalidation is independent from motion validity. */\n readonly reactive: boolean;\n readonly reactiveReasons: readonly RenderableReactiveReason[];\n readonly previousTransform: TransformSnapshot;\n readonly previousInstances: InstancesSnapshot | undefined;\n readonly previousSkin: SkinPaletteReceipt | undefined;\n readonly previousMorphWeights: Float32Array | undefined;\n}\n\nexport interface MorphSnapshot {\n readonly weights: Float32Array;\n readonly targetCount: number;\n}\n\nexport type { GpuDrivenDrawSnapshot } from './extract/gpu-driven';\n\nexport interface InstancesSnapshot {\n /** Renderer-owned collection identity. */\n readonly collectionId?: InstanceCollectionId;\n /** Packed column-major mat4 transforms (16 f32 per instance). */\n readonly transforms: Float32Array;\n /** Monotonic per-ordinal identity generations, when the collection owns them. */\n readonly generations?: Uint32Array;\n /** Number of instances (transforms.length / 16). */\n readonly instanceCount: number;\n /** Collection revision captured by this detached frame snapshot. */\n readonly revision?: number;\n /** Coalesced matrix ordinals dirtied since the previous authoring update. */\n readonly dirtyRanges?: readonly {\n readonly start: number;\n readonly end: number;\n }[];\n /** Stable per-entity GPU buffer cache key (the packed Entity u32). */\n readonly cacheKey: number;\n /**\n * Archetype version stamp at snapshot time. The record stage compares this\n * against its cached version per cacheKey; a bump means the underlying\n * BufferPool slot may have grown / been reallocated, forcing a fresh\n * `device.createBuffer + queue.writeBuffer` round.\n */\n readonly archVersion: number;\n}\n\n/**\n * feat-20260625-sprite-instances-and-tilemap-terrain-static-batch M3 / w10:\n * extract-stage view of a `SpriteInstances` carrier (2D peer of\n * `InstancesSnapshot`).\n *\n * Field shapes mirror `InstancesSnapshot` so the record-stage cache protocol\n * (`(cacheKey, archVersion, byteLength)` fingerprint triple) is reused\n * verbatim. The byte length consumed at upload time is the sum\n * `transforms.byteLength + regions.byteLength` (= 80*N for N instances,\n * plan-strategy D-1 interleaved single-buffer); the record stage builds the\n * 80B/instance interleaved buffer once per (entity, archVersion, byteLength)\n * fingerprint change.\n */\nexport interface SpriteInstancesSnapshot {\n /** Packed column-major mat4 transforms (16 f32 per instance, stride 16). */\n readonly transforms: Float32Array;\n /** Per-instance UV vec4 regions (4 f32 per instance, stride 4). */\n readonly regions: Float32Array;\n /**\n * Number of instances. Derived from `transforms.length / 16` (equivalently\n * `regions.length / 4`); the extract-entry validator guarantees the two\n * derivations agree, otherwise it fires\n * `'sprite-instances-count-mismatch'` and skips the renderable.\n */\n readonly instanceCount: number;\n /** Stable per-entity GPU buffer cache key (the packed Entity u32, D-9). */\n readonly cacheKey: number;\n /** Archetype version stamp at snapshot time (cache invalidation fingerprint). */\n readonly archVersion: number;\n}\n\n/**\n * TransformSnapshot: extract-stage view of one entity's resolved world\n * transform (feat-20260601 D-3). Holds the single `world` mat4 (column-major\n * 16 floats, copied from the entity's `GlobalTransform.world` view written by\n * propagateTransforms). The record stage copies these 16 floats straight into\n * the mesh SSBO slot (zero `mat4.compose`); position / scale consumers derive\n * from the mat4 via `mat4.getTranslation` / basis-column lengths.\n */\nexport interface TransformSnapshot {\n readonly world: Float32Array;\n}\n\n/**\n * MaterialSnapshot: extract-stage view of one entity's material asset (M2 / w6\n * of feat-20260517-merge-mesh-renderer-material-renderer; plan-strategy section 2.3).\n *\n * Adds optional `baseColorTexture` + `sampler` slots (consumed by the record\n * stage's textured-material code path; M3 / w10 dropped the cast-over-firstMaterial\n * pattern in favour of direct snapshot field reads).\n *\n * feat-20260522-learn-render-3-1-sponza-model-loading-with-multi-l M4 extends\n * the snapshot with `metallicRoughnessTexture` and `normalTexture`\n * so the record stage can wire PBR texture bindings 4 and 6\n * from real GPU views instead of placeholder 1x1 white / flat-normal views.\n *\n * Bounded scope: the snapshot tracks only what the record stage actually\n * consumes today (charter proposition 5 consistent abstraction; YAGNI for\n * future-proof field bloat). Future MaterialAsset extensions (emissive / etc)\n * drive snapshot extensions when the record stage starts consuming them, not\n * vice-versa.\n *\n * tweak-20260701 M1: `shadingModel` field removed — shader identity via\n * {@link materialShaderId} is the single source of truth for material dispatch.\n */\nexport interface MaterialSnapshot {\n readonly baseColor: Vec3;\n readonly metallic: number;\n readonly roughness: number;\n /** Root-owned Surface model used only for typed pass routing. */\n readonly surfaceModel?: MaterialSurfaceModel | undefined;\n /** Whether this material publishes a Deferred pass consumed before the forward-only lane. */\n readonly deferredPass?: boolean | undefined;\n /** Authored Standard PBR specular color in linear runtime color space. */\n readonly specularColor?: readonly [number, number, number] | undefined;\n /**\n * Schema-driven material shader identifier (feat-20260523 M4-T05).\n * Populated when the material asset uses the schema-driven path\n * (payload.materialShader set). Undefined for unlit/sprite legacy\n * materials and for case-B defaultMaterialSnapshot.\n *\n * The record stage uses this as the pipeline cache key first-level\n * discriminator (M4-T06).\n */\n readonly materialShaderId?: string | undefined;\n readonly materialProgramKeys?: Readonly<Record<string, string>> | undefined;\n /** Producer-selected scene-index program keys, when a cooked publication carries them. */\n readonly materialSceneIndexProgramKeys?:\n | Readonly<Record<string, MaterialSceneIndexProgramKey>>\n | undefined;\n /**\n * Stable source handle for the material asset. Record uses this only for\n * same-frame assembly reuse; GPU bind-group validity still comes from the\n * resource-identity cache.\n */\n readonly materialHandle?: number | undefined;\n /**\n * The selected forward-pass state for this exact material. A mesh can bind\n * different materials to its submeshes, so pipeline selection must read the\n * state from the submesh snapshot rather than the entity's first material.\n */\n readonly renderState?: MaterialRenderState | undefined;\n /**\n * Schema-driven parameter snapshot (feat-20260523 M4-T05).\n * Populated alongside materialShaderId. Maps param name to its\n * runtime-resolved value: number for scalar params, number[] for\n * vec/color params, string (GUID) for texture2d/sampler params.\n */\n readonly paramSnapshot?: Readonly<Record<string, number | number[] | string>> | undefined;\n /** Effective MaterialAsset parameter contract used to lay out this snapshot. */\n readonly materialParamSchema?: readonly ParamSchemaEntry[] | undefined;\n /** Authored texture presence, separate from the shared GPU layout schema. */\n readonly standardTextureMask?: number | undefined;\n /** Authored per-slot UV set and KHR texture transform metadata. */\n readonly textureCoordinates?: ReadonlyMap<string, MaterialTextureCoordinates> | undefined;\n /**\n * User-region texture handles keyed by paramSchema field name\n * (feat-20260621-learn-render-5-5-parallax M2 / w7). The SSOT carrier for\n * EVERY texture the shader's `derive(paramSchema).textureFieldNames`\n * declares — `baseColorTexture` / `metallicRoughnessTexture` /\n * `normalTexture` for built-in standard-PBR, plus each custom field such as\n * `heightTexture` (LO 5.5 parallax). The record stage iterates this map to\n * assemble the user-region bind group per the per-shader BGL (w8), so a 4th\n * (or Nth) texture flows end-to-end without a hardcoded field list.\n *\n * Populated by iterating `textureFieldNames`; absent keys mean the\n * paramValue was missing / mis-typed (record falls back to default white).\n * `emissiveTexture` / `occlusionTexture` are included here as ordinary\n * Standard user-region fields; the production layout does not duplicate\n * them in a lightmap injection region.\n */\n readonly textureHandles?: ReadonlyMap<string, Handle<'TextureAsset', 'shared'>> | undefined;\n /** Explicitly authored texture fields that must resolve before GPU admission. */\n readonly authoredTextureFields?: ReadonlySet<string> | undefined;\n /** Renderer-local target sources; never projected as TextureAsset handles. */\n readonly textureSources?: ReadonlyMap<string, RenderTargetTextureSource> | undefined;\n /**\n * User-region texture field names whose paramValue resolved to a VideoAsset\n * (kind `'video'`) rather than a static TextureAsset\n * (feat-20260623-world-space-video-asset M4 / w14, D-5). The video GUID\n * occupies the same texture2d values slot a static texture would (P4:\n * one binding shape), but extract routes it here instead of `textureHandles`\n * so the record stage pulls the current-frame view from the transient\n * DynamicTextureStore (D-3) instead of `GpuResidencyCache.ensureResident`\n * (which has no `video` arm; AC-08). Each entry also carries the resolved\n * clip handle so the record stage can key the per-frame upload.\n *\n * Producer/consumer split (charter P5 / AC-07 gate): extract owns the\n * asset->snapshot translation; record consumes this POD field only — it never\n * reaches back into the MaterialAsset to learn a field is video-sourced.\n */\n readonly videoTextureFields?: ReadonlyMap<string, Handle<'VideoAsset', 'shared'>> | undefined;\n /** Authored sampler handles keyed by their matching texture parameter. */\n readonly samplerHandles?: ReadonlyMap<string, Handle<'SamplerAsset', 'shared'>> | undefined;\n /** Explicitly authored sampler fields that must resolve before GPU admission. */\n readonly authoredSamplerFields?: ReadonlySet<string> | undefined;\n readonly baseColorTexture?: Handle<'TextureAsset', 'shared'> | undefined;\n /**\n * PBR metallic-roughness texture handle (present for PBR/sprite/skin\n * shaders). Undefined for the default-unlit shader\n * (materialShaderId === 'forgeax::default-unlit'). The record stage reads\n * this to write GPU view at material bind-group binding 4, falling\n * back to a 1x1 white placeholder when undefined.\n *\n * feat-20260522-learn-render-3-1-sponza-model-loading-with-multi-l M4:\n * field added so the record stage can wire real metallic-roughness\n * textures from Sponza glTF materials (M3 writes the handle into\n * SchemaDrivenMaterialAsset values; M4 extract carries it through to the snapshot).\n */\n readonly metallicRoughnessTexture?: Handle<'TextureAsset', 'shared'> | undefined;\n /**\n * PBR tangent-space normal texture handle (present for PBR/sprite/skin\n * shaders). Undefined for the default-unlit shader\n * (materialShaderId === 'forgeax::default-unlit'). The record stage reads\n * this to write GPU view at material bind-group binding 6, falling\n * back to a (0.5,0.5,1.0) flat-normal placeholder when undefined.\n *\n * feat-20260522-learn-render-3-1-sponza-model-loading-with-multi-l M4:\n * field added symmetrically with metallicRoughnessTexture so the record\n * stage can wire real normal textures from Sponza glTF materials.\n */\n readonly normalTexture?: Handle<'TextureAsset', 'shared'> | undefined;\n /** Scalar applied to tangent-space normal XY after the normal texture sample. */\n readonly normalScale?: number | undefined;\n readonly emissive?: readonly [number, number, number] | undefined;\n readonly emissiveIntensity?: number | undefined;\n readonly emissiveTexture?: Handle<'TextureAsset', 'shared'> | undefined;\n readonly occlusionTexture?: Handle<'TextureAsset', 'shared'> | undefined;\n readonly occlusionStrength?: number | undefined;\n /**\n * Transparent composition flag derived from the first pass's\n * `renderState.blend` presence on the underlying\n * {@link MaterialPass} (feat-20260626-collapse M2: blend\n * presence is the SSOT after `MaterialPass.transparent` was\n * dropped in M1).\n *\n * The record stage reads this to drive both the LDR split-pass\n * decision and the premultiplied-alpha blend resolution on the\n * generic materialShaderId pipeline path — shader-agnostic, decoupled\n * from the legacy `shadingModel` discriminant (feat-20260625 M2 D-3,\n * finalised in w15; `shadingModel` field removed in tweak-20260701 M1).\n *\n * This describes the primary-pass snapshot for consumers that need a\n * material summary. Actual draw routing and the LDR split read the selected\n * DispatchEntry.renderState, so mixed opaque/transparent Passes remain valid.\n *\n * Type is `boolean | undefined` (derived): `undefined` means \"no\n * passes / unknown\"; consumers must read `=== true` / `!== true` to\n * stay correct under both populated and absent cases.\n */\n readonly transparent?: boolean | undefined;\n}\n\n/**\n * One producer-selected scene-index program, retaining the effective Pass\n * kind so record does not infer shadow/depth semantics from an authored name.\n */\nexport interface MaterialSceneIndexProgramKey {\n readonly specializationKey: string;\n readonly pass: 'forward' | 'shadow' | 'depth';\n}\n\nexport interface MaterialCacheChainIdentity {\n readonly asset: MaterialAsset;\n readonly parentGuid: string | undefined;\n}\n\nexport interface MaterialSnapshotCacheEntry {\n readonly snapshot: MaterialSnapshot;\n readonly passes: readonly MaterialPass[];\n /** Root/chain identities are present only on cross-frame-safe entries. */\n readonly chain?: readonly MaterialCacheChainIdentity[];\n /** AssetRegistry epoch at which the root/parent chain was last validated. */\n readonly catalogEpoch?: number;\n /** True only when every object reachable from the authored chain is frozen. */\n readonly crossFrameSafe: boolean;\n}\n\nexport type MaterialSnapshotCache = Map<number, MaterialSnapshotCacheEntry>;\nexport type MaterialSnapshotCachesByWorld = WeakMap<World, MaterialSnapshotCache>;\n\nexport function gpuDrivenMaterialResourceClass(material: MaterialSnapshot): string {\n const textures = [...(material.textureHandles?.entries() ?? [])]\n .map(([name, handle]) => [name, Number(handle)] as const)\n .sort(([left], [right]) => left.localeCompare(right));\n const samplers = [...(material.samplerHandles?.entries() ?? [])]\n .map(([name, handle]) => [name, Number(handle)] as const)\n .sort(([left], [right]) => left.localeCompare(right));\n return JSON.stringify({\n textures,\n samplers,\n video: [...(material.videoTextureFields?.keys() ?? [])].sort(),\n });\n}\n\n// === DispatchEntry — M3 / w26 single dispatch list (feat-20260526-material-asset-multipass-renderstate) ===\n//\n// Plan-strategy D-3: single dispatch list sorted by queue value,\n// replacing the old three-bucket opaque/transparent/overlay dispatch.\n// Each entry carries the per-pass render-state and entry-point\n// data from the resolved MaterialPass so the record stage\n// reads them without re-resolving the material.\n\nexport interface DispatchEntry {\n readonly entityIndex: number;\n readonly materialHandle: number;\n readonly renderableIndex: number;\n readonly passIndex: number;\n readonly queue: number;\n /**\n * Signed i32 from the entity's {@link Layer} component value (default 0 for\n * entities without a Layer). Primary sort key for the transparent-dispatch\n * sort in {@link render-system.ts}: lower value = drawn first (behind).\n */\n readonly layer: number;\n readonly tags: Record<string, string>;\n readonly renderState: MaterialRenderState | undefined;\n readonly defines: Record<string, string> | undefined;\n readonly vertexEntry: string | undefined;\n readonly fragmentEntry: string | undefined;\n readonly materialShaderId: string | undefined;\n readonly paramSnapshot: Readonly<Record<string, number | number[] | string>> | undefined;\n /**\n * Stencil reference value from {@link MaterialPass.stencilReference}\n * (draw-call dynamic state). Folded during extract for per-draw consumption\n * in the record stage. `undefined` when the pass does not set a reference\n * value (record stage falls back to WebGPU default 0).\n */\n readonly stencilReference?: number;\n}\n\n/**\n * Stable-sort dispatch entries by `queue` value ascending.\n * Returns a new sorted array (does not mutate the input).\n * Same-queue entries preserve insertion order (AC-11 stable-order guarantee).\n */\nexport function sortDispatchByQueue<E extends { readonly queue: number }>(\n entries: readonly E[],\n): E[] {\n // Array.prototype.sort is stable per ES2019 spec (V8 7.0+ / Node 12+).\n return entries.slice().sort((a, b) => a.queue - b.queue);\n}\n\nexport const DEFAULT_FORWARD_PASS: MaterialPass = {\n name: 'forward',\n program: { module: 'forgeax::default-unlit', vertexEntry: 'vs_main', fragmentEntry: 'fs_main' },\n renderState: { tags: { LightMode: 'Forward' }, queue: 2000 },\n};\n\nexport function appendMaterialDispatchEntries(\n pendingDispatch: DispatchEntry[],\n passes: readonly MaterialPass[],\n entity: EntityHandle,\n materialHandle: number,\n renderableIndex: number,\n layer: number,\n paramSnapshot: Readonly<Record<string, number | number[] | string>> | undefined,\n passIndexOffset = 0,\n materialProgramKeys?: Readonly<Record<string, string>>,\n): void {\n const matchedPasses = selectPasses(passes, {});\n for (let pIdx = 0; pIdx < matchedPasses.length; pIdx++) {\n const pass = matchedPasses[pIdx];\n if (pass === undefined) continue;\n const passState = (pass.renderState ?? {}) as MaterialRenderState & {\n readonly tags?: Record<string, string>;\n readonly queue?: number;\n readonly stencilReference?: number;\n };\n const authoredShaderId = runtimeMaterialShaderId(pass.program.module, pass.name);\n const dispatchShaderId =\n materialProgramKeys === undefined ? authoredShaderId : materialProgramKeys[pass.name];\n if (materialProgramKeys !== undefined && dispatchShaderId === undefined)\n throw new Error(`Missing published material program for Pass ${pass.name}`);\n pendingDispatch.push({\n entityIndex: entity,\n materialHandle,\n renderableIndex,\n passIndex: passIndexOffset + pIdx,\n queue: passState.queue ?? 2000,\n layer,\n tags: passState.tags ?? {},\n renderState: pipelineRenderState(passState),\n // Material module identity is already closed in the cooked program.\n // It must never become a draw-time define map.\n defines: undefined,\n vertexEntry: pass.program.vertexEntry,\n fragmentEntry: pass.program.fragmentEntry,\n materialShaderId: dispatchShaderId,\n paramSnapshot,\n ...(passState.stencilReference !== undefined && {\n stencilReference: passState.stencilReference,\n }),\n });\n }\n}\n\nexport interface ExtractedFrame {\n readonly cameras: CameraSnapshot[];\n /** Auxiliary target cameras selected after the display camera is fixed. */\n readonly auxiliaryCameras: readonly CameraSnapshot[];\n /** Cube capture intents extracted beside the display camera in one pass. */\n readonly cubeCameras: readonly CubeCameraSnapshot[];\n /** Reflection probe facts projected from the same World extraction. */\n readonly reflectionProbes?: readonly ReflectionProbeFact[];\n readonly lights: ExtractedLights;\n /** Resource-owner environment facts selected once at the extract boundary. */\n readonly environment: EnvironmentFrame | undefined;\n /** False when the resource-owner world failed environment/fog selection. */\n readonly environmentReady: boolean;\n /** One resource-owner volume projection; absent means no authored fog. */\n readonly volumetricFog?: ExtractedVolumetricFog;\n /** Resource-owner CloudLayer facts selected once at the extract boundary. */\n readonly cloudLayer?: import('./cloud/extract').ExtractedCloudLayer;\n readonly renderables: RenderableSnapshot[];\n /**\n * Single dispatch list sorted by queue value (ascending, stable sort).\n * Replaces the old opaqueDispatch / transparentDispatch / overlayDispatch\n * three-bucket model per plan-strategy D-3.\n */\n readonly dispatch: DispatchEntry[];\n readonly shadowCasterEntityKeys: ReadonlySet<number>;\n /** ShadowCaster ownership keyed by concrete draw item and pass. */\n readonly shadowCasterDrawKeys: ReadonlySet<string>;\n /** Structured ShadowCaster ownership facts retained for exact residual routing. */\n readonly shadowCasterMembership?: readonly ShadowCasterMembership[];\n readonly skylight: SkylightSnapshot | undefined;\n readonly skylightCount: number;\n /** World-local diffuse probe candidates; never a direct-light slot. */\n readonly lightProbes?: readonly LightProbeSnapshot[];\n readonly skybox: SkyboxSnapshot | undefined;\n readonly skyboxCount: number;\n /** Resource-owner Fog facts selected once at the frame boundary. */\n readonly fog: FogFrame | undefined;\n /** Last invalid Fog update retained alongside the current valid/LKG frame. */\n readonly fogFailure?: FogSelectionFailure;\n /**\n * feat-20260528-frustum-culling M3 / w11: frustum culling statistics\n * collected during the extract phase. `total` is the count of entities\n * that reached the culling decision point; `culled` is the count of\n * those that were removed from renderables by frustum culling.\n */\n readonly frustumStats: { readonly culled: number; readonly total: number };\n /** Candidate entities rejected by author visibility before resource parsing. */\n readonly visibilityStats: { readonly explicitlyHidden: number };\n /** Detached material-source probe accounting for this extraction. */\n readonly materialTextureSources?: MaterialTextureSourceStats;\n /**\n * Per-frame post-process params snapshot collected from PostProcessParams\n * entities (D-1: data-driven params channel). Maps shader id to the\n * raw data bytes (Uint8Array = FieldValueType<'buffer'>). Last-one-wins\n * when multiple entities bear the same shader id.\n * Empty map when no PostProcessParams entities exist.\n */\n readonly postProcessParams: ReadonlyMap<string, Uint8Array>;\n /** Visibility snapshots prepared for each contributing World. */\n readonly visibilitySnapshots: readonly VisibilitySnapshot[];\n /** World-labelled snapshots passed to generic RenderFeature extraction. */\n readonly featureVisibilitySnapshots: readonly RenderFeatureWorldVisibilitySnapshot[];\n /** Built-in hidden candidates, retained for host-side producer deduplication. */\n readonly hiddenEntityReports: readonly RenderFeatureHiddenEntityReport[];\n}\n\n/** Extracted ownership fact for one concrete ShadowCaster pass. */\nexport interface ShadowCasterMembership {\n readonly worldEntity: number;\n readonly renderableIndex: number;\n readonly drawItemIndex: number;\n readonly materialHandle: number;\n readonly passIndex: number;\n readonly materialShaderId?: string;\n /** Selected authored ShadowCaster entry points, when published. */\n readonly vertexEntry?: string;\n readonly fragmentEntry?: string;\n readonly renderState?: MaterialRenderState;\n readonly cpuReason?: ShadowCasterCpuReason;\n /** Producer-owned result of the complete ShadowCaster admission check. */\n readonly gpuDrivenEligible?: boolean;\n}\n\n/** Producer evidence for a concrete ShadowCaster pass that remains on CPU. */\nexport type ShadowCasterCpuReason =\n | 'transparent'\n | 'morph'\n | 'unsupported-shader'\n | 'unsupported-render-state'\n | 'missing-skin-bounds'\n | 'missing-gpu-draw'\n | 'unprepared'\n | 'prepared-contract'\n | 'multi-pass';\n\nexport type CameraTargetUpdate = 'once' | 'on-demand' | 'continuous';\n\nexport interface CameraTargetCandidate {\n readonly worldId: number;\n readonly entityKey: number;\n readonly target?: RenderTarget;\n readonly requestVersion: number;\n readonly update: CameraTargetUpdate;\n}\n\nexport interface CameraTargetRejection {\n readonly entityKey: number;\n readonly reason: 'budget' | 'display-target' | 'duplicate-target';\n}\n\nexport interface CameraTargetSelection {\n readonly display: CameraTargetCandidate | undefined;\n readonly auxiliary: readonly CameraTargetCandidate[];\n readonly rejected: readonly CameraTargetRejection[];\n}\n\nexport function selectCameraTargetViews(\n candidates: readonly CameraTargetCandidate[],\n options: { readonly displayEntityKey?: number; readonly budget: number },\n): CameraTargetSelection {\n const display = candidates.find(\n (candidate) =>\n candidate.entityKey === options.displayEntityKey && candidate.target === undefined,\n );\n const rejected: CameraTargetRejection[] = [];\n const ordered = candidates\n .filter((candidate) => candidate.target !== undefined)\n .sort((left, right) => left.worldId - right.worldId || left.entityKey - right.entityKey);\n const auxiliary: CameraTargetCandidate[] = [];\n const seenTargets = new Set<RenderTarget>();\n for (const candidate of ordered) {\n const duplicate = candidate.target !== undefined && seenTargets.has(candidate.target);\n if (candidate.target !== undefined) seenTargets.add(candidate.target);\n if (candidate.entityKey === options.displayEntityKey) {\n rejected.push({ entityKey: candidate.entityKey, reason: 'display-target' });\n continue;\n }\n if (candidate.target === undefined || duplicate) {\n rejected.push({ entityKey: candidate.entityKey, reason: 'duplicate-target' });\n continue;\n }\n if (auxiliary.length >= Math.max(0, options.budget)) {\n rejected.push({ entityKey: candidate.entityKey, reason: 'budget' });\n continue;\n }\n auxiliary.push(candidate);\n }\n return {\n display,\n auxiliary: Object.freeze(auxiliary),\n rejected: Object.freeze(rejected),\n };\n}\n\n/**\n * Internal world surface used by extract for archetype-graph traversal and\n * error routing. The packed `Entity` handle for a row is read directly from\n * the essential id=0 `Entity` column (`arch.columns.get(Entity.id).get('self')`)\n * -- no generation lookup / encodeEntity rebuild (feat-20260602 M2).\n */\ntype RenderErrorContext = {\n readonly systemName: string;\n /** Retained as diagnostic metadata for legacy render call sites. */\n readonly severity?: 'error' | 'warning';\n};\n\ntype ArrayFieldView = ArrayLike<number>;\n\n/**\n * Render's old zero-copy ECS calls now use the explicit public projection\n * boundary. The optimized ECS owner keeps storage behind `World`; render\n * receives a detached array snapshot and routes failures through the same\n * projection owner.\n */\nexport type WorldInternalView = {\n _routeError(error: unknown, ctx: RenderErrorContext): void;\n _getArrayView<N extends string, S extends ComponentSchema>(\n entity: EntityHandle,\n component: Component<N, S>,\n fieldName: string,\n ): ArrayFieldView | undefined;\n};\n\nexport const Severity = Object.freeze({ Error: 'error', Warning: 'warning' } as const);\n\nexport function createWorldInternalView(world: World): WorldInternalView {\n return {\n _routeError(error, ctx) {\n routeWorldError(world, error, { systemName: ctx.systemName });\n },\n _getArrayView(entity, component, fieldName) {\n return readRenderArrayView(world, entity, component, fieldName) as ArrayFieldView | undefined;\n },\n };\n}\n\nexport function resolveCameraTarget(\n world: World,\n raw: number | undefined,\n): RenderTarget | undefined {\n if (raw === undefined || raw <= 0) return undefined;\n const resolved = world.sharedRefs.resolve<'RenderTarget', RenderTarget>(\n toShared<'RenderTarget'>(Math.round(raw)),\n );\n return resolved.ok ? resolved.value : undefined;\n}\n\n/**\n * The user-region texture fields the built-in standard-PBR material declares.\n * Used as the fallback texture-field set when the shader id is not registered\n * (cross-worktree shader-late-register, plan R-4) so a built-in material still\n * resolves its user-region textures. Mirrors `derive(default-standard-pbr).textureFieldNames`.\n */\nexport const BUILTIN_USER_REGION_TEXTURE_FIELDS: readonly string[] = [\n 'baseColorTexture',\n 'metallicRoughnessTexture',\n 'normalTexture',\n 'specularColorTexture',\n 'emissiveTexture',\n 'occlusionTexture',\n 'transmissionTexture',\n 'thicknessTexture',\n];\nconst BUILTIN_USER_REGION_TEXTURE_FIELD_SET = new Set(BUILTIN_USER_REGION_TEXTURE_FIELDS);\nconst BUILTIN_BASE_COLOR_TEXTURE_FIELD_SET = new Set(['baseColorTexture']);\n\nexport function materialTextureFields(\n shaderId: string | undefined,\n fields: ReadonlySet<string> | undefined,\n): ReadonlySet<string> | undefined {\n if (fields !== undefined && fields.size > 0) return fields;\n if (\n shaderId === 'forgeax::default-standard-pbr' ||\n shaderId === 'forgeax::default-standard-pbr-skin' ||\n shaderId === 'forgeax::pbr-skin'\n ) {\n return BUILTIN_USER_REGION_TEXTURE_FIELD_SET;\n }\n if (\n shaderId === 'forgeax::default-unlit' ||\n shaderId === 'forgeax::sprite' ||\n shaderId === 'forgeax::sprite-lit'\n ) {\n return BUILTIN_BASE_COLOR_TEXTURE_FIELD_SET;\n }\n return fields;\n}\n\nfunction declaredMaterialTextureFields(\n shaderId: string | undefined,\n paramSchema: readonly ParamSchemaEntry[] | undefined,\n assets: AssetRegistry,\n): ReadonlySet<string> | undefined {\n return materialTextureFields(\n shaderId,\n paramSchema !== undefined\n ? derive(paramSchema).textureFieldNames\n : shaderId !== undefined\n ? assets.materialShaderTextureFieldNames(shaderId)\n : undefined,\n );\n}\n\n/** Preserve authored-vs-default intent for the GPU resource readiness gate. */\nexport function collectAuthoredMaterialTextureFields(\n values: Readonly<Record<string, unknown>>,\n shaderId: string | undefined,\n paramSchema: readonly ParamSchemaEntry[] | undefined,\n assets: AssetRegistry,\n): ReadonlySet<string> | undefined {\n const fields = declaredMaterialTextureFields(shaderId, paramSchema, assets);\n if (fields === undefined) return undefined;\n const authored = new Set<string>();\n for (const field of fields) {\n if (Object.hasOwn(values, field)) authored.add(field);\n }\n return authored.size === 0 ? undefined : authored;\n}\n\n/** Preserve explicit sampler intent; omitted samplers use the default sampler. */\nexport function collectAuthoredMaterialSamplerFields(\n values: Readonly<Record<string, unknown>>,\n textureFields: ReadonlySet<string> | undefined,\n): ReadonlySet<string> | undefined {\n const authored = new Set<string>();\n for (const field of textureFields ?? []) {\n if (materialTextureValue(values[field])?.sampler !== undefined) authored.add(field);\n }\n if (Object.hasOwn(values, 'sampler') && values.sampler !== undefined) {\n authored.add('baseColorTexture');\n }\n return authored.size === 0 ? undefined : authored;\n}\n\n/**\n * The authored material surface uses the module IDs declared by built-in WGSL\n * sources. Runtime pipeline caches still use the existing engine registration\n * IDs, so this small projection keeps authored identity and renderer lookup\n * identity in one place during the migration.\n */\nexport function runtimeMaterialShaderId(\n module: string | undefined,\n passName?: string,\n): string | undefined {\n if (\n passName === 'shadow-caster' &&\n (module === 'forgeax_material::standard' ||\n module === 'forgeax_material::unlit' ||\n module === 'forgeax::default-standard-pbr' ||\n module === 'forgeax::default-unlit')\n ) {\n return 'forgeax::default-shadow-caster';\n }\n switch (module) {\n case 'forgeax_material::standard':\n return 'forgeax::default-standard-pbr';\n case 'forgeax_material::unlit':\n return 'forgeax::default-unlit';\n case 'forgeax_material::sprite':\n return 'forgeax::sprite';\n case 'forgeax_material::sprite-lit':\n return 'forgeax::sprite-lit';\n default:\n return module;\n }\n}\n\n/**\n * Select the runtime identity for one resolved material. A cooked publication\n * owns the composed material artifact identity; the authored pass module is\n * the built-in fallback used before that publication is ready.\n */\nexport function materialProgramKeysForMaterial(\n material: MaterialAsset,\n assets: AssetRegistry,\n context: MaterialCookProgramContext | undefined,\n): Readonly<Record<string, string>> | undefined {\n return materialProgramKeysForAddress(material, assets, context, 'direct');\n}\n\n/**\n * Return the exact direct/scene-index programs selected for one renderer\n * context. The selection result is kept next to the key projection so\n * consumers that validate a mesh contract can inspect the producer ABI\n * without rebuilding pass/context matching from payload order.\n */\nexport interface MaterialProgramSelection {\n readonly pass: string;\n readonly context: MaterialCookProgramContext;\n readonly specializationKey: string;\n readonly abi?: MaterialProgramAbi;\n}\n\nexport function materialProgramSelectionsForMaterial(\n material: MaterialAsset,\n assets: AssetRegistry,\n context: MaterialCookProgramContext | undefined,\n address: 'direct' | 'scene-index' = 'direct',\n): readonly MaterialProgramSelection[] | undefined {\n const projection = assets.getMaterialProjectionForPayload(material);\n if (projection === undefined) return undefined;\n if (context === undefined)\n throw new Error('Published material selection requires renderer-owned compiler context');\n return projection.passes.map((pass) => {\n const mode = String(\n (pass.renderState?.tags as Record<string, unknown> | undefined)?.LightMode ?? pass.name,\n );\n const passKind = /shadow/i.test(mode)\n ? ('shadow' as const)\n : /depth/i.test(mode)\n ? ('depth' as const)\n : ('forward' as const);\n const selectedContext: MaterialCookProgramContext = {\n ...context,\n pass: passKind,\n pipeline: /deferred|gbuffer/i.test(mode) ? 'deferred' : context.pipeline,\n };\n const selected = selectMaterialPassProgram(projection, pass.name, selectedContext, address);\n return {\n pass: pass.name,\n context: selectedContext,\n specializationKey: selected.specializationKey,\n ...(selected.abi === undefined ? {} : { abi: selected.abi }),\n };\n });\n}\n\n/** Resolve the producer's scene-index program key for each cooked Pass. */\nexport function materialSceneIndexProgramKeysForMaterial(\n material: MaterialAsset,\n assets: AssetRegistry,\n context: MaterialCookProgramContext | undefined,\n): Readonly<Record<string, MaterialSceneIndexProgramKey>> | undefined {\n const projection = assets.getMaterialProjectionForPayload(material);\n if (projection === undefined) return undefined;\n if (context === undefined)\n throw new Error('Published material selection requires renderer-owned compiler context');\n const entries: Record<string, MaterialSceneIndexProgramKey> = {};\n for (const pass of projection.passes) {\n const mode = String(\n (pass.renderState?.tags as Record<string, unknown> | undefined)?.LightMode ?? pass.name,\n );\n const passKind = /shadow/i.test(mode)\n ? ('shadow' as const)\n : /depth/i.test(mode)\n ? ('depth' as const)\n : ('forward' as const);\n const selectedContext: MaterialCookProgramContext = {\n ...context,\n pass: passKind,\n pipeline: /deferred|gbuffer/i.test(mode) ? 'deferred' : context.pipeline,\n };\n try {\n const selected = selectMaterialPassProgram(\n projection,\n pass.name,\n selectedContext,\n 'scene-index',\n );\n entries[pass.name] = { specializationKey: selected.specializationKey, pass: passKind };\n } catch (error) {\n if (!isMissingMaterialProgram(error)) throw error;\n }\n }\n return Object.keys(entries).length === 0 ? undefined : entries;\n}\n\nfunction isMissingMaterialProgram(error: unknown): boolean {\n return (\n error !== null &&\n typeof error === 'object' &&\n (error as { readonly code?: unknown }).code === 'material-specialization-not-cooked'\n );\n}\n\nfunction materialProgramKeysForAddress(\n material: MaterialAsset,\n assets: AssetRegistry,\n context: MaterialCookProgramContext | undefined,\n address: 'direct' | 'scene-index',\n): Readonly<Record<string, string>> | undefined {\n const selections = materialProgramSelectionsForMaterial(material, assets, context, address);\n return selections === undefined\n ? undefined\n : Object.fromEntries(\n selections.map(({ pass, specializationKey }) => [pass, specializationKey]),\n );\n}\n\nexport function runtimeMaterialShaderIdForMaterial(\n passes: readonly MaterialPass[],\n programs: Readonly<Record<string, string>> | undefined,\n): string | undefined {\n const pass =\n passes.find(\n (pass) =>\n !/shadow|depth/i.test(\n String(\n (pass.renderState?.tags as Record<string, unknown> | undefined)?.LightMode ?? pass.name,\n ),\n ),\n ) ?? passes[0];\n if (pass === undefined) return undefined;\n return programs === undefined\n ? runtimeMaterialShaderId(pass.program.module, pass.name)\n : programs[pass.name];\n}\n\nexport function pipelineRenderState(\n renderState:\n | (MaterialRenderState & {\n readonly tags?: Readonly<Record<string, string>>;\n readonly queue?: number;\n readonly stencilReference?: number;\n })\n | undefined,\n): MaterialRenderState | undefined {\n if (renderState === undefined) return undefined;\n const {\n cullMode,\n depthCompare,\n depthWriteEnabled,\n blend,\n alphaToCoverageEnabled,\n stencil,\n stencilReadMask,\n stencilWriteMask,\n frontFace,\n } = renderState;\n if (\n cullMode === undefined &&\n depthCompare === undefined &&\n depthWriteEnabled === undefined &&\n blend === undefined &&\n alphaToCoverageEnabled === undefined &&\n stencil === undefined &&\n stencilReadMask === undefined &&\n stencilWriteMask === undefined &&\n frontFace === undefined\n ) {\n return undefined;\n }\n return {\n ...(cullMode !== undefined && { cullMode }),\n ...(depthCompare !== undefined && { depthCompare }),\n ...(depthWriteEnabled !== undefined && { depthWriteEnabled }),\n ...(blend !== undefined && { blend }),\n ...(alphaToCoverageEnabled !== undefined && { alphaToCoverageEnabled }),\n ...(stencil !== undefined && { stencil }),\n ...(stencilReadMask !== undefined && { stencilReadMask }),\n ...(stencilWriteMask !== undefined && { stencilWriteMask }),\n ...(frontFace !== undefined && { frontFace }),\n };\n}\n\nexport function shadowCasterCpuReason(\n material: MaterialSnapshot,\n draw: GpuDrivenDrawSnapshot | undefined,\n shadowEntries: readonly DispatchEntry[],\n morph: MorphSnapshot | undefined,\n skin: SkinPaletteReceipt | undefined,\n): ShadowCasterCpuReason | undefined {\n if (shadowEntries.length !== 1) return 'multi-pass';\n if (material.transparent === true || material.renderState?.blend !== undefined) {\n return 'transparent';\n }\n if (morph !== undefined) return 'morph';\n const shadowEntry = shadowEntries[0];\n if (shadowEntry?.renderState !== undefined) return 'unsupported-render-state';\n if (draw === undefined) return 'missing-gpu-draw';\n if (draw.prepared === undefined) return 'unprepared';\n const preparedMaterial = draw.prepared.identity.material;\n const preparedDeformation = draw.prepared.identity.deformation;\n const materialContractMatches = preparedMaterial === material.materialShaderId;\n const deformationContractMatches =\n (skin === undefined && preparedDeformation === 'rigid') ||\n (skin !== undefined && preparedDeformation === 'skin');\n if (!materialContractMatches || !deformationContractMatches) return 'prepared-contract';\n if (preparedDeformation === 'skin' && !hasFiniteOrderedSkinBounds(skin?.bounds)) {\n return 'missing-skin-bounds';\n }\n return undefined;\n}\n\nfunction hasFiniteOrderedSkinBounds(bounds: Float32Array | undefined): bounds is Float32Array {\n if (bounds === undefined || bounds.length !== 6) return false;\n const minX = bounds[0];\n const minY = bounds[1];\n const minZ = bounds[2];\n const maxX = bounds[3];\n const maxY = bounds[4];\n const maxZ = bounds[5];\n return (\n minX !== undefined &&\n minY !== undefined &&\n minZ !== undefined &&\n maxX !== undefined &&\n maxY !== undefined &&\n maxZ !== undefined &&\n Number.isFinite(minX) &&\n Number.isFinite(minY) &&\n Number.isFinite(minZ) &&\n Number.isFinite(maxX) &&\n Number.isFinite(maxY) &&\n Number.isFinite(maxZ) &&\n minX <= maxX &&\n minY <= maxY &&\n minZ <= maxZ\n );\n}\n\n/**\n * tweak-20260627-model-loading-smoke-build-perf M4: per-World intern cache for\n * the loadByGuid texture/sampler resolution path. A MaterialAsset's\n * texture/sampler values remain embedded GUID strings (dash-form) after\n * loadByGuid; the extract stage re-resolves each GUID to a column handle every\n * frame. Before this cache each resolution called `world.allocSharedRef`, which\n * mints a NEW monotonically-increasing slot id per call. Because the GPU\n * residency cache (`GpuResidencyCache.textureGpuHandles`) is keyed on\n * `handleSlot(handle)`, a fresh slot every frame meant the residency check\n * ALWAYS missed -> all textures re-uploaded to the GPU every frame, old GPU\n * textures never freed (refcount never hits 0). Unbounded GPU memory +\n * unbounded per-frame upload cost (628ms -> 2764ms over 12 frames, SIGKILL).\n *\n * The fix interns the GUID-string -> column-handle resolution: each unique\n * `(guid, brand)` pair mints EXACTLY ONE stable shared handle per World, reused\n * across frames (architecture-principle §6 idempotency: same GUID resolved N\n * times yields the same handle). The handle is intentionally long-lived -- it\n * lives as long as the World references the material, which is exactly the\n * desired lifetime; the `onLastRelease` -> `gpuStore.evictTexture` wiring stays\n * coherent because the handle is no longer churned per frame.\n *\n * Invariant boundary (asset-registry.ts:1958-1962): the AssetRegistry is a\n * GUID -> payload catalogue with NO handle/World concept -- it cannot mint a\n * column handle. So this intern cache lives in the extract/render layer, keyed\n * per-World via a WeakMap (the World owns the SharedRefStore that mints slots).\n *\n * Inner key is `${lowercasedGuid}\\u0000${brand}` -- a GUID catalogues to a\n * single asset kind in practice, but the brand keeps the key correct if the\n * same GUID is ever resolved under two brands.\n *\n * Cache hits are validated against the registry's current payload identity.\n * Re-cataloguing the same GUID therefore retires the cache's allocation grant\n * and mints a handle for the replacement payload. An invalidated GUID retires\n * the entry immediately instead of keeping a stale payload alive.\n */\ninterface GuidHandleInternEntry {\n readonly handle: number;\n readonly payload: Asset;\n}\n\nconst guidHandleInternByWorld = new WeakMap<World, Map<string, GuidHandleInternEntry>>();\n\nexport function internSharedRefFromGuid<B extends string>(\n world: World,\n assetsRef: AssetRegistry,\n guid: string,\n brand: B,\n): Handle<B, 'shared'> | undefined {\n let perWorld = guidHandleInternByWorld.get(world);\n if (perWorld === undefined) {\n perWorld = new Map<string, GuidHandleInternEntry>();\n guidHandleInternByWorld.set(world, perWorld);\n }\n const key = `${guid.toLowerCase()}\\u0000${brand}`;\n const cached = perWorld.get(key);\n const payload = assetsRef.lookup(guid);\n if (cached !== undefined && cached.payload === payload) {\n const cachedHandle = toShared<B>(cached.handle);\n if (world.sharedRefs.resolve(cachedHandle).ok) return cachedHandle;\n }\n if (cached !== undefined) {\n world.sharedRefs.release(toShared<B>(cached.handle));\n perWorld.delete(key);\n }\n if (payload === undefined) return undefined;\n // Mint exactly once per (world, guid, brand). ECS owns the allocation grant\n // and publishes release evidence through SharedRefStore; render does not\n // attach a second deleter lifecycle to the World.\n const handle = world.internSharedRef(brand, payload);\n perWorld.set(key, { handle, payload });\n return handle;\n}\n\n/**\n * feat-20260623-world-space-video-asset M4 / w14 (D-5): if a user-region\n * texture field's paramValue is an embedded GUID string that catalogues to a\n * VideoAsset (`kind === 'video'`), mint a `VideoAsset`-branded column handle for\n * it and return that handle; otherwise return undefined (the field is a static\n * texture / sampler / scalar and flows through the normal TextureAsset path).\n *\n * The video GUID occupies the same texture2d values slot a static texture\n * would (P4: identical binding shape) — extract just routes it to a different\n * GPU lifecycle (the transient DynamicTextureStore, D-3) instead of the static\n * `ensureResident` cache, whose switch has no `video` arm (AC-08). Minting a\n * brand-`VideoAsset` handle keeps the snapshot self-describing: the record stage\n * sees a video handle and resolves the per-frame view without reaching back into\n * the asset (charter P5).\n *\n * A `number` paramValue (already a minted column handle) is not a GUID string so\n * it cannot be a freshly-catalogued video; it passes through as undefined here.\n */\nexport function resolveVideoFieldHandle(\n value: unknown,\n world: World,\n assetsRef: AssetRegistry,\n): Handle<'VideoAsset', 'shared'> | undefined {\n const texture = materialTextureValue(value);\n const textureGuid = assetReferenceText(texture?.texture ?? value);\n if (textureGuid === undefined) return undefined;\n const payload = assetsRef.lookup(textureGuid);\n if (payload === undefined || payload.kind !== 'video') return undefined;\n // M4: intern so a video GUID mints one stable VideoAsset handle per World\n // instead of a fresh slot every frame. The transient per-frame view is\n // resolved downstream by this handle (DynamicTextureStore); minting the\n // handle once does not freeze the view (P5: handle != frame data).\n return internSharedRefFromGuid(world, assetsRef, textureGuid, 'VideoAsset');\n}\n\nexport function materialTextureValue(value: unknown): MaterialTextureValue | undefined {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;\n const textureValue = value as Partial<MaterialTextureValue>;\n return typeof textureValue.texture === 'number' ||\n typeof textureValue.texture === 'string' ||\n textureValue.texture instanceof Uint8Array\n ? (textureValue as MaterialTextureValue)\n : undefined;\n}\n\nexport function assetReferenceText(value: unknown): string | undefined {\n if (typeof value === 'string') return value;\n if (value instanceof Uint8Array && isAssetGuidBytes(value)) return AssetGuid.format(value);\n return undefined;\n}\n\nexport function isAssetGuidBytes(value: Uint8Array): value is AssetGuidBytes {\n return value.byteLength === 16;\n}\n\nexport function materialNormalScale(values: Readonly<Record<string, unknown>>): number {\n for (const [field, value] of Object.entries(values)) {\n if (field !== 'normalTexture') continue;\n const scale = materialTextureValue(value)?.normalScale;\n return typeof scale === 'number' && Number.isFinite(scale) ? scale : 1;\n }\n return 1;\n}\n\nexport function materialTextureRef(value: unknown): unknown {\n return materialTextureValue(value)?.texture ?? value;\n}\n\nexport function collectMaterialTextureCoordinates(\n values: Readonly<Record<string, unknown>>,\n): Map<string, MaterialTextureCoordinates> {\n const out = new Map<string, MaterialTextureCoordinates>();\n // Texture transforms belong to the value itself. Walking every authored\n // value keeps the route closed when Standard gains another physical map\n // without adding another renderer-side field inventory.\n for (const [field, value] of Object.entries(values)) {\n if (!field.endsWith('Texture')) continue;\n const coordinates = materialTextureValue(value)?.coordinates;\n if (coordinates !== undefined) out.set(field, coordinates);\n }\n return out;\n}\n\n/**\n * Return the schema-owned fields that may carry a texture source handle.\n * Numeric material values are otherwise scalar parameters (roughness,\n * metallic, custom steps, ...), so probing them through SharedRefStore is\n * both wasted work and an accidental dependency on slot-number collisions.\n */\nexport function materialTextureSourceFields(\n schema: readonly ParamSchemaEntry[] | undefined,\n): ReadonlySet<string> | undefined {\n if (schema === undefined) return undefined;\n const fields = new Set<string>();\n for (const entry of schema) {\n if (entry.type.startsWith('texture')) fields.add(entry.name);\n }\n return fields;\n}\n\nexport interface MaterialTextureSourceStats {\n sourceFieldsVisited: number;\n numericSharedRefProbes: number;\n sourceCacheHits: number;\n sourceCacheMisses: number;\n producerRoutes: Record<string, number>;\n}\n\n/**\n * Extract-local cache for numeric shared references. `null` is a deliberate\n * negative entry: a handle that is not a render-target source must not be\n * resolved repeatedly for every material field in the same frame.\n */\nexport type MaterialTextureSourceCache = Map<number, RenderTargetTextureSource | null>;\n\nexport function collectMaterialTextureSources(\n values: Readonly<Record<string, unknown>>,\n world: World,\n textureFields?: ReadonlySet<string>,\n stats?: MaterialTextureSourceStats,\n cache?: MaterialTextureSourceCache,\n): Map<string, RenderTargetTextureSource> {\n const out = new Map<string, RenderTargetTextureSource>();\n for (const [field, value] of Object.entries(values)) {\n const structured = materialTextureValue(value);\n const schemaKnown = textureFields !== undefined;\n const schemaAdmitted = textureFields?.has(field) === true;\n // With a known schema, only producer-admitted texture fields may carry a\n // source handle. Without a schema, retain the historical numeric parse so\n // an older producer can still publish a direct shared-ref value; its\n // structured form is accepted on the same conservative path.\n if (schemaKnown && !schemaAdmitted) continue;\n const reference = structured?.texture ?? value;\n if (stats !== undefined) stats.sourceFieldsVisited += 1;\n if (typeof reference !== 'number') continue;\n if (stats !== undefined) stats.numericSharedRefProbes += 1;\n let source: RenderTargetTextureSource | undefined;\n if (cache?.has(reference) === true) {\n if (stats !== undefined) stats.sourceCacheHits += 1;\n source = cache.get(reference) ?? undefined;\n } else {\n if (stats !== undefined) stats.sourceCacheMisses += 1;\n const resolved = world.sharedRefs.resolve<\n 'RenderTargetTextureSource',\n RenderTargetTextureSource\n >(toShared<'RenderTargetTextureSource'>(reference));\n if (!resolved.ok) {\n cache?.set(reference, null);\n } else {\n const binding = resolveRenderTargetMaterialSource(resolved.value);\n cache?.set(reference, binding === undefined ? null : resolved.value);\n source = binding === undefined ? undefined : resolved.value;\n }\n }\n if (source === undefined) continue;\n if (stats !== undefined) {\n stats.producerRoutes.renderTarget = (stats.producerRoutes.renderTarget ?? 0) + 1;\n }\n out.set(field, source);\n }\n return out;\n}\n\nexport function collectMaterialTextureSamplers(\n values: Readonly<Record<string, unknown>>,\n resolveSampler: (value: unknown) => Handle<'SamplerAsset', 'shared'> | undefined,\n): Map<string, Handle<'SamplerAsset', 'shared'>> {\n const out = new Map<string, Handle<'SamplerAsset', 'shared'>>();\n for (const [field, value] of Object.entries(values)) {\n const sampler = resolveSampler(materialTextureValue(value)?.sampler);\n if (sampler !== undefined) out.set(field, sampler);\n }\n const legacySampler = resolveSampler(values.sampler);\n if (legacySampler !== undefined && !out.has('baseColorTexture')) {\n out.set('baseColorTexture', legacySampler);\n }\n return out;\n}\n\n/**\n * feat-20260621-learn-render-5-5-parallax M2 / w7 (D-3): collect the\n * user-region texture handles for a material by iterating the shader's\n * `derive(paramSchema).textureFieldNames` SSOT (via\n * `AssetRegistry.materialShaderTextureFieldNames`). Each declared texture\n * field whose paramValue resolves to a handle lands in the returned map keyed\n * by field name; this is the single path through which an arbitrary number of user-region\n * textures (8 Standard or 9+ custom, e.g. parallax `heightTexture`) flow.\n *\n * When the shader is not registered the built-in Standard field set is used\n * so standard materials still resolve. Emissive and occlusion are ordinary\n * schema-driven user-region textures in that set.\n *\n * feat-20260623-world-space-video-asset M4 / w14 (D-5): a field whose paramValue\n * catalogues to a VideoAsset is routed into `videoOut` (a VideoAsset-branded\n * handle) instead of the TextureAsset map, so the record stage pulls its view\n * from the transient DynamicTextureStore (D-3) rather than the static\n * ensureResident cache (AC-08). The video GUID still has to be in this\n * `textureFieldNames` traversal set or it is never inspected (R-7) — that\n * membership is asserted in w13.\n */\nexport function collectUserRegionTextureHandles(\n pv: Readonly<Record<string, unknown>>,\n shaderId: string | undefined,\n paramSchema: readonly ParamSchemaEntry[] | undefined,\n assetsRef: AssetRegistry,\n world: World,\n resolveTex: (\n value: unknown,\n brand: 'TextureAsset',\n ) => Handle<'TextureAsset', 'shared'> | undefined,\n videoOut: Map<string, Handle<'VideoAsset', 'shared'>>,\n): Map<string, Handle<'TextureAsset', 'shared'>> {\n const fields =\n materialTextureFields(\n shaderId,\n paramSchema !== undefined\n ? derive(paramSchema).textureFieldNames\n : shaderId !== undefined\n ? assetsRef.materialShaderTextureFieldNames(shaderId)\n : undefined,\n ) ?? BUILTIN_USER_REGION_TEXTURE_FIELDS;\n const out = new Map<string, Handle<'TextureAsset', 'shared'>>();\n for (const field of fields) {\n // D-5: a video-kind paramValue is routed to the transient path (videoOut),\n // NOT minted as a TextureAsset (which would crash the record-stage\n // ensureResident, AC-08). A static field falls through to resolveTex.\n const videoHandle = resolveVideoFieldHandle(pv[field], world, assetsRef);\n if (videoHandle !== undefined) {\n videoOut.set(field, videoHandle);\n continue;\n }\n const handle = resolveTex(materialTextureRef(pv[field]), 'TextureAsset');\n if (handle !== undefined) out.set(field, handle);\n }\n return out;\n}\n\nconst ENGINE_INJECTED_TEXTURE_FIELDS = new Set(['emissiveTexture', 'occlusionTexture']);\n\nexport function isEngineInjectedTextureField(\n shaderId: string | undefined,\n fieldName: string,\n): boolean {\n return isStandardPbrMaterialShader(shaderId) && ENGINE_INJECTED_TEXTURE_FIELDS.has(fieldName);\n}\n\nexport function materialStandardTextureMask(\n parameters: readonly MaterialParameter[] | undefined,\n shaderId: string | undefined,\n values: Readonly<Record<string, unknown>>,\n): number | undefined {\n return isCanonicalStandardPbrMaterialShader(shaderId)\n ? standardTextureMask(\n // Canonical materials may provide values without redeclaring the root\n // schema. Pruning must agree with the texture binder in that route too.\n DEFAULT_STANDARD_PBR_PARAM_SCHEMA.filter(\n (entry) =>\n entry.type === 'texture2d' &&\n (values[entry.name] !== undefined ||\n parameters?.some(\n (parameter) => parameter.name === entry.name && parameter.default !== undefined,\n )),\n ),\n )\n : undefined;\n}\n\n/**\n * Project one material's authoring parameters into the runtime ABI.\n *\n * Engine-owned Standard roots are compiled against the canonical superset\n * schema even when the authoring asset omits optional physical fields. A\n * compact authored schema would move later UBO members (for example `ior`)\n * into the wrong slots. Custom material roots keep their own published\n * parameter projection.\n */\nexport function materialParametersToParamSchema(\n parameters: readonly MaterialParameter[],\n shaderId?: string,\n): readonly ParamSchemaEntry[] {\n if (isCanonicalStandardPbrMaterialShader(shaderId)) return STANDARD_PIPELINE_PARAM_SCHEMA;\n return projectMaterialParametersToParamSchema(parameters);\n}\n\n/**\n * Select the parameter ABI for one resolved material. The canonical Standard\n * schema is valid only for the engine-owned default Surface; a Standard root\n * with a project Surface keeps the custom fields that its cooked WGSL reads.\n */\nexport function materialParamSchemaForMaterial(\n parameters: readonly MaterialParameter[],\n authoredShaderId: string | undefined,\n passes: readonly MaterialPass[],\n): readonly ParamSchemaEntry[] {\n const firstPass =\n passes.find(\n (pass) =>\n !/shadow|depth/i.test(\n String(\n (pass.renderState?.tags as Record<string, unknown> | undefined)?.LightMode ?? pass.name,\n ),\n ),\n ) ?? passes[0];\n const surfaceModule = firstPass?.program.moduleSlots?.surface;\n const schemaShaderId =\n surfaceModule === undefined || surfaceModule === DEFAULT_STANDARD_SURFACE_MODULE\n ? authoredShaderId\n : undefined;\n return materialParametersToParamSchema(parameters, schemaShaderId);\n}\n\n/**\n * Resolve color semantics from the material asset first and the shader schema\n * for fields the asset does not redeclare. Generated and historical pack\n * materials commonly omit `parameters`, while the shader registry still owns\n * the complete parameter contract.\n */\nexport function materialColorParameterSchema(\n parameters: readonly MaterialParameter[],\n shaderId: string | undefined,\n assets: AssetRegistry,\n): readonly MaterialColorParameterSchema[] {\n if (shaderId === undefined) return parameters;\n const shader = assets.shaderRegistry.findMaterialArtifact(shaderId);\n if (!shader.ok) return parameters;\n\n const byName = new Map<string, MaterialColorParameterSchema>(\n shader.value.paramSchema.map((parameter) => [parameter.name, parameter]),\n );\n for (const parameter of parameters) byName.set(parameter.name, parameter);\n return [...byName.values()];\n}\n\nconst MATERIAL_PARENT_CHAIN_LIMIT = 128;\n\nexport function isDeepFrozen(value: unknown, seen = new Set<object>()): boolean {\n if (typeof value !== 'object' || value === null) return true;\n if (seen.has(value)) return true;\n if (!Object.isFrozen(value)) return false;\n seen.add(value);\n for (const child of Object.values(value)) {\n if (!isDeepFrozen(child, seen)) return false;\n }\n return true;\n}\n\n/**\n * Capture the object identities that make a resolved material stable. The\n * renderer owns this cache, but the AssetRegistry owns parent GUID lookup, so\n * validation must walk the same chain on every cross-frame read. A malformed\n * or cyclic chain is deliberately not cacheable.\n */\nexport function captureMaterialCacheChain(\n root: MaterialAsset,\n assets: AssetRegistry,\n): readonly MaterialCacheChainIdentity[] | undefined {\n const chain: MaterialCacheChainIdentity[] = [];\n const visitedParentGuids = new Set<string>();\n let current = root;\n for (let depth = 0; depth < MATERIAL_PARENT_CHAIN_LIMIT; depth += 1) {\n const parentRef = current.parent;\n const parentGuid = parentRef === undefined ? undefined : materialGuidText(parentRef);\n chain.push({ asset: current, parentGuid });\n if (parentGuid === undefined) return chain;\n if (parentRef === undefined) return undefined;\n if (visitedParentGuids.has(parentGuid)) return undefined;\n visitedParentGuids.add(parentGuid);\n const parent = assets.lookup<Asset>(parentRef);\n if (parent?.kind !== 'material') return undefined;\n current = parent;\n }\n return undefined;\n}\n\nexport function readPersistentMaterialSnapshot(\n cache: MaterialSnapshotCache | undefined,\n handleRaw: number,\n assets: AssetRegistry,\n): MaterialSnapshotCacheEntry | undefined {\n const entry = cache?.get(handleRaw);\n if (entry === undefined) return undefined;\n if (\n entry.crossFrameSafe &&\n entry.chain !== undefined &&\n entry.catalogEpoch === assets.catalogEpoch\n )\n return entry;\n // The snapshot contains resolved texture and sampler handles as well as the\n // material parent chain. Any registry mutation can replace one of those\n // referenced payloads, so an epoch mismatch is a hard miss even when the\n // material objects themselves are unchanged.\n cache?.delete(handleRaw);\n return undefined;\n}\n\n/**\n * Fast path for a cache entry whose chain was already validated at the\n * current registry epoch. The full reader needs the root asset only when an\n * epoch changed; asking ECS to resolve that root before checking the epoch\n * defeats the cross-frame cache on the ordinary stable frame.\n */\nexport function readStablePersistentMaterialSnapshot(\n cache: MaterialSnapshotCache | undefined,\n handleRaw: number,\n assets: AssetRegistry,\n): MaterialSnapshotCacheEntry | undefined {\n const entry = cache?.get(handleRaw);\n return entry?.crossFrameSafe === true &&\n entry.chain !== undefined &&\n entry.catalogEpoch === assets.catalogEpoch\n ? entry\n : undefined;\n}\n\nexport function storeMaterialSnapshot(\n cache: MaterialSnapshotCache,\n handleRaw: number,\n snapshot: MaterialSnapshot,\n passes: readonly MaterialPass[],\n root: MaterialAsset,\n assets: AssetRegistry,\n): MaterialSnapshotCacheEntry {\n const chain = captureMaterialCacheChain(root, assets);\n const entry: MaterialSnapshotCacheEntry = {\n snapshot,\n passes,\n crossFrameSafe: chain?.every(({ asset }) => isDeepFrozen(asset)) === true,\n ...(chain === undefined ? {} : { chain }),\n ...(chain === undefined ? {} : { catalogEpoch: assets.catalogEpoch }),\n };\n cache.set(handleRaw, entry);\n return entry;\n}\n\n/**\n * feat-20260608 M5 amend / w11-a: resolve a single MaterialAsset handle into\n * a per-submesh MaterialSnapshot. Used by the extractFrame archetype loop to\n * build `RenderableSnapshot.materials[]` for indices >= 1 (the entity-level\n * snapshot at index 0 is built inline because it also drives multi-pass\n * DispatchEntry creation + sprite-region overrides; per-submesh secondary\n * materials are non-sprite + single-pass-equivalent for the record stage's\n * UBO upload, so this helper produces a plain MaterialSnapshot only).\n *\n * Returns `defaultMaterialSnapshot()` (mid-grey unlit) for handle=0 (case-B\n * sentinel, mirroring the inline path) and on each unresolved / non-material\n * asset (so a partially-mis-registered multi-material entity still renders\n * the resolvable submeshes; the count-mismatch validator already filtered\n * the count-disagreement case earlier).\n */\nexport function resolveMaterialSnapshot(\n handleRaw: number,\n world: World,\n assetsRef: AssetRegistry,\n materialSnapshotCache?: MaterialSnapshotCache,\n persistentMaterialSnapshotCache?: MaterialSnapshotCache,\n materialContext?: MaterialCookProgramContext,\n materialTextureSourceStats?: MaterialTextureSourceStats,\n materialTextureSourceCache?: MaterialTextureSourceCache,\n): MaterialSnapshot {\n if (handleRaw === 0) return defaultMaterialSnapshot(handleRaw);\n const cached = materialSnapshotCache?.get(handleRaw);\n if (cached !== undefined) return cached.snapshot;\n const stablePersistentCached = readStablePersistentMaterialSnapshot(\n persistentMaterialSnapshotCache,\n handleRaw,\n assetsRef,\n );\n if (stablePersistentCached !== undefined) {\n materialSnapshotCache?.set(handleRaw, stablePersistentCached);\n return stablePersistentCached.snapshot;\n }\n const tagged = toShared<'MaterialAsset'>(handleRaw);\n const res = resolveAssetHandle(world, tagged);\n if (!res.ok) return defaultMaterialSnapshot(handleRaw);\n const asset = res.value;\n if (asset.kind !== 'material') return defaultMaterialSnapshot(handleRaw);\n const persistentCached = readPersistentMaterialSnapshot(\n persistentMaterialSnapshotCache,\n handleRaw,\n assetsRef,\n );\n if (persistentCached !== undefined) {\n materialSnapshotCache?.set(handleRaw, persistentCached);\n return persistentCached.snapshot;\n }\n const resolvedResult = walkMaterialPassesOverSharedRefs(world, tagged, assetsRef);\n if (!resolvedResult.ok) return defaultMaterialSnapshot(handleRaw);\n const resolved = resolvedResult.value;\n const allPasses = resolved.passes;\n const materialProgramKeys = materialProgramKeysForMaterial(asset, assetsRef, materialContext);\n const materialSceneIndexProgramKeys = materialSceneIndexProgramKeysForMaterial(\n asset,\n assetsRef,\n materialContext,\n );\n const authoredFirstPassShader = runtimeMaterialShaderIdForMaterial(allPasses, undefined);\n const firstPassShader = runtimeMaterialShaderIdForMaterial(allPasses, materialProgramKeys);\n const pv = materialValuesToLinearRuntime(\n resolved.values,\n materialColorParameterSchema(resolved.parameters ?? [], firstPassShader, assetsRef),\n resolved.colorSpace,\n ) as Readonly<Record<string, unknown>>;\n const baseColorPv = pv.baseColor as readonly number[] | undefined;\n const baseColor = vec3.create(\n baseColorPv?.[0] ?? 1,\n baseColorPv?.[1] ?? 1,\n baseColorPv?.[2] ?? 1,\n );\n const metallicPv = typeof pv.metallic === 'number' ? pv.metallic : 0;\n const roughnessPv = typeof pv.roughness === 'number' ? pv.roughness : 0.5;\n const specularColorPv = pv.specularColor as readonly number[] | undefined;\n const normalScalePv = materialNormalScale(pv);\n\n const paramSnap: Record<string, number | number[] | string> = {};\n for (const [k, v] of Object.entries(pv)) {\n if (typeof v === 'number') paramSnap[k] = v;\n else if (typeof v === 'string') paramSnap[k] = v;\n else if (Array.isArray(v) && v.every((x) => typeof x === 'number')) {\n paramSnap[k] = v as number[];\n }\n }\n const materialParamSchema = materialParamSchemaForMaterial(\n resolved.parameters ?? [],\n authoredFirstPassShader,\n allPasses,\n );\n // feat-20260614 M8 (D-19): texture / sampler values are embedded GUIDs\n // (dash-form strings) after loadByGuid. Resolve each to a user-tier column\n // handle by looking up the catalogued payload and minting via\n // world.allocSharedRef; a numeric value (already a column handle from a\n // directly-minted material) passes through unchanged.\n const resolveTexLike = <B extends string>(\n value: unknown,\n brand: B,\n ): Handle<B, 'shared'> | undefined => {\n if (typeof value === 'number') return toShared<B>(value);\n if (typeof value === 'string') {\n // M4: intern the GUID -> column-handle resolution so each unique\n // (world, guid, brand) mints exactly ONE stable handle reused across\n // frames (stops the per-frame slot churn that defeated the GPU\n // residency cache). feat-20260619 M2 / w8: TextureAsset brand wires\n // onLastRelease -> gpuStore.evictTexture; other brands (SamplerAsset)\n // bypass (releaseUnreferenced-fallback lifecycle).\n return internSharedRefFromGuid(world, assetsRef, value, brand);\n }\n return undefined;\n };\n // feat-20260621-learn-render-5-5-parallax M2 / w7 (D-3): iterate the\n // shader's derive(paramSchema).textureFieldNames SSOT instead of a hardcoded\n // user-region field list, so an Nth texture (e.g. parallax heightTexture)\n // resolves through the same path, including emissive/occlusion fields.\n const videoTextureFields = new Map<string, Handle<'VideoAsset', 'shared'>>();\n const textureHandles = collectUserRegionTextureHandles(\n pv,\n firstPassShader,\n materialParamSchema.length > 0 ? materialParamSchema : undefined,\n assetsRef,\n world,\n resolveTexLike,\n videoTextureFields,\n );\n const samplerHandles = collectMaterialTextureSamplers(pv, (value) =>\n resolveTexLike(materialTextureRef(value), 'SamplerAsset'),\n );\n const textureSources = collectMaterialTextureSources(\n pv,\n world,\n materialTextureSourceFields(materialParamSchema.length > 0 ? materialParamSchema : undefined),\n materialTextureSourceStats,\n materialTextureSourceCache,\n );\n const emissiveTextureHandle = resolveTexLike(\n materialTextureRef(pv.emissiveTexture),\n 'TextureAsset',\n );\n const occlusionTextureHandle = resolveTexLike(\n materialTextureRef(pv.occlusionTexture),\n 'TextureAsset',\n );\n const textureCoordinates = collectMaterialTextureCoordinates(pv);\n // Named user-region fields are derived from the map (sprite + legacy reads).\n const baseColorTextureHandle = textureHandles.get('baseColorTexture');\n const metallicRoughnessTextureHandle = textureHandles.get('metallicRoughnessTexture');\n const normalTextureHandle = textureHandles.get('normalTexture');\n const emissivePv = pv.emissive as readonly number[] | undefined;\n const snapshot: MaterialSnapshot = {\n baseColor,\n metallic: metallicPv,\n roughness: roughnessPv,\n ...(resolved.surface?.model === undefined ? {} : { surfaceModel: resolved.surface.model }),\n deferredPass: allPasses.some(\n (pass) =>\n String(\n (pass.renderState?.tags as Record<string, unknown> | undefined)?.LightMode ?? pass.name,\n ) === 'Deferred',\n ),\n ...(specularColorPv !== undefined && {\n specularColor: [\n specularColorPv[0] ?? 1,\n specularColorPv[1] ?? 1,\n specularColorPv[2] ?? 1,\n ] as readonly [number, number, number],\n }),\n normalScale: normalScalePv,\n materialShaderId: firstPassShader,\n materialProgramKeys,\n materialSceneIndexProgramKeys,\n materialHandle: handleRaw,\n renderState: pipelineRenderState(allPasses[0]?.renderState),\n paramSnapshot: paramSnap,\n ...(materialParamSchema.length > 0 && { materialParamSchema }),\n standardTextureMask: materialStandardTextureMask(resolved.parameters, firstPassShader, pv),\n ...(textureCoordinates.size > 0 && { textureCoordinates }),\n ...(textureHandles.size > 0 && { textureHandles }),\n ...(textureSources.size > 0 && { textureSources }),\n ...(videoTextureFields.size > 0 && { videoTextureFields }),\n ...(samplerHandles.size > 0 && { samplerHandles }),\n ...(baseColorTextureHandle !== undefined && { baseColorTexture: baseColorTextureHandle }),\n ...(metallicRoughnessTextureHandle !== undefined && {\n metallicRoughnessTexture: metallicRoughnessTextureHandle,\n }),\n ...(normalTextureHandle !== undefined && { normalTexture: normalTextureHandle }),\n ...(emissivePv !== undefined && {\n emissive: [emissivePv[0] ?? 0, emissivePv[1] ?? 0, emissivePv[2] ?? 0] as readonly [\n number,\n number,\n number,\n ],\n }),\n ...(typeof pv.emissiveIntensity === 'number' && { emissiveIntensity: pv.emissiveIntensity }),\n ...(emissiveTextureHandle !== undefined && { emissiveTexture: emissiveTextureHandle }),\n ...(occlusionTextureHandle !== undefined && { occlusionTexture: occlusionTextureHandle }),\n ...(typeof pv.occlusionStrength === 'number' && { occlusionStrength: pv.occlusionStrength }),\n // feat-city-glb Bug 5 (per-submesh transparency): derive `transparent`\n // from the first pass's `renderState.blend` presence, identical to the\n // entity-level snapshot builder (extractFrame archetype loop). Without\n // this, per-submesh materials (materials[i>=1], e.g. a glTF BLEND decal\n // submesh on a multi-material mesh) never carry the transparent flag, so\n // the record stage's LDR split + blend routing treats them as opaque and\n // their alpha=0 texels composite as black.\n transparent: allPasses[0]?.renderState?.blend !== undefined,\n };\n const stored =\n materialSnapshotCache !== undefined\n ? storeMaterialSnapshot(\n materialSnapshotCache,\n handleRaw,\n snapshot,\n allPasses,\n asset,\n assetsRef,\n )\n : undefined;\n const cacheEntry =\n stored ??\n (persistentMaterialSnapshotCache !== undefined\n ? storeMaterialSnapshot(\n persistentMaterialSnapshotCache,\n handleRaw,\n snapshot,\n allPasses,\n asset,\n assetsRef,\n )\n : undefined);\n if (cacheEntry?.crossFrameSafe === true) {\n persistentMaterialSnapshotCache?.set(handleRaw, cacheEntry);\n }\n return snapshot;\n}\n\n/**\n * feat-20260612-skin-palette-per-frame-upload M2 / m2-6: narrow per-frame\n * pipeline surface consumed by `extractFrame`. Today only `skinPaletteAllocator`\n * crosses the seam (the allocator owns the per-frame palette buffer + cursor;\n * extract calls `resetForFrame` at frame entry then `allocateSlice` +\n * `writeJointPalette` per skinned entity). Kept narrow on purpose — extract\n * does NOT see the rest of `PipelineState` to avoid a circular import via\n * `render-system.ts`.\n */\nexport interface ExtractPipelineSurface {\n readonly skinPaletteAllocator: SkinPaletteAllocator | null;\n}\n\n/**\n * PSSM (Parallel-Split Shadow Maps) split plane computation.\n *\n * Formula (plan-strategy D-8, research F1):\n * C_i = λ·n·(f/n)^(i/m) + (1-λ)·(n + i/m·(f-n))\n * where i = 1..m, n = near, f = far, m = cascadeCount\n *\n * The coverage range is [camera near, DirectionalLight.shadowDistance] — the\n * near end derives from the active camera, the far end is the shadowDistance\n * knob. Returns strictly monotonic view-space z depths (positive).\n *\n * When `far <= near + ε` (ε=1e-6), throws ShadowInvalidConfigError\n * (charter P3 explicit failure — research F2 guarantees formula stability\n * but degenerate configuration must be surfaced to the caller).\n *\n * @param nearPlane - near of the shadow casting range (from the camera near)\n * @param farPlane - far of the shadow casting range (DirectionalLight.shadowDistance)\n * @param cascadeCount - number of cascades (1..4)\n * @param splitLambda - PSSM split weight (0 = pure uniform, 1 = pure log)\n * @returns Array of m split depths (view-space z); length = cascadeCount,\n * guaranteed strictly monotonic, last element = far.\n *\n * @internal exported for w6/w7 testing only; production callers route through\n * extractFrame which validates cascadeCount/splitLambda via component schema.\n */\n/**\n * Compute the 8 world-space corner points of a camera frustum slice.\n *\n * Uses mat4.unproject to map NDC cube corners back to world space.\n * The slice is defined by view-space nearZ and farZ depths.\n *\n * For a WebGPU perspective matrix, ndcZ(viewZ) = camFar * (viewZ - camNear) /\n * (viewZ * (camFar - camNear)). We compute the ndcZ for each slice boundary\n * and unproject directly.\n *\n * @param vp - camera view-projection matrix (column-major 16 floats)\n * @param camNear - camera near plane (used to derive NDC mapping)\n * @param camFar - camera far plane (used to derive NDC mapping)\n * @param nearZ - near depth of the frustum slice (view-space, positive)\n * @param farZ - far depth of the frustum slice (view-space, positive)\n * @returns Array of 8 Vec3 world-space corner positions.\n */\nfunction computeFrustumCorners(\n vp: Mat4,\n camNear: number,\n camFar: number,\n nearZ: number,\n farZ: number,\n projection: 'perspective' | 'orthographic',\n): Vec3[] {\n const invVP = mat4.create();\n mat4.invert(invVP, vp);\n const corners: Vec3[] = [];\n\n // NDC z mapping is projection-dependent (WebGPU clip-space z in [0,1]):\n // perspective: ndc(z) = camFar * (z - camNear) / (z * (camFar - camNear))\n // orthographic: ndc(z) = (z - camNear) / (camFar - camNear)\n // feat-20260613-csm M6 / w22: orthographic cameras silently produced\n // garbage NDC z (perspective formula divides by viewZ, but ortho NDC is\n // linear), which mapped the cascade slab back to a degenerate world-space\n // corner set and the AABB-fit collapsed to near zero -- shadow_caster\n // wrote its triangles outside the [-1,1] clip volume so the depth\n // attachment stayed at clear=1.0 (root cause for shadow-m2 / shadow-m3 /\n // shadow-opt-out dawn red surfaced after w20's host-side ortho fix).\n const span = camFar - camNear;\n const ndcNear =\n projection === 'orthographic'\n ? (nearZ - camNear) / span\n : (camFar * (nearZ - camNear)) / (nearZ * span);\n const ndcFar =\n projection === 'orthographic'\n ? (farZ - camNear) / span\n : (camFar * (farZ - camNear)) / (farZ * span);\n\n const signs = [-1, 1];\n for (const sx of signs) {\n for (const sy of signs) {\n corners.push(unprojectNDC(invVP, sx, sy, ndcNear));\n }\n }\n for (const sx of signs) {\n for (const sy of signs) {\n corners.push(unprojectNDC(invVP, sx, sy, ndcFar));\n }\n }\n\n return corners;\n}\n\n/**\n * Unproject a single NDC point to world space.\n */\nfunction unprojectNDC(invVP: Mat4, ndcX: number, ndcY: number, ndcZ: number): Vec3 {\n const ndc = vec3.create(ndcX, ndcY, ndcZ);\n const ws = vec3.create();\n mat4.unproject(ws, ndc, invVP);\n return ws;\n}\n\nexport function pssmSplit(\n nearPlane: number,\n farPlane: number,\n cascadeCount: number,\n splitLambda: number,\n): Float32Array {\n const EPS = 1e-6;\n if (farPlane <= nearPlane + EPS) {\n throw new ShadowInvalidConfigError('shadowDistance', farPlane, nearPlane + EPS);\n }\n\n const result = new Float32Array(cascadeCount);\n const m = cascadeCount;\n const n = nearPlane;\n const f = farPlane;\n const ratio = f / n;\n\n for (let i = 1; i <= m; i++) {\n const t = i / m;\n const logPart = n * ratio ** t;\n const uniformPart = n + t * (f - n);\n result[i - 1] = splitLambda * logPart + (1 - splitLambda) * uniformPart;\n }\n\n return result;\n}\n\n// feat-20260612-point-light-shadows-urp-hdrp M1 / T-M1-5 (plan-strategy §D-3,\n// requirements §5.3): 6-face view-proj matrix table for one omnidirectional\n// shadow caster.\n//\n/**\n * Build 6 face view-proj matrices for an omnidirectional shadow caster\n * (point-light cube map). Returns 6 mat4 (column-major 16-float each) in face\n * order [+X, -X, +Y, -Y, +Z, -Z] matching the WebGPU cube-camera layer\n * convention.\n *\n * Derive face directions from the shared CubeCamera owner, then reflect clip X\n * to match WebGPU cubemap texel orientation. The point-shadow raster lane\n * mirrors authored front-face winding when it uses these reflected matrices.\n *\n * The returned `Mat4[]` length is always exactly 6. Caller can flatten into a\n * 96-float (6 mat4) Float32Array for UBO upload (T-M1-7).\n *\n * @param lightPos world-space position of the point light (from companion Transform)\n * @param near near plane distance (PointLightShadow.nearPlane)\n * @param far far plane distance (PointLightShadow.farPlane)\n */\nexport function buildPointShadowMatrices(lightPos: Vec3, near: number, far: number): Mat4[] {\n return buildCubeCameraFaceViews({ position: lightPos, near, far }).map(({ viewProjection }) => {\n for (const offset of [0, 4, 8, 12]) viewProjection[offset] = -(viewProjection[offset] ?? 0);\n return viewProjection;\n });\n}\n\n/**\n * bug-20260710-editor-cross-world-shadow: the camera-frustum subset of\n * {@link CameraSnapshot} that the directional-CSM matrix builder consumes.\n * Extracted so the builder can run both inside {@link extractFrame} (single\n * world) AND at the {@link extractFrames} merge layer, where the camera and the\n * directional light may originate in DIFFERENT worlds (the editor\n * editorWorld/sceneWorld super-composite). A cameraless world produces zero\n * lightViewProj matrices, so the merge layer MUST recompute using the surfaced\n * camera — see {@link computeDirectionalCsm}.\n */\nexport interface CsmCameraData {\n readonly world: Float32Array;\n readonly fov: number;\n readonly aspect: number;\n readonly near: number;\n readonly far: number;\n readonly projection: 'perspective' | 'orthographic';\n readonly orthoLeft: number;\n readonly orthoRight: number;\n readonly orthoBottom: number;\n readonly orthoTop: number;\n}\n\n/**\n * bug-20260710-editor-cross-world-shadow: the raw directional-shadow config a\n * DirectionalLight carries, threaded onto {@link ExtractedLights} so the merge\n * layer can recompute CSM matrices against the surfaced camera. Distinct from\n * the *computed* outputs (lightViewProj / splitPlanes) also on ExtractedLights.\n */\nexport interface DirectionalCsmConfig {\n readonly cascadeCount: number;\n readonly splitLambda: number;\n readonly cascadeBlend: number;\n readonly mapSize: number;\n readonly shadowDistance: number;\n readonly shadowFilter: number;\n readonly shadowAngularRadius: number;\n readonly maxPenumbraTexels: number;\n}\n\n/**\n * bug-20260710-editor-cross-world-shadow: computed directional-CSM output —\n * the per-cascade light-view-projection matrices plus the derived cascade\n * metadata. Returned by {@link computeDirectionalCsm}; `undefined` when the\n * config or camera is missing (caller leaves the fields undefined).\n */\nexport interface DirectionalCsmResult {\n readonly lightViewProj: Float32Array[];\n readonly splitPlanes: Float32Array;\n readonly cascadeCount: number;\n readonly cascadeBlend: number;\n readonly shadowMapSize: number;\n readonly directionalShadowQuality: DirectionalShadowQuality;\n}\n\n/**\n * bug-20260710-editor-cross-world-shadow: pure directional-CSM matrix builder,\n * extracted verbatim from the former inline block in {@link extractFrame} (the\n * PSSM split + per-cascade frustum-slice AABB fit + orthographic light\n * projection). It is now a free function so BOTH the per-world extract and the\n * cross-world merge layer can call it — the merge layer is the only place that\n * pairs the first-hit directional light of one world with the surfaced camera\n * of another (editor super-composite). Returns `null` when there is no camera\n * to fit against (a cameraless world's directional light yields no matrices —\n * the caller leaves lightViewProj undefined rather than emitting zero matrices\n * that the WGSL reader would sample as NaN → \"fully lit\").\n *\n * Keeps the prior PSSM lambda, toward-light Z reach RC-2 fix, and clip-space\n * matrix / tile-placement-in-shader split. The XY fit is additionally snapped\n * to the cascade's shadow-texel grid so camera motion cannot continuously\n * shimmer a receiver across raster texel boundaries.\n */\nexport function computeDirectionalCsm(\n direction: Vec3,\n config: DirectionalCsmConfig,\n cameraData: CsmCameraData | undefined,\n): DirectionalCsmResult | null {\n const cascadeCount = Math.round(config.cascadeCount);\n // Coverage range: near from the active camera near (no separate near knob);\n // far is the component's shadowDistance. Fallback near (0.1) only when no\n // camera exists — but matrices are gated on cameraData below anyway.\n const sNear = cameraData?.near ?? 0.1;\n const sFar = config.shadowDistance;\n\n // PSSM split planes: [camera near, shadowDistance], not the camera far.\n const splits = pssmSplit(sNear, sFar, cascadeCount, config.splitLambda);\n // Light view matrix: camera at origin, looking along the light direction.\n const lightDirN = vec3.normalize(vec3.create(), direction);\n const lightTarget = vec3.create(lightDirN[0] ?? 0, lightDirN[1] ?? 0, lightDirN[2] ?? 0);\n const lightView = mat4.create();\n mat4.lookAt(lightView, vec3.create(0, 0, 0), lightTarget, vec3.create(0, 1, 0));\n\n // Camera view-projection for frustum-corner computation. Without a camera the\n // frustum cannot be fit — bail so the caller emits no matrices (undefined),\n // NOT zero matrices (which read as NaN in the shadow shader → no shadow).\n if (cameraData === undefined) return null;\n const camProj = mat4.create();\n if (cameraData.projection === 'orthographic') {\n mat4.orthographic(\n camProj,\n cameraData.orthoLeft,\n cameraData.orthoRight,\n cameraData.orthoTop,\n cameraData.orthoBottom,\n cameraData.near,\n cameraData.far,\n );\n } else {\n mat4.perspective(camProj, cameraData.fov, cameraData.aspect, cameraData.near, cameraData.far);\n }\n const camView = mat4.create();\n mat4.invert(camView, cameraData.world);\n const cameraVP = mat4.create();\n mat4.multiply(cameraVP, camProj, camView);\n\n const resultLightViewProjs: Float32Array[] = [];\n const cascadeFits: DirectionalShadowCascadeFit[] = [];\n\n // bug-20260619 RC-2 (AC-05): toward-light Z reach. Extend the near (toward-\n // light) bound of EVERY cascade to the toward-light extreme of the WHOLE\n // shadow frustum (sNear..sFar) so casters between the light and a slice are\n // admitted; X/Y stays per-cascade tight. Larger light-space z == closer to\n // the light (lookAt forward = eye-target), so the full-frustum max-z is the\n // toward-light reach used as -maxZ (the ortho near plane) per cascade.\n let lightSpaceMaxZFull = -Infinity;\n const fullCorners = computeFrustumCorners(\n cameraVP,\n cameraData.near,\n cameraData.far,\n sNear,\n sFar,\n cameraData.projection,\n );\n for (const ws of fullCorners) {\n const ls = vec3.create();\n mat4.transformVec3(ls, lightView, ws);\n if ((ls[2] ?? 0) > lightSpaceMaxZFull) lightSpaceMaxZFull = ls[2] ?? 0;\n }\n\n // Pre-allocate 4-cascade array; fill in the effective cascades.\n for (let cIdx = 0; cIdx < 4; cIdx++) {\n if (cIdx >= cascadeCount) {\n resultLightViewProjs.push(new Float32Array(16));\n continue;\n }\n // The receiver blends into this cascade before the preceding split.\n // Fit that same overlap instead of sampling outside the next projection.\n const previousSplit = splits[cIdx - 1] ?? sNear;\n const cascadeNear =\n cIdx === 0 ? sNear : Math.max(sNear, previousSplit * (1 - config.cascadeBlend));\n const cascadeFar = splits[cIdx] ?? sFar;\n const corners = computeFrustumCorners(\n cameraVP,\n cameraData.near,\n cameraData.far,\n cascadeNear,\n cascadeFar,\n cameraData.projection,\n );\n const lightMVP = mat4.clone(lightView);\n let minX = Infinity;\n let maxX = -Infinity;\n let minY = Infinity;\n let maxY = -Infinity;\n let minZ = Infinity;\n let maxZ = -Infinity;\n for (const ws of corners) {\n const ls = vec3.create();\n mat4.transformVec3(ls, lightMVP, ws);\n if ((ls[0] ?? 0) < minX) minX = ls[0] ?? 0;\n if ((ls[0] ?? 0) > maxX) maxX = ls[0] ?? 0;\n if ((ls[1] ?? 0) < minY) minY = ls[1] ?? 0;\n if ((ls[1] ?? 0) > maxY) maxY = ls[1] ?? 0;\n if ((ls[2] ?? 0) < minZ) minZ = ls[2] ?? 0;\n if ((ls[2] ?? 0) > maxZ) maxZ = ls[2] ?? 0;\n }\n // Stabilize the orthographic receiver grid against sub-texel camera\n // motion. The raster pass writes each cascade into a square `mapSize`\n // viewport, so the light-space texel pitch is the fitted extent divided\n // by that viewport size. Snap the fitted center to that grid and retain a\n // half-texel guard on each side; caster and receiver projections then move\n // together in whole shadow texels without clipping a frustum corner when\n // the rounded center shifts by half a texel.\n const texelX = (maxX - minX) / config.mapSize;\n const texelY = (maxY - minY) / config.mapSize;\n if (Number.isFinite(texelX) && texelX > 0) {\n const centerX = (minX + maxX) * 0.5;\n const snappedCenterX = Math.round(centerX / texelX) * texelX;\n const halfWidth = (maxX - minX) * 0.5 + texelX * 0.5;\n minX = snappedCenterX - halfWidth;\n maxX = snappedCenterX + halfWidth;\n }\n if (Number.isFinite(texelY) && texelY > 0) {\n const centerY = (minY + maxY) * 0.5;\n const snappedCenterY = Math.round(centerY / texelY) * texelY;\n const halfHeight = (maxY - minY) * 0.5 + texelY * 0.5;\n minY = snappedCenterY - halfHeight;\n maxY = snappedCenterY + halfHeight;\n }\n // Orthographic projection from light-space AABB. RC-2: whole-frustum\n // toward-light extreme for the near bound; per-cascade far (minZ) + X/Y.\n const nearZ = Math.max(maxZ, lightSpaceMaxZFull);\n const orthoProj = mat4.create();\n mat4.orthographic(orthoProj, minX, maxX, maxY, minY, -nearZ, -minZ);\n // lightViewProj = orthoProj * lightView — pure clip-space [-1,1]. Atlas\n // tile placement is handled by the per-cascade viewport + fragment-side UV\n // math (evalDirectional), so shadow_caster.gl_Position stays clip-space.\n cascadeFits.push({\n split: splits[cIdx] ?? sFar,\n minX,\n maxX,\n minY,\n maxY,\n minZ,\n maxZ: nearZ,\n });\n resultLightViewProjs.push(new Float32Array(mat4.multiply(mat4.create(), orthoProj, lightView)));\n }\n\n const projection = projectDirectionalShadow(\n cascadeFits,\n config.mapSize,\n config.shadowFilter ?? 2,\n config.shadowAngularRadius ?? 0.00465,\n config.maxPenumbraTexels ?? 32,\n );\n if (projection === undefined) return null;\n\n return {\n lightViewProj: resultLightViewProjs,\n splitPlanes: projection.splitPlanes,\n cascadeCount,\n cascadeBlend: config.cascadeBlend,\n shadowMapSize: config.mapSize,\n directionalShadowQuality: projection.directionalShadowQuality,\n };\n}\n\n/**\n * feat-20260709-editor-world-partition M1 / w4 (AC-08, plan-strategy §2 D-3):\n * the owner index that previously served BOTH cameras and singleton render\n * resources (skylight / skybox / postProcessParams) is split into two\n * independent indices. `cameraOwner` selects the world whose cameras are\n * surfaced; `resourceOwner` selects the world whose singleton resources are\n * surfaced. A single number is accepted as the backward-compatible legacy form\n * where `cameraOwner === resourceOwner === owner` (single-world callers +\n * frame-loop stay byte-identical; the hard `{ owner }` cutover lands in M2).\n */\nexport interface ExtractFramesOwner {\n readonly cameraOwner: number;\n readonly resourceOwner: number;\n /** Explicit display-camera entity selected by the frame owner. */\n readonly cameraEntityKey?: number;\n}\n\nexport interface PreparedExtractContext {\n readonly materialContext?: MaterialCookProgramContext | undefined;\n readonly assets: AssetRegistry | null | undefined;\n readonly pipelineState: ExtractPipelineSurface | null | undefined;\n readonly materialSnapshotCache: MaterialSnapshotCache | undefined;\n /** `undefined` keeps direct extractFrame's local Fog semantics; `null` means\n * the frame owner already selected that no Fog is present for this world. */\n readonly resourceOwnerFog: FogFrame | null | undefined;\n readonly cull: 'self' | 'none' | 'external';\n readonly cullCameras: readonly CameraSnapshot[] | undefined;\n /** Explicit display-camera entity for this world's camera-owner extract. */\n readonly cameraEntityKey?: number;\n readonly renderables: 'full' | 'none';\n readonly renderableEntities: ReadonlySet<number> | undefined;\n readonly retainHidden: boolean;\n /** World identity used to form cross-world producer ownership keys. */\n readonly worldId: number;\n readonly visibility: VisibilitySnapshot;\n /** Producer-owned artifact lookup; extraction only, never record-time asset reads. */\n readonly getMaterialShaderArtifact:\n | ((\n materialShaderId: string,\n request?: {\n readonly vertexColorAvailable?: boolean;\n readonly deformation?: 'rigid' | 'skin';\n readonly variantSet?: string;\n readonly pass?: 'forward' | 'shadow' | 'depth';\n readonly address?: 'direct' | 'scene-index';\n },\n ) => MaterialShaderArtifact | undefined)\n | undefined;\n /** Renderer-private projection of World-authored instance matrices. */\n readonly instanceCollections: InstanceProjectionStore | undefined;\n}\n\nconst ALL_VISIBLE: VisibilitySnapshot = {\n diagnostics: [],\n hasAnyIntent: false,\n hasAnyHiddenIntent: false,\n get: () => undefined,\n effective: () => 'visible',\n};\n\nfunction collectCameraSnapshots(world: World): CameraSnapshot[] {\n const worldInternal = createWorldInternalView(world);\n const cameras: CameraSnapshot[] = [];\n const cameraQuery = world\n .query({\n read: [Camera],\n optional: [\n MotionBlur,\n DynamicResolution,\n ScreenSpaceReflection,\n DepthOfField,\n BarrelDistortion,\n ],\n with: [Transform, GlobalTransform],\n })\n .unwrap();\n for (const row of cameraQuery) {\n const cam = row.get(Camera);\n const motionBlur = row.get(MotionBlur);\n const barrelDistortion = row.get(BarrelDistortion);\n const motionBlurResult = resolveMotionBlurParams(motionBlur);\n if (!motionBlurResult.ok) throw motionBlurResult.error;\n const motionBlurParams = motionBlurResult.value;\n const depthOfField = row.get(DepthOfField);\n const dynamicResolution = row.get(DynamicResolution);\n const screenSpaceReflection = row.get(ScreenSpaceReflection);\n const projection = cameraProjectionFromF32(cam.projection);\n const depthOfFieldResult = resolveDepthOfFieldParams(depthOfField, {\n projection,\n fov: cam.fov,\n near: cam.near,\n far: cam.far,\n });\n const depthOfFieldError = depthOfFieldResult.ok\n ? undefined\n : depthOfFieldRequestFailure(depthOfFieldResult.error);\n const entity = row.entity;\n const view = worldInternal._getArrayView(entity, GlobalTransform, 'world');\n if (view === undefined) continue;\n const worldMat = new Float32Array(view);\n const target = resolveCameraTarget(world, cam.target);\n const hasNonDefaultOutput =\n cam.exposureMode !== CAMERA_EXPOSURE_MODE_MANUAL ||\n cam.exposure !== 1 ||\n cam.temperature !== 6504 ||\n cam.tint !== 0 ||\n cam.colorLut !== 0 ||\n cam.colorLutStrength !== 0;\n const output = hasNonDefaultOutput\n ? {\n exposure: cameraExposureFromColumns(cam),\n temperature: cam.temperature,\n tint: cam.tint,\n colorLut: cam.colorLut,\n colorLutStrength: cam.colorLutStrength,\n }\n : undefined;\n const antialias = antialiasFromF32(cam.antialias);\n const dynamicResolutionResult = validateDynamicResolutionCamera(dynamicResolution, antialias);\n if (!dynamicResolutionResult.ok) throw dynamicResolutionResult.error;\n const barrelDistortionResult = validateBarrelDistortionParameters(barrelDistortion);\n if (!barrelDistortionResult.ok) throw barrelDistortionResult.error;\n cameras.push({\n entityKey: entity as number,\n ...(target === undefined ? {} : { target }),\n historyVersion: cam.historyVersion,\n position: mat4.getTranslation(vec3.create(), worldMat),\n world: worldMat,\n fov: cam.fov,\n aspect: cam.aspect,\n near: cam.near,\n far: cam.far,\n projection,\n orthoLeft: cam.left,\n orthoRight: cam.right,\n orthoBottom: cam.bottom,\n orthoTop: cam.top,\n tonemap: tonemapFromF32(cam.tonemap),\n exposure: cam.exposure,\n whitePoint: cam.whitePoint,\n ...(output === undefined ? {} : { output }),\n antialias,\n ...(dynamicResolutionResult.value === undefined\n ? {}\n : { dynamicResolution: dynamicResolutionResult.value }),\n bloom: validateCameraBloom(\n cam.bloom,\n cam.bloomThreshold,\n cam.bloomIntensity,\n cam.bloomSoftKnee,\n cam.bloomScatter,\n ),\n bloomThreshold: cam.bloomThreshold,\n bloomIntensity: cam.bloomIntensity,\n bloomSoftKnee: cam.bloomSoftKnee,\n bloomScatter: cam.bloomScatter,\n clearColor: [\n cam.clearColor[0] ?? 0,\n cam.clearColor[1] ?? 0,\n cam.clearColor[2] ?? 0,\n cam.clearColor[3] ?? 1,\n ],\n ...(depthOfFieldResult.ok && depthOfFieldResult.value !== undefined\n ? { depthOfField: depthOfFieldResult.value }\n : {}),\n ...(depthOfFieldError === undefined ? {} : { depthOfFieldError }),\n ...(motionBlurParams === undefined\n ? {}\n : {\n motionBlur: {\n shutterAngle: motionBlurParams.shutterAngle,\n maxRadiusPixels: motionBlurParams.maxRadiusPixels,\n sampleCount: motionBlurParams.sampleCount,\n targetFps: motionBlurParams.targetFps,\n },\n }),\n ...(barrelDistortion === undefined ? {} : { barrelDistortion: barrelDistortionResult.value }),\n ...(screenSpaceReflection === undefined\n ? {}\n : {\n screenSpaceReflection: {\n maxDistance: screenSpaceReflection.maxDistance,\n thickness: screenSpaceReflection.thickness,\n maxRoughness: screenSpaceReflection.maxRoughness,\n },\n }),\n });\n }\n return cameras;\n}\n\nexport function collectCubeCameraSnapshots(world: World): CubeCameraSnapshot[] {\n const worldInternal = createWorldInternalView(world);\n const snapshots: CubeCameraSnapshot[] = [];\n const query = world.query({ read: [CubeCamera], with: [Transform, GlobalTransform] }).unwrap();\n for (const row of query) {\n const camera = row.get(CubeCamera);\n const target = resolveCameraTarget(world, camera.target);\n if (target === undefined) continue;\n const view = worldInternal._getArrayView(row.entity, GlobalTransform, 'world');\n if (view === undefined) continue;\n snapshots.push({\n entityKey: row.entity as number,\n target,\n position: [view[12] ?? 0, view[13] ?? 0, view[14] ?? 0],\n near: camera.near,\n far: camera.far,\n updateIntent: cubeCameraUpdateIntentFromF32(camera.updateIntent),\n requestVersion: camera.requestVersion,\n faceBudget: camera.faceBudget,\n });\n }\n return snapshots;\n}\n\nexport function collectReflectionProbeFacts(world: World): ReflectionProbeFact[] {\n const worldInternal = createWorldInternalView(world);\n const facts: ReflectionProbeFact[] = [];\n const query = world\n .query({ read: [ReflectionProbe], with: [Transform, GlobalTransform] })\n .unwrap();\n for (const row of query) {\n const probe = row.get(ReflectionProbe);\n const view = worldInternal._getArrayView(row.entity, GlobalTransform, 'world');\n if (view === undefined) {\n continue;\n }\n facts.push({\n worldId: 0,\n entityKey: row.entity as number,\n center: [view[12] ?? 0, view[13] ?? 0, view[14] ?? 0],\n halfExtents: [\n probe.halfExtents[0] ?? 0,\n probe.halfExtents[1] ?? 0,\n probe.halfExtents[2] ?? 0,\n ],\n priority: probe.priority,\n intensity: probe.intensity,\n resolution: probe.resolution,\n boxProjection: probe.boxProjection,\n revision: probe.invalidationVersion,\n updateIntent: reflectionProbeUpdateIntentFromF32(probe.updateIntent),\n invalidationVersion: probe.invalidationVersion,\n });\n }\n return facts;\n}\n\ninterface CameraRoleSelection {\n readonly display: readonly CameraSnapshot[];\n readonly auxiliary: readonly CameraSnapshot[];\n}\n\nexport function selectCameraRoles(world: World, requestedEntityKey?: number): CameraRoleSelection {\n const cameras = collectCameraSnapshots(world);\n const displayEntities = cameras\n .filter((camera) => camera.target === undefined)\n .map((camera) => camera.entityKey ?? 0);\n const hasExplicitSelection = requestedEntityKey !== undefined;\n const activeCameraIndex = selectActiveCameraIndex(\n displayEntities,\n hasExplicitSelection ? requestedEntityKey : getActiveCamera(world)?.entity,\n );\n // An explicit FrameCamera selection is authoritative. If it does not name a\n // display camera, retain the existing no-camera error path instead of\n // silently selecting the first camera. ActiveCamera keeps its established\n // first-hit fallback when no explicit frame selection is supplied.\n const displayEntityKey = hasExplicitSelection\n ? displayEntities[activeCameraIndex]\n : (displayEntities[activeCameraIndex] ?? displayEntities[0]);\n const display =\n displayEntityKey === undefined\n ? []\n : cameras.filter((camera) => camera.entityKey === displayEntityKey);\n const candidates: CameraTargetCandidate[] = cameras.map((camera) => ({\n worldId: 0,\n entityKey: camera.entityKey ?? 0,\n ...(camera.target === undefined ? {} : { target: camera.target }),\n requestVersion: 0,\n update: 'continuous',\n }));\n const selected = selectCameraTargetViews(candidates, {\n ...(displayEntityKey === undefined ? {} : { displayEntityKey }),\n budget: 1,\n });\n const auxiliary = selected.auxiliary.flatMap((candidate) =>\n cameras.filter((camera) => camera.entityKey === candidate.entityKey),\n );\n return { display, auxiliary };\n}\n\nexport function extractCameraSnapshots(world: World): CameraSnapshot[] {\n return [...selectCameraRoles(world).display];\n}\n\nexport function extractCameraTargetSnapshots(world: World): readonly CameraSnapshot[] {\n return selectCameraRoles(world).auxiliary;\n}\n\nexport function tonemapParams(camera: CameraSnapshot): Uint8Array {\n const bytes = new ArrayBuffer(16);\n const floats = new Float32Array(bytes);\n const integers = new Uint32Array(bytes);\n floats[0] = camera.exposure;\n floats[1] = camera.whitePoint;\n integers[2] = tonemapToU32(camera.tonemap);\n return new Uint8Array(bytes);\n}\n\nexport function prepareExtractContext(\n world: World,\n options: {\n readonly materialContext?: MaterialCookProgramContext;\n readonly assets?: AssetRegistry | null;\n readonly pipelineState?: ExtractPipelineSurface | null;\n readonly materialSnapshotCache?: MaterialSnapshotCache;\n readonly resourceOwnerFog?: FogFrame | null;\n readonly cull?: 'self' | 'none' | 'external';\n readonly cullCameras?: readonly CameraSnapshot[];\n readonly cameraEntityKey?: number;\n readonly renderables?: 'full' | 'none';\n readonly renderableEntities?: ReadonlySet<number>;\n readonly retainHidden?: boolean;\n readonly worldId?: number;\n readonly getMaterialShaderArtifact?: (\n materialShaderId: string,\n request?: {\n readonly vertexColorAvailable?: boolean;\n readonly deformation?: 'rigid' | 'skin';\n readonly variantSet?: string;\n readonly pass?: 'forward' | 'shadow' | 'depth';\n readonly address?: 'direct' | 'scene-index';\n },\n ) => MaterialShaderArtifact | undefined;\n readonly instanceCollections?: InstanceProjectionStore;\n } = {},\n): PreparedExtractContext {\n const renderables = options.renderables ?? 'full';\n return {\n materialContext: options.materialContext,\n assets: options.assets,\n pipelineState: options.pipelineState,\n materialSnapshotCache: options.materialSnapshotCache,\n resourceOwnerFog: options.resourceOwnerFog,\n cull: options.cull ?? 'self',\n cullCameras: options.cullCameras,\n ...(options.cameraEntityKey === undefined ? {} : { cameraEntityKey: options.cameraEntityKey }),\n renderables,\n worldId: options.worldId ?? 0,\n renderableEntities: options.renderableEntities,\n retainHidden: options.retainHidden ?? false,\n visibility: renderables === 'none' ? ALL_VISIBLE : resolveVisibility(world),\n getMaterialShaderArtifact: options.getMaterialShaderArtifact,\n instanceCollections: options.instanceCollections,\n };\n}\n\nconst fogQueries = new WeakMap<World, Query<readonly [typeof Fog]>>();\nconst fogLkgStates = new WeakMap<\n World,\n { lkg: FogFrame | undefined; failure: FogSelectionFailure | undefined }\n>();\n\nexport function fogState(world: World): {\n lkg: FogFrame | undefined;\n failure: FogSelectionFailure | undefined;\n} {\n const existing = fogLkgStates.get(world);\n if (existing !== undefined) return existing;\n const created = { lkg: undefined, failure: undefined };\n fogLkgStates.set(world, created);\n return created;\n}\n\nexport function selectFogFrame(world: World): FogFrame | undefined {\n // Query compilation is owned once per World; Query refreshes its matched\n // tables when the ECS structure changes, while iteration reads current Fog\n // values. This keeps the frame boundary free of repeated descriptor work.\n const fogCandidates: FogCandidate[] = [];\n let fogQuery = fogQueries.get(world);\n if (fogQuery === undefined) {\n fogQuery = world.query({ read: [Fog] }).unwrap();\n fogQueries.set(world, fogQuery);\n }\n for (const row of fogQuery) {\n const value = row.get(Fog);\n fogCandidates.push({\n entityKey: row.entity,\n color: [value.color[0] ?? 0, value.color[1] ?? 0, value.color[2] ?? 0],\n density: value.density,\n heightFalloff: value.heightFalloff,\n maxOpacity: value.maxOpacity,\n });\n }\n const fogSelection = selectEnvironment({\n environments: [],\n fogs: fogCandidates,\n suns: [],\n lane: 'direct',\n });\n const state = fogState(world);\n if (fogSelection.ok) {\n state.lkg = fogSelection.value.fog;\n state.failure = undefined;\n return fogSelection.value.fog;\n }\n state.failure = {\n code: fogSelection.error.code,\n expected: fogSelection.error.expected,\n hint: fogSelection.error.hint,\n detail: Object.freeze({ ...fogSelection.error.detail }),\n };\n routeWorldError(world, fogSelection.error, {\n systemName: 'RenderSystem.extract (fog-selection)',\n });\n if (state.lkg !== undefined) return state.lkg;\n throw fogSelection.error;\n}\n\nexport function textureDigest(texture: TextureAsset): string {\n // The render inspection needs a stable identity token, not a second byte\n // store. FNV-1a is deterministic, synchronous, and deliberately labelled\n // as a non-cryptographic digest so it cannot be mistaken for Catalog proof.\n let hash = 2166136261;\n for (const byte of texture.data) hash = Math.imul(hash ^ byte, 16777619) >>> 0;\n return `fnv1a:${hash.toString(16).padStart(8, '0')}`;\n}\n\nexport function extractVolumeSnapshot(\n world: World,\n assets: AssetRegistry | null | undefined,\n worldInternal: WorldInternalView,\n): ExtractedVolumetricFog | undefined {\n const elapsed = world.getResource(Time).elapsed;\n const worldTimeSeconds = Number.isFinite(elapsed) ? Math.max(0, elapsed) : 0;\n const query = world.query({ read: [VolumetricFog] }).unwrap();\n const authorings: VolumetricFogAuthoring[] = [];\n const members: ExtractedVolumetricFog[] = [];\n let selectedLight:\n | {\n readonly entity: EntityHandle;\n readonly kind: 'directional' | 'point' | 'spot';\n readonly pointLightEntity?: EntityHandle;\n readonly spotLightEntity?: EntityHandle;\n }\n | undefined;\n\n for (const row of query) {\n selectedLight = undefined;\n const source = row.get(VolumetricFog);\n if (source.light === null) continue;\n const selected = resolveSelectedVolumetricLight(world, source.light);\n if (selected.status === 'available') {\n const pairSpot = source.spotLight === null ? undefined : source.spotLight;\n selectedLight ??= {\n entity: selected.entity,\n kind: selected.kind,\n ...(selected.kind === 'point' ? { pointLightEntity: selected.entity } : {}),\n ...(pairSpot === undefined ? {} : { spotLightEntity: pairSpot }),\n };\n }\n const densityHandle = toShared<'TextureAsset'>(Math.round(Number(source.density)));\n const resolved = resolveAssetHandle<TextureAsset>(world, densityHandle);\n if (!resolved.ok || resolved.value.kind !== 'texture') {\n worldInternal._routeError(\n resolved.ok\n ? new RhiError({\n code: 'asset-not-registered',\n expected: 'VolumetricFog.density resolves to a TextureAsset',\n hint: 'load a TextureAsset before assigning it to VolumetricFog.density',\n detail: { assetHandle: Number(densityHandle) },\n })\n : resolved.error,\n { severity: Severity.Error, systemName: 'RenderSystem.extract (volumetric-density)' },\n );\n return { status: 'degraded', worldTimeSeconds };\n }\n const densityAsset = resolved.value;\n const guid = assets?.guidOf(densityAsset) ?? `handle:${Number(densityHandle)}`;\n const shape = densityAsset.shape;\n const density: VolumeDensityBinding =\n shape.viewDimension === '3d'\n ? {\n guid,\n generation: 1,\n shape: {\n viewDimension: '3d',\n extent: {\n width: shape.extent.width,\n height: shape.extent.height,\n depth: shape.extent.depth,\n },\n },\n format: densityAsset.format,\n colorSpace: densityAsset.colorSpace,\n }\n : {\n guid,\n generation: 1,\n shape: {\n viewDimension: shape.viewDimension,\n extent:\n shape.viewDimension === '2d-array'\n ? {\n width: shape.extent.width,\n height: shape.extent.height,\n layers: shape.extent.layers,\n }\n : { width: shape.extent.width, height: shape.extent.height },\n },\n format: densityAsset.format,\n colorSpace: densityAsset.colorSpace,\n };\n const authoring: VolumetricFogAuthoring = {\n light: source.light,\n density,\n bounds: {\n min: [source.boundsMin[0] ?? 0, source.boundsMin[1] ?? 0, source.boundsMin[2] ?? 0],\n max: [source.boundsMax[0] ?? 0, source.boundsMax[1] ?? 0, source.boundsMax[2] ?? 0],\n },\n extinction: [source.extinction[0] ?? 0, source.extinction[1] ?? 0, source.extinction[2] ?? 0],\n albedo: [source.albedo[0] ?? 0, source.albedo[1] ?? 0, source.albedo[2] ?? 0],\n emission: [source.emission[0] ?? 0, source.emission[1] ?? 0, source.emission[2] ?? 0],\n anisotropy: source.anisotropy,\n maxDistance: source.maxDistance,\n sampling: source.sampling === 1 ? 'density' : 'noise',\n };\n authorings.push(authoring);\n members.push({\n status: 'available',\n worldTimeSeconds,\n densityHandle,\n densityAsset,\n guid,\n generation: 1,\n digest: textureDigest(densityAsset),\n ...(selectedLight === undefined\n ? {}\n : {\n lightEntity: selectedLight.entity,\n lightKind: selectedLight.kind,\n ...(selectedLight.pointLightEntity === undefined\n ? {}\n : { pointLightEntity: selectedLight.pointLightEntity }),\n ...(selectedLight.spotLightEntity === undefined\n ? {}\n : { spotLightEntity: selectedLight.spotLightEntity }),\n }),\n });\n }\n\n if (authorings.length === 0) return undefined;\n const extracted = extractVolumetricFog(authorings);\n if (!extracted.ok) {\n worldInternal._routeError(extracted.error, {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (volumetric-fog)',\n });\n return { ...members[0], status: 'degraded' };\n }\n if (extracted.value.status === 'off') return { status: 'off' };\n const validatedMembers = extracted.value.fogs.map((fog, index) => ({\n ...members[index],\n status: 'available' as const,\n fog,\n }));\n return {\n status: 'available',\n ...validatedMembers[0],\n additional: validatedMembers.slice(1),\n };\n}\n\n// Source contract anchor: the spot-light query remains single-source in this\n// extraction boundary (`const spotLightQuery = world.query({ read: [SpotLight] })`)\n// and snapshots retain the\n// normalized `const dirN = vec3.create(` then `direction: dirN` fields; the implementation body lives in the\n// tail module to keep this owner below the physical line budget. The tail keeps\n// the extract integration bound to deriveInstancesUnionBounds, rather than\n// introducing a second bounds ledger in this forwarding owner.\n\nexport { defaultMaterialSnapshot, extractFrame, extractFrames } from './render-system-extract-tail';\n"]}