@forgeax/engine-render 0.1.34 → 0.1.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (273) hide show
  1. package/README.md +69 -3
  2. package/dist/assembly/device-feature-admission.d.ts +2 -2
  3. package/dist/assembly/host-contract.d.ts +3 -2
  4. package/dist/assembly/host-contract.d.ts.map +1 -1
  5. package/dist/assembly/recovery/renderer-recover.d.ts.map +1 -1
  6. package/dist/assembly/render-target-host.d.ts +5 -0
  7. package/dist/assembly/render-target-host.d.ts.map +1 -1
  8. package/dist/assembly/renderer-facade.d.ts.map +1 -1
  9. package/dist/assembly/webgpu-renderer.d.ts +1 -0
  10. package/dist/assembly/webgpu-renderer.d.ts.map +1 -1
  11. package/dist/assembly/webgpu-vertex-layouts.d.ts.map +1 -1
  12. package/dist/authoring.mjs +2 -4
  13. package/dist/authoring.mjs.map +1 -1
  14. package/dist/chunk-2OZAS3WU.mjs +3489 -0
  15. package/dist/chunk-2OZAS3WU.mjs.map +1 -0
  16. package/dist/{chunk-UI5SFODX.mjs → chunk-BZQ4CDRF.mjs} +2338 -1991
  17. package/dist/chunk-BZQ4CDRF.mjs.map +1 -0
  18. package/dist/{chunk-MKDIT2EM.mjs → chunk-CJOV2XLO.mjs} +216 -261
  19. package/dist/chunk-CJOV2XLO.mjs.map +1 -0
  20. package/dist/chunk-D6WSBXJ2.mjs +1842 -0
  21. package/dist/chunk-D6WSBXJ2.mjs.map +1 -0
  22. package/dist/{chunk-HEB564WF.mjs → chunk-DRF6OULX.mjs} +4 -4
  23. package/dist/{chunk-HEB564WF.mjs.map → chunk-DRF6OULX.mjs.map} +1 -1
  24. package/dist/{chunk-OCDLEI6I.mjs → chunk-OB5WAFYH.mjs} +117 -5
  25. package/dist/chunk-OB5WAFYH.mjs.map +1 -0
  26. package/dist/{chunk-ODZWR6JQ.mjs → chunk-OEYKKMXG.mjs} +2042 -27
  27. package/dist/chunk-OEYKKMXG.mjs.map +1 -0
  28. package/dist/chunk-RIPAEGI6.mjs +48 -0
  29. package/dist/chunk-RIPAEGI6.mjs.map +1 -0
  30. package/dist/{chunk-ELJFJ2BU.mjs → chunk-X2KA6WHM.mjs} +29 -4
  31. package/dist/chunk-X2KA6WHM.mjs.map +1 -0
  32. package/dist/{chunk-BLXGONR2.mjs → chunk-XSFB7XXQ.mjs} +51 -4
  33. package/dist/chunk-XSFB7XXQ.mjs.map +1 -0
  34. package/dist/cloud/frame-context.d.ts +2 -2
  35. package/dist/cloud/frame-context.d.ts.map +1 -1
  36. package/dist/construct-renderer.mjs +936 -2140
  37. package/dist/construct-renderer.mjs.map +1 -1
  38. package/dist/device/device-scope.d.ts.map +1 -1
  39. package/dist/device/gpu-residency.d.ts +19 -19
  40. package/dist/device/gpu-residency.d.ts.map +1 -1
  41. package/dist/errors/render.d.ts +3 -2
  42. package/dist/errors/render.d.ts.map +1 -1
  43. package/dist/extract/material-context.d.ts +7 -0
  44. package/dist/extract/material-context.d.ts.map +1 -0
  45. package/dist/features/host.d.ts +5 -0
  46. package/dist/features/host.d.ts.map +1 -1
  47. package/dist/features/particle-mesh-layout.d.ts +19 -0
  48. package/dist/features/particle-mesh-layout.d.ts.map +1 -0
  49. package/dist/features/plan.d.ts +2 -0
  50. package/dist/features/plan.d.ts.map +1 -1
  51. package/dist/features/types.d.ts +8 -0
  52. package/dist/features/types.d.ts.map +1 -1
  53. package/dist/glyph-text-layout-system.d.ts +1 -1
  54. package/dist/glyph-text-layout-system.d.ts.map +1 -1
  55. package/dist/gpu-driven/production-raster.d.ts +1 -1
  56. package/dist/gpu-driven/production-raster.d.ts.map +1 -1
  57. package/dist/gpu-driven/shadow-ownership.d.ts +3 -3
  58. package/dist/gpu-driven/shadow-ownership.d.ts.map +1 -1
  59. package/dist/gpu-driven/shadow-views.d.ts +1 -1
  60. package/dist/gpu-driven/shadow-views.d.ts.map +1 -1
  61. package/dist/gpu-driven/view-gpu.d.ts +1 -1
  62. package/dist/gpu-driven/view-gpu.d.ts.map +1 -1
  63. package/dist/ibl/frame-resources.d.ts.map +1 -1
  64. package/dist/ibl/skylight-bind-group.d.ts +4 -4
  65. package/dist/ibl/skylight-bind-group.d.ts.map +1 -1
  66. package/dist/index.d.ts +3 -0
  67. package/dist/index.d.ts.map +1 -1
  68. package/dist/index.mjs +542 -9
  69. package/dist/index.mjs.map +1 -1
  70. package/dist/instances.d.ts +3 -4
  71. package/dist/instances.d.ts.map +1 -1
  72. package/dist/internal.mjs +7 -8
  73. package/dist/internal.mjs.map +1 -1
  74. package/dist/pbr-pipeline.d.ts +3 -3
  75. package/dist/pbr-pipeline.d.ts.map +1 -1
  76. package/dist/pipeline/standard-output/lut-gpu.d.ts +2 -2
  77. package/dist/pipeline/standard-output/lut-gpu.d.ts.map +1 -1
  78. package/dist/pipeline/standard-output/resources.d.ts +2 -2
  79. package/dist/pipeline/standard-output/resources.d.ts.map +1 -1
  80. package/dist/publication/contract.d.ts +77 -0
  81. package/dist/publication/contract.d.ts.map +1 -0
  82. package/dist/publication/dependencies.d.ts +7 -0
  83. package/dist/publication/dependencies.d.ts.map +1 -0
  84. package/dist/publication/prepare-geometry.d.ts +9 -0
  85. package/dist/publication/prepare-geometry.d.ts.map +1 -0
  86. package/dist/publication/programs.d.ts +5 -0
  87. package/dist/publication/programs.d.ts.map +1 -0
  88. package/dist/publication/publisher.d.ts +34 -0
  89. package/dist/publication/publisher.d.ts.map +1 -0
  90. package/dist/publication/receiver.d.ts +29 -0
  91. package/dist/publication/receiver.d.ts.map +1 -0
  92. package/dist/publication/resource-scope.d.ts +18 -0
  93. package/dist/publication/resource-scope.d.ts.map +1 -0
  94. package/dist/publication/targets.d.ts +33 -0
  95. package/dist/publication/targets.d.ts.map +1 -0
  96. package/dist/publication/video.d.ts +5 -0
  97. package/dist/publication/video.d.ts.map +1 -0
  98. package/dist/record/fold-buckets.d.ts +3 -3
  99. package/dist/record/fold-buckets.d.ts.map +1 -1
  100. package/dist/record/frame-snapshot.d.ts +6 -6
  101. package/dist/record/frame-snapshot.d.ts.map +1 -1
  102. package/dist/record/frame.d.ts +5 -4
  103. package/dist/record/frame.d.ts.map +1 -1
  104. package/dist/record/helpers.d.ts +2 -2
  105. package/dist/record/helpers.d.ts.map +1 -1
  106. package/dist/record/main-pass-geometry.d.ts +2 -2
  107. package/dist/record/main-pass-geometry.d.ts.map +1 -1
  108. package/dist/record/main-pass-material.d.ts +7 -9
  109. package/dist/record/main-pass-material.d.ts.map +1 -1
  110. package/dist/record/main-pass-sprite-draws.d.ts +3 -16
  111. package/dist/record/main-pass-sprite-draws.d.ts.map +1 -1
  112. package/dist/record/main-pass.d.ts.map +1 -1
  113. package/dist/record/prepared-material-bindings.d.ts +2 -3
  114. package/dist/record/prepared-material-bindings.d.ts.map +1 -1
  115. package/dist/record/render-context.d.ts +4 -2
  116. package/dist/record/render-context.d.ts.map +1 -1
  117. package/dist/record/shadow-pass.d.ts +2 -2
  118. package/dist/record/shadow-pass.d.ts.map +1 -1
  119. package/dist/record/sprite-instance-buffer.d.ts +31 -0
  120. package/dist/record/sprite-instance-buffer.d.ts.map +1 -0
  121. package/dist/record/target-capture-graph.d.ts +19 -0
  122. package/dist/record/target-capture-graph.d.ts.map +1 -0
  123. package/dist/record/typed-frame-graph.d.ts +2 -13
  124. package/dist/record/typed-frame-graph.d.ts.map +1 -1
  125. package/dist/record/view-ubo.d.ts.map +1 -1
  126. package/dist/record/volume-params.d.ts +2 -2
  127. package/dist/record/volume-params.d.ts.map +1 -1
  128. package/dist/recovery/render-system-candidate.d.ts +5 -12
  129. package/dist/recovery/render-system-candidate.d.ts.map +1 -1
  130. package/dist/render-contract.d.ts +4 -1
  131. package/dist/render-contract.d.ts.map +1 -1
  132. package/dist/render-system-extract-tail.d.ts.map +1 -1
  133. package/dist/render-system-extract.d.ts +2 -0
  134. package/dist/render-system-extract.d.ts.map +1 -1
  135. package/dist/render-system-presentation.d.ts +2 -2
  136. package/dist/render-system-presentation.d.ts.map +1 -1
  137. package/dist/render-system-projections.d.ts +3 -2
  138. package/dist/render-system-projections.d.ts.map +1 -1
  139. package/dist/render-system-residency.d.ts +2 -2
  140. package/dist/render-system-residency.d.ts.map +1 -1
  141. package/dist/render-system.d.ts +3 -7
  142. package/dist/render-system.d.ts.map +1 -1
  143. package/dist/scene/render-scene.d.ts +8 -4
  144. package/dist/scene/render-scene.d.ts.map +1 -1
  145. package/dist/scene/render-source.d.ts +42 -0
  146. package/dist/scene/render-source.d.ts.map +1 -0
  147. package/dist/scene/source-systems.d.ts +6 -0
  148. package/dist/scene/source-systems.d.ts.map +1 -0
  149. package/dist/systems/skin-palette-allocator.d.ts.map +1 -1
  150. package/dist/systems/skin-palette-types.d.ts +10 -0
  151. package/dist/systems/skin-palette-types.d.ts.map +1 -1
  152. package/dist/systems/transparent-dispatch.d.ts +2 -2
  153. package/dist/systems/transparent-dispatch.d.ts.map +1 -1
  154. package/dist/systems/transparent-sort-config.d.ts +2 -1
  155. package/dist/systems/transparent-sort-config.d.ts.map +1 -1
  156. package/dist/temporal/index.mjs +6 -7
  157. package/dist/typed-shadow-passes.d.ts.map +1 -1
  158. package/package.json +21 -21
  159. package/src/__tests__/auto-exposure-transaction.integration.test.ts +4 -9
  160. package/src/__tests__/device-feature-admission.unit.test.ts +3 -2
  161. package/src/__tests__/device-scope-lifecycle.unit.test.ts +26 -0
  162. package/src/__tests__/gpu-driven-pbr.dawn.test.ts +3 -4
  163. package/src/__tests__/gpu-driven-production.integration.test.ts +18 -1
  164. package/src/__tests__/gpu-driven-shadow-views.unit.test.ts +23 -0
  165. package/src/__tests__/ktx2-basis-gpu-consumer.dawn.test.ts +4 -1
  166. package/src/__tests__/main-pass-material-medium-selection.unit.test.ts +0 -1
  167. package/src/__tests__/material-vertex-texture.browser.test.ts +7 -0
  168. package/src/__tests__/material-vertex-texture.dawn.test.ts +7 -0
  169. package/src/__tests__/material-vertex-texture.fixture.ts +31 -0
  170. package/src/__tests__/materials-standard-contract.unit.test.ts +0 -1
  171. package/src/__tests__/physical-clearcoat.integration.test.ts +23 -23
  172. package/src/__tests__/physical-material-budget.unit.test.ts +40 -0
  173. package/src/__tests__/recovery-candidate-prepare.contract.test.ts +5 -0
  174. package/src/__tests__/render-error-code-owner.test-d.ts +1 -0
  175. package/src/__tests__/renderer-factory-material-contract.unit.test.ts +107 -5
  176. package/src/__tests__/runtime-material-program.integration.test.ts +79 -0
  177. package/src/__tests__/vertex-layouts-ssot.unit.test.ts +23 -3
  178. package/src/assembly/device-feature-admission.ts +2 -2
  179. package/src/assembly/host-contract.ts +5 -2
  180. package/src/assembly/recovery/renderer-recover.ts +9 -0
  181. package/src/assembly/render-target-host.ts +57 -47
  182. package/src/assembly/renderer-facade.ts +3 -1
  183. package/src/assembly/webgpu-ready.ts +1 -1
  184. package/src/assembly/webgpu-renderer.ts +101 -70
  185. package/src/assembly/webgpu-vertex-layouts.ts +2 -9
  186. package/src/cloud/frame-context.ts +2 -2
  187. package/src/device/device-scope.ts +3 -0
  188. package/src/device/gpu-residency.ts +26 -25
  189. package/src/errors/render.ts +3 -1
  190. package/src/extract/material-context.ts +21 -0
  191. package/src/features/host.ts +13 -5
  192. package/src/features/particle-mesh-layout.ts +25 -0
  193. package/src/features/plan.ts +2 -0
  194. package/src/features/types.ts +8 -0
  195. package/src/glyph-text-layout-system.ts +2 -2
  196. package/src/gpu-driven/production-raster.ts +9 -3
  197. package/src/gpu-driven/shadow-ownership.ts +3 -3
  198. package/src/gpu-driven/shadow-views.ts +27 -2
  199. package/src/gpu-driven/view-gpu.ts +5 -0
  200. package/src/ibl/frame-resources.ts +0 -1
  201. package/src/ibl/skylight-bind-group.ts +13 -25
  202. package/src/index.ts +9 -0
  203. package/src/instances.ts +9 -6
  204. package/src/pbr-pipeline.ts +15 -18
  205. package/src/pipeline/standard-output/lut-gpu.ts +3 -3
  206. package/src/pipeline/standard-output/resources.ts +2 -2
  207. package/src/publication/__tests__/derived-geometry.integration.test.ts +177 -0
  208. package/src/publication/__tests__/features.integration.test.ts +173 -0
  209. package/src/publication/__tests__/programs.unit.test.ts +25 -0
  210. package/src/publication/__tests__/publication.integration.test.ts +415 -0
  211. package/src/publication/__tests__/targets.integration.test.ts +120 -0
  212. package/src/publication/__tests__/video.browser.test.ts +50 -0
  213. package/src/publication/contract.ts +104 -0
  214. package/src/publication/dependencies.ts +54 -0
  215. package/src/publication/prepare-geometry.ts +94 -0
  216. package/src/publication/programs.ts +45 -0
  217. package/src/publication/publisher.ts +645 -0
  218. package/src/publication/receiver.ts +297 -0
  219. package/src/publication/resource-scope.ts +31 -0
  220. package/src/publication/targets.ts +182 -0
  221. package/src/publication/video.ts +33 -0
  222. package/src/record/__tests__/material-bg-cache.unit.test.ts +15 -1
  223. package/src/record/__tests__/prepared-runtime-material.integration.test.ts +134 -0
  224. package/src/record/__tests__/sprite-material-abi.unit.test.ts +8 -10
  225. package/src/record/__tests__/video-texture-view.unit.test.ts +9 -9
  226. package/src/record/fold-buckets.ts +8 -5
  227. package/src/record/frame-snapshot.ts +6 -6
  228. package/src/record/frame.ts +87 -28
  229. package/src/record/helpers.ts +2 -2
  230. package/src/record/main-pass-geometry.ts +21 -2
  231. package/src/record/main-pass-material.ts +37 -33
  232. package/src/record/main-pass-sprite-draws.ts +6 -152
  233. package/src/record/main-pass.ts +8 -7
  234. package/src/record/prepared-material-bindings.ts +16 -37
  235. package/src/record/render-context.ts +4 -2
  236. package/src/record/shadow-pass.ts +65 -7
  237. package/src/record/sprite-instance-buffer.ts +155 -0
  238. package/src/record/target-capture-graph.ts +258 -0
  239. package/src/record/typed-frame-graph.ts +11 -207
  240. package/src/record/view-ubo.ts +1 -1
  241. package/src/record/volume-params.ts +6 -6
  242. package/src/recovery/render-system-candidate.ts +10 -18
  243. package/src/render-contract.ts +6 -1
  244. package/src/render-system-extract-tail.ts +48 -23
  245. package/src/render-system-extract.ts +11 -2
  246. package/src/render-system-presentation.ts +2 -2
  247. package/src/render-system-projections.ts +3 -2
  248. package/src/render-system-residency.ts +2 -2
  249. package/src/render-system.ts +82 -54
  250. package/src/scene/render-scene.ts +110 -100
  251. package/src/scene/render-source.ts +90 -0
  252. package/src/scene/source-systems.ts +33 -0
  253. package/src/systems/skin-palette-allocator.ts +1 -0
  254. package/src/systems/skin-palette-types.ts +11 -0
  255. package/src/systems/transparent-dispatch.ts +2 -2
  256. package/src/systems/transparent-sort-config.ts +3 -1
  257. package/src/typed-shadow-passes.ts +36 -5
  258. package/dist/chunk-BLXGONR2.mjs.map +0 -1
  259. package/dist/chunk-ELJFJ2BU.mjs.map +0 -1
  260. package/dist/chunk-ILQ5MEZF.mjs +0 -32
  261. package/dist/chunk-ILQ5MEZF.mjs.map +0 -1
  262. package/dist/chunk-MKDIT2EM.mjs.map +0 -1
  263. package/dist/chunk-OCDLEI6I.mjs.map +0 -1
  264. package/dist/chunk-ODZWR6JQ.mjs.map +0 -1
  265. package/dist/chunk-RXZ3RGOU.mjs +0 -53
  266. package/dist/chunk-RXZ3RGOU.mjs.map +0 -1
  267. package/dist/chunk-SHFUFJ5N.mjs +0 -1781
  268. package/dist/chunk-SHFUFJ5N.mjs.map +0 -1
  269. package/dist/chunk-UI5SFODX.mjs.map +0 -1
  270. package/dist/chunk-UINHLCZA.mjs +0 -2389
  271. package/dist/chunk-UINHLCZA.mjs.map +0 -1
  272. package/dist/chunk-WEX45HKH.mjs +0 -1524
  273. package/dist/chunk-WEX45HKH.mjs.map +0 -1
@@ -0,0 +1,3489 @@
1
+ import { err, ok, derive } from '@forgeax/engine-types';
2
+ import { cubeArrayDepthDescriptor, comparisonSamplerDescriptor, cubeArrayDepthFaceView } from '@forgeax/engine-rhi';
3
+ import { vec3 } from '@forgeax/engine-math';
4
+ import { InstanceTransformsStrideMismatchError } from '@forgeax/engine-ecs/projection';
5
+ import { STANDARD_PIPELINE_PARAM_SCHEMA, standardPhysicalTextureFields, STANDARD_PHYSICAL_TEXTURE_FIELDS } from '@forgeax/engine-shader';
6
+ import { deriveVertexLayoutProjection } from '@forgeax/engine-geometry';
7
+
8
+ // src/pipeline/standard-output/auto-exposure/inspection.ts
9
+ var AutoExposureInvalidParameterError = class extends Error {
10
+ constructor(detail) {
11
+ super(`auto-exposure-invalid-parameter: ${detail.field}`);
12
+ this.detail = detail;
13
+ this.name = "AutoExposureInvalidParameterError";
14
+ }
15
+ detail;
16
+ code = "auto-exposure-invalid-parameter";
17
+ expected = ERROR_POLICY[this.code].expected;
18
+ hint = ERROR_POLICY[this.code].hint;
19
+ };
20
+ var AutoExposureCapabilityUnavailableError = class extends Error {
21
+ constructor(detail) {
22
+ super(`auto-exposure-capability-unavailable: ${detail.capability}`);
23
+ this.detail = detail;
24
+ this.name = "AutoExposureCapabilityUnavailableError";
25
+ }
26
+ detail;
27
+ code = "auto-exposure-capability-unavailable";
28
+ expected = ERROR_POLICY[this.code].expected;
29
+ hint = ERROR_POLICY[this.code].hint;
30
+ };
31
+ var AutoExposureStaleGenerationError = class extends Error {
32
+ constructor(detail) {
33
+ super(
34
+ `auto-exposure-stale-generation: ${detail.actualGeneration} != ${detail.expectedGeneration}`
35
+ );
36
+ this.detail = detail;
37
+ this.name = "AutoExposureStaleGenerationError";
38
+ }
39
+ detail;
40
+ code = "auto-exposure-stale-generation";
41
+ expected = ERROR_POLICY[this.code].expected;
42
+ hint = ERROR_POLICY[this.code].hint;
43
+ };
44
+ var AutoExposureStageFailedError = class extends Error {
45
+ constructor(detail) {
46
+ super(`auto-exposure-stage-failed: ${detail.operation}`);
47
+ this.detail = detail;
48
+ this.name = "AutoExposureStageFailedError";
49
+ }
50
+ detail;
51
+ code = "auto-exposure-stage-failed";
52
+ expected = ERROR_POLICY[this.code].expected;
53
+ hint = ERROR_POLICY[this.code].hint;
54
+ };
55
+ var ERROR_POLICY = {
56
+ "auto-exposure-invalid-parameter": {
57
+ expected: "camera auto-exposure parameters are finite and within their declared ranges",
58
+ hint: "inspect the field and provide a finite value before rebuilding the camera output"
59
+ },
60
+ "auto-exposure-capability-unavailable": {
61
+ expected: "the auto-exposure stage has the required device capability",
62
+ hint: "inspect live capabilities and retry the same camera generation"
63
+ },
64
+ "auto-exposure-stale-generation": {
65
+ expected: "the prepared auto-exposure state matches the camera target generation",
66
+ hint: "discard stale prepared state and rebuild from the latest camera snapshot"
67
+ },
68
+ "auto-exposure-stage-failed": {
69
+ expected: "the auto-exposure stage completes its declared operation",
70
+ hint: "inspect the structured cause, preserve lastKnownGood, and retry the stage"
71
+ }
72
+ };
73
+ function createAutoExposureError(input) {
74
+ if (input instanceof AutoExposureInvalidParameterError || input instanceof AutoExposureCapabilityUnavailableError || input instanceof AutoExposureStaleGenerationError || input instanceof AutoExposureStageFailedError) {
75
+ return input;
76
+ }
77
+ switch (input.code) {
78
+ case "auto-exposure-invalid-parameter":
79
+ return new AutoExposureInvalidParameterError(input.detail);
80
+ case "auto-exposure-capability-unavailable":
81
+ return new AutoExposureCapabilityUnavailableError(input.detail);
82
+ case "auto-exposure-stale-generation":
83
+ return new AutoExposureStaleGenerationError(input.detail);
84
+ case "auto-exposure-stage-failed":
85
+ return new AutoExposureStageFailedError(input.detail);
86
+ }
87
+ }
88
+ function cloneExposure(exposure) {
89
+ if (exposure.kind === "manual") return { ...exposure };
90
+ return {
91
+ ...exposure,
92
+ rangeEv: [exposure.rangeEv[0], exposure.rangeEv[1]],
93
+ rates: [exposure.rates[0], exposure.rates[1]]
94
+ };
95
+ }
96
+ function cloneFailure(error) {
97
+ if (error === void 0) return void 0;
98
+ return Object.freeze({
99
+ ...error,
100
+ detail: Object.freeze({ ...error.detail })
101
+ });
102
+ }
103
+ function createAutoExposureInspection(input) {
104
+ const base = {
105
+ requested: cloneExposure(input.requested),
106
+ actual: input.actual,
107
+ actualState: input.actualState ?? (input.actual === null ? "gpu-resident" : "accepted"),
108
+ fallback: input.fallback,
109
+ lastKnownGood: input.lastKnownGood,
110
+ targetGeneration: input.targetGeneration,
111
+ reset: Object.freeze([...input.reset]),
112
+ cost: Object.freeze({ ...input.cost }),
113
+ receipt: Object.freeze({ ...input.receipt })
114
+ };
115
+ if (input.recentFailure === void 0) return Object.freeze(base);
116
+ const recentFailure = cloneFailure(createAutoExposureError(input.recentFailure));
117
+ if (recentFailure === void 0) return Object.freeze(base);
118
+ return Object.freeze({ ...base, recentFailure });
119
+ }
120
+
121
+ // src/errors/render.ts
122
+ var LifecycleConstructionError = class extends Error {
123
+ code = "lifecycle-construction-failed";
124
+ expected = "all DeviceScope resources establish and terminate in order";
125
+ hint = "inspect detail and cleanupFailures, then recover or rebuild the DeviceScope";
126
+ detail;
127
+ constructor(detail) {
128
+ super(`lifecycle-construction-failed: ${detail.resourceKind} lifecycle transaction failed`);
129
+ this.name = "LifecycleConstructionError";
130
+ this.detail = detail;
131
+ }
132
+ };
133
+ var LightResourceUnavailableError = class extends Error {
134
+ code = "light-resource-unavailable";
135
+ expected;
136
+ hint;
137
+ detail;
138
+ constructor(detail, expected, actual, hint) {
139
+ super(`light-resource-unavailable: ${detail.feature} ${actual}`);
140
+ this.name = "LightResourceUnavailableError";
141
+ this.expected = expected;
142
+ this.hint = hint;
143
+ this.detail = detail;
144
+ }
145
+ };
146
+ function createLightResourceUnavailable(input) {
147
+ return new LightResourceUnavailableError(
148
+ {
149
+ entity: input.entity,
150
+ feature: input.feature,
151
+ generation: input.generation,
152
+ sourceKey: input.sourceKey,
153
+ reason: input.reason
154
+ },
155
+ input.expected,
156
+ input.actual,
157
+ input.hint
158
+ );
159
+ }
160
+ var TemporalFrameSubmitError = class extends Error {
161
+ code = "temporal-frame-submit-rejected";
162
+ expected = "the staged frame is accepted by queue.submit before temporal facts advance";
163
+ hint = "inspect the queue submission and retry the frame after the device is available";
164
+ detail;
165
+ constructor(reason) {
166
+ super(`temporal-frame-submit-rejected: ${reason}`);
167
+ this.name = "TemporalFrameSubmitError";
168
+ this.detail = { reason };
169
+ }
170
+ };
171
+ var ShadowInvalidConfigError = class extends Error {
172
+ code = "shadow-invalid-config";
173
+ expected;
174
+ hint;
175
+ detail;
176
+ constructor(field, actual, minOrBound, maxOrComparator, reason) {
177
+ const bound = typeof minOrBound === "number" ? typeof maxOrComparator === "number" ? { kind: "range", min: minOrBound, max: maxOrComparator } : {
178
+ kind: "lower-bound",
179
+ operator: maxOrComparator === ">" ? ">" : ">=",
180
+ value: minOrBound
181
+ } : minOrBound;
182
+ const resolvedReason = reason ?? shadowBoundReason(bound);
183
+ const expected = shadowBoundExpected(field, bound);
184
+ const hint = `set ${field} to ${resolvedReason}; got ${actual}`;
185
+ super(`shadow component .${field} is invalid: ${resolvedReason}; got ${actual}`);
186
+ this.name = "ShadowInvalidConfigError";
187
+ this.hint = hint;
188
+ this.expected = expected;
189
+ this.detail = { field, actual, bound, reason: resolvedReason };
190
+ }
191
+ };
192
+ function shadowBoundExpected(field, bound) {
193
+ switch (bound.kind) {
194
+ case "range":
195
+ return `${field} in [${bound.min}, ${bound.max}]`;
196
+ case "lower-bound":
197
+ return `${field} ${bound.operator} ${bound.value}`;
198
+ case "allowed-values":
199
+ return `${field} in {${bound.values.join(", ")}}`;
200
+ }
201
+ }
202
+ function shadowBoundReason(bound) {
203
+ switch (bound.kind) {
204
+ case "range":
205
+ return `a value in [${bound.min}, ${bound.max}]`;
206
+ case "lower-bound":
207
+ return `a value ${bound.operator} ${bound.value}`;
208
+ case "allowed-values":
209
+ return `one of [${bound.values.join(", ")}]`;
210
+ }
211
+ }
212
+ var EquirectProjectionFailedError = class extends Error {
213
+ code = "equirect-projection-failed";
214
+ expected;
215
+ hint;
216
+ detail;
217
+ constructor(handle) {
218
+ const expected = `equirect handle ${handle} projects to a GPU cubemap + IBL precompute`;
219
+ const hint = `equirect handle ${handle} referenced by Skylight/SkyboxBackground failed projection; declare Skylight{equirect} with a valid HDR equirect source and check device.caps.rgba16floatRenderable. The projection is internal (no user upload call); the record arm does not retry`;
220
+ super(`equirect handle ${handle} cubemap projection failed`);
221
+ this.name = "EquirectProjectionFailedError";
222
+ this.expected = expected;
223
+ this.hint = hint;
224
+ this.detail = { handle };
225
+ }
226
+ };
227
+ var StandardLightBudgetExceededError = class extends Error {
228
+ code = "standard-light-budget-exceeded";
229
+ expected;
230
+ hint;
231
+ detail;
232
+ constructor(actual, budget) {
233
+ const expected = `light count <= ${budget}`;
234
+ const hint = `${actual} finite local lights exceed Standard budget ${budget}; reduce the local-light set or select a profile with a supported budget`;
235
+ super(`Standard light budget exceeded: ${actual} > ${budget}`);
236
+ this.name = "StandardLightBudgetExceededError";
237
+ this.expected = expected;
238
+ this.hint = hint;
239
+ this.detail = { actual, budget };
240
+ }
241
+ };
242
+ var StandardClusterIndexOverflowError = class extends Error {
243
+ code = "standard-cluster-index-overflow";
244
+ expected;
245
+ hint;
246
+ detail;
247
+ constructor(actual, capacity) {
248
+ const expected = `light index list entries <= ${capacity}`;
249
+ const hint = `cluster binner overflow: writeCount ${actual} exceeds capacity ${capacity}; reduce finite local lights or choose a supported cluster layout`;
250
+ super(`Standard cluster index list overflow: ${actual} > ${capacity}`);
251
+ this.name = "StandardClusterIndexOverflowError";
252
+ this.expected = expected;
253
+ this.hint = hint;
254
+ this.detail = { actual, capacity };
255
+ }
256
+ };
257
+ var StandardClusterTransportUnavailableError = class extends Error {
258
+ code = "standard-cluster-transport-unavailable";
259
+ expected = "all requested local lights have a proven Cluster transport";
260
+ hint;
261
+ detail;
262
+ constructor(requested, hint = "enable a proven Cluster storage transport before drawing") {
263
+ super(`Standard Cluster transport unavailable for ${requested} local lights`);
264
+ this.name = "StandardClusterTransportUnavailableError";
265
+ this.hint = hint;
266
+ this.detail = { requested, admitted: 0 };
267
+ }
268
+ };
269
+ var StandardProfileInvalidError = class extends Error {
270
+ code = "standard-profile-invalid";
271
+ expected;
272
+ hint;
273
+ detail;
274
+ constructor(message, detail) {
275
+ super(message);
276
+ this.name = "StandardProfileInvalidError";
277
+ this.detail = detail ?? { field: "profile", actual: message };
278
+ if (this.detail.field === "clusterGrid") {
279
+ this.expected = "clusterGrid.{x,y,z} each positive integer in [1, 64]";
280
+ this.hint = "set clusterGrid.x, clusterGrid.y, and clusterGrid.z to positive integers in [1, 64]";
281
+ } else {
282
+ this.expected = "StandardProfile contains only supported fields and values";
283
+ this.hint = "repair the Standard profile fields and retry setProfile";
284
+ }
285
+ }
286
+ };
287
+ var PointShadowAtlasUninitializedError = class extends Error {
288
+ code = "point-shadow-atlas-uninitialized";
289
+ expected;
290
+ hint;
291
+ constructor() {
292
+ const expected = "ShadowAtlas.ensure() invoked before faceView()";
293
+ const hint = "Gate faceView on isAllocated() or call ensure() once in the per-frame extract step before iterating face views";
294
+ super("ShadowAtlas.faceView called before ensure(); the cube_array texture is not allocated");
295
+ this.name = "PointShadowAtlasUninitializedError";
296
+ this.expected = expected;
297
+ this.hint = hint;
298
+ }
299
+ };
300
+ var PointShadowAtlasBoundsViolationError = class extends Error {
301
+ code = "point-shadow-atlas-bounds-violation";
302
+ expected;
303
+ hint;
304
+ detail;
305
+ constructor(axis, value, max) {
306
+ const expected = `0 <= ${axis} < ${max}`;
307
+ const hint = axis === "layer" ? `clamp PointLight.shadowAtlasLayer to [0, ${max}); the cap on layers equals PointLightShadow cardinality (4)` : `clamp face index to [0, ${max}); cube faces are indexed 0..5 in +X/-X/+Y/-Y/+Z/-Z order`;
308
+ super(`ShadowAtlas.faceView ${axis} out of range: ${value} (must be in [0, ${max}))`);
309
+ this.name = "PointShadowAtlasBoundsViolationError";
310
+ this.expected = expected;
311
+ this.hint = hint;
312
+ this.detail = { axis, value, max };
313
+ }
314
+ };
315
+ var VideoUploadUnsupportedError = class extends Error {
316
+ code = "video-upload-unsupported";
317
+ expected;
318
+ hint;
319
+ constructor() {
320
+ const expected = "at least one video upload path available: a host HTMLVideoElement (general copyExternalImageToTexture path) or GPUExternalTexture capability (high-perf path)";
321
+ const hint = "this backend exposes no usable video upload path; render a static texture instead, or switch to a WebGPU backend that supports video texture upload";
322
+ super("video upload unsupported \u2014 no general or high-perf path available");
323
+ this.name = "VideoUploadUnsupportedError";
324
+ this.expected = expected;
325
+ this.hint = hint;
326
+ }
327
+ };
328
+ var VertexColorVariantConflictError = class extends Error {
329
+ code = "vertex-color-variant-conflict";
330
+ expected;
331
+ hint;
332
+ detail;
333
+ constructor(authoredValue, projected) {
334
+ const expected = `VERTEX_COLOR_AVAILABLE=${projected ? "true" : "false"}`;
335
+ const hint = "derive the shader variant from the mesh VertexLayoutProjection; COLOR_0 presence is a geometry fact";
336
+ super(`authored vertex-color variant ${authoredValue} disagrees with projected ${expected}`);
337
+ this.name = "VertexColorVariantConflictError";
338
+ this.expected = expected;
339
+ this.hint = hint;
340
+ this.detail = { authored: true, authoredValue, projected };
341
+ }
342
+ };
343
+ var SkinPaletteOverflowError = class extends Error {
344
+ code = "skin-palette-overflow";
345
+ expected;
346
+ hint;
347
+ detail;
348
+ constructor(requestedBytes, limit) {
349
+ const expected = `skinned joint palette (${requestedBytes} B) fits within device.limits.maxStorageBufferBindingSize (${limit} B)`;
350
+ const hint = "palette buffer exceeds device maxStorageBufferBindingSize; reduce skinned entity count or split into multiple palette buffers (OOS-skin-palette-batch)";
351
+ super(`skin palette buffer needs ${requestedBytes} B, exceeds device limit ${limit} B`);
352
+ this.name = "SkinPaletteOverflowError";
353
+ this.expected = expected;
354
+ this.hint = hint;
355
+ this.detail = { requestedBytes, limit };
356
+ }
357
+ };
358
+ var SkinMaterialMismatchError = class extends Error {
359
+ code = "skin-material-mismatch";
360
+ expected;
361
+ hint;
362
+ detail;
363
+ constructor(entity, actualShader) {
364
+ const expected = "Skin entity's first material program module === 'forgeax::pbr-skin'";
365
+ const hint = `entity ${entity} has Skin but the first material program module is ${actualShader ?? "<empty>"}; load the mesh via the gltf importer (cooker auto-routes 'forgeax::pbr-skin' for skinned primitives), or remove the Skin component to render the entity unskinned with Materials.standard / Materials.unlit`;
366
+ super(
367
+ `Skin / material mismatch on entity ${entity}: expected forgeax::pbr-skin, got ${actualShader ?? "<empty>"}`
368
+ );
369
+ this.name = "SkinMaterialMismatchError";
370
+ this.expected = expected;
371
+ this.hint = hint;
372
+ this.detail = { entity, actualShader };
373
+ }
374
+ };
375
+ var MaterialSkinAttrMissingError = class extends Error {
376
+ code = "material-skin-attr-missing";
377
+ expected;
378
+ hint;
379
+ detail;
380
+ constructor(entity, missing) {
381
+ const expected = "pbr-skin material requires mesh.attributes.skinIndex + skinWeight";
382
+ const hint = `entity ${entity} uses forgeax::pbr-skin but its MeshAsset is missing ${missing}; switch the entity to a skinned glTF mesh authored with JOINTS_0 + WEIGHTS_0, or change the material to a non-skin shader via Materials.standard / Materials.unlit`;
383
+ super(
384
+ `material/skin attribute mismatch on entity ${entity}: pbr-skin material with mesh missing ${missing}`
385
+ );
386
+ this.name = "MaterialSkinAttrMissingError";
387
+ this.expected = expected;
388
+ this.hint = hint;
389
+ this.detail = { entity, missing };
390
+ }
391
+ };
392
+ var TransmissionCapabilityMissingError = class extends Error {
393
+ code = "transmission-capability-missing";
394
+ expected = "the renderer exposes the transmission capability for this material";
395
+ hint = "disable transmission or provide the renderer capability before drawing";
396
+ detail;
397
+ constructor(material, stage, evidence) {
398
+ super(`transmission capability is missing for material '${material}'`);
399
+ this.name = "TransmissionCapabilityMissingError";
400
+ this.detail = { material, capability: "transmission", stage, ...evidence };
401
+ }
402
+ };
403
+ var renderFeatureRecoveryHintByRecovery = {
404
+ "next-frame": (featureIdentity, stage) => `correct '${featureIdentity}' ${stage} data and retry on the next frame`,
405
+ "renderer-recover": (featureIdentity, _stage) => `wait for renderer recovery before retrying '${featureIdentity}'`,
406
+ registration: (featureIdentity, _stage) => `correct '${featureIdentity}' registration before retrying`
407
+ };
408
+ var RenderFeatureRegistrationConflictError = class extends Error {
409
+ code = "render-feature-registration-conflict";
410
+ expected;
411
+ hint;
412
+ detail;
413
+ constructor(featureIdentity, order, conflictingOrder) {
414
+ const expected = `feature identity '${featureIdentity}' is unique`;
415
+ const hint = `rename '${featureIdentity}' or remove the duplicate feature before registration`;
416
+ super(`render feature registration conflict for '${featureIdentity}'`);
417
+ this.name = "RenderFeatureRegistrationConflictError";
418
+ this.expected = expected;
419
+ this.hint = hint;
420
+ this.detail = { featureIdentity, order, conflictingOrder };
421
+ }
422
+ };
423
+ var RenderFeatureStageFailedError = class extends Error {
424
+ code = "render-feature-stage-failed";
425
+ expected;
426
+ hint;
427
+ detail;
428
+ constructor(featureIdentity, order, stage, recovery, cause) {
429
+ const expected = `feature '${featureIdentity}' completes its ${stage} stage without an error`;
430
+ const hint = renderFeatureRecoveryHintByRecovery[recovery](featureIdentity, stage);
431
+ super(`render feature '${featureIdentity}' failed during ${stage}`);
432
+ this.name = "RenderFeatureStageFailedError";
433
+ this.expected = expected;
434
+ this.hint = hint;
435
+ this.detail = {
436
+ featureIdentity,
437
+ order,
438
+ stage,
439
+ recovery,
440
+ ...cause === void 0 ? {} : { cause }
441
+ };
442
+ }
443
+ };
444
+ var RenderFeatureCapabilityMissingError = class extends Error {
445
+ code = "render-feature-capability-missing";
446
+ expected;
447
+ hint;
448
+ detail;
449
+ constructor(featureIdentity, order, capability) {
450
+ const expected = `device capability '${capability}' is available for feature '${featureIdentity}'`;
451
+ const hint = `disable '${featureIdentity}' or use a device with '${capability}' capability`;
452
+ super(`render feature '${featureIdentity}' requires missing capability '${capability}'`);
453
+ this.name = "RenderFeatureCapabilityMissingError";
454
+ this.expected = expected;
455
+ this.hint = hint;
456
+ this.detail = { featureIdentity, order, capability };
457
+ }
458
+ };
459
+ var RenderFeaturePreparationFailedError = class extends Error {
460
+ code = "render-feature-preparation-failed";
461
+ expected;
462
+ hint;
463
+ detail;
464
+ constructor(featureIdentity, order, operation, resourceKind, resourceName, reason, recovery) {
465
+ const expected = `${resourceKind} '${resourceName}' is prepared during ${operation}`;
466
+ const hint = `repair '${resourceName}' and retry feature '${featureIdentity}' on ${recovery}`;
467
+ super(`render feature '${featureIdentity}' preparation failed for '${resourceName}'`);
468
+ this.name = "RenderFeaturePreparationFailedError";
469
+ this.expected = expected;
470
+ this.hint = hint;
471
+ this.detail = {
472
+ featureIdentity,
473
+ order,
474
+ stage: "prepare",
475
+ operation,
476
+ resourceKind,
477
+ resourceName,
478
+ reason,
479
+ recovery
480
+ };
481
+ }
482
+ };
483
+ var RenderFeaturePreparedStateMismatchError = class extends Error {
484
+ code = "render-feature-prepared-state-mismatch";
485
+ expected;
486
+ hint;
487
+ detail;
488
+ constructor(detail) {
489
+ const expected = `${detail.resourceKind} state is compatible for '${detail.operation}'`;
490
+ const hint = `repair '${detail.reason}' for feature '${detail.featureIdentity}' and retry`;
491
+ super(`render feature '${detail.featureIdentity}' prepared state mismatch`);
492
+ this.name = "RenderFeaturePreparedStateMismatchError";
493
+ this.expected = expected;
494
+ this.hint = hint;
495
+ this.detail = detail;
496
+ }
497
+ };
498
+ var RenderFeatureDrawRecordingFailedError = class extends Error {
499
+ code = "render-feature-draw-recording-failed";
500
+ expected;
501
+ hint;
502
+ detail;
503
+ constructor(featureIdentity, order, operation, resourceKind, reason, backendReason, recovery) {
504
+ const expected = `${resourceKind} recording succeeds for '${operation}'`;
505
+ const hint = `repair '${reason}' and retry feature '${featureIdentity}' after ${recovery}`;
506
+ super(`render feature '${featureIdentity}' draw recording failed`);
507
+ this.name = "RenderFeatureDrawRecordingFailedError";
508
+ this.expected = expected;
509
+ this.hint = hint;
510
+ this.detail = {
511
+ featureIdentity,
512
+ order,
513
+ stage: "record",
514
+ operation,
515
+ resourceKind,
516
+ reason,
517
+ backendReason,
518
+ recovery
519
+ };
520
+ }
521
+ };
522
+ var ObservationUnavailableError = class extends Error {
523
+ code = "observation-unavailable";
524
+ expected;
525
+ hint;
526
+ detail;
527
+ constructor(reason, hint) {
528
+ let recovery;
529
+ if (reason === "copy-src") recovery = "enable-copy-src";
530
+ else if (reason === "resource" || reason === "readback-failed") recovery = "retry-readback";
531
+ else recovery = "draw-current-frame";
532
+ super(`current-frame observation unavailable: ${reason}`);
533
+ this.name = "ObservationUnavailableError";
534
+ this.expected = "a fresh producer-owned rgba16float current-frame observation";
535
+ this.hint = hint;
536
+ this.detail = { reason, recovery };
537
+ }
538
+ };
539
+ var SceneDataUnavailableError = class extends Error {
540
+ code = "scene-data-unavailable";
541
+ expected = "the requested semantic scene data is available for the active plan";
542
+ hint;
543
+ detail;
544
+ constructor(detail) {
545
+ const hint = detail.recovery === "enable-capability" ? "enable rgba16floatRenderable and retry the current frame" : detail.recovery === "renderer-recover" ? "wait for renderer recovery, then retry the frame" : "restore the producer coverage and retry on the next frame";
546
+ super(`scene data '${detail.schema}' unavailable for '${detail.featureIdentity}'`);
547
+ this.name = "SceneDataUnavailableError";
548
+ this.hint = hint;
549
+ this.detail = Object.freeze({
550
+ ...detail,
551
+ missingContributorIds: Object.freeze([...detail.missingContributorIds].slice(0, 32)),
552
+ omittedMissingContributorCount: Math.max(
553
+ detail.omittedMissingContributorCount,
554
+ Math.max(0, detail.missingContributorIds.length - 32)
555
+ )
556
+ });
557
+ }
558
+ };
559
+ var FrameReceiptStaleError = class extends Error {
560
+ code = "frame-receipt-stale";
561
+ expected = "the observation receipt belongs to the active device generation";
562
+ hint = "draw a new frame and call observe with its returned FrameReceipt";
563
+ detail;
564
+ constructor(detail) {
565
+ super("frame receipt belongs to a retired device generation");
566
+ this.name = "FrameReceiptStaleError";
567
+ this.detail = detail;
568
+ }
569
+ };
570
+ var RendererContractFailureError = class extends Error {
571
+ code = "renderer-contract-failed";
572
+ expected = "renderer owner contracts remain valid at the public boundary";
573
+ hint = "repair the owner contract and retry the operation";
574
+ detail;
575
+ constructor(operation, cause) {
576
+ super(`renderer ${operation} contract failed: ${cause}`);
577
+ this.name = "RendererContractFailureError";
578
+ this.detail = { operation, cause };
579
+ }
580
+ };
581
+ var EnvironmentSourceConflictError = class extends Error {
582
+ code = "environment-source-conflict";
583
+ expected = "exactly one environment source owns the frame";
584
+ hint = "remove all but one image or atmosphere environment owner";
585
+ detail;
586
+ constructor(owners) {
587
+ super("environment source owners conflict");
588
+ this.name = "EnvironmentSourceConflictError";
589
+ this.detail = { owners: owners.map((owner) => Object.freeze({ ...owner })) };
590
+ }
591
+ };
592
+ var FogCardinalityError = class extends Error {
593
+ code = "fog-cardinality";
594
+ expected = "zero or one Fog owner contributes to a frame";
595
+ hint = "remove extra Fog owners so the resource owner has at most one";
596
+ detail;
597
+ constructor(count) {
598
+ super(`Fog owner cardinality is ${count}`);
599
+ this.name = "FogCardinalityError";
600
+ this.detail = { count };
601
+ }
602
+ };
603
+ var TaaCapsInsufficientError = class extends Error {
604
+ code = "taa-caps-insufficient";
605
+ expected = "the backend exposes the capabilities required by TAA";
606
+ hint = "select a backend with the required TAA capabilities or disable TAA on Camera";
607
+ detail;
608
+ constructor(required, available) {
609
+ super("TAA capabilities are insufficient");
610
+ this.name = "TaaCapsInsufficientError";
611
+ this.detail = { required: [...required], available: [...available] };
612
+ }
613
+ };
614
+ var EnvironmentGenerationFailedError = class extends Error {
615
+ code = "environment-generation-failed";
616
+ expected = "the selected environment generation completes its owner stage";
617
+ hint = "inspect the stage and sourceKey, then retry after correcting the environment";
618
+ detail;
619
+ constructor(sourceKey, stage) {
620
+ super(`environment generation failed during ${stage}`);
621
+ this.name = "EnvironmentGenerationFailedError";
622
+ this.detail = { sourceKey, stage };
623
+ }
624
+ };
625
+ var AtmosphereInvalidParameterError = class extends Error {
626
+ code = "atmosphere-invalid-parameter";
627
+ expected;
628
+ hint;
629
+ detail;
630
+ constructor(field, value, range) {
631
+ super(`Atmosphere.${field} is invalid`);
632
+ this.name = "AtmosphereInvalidParameterError";
633
+ this.detail = { field, value };
634
+ const rangeText = Number.isFinite(range.max) ? `[${range.min}, ${range.max}]` : `>= ${range.min}`;
635
+ this.expected = `Atmosphere.${field} must be finite and ${rangeText}`;
636
+ this.hint = `set Atmosphere.${field} to a finite value ${rangeText}`;
637
+ }
638
+ };
639
+ var DynamicResolutionInvalidParameterError = class extends Error {
640
+ code = "dynamic-resolution-invalid-parameter";
641
+ expected;
642
+ hint;
643
+ detail;
644
+ constructor(detail) {
645
+ super(`DynamicResolution.${detail.field} is invalid`);
646
+ this.name = "DynamicResolutionInvalidParameterError";
647
+ this.expected = `DynamicResolution.${detail.field} must be ${detail.expected}`;
648
+ this.hint = `set DynamicResolution.${detail.field} to a value that is ${detail.expected}`;
649
+ this.detail = detail;
650
+ }
651
+ };
652
+ var DynamicResolutionRequiresTaaError = class extends Error {
653
+ code = "dynamic-resolution-requires-taa";
654
+ expected = "DynamicResolution requires Camera.antialias to be 'taa'";
655
+ hint = "set Camera.antialias to 'taa' or remove DynamicResolution before retrying";
656
+ detail;
657
+ constructor(detail) {
658
+ super("DynamicResolution requires TAA");
659
+ this.name = "DynamicResolutionRequiresTaaError";
660
+ this.detail = detail;
661
+ }
662
+ };
663
+ var DynamicResolutionTimingUnavailableError = class extends Error {
664
+ code = "dynamic-resolution-timing-unavailable";
665
+ expected = "adaptive resolution receives a completed GPU timing sample";
666
+ hint = "use fixed minScale=maxScale or retry after timestamp support is available";
667
+ detail;
668
+ constructor(detail) {
669
+ super(`DynamicResolution timing is unavailable for generation ${detail.generation}`);
670
+ this.name = "DynamicResolutionTimingUnavailableError";
671
+ this.detail = detail;
672
+ }
673
+ };
674
+ var BarrelDistortionInvalidParameterError = class extends Error {
675
+ code = "barrel-distortion-invalid-parameter";
676
+ expected;
677
+ hint;
678
+ detail;
679
+ constructor(detail) {
680
+ super(`BarrelDistortion.${detail.field} is invalid`);
681
+ this.name = "BarrelDistortionInvalidParameterError";
682
+ this.expected = `BarrelDistortion.${detail.field} must be ${detail.expected}`;
683
+ this.hint = `set BarrelDistortion.${detail.field} to a value that is ${detail.expected}`;
684
+ this.detail = detail;
685
+ }
686
+ };
687
+ var OwnerStageFailedError = class extends Error {
688
+ code = "owner-stage-failed";
689
+ expected = "the owner completes its current frame stage";
690
+ hint = "inspect the owner and stage, keep the last-known-good frame, and retry";
691
+ detail;
692
+ constructor(owner, stage) {
693
+ super(`${owner} owner failed during ${stage}`);
694
+ this.name = "OwnerStageFailedError";
695
+ this.detail = { owner, stage };
696
+ }
697
+ };
698
+ var RENDERER_OPERATION_ERROR_POLICY = {
699
+ "world-lease-invalid": {
700
+ expected: "every render World is represented by a live lease owned by this Renderer",
701
+ hint: "attach the World to this Renderer and use the returned lease"
702
+ },
703
+ "frame-input-invalid": {
704
+ expected: "the frame input references attached leases and a valid immutable RenderProfile",
705
+ hint: "repair the frame input and retry draw or setProfile"
706
+ },
707
+ "scene-projection-failed": {
708
+ expected: "the attached World projects into the renderer-owned RenderScene",
709
+ hint: "inspect the structured cause, repair the World publication, and retry draw"
710
+ },
711
+ "asset-binding-failed": {
712
+ expected: "all frame assets resolve to valid renderer-owned bindings",
713
+ hint: "inspect the structured cause, rebuild or cold-cook the asset, and retry draw"
714
+ },
715
+ "feature-plan-failed": {
716
+ expected: "every installed RenderFeature produces a valid declarative plan",
717
+ hint: "inspect the feature cause, repair its plan, and retry draw"
718
+ },
719
+ "graph-build-failed": {
720
+ expected: "the Standard graph builds from the active profile and feature plans",
721
+ hint: "inspect the graph cause, repair the profile or plan, and retry"
722
+ },
723
+ "device-operation-failed": {
724
+ expected: "the active device generation completes the renderer-owned operation",
725
+ hint: "inspect renderer state and the structured cause, then retry or recover"
726
+ },
727
+ "surface-unavailable": {
728
+ expected: "the presentation surface accepts the requested lifecycle operation",
729
+ hint: "inspect renderer state, then restore the surface or create a new Renderer"
730
+ },
731
+ "renderer-state-invalid": {
732
+ expected: "the Renderer is in a state that accepts the requested operation",
733
+ hint: "inspect renderer state and choose retry, restoreSurface, recover, or stop"
734
+ },
735
+ "recovery-failed": {
736
+ expected: "one recovery attempt publishes a complete replacement device generation",
737
+ hint: "inspect the structured cause and retry recover after the host-selected delay"
738
+ },
739
+ "cleanup-failed": {
740
+ expected: "Renderer disposal completes every registered cleanup in reverse ownership order",
741
+ hint: "inspect the ordered cleanup causes; the Renderer remains disposed and must not be reused"
742
+ }
743
+ };
744
+ var RendererOperationError = class extends Error {
745
+ code;
746
+ expected;
747
+ hint;
748
+ detail;
749
+ constructor(code, detail) {
750
+ const policy = RENDERER_OPERATION_ERROR_POLICY[code];
751
+ super(`${code}: ${policy.expected}`);
752
+ this.name = "RendererOperationError";
753
+ this.code = code;
754
+ this.expected = policy.expected;
755
+ this.hint = policy.hint;
756
+ this.detail = detail;
757
+ }
758
+ };
759
+ var PointsLinesInvalidStyleError = class extends Error {
760
+ code = "points-lines-invalid-style";
761
+ expected;
762
+ hint;
763
+ detail;
764
+ constructor(detail) {
765
+ super(`invalid ${detail.component} style at ${detail.field}`);
766
+ this.name = "PointsLinesInvalidStyleError";
767
+ this.expected = detail.expected;
768
+ this.hint = `repair entity ${detail.entity} ${detail.component}.${detail.field} and retry admission`;
769
+ this.detail = detail;
770
+ }
771
+ };
772
+ var PointsLinesTopologyMismatchError = class extends Error {
773
+ code = "points-lines-topology-mismatch";
774
+ expected;
775
+ hint;
776
+ detail;
777
+ constructor(detail) {
778
+ super(`Points/Lines topology mismatch at submesh ${detail.submesh}`);
779
+ this.name = "PointsLinesTopologyMismatchError";
780
+ this.expected = `submesh ${detail.submesh} topology is ${detail.expected}`;
781
+ this.hint = `rebuild entity ${detail.entity} with ${detail.expected} geometry before retrying Points/Lines admission`;
782
+ this.detail = detail;
783
+ }
784
+ };
785
+ var PointsLinesStyleUnsupportedError = class extends Error {
786
+ code = "points-lines-style-unsupported";
787
+ expected;
788
+ hint;
789
+ detail;
790
+ constructor(detail) {
791
+ super(`unsupported Points/Lines ${detail.field} member ${detail.member}`);
792
+ this.name = "PointsLinesStyleUnsupportedError";
793
+ this.expected = `${detail.field} is one of ${detail.supported.join(", ")}`;
794
+ this.hint = `use a supported Points/Lines ${detail.field} member or wait for a later milestone`;
795
+ this.detail = detail;
796
+ }
797
+ };
798
+ var PointsLinesMaterialUnsupportedError = class extends Error {
799
+ code = "points-lines-material-unsupported";
800
+ expected = "one engine-owned unlit forward MaterialAsset pass";
801
+ hint;
802
+ detail;
803
+ constructor(detail) {
804
+ super(`Points/Lines material is unsupported on entity ${detail.entity}`);
805
+ this.name = "PointsLinesMaterialUnsupportedError";
806
+ this.hint = `use Materials.unlit without a shadow-caster pass for entity ${detail.entity}`;
807
+ this.detail = detail;
808
+ }
809
+ };
810
+ var PointsLinesBudgetExceededError = class extends Error {
811
+ code = "points-lines-budget-exceeded";
812
+ expected;
813
+ hint;
814
+ detail;
815
+ constructor(detail) {
816
+ super(`Points/Lines ${detail.unit} budget exceeded`);
817
+ this.name = "PointsLinesBudgetExceededError";
818
+ this.expected = `${detail.unit} <= ${detail.limit}`;
819
+ this.hint = `reduce Points/Lines ${detail.unit} or split the entity into bounded equivalent batches`;
820
+ this.detail = detail;
821
+ }
822
+ };
823
+ var PointsLinesPrepareFailedError = class extends Error {
824
+ code = "points-lines-prepare-failed";
825
+ expected = "the complete Points/Lines candidate validates before publication";
826
+ hint;
827
+ detail;
828
+ constructor(detail) {
829
+ super(`Points/Lines prepare failed at generation ${detail.generation}`);
830
+ this.name = "PointsLinesPrepareFailedError";
831
+ this.hint = detail.lastKnownGood ? "retain the last known good candidate, repair the producer, and retry prepare" : "repair the producer and retry prepare; the failed first candidate produces zero draw";
832
+ this.detail = detail;
833
+ }
834
+ };
835
+ var RenderTargetDescriptorInvalidError = class extends Error {
836
+ code = "render-target-descriptor-invalid";
837
+ expected;
838
+ hint;
839
+ detail;
840
+ constructor(detail) {
841
+ super(`render-target-descriptor-invalid: ${detail.field} does not satisfy ${detail.expected}`);
842
+ this.name = "RenderTargetDescriptorInvalidError";
843
+ this.expected = detail.expected;
844
+ this.hint = `set RenderTargetDescriptor.${detail.field} to the expected value, then retry create or resize`;
845
+ this.detail = detail;
846
+ }
847
+ };
848
+ var RenderTargetCapabilityMissingError = class extends Error {
849
+ code = "render-target-capability-missing";
850
+ expected;
851
+ hint;
852
+ detail;
853
+ constructor(detail) {
854
+ super(
855
+ `render-target-capability-missing: ${detail.capability} does not admit ${detail.requested}`
856
+ );
857
+ this.name = "RenderTargetCapabilityMissingError";
858
+ this.expected = `${detail.capability} admits ${detail.requested}`;
859
+ this.hint = `choose an admitted target descriptor or use a backend providing ${detail.capability}`;
860
+ this.detail = detail;
861
+ }
862
+ };
863
+ var RenderTargetStateInvalidError = class extends Error {
864
+ code = "render-target-state-invalid";
865
+ expected;
866
+ hint;
867
+ detail;
868
+ constructor(detail) {
869
+ super(`render-target-state-invalid: ${detail.operation} cannot use ${detail.reason}`);
870
+ this.name = "RenderTargetStateInvalidError";
871
+ this.expected = `target state permits ${detail.operation}`;
872
+ this.hint = "use the Renderer that created the target, then initialize, recover, or stop using the destroyed token";
873
+ this.detail = detail;
874
+ }
875
+ };
876
+ var RenderTargetOperationFailedError = class extends Error {
877
+ code = "render-target-operation-failed";
878
+ expected;
879
+ hint;
880
+ detail;
881
+ constructor(detail) {
882
+ super(`render-target-operation-failed: ${detail.operation} failed during ${detail.stage}`);
883
+ this.name = "RenderTargetOperationFailedError";
884
+ this.expected = `${detail.operation} completes ${detail.stage}`;
885
+ this.hint = "inspect detail.cause, then retry, recover the Renderer, or retain the last-known-good generation";
886
+ this.detail = detail;
887
+ }
888
+ };
889
+ var RenderIntentInvalidError = class extends Error {
890
+ code = "render-intent-invalid";
891
+ expected;
892
+ hint;
893
+ detail;
894
+ constructor(component, value) {
895
+ super(`render-intent-invalid: ${component}.updateIntent is not an admitted value`);
896
+ this.name = "RenderIntentInvalidError";
897
+ this.expected = `${component}.updateIntent is one of 0, 1, or 2`;
898
+ this.hint = `set ${component}.updateIntent to 0, 1, or 2`;
899
+ this.detail = { component, field: "updateIntent", value, allowed: [0, 1, 2] };
900
+ }
901
+ };
902
+ var VolumeOwnerConflictError = class extends Error {
903
+ code = "volume-owner-conflict";
904
+ expected = "at most eight local VolumetricFog owners per rendered World";
905
+ hint = "reduce simultaneously visible volume owners and retry extraction";
906
+ detail;
907
+ constructor(ownerCount) {
908
+ super(`volume-owner-conflict: received ${ownerCount} owners`);
909
+ this.name = "VolumeOwnerConflictError";
910
+ this.detail = { ownerCount };
911
+ }
912
+ };
913
+ var VolumeDensityShapeMismatchError = class extends Error {
914
+ code = "volume-density-shape-mismatch";
915
+ expected = "density is a linear 3D TextureAsset";
916
+ hint = "bind a verified linear texture with viewDimension 3d";
917
+ detail;
918
+ constructor(guid, viewDimension) {
919
+ super(`volume-density-shape-mismatch: ${viewDimension} density is not 3d`);
920
+ this.name = "VolumeDensityShapeMismatchError";
921
+ this.detail = { guid, viewDimension };
922
+ }
923
+ };
924
+ var VolumeInvalidBoundsError = class extends Error {
925
+ code = "volume-invalid-bounds";
926
+ expected = "bounds are finite and max is greater than min on every axis";
927
+ hint = "set finite non-degenerate volume bounds";
928
+ detail;
929
+ constructor(bounds) {
930
+ super("volume-invalid-bounds: bounds must be finite and non-degenerate");
931
+ this.name = "VolumeInvalidBoundsError";
932
+ this.detail = bounds;
933
+ }
934
+ };
935
+ var VolumeInvalidParametersError = class extends Error {
936
+ code = "volume-invalid-parameters";
937
+ expected = "volume parameters remain finite and inside their closed ranges";
938
+ hint = "repair extinction, albedo, emission, anisotropy, maxDistance, or sampling";
939
+ detail;
940
+ constructor(input) {
941
+ const invalidSampling = input.sampling !== void 0 && input.sampling !== "noise" && input.sampling !== "density";
942
+ const field = invalidSampling ? "sampling" : input.maxDistance !== void 0 && input.maxDistance <= 0 ? "maxDistance" : "parameters";
943
+ const value = invalidSampling ? input.sampling : field === "maxDistance" ? input.maxDistance : input.anisotropy;
944
+ super(`volume-invalid-parameters: ${field} is outside the authored range`);
945
+ this.name = "VolumeInvalidParametersError";
946
+ this.detail = { field, value };
947
+ }
948
+ };
949
+ var MOTION_BLUR_PARAMS_BYTE_SIZE = 32;
950
+ var DEFAULT_MOTION_BLUR_PARAMS = Object.freeze({
951
+ shutterAngle: 180,
952
+ maxRadiusPixels: 32,
953
+ sampleCount: 8,
954
+ targetFps: 60
955
+ });
956
+ var MotionBlurValidationError = class extends Error {
957
+ code = "motion-blur-invalid-params";
958
+ expected;
959
+ hint;
960
+ detail;
961
+ constructor(detail) {
962
+ const integer = detail.integer === true ? "integer " : "";
963
+ const expected = `${detail.field} ${integer}in [${detail.min}, ${detail.max}]`;
964
+ super(`motion-blur-invalid-params: ${expected}`);
965
+ this.name = "MotionBlurValidationError";
966
+ this.expected = expected;
967
+ this.hint = `set ${detail.field} to an ${integer}value in [${detail.min}, ${detail.max}]`;
968
+ this.detail = detail;
969
+ }
970
+ };
971
+ function validateField(field, value, min, max, integer = false) {
972
+ if (!Number.isFinite(value) || value < min || value > max || integer && !Number.isInteger(value)) {
973
+ return new MotionBlurValidationError({
974
+ field,
975
+ value,
976
+ min,
977
+ max,
978
+ ...integer ? { integer } : {}
979
+ });
980
+ }
981
+ return void 0;
982
+ }
983
+ function validateMotionBlurParams(input) {
984
+ const value = input ?? {};
985
+ const shutterAngle = value.shutterAngle ?? DEFAULT_MOTION_BLUR_PARAMS.shutterAngle;
986
+ const maxRadiusPixels = value.maxRadiusPixels ?? DEFAULT_MOTION_BLUR_PARAMS.maxRadiusPixels;
987
+ const sampleCount = value.sampleCount ?? DEFAULT_MOTION_BLUR_PARAMS.sampleCount;
988
+ const targetFps = value.targetFps ?? DEFAULT_MOTION_BLUR_PARAMS.targetFps;
989
+ const shutterError = validateField("shutterAngle", shutterAngle, 0, 360);
990
+ if (shutterError !== void 0) return err(shutterError);
991
+ const radiusError = validateField("maxRadiusPixels", maxRadiusPixels, 0, 64);
992
+ if (radiusError !== void 0) return err(radiusError);
993
+ const sampleError = validateField("sampleCount", sampleCount, 4, 16, true);
994
+ if (sampleError !== void 0) return err(sampleError);
995
+ const targetFpsError = validateField("targetFps", targetFps, 0, 240, true);
996
+ if (targetFpsError !== void 0) return err(targetFpsError);
997
+ return ok(Object.freeze({ shutterAngle, maxRadiusPixels, sampleCount, targetFps }));
998
+ }
999
+ function motionBlurTemporalDemand(params) {
1000
+ return params !== void 0 && params.shutterAngle > 0 && params.maxRadiusPixels > 0;
1001
+ }
1002
+ function effectiveMotionBlurSampleCount(sampleCount) {
1003
+ if (!Number.isFinite(sampleCount) || sampleCount < 4) return 0;
1004
+ if (sampleCount < 8) return 4;
1005
+ if (sampleCount < 16) return 8;
1006
+ return 16;
1007
+ }
1008
+ function isMotionBlurIntervalValid(frameDeltaSeconds) {
1009
+ return Number.isFinite(frameDeltaSeconds) && frameDeltaSeconds > 0 && frameDeltaSeconds <= 0.1;
1010
+ }
1011
+ function motionBlurExposureScale(frameDeltaSeconds, targetFps) {
1012
+ if (!isMotionBlurIntervalValid(frameDeltaSeconds)) return 0;
1013
+ if (!Number.isFinite(targetFps) || targetFps < 0 || targetFps > 240 || !Number.isInteger(targetFps)) {
1014
+ return 0;
1015
+ }
1016
+ if (targetFps === 0) return 1;
1017
+ return 1 / (targetFps * frameDeltaSeconds);
1018
+ }
1019
+ function motionBlurSampleDelta(sampleTimeSeconds, previousSampleTimeSeconds, fallbackDeltaSeconds) {
1020
+ if (sampleTimeSeconds !== void 0 && !Number.isFinite(sampleTimeSeconds) || previousSampleTimeSeconds !== void 0 && !Number.isFinite(previousSampleTimeSeconds)) {
1021
+ return Number.NaN;
1022
+ }
1023
+ if (Number.isFinite(sampleTimeSeconds) && Number.isFinite(previousSampleTimeSeconds)) {
1024
+ return sampleTimeSeconds - previousSampleTimeSeconds;
1025
+ }
1026
+ return fallbackDeltaSeconds;
1027
+ }
1028
+ function resolveMotionBlurParams(input) {
1029
+ if (input === void 0) return ok(void 0);
1030
+ return validateMotionBlurParams(input);
1031
+ }
1032
+ var DeviceResourceRef = class {
1033
+ kind;
1034
+ owner;
1035
+ generation;
1036
+ value;
1037
+ constructor(kind, owner, generation, value) {
1038
+ this.kind = kind;
1039
+ this.owner = owner;
1040
+ this.generation = generation;
1041
+ this.value = value;
1042
+ }
1043
+ isCurrent(scope) {
1044
+ return scope.accepts(this);
1045
+ }
1046
+ isStale(scope) {
1047
+ return !this.isCurrent(scope);
1048
+ }
1049
+ };
1050
+ function idempotentCleanup(cleanup) {
1051
+ let cleaned = false;
1052
+ return (value) => {
1053
+ if (cleaned) return;
1054
+ cleaned = true;
1055
+ return cleanup(value);
1056
+ };
1057
+ }
1058
+ var DeviceScope = class _DeviceScope {
1059
+ generation;
1060
+ owner;
1061
+ parent;
1062
+ lifecycleState = "active";
1063
+ resources = /* @__PURE__ */ new Map();
1064
+ children = [];
1065
+ constructor(generation, owner, parent) {
1066
+ this.generation = generation;
1067
+ this.owner = owner;
1068
+ this.parent = parent;
1069
+ parent?.children.push(this);
1070
+ }
1071
+ static create(generation, owner) {
1072
+ if (!Number.isSafeInteger(generation) || generation < 0) {
1073
+ throw new RangeError("DeviceScope generation must be a non-negative safe integer.");
1074
+ }
1075
+ if (owner.length === 0) throw new TypeError("DeviceScope owner must not be empty.");
1076
+ return new _DeviceScope(generation, owner);
1077
+ }
1078
+ get state() {
1079
+ return this.lifecycleState;
1080
+ }
1081
+ get childrenSnapshot() {
1082
+ return [...this.children];
1083
+ }
1084
+ /** Create a renderer-owned child scope without exposing a second device owner. */
1085
+ createChild(owner) {
1086
+ if (this.lifecycleState !== "active") {
1087
+ throw new Error("Cannot create a child DeviceScope from an inactive scope.");
1088
+ }
1089
+ if (owner.length === 0) throw new TypeError("DeviceScope child owner must not be empty.");
1090
+ return new _DeviceScope(this.generation, owner, this);
1091
+ }
1092
+ ref(kind, value) {
1093
+ const ref = new DeviceResourceRef(kind, this.owner, this.generation, value);
1094
+ this.resources.set(ref, { ref, cleanup: () => void 0 });
1095
+ return ref;
1096
+ }
1097
+ accepts(ref) {
1098
+ return this.lifecycleState === "active" && ref.owner === this.owner && ref.generation === this.generation;
1099
+ }
1100
+ isAlive() {
1101
+ return this.lifecycleState === "active";
1102
+ }
1103
+ resourceDelta() {
1104
+ return this.resources.size;
1105
+ }
1106
+ /** @internal */
1107
+ _adopt(kind, value, cleanup) {
1108
+ const ref = new DeviceResourceRef(kind, this.owner, this.generation, value);
1109
+ this.resources.set(ref, {
1110
+ ref,
1111
+ cleanup: idempotentCleanup(cleanup)
1112
+ });
1113
+ return ref;
1114
+ }
1115
+ /** @internal Remove ownership only after the resource's cleanup succeeded. */
1116
+ _release(ref) {
1117
+ this.resources.delete(ref);
1118
+ }
1119
+ /** @internal */
1120
+ _clearResources() {
1121
+ const resources = [...this.resources.values()];
1122
+ this.resources.clear();
1123
+ for (const resource of resources.reverse()) {
1124
+ try {
1125
+ const pending = resource.cleanup(resource.ref.value);
1126
+ if (pending instanceof Promise) void pending.catch(() => void 0);
1127
+ } catch {
1128
+ }
1129
+ }
1130
+ return resources;
1131
+ }
1132
+ /** Mark an active child as retiring without releasing in-flight resources. */
1133
+ beginRetire() {
1134
+ if (this.lifecycleState === "active") this.lifecycleState = "retiring";
1135
+ }
1136
+ clearChildren() {
1137
+ for (const child of [...this.children].reverse()) {
1138
+ child.retire();
1139
+ }
1140
+ }
1141
+ detachChild(child) {
1142
+ const index = this.children.indexOf(child);
1143
+ if (index >= 0) this.children.splice(index, 1);
1144
+ }
1145
+ retire() {
1146
+ if (this.lifecycleState !== "active" && this.lifecycleState !== "retiring") return;
1147
+ this.lifecycleState = "retiring";
1148
+ this.clearChildren();
1149
+ this._clearResources();
1150
+ this.lifecycleState = "retired";
1151
+ this.parent?.detachChild(this);
1152
+ }
1153
+ abandon() {
1154
+ if (this.lifecycleState !== "active") return;
1155
+ this.lifecycleState = "abandoned";
1156
+ this.clearChildren();
1157
+ this._clearResources();
1158
+ this.parent?.detachChild(this);
1159
+ }
1160
+ dispose() {
1161
+ if (this.lifecycleState === "disposed") return;
1162
+ this.lifecycleState = "disposed";
1163
+ this.clearChildren();
1164
+ this._clearResources();
1165
+ this.parent?.detachChild(this);
1166
+ }
1167
+ async replace(generation, resources) {
1168
+ const replacement = new _DeviceScope(generation, this.owner, this);
1169
+ const transaction = new LifecycleTransaction(replacement);
1170
+ for (const resource of resources) transaction.add(resource);
1171
+ const result = await transaction.commit();
1172
+ if (!result.ok) {
1173
+ replacement.abandon();
1174
+ return result;
1175
+ }
1176
+ if (!this.isAlive()) {
1177
+ replacement.dispose();
1178
+ return transaction.failure("dispose");
1179
+ }
1180
+ this.detachChild(replacement);
1181
+ this.retire();
1182
+ return ok(replacement);
1183
+ }
1184
+ /** @internal */
1185
+ _receipt() {
1186
+ return {
1187
+ owner: this.owner,
1188
+ generation: this.generation,
1189
+ resourceCount: this.resources.size
1190
+ };
1191
+ }
1192
+ };
1193
+ var LifecycleTransaction = class {
1194
+ constructor(scope, options = {}) {
1195
+ this.scope = scope;
1196
+ this.options = options;
1197
+ }
1198
+ scope;
1199
+ resources = [];
1200
+ options;
1201
+ committed = false;
1202
+ add(spec) {
1203
+ if (this.committed) throw new Error("LifecycleTransaction is already committed.");
1204
+ this.resources.push(spec);
1205
+ return this;
1206
+ }
1207
+ async commit() {
1208
+ if (this.committed) return this.failure("create");
1209
+ this.committed = true;
1210
+ const created = [];
1211
+ for (let index = 0; index < this.resources.length; index += 1) {
1212
+ const spec = this.resources[index];
1213
+ if (spec === void 0) continue;
1214
+ try {
1215
+ if (this.options.failureAt === index + 1) {
1216
+ throw new Error(`injected lifecycle failure at ${index + 1}`);
1217
+ }
1218
+ const value = await spec.create();
1219
+ if (!this.scope.isAlive()) {
1220
+ await this.cleanupOne(value, created, idempotentCleanup(spec.cleanup));
1221
+ return this.failure("dispose");
1222
+ }
1223
+ created.push({ spec, value, cleanup: idempotentCleanup(spec.cleanup) });
1224
+ } catch (cause) {
1225
+ const cleanupFailures = await this.cleanupCreated(created);
1226
+ return this.failure("create", spec.kind, cleanupFailures, cause);
1227
+ }
1228
+ }
1229
+ if (!this.scope.isAlive()) {
1230
+ const cleanupFailures = await this.cleanupCreated(created);
1231
+ return this.failure("dispose", this.resources.at(-1)?.kind ?? "listener", cleanupFailures);
1232
+ }
1233
+ for (const item of created) this.scope._adopt(item.spec.kind, item.value, item.spec.cleanup);
1234
+ return ok(this.scope);
1235
+ }
1236
+ failure(operation, resourceKind = this.resources.at(-1)?.kind ?? "listener", cleanupFailures = [], cause = void 0) {
1237
+ return err({
1238
+ primary: new LifecycleConstructionError({
1239
+ owner: this.scope.owner,
1240
+ generation: this.scope.generation,
1241
+ operation,
1242
+ resourceKind,
1243
+ cause,
1244
+ cleanupFailures,
1245
+ receipt: this.scope._receipt()
1246
+ }),
1247
+ cleanupFailures,
1248
+ receipt: this.scope._receipt()
1249
+ });
1250
+ }
1251
+ async cleanupCreated(created) {
1252
+ const failures = [];
1253
+ for (let index = created.length - 1; index >= 0; index -= 1) {
1254
+ const item = created[index];
1255
+ if (item === void 0) continue;
1256
+ try {
1257
+ await item.cleanup(item.value);
1258
+ } catch (cause) {
1259
+ failures.push({ resourceKind: item.spec.kind, cause });
1260
+ }
1261
+ }
1262
+ return failures;
1263
+ }
1264
+ async cleanupOne(value, created, cleanup) {
1265
+ await this.cleanupCreated(created);
1266
+ try {
1267
+ await cleanup(value);
1268
+ } catch {
1269
+ }
1270
+ }
1271
+ };
1272
+
1273
+ // src/gpu-texture-usage.ts
1274
+ var GPU_TEXTURE_USAGE_COPY_SRC = 1;
1275
+ var GPU_TEXTURE_USAGE_COPY_DST = 2;
1276
+ var GPU_TEXTURE_USAGE_TEXTURE_BINDING = 4;
1277
+ var GPU_TEXTURE_USAGE_STORAGE_BINDING = 8;
1278
+ var GPU_TEXTURE_USAGE_RENDER_ATTACHMENT = 16;
1279
+ var GPU_TEXTURE_USAGE_RENDER_ATTACHMENT_AND_TEXTURE_BINDING = GPU_TEXTURE_USAGE_RENDER_ATTACHMENT | GPU_TEXTURE_USAGE_TEXTURE_BINDING;
1280
+
1281
+ // src/gpu-usage.ts
1282
+ var GPU_BUFFER_USAGE_VERTEX = 32;
1283
+ var GPU_BUFFER_USAGE_INDEX = 16;
1284
+ var GPU_BUFFER_USAGE_COPY_DST = 8;
1285
+ var GPU_BUFFER_USAGE_COPY_SRC = 4;
1286
+ var GPU_BUFFER_USAGE_UNIFORM = 64;
1287
+ var GPU_BUFFER_USAGE_STORAGE = 128;
1288
+ var GPU_BUFFER_USAGE_INDIRECT = 256;
1289
+ var GPU_BUFFER_USAGE_MAP_READ = 1;
1290
+ var GPU_BUFFER_USAGE_QUERY_RESOLVE = 512;
1291
+
1292
+ // src/prepare/extended-lighting/resources.ts
1293
+ var EXTENDED_LIGHTING_TOPOLOGY = "extendedLighting";
1294
+ var IES_SLICE_CAPACITY = 32;
1295
+ var COOKIE_SLICE_CAPACITY = 32;
1296
+ var IES_SLICE_WIDTH = 256;
1297
+ var IES_SLICE_HEIGHT = 128;
1298
+ var COOKIE_SLICE_SIZE = 256;
1299
+ var COOKIE_MATRIX_BYTES = 32 * 16 * Float32Array.BYTES_PER_ELEMENT;
1300
+ var EXTENDED_LIGHTING_REQUIRED_SAMPLED_TEXTURES = 21;
1301
+ function extendedLightingSampledTextureCapacityAvailable(maxSampledTexturesPerShaderStage) {
1302
+ return maxSampledTexturesPerShaderStage !== void 0 && maxSampledTexturesPerShaderStage >= EXTENDED_LIGHTING_REQUIRED_SAMPLED_TEXTURES;
1303
+ }
1304
+ function deriveExtendedLightingCapability(device) {
1305
+ const maxSampledTextures = device.limits.maxSampledTexturesPerShaderStage;
1306
+ if (!extendedLightingSampledTextureCapacityAvailable(maxSampledTextures)) {
1307
+ return {
1308
+ admitted: false,
1309
+ topology: EXTENDED_LIGHTING_TOPOLOGY,
1310
+ reason: `maxSampledTexturesPerShaderStage ${maxSampledTextures ?? 0} < ${EXTENDED_LIGHTING_REQUIRED_SAMPLED_TEXTURES}`
1311
+ };
1312
+ }
1313
+ const maxLayers = device.limits.maxTextureArrayLayers ?? 0;
1314
+ const maxUniformBuffers = device.limits.maxUniformBuffersPerShaderStage ?? 0;
1315
+ if (maxLayers < IES_SLICE_CAPACITY) {
1316
+ return {
1317
+ admitted: false,
1318
+ topology: EXTENDED_LIGHTING_TOPOLOGY,
1319
+ reason: `maxTextureArrayLayers ${maxLayers} < ${IES_SLICE_CAPACITY}`
1320
+ };
1321
+ }
1322
+ if (maxUniformBuffers < 1) {
1323
+ return {
1324
+ admitted: false,
1325
+ topology: EXTENDED_LIGHTING_TOPOLOGY,
1326
+ reason: `maxUniformBuffersPerShaderStage ${maxUniformBuffers} < 1`
1327
+ };
1328
+ }
1329
+ if (!device.caps.storageBuffer || !device.caps.rgba16floatRenderable || !device.caps.samplerAliasing) {
1330
+ return {
1331
+ admitted: false,
1332
+ topology: EXTENDED_LIGHTING_TOPOLOGY,
1333
+ reason: "required storage-buffer, rgba16float, or sampler capability is unavailable"
1334
+ };
1335
+ }
1336
+ return { admitted: true, topology: EXTENDED_LIGHTING_TOPOLOGY, reason: void 0 };
1337
+ }
1338
+ var SHADOW_ATLAS_DEFAULT_FACE_SIZE = 512;
1339
+ var SHADOW_ATLAS_DEFAULT_LAYERS = 4;
1340
+ var ShadowAtlas = class {
1341
+ /** Backing cube_array depth texture. `null` until `ensure()` has run. */
1342
+ texture = null;
1343
+ /**
1344
+ * Whole-atlas cube_array sampling view used by URP shaders that bind the
1345
+ * atlas at `@group(0) @binding(5)`. `null` until `ensure()` has run.
1346
+ */
1347
+ cubeArrayView = null;
1348
+ /** Comparison sampler for `texture_depth_cube_array`. */
1349
+ compareSampler = null;
1350
+ /** Per-face 2D depth view cache, keyed by `layer * 6 + face`. */
1351
+ faceViews = /* @__PURE__ */ new Map();
1352
+ /** Per-face label cache (debug aid). Reused on re-creation. */
1353
+ device;
1354
+ /** Per-face square size in pixels. */
1355
+ faceSize;
1356
+ /** Cube layer count. */
1357
+ layers;
1358
+ constructor(device, options = {}) {
1359
+ this.device = device;
1360
+ this.faceSize = options.faceSize ?? SHADOW_ATLAS_DEFAULT_FACE_SIZE;
1361
+ this.layers = options.layers ?? SHADOW_ATLAS_DEFAULT_LAYERS;
1362
+ }
1363
+ /**
1364
+ * Returns `true` once the atlas texture is allocated. Used by the extract /
1365
+ * record path to gate "no PointLightShadow → no allocation" (AC-09) — the
1366
+ * caller calls {@link ensure} on a frame that has at least one snapshot;
1367
+ * before that, `isAllocated()` stays `false` and tests can assert no GPU
1368
+ * resources were created.
1369
+ */
1370
+ isAllocated() {
1371
+ return this.texture !== null;
1372
+ }
1373
+ /**
1374
+ * Lazy-allocate the atlas texture + cube_array sampling view + comparison
1375
+ * sampler. Idempotent: subsequent calls are zero-cost no-ops once the
1376
+ * resources exist.
1377
+ *
1378
+ * Throws (via the RHI error registry) on allocation failure. This is the
1379
+ * only path that touches the GPU — keeping it inside one method makes the
1380
+ * "zero-shadow scene = zero allocation" gate easy to enforce: the renderer
1381
+ * never calls this method on a frame with no PointLightShadow entities.
1382
+ */
1383
+ ensure() {
1384
+ if (this.texture !== null) return;
1385
+ const usage = GPU_TEXTURE_USAGE_RENDER_ATTACHMENT_AND_TEXTURE_BINDING;
1386
+ const texDesc = cubeArrayDepthDescriptor(this.faceSize, this.layers, usage);
1387
+ const texRes = this.device.createTexture(texDesc);
1388
+ if (!texRes.ok) throw texRes.error;
1389
+ this.texture = texRes.value;
1390
+ const viewRes = this.device.createTextureView(this.texture, {
1391
+ label: "shadow-atlas-cube-array-view",
1392
+ dimension: "cube-array",
1393
+ aspect: "depth-only",
1394
+ baseArrayLayer: 0,
1395
+ arrayLayerCount: 6 * this.layers,
1396
+ baseMipLevel: 0,
1397
+ mipLevelCount: 1
1398
+ });
1399
+ if (!viewRes.ok) {
1400
+ this.device.destroyTexture(this.texture);
1401
+ this.texture = null;
1402
+ throw viewRes.error;
1403
+ }
1404
+ this.cubeArrayView = viewRes.value;
1405
+ const sampRes = this.device.createSampler(comparisonSamplerDescriptor());
1406
+ if (!sampRes.ok) {
1407
+ this.device.destroyTexture(this.texture);
1408
+ this.texture = null;
1409
+ this.cubeArrayView = null;
1410
+ throw sampRes.error;
1411
+ }
1412
+ this.compareSampler = sampRes.value;
1413
+ }
1414
+ /**
1415
+ * Whole-atlas cube_array sampling view (`texture_depth_cube_array`). Returns
1416
+ * `null` if the atlas is not yet allocated; the caller should gate on a
1417
+ * non-null pointShadow array before calling {@link ensure} + this getter.
1418
+ */
1419
+ getAtlasView() {
1420
+ return this.cubeArrayView;
1421
+ }
1422
+ /**
1423
+ * Comparison sampler (`compare: 'less'`) for cube_array depth sampling.
1424
+ * Returns `null` if the atlas is not yet allocated.
1425
+ */
1426
+ getComparisonSampler() {
1427
+ return this.compareSampler;
1428
+ }
1429
+ /**
1430
+ * Backing texture handle. Returns `null` if the atlas is not yet allocated.
1431
+ */
1432
+ getTexture() {
1433
+ return this.texture;
1434
+ }
1435
+ /**
1436
+ * Lazy 2D depth view selecting `(layer, face)` (the caller passes
1437
+ * `shadowAtlasLayer` from the snapshot and a face index 0..5). Used as the
1438
+ * depth attachment of the shadow-caster render pass for one cube face.
1439
+ *
1440
+ * Caches per `(layer, face)` so the per-frame shadow loop pays zero
1441
+ * `createTextureView` cost after the first allocation. Cache is cleared on
1442
+ * {@link dispose}.
1443
+ *
1444
+ * @throws PointShadowAtlasUninitializedError if the atlas is not yet
1445
+ * allocated (caller must call {@link ensure} first).
1446
+ * @throws PointShadowAtlasBoundsViolationError if `layer` or `face` is out
1447
+ * of range.
1448
+ * @throws RhiError if the underlying `createTextureView` fails.
1449
+ */
1450
+ faceView(layer, face) {
1451
+ if (this.texture === null) {
1452
+ throw new PointShadowAtlasUninitializedError();
1453
+ }
1454
+ if (layer < 0 || layer >= this.layers) {
1455
+ throw new PointShadowAtlasBoundsViolationError("layer", layer, this.layers);
1456
+ }
1457
+ if (face < 0 || face >= 6) {
1458
+ throw new PointShadowAtlasBoundsViolationError("face", face, 6);
1459
+ }
1460
+ const key = layer * 6 + face;
1461
+ const cached = this.faceViews.get(key);
1462
+ if (cached !== void 0) return cached;
1463
+ const desc = cubeArrayDepthFaceView(layer, face);
1464
+ const r = this.device.createTextureView(this.texture, desc);
1465
+ if (!r.ok) throw r.error;
1466
+ this.faceViews.set(key, r.value);
1467
+ return r.value;
1468
+ }
1469
+ /**
1470
+ * Release the GPU resources and clear the per-face view cache. Idempotent;
1471
+ * subsequent calls are zero-cost. After dispose, `isAllocated()` returns
1472
+ * `false` and the next `ensure()` re-allocates from scratch.
1473
+ */
1474
+ dispose() {
1475
+ this.faceViews.clear();
1476
+ if (this.texture !== null) {
1477
+ this.device.destroyTexture(this.texture);
1478
+ this.texture = null;
1479
+ }
1480
+ this.cubeArrayView = null;
1481
+ this.compareSampler = null;
1482
+ }
1483
+ };
1484
+ function worldEntityKey(worldId, entityKey) {
1485
+ return worldId * 4294967296 + entityKey;
1486
+ }
1487
+ function instanceCollectionCacheKey(worldId, instance) {
1488
+ return -(4294967296 + worldEntityKey(worldId, instance.collectionId ?? instance.cacheKey));
1489
+ }
1490
+ var ZERO_CAMERA_CLEAR_FALLBACK = [0, 0, 0, 1];
1491
+ var textureIdentities = /* @__PURE__ */ new WeakMap();
1492
+ var nextTextureIdentity = 1;
1493
+ var opaqueResourceIdentities = /* @__PURE__ */ new WeakMap();
1494
+ var nextOpaqueResourceIdentity = 1;
1495
+ function getOpaqueResourceIdentity(resource) {
1496
+ const existing = opaqueResourceIdentities.get(resource);
1497
+ if (existing !== void 0) return existing;
1498
+ const identity = nextOpaqueResourceIdentity++;
1499
+ opaqueResourceIdentities.set(resource, identity);
1500
+ return identity;
1501
+ }
1502
+ function getTextureIdentity(texture) {
1503
+ const object = texture;
1504
+ const existing = textureIdentities.get(object);
1505
+ if (existing !== void 0) return existing;
1506
+ const identity = nextTextureIdentity++;
1507
+ textureIdentities.set(object, identity);
1508
+ return identity;
1509
+ }
1510
+ function validateGraphTargetCaptureReadback(input) {
1511
+ const { bytes, expectedByteLength, sentinel, allowZero = false } = input;
1512
+ if (bytes.byteLength !== expectedByteLength)
1513
+ return { ok: false, code: "capture-readback-length" };
1514
+ if (sentinel?.every((value, index2) => bytes[index2] === value)) {
1515
+ return { ok: false, code: "capture-readback-untouched-sentinel" };
1516
+ }
1517
+ if (!allowZero && bytes.every((value) => value === 0)) {
1518
+ return { ok: false, code: "capture-readback-empty" };
1519
+ }
1520
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1521
+ let index = 0;
1522
+ for (; index + 3 < bytes.byteLength; index += 4) {
1523
+ const word = view.getUint32(index, true);
1524
+ if ((word & 31744) === 31744 || (word & 2080374784) === 2080374784)
1525
+ return { ok: false, code: "capture-readback-non-finite" };
1526
+ }
1527
+ if (index + 1 < bytes.byteLength && (view.getUint16(index, true) & 31744) === 31744)
1528
+ return { ok: false, code: "capture-readback-non-finite" };
1529
+ return { ok: true };
1530
+ }
1531
+ function makeZeroCameraFallbackSnapshot() {
1532
+ const identityWorld = new Float32Array(16);
1533
+ identityWorld[0] = 1;
1534
+ identityWorld[5] = 1;
1535
+ identityWorld[10] = 1;
1536
+ identityWorld[15] = 1;
1537
+ return {
1538
+ position: vec3.create(0, 0, 0),
1539
+ world: identityWorld,
1540
+ fov: Math.PI / 4,
1541
+ aspect: 1,
1542
+ near: 0.1,
1543
+ far: 100,
1544
+ // feat-20260613 M6 / w20: synthetic camera defaults to perspective so
1545
+ // the CSM extract path stays consistent with the previously-implicit
1546
+ // perspective shape (unchanged behavior; explicit field).
1547
+ projection: "perspective",
1548
+ orthoLeft: -1,
1549
+ orthoRight: 1,
1550
+ orthoBottom: -1,
1551
+ orthoTop: 1,
1552
+ tonemap: "none",
1553
+ exposure: 1,
1554
+ whitePoint: 4,
1555
+ antialias: "none",
1556
+ bloom: "off",
1557
+ bloomThreshold: 1,
1558
+ bloomIntensity: 1,
1559
+ bloomSoftKnee: 0.5,
1560
+ bloomScatter: 0.7,
1561
+ clearColor: ZERO_CAMERA_CLEAR_FALLBACK
1562
+ };
1563
+ }
1564
+
1565
+ // src/errors/gpu-driven.ts
1566
+ var ERROR_POLICY2 = {
1567
+ "missing-material-receipt": {
1568
+ expected: "a producer-owned material program receipt is present",
1569
+ hint: "cook and load the selected material program artifact, then retry preparation",
1570
+ recovery: "rebuild-producer"
1571
+ },
1572
+ "material-abi-not-executable": {
1573
+ expected: "the published material ABI fits the GPU Scene submission layout",
1574
+ hint: "recook the material with a scene-index ABI supported by the GPU-driven owner or keep it on its authored lane",
1575
+ recovery: "route-cpu-lane"
1576
+ },
1577
+ "missing-uv": {
1578
+ expected: "the geometry exposes every UV set named by the material receipt",
1579
+ hint: "repair the geometry UV semantic or route the draw to the CPU semantic lane",
1580
+ recovery: "route-cpu-lane"
1581
+ },
1582
+ "reflection-mismatch": {
1583
+ expected: "the loaded reflection receipt matches the artifact layout identity",
1584
+ hint: "rebuild the material artifact and reflection from one source, then retry",
1585
+ recovery: "rebuild-producer"
1586
+ },
1587
+ "vertex-input-mismatch": {
1588
+ expected: "geometry vertex semantics match the material reflection receipt",
1589
+ hint: "repair the geometry vertex semantic layout or route the draw to the CPU lane",
1590
+ recovery: "route-cpu-lane"
1591
+ },
1592
+ "alpha-mask-mismatch": {
1593
+ expected: "the Alpha Mask cutoff is present in the material receipt",
1594
+ hint: "declare the pass coverage cutoff in the material schema and recook it",
1595
+ recovery: "rebuild-producer"
1596
+ },
1597
+ "resource-not-ready": {
1598
+ expected: "all material resource slots have resolved handles",
1599
+ hint: "resolve the declared texture and sampler resources before recording",
1600
+ recovery: "retry-same-draw"
1601
+ },
1602
+ "stale-generation": {
1603
+ expected: "receipt and prepared inputs belong to the requested generation",
1604
+ hint: "discard stale GPU facts, rebuild the producer receipt, and retry the same draw",
1605
+ recovery: "rebuild-generation"
1606
+ },
1607
+ "skin-receipt-mismatch": {
1608
+ expected: "skinned geometry has a current palette address receipt",
1609
+ hint: "rebuild the Skin palette receipt for this generation before recording",
1610
+ recovery: "rebuild-producer"
1611
+ },
1612
+ "shadow-ownership": {
1613
+ expected: "every declared ShadowCaster pass has one GPU-compatible draw-item owner",
1614
+ hint: "repair the ShadowCaster producer membership or keep the residual on its explicit CPU lane",
1615
+ recovery: "route-cpu-lane"
1616
+ }
1617
+ };
1618
+ var GpuDrivenPreparationError = class extends Error {
1619
+ code;
1620
+ expected;
1621
+ hint;
1622
+ detail;
1623
+ constructor(code, detail) {
1624
+ const policy = ERROR_POLICY2[code];
1625
+ super(`[GpuDrivenPreparationError ${code}] ${policy.expected}`);
1626
+ this.name = "GpuDrivenPreparationError";
1627
+ this.code = code;
1628
+ this.expected = policy.expected;
1629
+ this.hint = policy.hint;
1630
+ this.detail = Object.freeze({
1631
+ ...detail,
1632
+ recovery: detail.recovery ?? policy.recovery
1633
+ });
1634
+ }
1635
+ };
1636
+ var MATRIX_STRIDE = 16;
1637
+ var InstanceTransformsError = class extends Error {
1638
+ constructor(detail) {
1639
+ super("Instances.transforms must contain complete finite matrices");
1640
+ this.detail = detail;
1641
+ this.name = "InstanceTransformsError";
1642
+ }
1643
+ detail;
1644
+ code = "instance-transforms-invalid";
1645
+ expected = "finite column-major mat4 values, with transforms.length a multiple of 16";
1646
+ hint = "repair Instances.transforms in the World or source SceneAsset and retry";
1647
+ };
1648
+ function validateInstanceTransforms(transforms) {
1649
+ if (transforms.length % MATRIX_STRIDE !== 0)
1650
+ return new InstanceTransformsStrideMismatchError(transforms.length);
1651
+ for (let index = 0; index < transforms.length; index++) {
1652
+ if (!Number.isFinite(transforms[index]))
1653
+ return new InstanceTransformsError({
1654
+ actualLength: transforms.length,
1655
+ nonFiniteIndex: index
1656
+ });
1657
+ }
1658
+ return void 0;
1659
+ }
1660
+ function instanceUploadRangesForResident(activeIsNew, dirtyRanges, fullRange) {
1661
+ return activeIsNew ? [fullRange] : dirtyRanges;
1662
+ }
1663
+ var InstanceProjectionStore = class {
1664
+ nextId = 1;
1665
+ nextGeneration = 1;
1666
+ identities = /* @__PURE__ */ new WeakMap();
1667
+ records = /* @__PURE__ */ new Map();
1668
+ residency = /* @__PURE__ */ new Map();
1669
+ project(world, entity, transforms) {
1670
+ const collectionId = this.identities.get(world)?.get(entity) ?? this.nextId++;
1671
+ const previous = this.records.get(collectionId);
1672
+ if (previous !== void 0 && previous.transforms.length === transforms.length && previous.transforms.every((value, index) => Object.is(value, transforms[index])))
1673
+ return previous;
1674
+ const count = transforms.length / MATRIX_STRIDE;
1675
+ const generations = previous?.count === count ? previous.generations : Uint32Array.from({ length: count }, () => this.nextGeneration++);
1676
+ const record = {
1677
+ collectionId,
1678
+ world,
1679
+ entity,
1680
+ transforms: new Float32Array(transforms),
1681
+ generations,
1682
+ count,
1683
+ revision: (previous?.revision ?? 0) + 1
1684
+ };
1685
+ return record;
1686
+ }
1687
+ /** Called only after the owning RenderScene accepts its prepared changes. */
1688
+ accept(world, entity, snapshot) {
1689
+ const { collectionId, revision, transforms, generations } = snapshot;
1690
+ if (collectionId === void 0 || revision === void 0 || generations === void 0) return;
1691
+ let entities = this.identities.get(world);
1692
+ if (entities === void 0) {
1693
+ entities = /* @__PURE__ */ new Map();
1694
+ this.identities.set(world, entities);
1695
+ }
1696
+ entities.set(entity, collectionId);
1697
+ this.records.set(collectionId, {
1698
+ collectionId,
1699
+ revision,
1700
+ transforms,
1701
+ generations,
1702
+ count: transforms.length / MATRIX_STRIDE,
1703
+ world,
1704
+ entity
1705
+ });
1706
+ }
1707
+ release(world, entity) {
1708
+ const entities = this.identities.get(world);
1709
+ const id = entities?.get(entity);
1710
+ if (id === void 0) return;
1711
+ entities?.delete(entity);
1712
+ this.records.delete(id);
1713
+ this.residency.delete(id);
1714
+ }
1715
+ retain(ids) {
1716
+ for (const record of this.records.values()) {
1717
+ if (!ids.has(record.collectionId)) this.release(record.world, record.entity);
1718
+ }
1719
+ }
1720
+ dispose() {
1721
+ this.records.clear();
1722
+ this.residency.clear();
1723
+ this.identities = /* @__PURE__ */ new WeakMap();
1724
+ }
1725
+ _resetResidency() {
1726
+ this.residency.clear();
1727
+ }
1728
+ _reportResidency(input) {
1729
+ if (!this.records.has(input.collectionId)) return;
1730
+ const previous = this.residency.get(input.collectionId);
1731
+ const sameFrame = previous?.frameNumber === input.frameNumber && previous.error === void 0;
1732
+ const ranges = [...sameFrame ? previous.uploadRanges : [], ...input.uploadRanges].map((range) => ({ ...range })).sort((a, b) => a.start - b.start);
1733
+ const uploadRanges = [];
1734
+ for (const range of ranges) {
1735
+ const last = uploadRanges.at(-1);
1736
+ if (last !== void 0 && range.start <= last.end) last.end = Math.max(last.end, range.end);
1737
+ else uploadRanges.push(range);
1738
+ }
1739
+ this.residency.set(input.collectionId, {
1740
+ ...input,
1741
+ uploadRanges,
1742
+ uploadedBytes: input.uploadedBytes + (sameFrame ? previous.uploadedBytes : 0),
1743
+ error: void 0
1744
+ });
1745
+ }
1746
+ _reportFailure(input) {
1747
+ if (!this.records.has(input.collectionId)) return;
1748
+ this.residency.set(input.collectionId, {
1749
+ frameNumber: -1,
1750
+ residentGeneration: void 0,
1751
+ lane: "unavailable",
1752
+ uploadRanges: [],
1753
+ uploadedBytes: 0,
1754
+ requestedBytes: input.facts.requestedBytes,
1755
+ supportedBytes: input.facts.supportedBytes,
1756
+ backend: input.facts.backend,
1757
+ error: {
1758
+ code: input.code,
1759
+ expected: input.expected,
1760
+ hint: input.hint,
1761
+ detail: { ...input.facts }
1762
+ }
1763
+ });
1764
+ }
1765
+ _inspections(frameNumber) {
1766
+ return [...this.records.values()].map((record) => {
1767
+ const resident = this.residency.get(record.collectionId);
1768
+ const current = resident?.frameNumber === frameNumber;
1769
+ return {
1770
+ collectionId: record.collectionId,
1771
+ count: record.count,
1772
+ revision: record.revision,
1773
+ residentGeneration: resident?.residentGeneration,
1774
+ lane: resident?.lane ?? "unresident",
1775
+ uploadRanges: current ? resident.uploadRanges.map((range) => ({ ...range })) : [],
1776
+ uploadedBytes: current ? resident.uploadedBytes : 0,
1777
+ requestedBytes: resident?.requestedBytes ?? record.transforms.byteLength,
1778
+ supportedBytes: resident?.supportedBytes,
1779
+ backend: resident?.backend ?? "unknown",
1780
+ owner: "renderer.instances",
1781
+ error: resident?.error
1782
+ };
1783
+ });
1784
+ }
1785
+ };
1786
+
1787
+ // src/scene/visibility/budget.ts
1788
+ var DEFAULT_CONFIGURED_QUERY_BUDGET = 2048;
1789
+ var MAX_QUERY_BUDGET = 4096;
1790
+ var VISIBILITY_CANDIDATE_COUNT = 1e5;
1791
+ var VISIBILITY_OCCLUDED_COUNT = 9e4;
1792
+ function createVisibilityBudget(configuredQueryBudget = DEFAULT_CONFIGURED_QUERY_BUDGET) {
1793
+ if (!Number.isSafeInteger(configuredQueryBudget) || configuredQueryBudget <= 0) {
1794
+ throw new RangeError("configuredQueryBudget must be a positive safe integer");
1795
+ }
1796
+ const effectiveQueryBudget = Math.min(configuredQueryBudget, MAX_QUERY_BUDGET);
1797
+ const oneSweepCandidates = oneSweep(VISIBILITY_CANDIDATE_COUNT, effectiveQueryBudget);
1798
+ const oneSweepOccluded = oneSweep(VISIBILITY_OCCLUDED_COUNT, effectiveQueryBudget);
1799
+ const retestSubmits = Math.max(6, oneSweepOccluded);
1800
+ return Object.freeze({
1801
+ configuredQueryBudget,
1802
+ effectiveQueryBudget,
1803
+ oneSweepCandidates,
1804
+ oneSweepOccluded,
1805
+ settleSubmits: 2 * oneSweepCandidates,
1806
+ retestSubmits,
1807
+ expirySubmits: Math.max(8, retestSubmits + oneSweepOccluded)
1808
+ });
1809
+ }
1810
+ function oneSweep(candidateCount, effectiveQueryBudget) {
1811
+ return Math.ceil(candidateCount / effectiveQueryBudget);
1812
+ }
1813
+
1814
+ // src/render-contract.ts
1815
+ var STANDARD_OUTPUT_TRANSFORM_FEATURE_ID = "forgeax::standard::output-transform";
1816
+ var FXAA_POST_PROCESS_ID = "forgeax::post::fxaa";
1817
+ var RENDER_GRAPH_EXECUTION_PHASE_CATALOG = [
1818
+ "record/graph-execute/point-shadow",
1819
+ "record/graph-execute/cluster-binner-upload",
1820
+ "record/graph-execute/g-buffer",
1821
+ "record/graph-execute/g-buffer/geometry-loop",
1822
+ "record/graph-execute/g-buffer/material-bind-groups",
1823
+ "record/graph-execute/g-buffer/pipeline-selection",
1824
+ "record/graph-execute/g-buffer/draw-submit",
1825
+ "record/graph-execute/ssao-calc",
1826
+ "record/graph-execute/ssao-blur",
1827
+ "record/graph-execute/lighting",
1828
+ "record/graph-execute/forward",
1829
+ "record/graph-execute/forward/geometry-loop",
1830
+ "record/graph-execute/forward/material-bind-groups",
1831
+ "record/graph-execute/forward/pipeline-selection",
1832
+ "record/graph-execute/forward/draw-submit",
1833
+ "record/graph-execute/output-transform",
1834
+ "record/graph-execute/present",
1835
+ "record/graph-execute/debug-overlay",
1836
+ "record/graph-execute/shadow",
1837
+ "record/graph-execute/spot-shadow",
1838
+ "record/graph-execute/skybox",
1839
+ "record/graph-execute/main",
1840
+ "record/graph-execute/fxaa",
1841
+ "record/graph-execute/bloom-downsample",
1842
+ "record/graph-execute/bloom-upsample",
1843
+ "record/graph-execute/bloom-composite",
1844
+ "record/graph-execute/ssr-hiz",
1845
+ "record/graph-execute/ssr-trace",
1846
+ "record/graph-execute/ssr-temporal",
1847
+ "record/graph-execute/ssr-reflection-mip",
1848
+ "record/graph-execute/ssr-compose",
1849
+ "record/graph-execute/other"
1850
+ ];
1851
+ var RENDER_HDRP_BINNER_PHASE_CATALOG = [
1852
+ "record/scene-state/hdrp-cluster/binner/light-bounds-and-occupancy",
1853
+ "record/scene-state/hdrp-cluster/binner/light-bounds-and-occupancy/light-aabb",
1854
+ "record/scene-state/hdrp-cluster/binner/light-bounds-and-occupancy/cluster-occupancy",
1855
+ "record/scene-state/hdrp-cluster/binner/cluster-reserve",
1856
+ "record/scene-state/hdrp-cluster/binner/input-preparation",
1857
+ "record/scene-state/hdrp-cluster/binner/bin-core",
1858
+ "record/scene-state/hdrp-cluster/binner/light-index-write",
1859
+ "record/scene-state/hdrp-cluster/binner/light-index-write/bounds-read",
1860
+ "record/scene-state/hdrp-cluster/binner/light-index-write/cluster-write"
1861
+ ];
1862
+ var RENDER_HDRP_CLUSTER_PHASE_CATALOG = [
1863
+ "record/scene-state/hdrp-cluster/binner",
1864
+ ...RENDER_HDRP_BINNER_PHASE_CATALOG,
1865
+ "record/scene-state/hdrp-cluster/payload-packing",
1866
+ "record/scene-state/hdrp-cluster/buffer-upload"
1867
+ ];
1868
+ var RENDER_SCENE_STATE_PHASE_CATALOG = [
1869
+ "record/scene-state/fold-buckets",
1870
+ "record/scene-state/lighting-prep",
1871
+ "record/scene-state/ambient-resolution",
1872
+ "record/scene-state/directional-shadow-cache",
1873
+ "record/scene-state/hdrp-cluster",
1874
+ ...RENDER_HDRP_CLUSTER_PHASE_CATALOG
1875
+ ];
1876
+ var RENDER_RECORD_PHASE_CATALOG = [
1877
+ "record/occlusion-query-submit",
1878
+ "record/occlusion-global-advance",
1879
+ "record/scene-state",
1880
+ ...RENDER_SCENE_STATE_PHASE_CATALOG,
1881
+ "record/swapchain",
1882
+ "record/render-graph",
1883
+ "record/target-views",
1884
+ "record/validation",
1885
+ "record/dispatch-plan",
1886
+ "record/uploads",
1887
+ "record/bind-groups",
1888
+ "record/graph-execute",
1889
+ ...RENDER_GRAPH_EXECUTION_PHASE_CATALOG
1890
+ ];
1891
+ var RENDER_PHASE_CATALOG = [
1892
+ "extract",
1893
+ "occlusion-prepare",
1894
+ "bind-groups",
1895
+ "features",
1896
+ "sort",
1897
+ "record",
1898
+ ...RENDER_RECORD_PHASE_CATALOG
1899
+ ];
1900
+
1901
+ // src/targets/material-source.ts
1902
+ var sourceBindings = /* @__PURE__ */ new WeakMap();
1903
+ var targetIdentities = /* @__PURE__ */ new WeakMap();
1904
+ var nextTargetIdentity = 1;
1905
+ function targetIdentity(target) {
1906
+ const object = target;
1907
+ const existing = targetIdentities.get(object);
1908
+ if (existing !== void 0) return existing;
1909
+ const identity = nextTargetIdentity;
1910
+ nextTargetIdentity += 1;
1911
+ targetIdentities.set(object, identity);
1912
+ return identity;
1913
+ }
1914
+ function sourceToken() {
1915
+ return Object.freeze({});
1916
+ }
1917
+ function resolveRenderTargetMaterialSource(source) {
1918
+ return sourceBindings.get(source);
1919
+ }
1920
+ function renderTargetMaterialSourceIdentity(source) {
1921
+ const binding = resolveRenderTargetMaterialSource(source);
1922
+ if (binding === void 0) return void 0;
1923
+ return [
1924
+ targetIdentity(binding.target),
1925
+ binding.generation,
1926
+ binding.shape,
1927
+ binding.format,
1928
+ binding.view.dimension,
1929
+ binding.view.mipLevel,
1930
+ binding.view.resolveRequired ? 1 : 0
1931
+ ].join(":");
1932
+ }
1933
+ function invalid(field, value, expected) {
1934
+ return {
1935
+ ok: false,
1936
+ error: new RenderTargetDescriptorInvalidError({ field, value, expected })
1937
+ };
1938
+ }
1939
+ function createRenderTargetMaterialSource(target, descriptor, options) {
1940
+ if (options.aspect !== "color") return invalid("aspect", options.aspect, "color");
1941
+ if (options.dimension !== descriptor.shape) {
1942
+ return invalid("dimension", options.dimension, `dimension matches ${descriptor.shape}`);
1943
+ }
1944
+ const mipCount = descriptor.mipLevels === 1 ? 1 : Math.floor(Math.log2(Math.max(descriptor.width, descriptor.height))) + 1;
1945
+ if (!Number.isInteger(options.mipLevel) || options.mipLevel < 0 || options.mipLevel >= mipCount) {
1946
+ return invalid("mipLevel", options.mipLevel, `an admitted mip level below ${mipCount}`);
1947
+ }
1948
+ if (!Number.isInteger(options.generation) || options.generation < 0) {
1949
+ return invalid("generation", options.generation, "a non-negative device generation");
1950
+ }
1951
+ const result = {
1952
+ ok: true,
1953
+ value: Object.freeze({
1954
+ source: sourceToken(),
1955
+ target,
1956
+ generation: options.generation,
1957
+ shape: descriptor.shape,
1958
+ format: descriptor.format,
1959
+ view: Object.freeze({
1960
+ dimension: options.dimension,
1961
+ mipLevel: options.mipLevel,
1962
+ resolveRequired: descriptor.sampleCount === 4
1963
+ })
1964
+ })
1965
+ };
1966
+ sourceBindings.set(result.value.source, result.value);
1967
+ return result;
1968
+ }
1969
+
1970
+ // src/gpu-stage.ts
1971
+ var GPU_SHADER_STAGE_VERTEX = 1;
1972
+ var GPU_SHADER_STAGE_FRAGMENT = 2;
1973
+ var GPU_SHADER_STAGE_COMPUTE = 4;
1974
+ var BGL_ONLY_SPEC_STUB = Object.freeze({
1975
+ shader: { id: "", passKind: "forward", variantSet: void 0 },
1976
+ attachments: { colorFormats: [], depthFormat: void 0, sampleCount: 1 },
1977
+ geometry: { topology: "triangle-list", vertexLayout: {} },
1978
+ renderState: void 0
1979
+ });
1980
+ function buildPbrMaterialUserRegionEntries(paramSchema = STANDARD_PIPELINE_PARAM_SCHEMA, excludedTextureFields = []) {
1981
+ const excluded = new Set(excludedTextureFields);
1982
+ for (const field of standardPhysicalTextureFields(paramSchema)) excluded.add(field);
1983
+ const derived = derive(
1984
+ excluded.size === 0 ? paramSchema : paramSchema.filter(
1985
+ (entry) => !excluded.has(entry.name) || !entry.type.startsWith("texture")
1986
+ )
1987
+ );
1988
+ let entries = derived.bglEntries.map(
1989
+ (entry) => ({
1990
+ binding: entry.binding,
1991
+ visibility: entry.texture !== void 0 || entry.sampler !== void 0 ? GPU_SHADER_STAGE_VERTEX | GPU_SHADER_STAGE_FRAGMENT : entry.visibility,
1992
+ ...entry.buffer === void 0 ? {} : { buffer: entry.buffer },
1993
+ ...entry.sampler === void 0 ? {} : { sampler: entry.sampler },
1994
+ ...entry.texture === void 0 ? {} : { texture: entry.texture },
1995
+ ...entry.storageTexture === void 0 ? {} : { storageTexture: entry.storageTexture }
1996
+ })
1997
+ );
1998
+ const ubo = entries[0];
1999
+ if (ubo !== void 0 && ubo.binding === 0 && ubo.buffer?.type === "uniform") {
2000
+ entries[0] = {
2001
+ binding: 0,
2002
+ visibility: GPU_SHADER_STAGE_VERTEX | GPU_SHADER_STAGE_FRAGMENT,
2003
+ buffer: { type: "uniform", hasDynamicOffset: true }
2004
+ };
2005
+ } else {
2006
+ entries = [
2007
+ {
2008
+ binding: 0,
2009
+ visibility: GPU_SHADER_STAGE_VERTEX | GPU_SHADER_STAGE_FRAGMENT,
2010
+ buffer: { type: "uniform", hasDynamicOffset: true }
2011
+ },
2012
+ ...entries.map((entry) => ({ ...entry, binding: entry.binding + 1 }))
2013
+ ];
2014
+ }
2015
+ return entries;
2016
+ }
2017
+ function appendInjection(bgl, kind) {
2018
+ const start = bgl.length;
2019
+ switch (kind) {
2020
+ case "ibl":
2021
+ return [
2022
+ // binding start+0: irradianceMap (texture_cube)
2023
+ {
2024
+ binding: start,
2025
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2026
+ texture: { sampleType: "float", viewDimension: "cube" }
2027
+ },
2028
+ // binding start+1: irradianceSampler
2029
+ {
2030
+ binding: start + 1,
2031
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2032
+ sampler: { type: "filtering" }
2033
+ },
2034
+ // binding start+2: prefilterMap (texture_cube)
2035
+ {
2036
+ binding: start + 2,
2037
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2038
+ texture: { sampleType: "float", viewDimension: "cube" }
2039
+ },
2040
+ // binding start+3: prefilterSampler
2041
+ {
2042
+ binding: start + 3,
2043
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2044
+ sampler: { type: "filtering" }
2045
+ },
2046
+ // binding start+4: brdfLut (texture_2d)
2047
+ {
2048
+ binding: start + 4,
2049
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2050
+ texture: { sampleType: "float", viewDimension: "2d" }
2051
+ },
2052
+ // binding start+5: uniform { intensity: f32 }
2053
+ {
2054
+ binding: start + 5,
2055
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2056
+ buffer: { type: "uniform" }
2057
+ }
2058
+ ];
2059
+ case "lightmap":
2060
+ return [
2061
+ // emissive sampler + texture pair
2062
+ {
2063
+ binding: start,
2064
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2065
+ sampler: { type: "filtering" }
2066
+ },
2067
+ {
2068
+ binding: start + 1,
2069
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2070
+ texture: { sampleType: "float", viewDimension: "2d" }
2071
+ },
2072
+ // occlusion sampler + texture pair
2073
+ {
2074
+ binding: start + 2,
2075
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2076
+ sampler: { type: "filtering" }
2077
+ },
2078
+ {
2079
+ binding: start + 3,
2080
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2081
+ texture: { sampleType: "float", viewDimension: "2d" }
2082
+ }
2083
+ ];
2084
+ case "shadow":
2085
+ return [
2086
+ {
2087
+ binding: start,
2088
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2089
+ sampler: { type: "comparison" }
2090
+ },
2091
+ {
2092
+ binding: start + 1,
2093
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2094
+ texture: { sampleType: "depth", viewDimension: "2d" }
2095
+ }
2096
+ ];
2097
+ case "transmission":
2098
+ return [
2099
+ {
2100
+ binding: start,
2101
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2102
+ sampler: { type: "filtering" }
2103
+ },
2104
+ {
2105
+ binding: start + 1,
2106
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2107
+ texture: { sampleType: "float", viewDimension: "2d" }
2108
+ }
2109
+ ];
2110
+ }
2111
+ }
2112
+ function appendSingleLayerMediumInjection(bgl) {
2113
+ const start = bgl.length;
2114
+ return [
2115
+ {
2116
+ binding: start,
2117
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2118
+ sampler: { type: "non-filtering" }
2119
+ },
2120
+ {
2121
+ binding: start + 1,
2122
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2123
+ texture: { sampleType: "unfilterable-float", viewDimension: "2d" }
2124
+ },
2125
+ {
2126
+ binding: start + 2,
2127
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2128
+ sampler: { type: "filtering" }
2129
+ },
2130
+ {
2131
+ binding: start + 3,
2132
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2133
+ texture: { sampleType: "float", viewDimension: "2d" }
2134
+ },
2135
+ {
2136
+ binding: start + 4,
2137
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2138
+ sampler: { type: "non-filtering" }
2139
+ },
2140
+ {
2141
+ binding: start + 5,
2142
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2143
+ texture: { sampleType: "unfilterable-float", viewDimension: "2d" }
2144
+ }
2145
+ ];
2146
+ }
2147
+ function physicalTextureFields(paramSchema) {
2148
+ return standardPhysicalTextureFields(paramSchema);
2149
+ }
2150
+ function appendTextureInjection(_bgl, fields) {
2151
+ const fieldSet = new Set(fields);
2152
+ return standardPhysicalTextureFields(
2153
+ STANDARD_PIPELINE_PARAM_SCHEMA.concat(
2154
+ fields.map((name) => ({ name, type: "texture2d" }))
2155
+ )
2156
+ ).flatMap((field) => {
2157
+ if (!fieldSet.has(field)) return [];
2158
+ const canonicalIndex = STANDARD_PHYSICAL_TEXTURE_FIELDS.indexOf(field);
2159
+ const binding = 26 + canonicalIndex * 2;
2160
+ return [
2161
+ {
2162
+ binding,
2163
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2164
+ sampler: { type: "filtering" }
2165
+ },
2166
+ {
2167
+ binding: binding + 1,
2168
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2169
+ texture: { sampleType: "float", viewDimension: "2d" }
2170
+ }
2171
+ ];
2172
+ });
2173
+ }
2174
+ function materialBindGroupLayoutIdentity(shaderId, paramSchema) {
2175
+ const descriptor = buildBindGroupLayoutDescriptor(
2176
+ {
2177
+ shader: { id: shaderId, passKind: "forward", variantSet: void 0 },
2178
+ attachments: { colorFormats: [], depthFormat: void 0, sampleCount: 1 }},
2179
+ { kind: "pbr-material-merged", materialParamSchema: paramSchema }
2180
+ );
2181
+ return JSON.stringify({
2182
+ entries: descriptor.entries,
2183
+ physicalTextureFields: physicalTextureFields(paramSchema)
2184
+ });
2185
+ }
2186
+ function buildPbrViewBglEntries(caps) {
2187
+ const entries = [
2188
+ {
2189
+ binding: 0,
2190
+ visibility: GPU_SHADER_STAGE_VERTEX | GPU_SHADER_STAGE_FRAGMENT,
2191
+ // View captures use the same bind group with a per-face view slot.
2192
+ // Keeping this dynamic is also valid for the display slot at offset 0.
2193
+ buffer: { type: "uniform", hasDynamicOffset: true }
2194
+ },
2195
+ {
2196
+ binding: 3,
2197
+ visibility: GPU_SHADER_STAGE_VERTEX | GPU_SHADER_STAGE_FRAGMENT,
2198
+ texture: { sampleType: "depth", viewDimension: "2d" }
2199
+ },
2200
+ {
2201
+ binding: 4,
2202
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2203
+ sampler: { type: "comparison" }
2204
+ },
2205
+ // feat-20260612-point-light-shadows-urp-hdrp Round-2 F-1: point shadow
2206
+ // cube_array depth atlas. Bound to either the real ShadowAtlas
2207
+ // cube_array view (when point shadows are active) or a 1x1x6 fallback
2208
+ // cube_array view cleared to 1.0 (fully lit). Visibility is FRAGMENT
2209
+ // only -- the directional binding 3 is VERTEX|FRAGMENT for shadow
2210
+ // probe-debug sampling, but the cube atlas has no host-side probe path.
2211
+ {
2212
+ binding: 5,
2213
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2214
+ texture: { sampleType: "depth", viewDimension: "cube-array" }
2215
+ },
2216
+ // feat-20260612-point-light-shadows-urp-hdrp Round-2 F-1: point shadow
2217
+ // params UBO. Carries `array<vec4<f32>, 4>` = 64 B with one lane per
2218
+ // shadow-casting point light slot (shadowAtlasLayer in [0, 4)). Each
2219
+ // lane stores `(near, far, depthBias, normalBias)` so the fragment-shader
2220
+ // depth-ref reconstruction (lighting-punctual.wgsl evalPointShadowed)
2221
+ // can avoid sampling DirectLightSlot for the URP path. The shared
2222
+ // DirectLightSlot metadata remains the identity owner, so binding 6 is
2223
+ // unused on HDRP shaders even though the BGL declares it (charter P4 single SSOT
2224
+ // BGL across pipelines; the HDRP variant simply doesn't reference the
2225
+ // binding in WGSL, which is allowed).
2226
+ {
2227
+ binding: 6,
2228
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2229
+ buffer: { type: "uniform" }
2230
+ },
2231
+ // feat-20260613-csm-cascaded-shadow-maps M5 / w28: shadowCasterCascade
2232
+ // UBO (16 B). Carries the 0-based cascade index of the shadow pass
2233
+ // currently being rasterized so `shadow_caster.wgsl` can index into
2234
+ // `view.lightViewProj_X` per cascade. Shifted from binding 5 to
2235
+ // binding 7 on 2026-06-13 to make room for point-shadow bindings 5/6
2236
+ // (they predate this feat in main; CSM's slot was the optimal-yield
2237
+ // give since point-shadow needs FRAGMENT-only and the cascade UBO
2238
+ // needs vertex-stage too — keeping cascade higher avoids interleaving
2239
+ // visibility flags within the contiguous shadow-binding cluster).
2240
+ {
2241
+ binding: 7,
2242
+ visibility: GPU_SHADER_STAGE_VERTEX | GPU_SHADER_STAGE_FRAGMENT,
2243
+ buffer: { type: "uniform" }
2244
+ },
2245
+ // feat-20260625-spot-light-shadow-mapping M3 / w14 (D-5): spot shadow
2246
+ // atlas. A single `texture_depth_2d` holding up to 4 spot shadows in a 2x2
2247
+ // tile grid (urp-pipeline.ts spotShadowDepth). FRAGMENT-only — the spot
2248
+ // shadow factor is reconstructed at fragment time via perspective-divide in
2249
+ // `evalSpotShadowed` (lighting-punctual.wgsl).
2250
+ //
2251
+ // ALWAYS-ON (no caps gate, unlike the point cube_array atlas at binding 5
2252
+ // which rides POINT_SHADOW_AVAILABLE): spot uses `texture_depth_2d` which is
2253
+ // compat-safe in every WebGPU profile, so the binding is unconditionally
2254
+ // declared. The matching WGSL declaration is `spotShadowMap` at @group(0)
2255
+ // binding 8 in common.wgsl (also unconditional) — the two must stay in
2256
+ // lock-step or WebGPU validation rejects the bind group at smoke time
2257
+ // (memory: BGL shape mismatch is a browser-path-only bug). No binding 9
2258
+ // sampler: spot reuses the comparison sampler at binding 4.
2259
+ // feat-20260625-spot-light-shadow-mapping M3 / w14 (D-5): spot shadow 2D
2260
+ // atlas, the LAST view-BG binding. The per-spot fragment-read perspective
2261
+ // lightViewProj matrices that w24 originally declared at a standalone
2262
+ // binding 9 uniform buffer were folded into the View UBO (binding 0,
2263
+ // `view.spotLightViewProj`) in w25 (scope-amend webkit-fallback): the
2264
+ // standalone binding pushed the WebGL2 fallback fragment uniform-buffer
2265
+ // count to 12, over GLES 3.0's `max_uniform_buffers_per_shader_stage = 11`,
2266
+ // crashing pipeline-layout creation on the compat path (this feat's target).
2267
+ {
2268
+ binding: 8,
2269
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2270
+ texture: { sampleType: "depth", viewDimension: "2d" }
2271
+ }
2272
+ ];
2273
+ const extendedLighting = caps.extendedLighting ?? true;
2274
+ const lowLimitCloudBindings = extendedLighting === false && caps.projectorAvailable === false;
2275
+ if (extendedLighting) {
2276
+ entries.push(
2277
+ {
2278
+ binding: 9,
2279
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2280
+ sampler: { type: "filtering" }
2281
+ },
2282
+ {
2283
+ binding: 11,
2284
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2285
+ texture: { sampleType: "float", viewDimension: "2d-array" }
2286
+ },
2287
+ {
2288
+ binding: 12,
2289
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2290
+ texture: { sampleType: "float", viewDimension: "2d-array" }
2291
+ },
2292
+ {
2293
+ binding: 13,
2294
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2295
+ texture: { sampleType: "float", viewDimension: "2d" }
2296
+ },
2297
+ {
2298
+ binding: 14,
2299
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2300
+ texture: { sampleType: "float", viewDimension: "2d" }
2301
+ },
2302
+ {
2303
+ binding: 15,
2304
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2305
+ buffer: { type: "uniform" }
2306
+ }
2307
+ );
2308
+ } else if (caps.projectorAvailable !== false) {
2309
+ entries.push(
2310
+ {
2311
+ binding: 11,
2312
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2313
+ texture: { sampleType: "float", viewDimension: "2d" }
2314
+ },
2315
+ {
2316
+ binding: 12,
2317
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2318
+ sampler: { type: "filtering" }
2319
+ }
2320
+ );
2321
+ }
2322
+ entries.push({
2323
+ binding: 10,
2324
+ visibility: GPU_SHADER_STAGE_VERTEX,
2325
+ buffer: { type: "uniform", hasDynamicOffset: true }
2326
+ });
2327
+ if (!lowLimitCloudBindings) {
2328
+ entries.push(
2329
+ {
2330
+ binding: 16,
2331
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2332
+ texture: { sampleType: "float", viewDimension: "2d" }
2333
+ },
2334
+ {
2335
+ binding: 17,
2336
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2337
+ sampler: { type: "filtering" }
2338
+ }
2339
+ );
2340
+ }
2341
+ return entries;
2342
+ }
2343
+ function buildPbrPipelineLayouts(device, caps) {
2344
+ const viewBglRes = device.createBindGroupLayout(
2345
+ buildBindGroupLayoutDescriptor(BGL_ONLY_SPEC_STUB, { kind: "pbr-view", caps })
2346
+ );
2347
+ if (!viewBglRes.ok) throw viewBglRes.error;
2348
+ const materialBglRes = device.createBindGroupLayout(
2349
+ buildBindGroupLayoutDescriptor(BGL_ONLY_SPEC_STUB, {
2350
+ kind: "pbr-material-merged",
2351
+ caps
2352
+ })
2353
+ );
2354
+ if (!materialBglRes.ok) throw materialBglRes.error;
2355
+ const meshArrayBglRes = device.createBindGroupLayout(
2356
+ buildBindGroupLayoutDescriptor(BGL_ONLY_SPEC_STUB, { kind: "pbr-mesh-array", caps })
2357
+ );
2358
+ if (!meshArrayBglRes.ok) throw meshArrayBglRes.error;
2359
+ const instancesBglRes = device.createBindGroupLayout(
2360
+ buildBindGroupLayoutDescriptor(BGL_ONLY_SPEC_STUB, {
2361
+ kind: "pbr-instances",
2362
+ caps: { ...caps, probeBlend: false }
2363
+ })
2364
+ );
2365
+ if (!instancesBglRes.ok) throw instancesBglRes.error;
2366
+ const probeInstancesBglRes = caps.storageBuffer ? device.createBindGroupLayout(
2367
+ buildBindGroupLayoutDescriptor(BGL_ONLY_SPEC_STUB, {
2368
+ kind: "pbr-instances",
2369
+ caps: { ...caps, probeBlend: true }
2370
+ })
2371
+ ) : { ok: true, value: instancesBglRes.value };
2372
+ if (!probeInstancesBglRes.ok) throw probeInstancesBglRes.error;
2373
+ const layouts = [
2374
+ viewBglRes.value,
2375
+ materialBglRes.value,
2376
+ meshArrayBglRes.value,
2377
+ instancesBglRes.value
2378
+ ];
2379
+ const pipelineLayoutRes = device.createPipelineLayout({
2380
+ label: "pbr-pl",
2381
+ bindGroupLayouts: layouts
2382
+ });
2383
+ if (!pipelineLayoutRes.ok) throw pipelineLayoutRes.error;
2384
+ const probeLayouts = [viewBglRes.value, materialBglRes.value, meshArrayBglRes.value, probeInstancesBglRes.value];
2385
+ let probePipelineLayout = null;
2386
+ if (caps.storageBuffer) {
2387
+ const probePipelineLayoutRes = device.createPipelineLayout({
2388
+ label: "pbr-probe-pl",
2389
+ bindGroupLayouts: probeLayouts
2390
+ });
2391
+ if (!probePipelineLayoutRes.ok) throw probePipelineLayoutRes.error;
2392
+ probePipelineLayout = probePipelineLayoutRes.value;
2393
+ }
2394
+ return {
2395
+ pipelineLayout: pipelineLayoutRes.value,
2396
+ viewBgl: viewBglRes.value,
2397
+ materialBgl: materialBglRes.value,
2398
+ meshArrayBgl: meshArrayBglRes.value,
2399
+ instancesBgl: instancesBglRes.value,
2400
+ probeInstancesBgl: probeInstancesBglRes.value,
2401
+ probePipelineLayout,
2402
+ bindGroupLayouts: layouts
2403
+ };
2404
+ }
2405
+ var SKIN_MATERIAL_SHADER_ID = "forgeax::pbr-skin";
2406
+ var SHADOW_CASTER_SHADER_ID = "forgeax::default-shadow-caster";
2407
+ var AUTHORED_STANDARD_ID_RE = /::(?:standard|pbr-skin)(?:-|$)/;
2408
+ function isStandardPbrSkinMaterialShader(shaderId) {
2409
+ return shaderId === SKIN_MATERIAL_SHADER_ID || shaderId === "forgeax::default-standard-pbr-skin" || shaderId !== void 0 && /::pbr-skin(?:-|$)/.test(shaderId);
2410
+ }
2411
+ function shadowCasterVariantSet(storageBuffer, skinned, gpuDrivenSceneIndex = false, alphaMask = false, vertexColorAvailable = false) {
2412
+ const skinningDisabled = !skinned;
2413
+ const defines = {
2414
+ ALPHA_MASK: alphaMask,
2415
+ GPU_DRIVEN_SCENE_INDEX_AVAILABLE: gpuDrivenSceneIndex,
2416
+ GPU_DRIVEN_SCENE_INDEX_EXPLICIT: false,
2417
+ SKINNING_DISABLED: skinningDisabled,
2418
+ STORAGE_BUFFER_AVAILABLE: storageBuffer
2419
+ };
2420
+ if (vertexColorAvailable) defines.VERTEX_COLOR_AVAILABLE = true;
2421
+ return Object.entries(defines).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([name, value]) => `${name}=${String(value)}`).join("+");
2422
+ }
2423
+ function resolvePipelineGroup2Contract(source) {
2424
+ const withoutComments = source.replace(/\/\*[\s\S]*?\*\//gu, "").replace(/\/\/.*$/gmu, "");
2425
+ const bindings = [
2426
+ ...withoutComments.matchAll(/@group\s*\(\s*2\s*\)\s*@binding\s*\(\s*(\d+)\s*\)/gu)
2427
+ ].map((match) => Number(match[1]));
2428
+ const hasSkinBindings = bindings.includes(1) || bindings.includes(2);
2429
+ const hasClusterBindings = bindings.some((binding) => binding >= 3);
2430
+ if (hasSkinBindings && hasClusterBindings) return "skin-cluster";
2431
+ if (hasSkinBindings) return "skin";
2432
+ if (hasClusterBindings) return "cluster";
2433
+ return "mesh";
2434
+ }
2435
+ function isStandardPbrMaterialShader(shaderId) {
2436
+ return shaderId === "forgeax::default-standard-pbr" || shaderId === SKIN_MATERIAL_SHADER_ID || shaderId === "forgeax::default-standard-pbr-skin" || shaderId !== void 0 && AUTHORED_STANDARD_ID_RE.test(shaderId);
2437
+ }
2438
+ function isCanonicalStandardPbrMaterialShader(shaderId) {
2439
+ return shaderId === "forgeax::default-standard-pbr" || shaderId === SKIN_MATERIAL_SHADER_ID || shaderId === "forgeax::default-standard-pbr-skin";
2440
+ }
2441
+ function buildPbrSkinLayouts(device, caps, pbr) {
2442
+ const skinMeshArrayBglRes = device.createBindGroupLayout(
2443
+ buildBindGroupLayoutDescriptor(BGL_ONLY_SPEC_STUB, {
2444
+ kind: "pbr-skin-mesh-array",
2445
+ caps
2446
+ })
2447
+ );
2448
+ if (!skinMeshArrayBglRes.ok) throw skinMeshArrayBglRes.error;
2449
+ const layouts = [
2450
+ pbr.viewBgl,
2451
+ pbr.materialBgl,
2452
+ skinMeshArrayBglRes.value,
2453
+ pbr.instancesBgl
2454
+ ];
2455
+ const pipelineLayoutRes = device.createPipelineLayout({
2456
+ label: "pbr-skin-pl",
2457
+ bindGroupLayouts: layouts
2458
+ });
2459
+ if (!pipelineLayoutRes.ok) throw pipelineLayoutRes.error;
2460
+ const probeLayouts = [pbr.viewBgl, pbr.materialBgl, skinMeshArrayBglRes.value, pbr.probeInstancesBgl];
2461
+ let probePipelineLayout = null;
2462
+ if (caps.storageBuffer) {
2463
+ const probePipelineLayoutRes = device.createPipelineLayout({
2464
+ label: "pbr-skin-probe-pl",
2465
+ bindGroupLayouts: probeLayouts
2466
+ });
2467
+ if (!probePipelineLayoutRes.ok) throw probePipelineLayoutRes.error;
2468
+ probePipelineLayout = probePipelineLayoutRes.value;
2469
+ }
2470
+ return {
2471
+ pipelineLayout: pipelineLayoutRes.value,
2472
+ viewBgl: pbr.viewBgl,
2473
+ materialBgl: pbr.materialBgl,
2474
+ meshArrayBgl: skinMeshArrayBglRes.value,
2475
+ instancesBgl: pbr.instancesBgl,
2476
+ probeInstancesBgl: pbr.probeInstancesBgl,
2477
+ probePipelineLayout,
2478
+ bindGroupLayouts: layouts
2479
+ };
2480
+ }
2481
+ function buildGpuDrivenPbrInstancesBindGroupLayout(device, caps) {
2482
+ if (!caps.storageBuffer) {
2483
+ throw new Error("GPU-driven PBR instances layout requires storage-buffer capability");
2484
+ }
2485
+ const result = device.createBindGroupLayout(
2486
+ buildBindGroupLayoutDescriptor(BGL_ONLY_SPEC_STUB, {
2487
+ kind: "pbr-gpu-driven-instances",
2488
+ caps
2489
+ })
2490
+ );
2491
+ if (!result.ok) throw result.error;
2492
+ return result.value;
2493
+ }
2494
+ function buildSurfaceDirectInstancesBindGroupLayout(device, caps) {
2495
+ if (!caps.storageBuffer) {
2496
+ throw new Error("Direct Surface instances layout requires storage-buffer capability");
2497
+ }
2498
+ const result = device.createBindGroupLayout(
2499
+ buildBindGroupLayoutDescriptor(BGL_ONLY_SPEC_STUB, {
2500
+ kind: "pbr-surface-direct-instances",
2501
+ caps
2502
+ })
2503
+ );
2504
+ if (!result.ok) throw result.error;
2505
+ return result.value;
2506
+ }
2507
+ function buildGpuDrivenPbrPipelineLayout(device, pbr, gpuDrivenInstancesBgl) {
2508
+ const result = device.createPipelineLayout({
2509
+ label: "pbr-gpu-driven-pl",
2510
+ bindGroupLayouts: [pbr.viewBgl, pbr.materialBgl, pbr.meshArrayBgl, gpuDrivenInstancesBgl]
2511
+ });
2512
+ if (!result.ok) throw result.error;
2513
+ return result.value;
2514
+ }
2515
+ function buildGpuDrivenPbrSkinPipelineLayout(device, pbrSkin, gpuDrivenInstancesBgl) {
2516
+ const result = device.createPipelineLayout({
2517
+ label: "pbr-skin-gpu-driven-pl",
2518
+ bindGroupLayouts: [
2519
+ pbrSkin.viewBgl,
2520
+ pbrSkin.materialBgl,
2521
+ pbrSkin.meshArrayBgl,
2522
+ gpuDrivenInstancesBgl
2523
+ ]
2524
+ });
2525
+ if (!result.ok) throw result.error;
2526
+ return result.value;
2527
+ }
2528
+ function createPbrSkinMeshBindGroupEntries(meshBuffer, meshSize, paletteBuffer, paletteWindowBytes) {
2529
+ return [
2530
+ {
2531
+ binding: 0,
2532
+ resource: { kind: "buffer", value: { buffer: meshBuffer, offset: 0, size: meshSize } }
2533
+ },
2534
+ ...[1, 2].map((binding) => ({
2535
+ binding,
2536
+ resource: {
2537
+ kind: "buffer",
2538
+ value: {
2539
+ buffer: paletteBuffer,
2540
+ offset: 0,
2541
+ size: paletteWindowBytes
2542
+ }
2543
+ }
2544
+ }))
2545
+ ];
2546
+ }
2547
+ function pbrSkinMeshDynamicOffsets(meshOffset, paletteOffset) {
2548
+ return [meshOffset, paletteOffset, paletteOffset];
2549
+ }
2550
+ var SPRITE_PASS_PER_INSTANCE_REGION_VARIANT_SET = "";
2551
+ function createHdrpBindGroupLayoutDescriptor() {
2552
+ const meshBufType = "read-only-storage";
2553
+ const clusterBufType = "read-only-storage";
2554
+ return {
2555
+ label: "hdrp-unified-bgl-group2",
2556
+ entries: [
2557
+ {
2558
+ binding: 0,
2559
+ // Standard fragment lighting (transmission/refraction and clustered
2560
+ // evaluation) reads the same mesh transform window as the vertex
2561
+ // stage. Keep this visibility in the HDRP descriptor aligned with
2562
+ // the URP mesh-array descriptor; restricting it to vertex makes the
2563
+ // HDRP pipeline invalid when fs_main accesses `meshes[0]`.
2564
+ visibility: GPU_SHADER_STAGE_VERTEX | GPU_SHADER_STAGE_FRAGMENT,
2565
+ buffer: { type: meshBufType, hasDynamicOffset: true }
2566
+ },
2567
+ // Bindings 1 and 2 stay absent for the URP physical isolation gap.
2568
+ {
2569
+ binding: 3,
2570
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2571
+ buffer: { type: clusterBufType, hasDynamicOffset: false }
2572
+ },
2573
+ {
2574
+ binding: 4,
2575
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2576
+ buffer: { type: clusterBufType, hasDynamicOffset: false }
2577
+ },
2578
+ {
2579
+ binding: 5,
2580
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2581
+ buffer: { type: clusterBufType, hasDynamicOffset: false }
2582
+ },
2583
+ {
2584
+ binding: 6,
2585
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2586
+ buffer: { type: "uniform", hasDynamicOffset: false }
2587
+ },
2588
+ {
2589
+ binding: 7,
2590
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2591
+ texture: { sampleType: "float", viewDimension: "2d", multisampled: false }
2592
+ },
2593
+ {
2594
+ binding: 8,
2595
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2596
+ sampler: { type: "filtering" }
2597
+ }
2598
+ ]
2599
+ };
2600
+ }
2601
+ function createHdrpSkinBindGroupLayoutDescriptor() {
2602
+ const base = createHdrpBindGroupLayoutDescriptor();
2603
+ const baseEntries = base.entries;
2604
+ if (baseEntries === void 0 || baseEntries[0] === void 0) {
2605
+ throw new Error("HDRP base group(2) layout must declare mesh binding 0");
2606
+ }
2607
+ const paletteType = "read-only-storage";
2608
+ return {
2609
+ label: "hdrp-skin-unified-bgl-group2",
2610
+ entries: [
2611
+ baseEntries[0],
2612
+ {
2613
+ binding: 1,
2614
+ visibility: GPU_SHADER_STAGE_VERTEX,
2615
+ buffer: { type: paletteType, hasDynamicOffset: true }
2616
+ },
2617
+ {
2618
+ binding: 2,
2619
+ visibility: GPU_SHADER_STAGE_VERTEX,
2620
+ buffer: { type: paletteType, hasDynamicOffset: true }
2621
+ },
2622
+ ...baseEntries.slice(1)
2623
+ ]
2624
+ };
2625
+ }
2626
+ function resolveMaterialParamSchema(spec, options) {
2627
+ if (options.materialParamSchema !== void 0) return options.materialParamSchema;
2628
+ if (options.registry !== void 0) {
2629
+ const lookup = options.registry.findMaterialArtifact(spec.shader.id);
2630
+ if (lookup.ok) return lookup.value.paramSchema;
2631
+ }
2632
+ return void 0;
2633
+ }
2634
+ function buildBindGroupLayoutDescriptor(spec, options) {
2635
+ switch (options.kind) {
2636
+ case "pbr-view": {
2637
+ const caps = options.caps ?? { };
2638
+ return {
2639
+ label: "pbr-view-bgl",
2640
+ entries: buildPbrViewBglEntries(caps)
2641
+ };
2642
+ }
2643
+ case "pbr-mesh-array": {
2644
+ const caps = options.caps ?? { storageBuffer: true };
2645
+ const meshBufType = caps.storageBuffer ? "read-only-storage" : "uniform";
2646
+ return {
2647
+ label: "pbr-mesh-array-bgl",
2648
+ entries: [
2649
+ {
2650
+ binding: 0,
2651
+ visibility: GPU_SHADER_STAGE_VERTEX | GPU_SHADER_STAGE_FRAGMENT,
2652
+ buffer: { type: meshBufType, hasDynamicOffset: true }
2653
+ }
2654
+ ]
2655
+ };
2656
+ }
2657
+ case "pbr-instances": {
2658
+ const caps = options.caps ?? { storageBuffer: true };
2659
+ const meshBufType = caps.storageBuffer ? "read-only-storage" : "uniform";
2660
+ const entries = [
2661
+ {
2662
+ binding: 0,
2663
+ visibility: GPU_SHADER_STAGE_VERTEX,
2664
+ buffer: { type: meshBufType, hasDynamicOffset: false }
2665
+ },
2666
+ ...caps.probeBlend === true ? [
2667
+ {
2668
+ // Per-object fragment lane; the record is always exactly 160B.
2669
+ binding: 1,
2670
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2671
+ buffer: { type: meshBufType, hasDynamicOffset: true }
2672
+ }
2673
+ ] : []
2674
+ ];
2675
+ return {
2676
+ label: caps.probeBlend === true ? "pbr-probe-instances-bgl" : "pbr-instances-bgl",
2677
+ entries: entries.map(
2678
+ (entry) => entry.binding === 0 ? {
2679
+ ...entry,
2680
+ // Standard transmission reads the same per-instance transform in
2681
+ // fs_main to convert glTF unit-space thickness into world metres.
2682
+ visibility: GPU_SHADER_STAGE_VERTEX | GPU_SHADER_STAGE_FRAGMENT
2683
+ } : entry
2684
+ )
2685
+ };
2686
+ }
2687
+ case "pbr-gpu-driven-instances": {
2688
+ const caps = options.caps ?? { storageBuffer: true };
2689
+ const meshBufType = caps.storageBuffer ? "read-only-storage" : "uniform";
2690
+ return {
2691
+ label: "pbr-gpu-driven-instances-bgl",
2692
+ entries: [
2693
+ {
2694
+ binding: 0,
2695
+ visibility: GPU_SHADER_STAGE_VERTEX,
2696
+ buffer: { type: meshBufType, hasDynamicOffset: false }
2697
+ },
2698
+ {
2699
+ // ShadowCaster's scene-index entry still reads the visible row
2700
+ // through binding(1). Keep this alias in the dedicated layout so
2701
+ // the shared visible bind group can serve both the Standard PBR
2702
+ // (binding(2)) and depth-only shadow (binding(1)) consumers.
2703
+ binding: 1,
2704
+ visibility: GPU_SHADER_STAGE_VERTEX | GPU_SHADER_STAGE_FRAGMENT,
2705
+ buffer: { type: meshBufType, hasDynamicOffset: false }
2706
+ },
2707
+ {
2708
+ binding: 2,
2709
+ visibility: GPU_SHADER_STAGE_VERTEX,
2710
+ buffer: { type: meshBufType, hasDynamicOffset: false }
2711
+ },
2712
+ {
2713
+ // Generic Surface dynamic pages are read by authored Surface
2714
+ // accessors. The binding is present for every scene-index group
2715
+ // so Standard and custom Surface batches share one owner shape.
2716
+ binding: 3,
2717
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2718
+ buffer: { type: meshBufType, hasDynamicOffset: false }
2719
+ },
2720
+ {
2721
+ // Frame time, explicit event ranges, and paired background/depth
2722
+ // facts use separate read-only pages. This keeps live state out
2723
+ // of the material row and leaves skin's address lane untouched.
2724
+ binding: 4,
2725
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2726
+ buffer: { type: meshBufType, hasDynamicOffset: false }
2727
+ },
2728
+ {
2729
+ // Frame time is one frame-global fact. Keeping it outside the
2730
+ // member row prevents a stable frame from issuing one 4-byte
2731
+ // queue write for every visible Surface member.
2732
+ binding: 5,
2733
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2734
+ buffer: { type: "uniform", hasDynamicOffset: false }
2735
+ }
2736
+ ]
2737
+ };
2738
+ }
2739
+ case "pbr-surface-direct-instances": {
2740
+ return {
2741
+ label: "pbr-surface-direct-instances-bgl",
2742
+ entries: [
2743
+ {
2744
+ binding: 0,
2745
+ // Direct instance transforms are consumed only by vs_main. Keep
2746
+ // them out of the fragment-stage storage budget; Surface already
2747
+ // needs the retained ProbeBlend/page/frame records there and the
2748
+ // portable WebGPU limit is eight storage buffers per stage.
2749
+ visibility: GPU_SHADER_STAGE_VERTEX,
2750
+ buffer: { type: "read-only-storage", hasDynamicOffset: false }
2751
+ },
2752
+ {
2753
+ binding: 1,
2754
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2755
+ buffer: { type: "read-only-storage", hasDynamicOffset: true }
2756
+ },
2757
+ {
2758
+ binding: 3,
2759
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2760
+ buffer: { type: "read-only-storage", hasDynamicOffset: false }
2761
+ },
2762
+ {
2763
+ binding: 4,
2764
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2765
+ buffer: { type: "read-only-storage", hasDynamicOffset: false }
2766
+ },
2767
+ {
2768
+ binding: 5,
2769
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2770
+ buffer: { type: "uniform", hasDynamicOffset: false }
2771
+ },
2772
+ {
2773
+ binding: 6,
2774
+ visibility: GPU_SHADER_STAGE_VERTEX,
2775
+ buffer: { type: "uniform", hasDynamicOffset: false }
2776
+ }
2777
+ ]
2778
+ };
2779
+ }
2780
+ case "pbr-skin-mesh-array": {
2781
+ const caps = options.caps ?? { storageBuffer: true };
2782
+ const meshBufType = caps.storageBuffer ? "read-only-storage" : "uniform";
2783
+ return {
2784
+ label: "pbr-skin-mesh-array-bgl",
2785
+ entries: [
2786
+ {
2787
+ binding: 0,
2788
+ visibility: GPU_SHADER_STAGE_VERTEX | GPU_SHADER_STAGE_FRAGMENT,
2789
+ buffer: { type: meshBufType, hasDynamicOffset: true }
2790
+ },
2791
+ {
2792
+ binding: 1,
2793
+ visibility: GPU_SHADER_STAGE_VERTEX,
2794
+ buffer: { type: meshBufType, hasDynamicOffset: true }
2795
+ },
2796
+ {
2797
+ binding: 2,
2798
+ visibility: GPU_SHADER_STAGE_VERTEX,
2799
+ buffer: { type: meshBufType, hasDynamicOffset: true }
2800
+ }
2801
+ ]
2802
+ };
2803
+ }
2804
+ case "pbr-material-merged": {
2805
+ const resolvedSchema = resolveMaterialParamSchema(spec, options);
2806
+ const effectiveSchema = resolvedSchema ?? STANDARD_PIPELINE_PARAM_SCHEMA;
2807
+ const physicalFields = physicalTextureFields(effectiveSchema);
2808
+ const userRegionSchema = isCanonicalStandardPbrMaterialShader(spec.shader.id) ? STANDARD_PIPELINE_PARAM_SCHEMA : effectiveSchema;
2809
+ const userRegion = buildPbrMaterialUserRegionEntries(userRegionSchema);
2810
+ const afterIbl = [...userRegion, ...appendInjection(userRegion, "ibl")];
2811
+ const afterTransmission = [...afterIbl, ...appendInjection(afterIbl, "transmission")];
2812
+ const engineRegion = options.caps?.transmissionBackdrop === false && spec.shader.id !== "forgeax::single-layer-medium" ? afterIbl : afterTransmission;
2813
+ const afterSurfaceMedium = spec.shader.id === "forgeax::single-layer-medium" ? [...engineRegion, ...appendSingleLayerMediumInjection(engineRegion)] : engineRegion;
2814
+ const merged = [
2815
+ ...afterSurfaceMedium,
2816
+ ...appendTextureInjection(afterSurfaceMedium, physicalFields)
2817
+ ];
2818
+ if (options.caps?.storageBuffer ?? true) {
2819
+ merged.push({
2820
+ binding: 46,
2821
+ visibility: GPU_SHADER_STAGE_VERTEX | GPU_SHADER_STAGE_FRAGMENT,
2822
+ buffer: { type: "read-only-storage", hasDynamicOffset: false }
2823
+ });
2824
+ }
2825
+ const entries = [
2826
+ ...merged,
2827
+ ...spec.shader.id === "forgeax::single-layer-medium" ? [] : [
2828
+ {
2829
+ binding: 47,
2830
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2831
+ texture: { sampleType: "float", viewDimension: "cube" }
2832
+ }
2833
+ ]
2834
+ ];
2835
+ return {
2836
+ label: "pbr-material-skylight-bgl",
2837
+ entries
2838
+ };
2839
+ }
2840
+ case "unlit-material": {
2841
+ const resolvedSchema = resolveMaterialParamSchema(spec, options);
2842
+ return {
2843
+ label: "unlit-material-bgl",
2844
+ entries: buildPbrMaterialUserRegionEntries(resolvedSchema)
2845
+ };
2846
+ }
2847
+ case "hdrp-7-slot": {
2848
+ const desc = createHdrpBindGroupLayoutDescriptor();
2849
+ return {
2850
+ label: desc.label ?? "hdrp-unified-bgl-group2",
2851
+ entries: [...desc.entries ?? []]
2852
+ };
2853
+ }
2854
+ case "fullscreen-post": {
2855
+ return {
2856
+ label: "fullscreen-post-bgl",
2857
+ entries: buildFullscreenPostInputEntries(spec)
2858
+ };
2859
+ }
2860
+ case "fullscreen-post-with-params": {
2861
+ return {
2862
+ label: "fullscreen-post-with-params-bgl",
2863
+ entries: [
2864
+ ...buildFullscreenPostInputEntries(spec),
2865
+ {
2866
+ binding: 2,
2867
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2868
+ buffer: { type: "uniform" }
2869
+ }
2870
+ ]
2871
+ };
2872
+ }
2873
+ case "fullscreen-post-with-scene-depth": {
2874
+ return {
2875
+ label: "fullscreen-post-with-scene-depth-bgl",
2876
+ entries: [
2877
+ ...buildFullscreenPostInputEntries(spec),
2878
+ {
2879
+ binding: 2,
2880
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2881
+ buffer: { type: "uniform" }
2882
+ },
2883
+ {
2884
+ binding: 3,
2885
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2886
+ texture: { sampleType: "depth", viewDimension: "2d" }
2887
+ },
2888
+ {
2889
+ binding: 4,
2890
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2891
+ sampler: { type: "non-filtering" }
2892
+ }
2893
+ ]
2894
+ };
2895
+ }
2896
+ case "fullscreen-post-with-scene-depth-msaa": {
2897
+ return {
2898
+ label: "fullscreen-post-with-scene-depth-msaa-bgl",
2899
+ entries: [
2900
+ ...buildFullscreenPostInputEntries(spec),
2901
+ {
2902
+ binding: 2,
2903
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2904
+ buffer: { type: "uniform" }
2905
+ },
2906
+ {
2907
+ binding: 3,
2908
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2909
+ texture: { sampleType: "depth", viewDimension: "2d", multisampled: true }
2910
+ },
2911
+ {
2912
+ binding: 4,
2913
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2914
+ sampler: { type: "non-filtering" }
2915
+ }
2916
+ ]
2917
+ };
2918
+ }
2919
+ case "fullscreen-post-with-paired-msaa": {
2920
+ return {
2921
+ label: "fullscreen-post-with-paired-msaa-bgl",
2922
+ entries: [
2923
+ {
2924
+ binding: 0,
2925
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2926
+ texture: {
2927
+ sampleType: "unfilterable-float",
2928
+ viewDimension: "2d",
2929
+ multisampled: true
2930
+ }
2931
+ },
2932
+ {
2933
+ binding: 1,
2934
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2935
+ sampler: { type: "filtering" }
2936
+ },
2937
+ {
2938
+ binding: 2,
2939
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2940
+ buffer: { type: "uniform" }
2941
+ },
2942
+ {
2943
+ binding: 3,
2944
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2945
+ texture: { sampleType: "depth", viewDimension: "2d", multisampled: true }
2946
+ },
2947
+ {
2948
+ binding: 4,
2949
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2950
+ sampler: { type: "non-filtering" }
2951
+ }
2952
+ ]
2953
+ };
2954
+ }
2955
+ }
2956
+ }
2957
+ function buildFullscreenPostInputEntries(spec) {
2958
+ const inputFormat = spec.attachments.depthFormat ?? spec.attachments.colorFormats[0];
2959
+ const sampleType = inputFormat === "depth32float" || inputFormat === "depth24plus" || inputFormat === "depth24plus-stencil8" || inputFormat === "depth16unorm" ? "depth" : inputFormat === "r32float" ? "unfilterable-float" : "float";
2960
+ return [
2961
+ {
2962
+ binding: 0,
2963
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2964
+ texture: { sampleType, viewDimension: "2d" }
2965
+ },
2966
+ {
2967
+ binding: 1,
2968
+ visibility: GPU_SHADER_STAGE_FRAGMENT,
2969
+ sampler: {
2970
+ type: sampleType === "depth" ? "comparison" : "filtering"
2971
+ }
2972
+ }
2973
+ ];
2974
+ }
2975
+
2976
+ // src/systems/pass-selector.ts
2977
+ function matchPass(tags, selector) {
2978
+ if (Object.keys(selector).length === 0) return true;
2979
+ for (const [key, allowedValues] of Object.entries(selector)) {
2980
+ const passValue = tags[key];
2981
+ if (passValue === void 0) return false;
2982
+ if (allowedValues.length === 0) return false;
2983
+ if (!allowedValues.includes(passValue)) return false;
2984
+ }
2985
+ return true;
2986
+ }
2987
+ function selectPasses(passes, selector) {
2988
+ if (Object.keys(selector).length === 0) return passes;
2989
+ return passes.filter(
2990
+ (p) => matchPass(p.renderState?.tags ?? {}, selector)
2991
+ );
2992
+ }
2993
+
2994
+ // src/gpu-driven/prepared-draw.ts
2995
+ function failure(code, detail) {
2996
+ return { ok: false, error: new GpuDrivenPreparationError(code, detail) };
2997
+ }
2998
+ function hasRequiredVertexInputs(expected, actual) {
2999
+ return expected.every(
3000
+ (input) => actual.some(
3001
+ (candidate) => candidate.semantic === input.semantic && candidate.location === input.location && candidate.format === input.format
3002
+ )
3003
+ );
3004
+ }
3005
+ function hasMaterialResources(snapshot, receipt) {
3006
+ if ((snapshot.material.textureSources?.size ?? 0) > 0 || (snapshot.material.videoTextureFields?.size ?? 0) > 0) {
3007
+ return false;
3008
+ }
3009
+ const textures = snapshot.material.textureHandles;
3010
+ const samplers = snapshot.material.samplerHandles;
3011
+ const authoredTextures = snapshot.material.authoredTextureFields;
3012
+ const authoredSamplers = snapshot.material.authoredSamplerFields;
3013
+ return receipt.resourceSlots.every((slot) => {
3014
+ if (slot.kind === "storage-buffer") {
3015
+ return receipt.surface?.dynamicInput?.group === slot.group && receipt.surface.dynamicInput.binding === slot.binding && slot.group === 3 && slot.binding === 3;
3016
+ }
3017
+ if (slot.kind === "texture") {
3018
+ if (!authoredTextures?.has(slot.parameter)) return true;
3019
+ return textures?.has(slot.parameter) === true || snapshot.material.textureSources?.has(slot.parameter) === true || snapshot.material.videoTextureFields?.has(slot.parameter) === true;
3020
+ }
3021
+ if (!authoredSamplers?.has(slot.parameter)) return true;
3022
+ return samplers?.has(slot.parameter) === true;
3023
+ });
3024
+ }
3025
+ function prepareGpuDrivenDraw(input) {
3026
+ const receipt = input.artifact.receipt;
3027
+ if (receipt === void 0) {
3028
+ return failure("missing-material-receipt", {
3029
+ reason: "material-receipt-missing",
3030
+ owner: "material",
3031
+ expected: "MaterialShaderArtifact.receipt"
3032
+ });
3033
+ }
3034
+ if (receipt.generation !== input.generation) {
3035
+ return failure("stale-generation", {
3036
+ reason: "generation-stale",
3037
+ owner: "generation",
3038
+ expectedGeneration: input.generation,
3039
+ actualGeneration: receipt.generation
3040
+ });
3041
+ }
3042
+ if (receipt.reflection.layoutIdentity !== input.artifact.layoutIdentity) {
3043
+ return failure("reflection-mismatch", {
3044
+ reason: "reflection-receipt-mismatch",
3045
+ owner: "material",
3046
+ expected: input.artifact.layoutIdentity,
3047
+ actual: receipt.reflection.layoutIdentity
3048
+ });
3049
+ }
3050
+ if (receipt.uvSets.some((uv) => uv.set > 0) && input.geometry.vertexInputs.length < 3) {
3051
+ return failure("missing-uv", {
3052
+ reason: "uv-set-missing",
3053
+ owner: "geometry",
3054
+ expected: `${receipt.uvSets.length} material UV sets`,
3055
+ actual: `${input.geometry.vertexInputs.filter((vertex) => vertex.semantic.startsWith("uv")).length} geometry UV sets`
3056
+ });
3057
+ }
3058
+ if (!hasRequiredVertexInputs(receipt.vertexInputs, input.geometry.vertexInputs)) {
3059
+ return failure("vertex-input-mismatch", {
3060
+ reason: "vertex-semantic-mismatch",
3061
+ owner: "geometry",
3062
+ expected: receipt.vertexInputs.map((input2) => input2.semantic).join(","),
3063
+ actual: input.geometry.vertexInputs.map((input2) => input2.semantic).join(",")
3064
+ });
3065
+ }
3066
+ const hasAlphaMask = receipt.alphaMask.cutoff.length > 0 || receipt.alphaMask.source.length > 0;
3067
+ if (hasAlphaMask && (receipt.alphaMask.cutoff.length === 0 || receipt.alphaMask.source.length === 0)) {
3068
+ return failure("alpha-mask-mismatch", {
3069
+ reason: "alpha-mask-receipt-missing",
3070
+ owner: "material",
3071
+ expected: "alphaMask.cutoff and alphaMask.source for a masked Pass"
3072
+ });
3073
+ }
3074
+ if (!hasMaterialResources(input.snapshot, receipt)) {
3075
+ return failure("resource-not-ready", {
3076
+ reason: "material-resource-missing",
3077
+ owner: "material",
3078
+ expected: receipt.resourceSlots.map((slot) => slot.parameter).join(",")
3079
+ });
3080
+ }
3081
+ const deformation = input.snapshot.skin === void 0 ? "rigid" : "skin";
3082
+ if (deformation === "skin") {
3083
+ if (input.skinReceipt === void 0 || receipt.skinPaletteAddress === void 0) {
3084
+ return failure("skin-receipt-mismatch", {
3085
+ reason: "skin-address-missing",
3086
+ owner: "skin",
3087
+ expected: "skinPaletteAddress and skinReceipt"
3088
+ });
3089
+ }
3090
+ if (input.skinReceipt.identity !== input.snapshot.skin?.identity || input.skinReceipt.generation !== input.snapshot.skin?.generation || input.skinReceipt.group !== receipt.skinPaletteAddress.group || input.skinReceipt.binding !== receipt.skinPaletteAddress.binding) {
3091
+ return failure("skin-receipt-mismatch", {
3092
+ reason: "skin-address-missing",
3093
+ owner: "skin",
3094
+ expected: `${receipt.skinPaletteAddress.group}:${receipt.skinPaletteAddress.binding}@${input.snapshot.skin?.generation ?? "<missing>"}`,
3095
+ actual: `${input.skinReceipt.group}:${input.skinReceipt.binding}@${input.skinReceipt.generation}`
3096
+ });
3097
+ }
3098
+ }
3099
+ return {
3100
+ ok: true,
3101
+ value: {
3102
+ identity: {
3103
+ material: input.artifact.material,
3104
+ geometry: input.geometry.identity,
3105
+ deformation
3106
+ },
3107
+ receiptGeneration: receipt.generation,
3108
+ receiptIdentity: receipt.receiptIdentity,
3109
+ directEntry: receipt.directEntry,
3110
+ sceneIndexEntry: receipt.sceneIndexEntry,
3111
+ materialRow: receipt.materialRow,
3112
+ resourceSlots: receipt.resourceSlots,
3113
+ uvSets: receipt.uvSets,
3114
+ vertexInputs: receipt.vertexInputs,
3115
+ alphaMask: receipt.alphaMask,
3116
+ skinPaletteAddress: receipt.skinPaletteAddress,
3117
+ topology: input.draw.topology,
3118
+ indexed: input.draw.kind === "indexed",
3119
+ first: input.draw.first,
3120
+ count: input.draw.count,
3121
+ baseVertex: input.draw.baseVertex
3122
+ }
3123
+ };
3124
+ }
3125
+
3126
+ // src/extract/gpu-driven.ts
3127
+ function gpuDrivenDrawKey(worldEntity, materialHandle, drawItemIndex) {
3128
+ return `${worldEntity}:${materialHandle}:${drawItemIndex}`;
3129
+ }
3130
+ function gpuDrivenShadowDrawKey(worldEntity, materialHandle, drawItemIndex, passIndex) {
3131
+ return `${gpuDrivenDrawKey(worldEntity, materialHandle, drawItemIndex)}:${passIndex}`;
3132
+ }
3133
+ function gpuDrivenMaterialArtifactKey(input) {
3134
+ return [
3135
+ input.material,
3136
+ input.deformation,
3137
+ input.receiptIdentity ?? "<legacy-receipt>",
3138
+ input.receiptGeneration
3139
+ ].join("|");
3140
+ }
3141
+ function gpuDrivenSourceDrawItemIndex(draw, compactIndex) {
3142
+ return draw.drawItemIndex ?? compactIndex;
3143
+ }
3144
+ function resolvePreparedGpuDrivenDraw(input) {
3145
+ return prepareGpuDrivenDraw(input);
3146
+ }
3147
+ function gpuDrivenMaterialResourceClass(material) {
3148
+ const textures = [...material.textureHandles?.entries() ?? []].map(([name, handle]) => [name, Number(handle)]).sort(([left], [right]) => left.localeCompare(right));
3149
+ const samplers = [...material.samplerHandles?.entries() ?? []].map(([name, handle]) => [name, Number(handle)]).sort(([left], [right]) => left.localeCompare(right));
3150
+ return JSON.stringify({
3151
+ textures,
3152
+ samplers
3153
+ });
3154
+ }
3155
+ function hasCpuOnlyMaterialResources(material) {
3156
+ return (material.textureSources?.size ?? 0) > 0 || (material.videoTextureFields?.size ?? 0) > 0;
3157
+ }
3158
+ function buildGpuDrivenDraws(input) {
3159
+ const legacy = "submeshes" in input;
3160
+ if (!legacy && input.mesh === void 0) return [];
3161
+ const parsedMesh = legacy ? void 0 : input.mesh;
3162
+ if (!legacy && parsedMesh === void 0) return [];
3163
+ const indexed = legacy ? input.indexed : parsedMesh?.indices !== void 0;
3164
+ const submeshes = legacy ? input.submeshes : parsedMesh?.submeshes ?? [];
3165
+ const layoutProjection = parsedMesh === void 0 ? void 0 : deriveVertexLayoutProjection(parsedMesh.attributes);
3166
+ const geometry = {
3167
+ identity: parsedMesh === void 0 ? "<no-mesh>" : `${parsedMesh.guid ?? "<no-guid>"}:${layoutProjection?.digest ?? ""}`,
3168
+ vertexInputs: (layoutProjection?.attributes ?? []).map((attribute) => ({
3169
+ semantic: attribute.key,
3170
+ location: attribute.shaderLocation,
3171
+ format: attribute.format
3172
+ })),
3173
+ topology: submeshes[0]?.topology ?? "triangle-list",
3174
+ indexed
3175
+ };
3176
+ let nonIndexedFirst = 0;
3177
+ return submeshes.flatMap((submesh, drawItemIndex) => {
3178
+ const drawMaterial = input.materials[submesh.materialSlot] ?? input.fallbackMaterial;
3179
+ const first = indexed ? submesh.indexOffset : nonIndexedFirst;
3180
+ nonIndexedFirst += submesh.vertexCount;
3181
+ if (drawMaterial.transparent === true) return [];
3182
+ const draw = {
3183
+ drawItemIndex,
3184
+ kind: indexed ? "indexed" : "non-indexed",
3185
+ first,
3186
+ count: indexed ? submesh.indexCount : submesh.vertexCount,
3187
+ baseVertex: 0,
3188
+ materialSlot: submesh.materialSlot,
3189
+ topology: submesh.topology,
3190
+ pipelineClass: `${drawMaterial.materialShaderId ?? "forgeax::default-unlit"}|${submesh.topology}|${JSON.stringify(drawMaterial.renderState ?? null)}`,
3191
+ materialResourceClass: gpuDrivenMaterialResourceClass(drawMaterial)
3192
+ };
3193
+ const lodRanges = !legacy ? input.lodMeshes?.map((lodMesh) => {
3194
+ if (lodMesh === void 0) return void 0;
3195
+ const lower = lodMesh.submeshes[drawItemIndex];
3196
+ if (lower === void 0) return void 0;
3197
+ const lowerIndexed = lodMesh.indices !== void 0;
3198
+ const lowerFirst = lowerIndexed ? lower.indexOffset : lodMesh.submeshes.slice(0, drawItemIndex).reduce((offset, entry) => offset + entry.vertexCount, 0);
3199
+ return {
3200
+ first: lowerFirst,
3201
+ count: lowerIndexed ? lower.indexCount : lower.vertexCount,
3202
+ baseVertex: 0
3203
+ };
3204
+ }) : void 0;
3205
+ const withLodRanges = lodRanges?.length !== 0 && lodRanges?.every((range) => range !== void 0) ? { lodRanges } : {};
3206
+ const prepared = legacy ? input.prepare?.(draw, drawMaterial) : hasCpuOnlyMaterialResources(drawMaterial) ? void 0 : (() => {
3207
+ const materialShaderId = drawMaterial.materialShaderId;
3208
+ const vertexColorAvailable = geometry.vertexInputs.some(
3209
+ (input2) => input2.semantic === "color"
3210
+ );
3211
+ const sceneIndexProgramKey = Object.entries(
3212
+ drawMaterial.materialSceneIndexProgramKeys ?? {}
3213
+ ).find(
3214
+ ([passName, program]) => program.pass === "forward" && drawMaterial.materialProgramKeys?.[passName] === materialShaderId
3215
+ )?.[1]?.specializationKey;
3216
+ const artifact = materialShaderId === void 0 ? void 0 : input.getMaterialShaderArtifact?.(sceneIndexProgramKey ?? materialShaderId, {
3217
+ vertexColorAvailable,
3218
+ deformation: input.baseSnapshot.skin === void 0 ? "rigid" : "skin",
3219
+ pass: "forward",
3220
+ address: "scene-index"
3221
+ });
3222
+ const requiresReceipt = isCanonicalStandardPbrMaterialShader(materialShaderId) || sceneIndexProgramKey !== void 0;
3223
+ if (artifact === void 0) {
3224
+ return input.getMaterialShaderArtifact !== void 0 && requiresReceipt ? new GpuDrivenPreparationError("missing-material-receipt", {
3225
+ reason: "material-receipt-missing",
3226
+ owner: "material",
3227
+ expected: `artifact for ${materialShaderId}`
3228
+ }) : void 0;
3229
+ }
3230
+ const receipt = artifact.receipt;
3231
+ if (receipt === void 0) {
3232
+ return new GpuDrivenPreparationError("missing-material-receipt", {
3233
+ reason: "material-receipt-missing",
3234
+ owner: "material",
3235
+ expected: `receipt for ${materialShaderId}`
3236
+ });
3237
+ }
3238
+ const skinReceipt = input.baseSnapshot.skin !== void 0 && receipt.skinPaletteAddress !== void 0 ? {
3239
+ identity: input.baseSnapshot.skin.identity,
3240
+ generation: input.baseSnapshot.skin.generation,
3241
+ group: receipt.skinPaletteAddress.group,
3242
+ binding: receipt.skinPaletteAddress.binding,
3243
+ byteOffset: input.baseSnapshot.skin.byteOffset
3244
+ } : void 0;
3245
+ const selectedArtifact = artifact === void 0 || sceneIndexProgramKey === void 0 || materialShaderId === void 0 ? artifact : {
3246
+ ...artifact,
3247
+ material: materialShaderId,
3248
+ specializationKey: sceneIndexProgramKey
3249
+ };
3250
+ const result = resolvePreparedGpuDrivenDraw({
3251
+ snapshot: { ...input.baseSnapshot, material: drawMaterial },
3252
+ artifact: selectedArtifact ?? artifact,
3253
+ geometry: { ...geometry, topology: draw.topology, indexed: draw.kind === "indexed" },
3254
+ generation: receipt.generation,
3255
+ draw,
3256
+ ...skinReceipt === void 0 ? {} : { skinReceipt }
3257
+ });
3258
+ return result.ok ? result.value : result.error;
3259
+ })();
3260
+ if (prepared instanceof GpuDrivenPreparationError) {
3261
+ return [{ ...draw, preparationError: prepared, ...withLodRanges }];
3262
+ }
3263
+ return [
3264
+ prepared === void 0 ? { ...draw, ...withLodRanges } : { ...draw, prepared, ...withLodRanges }
3265
+ ];
3266
+ });
3267
+ }
3268
+
3269
+ // src/instances-derived-bounds.ts
3270
+ var fingerprintScalar = new Float32Array(1);
3271
+ var fingerprintBits = new Uint32Array(fingerprintScalar.buffer);
3272
+ function fingerprintNumericArray(values) {
3273
+ let hash = 2166136261;
3274
+ for (let index = 0; index < values.length; index += 1) {
3275
+ fingerprintScalar[0] = Number(values[index]);
3276
+ hash = Math.imul(hash ^ (fingerprintBits[0] ?? 0), 16777619) >>> 0;
3277
+ }
3278
+ return hash >>> 0;
3279
+ }
3280
+ function finiteAabb(aabb) {
3281
+ if (aabb === void 0 || aabb.length < 6) return false;
3282
+ const minX = aabb[0];
3283
+ const minY = aabb[1];
3284
+ const minZ = aabb[2];
3285
+ const maxX = aabb[3];
3286
+ const maxY = aabb[4];
3287
+ const maxZ = aabb[5];
3288
+ return Number.isFinite(minX) && Number.isFinite(minY) && Number.isFinite(minZ) && Number.isFinite(maxX) && Number.isFinite(maxY) && Number.isFinite(maxZ) && minX <= maxX && minY <= maxY && minZ <= maxZ;
3289
+ }
3290
+ function finiteMatrix(matrix) {
3291
+ if (matrix.length < 16) return false;
3292
+ for (let index = 0; index < 16; index += 1) {
3293
+ if (!Number.isFinite(matrix[index])) return false;
3294
+ }
3295
+ return true;
3296
+ }
3297
+ function multiplyMat4(out, left, right, rightOffset = 0) {
3298
+ for (let column = 0; column < 4; column += 1) {
3299
+ const rightColumn = rightOffset + column * 4;
3300
+ const right0 = Number(right[rightColumn] ?? 0);
3301
+ const right1 = Number(right[rightColumn + 1] ?? 0);
3302
+ const right2 = Number(right[rightColumn + 2] ?? 0);
3303
+ const right3 = Number(right[rightColumn + 3] ?? 0);
3304
+ const outOffset = column * 4;
3305
+ out[outOffset] = Number(left[0] ?? 0) * right0 + Number(left[4] ?? 0) * right1 + Number(left[8] ?? 0) * right2 + Number(left[12] ?? 0) * right3;
3306
+ out[outOffset + 1] = Number(left[1] ?? 0) * right0 + Number(left[5] ?? 0) * right1 + Number(left[9] ?? 0) * right2 + Number(left[13] ?? 0) * right3;
3307
+ out[outOffset + 2] = Number(left[2] ?? 0) * right0 + Number(left[6] ?? 0) * right1 + Number(left[10] ?? 0) * right2 + Number(left[14] ?? 0) * right3;
3308
+ out[outOffset + 3] = Number(left[3] ?? 0) * right0 + Number(left[7] ?? 0) * right1 + Number(left[11] ?? 0) * right2 + Number(left[15] ?? 0) * right3;
3309
+ }
3310
+ }
3311
+ function finiteMatrixAt(values, offset) {
3312
+ if (values.length - offset < 16) return false;
3313
+ for (let index = 0; index < 16; index += 1) {
3314
+ if (!Number.isFinite(values[offset + index])) return false;
3315
+ }
3316
+ return true;
3317
+ }
3318
+ function isAffine(matrix) {
3319
+ return matrix[3] === 0 && matrix[7] === 0 && matrix[11] === 0 && matrix[15] === 1;
3320
+ }
3321
+ function includeBox(out, candidate, initialized) {
3322
+ const minX = candidate[0];
3323
+ const minY = candidate[1];
3324
+ const minZ = candidate[2];
3325
+ const maxX = candidate[3];
3326
+ const maxY = candidate[4];
3327
+ const maxZ = candidate[5];
3328
+ if (!initialized) {
3329
+ out[0] = minX;
3330
+ out[1] = minY;
3331
+ out[2] = minZ;
3332
+ out[3] = maxX;
3333
+ out[4] = maxY;
3334
+ out[5] = maxZ;
3335
+ return true;
3336
+ }
3337
+ if (minX < (out[0] ?? Number.POSITIVE_INFINITY)) out[0] = minX;
3338
+ if (minY < (out[1] ?? Number.POSITIVE_INFINITY)) out[1] = minY;
3339
+ if (minZ < (out[2] ?? Number.POSITIVE_INFINITY)) out[2] = minZ;
3340
+ if (maxX > (out[3] ?? Number.NEGATIVE_INFINITY)) out[3] = maxX;
3341
+ if (maxY > (out[4] ?? Number.NEGATIVE_INFINITY)) out[4] = maxY;
3342
+ if (maxZ > (out[5] ?? Number.NEGATIVE_INFINITY)) out[5] = maxZ;
3343
+ return true;
3344
+ }
3345
+ function transformAabb(out, local, matrix) {
3346
+ const minX = local[0];
3347
+ const minY = local[1];
3348
+ const minZ = local[2];
3349
+ const maxX = local[3];
3350
+ const maxY = local[4];
3351
+ const maxZ = local[5];
3352
+ const centerX = (minX + maxX) * 0.5;
3353
+ const centerY = (minY + maxY) * 0.5;
3354
+ const centerZ = (minZ + maxZ) * 0.5;
3355
+ const extentX = (maxX - minX) * 0.5;
3356
+ const extentY = (maxY - minY) * 0.5;
3357
+ const extentZ = (maxZ - minZ) * 0.5;
3358
+ if (isAffine(matrix)) {
3359
+ const centerWorldX = matrix[0] * centerX + matrix[4] * centerY + matrix[8] * centerZ + matrix[12];
3360
+ const centerWorldY = matrix[1] * centerX + matrix[5] * centerY + matrix[9] * centerZ + matrix[13];
3361
+ const centerWorldZ = matrix[2] * centerX + matrix[6] * centerY + matrix[10] * centerZ + matrix[14];
3362
+ const extentWorldX = Math.abs(matrix[0]) * extentX + Math.abs(matrix[4]) * extentY + Math.abs(matrix[8]) * extentZ;
3363
+ const extentWorldY = Math.abs(matrix[1]) * extentX + Math.abs(matrix[5]) * extentY + Math.abs(matrix[9]) * extentZ;
3364
+ const extentWorldZ = Math.abs(matrix[2]) * extentX + Math.abs(matrix[6]) * extentY + Math.abs(matrix[10]) * extentZ;
3365
+ out[0] = centerWorldX - extentWorldX;
3366
+ out[1] = centerWorldY - extentWorldY;
3367
+ out[2] = centerWorldZ - extentWorldZ;
3368
+ out[3] = centerWorldX + extentWorldX;
3369
+ out[4] = centerWorldY + extentWorldY;
3370
+ out[5] = centerWorldZ + extentWorldZ;
3371
+ return finiteAabb(out);
3372
+ }
3373
+ let minimumW = Number.POSITIVE_INFINITY;
3374
+ let maximumW = Number.NEGATIVE_INFINITY;
3375
+ for (let corner = 0; corner < 8; corner += 1) {
3376
+ const x = (corner & 1) === 0 ? minX : maxX;
3377
+ const y = (corner & 2) === 0 ? minY : maxY;
3378
+ const z = (corner & 4) === 0 ? minZ : maxZ;
3379
+ const w = matrix[3] * x + matrix[7] * y + matrix[11] * z + matrix[15];
3380
+ if (!Number.isFinite(w)) return false;
3381
+ if (w < minimumW) minimumW = w;
3382
+ if (w > maximumW) maximumW = w;
3383
+ }
3384
+ if (minimumW <= 0 && maximumW >= 0) return false;
3385
+ let unionMinX = Number.POSITIVE_INFINITY;
3386
+ let unionMinY = Number.POSITIVE_INFINITY;
3387
+ let unionMinZ = Number.POSITIVE_INFINITY;
3388
+ let unionMaxX = Number.NEGATIVE_INFINITY;
3389
+ let unionMaxY = Number.NEGATIVE_INFINITY;
3390
+ let unionMaxZ = Number.NEGATIVE_INFINITY;
3391
+ for (let corner = 0; corner < 8; corner += 1) {
3392
+ const x = (corner & 1) === 0 ? minX : maxX;
3393
+ const y = (corner & 2) === 0 ? minY : maxY;
3394
+ const z = (corner & 4) === 0 ? minZ : maxZ;
3395
+ const rawX = matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12];
3396
+ const rawY = matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13];
3397
+ const rawZ = matrix[2] * x + matrix[6] * y + matrix[10] * z + matrix[14];
3398
+ const w = matrix[3] * x + matrix[7] * y + matrix[11] * z + matrix[15];
3399
+ const projectedX = rawX / w;
3400
+ const projectedY = rawY / w;
3401
+ const projectedZ = rawZ / w;
3402
+ if (!Number.isFinite(projectedX) || !Number.isFinite(projectedY) || !Number.isFinite(projectedZ)) {
3403
+ return false;
3404
+ }
3405
+ if (projectedX < unionMinX) unionMinX = projectedX;
3406
+ if (projectedY < unionMinY) unionMinY = projectedY;
3407
+ if (projectedZ < unionMinZ) unionMinZ = projectedZ;
3408
+ if (projectedX > unionMaxX) unionMaxX = projectedX;
3409
+ if (projectedY > unionMaxY) unionMaxY = projectedY;
3410
+ if (projectedZ > unionMaxZ) unionMaxZ = projectedZ;
3411
+ }
3412
+ out[0] = unionMinX;
3413
+ out[1] = unionMinY;
3414
+ out[2] = unionMinZ;
3415
+ out[3] = unionMaxX;
3416
+ out[4] = unionMaxY;
3417
+ out[5] = unionMaxZ;
3418
+ return finiteAabb(out);
3419
+ }
3420
+ function deriveInstancesUnionBounds(input) {
3421
+ const { meshAabb, entityWorld, transforms } = input;
3422
+ if (!finiteAabb(meshAabb) || !finiteMatrix(entityWorld) || transforms === void 0) {
3423
+ return void 0;
3424
+ }
3425
+ if (transforms.length === 0 || transforms.length % 16 !== 0) return void 0;
3426
+ const local = meshAabb;
3427
+ const union = new Float32Array(6);
3428
+ const composed = new Float32Array(16);
3429
+ const transformed = new Float32Array(6);
3430
+ let initialized = false;
3431
+ for (let offset = 0; offset < transforms.length; offset += 16) {
3432
+ if (!finiteMatrixAt(transforms, offset)) return void 0;
3433
+ multiplyMat4(composed, entityWorld, transforms, offset);
3434
+ if (!finiteMatrix(composed) || !transformAabb(transformed, local, composed)) return void 0;
3435
+ initialized = includeBox(union, transformed, initialized);
3436
+ }
3437
+ return initialized && finiteAabb(union) ? union : void 0;
3438
+ }
3439
+ var InstanceBoundsCache = class {
3440
+ entries = /* @__PURE__ */ new Map();
3441
+ hits = 0;
3442
+ misses = 0;
3443
+ derives = 0;
3444
+ invalidations = 0;
3445
+ key(input) {
3446
+ return `${input.worldId === void 0 ? "" : `${input.worldId}:`}${input.entityKey}`;
3447
+ }
3448
+ get(input) {
3449
+ const previous = this.entries.get(this.key(input));
3450
+ if (previous !== void 0 && previous.meshGeneration === input.meshGeneration && previous.transformGeneration === input.transformGeneration && previous.matrixGeneration === input.matrixGeneration) {
3451
+ this.hits += 1;
3452
+ return previous.bounds;
3453
+ }
3454
+ this.misses += 1;
3455
+ this.derives += 1;
3456
+ const bounds = deriveInstancesUnionBounds(input);
3457
+ this.entries.set(this.key(input), {
3458
+ ...input.worldId === void 0 ? {} : { worldId: input.worldId },
3459
+ entityKey: input.entityKey,
3460
+ meshGeneration: input.meshGeneration,
3461
+ transformGeneration: input.transformGeneration,
3462
+ matrixGeneration: input.matrixGeneration,
3463
+ bounds
3464
+ });
3465
+ return bounds;
3466
+ }
3467
+ invalidate(entityKey, worldId) {
3468
+ if (entityKey === void 0) {
3469
+ if (this.entries.size > 0) this.invalidations += this.entries.size;
3470
+ this.entries.clear();
3471
+ } else {
3472
+ if (this.entries.delete(this.key({ entityKey, ...worldId === void 0 ? {} : { worldId } }))) {
3473
+ this.invalidations += 1;
3474
+ }
3475
+ }
3476
+ }
3477
+ inspect() {
3478
+ return {
3479
+ hits: this.hits,
3480
+ misses: this.misses,
3481
+ derives: this.derives,
3482
+ invalidations: this.invalidations
3483
+ };
3484
+ }
3485
+ };
3486
+
3487
+ export { AtmosphereInvalidParameterError, AutoExposureCapabilityUnavailableError, AutoExposureInvalidParameterError, AutoExposureStageFailedError, AutoExposureStaleGenerationError, BarrelDistortionInvalidParameterError, COOKIE_MATRIX_BYTES, COOKIE_SLICE_CAPACITY, COOKIE_SLICE_SIZE, DEFAULT_MOTION_BLUR_PARAMS, DeviceScope, DynamicResolutionInvalidParameterError, DynamicResolutionRequiresTaaError, DynamicResolutionTimingUnavailableError, EXTENDED_LIGHTING_REQUIRED_SAMPLED_TEXTURES, EXTENDED_LIGHTING_TOPOLOGY, EnvironmentGenerationFailedError, EnvironmentSourceConflictError, EquirectProjectionFailedError, FXAA_POST_PROCESS_ID, FogCardinalityError, FrameReceiptStaleError, GPU_BUFFER_USAGE_COPY_DST, GPU_BUFFER_USAGE_COPY_SRC, GPU_BUFFER_USAGE_INDEX, GPU_BUFFER_USAGE_INDIRECT, GPU_BUFFER_USAGE_MAP_READ, GPU_BUFFER_USAGE_QUERY_RESOLVE, GPU_BUFFER_USAGE_STORAGE, GPU_BUFFER_USAGE_UNIFORM, GPU_BUFFER_USAGE_VERTEX, GPU_SHADER_STAGE_COMPUTE, GPU_SHADER_STAGE_FRAGMENT, GPU_SHADER_STAGE_VERTEX, GPU_TEXTURE_USAGE_COPY_DST, GPU_TEXTURE_USAGE_COPY_SRC, GPU_TEXTURE_USAGE_RENDER_ATTACHMENT, GPU_TEXTURE_USAGE_RENDER_ATTACHMENT_AND_TEXTURE_BINDING, GPU_TEXTURE_USAGE_STORAGE_BINDING, GPU_TEXTURE_USAGE_TEXTURE_BINDING, GpuDrivenPreparationError, IES_SLICE_CAPACITY, IES_SLICE_HEIGHT, IES_SLICE_WIDTH, InstanceBoundsCache, InstanceProjectionStore, InstanceTransformsError, LifecycleTransaction, MOTION_BLUR_PARAMS_BYTE_SIZE, MaterialSkinAttrMissingError, MotionBlurValidationError, ObservationUnavailableError, OwnerStageFailedError, PointShadowAtlasBoundsViolationError, PointShadowAtlasUninitializedError, PointsLinesBudgetExceededError, PointsLinesInvalidStyleError, PointsLinesMaterialUnsupportedError, PointsLinesPrepareFailedError, PointsLinesStyleUnsupportedError, PointsLinesTopologyMismatchError, RENDER_PHASE_CATALOG, RenderFeatureCapabilityMissingError, RenderFeatureDrawRecordingFailedError, RenderFeaturePreparationFailedError, RenderFeaturePreparedStateMismatchError, RenderFeatureRegistrationConflictError, RenderFeatureStageFailedError, RenderIntentInvalidError, RenderTargetCapabilityMissingError, RenderTargetDescriptorInvalidError, RenderTargetOperationFailedError, RenderTargetStateInvalidError, RendererContractFailureError, RendererOperationError, SHADOW_ATLAS_DEFAULT_FACE_SIZE, SHADOW_ATLAS_DEFAULT_LAYERS, SHADOW_CASTER_SHADER_ID, SKIN_MATERIAL_SHADER_ID, SPRITE_PASS_PER_INSTANCE_REGION_VARIANT_SET, STANDARD_OUTPUT_TRANSFORM_FEATURE_ID, SceneDataUnavailableError, ShadowAtlas, ShadowInvalidConfigError, SkinMaterialMismatchError, SkinPaletteOverflowError, StandardClusterIndexOverflowError, StandardClusterTransportUnavailableError, StandardLightBudgetExceededError, StandardProfileInvalidError, TaaCapsInsufficientError, TemporalFrameSubmitError, TransmissionCapabilityMissingError, VertexColorVariantConflictError, VideoUploadUnsupportedError, VolumeDensityShapeMismatchError, VolumeInvalidBoundsError, VolumeInvalidParametersError, VolumeOwnerConflictError, buildBindGroupLayoutDescriptor, buildGpuDrivenDraws, buildGpuDrivenPbrInstancesBindGroupLayout, buildGpuDrivenPbrPipelineLayout, buildGpuDrivenPbrSkinPipelineLayout, buildPbrMaterialUserRegionEntries, buildPbrPipelineLayouts, buildPbrSkinLayouts, buildSurfaceDirectInstancesBindGroupLayout, createAutoExposureError, createAutoExposureInspection, createHdrpBindGroupLayoutDescriptor, createHdrpSkinBindGroupLayoutDescriptor, createLightResourceUnavailable, createPbrSkinMeshBindGroupEntries, createRenderTargetMaterialSource, createVisibilityBudget, deriveExtendedLightingCapability, deriveInstancesUnionBounds, effectiveMotionBlurSampleCount, extendedLightingSampledTextureCapacityAvailable, fingerprintNumericArray, getOpaqueResourceIdentity, getTextureIdentity, gpuDrivenDrawKey, gpuDrivenMaterialArtifactKey, gpuDrivenShadowDrawKey, gpuDrivenSourceDrawItemIndex, hasRequiredVertexInputs, instanceCollectionCacheKey, instanceUploadRangesForResident, isCanonicalStandardPbrMaterialShader, isMotionBlurIntervalValid, isStandardPbrMaterialShader, isStandardPbrSkinMaterialShader, makeZeroCameraFallbackSnapshot, matchPass, materialBindGroupLayoutIdentity, motionBlurExposureScale, motionBlurSampleDelta, motionBlurTemporalDemand, pbrSkinMeshDynamicOffsets, physicalTextureFields, renderTargetMaterialSourceIdentity, resolveMotionBlurParams, resolvePipelineGroup2Contract, resolveRenderTargetMaterialSource, selectPasses, shadowCasterVariantSet, validateGraphTargetCaptureReadback, validateInstanceTransforms, validateMotionBlurParams, worldEntityKey };
3488
+ //# sourceMappingURL=chunk-2OZAS3WU.mjs.map
3489
+ //# sourceMappingURL=chunk-2OZAS3WU.mjs.map