@forgeax/engine-render 0.1.2

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 (1172) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +1019 -0
  3. package/dist/.tsbuildinfo +1 -0
  4. package/dist/__tests__/analytic-sky-contract.test.d.ts +2 -0
  5. package/dist/__tests__/analytic-sky-contract.test.d.ts.map +1 -0
  6. package/dist/__tests__/analytic-sky-falsify.test.d.ts +2 -0
  7. package/dist/__tests__/analytic-sky-falsify.test.d.ts.map +1 -0
  8. package/dist/__tests__/assets-runtime-handoff.integration.test.d.ts +2 -0
  9. package/dist/__tests__/assets-runtime-handoff.integration.test.d.ts.map +1 -0
  10. package/dist/__tests__/authoring-path.unit.test.d.ts +2 -0
  11. package/dist/__tests__/authoring-path.unit.test.d.ts.map +1 -0
  12. package/dist/__tests__/backend-selection-rhi-capture.test-d.d.ts +2 -0
  13. package/dist/__tests__/backend-selection-rhi-capture.test-d.d.ts.map +1 -0
  14. package/dist/__tests__/backend-selection.integration.test.d.ts +2 -0
  15. package/dist/__tests__/backend-selection.integration.test.d.ts.map +1 -0
  16. package/dist/__tests__/callback-inference.test-d.d.ts +2 -0
  17. package/dist/__tests__/callback-inference.test-d.d.ts.map +1 -0
  18. package/dist/__tests__/camera-temporal.test-d.d.ts +2 -0
  19. package/dist/__tests__/camera-temporal.test-d.d.ts.map +1 -0
  20. package/dist/__tests__/camera-temporal.test.d.ts +2 -0
  21. package/dist/__tests__/camera-temporal.test.d.ts.map +1 -0
  22. package/dist/__tests__/cluster-binner.test.d.ts +2 -0
  23. package/dist/__tests__/cluster-binner.test.d.ts.map +1 -0
  24. package/dist/__tests__/cluster-grid-default-surface.unit.test.d.ts +2 -0
  25. package/dist/__tests__/cluster-grid-default-surface.unit.test.d.ts.map +1 -0
  26. package/dist/__tests__/construct-renderer-identity.unit.test.d.ts +2 -0
  27. package/dist/__tests__/construct-renderer-identity.unit.test.d.ts.map +1 -0
  28. package/dist/__tests__/direct-extract-consumer-contract.test-d.d.ts +2 -0
  29. package/dist/__tests__/direct-extract-consumer-contract.test-d.d.ts.map +1 -0
  30. package/dist/__tests__/direct-light-snapshot.unit.test.d.ts +2 -0
  31. package/dist/__tests__/direct-light-snapshot.unit.test.d.ts.map +1 -0
  32. package/dist/__tests__/directional-shadow-probe-atlas-layout.unit.test.d.ts +2 -0
  33. package/dist/__tests__/directional-shadow-probe-atlas-layout.unit.test.d.ts.map +1 -0
  34. package/dist/__tests__/environment-inspection.test.d.ts +2 -0
  35. package/dist/__tests__/environment-inspection.test.d.ts.map +1 -0
  36. package/dist/__tests__/factory-contract.integration.test.d.ts +2 -0
  37. package/dist/__tests__/factory-contract.integration.test.d.ts.map +1 -0
  38. package/dist/__tests__/fallback-row-stride-surface.unit.test.d.ts +2 -0
  39. package/dist/__tests__/fallback-row-stride-surface.unit.test.d.ts.map +1 -0
  40. package/dist/__tests__/fog-ai-user.fixture.d.ts +2 -0
  41. package/dist/__tests__/fog-ai-user.fixture.d.ts.map +1 -0
  42. package/dist/__tests__/fog-custom-render-feature.fixture.d.ts +16 -0
  43. package/dist/__tests__/fog-custom-render-feature.fixture.d.ts.map +1 -0
  44. package/dist/__tests__/fog-custom-render-feature.integration.test.d.ts +2 -0
  45. package/dist/__tests__/fog-custom-render-feature.integration.test.d.ts.map +1 -0
  46. package/dist/__tests__/fog-inspection.integration.test.d.ts +2 -0
  47. package/dist/__tests__/fog-inspection.integration.test.d.ts.map +1 -0
  48. package/dist/__tests__/fog-owner-state.integration.test.d.ts +2 -0
  49. package/dist/__tests__/fog-owner-state.integration.test.d.ts.map +1 -0
  50. package/dist/__tests__/fog-pipeline-topology.integration.test.d.ts +2 -0
  51. package/dist/__tests__/fog-pipeline-topology.integration.test.d.ts.map +1 -0
  52. package/dist/__tests__/fog-public-surface.integration.test.d.ts +2 -0
  53. package/dist/__tests__/fog-public-surface.integration.test.d.ts.map +1 -0
  54. package/dist/__tests__/fog-ray-contract.integration.test.d.ts +2 -0
  55. package/dist/__tests__/fog-ray-contract.integration.test.d.ts.map +1 -0
  56. package/dist/__tests__/fog-source-absence.integration.test.d.ts +2 -0
  57. package/dist/__tests__/fog-source-absence.integration.test.d.ts.map +1 -0
  58. package/dist/__tests__/fog-temporal.integration.test.d.ts +2 -0
  59. package/dist/__tests__/fog-temporal.integration.test.d.ts.map +1 -0
  60. package/dist/__tests__/frame-chain.unit.test.d.ts +2 -0
  61. package/dist/__tests__/frame-chain.unit.test.d.ts.map +1 -0
  62. package/dist/__tests__/frame-observation.contract.test.d.ts +2 -0
  63. package/dist/__tests__/frame-observation.contract.test.d.ts.map +1 -0
  64. package/dist/__tests__/glyph-text-layout-recovery.unit.test.d.ts +2 -0
  65. package/dist/__tests__/glyph-text-layout-recovery.unit.test.d.ts.map +1 -0
  66. package/dist/__tests__/gpu-driven-indirect-raster-evidence.d.ts +6 -0
  67. package/dist/__tests__/gpu-driven-indirect-raster-evidence.d.ts.map +1 -0
  68. package/dist/__tests__/gpu-driven-indirect-raster.browser.test.d.ts +2 -0
  69. package/dist/__tests__/gpu-driven-indirect-raster.browser.test.d.ts.map +1 -0
  70. package/dist/__tests__/gpu-driven-indirect-raster.dawn.test.d.ts +2 -0
  71. package/dist/__tests__/gpu-driven-indirect-raster.dawn.test.d.ts.map +1 -0
  72. package/dist/__tests__/gpu-driven-production.integration.test.d.ts +2 -0
  73. package/dist/__tests__/gpu-driven-production.integration.test.d.ts.map +1 -0
  74. package/dist/__tests__/gpu-driven-scaling.unit.test.d.ts +2 -0
  75. package/dist/__tests__/gpu-driven-scaling.unit.test.d.ts.map +1 -0
  76. package/dist/__tests__/gpu-driven-view-gpu-evidence.d.ts +12 -0
  77. package/dist/__tests__/gpu-driven-view-gpu-evidence.d.ts.map +1 -0
  78. package/dist/__tests__/gpu-driven-view-graph.integration.test.d.ts +2 -0
  79. package/dist/__tests__/gpu-driven-view-graph.integration.test.d.ts.map +1 -0
  80. package/dist/__tests__/gpu-driven-view.browser.test.d.ts +2 -0
  81. package/dist/__tests__/gpu-driven-view.browser.test.d.ts.map +1 -0
  82. package/dist/__tests__/gpu-driven-view.dawn.test.d.ts +2 -0
  83. package/dist/__tests__/gpu-driven-view.dawn.test.d.ts.map +1 -0
  84. package/dist/__tests__/gpu-driven-view.unit.test.d.ts +2 -0
  85. package/dist/__tests__/gpu-driven-view.unit.test.d.ts.map +1 -0
  86. package/dist/__tests__/gpu-resource-store-stride.unit.test.d.ts +2 -0
  87. package/dist/__tests__/gpu-resource-store-stride.unit.test.d.ts.map +1 -0
  88. package/dist/__tests__/gpu-scene-field-type-owner.test-d.d.ts +2 -0
  89. package/dist/__tests__/gpu-scene-field-type-owner.test-d.d.ts.map +1 -0
  90. package/dist/__tests__/gpu-scene-render-graph-gpu.d.ts +7 -0
  91. package/dist/__tests__/gpu-scene-render-graph-gpu.d.ts.map +1 -0
  92. package/dist/__tests__/gpu-scene-render-graph.browser.test.d.ts +2 -0
  93. package/dist/__tests__/gpu-scene-render-graph.browser.test.d.ts.map +1 -0
  94. package/dist/__tests__/gpu-scene-render-graph.dawn.test.d.ts +2 -0
  95. package/dist/__tests__/gpu-scene-render-graph.dawn.test.d.ts.map +1 -0
  96. package/dist/__tests__/gpu-scene-schema.unit.test.d.ts +2 -0
  97. package/dist/__tests__/gpu-scene-schema.unit.test.d.ts.map +1 -0
  98. package/dist/__tests__/gpu-scene.dawn.test.d.ts +2 -0
  99. package/dist/__tests__/gpu-scene.dawn.test.d.ts.map +1 -0
  100. package/dist/__tests__/gpu-scene.unit.test.d.ts +2 -0
  101. package/dist/__tests__/gpu-scene.unit.test.d.ts.map +1 -0
  102. package/dist/__tests__/hdrp-pipeline.unit.test.d.ts +2 -0
  103. package/dist/__tests__/hdrp-pipeline.unit.test.d.ts.map +1 -0
  104. package/dist/__tests__/ibl/ibl-fallback.unit.test.d.ts +2 -0
  105. package/dist/__tests__/ibl/ibl-fallback.unit.test.d.ts.map +1 -0
  106. package/dist/__tests__/infinite-grid-no-vertex-probe.unit.test.d.ts +2 -0
  107. package/dist/__tests__/infinite-grid-no-vertex-probe.unit.test.d.ts.map +1 -0
  108. package/dist/__tests__/injection-kind-owner.test-d.d.ts +2 -0
  109. package/dist/__tests__/injection-kind-owner.test-d.d.ts.map +1 -0
  110. package/dist/__tests__/ktx2-basis-gpu-consumer.dawn.test.d.ts +2 -0
  111. package/dist/__tests__/ktx2-basis-gpu-consumer.dawn.test.d.ts.map +1 -0
  112. package/dist/__tests__/light-buffer-layout.unit.test.d.ts +2 -0
  113. package/dist/__tests__/light-buffer-layout.unit.test.d.ts.map +1 -0
  114. package/dist/__tests__/material-contract-inventory.unit.test.d.ts +2 -0
  115. package/dist/__tests__/material-contract-inventory.unit.test.d.ts.map +1 -0
  116. package/dist/__tests__/material-cooked-projection.unit.test.d.ts +2 -0
  117. package/dist/__tests__/material-cooked-projection.unit.test.d.ts.map +1 -0
  118. package/dist/__tests__/material-derived-error-stop-draw.integration.test.d.ts +2 -0
  119. package/dist/__tests__/material-derived-error-stop-draw.integration.test.d.ts.map +1 -0
  120. package/dist/__tests__/material-derived-payload.integration.test.d.ts +2 -0
  121. package/dist/__tests__/material-derived-payload.integration.test.d.ts.map +1 -0
  122. package/dist/__tests__/material-snapshot-mutation.integration.test.d.ts +2 -0
  123. package/dist/__tests__/material-snapshot-mutation.integration.test.d.ts.map +1 -0
  124. package/dist/__tests__/material-static-dynamic-route.unit.test.d.ts +2 -0
  125. package/dist/__tests__/material-static-dynamic-route.unit.test.d.ts.map +1 -0
  126. package/dist/__tests__/material-stride-surface.unit.test.d.ts +2 -0
  127. package/dist/__tests__/material-stride-surface.unit.test.d.ts.map +1 -0
  128. package/dist/__tests__/materials.unit.test.d.ts +2 -0
  129. package/dist/__tests__/materials.unit.test.d.ts.map +1 -0
  130. package/dist/__tests__/mesh-buffer-usage-surface.unit.test.d.ts +2 -0
  131. package/dist/__tests__/mesh-buffer-usage-surface.unit.test.d.ts.map +1 -0
  132. package/dist/__tests__/mesh-material-bindings.unit.test.d.ts +2 -0
  133. package/dist/__tests__/mesh-material-bindings.unit.test.d.ts.map +1 -0
  134. package/dist/__tests__/mesh-stride-surface.unit.test.d.ts +2 -0
  135. package/dist/__tests__/mesh-stride-surface.unit.test.d.ts.map +1 -0
  136. package/dist/__tests__/morph-culling-reentry.dawn.test.d.ts +2 -0
  137. package/dist/__tests__/morph-culling-reentry.dawn.test.d.ts.map +1 -0
  138. package/dist/__tests__/morph-feature-gpu-work.integration.test.d.ts +2 -0
  139. package/dist/__tests__/morph-feature-gpu-work.integration.test.d.ts.map +1 -0
  140. package/dist/__tests__/morph-visual-evidence.integration.test.d.ts +2 -0
  141. package/dist/__tests__/morph-visual-evidence.integration.test.d.ts.map +1 -0
  142. package/dist/__tests__/nineslice-handle-surface.unit.test.d.ts +2 -0
  143. package/dist/__tests__/nineslice-handle-surface.unit.test.d.ts.map +1 -0
  144. package/dist/__tests__/param-schema-projection-census.unit.test.d.ts +2 -0
  145. package/dist/__tests__/param-schema-projection-census.unit.test.d.ts.map +1 -0
  146. package/dist/__tests__/persistent-render-scene.unit.test.d.ts +2 -0
  147. package/dist/__tests__/persistent-render-scene.unit.test.d.ts.map +1 -0
  148. package/dist/__tests__/pipeline-error-policy-owner.unit.test.d.ts +2 -0
  149. package/dist/__tests__/pipeline-error-policy-owner.unit.test.d.ts.map +1 -0
  150. package/dist/__tests__/pipeline-pass-trace.test.d.ts +2 -0
  151. package/dist/__tests__/pipeline-pass-trace.test.d.ts.map +1 -0
  152. package/dist/__tests__/pipeline-stage-owner.test-d.d.ts +2 -0
  153. package/dist/__tests__/pipeline-stage-owner.test-d.d.ts.map +1 -0
  154. package/dist/__tests__/plugin.test.d.ts +2 -0
  155. package/dist/__tests__/plugin.test.d.ts.map +1 -0
  156. package/dist/__tests__/post-process-error-policy-owner.unit.test.d.ts +2 -0
  157. package/dist/__tests__/post-process-error-policy-owner.unit.test.d.ts.map +1 -0
  158. package/dist/__tests__/prepared-buffer-kind-owner.test-d.d.ts +2 -0
  159. package/dist/__tests__/prepared-buffer-kind-owner.test-d.d.ts.map +1 -0
  160. package/dist/__tests__/prepared-graphics-backend-matrix.unit.test.d.ts +2 -0
  161. package/dist/__tests__/prepared-graphics-backend-matrix.unit.test.d.ts.map +1 -0
  162. package/dist/__tests__/prepared-graphics-capability.unit.test.d.ts +2 -0
  163. package/dist/__tests__/prepared-graphics-capability.unit.test.d.ts.map +1 -0
  164. package/dist/__tests__/prepared-graphics-generation.unit.test.d.ts +2 -0
  165. package/dist/__tests__/prepared-graphics-generation.unit.test.d.ts.map +1 -0
  166. package/dist/__tests__/prepared-graphics-lifecycle.unit.test.d.ts +2 -0
  167. package/dist/__tests__/prepared-graphics-lifecycle.unit.test.d.ts.map +1 -0
  168. package/dist/__tests__/prepared-graphics-pipeline-warmup.unit.test.d.ts +2 -0
  169. package/dist/__tests__/prepared-graphics-pipeline-warmup.unit.test.d.ts.map +1 -0
  170. package/dist/__tests__/prepared-graphics-resolver-recording.unit.test.d.ts +2 -0
  171. package/dist/__tests__/prepared-graphics-resolver-recording.unit.test.d.ts.map +1 -0
  172. package/dist/__tests__/prepared-graphics-resolver.unit.test.d.ts +2 -0
  173. package/dist/__tests__/prepared-graphics-resolver.unit.test.d.ts.map +1 -0
  174. package/dist/__tests__/prepared-graphics-snapshot.unit.test.d.ts +2 -0
  175. package/dist/__tests__/prepared-graphics-snapshot.unit.test.d.ts.map +1 -0
  176. package/dist/__tests__/prepared-graphics-store.unit.test.d.ts +2 -0
  177. package/dist/__tests__/prepared-graphics-store.unit.test.d.ts.map +1 -0
  178. package/dist/__tests__/prepared-graphics-validation.unit.test.d.ts +2 -0
  179. package/dist/__tests__/prepared-graphics-validation.unit.test.d.ts.map +1 -0
  180. package/dist/__tests__/profiler-default-off.test.d.ts +2 -0
  181. package/dist/__tests__/profiler-default-off.test.d.ts.map +1 -0
  182. package/dist/__tests__/profiler-phase-catalog.test.d.ts +2 -0
  183. package/dist/__tests__/profiler-phase-catalog.test.d.ts.map +1 -0
  184. package/dist/__tests__/profiler-phase-integration.test.d.ts +2 -0
  185. package/dist/__tests__/profiler-phase-integration.test.d.ts.map +1 -0
  186. package/dist/__tests__/profiler-phase-token.test.d.ts +2 -0
  187. package/dist/__tests__/profiler-phase-token.test.d.ts.map +1 -0
  188. package/dist/__tests__/public-pipeline-id.test-d.d.ts +2 -0
  189. package/dist/__tests__/public-pipeline-id.test-d.d.ts.map +1 -0
  190. package/dist/__tests__/public-surface.test-d.d.ts +2 -0
  191. package/dist/__tests__/public-surface.test-d.d.ts.map +1 -0
  192. package/dist/__tests__/recover-error-policy-owner.unit.test.d.ts +2 -0
  193. package/dist/__tests__/recover-error-policy-owner.unit.test.d.ts.map +1 -0
  194. package/dist/__tests__/render-dispatch-membership.unit.test.d.ts +2 -0
  195. package/dist/__tests__/render-dispatch-membership.unit.test.d.ts.map +1 -0
  196. package/dist/__tests__/render-error-code-owner.test-d.d.ts +2 -0
  197. package/dist/__tests__/render-error-code-owner.test-d.d.ts.map +1 -0
  198. package/dist/__tests__/render-error-detail-ssot.test-d.d.ts +2 -0
  199. package/dist/__tests__/render-error-detail-ssot.test-d.d.ts.map +1 -0
  200. package/dist/__tests__/render-error-exhaustive.test-d.d.ts +2 -0
  201. package/dist/__tests__/render-error-exhaustive.test-d.d.ts.map +1 -0
  202. package/dist/__tests__/render-feature-assembly.test-d.d.ts +2 -0
  203. package/dist/__tests__/render-feature-assembly.test-d.d.ts.map +1 -0
  204. package/dist/__tests__/render-feature-construction.unit.test.d.ts +2 -0
  205. package/dist/__tests__/render-feature-construction.unit.test.d.ts.map +1 -0
  206. package/dist/__tests__/render-feature-context.test-d.d.ts +2 -0
  207. package/dist/__tests__/render-feature-context.test-d.d.ts.map +1 -0
  208. package/dist/__tests__/render-feature-contract.test-d.d.ts +2 -0
  209. package/dist/__tests__/render-feature-contract.test-d.d.ts.map +1 -0
  210. package/dist/__tests__/render-feature-diagnostics.unit.test.d.ts +2 -0
  211. package/dist/__tests__/render-feature-diagnostics.unit.test.d.ts.map +1 -0
  212. package/dist/__tests__/render-feature-docs.unit.test.d.ts +2 -0
  213. package/dist/__tests__/render-feature-docs.unit.test.d.ts.map +1 -0
  214. package/dist/__tests__/render-feature-error-code-owner.test-d.d.ts +2 -0
  215. package/dist/__tests__/render-feature-error-code-owner.test-d.d.ts.map +1 -0
  216. package/dist/__tests__/render-feature-errors.unit.test.d.ts +2 -0
  217. package/dist/__tests__/render-feature-errors.unit.test.d.ts.map +1 -0
  218. package/dist/__tests__/render-feature-gpu-buffer-usage-owner.test-d.d.ts +2 -0
  219. package/dist/__tests__/render-feature-gpu-buffer-usage-owner.test-d.d.ts.map +1 -0
  220. package/dist/__tests__/render-feature-gpu-work.integration.test.d.ts +2 -0
  221. package/dist/__tests__/render-feature-gpu-work.integration.test.d.ts.map +1 -0
  222. package/dist/__tests__/render-feature-graph.integration.test.d.ts +2 -0
  223. package/dist/__tests__/render-feature-graph.integration.test.d.ts.map +1 -0
  224. package/dist/__tests__/render-feature-graphics-staging.unit.test.d.ts +2 -0
  225. package/dist/__tests__/render-feature-graphics-staging.unit.test.d.ts.map +1 -0
  226. package/dist/__tests__/render-feature-order.unit.test.d.ts +2 -0
  227. package/dist/__tests__/render-feature-order.unit.test.d.ts.map +1 -0
  228. package/dist/__tests__/render-feature-prepared-diagnostics.unit.test.d.ts +2 -0
  229. package/dist/__tests__/render-feature-prepared-diagnostics.unit.test.d.ts.map +1 -0
  230. package/dist/__tests__/render-feature-prepared-errors.test-d.d.ts +2 -0
  231. package/dist/__tests__/render-feature-prepared-errors.test-d.d.ts.map +1 -0
  232. package/dist/__tests__/render-feature-prepared-graphics-docs.unit.test.d.ts +2 -0
  233. package/dist/__tests__/render-feature-prepared-graphics-docs.unit.test.d.ts.map +1 -0
  234. package/dist/__tests__/render-feature-prepared-graphics-isolation.unit.test.d.ts +2 -0
  235. package/dist/__tests__/render-feature-prepared-graphics-isolation.unit.test.d.ts.map +1 -0
  236. package/dist/__tests__/render-feature-prepared-graphics-negative.test-d.d.ts +2 -0
  237. package/dist/__tests__/render-feature-prepared-graphics-negative.test-d.d.ts.map +1 -0
  238. package/dist/__tests__/render-feature-prepared-graphics-recording.unit.test.d.ts +2 -0
  239. package/dist/__tests__/render-feature-prepared-graphics-recording.unit.test.d.ts.map +1 -0
  240. package/dist/__tests__/render-feature-prepared-graphics.test-d.d.ts +2 -0
  241. package/dist/__tests__/render-feature-prepared-graphics.test-d.d.ts.map +1 -0
  242. package/dist/__tests__/render-feature-prepared-graphics.unit.test.d.ts +2 -0
  243. package/dist/__tests__/render-feature-prepared-graphics.unit.test.d.ts.map +1 -0
  244. package/dist/__tests__/render-feature-public-surface.test-d.d.ts +2 -0
  245. package/dist/__tests__/render-feature-public-surface.test-d.d.ts.map +1 -0
  246. package/dist/__tests__/render-feature-retry.unit.test.d.ts +2 -0
  247. package/dist/__tests__/render-feature-retry.unit.test.d.ts.map +1 -0
  248. package/dist/__tests__/render-feature-scheduling.unit.test.d.ts +2 -0
  249. package/dist/__tests__/render-feature-scheduling.unit.test.d.ts.map +1 -0
  250. package/dist/__tests__/render-feature-stage-failed-policy-owner.unit.test.d.ts +2 -0
  251. package/dist/__tests__/render-feature-stage-failed-policy-owner.unit.test.d.ts.map +1 -0
  252. package/dist/__tests__/render-feature-stage-fault-recovery.unit.test.d.ts +2 -0
  253. package/dist/__tests__/render-feature-stage-fault-recovery.unit.test.d.ts.map +1 -0
  254. package/dist/__tests__/render-feature-staging.unit.test.d.ts +2 -0
  255. package/dist/__tests__/render-feature-staging.unit.test.d.ts.map +1 -0
  256. package/dist/__tests__/render-feature-visibility-context.test-d.d.ts +2 -0
  257. package/dist/__tests__/render-feature-visibility-context.test-d.d.ts.map +1 -0
  258. package/dist/__tests__/render-feature-visibility-context.unit.test.d.ts +2 -0
  259. package/dist/__tests__/render-feature-visibility-context.unit.test.d.ts.map +1 -0
  260. package/dist/__tests__/render-feature-zero-work.unit.test.d.ts +2 -0
  261. package/dist/__tests__/render-feature-zero-work.unit.test.d.ts.map +1 -0
  262. package/dist/__tests__/render-graph-compute-raster-gpu.d.ts +7 -0
  263. package/dist/__tests__/render-graph-compute-raster-gpu.d.ts.map +1 -0
  264. package/dist/__tests__/render-graph-compute-raster.browser.test.d.ts +2 -0
  265. package/dist/__tests__/render-graph-compute-raster.browser.test.d.ts.map +1 -0
  266. package/dist/__tests__/render-graph-compute-raster.dawn.test.d.ts +2 -0
  267. package/dist/__tests__/render-graph-compute-raster.dawn.test.d.ts.map +1 -0
  268. package/dist/__tests__/render-graph-hzb-gpu.d.ts +7 -0
  269. package/dist/__tests__/render-graph-hzb-gpu.d.ts.map +1 -0
  270. package/dist/__tests__/render-graph-hzb.browser.test.d.ts +2 -0
  271. package/dist/__tests__/render-graph-hzb.browser.test.d.ts.map +1 -0
  272. package/dist/__tests__/render-graph-hzb.dawn.test.d.ts +2 -0
  273. package/dist/__tests__/render-graph-hzb.dawn.test.d.ts.map +1 -0
  274. package/dist/__tests__/render-graph-primitives.unit.test.d.ts +2 -0
  275. package/dist/__tests__/render-graph-primitives.unit.test.d.ts.map +1 -0
  276. package/dist/__tests__/render-graph-storage-indirect-gpu.d.ts +12 -0
  277. package/dist/__tests__/render-graph-storage-indirect-gpu.d.ts.map +1 -0
  278. package/dist/__tests__/render-graph-storage-indirect.browser.test.d.ts +2 -0
  279. package/dist/__tests__/render-graph-storage-indirect.browser.test.d.ts.map +1 -0
  280. package/dist/__tests__/render-graph-storage-indirect.dawn.test.d.ts +2 -0
  281. package/dist/__tests__/render-graph-storage-indirect.dawn.test.d.ts.map +1 -0
  282. package/dist/__tests__/render-scene-projection.unit.test.d.ts +2 -0
  283. package/dist/__tests__/render-scene-projection.unit.test.d.ts.map +1 -0
  284. package/dist/__tests__/renderer-factory-material-contract.unit.test.d.ts +2 -0
  285. package/dist/__tests__/renderer-factory-material-contract.unit.test.d.ts.map +1 -0
  286. package/dist/__tests__/renderer-lifecycle.integration.test.d.ts +2 -0
  287. package/dist/__tests__/renderer-lifecycle.integration.test.d.ts.map +1 -0
  288. package/dist/__tests__/renderer-render-scene-public.test-d.d.ts +2 -0
  289. package/dist/__tests__/renderer-render-scene-public.test-d.d.ts.map +1 -0
  290. package/dist/__tests__/rhi-backend-package-boundary.unit.test.d.ts +2 -0
  291. package/dist/__tests__/rhi-backend-package-boundary.unit.test.d.ts.map +1 -0
  292. package/dist/__tests__/scene-temporal-coverage.unit.test.d.ts +2 -0
  293. package/dist/__tests__/scene-temporal-coverage.unit.test.d.ts.map +1 -0
  294. package/dist/__tests__/scriptable-pack-consumer.test-d.d.ts +2 -0
  295. package/dist/__tests__/scriptable-pack-consumer.test-d.d.ts.map +1 -0
  296. package/dist/__tests__/shader-stage-surface.unit.test.d.ts +2 -0
  297. package/dist/__tests__/shader-stage-surface.unit.test.d.ts.map +1 -0
  298. package/dist/__tests__/ssao-kernel-surface.unit.test.d.ts +2 -0
  299. package/dist/__tests__/ssao-kernel-surface.unit.test.d.ts.map +1 -0
  300. package/dist/__tests__/sun-snapshot-consumers.test.d.ts +2 -0
  301. package/dist/__tests__/sun-snapshot-consumers.test.d.ts.map +1 -0
  302. package/dist/__tests__/surface-backend-kind-owner.test-d.d.ts +2 -0
  303. package/dist/__tests__/surface-backend-kind-owner.test-d.d.ts.map +1 -0
  304. package/dist/__tests__/surface-configuration.unit.test.d.ts +2 -0
  305. package/dist/__tests__/surface-configuration.unit.test.d.ts.map +1 -0
  306. package/dist/__tests__/taa-history-store.unit.test.d.ts +2 -0
  307. package/dist/__tests__/taa-history-store.unit.test.d.ts.map +1 -0
  308. package/dist/__tests__/temporal-frame-transaction.integration.test.d.ts +2 -0
  309. package/dist/__tests__/temporal-frame-transaction.integration.test.d.ts.map +1 -0
  310. package/dist/__tests__/temporal-inspection.unit.test.d.ts +2 -0
  311. package/dist/__tests__/temporal-inspection.unit.test.d.ts.map +1 -0
  312. package/dist/__tests__/texture-usage-surface.unit.test.d.ts +2 -0
  313. package/dist/__tests__/texture-usage-surface.unit.test.d.ts.map +1 -0
  314. package/dist/__tests__/typed-pipeline-topology.unit.test.d.ts +2 -0
  315. package/dist/__tests__/typed-pipeline-topology.unit.test.d.ts.map +1 -0
  316. package/dist/__tests__/urp-pipeline-targets.unit.test.d.ts +2 -0
  317. package/dist/__tests__/urp-pipeline-targets.unit.test.d.ts.map +1 -0
  318. package/dist/__tests__/urp-pipeline.unit.test.d.ts +2 -0
  319. package/dist/__tests__/urp-pipeline.unit.test.d.ts.map +1 -0
  320. package/dist/__tests__/vertex-color-pipeline.unit.test.d.ts +2 -0
  321. package/dist/__tests__/vertex-color-pipeline.unit.test.d.ts.map +1 -0
  322. package/dist/__tests__/vertex-layout-consumer.unit.test.d.ts +2 -0
  323. package/dist/__tests__/vertex-layout-consumer.unit.test.d.ts.map +1 -0
  324. package/dist/__tests__/visibility-diagnostics.integration.test.d.ts +2 -0
  325. package/dist/__tests__/visibility-diagnostics.integration.test.d.ts.map +1 -0
  326. package/dist/__tests__/visibility-extract.integration.test.d.ts +2 -0
  327. package/dist/__tests__/visibility-extract.integration.test.d.ts.map +1 -0
  328. package/dist/__tests__/visibility-extract.perf.test.d.ts +2 -0
  329. package/dist/__tests__/visibility-extract.perf.test.d.ts.map +1 -0
  330. package/dist/__tests__/visibility-feature-dedup.integration.test.d.ts +2 -0
  331. package/dist/__tests__/visibility-feature-dedup.integration.test.d.ts.map +1 -0
  332. package/dist/__tests__/visibility-hidden-report.unit.test.d.ts +2 -0
  333. package/dist/__tests__/visibility-hidden-report.unit.test.d.ts.map +1 -0
  334. package/dist/__tests__/visibility-instances.integration.test.d.ts +2 -0
  335. package/dist/__tests__/visibility-instances.integration.test.d.ts.map +1 -0
  336. package/dist/__tests__/visibility-multi-world.integration.test.d.ts +2 -0
  337. package/dist/__tests__/visibility-multi-world.integration.test.d.ts.map +1 -0
  338. package/dist/__tests__/visibility-producer-matrix.integration.test.d.ts +2 -0
  339. package/dist/__tests__/visibility-producer-matrix.integration.test.d.ts.map +1 -0
  340. package/dist/__tests__/visibility-producer-matrix.unit.test.d.ts +2 -0
  341. package/dist/__tests__/visibility-producer-matrix.unit.test.d.ts.map +1 -0
  342. package/dist/__tests__/visibility-public-surface.test-d.d.ts +2 -0
  343. package/dist/__tests__/visibility-public-surface.test-d.d.ts.map +1 -0
  344. package/dist/__tests__/visibility-resolver.unit.test.d.ts +2 -0
  345. package/dist/__tests__/visibility-resolver.unit.test.d.ts.map +1 -0
  346. package/dist/__tests__/visibility-snapshot-contract.unit.test.d.ts +2 -0
  347. package/dist/__tests__/visibility-snapshot-contract.unit.test.d.ts.map +1 -0
  348. package/dist/__tests__/vocabulary.unit.test.d.ts +2 -0
  349. package/dist/__tests__/vocabulary.unit.test.d.ts.map +1 -0
  350. package/dist/assets/__tests__/asset-decoders.unit.test.d.ts +2 -0
  351. package/dist/assets/__tests__/asset-decoders.unit.test.d.ts.map +1 -0
  352. package/dist/assets/__tests__/mipmap-generator.unit.test.d.ts +2 -0
  353. package/dist/assets/__tests__/mipmap-generator.unit.test.d.ts.map +1 -0
  354. package/dist/assets/__tests__/render-asset-port.unit.test.d.ts +2 -0
  355. package/dist/assets/__tests__/render-asset-port.unit.test.d.ts.map +1 -0
  356. package/dist/assets/__tests__/resolve-render-asset.unit.test.d.ts +2 -0
  357. package/dist/assets/__tests__/resolve-render-asset.unit.test.d.ts.map +1 -0
  358. package/dist/assets/asset-decoders.d.ts +5 -0
  359. package/dist/assets/asset-decoders.d.ts.map +1 -0
  360. package/dist/assets/render-asset-port.d.ts +17 -0
  361. package/dist/assets/render-asset-port.d.ts.map +1 -0
  362. package/dist/assets/resolve-render-asset.d.ts +6 -0
  363. package/dist/assets/resolve-render-asset.d.ts.map +1 -0
  364. package/dist/authoring.d.ts +12 -0
  365. package/dist/authoring.d.ts.map +1 -0
  366. package/dist/authoring.mjs +5 -0
  367. package/dist/authoring.mjs.map +1 -0
  368. package/dist/chunk-33UF5SAO.mjs +7397 -0
  369. package/dist/chunk-33UF5SAO.mjs.map +1 -0
  370. package/dist/chunk-A5QCJSNL.mjs +29913 -0
  371. package/dist/chunk-A5QCJSNL.mjs.map +1 -0
  372. package/dist/chunk-JMSB7AR4.mjs +3 -0
  373. package/dist/chunk-JMSB7AR4.mjs.map +1 -0
  374. package/dist/chunk-LXNGO6AO.mjs +569 -0
  375. package/dist/chunk-LXNGO6AO.mjs.map +1 -0
  376. package/dist/chunk-QRXPSX4X.mjs +659 -0
  377. package/dist/chunk-QRXPSX4X.mjs.map +1 -0
  378. package/dist/chunk-YAKEQPWO.mjs +1439 -0
  379. package/dist/chunk-YAKEQPWO.mjs.map +1 -0
  380. package/dist/cluster-binner.d.ts +152 -0
  381. package/dist/cluster-binner.d.ts.map +1 -0
  382. package/dist/components/__tests__/atmosphere-red.test.d.ts +2 -0
  383. package/dist/components/__tests__/atmosphere-red.test.d.ts.map +1 -0
  384. package/dist/components/__tests__/atmosphere.test.d.ts +2 -0
  385. package/dist/components/__tests__/atmosphere.test.d.ts.map +1 -0
  386. package/dist/components/__tests__/fog.test-d.d.ts +2 -0
  387. package/dist/components/__tests__/fog.test-d.d.ts.map +1 -0
  388. package/dist/components/__tests__/fog.test.d.ts +2 -0
  389. package/dist/components/__tests__/fog.test.d.ts.map +1 -0
  390. package/dist/components/__tests__/schema-parity.unit.test.d.ts +2 -0
  391. package/dist/components/__tests__/schema-parity.unit.test.d.ts.map +1 -0
  392. package/dist/components/__tests__/visibility-schema.unit.test.d.ts +2 -0
  393. package/dist/components/__tests__/visibility-schema.unit.test.d.ts.map +1 -0
  394. package/dist/components/atmosphere.d.ts +18 -0
  395. package/dist/components/atmosphere.d.ts.map +1 -0
  396. package/dist/components/camera.d.ts +311 -0
  397. package/dist/components/camera.d.ts.map +1 -0
  398. package/dist/components/directional-light.d.ts +76 -0
  399. package/dist/components/directional-light.d.ts.map +1 -0
  400. package/dist/components/environment.d.ts +116 -0
  401. package/dist/components/environment.d.ts.map +1 -0
  402. package/dist/components/glyph-text.d.ts +26 -0
  403. package/dist/components/glyph-text.d.ts.map +1 -0
  404. package/dist/components/index.d.ts +22 -0
  405. package/dist/components/index.d.ts.map +1 -0
  406. package/dist/components/instances.d.ts +41 -0
  407. package/dist/components/instances.d.ts.map +1 -0
  408. package/dist/components/layer.d.ts +34 -0
  409. package/dist/components/layer.d.ts.map +1 -0
  410. package/dist/components/light-helpers.d.ts +53 -0
  411. package/dist/components/light-helpers.d.ts.map +1 -0
  412. package/dist/components/mesh-filter.d.ts +24 -0
  413. package/dist/components/mesh-filter.d.ts.map +1 -0
  414. package/dist/components/mesh-renderer.d.ts +33 -0
  415. package/dist/components/mesh-renderer.d.ts.map +1 -0
  416. package/dist/components/point-light-shadow.d.ts +27 -0
  417. package/dist/components/point-light-shadow.d.ts.map +1 -0
  418. package/dist/components/point-light.d.ts +35 -0
  419. package/dist/components/point-light.d.ts.map +1 -0
  420. package/dist/components/post-process-params.d.ts +5 -0
  421. package/dist/components/post-process-params.d.ts.map +1 -0
  422. package/dist/components/scene-instance.d.ts +140 -0
  423. package/dist/components/scene-instance.d.ts.map +1 -0
  424. package/dist/components/sort-key.d.ts +44 -0
  425. package/dist/components/sort-key.d.ts.map +1 -0
  426. package/dist/components/spot-light.d.ts +81 -0
  427. package/dist/components/spot-light.d.ts.map +1 -0
  428. package/dist/components/sprite-animation.d.ts +75 -0
  429. package/dist/components/sprite-animation.d.ts.map +1 -0
  430. package/dist/components/sprite-instances.d.ts +51 -0
  431. package/dist/components/sprite-instances.d.ts.map +1 -0
  432. package/dist/components/sprite-playback-mode.d.ts +37 -0
  433. package/dist/components/sprite-playback-mode.d.ts.map +1 -0
  434. package/dist/components/sprite-region-override.d.ts +47 -0
  435. package/dist/components/sprite-region-override.d.ts.map +1 -0
  436. package/dist/components/tile-layer.d.ts +101 -0
  437. package/dist/components/tile-layer.d.ts.map +1 -0
  438. package/dist/components/tilemap.d.ts +25 -0
  439. package/dist/components/tilemap.d.ts.map +1 -0
  440. package/dist/components/visibility.d.ts +22 -0
  441. package/dist/components/visibility.d.ts.map +1 -0
  442. package/dist/construct-renderer.d.ts +2 -0
  443. package/dist/construct-renderer.d.ts.map +1 -0
  444. package/dist/construct-renderer.mjs +6 -0
  445. package/dist/construct-renderer.mjs.map +1 -0
  446. package/dist/debug-draw-glue.d.ts +56 -0
  447. package/dist/debug-draw-glue.d.ts.map +1 -0
  448. package/dist/deferred-lighting.d.ts +13 -0
  449. package/dist/deferred-lighting.d.ts.map +1 -0
  450. package/dist/dynamic-texture-store.d.ts +42 -0
  451. package/dist/dynamic-texture-store.d.ts.map +1 -0
  452. package/dist/engine-metrics.d.ts +23 -0
  453. package/dist/engine-metrics.d.ts.map +1 -0
  454. package/dist/environment/__tests__/failure-injection.test.d.ts +2 -0
  455. package/dist/environment/__tests__/failure-injection.test.d.ts.map +1 -0
  456. package/dist/environment/__tests__/generation-red.test.d.ts +2 -0
  457. package/dist/environment/__tests__/generation-red.test.d.ts.map +1 -0
  458. package/dist/environment/__tests__/generation.test.d.ts +2 -0
  459. package/dist/environment/__tests__/generation.test.d.ts.map +1 -0
  460. package/dist/environment/__tests__/graph-transaction.test.d.ts +2 -0
  461. package/dist/environment/__tests__/graph-transaction.test.d.ts.map +1 -0
  462. package/dist/environment/__tests__/inspection-red.test.d.ts +2 -0
  463. package/dist/environment/__tests__/inspection-red.test.d.ts.map +1 -0
  464. package/dist/environment/__tests__/lifecycle-evidence.test.d.ts +2 -0
  465. package/dist/environment/__tests__/lifecycle-evidence.test.d.ts.map +1 -0
  466. package/dist/environment/__tests__/pipeline-topology.test.d.ts +2 -0
  467. package/dist/environment/__tests__/pipeline-topology.test.d.ts.map +1 -0
  468. package/dist/environment/__tests__/readiness.test.d.ts +2 -0
  469. package/dist/environment/__tests__/readiness.test.d.ts.map +1 -0
  470. package/dist/environment/__tests__/recovery.test.d.ts +2 -0
  471. package/dist/environment/__tests__/recovery.test.d.ts.map +1 -0
  472. package/dist/environment/__tests__/resize-dispose.test.d.ts +2 -0
  473. package/dist/environment/__tests__/resize-dispose.test.d.ts.map +1 -0
  474. package/dist/environment/__tests__/signature-red.test.d.ts +2 -0
  475. package/dist/environment/__tests__/signature-red.test.d.ts.map +1 -0
  476. package/dist/environment/__tests__/signature.test.d.ts +2 -0
  477. package/dist/environment/__tests__/signature.test.d.ts.map +1 -0
  478. package/dist/environment/descriptors.d.ts +2 -0
  479. package/dist/environment/descriptors.d.ts.map +1 -0
  480. package/dist/environment/extracted-environment.d.ts +53 -0
  481. package/dist/environment/extracted-environment.d.ts.map +1 -0
  482. package/dist/environment/generation.d.ts +62 -0
  483. package/dist/environment/generation.d.ts.map +1 -0
  484. package/dist/environment/gpu-bundle.d.ts +23 -0
  485. package/dist/environment/gpu-bundle.d.ts.map +1 -0
  486. package/dist/environment/graph.d.ts +108 -0
  487. package/dist/environment/graph.d.ts.map +1 -0
  488. package/dist/environment/inspection.d.ts +48 -0
  489. package/dist/environment/inspection.d.ts.map +1 -0
  490. package/dist/environment/lifecycle.d.ts +22 -0
  491. package/dist/environment/lifecycle.d.ts.map +1 -0
  492. package/dist/environment/readiness.d.ts +29 -0
  493. package/dist/environment/readiness.d.ts.map +1 -0
  494. package/dist/environment/signature.d.ts +70 -0
  495. package/dist/environment/signature.d.ts.map +1 -0
  496. package/dist/errors/ecs-validation.d.ts +3 -0
  497. package/dist/errors/ecs-validation.d.ts.map +1 -0
  498. package/dist/errors/index.d.ts +4 -0
  499. package/dist/errors/index.d.ts.map +1 -0
  500. package/dist/errors/recover.d.ts +78 -0
  501. package/dist/errors/recover.d.ts.map +1 -0
  502. package/dist/errors/render.d.ts +633 -0
  503. package/dist/errors/render.d.ts.map +1 -0
  504. package/dist/extract/__tests__/directional-csm-domain.unit.test.d.ts +2 -0
  505. package/dist/extract/__tests__/directional-csm-domain.unit.test.d.ts.map +1 -0
  506. package/dist/extract/__tests__/environment-source.test.d.ts +2 -0
  507. package/dist/extract/__tests__/environment-source.test.d.ts.map +1 -0
  508. package/dist/extract/__tests__/schema-readers.unit.test.d.ts +2 -0
  509. package/dist/extract/__tests__/schema-readers.unit.test.d.ts.map +1 -0
  510. package/dist/extract/directional-csm.d.ts +129 -0
  511. package/dist/extract/directional-csm.d.ts.map +1 -0
  512. package/dist/extract/index.d.ts +5 -0
  513. package/dist/extract/index.d.ts.map +1 -0
  514. package/dist/extract/material-interface.d.ts +56 -0
  515. package/dist/extract/material-interface.d.ts.map +1 -0
  516. package/dist/extract/schema-readers.d.ts +20 -0
  517. package/dist/extract/schema-readers.d.ts.map +1 -0
  518. package/dist/extract/visibility.d.ts +26 -0
  519. package/dist/extract/visibility.d.ts.map +1 -0
  520. package/dist/features/graph-contribution.d.ts +64 -0
  521. package/dist/features/graph-contribution.d.ts.map +1 -0
  522. package/dist/features/host.d.ts +100 -0
  523. package/dist/features/host.d.ts.map +1 -0
  524. package/dist/features/index.d.ts +21 -0
  525. package/dist/features/index.d.ts.map +1 -0
  526. package/dist/features/morph/index.d.ts +3 -0
  527. package/dist/features/morph/index.d.ts.map +1 -0
  528. package/dist/features/morph/morph-bounds.d.ts +42 -0
  529. package/dist/features/morph/morph-bounds.d.ts.map +1 -0
  530. package/dist/features/morph/morph-feature.d.ts +45 -0
  531. package/dist/features/morph/morph-feature.d.ts.map +1 -0
  532. package/dist/features/prepared-gpu-work.d.ts +113 -0
  533. package/dist/features/prepared-gpu-work.d.ts.map +1 -0
  534. package/dist/features/prepared-graphics-store.d.ts +65 -0
  535. package/dist/features/prepared-graphics-store.d.ts.map +1 -0
  536. package/dist/features/prepared-graphics.d.ts +225 -0
  537. package/dist/features/prepared-graphics.d.ts.map +1 -0
  538. package/dist/features/render-graph-compute.d.ts +13 -0
  539. package/dist/features/render-graph-compute.d.ts.map +1 -0
  540. package/dist/features/render-graph-contribution.d.ts +15 -0
  541. package/dist/features/render-graph-contribution.d.ts.map +1 -0
  542. package/dist/features/render-graph-raster.d.ts +34 -0
  543. package/dist/features/render-graph-raster.d.ts.map +1 -0
  544. package/dist/features/render-graph-resources.d.ts +11 -0
  545. package/dist/features/render-graph-resources.d.ts.map +1 -0
  546. package/dist/features/scene-temporal.d.ts +45 -0
  547. package/dist/features/scene-temporal.d.ts.map +1 -0
  548. package/dist/features/taa-resolve.d.ts +21 -0
  549. package/dist/features/taa-resolve.d.ts.map +1 -0
  550. package/dist/features/targets.d.ts +32 -0
  551. package/dist/features/targets.d.ts.map +1 -0
  552. package/dist/features/types.d.ts +247 -0
  553. package/dist/features/types.d.ts.map +1 -0
  554. package/dist/frame-chain.d.ts +14 -0
  555. package/dist/frame-chain.d.ts.map +1 -0
  556. package/dist/fullscreen-post-process-pass.d.ts +178 -0
  557. package/dist/fullscreen-post-process-pass.d.ts.map +1 -0
  558. package/dist/glyph-text-layout-system.d.ts +18 -0
  559. package/dist/glyph-text-layout-system.d.ts.map +1 -0
  560. package/dist/gpu-driven/batch-topology.d.ts +124 -0
  561. package/dist/gpu-driven/batch-topology.d.ts.map +1 -0
  562. package/dist/gpu-driven/production-raster.d.ts +150 -0
  563. package/dist/gpu-driven/production-raster.d.ts.map +1 -0
  564. package/dist/gpu-driven/view-gpu.d.ts +141 -0
  565. package/dist/gpu-driven/view-gpu.d.ts.map +1 -0
  566. package/dist/gpu-driven/view-reference.d.ts +15 -0
  567. package/dist/gpu-driven/view-reference.d.ts.map +1 -0
  568. package/dist/gpu-resource-store.d.ts +294 -0
  569. package/dist/gpu-resource-store.d.ts.map +1 -0
  570. package/dist/gpu-resource.d.ts +73 -0
  571. package/dist/gpu-resource.d.ts.map +1 -0
  572. package/dist/gpu-scene-schema.d.ts +171 -0
  573. package/dist/gpu-scene-schema.d.ts.map +1 -0
  574. package/dist/gpu-scene.d.ts +81 -0
  575. package/dist/gpu-scene.d.ts.map +1 -0
  576. package/dist/gpu-stage.d.ts +4 -0
  577. package/dist/gpu-stage.d.ts.map +1 -0
  578. package/dist/gpu-texture-usage.d.ts +6 -0
  579. package/dist/gpu-texture-usage.d.ts.map +1 -0
  580. package/dist/gpu-usage.d.ts +9 -0
  581. package/dist/gpu-usage.d.ts.map +1 -0
  582. package/dist/hdrp-buffers.d.ts +213 -0
  583. package/dist/hdrp-buffers.d.ts.map +1 -0
  584. package/dist/hdrp-cluster-membership.d.ts +2 -0
  585. package/dist/hdrp-cluster-membership.d.ts.map +1 -0
  586. package/dist/hdrp-pipeline.d.ts +36 -0
  587. package/dist/hdrp-pipeline.d.ts.map +1 -0
  588. package/dist/ibl/IblPipelineCache.d.ts +274 -0
  589. package/dist/ibl/IblPipelineCache.d.ts.map +1 -0
  590. package/dist/ibl/cubemap-projection.d.ts +23 -0
  591. package/dist/ibl/cubemap-projection.d.ts.map +1 -0
  592. package/dist/ibl/face-uniforms.d.ts +65 -0
  593. package/dist/ibl/face-uniforms.d.ts.map +1 -0
  594. package/dist/ibl/skylight-bind-group.d.ts +130 -0
  595. package/dist/ibl/skylight-bind-group.d.ts.map +1 -0
  596. package/dist/index.d.ts +57 -0
  597. package/dist/index.d.ts.map +1 -0
  598. package/dist/index.mjs +5 -0
  599. package/dist/index.mjs.map +1 -0
  600. package/dist/instance-buffer-cache.d.ts +59 -0
  601. package/dist/instance-buffer-cache.d.ts.map +1 -0
  602. package/dist/internal.d.ts +74 -0
  603. package/dist/internal.d.ts.map +1 -0
  604. package/dist/internal.mjs +45 -0
  605. package/dist/internal.mjs.map +1 -0
  606. package/dist/lifecycle.d.ts +28 -0
  607. package/dist/lifecycle.d.ts.map +1 -0
  608. package/dist/light-buffer-layout.d.ts +164 -0
  609. package/dist/light-buffer-layout.d.ts.map +1 -0
  610. package/dist/materials.d.ts +50 -0
  611. package/dist/materials.d.ts.map +1 -0
  612. package/dist/mesh-material-bindings.d.ts +44 -0
  613. package/dist/mesh-material-bindings.d.ts.map +1 -0
  614. package/dist/mesh-update-errors.d.ts +71 -0
  615. package/dist/mesh-update-errors.d.ts.map +1 -0
  616. package/dist/mipmap-generator.d.ts +39 -0
  617. package/dist/mipmap-generator.d.ts.map +1 -0
  618. package/dist/param-schema-projection-census.d.ts +18 -0
  619. package/dist/param-schema-projection-census.d.ts.map +1 -0
  620. package/dist/pbr-pipeline.d.ts +253 -0
  621. package/dist/pbr-pipeline.d.ts.map +1 -0
  622. package/dist/persistent-render-scene.d.ts +158 -0
  623. package/dist/persistent-render-scene.d.ts.map +1 -0
  624. package/dist/pipeline/index.d.ts +11 -0
  625. package/dist/pipeline/index.d.ts.map +1 -0
  626. package/dist/pipeline-builder.d.ts +122 -0
  627. package/dist/pipeline-builder.d.ts.map +1 -0
  628. package/dist/pipeline-errors.d.ts +110 -0
  629. package/dist/pipeline-errors.d.ts.map +1 -0
  630. package/dist/pipeline-spec.d.ts +506 -0
  631. package/dist/pipeline-spec.d.ts.map +1 -0
  632. package/dist/plugin.d.ts +17 -0
  633. package/dist/plugin.d.ts.map +1 -0
  634. package/dist/post-process-errors.d.ts +182 -0
  635. package/dist/post-process-errors.d.ts.map +1 -0
  636. package/dist/prepare/__tests__/schema-readers.unit.test.d.ts +2 -0
  637. package/dist/prepare/__tests__/schema-readers.unit.test.d.ts.map +1 -0
  638. package/dist/prepare/index.d.ts +4 -0
  639. package/dist/prepare/index.d.ts.map +1 -0
  640. package/dist/prepare/prepared-graphics-resolver.d.ts +62 -0
  641. package/dist/prepare/prepared-graphics-resolver.d.ts.map +1 -0
  642. package/dist/prepare/schema-readers.d.ts +11 -0
  643. package/dist/prepare/schema-readers.d.ts.map +1 -0
  644. package/dist/record/__tests__/environment-record.test.d.ts +2 -0
  645. package/dist/record/__tests__/environment-record.test.d.ts.map +1 -0
  646. package/dist/record/__tests__/frame-targets.unit.test.d.ts +2 -0
  647. package/dist/record/__tests__/frame-targets.unit.test.d.ts.map +1 -0
  648. package/dist/record/__tests__/material-bg-cache.unit.test.d.ts +2 -0
  649. package/dist/record/__tests__/material-bg-cache.unit.test.d.ts.map +1 -0
  650. package/dist/record/__tests__/material-slot-plan.unit.test.d.ts +2 -0
  651. package/dist/record/__tests__/material-slot-plan.unit.test.d.ts.map +1 -0
  652. package/dist/record/__tests__/membership-timing.unit.test.d.ts +2 -0
  653. package/dist/record/__tests__/membership-timing.unit.test.d.ts.map +1 -0
  654. package/dist/record/__tests__/render-submission.integration.test.d.ts +2 -0
  655. package/dist/record/__tests__/render-submission.integration.test.d.ts.map +1 -0
  656. package/dist/record/__tests__/render-submission.perf.test.d.ts +2 -0
  657. package/dist/record/__tests__/render-submission.perf.test.d.ts.map +1 -0
  658. package/dist/record/__tests__/shadow-submit-mode.unit.test.d.ts +2 -0
  659. package/dist/record/__tests__/shadow-submit-mode.unit.test.d.ts.map +1 -0
  660. package/dist/record/__tests__/video-texture-view.unit.test.d.ts +2 -0
  661. package/dist/record/__tests__/video-texture-view.unit.test.d.ts.map +1 -0
  662. package/dist/record/__tests__/view-ubo-layout.unit.test.d.ts +2 -0
  663. package/dist/record/__tests__/view-ubo-layout.unit.test.d.ts.map +1 -0
  664. package/dist/record/frame-lighting.d.ts +187 -0
  665. package/dist/record/frame-lighting.d.ts.map +1 -0
  666. package/dist/record/frame-observation.d.ts +38 -0
  667. package/dist/record/frame-observation.d.ts.map +1 -0
  668. package/dist/record/frame-snapshot.d.ts +429 -0
  669. package/dist/record/frame-snapshot.d.ts.map +1 -0
  670. package/dist/record/frame-targets.d.ts +53 -0
  671. package/dist/record/frame-targets.d.ts.map +1 -0
  672. package/dist/record/frame.d.ts +59 -0
  673. package/dist/record/frame.d.ts.map +1 -0
  674. package/dist/record/helpers.d.ts +101 -0
  675. package/dist/record/helpers.d.ts.map +1 -0
  676. package/dist/record/index.d.ts +15 -0
  677. package/dist/record/index.d.ts.map +1 -0
  678. package/dist/record/main-pass-geometry.d.ts +20 -0
  679. package/dist/record/main-pass-geometry.d.ts.map +1 -0
  680. package/dist/record/main-pass-material.d.ts +173 -0
  681. package/dist/record/main-pass-material.d.ts.map +1 -0
  682. package/dist/record/main-pass-skin.d.ts +46 -0
  683. package/dist/record/main-pass-skin.d.ts.map +1 -0
  684. package/dist/record/main-pass-sprite-draws.d.ts +18 -0
  685. package/dist/record/main-pass-sprite-draws.d.ts.map +1 -0
  686. package/dist/record/main-pass-sprite.d.ts +69 -0
  687. package/dist/record/main-pass-sprite.d.ts.map +1 -0
  688. package/dist/record/main-pass.d.ts +20 -0
  689. package/dist/record/main-pass.d.ts.map +1 -0
  690. package/dist/record/material-payload.d.ts +43 -0
  691. package/dist/record/material-payload.d.ts.map +1 -0
  692. package/dist/record/material-slot-plan.d.ts +26 -0
  693. package/dist/record/material-slot-plan.d.ts.map +1 -0
  694. package/dist/record/membership-timing.d.ts +232 -0
  695. package/dist/record/membership-timing.d.ts.map +1 -0
  696. package/dist/record/mesh-ssbo.d.ts +173 -0
  697. package/dist/record/mesh-ssbo.d.ts.map +1 -0
  698. package/dist/record/shadow-caster-uniform.d.ts +8 -0
  699. package/dist/record/shadow-caster-uniform.d.ts.map +1 -0
  700. package/dist/record/shadow-pass.d.ts +125 -0
  701. package/dist/record/shadow-pass.d.ts.map +1 -0
  702. package/dist/record/shadow-submit-mode.d.ts +66 -0
  703. package/dist/record/shadow-submit-mode.d.ts.map +1 -0
  704. package/dist/record/skybox-post-pass.d.ts +33 -0
  705. package/dist/record/skybox-post-pass.d.ts.map +1 -0
  706. package/dist/record/typed-frame-graph.d.ts +13 -0
  707. package/dist/record/typed-frame-graph.d.ts.map +1 -0
  708. package/dist/record/view-ubo.d.ts +39 -0
  709. package/dist/record/view-ubo.d.ts.map +1 -0
  710. package/dist/render-data.d.ts +143 -0
  711. package/dist/render-data.d.ts.map +1 -0
  712. package/dist/render-dispatch-membership.d.ts +47 -0
  713. package/dist/render-dispatch-membership.d.ts.map +1 -0
  714. package/dist/render-graph-primitives.d.ts +424 -0
  715. package/dist/render-graph-primitives.d.ts.map +1 -0
  716. package/dist/render-pipeline-context.d.ts +289 -0
  717. package/dist/render-pipeline-context.d.ts.map +1 -0
  718. package/dist/render-pipeline-target.d.ts +16 -0
  719. package/dist/render-pipeline-target.d.ts.map +1 -0
  720. package/dist/render-pipeline.d.ts +149 -0
  721. package/dist/render-pipeline.d.ts.map +1 -0
  722. package/dist/render-scene-projection.d.ts +174 -0
  723. package/dist/render-scene-projection.d.ts.map +1 -0
  724. package/dist/render-system-extract.d.ts +1096 -0
  725. package/dist/render-system-extract.d.ts.map +1 -0
  726. package/dist/render-system-fold.d.ts +266 -0
  727. package/dist/render-system-fold.d.ts.map +1 -0
  728. package/dist/render-system.d.ts +814 -0
  729. package/dist/render-system.d.ts.map +1 -0
  730. package/dist/renderer/asset-service.d.ts +10 -0
  731. package/dist/renderer/asset-service.d.ts.map +1 -0
  732. package/dist/renderer/backend-selection.d.ts +26 -0
  733. package/dist/renderer/backend-selection.d.ts.map +1 -0
  734. package/dist/renderer/environment-classify.d.ts +6 -0
  735. package/dist/renderer/environment-classify.d.ts.map +1 -0
  736. package/dist/renderer/environment-error.d.ts +13 -0
  737. package/dist/renderer/environment-error.d.ts.map +1 -0
  738. package/dist/renderer/material/assembly.d.ts +22 -0
  739. package/dist/renderer/material/assembly.d.ts.map +1 -0
  740. package/dist/renderer/material/pipeline-projection.d.ts +91 -0
  741. package/dist/renderer/material/pipeline-projection.d.ts.map +1 -0
  742. package/dist/renderer/renderer-factory.d.ts +283 -0
  743. package/dist/renderer/renderer-factory.d.ts.map +1 -0
  744. package/dist/renderer.d.ts +771 -0
  745. package/dist/renderer.d.ts.map +1 -0
  746. package/dist/scene-instances/post-spawn-resolve-joints.d.ts +33 -0
  747. package/dist/scene-instances/post-spawn-resolve-joints.d.ts.map +1 -0
  748. package/dist/scene-utils/collect-subtree.d.ts +11 -0
  749. package/dist/scene-utils/collect-subtree.d.ts.map +1 -0
  750. package/dist/shadow-atlas.d.ts +117 -0
  751. package/dist/shadow-atlas.d.ts.map +1 -0
  752. package/dist/ssao-buffers.d.ts +31 -0
  753. package/dist/ssao-buffers.d.ts.map +1 -0
  754. package/dist/ssao-config.d.ts +28 -0
  755. package/dist/ssao-config.d.ts.map +1 -0
  756. package/dist/ssao-data.d.ts +34 -0
  757. package/dist/ssao-data.d.ts.map +1 -0
  758. package/dist/surface-format.d.ts +10 -0
  759. package/dist/surface-format.d.ts.map +1 -0
  760. package/dist/systems/active-camera.d.ts +53 -0
  761. package/dist/systems/active-camera.d.ts.map +1 -0
  762. package/dist/systems/pass-selector.d.ts +24 -0
  763. package/dist/systems/pass-selector.d.ts.map +1 -0
  764. package/dist/systems/skin-palette-allocator.d.ts +51 -0
  765. package/dist/systems/skin-palette-allocator.d.ts.map +1 -0
  766. package/dist/systems/transparent-sort-config.d.ts +91 -0
  767. package/dist/systems/transparent-sort-config.d.ts.map +1 -0
  768. package/dist/taa-history-store.d.ts +88 -0
  769. package/dist/taa-history-store.d.ts.map +1 -0
  770. package/dist/temporal-coverage.d.ts +35 -0
  771. package/dist/temporal-coverage.d.ts.map +1 -0
  772. package/dist/temporal-frame-transaction.d.ts +92 -0
  773. package/dist/temporal-frame-transaction.d.ts.map +1 -0
  774. package/dist/temporal-inspection.d.ts +57 -0
  775. package/dist/temporal-inspection.d.ts.map +1 -0
  776. package/dist/temporal-view.d.ts +43 -0
  777. package/dist/temporal-view.d.ts.map +1 -0
  778. package/dist/tilemap/resolve-tileset-runtime.d.ts +23 -0
  779. package/dist/tilemap/resolve-tileset-runtime.d.ts.map +1 -0
  780. package/dist/tilemap-chunk-extract-system.d.ts +142 -0
  781. package/dist/tilemap-chunk-extract-system.d.ts.map +1 -0
  782. package/dist/typed-render-graph-primitives.d.ts +59 -0
  783. package/dist/typed-render-graph-primitives.d.ts.map +1 -0
  784. package/dist/typed-shadow-passes.d.ts +11 -0
  785. package/dist/typed-shadow-passes.d.ts.map +1 -0
  786. package/dist/urp-pipeline.d.ts +4 -0
  787. package/dist/urp-pipeline.d.ts.map +1 -0
  788. package/package.json +94 -0
  789. package/src/__tests__/analytic-sky-contract.test.ts +27 -0
  790. package/src/__tests__/analytic-sky-falsify-carriers.mjs +43 -0
  791. package/src/__tests__/analytic-sky-falsify.test.ts +94 -0
  792. package/src/__tests__/assets-runtime-handoff.integration.test.ts +36 -0
  793. package/src/__tests__/authoring-path.unit.test.ts +14 -0
  794. package/src/__tests__/backend-selection-rhi-capture.test-d.ts +21 -0
  795. package/src/__tests__/backend-selection.integration.test.ts +11 -0
  796. package/src/__tests__/callback-inference.test-d.ts +5 -0
  797. package/src/__tests__/camera-temporal.test-d.ts +8 -0
  798. package/src/__tests__/camera-temporal.test.ts +188 -0
  799. package/src/__tests__/cluster-binner.test.ts +272 -0
  800. package/src/__tests__/cluster-grid-default-surface.unit.test.ts +17 -0
  801. package/src/__tests__/construct-renderer-identity.unit.test.ts +10 -0
  802. package/src/__tests__/direct-extract-consumer-contract.test-d.ts +34 -0
  803. package/src/__tests__/direct-light-snapshot.unit.test.ts +71 -0
  804. package/src/__tests__/directional-shadow-probe-atlas-layout.unit.test.ts +18 -0
  805. package/src/__tests__/environment-inspection.test.ts +45 -0
  806. package/src/__tests__/factory-contract.integration.test.ts +331 -0
  807. package/src/__tests__/fallback-row-stride-surface.unit.test.ts +18 -0
  808. package/src/__tests__/fog-ai-user.fixture.ts +350 -0
  809. package/src/__tests__/fog-custom-render-feature.fixture.ts +33 -0
  810. package/src/__tests__/fog-custom-render-feature.integration.test.ts +76 -0
  811. package/src/__tests__/fog-inspection.integration.test.ts +127 -0
  812. package/src/__tests__/fog-owner-state.integration.test.ts +112 -0
  813. package/src/__tests__/fog-pipeline-topology.integration.test.ts +93 -0
  814. package/src/__tests__/fog-public-surface.integration.test.ts +60 -0
  815. package/src/__tests__/fog-ray-contract.integration.test.ts +73 -0
  816. package/src/__tests__/fog-source-absence.integration.test.ts +51 -0
  817. package/src/__tests__/fog-temporal.integration.test.ts +115 -0
  818. package/src/__tests__/frame-chain.unit.test.ts +26 -0
  819. package/src/__tests__/frame-observation.contract.test.ts +103 -0
  820. package/src/__tests__/glyph-text-layout-recovery.unit.test.ts +172 -0
  821. package/src/__tests__/gpu-driven-indirect-raster-evidence.ts +347 -0
  822. package/src/__tests__/gpu-driven-indirect-raster.browser.test.ts +12 -0
  823. package/src/__tests__/gpu-driven-indirect-raster.dawn.test.ts +16 -0
  824. package/src/__tests__/gpu-driven-production.integration.test.ts +609 -0
  825. package/src/__tests__/gpu-driven-scaling.unit.test.ts +90 -0
  826. package/src/__tests__/gpu-driven-view-gpu-evidence.ts +192 -0
  827. package/src/__tests__/gpu-driven-view-graph.integration.test.ts +128 -0
  828. package/src/__tests__/gpu-driven-view.browser.test.ts +19 -0
  829. package/src/__tests__/gpu-driven-view.dawn.test.ts +17 -0
  830. package/src/__tests__/gpu-driven-view.unit.test.ts +455 -0
  831. package/src/__tests__/gpu-resource-store-stride.unit.test.ts +59 -0
  832. package/src/__tests__/gpu-scene-field-type-owner.test-d.ts +27 -0
  833. package/src/__tests__/gpu-scene-render-graph-gpu.ts +309 -0
  834. package/src/__tests__/gpu-scene-render-graph.browser.test.ts +19 -0
  835. package/src/__tests__/gpu-scene-render-graph.dawn.test.ts +19 -0
  836. package/src/__tests__/gpu-scene-schema.unit.test.ts +16 -0
  837. package/src/__tests__/gpu-scene.dawn.test.ts +209 -0
  838. package/src/__tests__/gpu-scene.unit.test.ts +161 -0
  839. package/src/__tests__/hdrp-pipeline.unit.test.ts +100 -0
  840. package/src/__tests__/ibl/ibl-fallback.unit.test.ts +23 -0
  841. package/src/__tests__/infinite-grid-no-vertex-probe.unit.test.ts +124 -0
  842. package/src/__tests__/injection-kind-owner.test-d.ts +14 -0
  843. package/src/__tests__/ktx2-basis-gpu-consumer.dawn.test.ts +719 -0
  844. package/src/__tests__/light-buffer-layout.unit.test.ts +85 -0
  845. package/src/__tests__/material-contract-inventory.unit.test.ts +24 -0
  846. package/src/__tests__/material-cooked-projection.unit.test.ts +177 -0
  847. package/src/__tests__/material-derived-error-stop-draw.integration.test.ts +69 -0
  848. package/src/__tests__/material-derived-payload.integration.test.ts +164 -0
  849. package/src/__tests__/material-snapshot-mutation.integration.test.ts +58 -0
  850. package/src/__tests__/material-static-dynamic-route.unit.test.ts +113 -0
  851. package/src/__tests__/material-stride-surface.unit.test.ts +32 -0
  852. package/src/__tests__/materials.unit.test.ts +25 -0
  853. package/src/__tests__/mesh-buffer-usage-surface.unit.test.ts +107 -0
  854. package/src/__tests__/mesh-material-bindings.unit.test.ts +89 -0
  855. package/src/__tests__/mesh-stride-surface.unit.test.ts +16 -0
  856. package/src/__tests__/morph-culling-reentry.dawn.test.ts +166 -0
  857. package/src/__tests__/morph-feature-gpu-work.integration.test.ts +78 -0
  858. package/src/__tests__/morph-visual-evidence.integration.test.ts +66 -0
  859. package/src/__tests__/nineslice-handle-surface.unit.test.ts +14 -0
  860. package/src/__tests__/param-schema-projection-census.unit.test.ts +40 -0
  861. package/src/__tests__/persistent-render-scene.unit.test.ts +1311 -0
  862. package/src/__tests__/pipeline-error-policy-owner.unit.test.ts +167 -0
  863. package/src/__tests__/pipeline-pass-trace.test.ts +92 -0
  864. package/src/__tests__/pipeline-stage-owner.test-d.ts +13 -0
  865. package/src/__tests__/plugin.test.ts +25 -0
  866. package/src/__tests__/post-process-error-policy-owner.unit.test.ts +208 -0
  867. package/src/__tests__/prepared-buffer-kind-owner.test-d.ts +29 -0
  868. package/src/__tests__/prepared-graphics-backend-matrix.unit.test.ts +129 -0
  869. package/src/__tests__/prepared-graphics-capability.unit.test.ts +140 -0
  870. package/src/__tests__/prepared-graphics-generation.unit.test.ts +175 -0
  871. package/src/__tests__/prepared-graphics-lifecycle.unit.test.ts +206 -0
  872. package/src/__tests__/prepared-graphics-pipeline-warmup.unit.test.ts +29 -0
  873. package/src/__tests__/prepared-graphics-resolver-recording.unit.test.ts +180 -0
  874. package/src/__tests__/prepared-graphics-resolver.unit.test.ts +287 -0
  875. package/src/__tests__/prepared-graphics-snapshot.unit.test.ts +105 -0
  876. package/src/__tests__/prepared-graphics-store.unit.test.ts +154 -0
  877. package/src/__tests__/prepared-graphics-validation.unit.test.ts +176 -0
  878. package/src/__tests__/profiler-default-off.test.ts +22 -0
  879. package/src/__tests__/profiler-phase-catalog.test.ts +66 -0
  880. package/src/__tests__/profiler-phase-integration.test.ts +70 -0
  881. package/src/__tests__/profiler-phase-token.test.ts +84 -0
  882. package/src/__tests__/public-pipeline-id.test-d.ts +6 -0
  883. package/src/__tests__/public-surface.test-d.ts +32 -0
  884. package/src/__tests__/recover-error-policy-owner.unit.test.ts +127 -0
  885. package/src/__tests__/render-dispatch-membership.unit.test.ts +117 -0
  886. package/src/__tests__/render-error-code-owner.test-d.ts +115 -0
  887. package/src/__tests__/render-error-detail-ssot.test-d.ts +234 -0
  888. package/src/__tests__/render-error-exhaustive.test-d.ts +84 -0
  889. package/src/__tests__/render-feature-assembly.test-d.ts +51 -0
  890. package/src/__tests__/render-feature-construction.unit.test.ts +124 -0
  891. package/src/__tests__/render-feature-context.test-d.ts +81 -0
  892. package/src/__tests__/render-feature-contract.test-d.ts +58 -0
  893. package/src/__tests__/render-feature-diagnostics.unit.test.ts +151 -0
  894. package/src/__tests__/render-feature-docs.unit.test.ts +88 -0
  895. package/src/__tests__/render-feature-error-code-owner.test-d.ts +27 -0
  896. package/src/__tests__/render-feature-errors.unit.test.ts +47 -0
  897. package/src/__tests__/render-feature-gpu-buffer-usage-owner.test-d.ts +46 -0
  898. package/src/__tests__/render-feature-gpu-work.integration.test.ts +377 -0
  899. package/src/__tests__/render-feature-graph.integration.test.ts +205 -0
  900. package/src/__tests__/render-feature-graphics-staging.unit.test.ts +200 -0
  901. package/src/__tests__/render-feature-order.unit.test.ts +66 -0
  902. package/src/__tests__/render-feature-prepared-diagnostics.unit.test.ts +101 -0
  903. package/src/__tests__/render-feature-prepared-errors.test-d.ts +82 -0
  904. package/src/__tests__/render-feature-prepared-graphics-docs.unit.test.ts +141 -0
  905. package/src/__tests__/render-feature-prepared-graphics-isolation.unit.test.ts +122 -0
  906. package/src/__tests__/render-feature-prepared-graphics-negative.test-d.ts +59 -0
  907. package/src/__tests__/render-feature-prepared-graphics-recording.unit.test.ts +107 -0
  908. package/src/__tests__/render-feature-prepared-graphics.test-d.ts +96 -0
  909. package/src/__tests__/render-feature-prepared-graphics.unit.test.ts +121 -0
  910. package/src/__tests__/render-feature-public-surface.test-d.ts +75 -0
  911. package/src/__tests__/render-feature-retry.unit.test.ts +128 -0
  912. package/src/__tests__/render-feature-scheduling.unit.test.ts +122 -0
  913. package/src/__tests__/render-feature-stage-failed-policy-owner.unit.test.ts +146 -0
  914. package/src/__tests__/render-feature-stage-fault-recovery.unit.test.ts +236 -0
  915. package/src/__tests__/render-feature-staging.unit.test.ts +94 -0
  916. package/src/__tests__/render-feature-visibility-context.test-d.ts +38 -0
  917. package/src/__tests__/render-feature-visibility-context.unit.test.ts +38 -0
  918. package/src/__tests__/render-feature-zero-work.unit.test.ts +82 -0
  919. package/src/__tests__/render-graph-compute-raster-gpu.ts +342 -0
  920. package/src/__tests__/render-graph-compute-raster.browser.test.ts +16 -0
  921. package/src/__tests__/render-graph-compute-raster.dawn.test.ts +22 -0
  922. package/src/__tests__/render-graph-hzb-gpu.ts +239 -0
  923. package/src/__tests__/render-graph-hzb.browser.test.ts +16 -0
  924. package/src/__tests__/render-graph-hzb.dawn.test.ts +23 -0
  925. package/src/__tests__/render-graph-primitives.unit.test.ts +22 -0
  926. package/src/__tests__/render-graph-storage-indirect-gpu.ts +162 -0
  927. package/src/__tests__/render-graph-storage-indirect.browser.test.ts +21 -0
  928. package/src/__tests__/render-graph-storage-indirect.dawn.test.ts +28 -0
  929. package/src/__tests__/render-scene-projection.unit.test.ts +206 -0
  930. package/src/__tests__/renderer-factory-material-contract.unit.test.ts +125 -0
  931. package/src/__tests__/renderer-lifecycle.integration.test.ts +10 -0
  932. package/src/__tests__/renderer-render-scene-public.test-d.ts +27 -0
  933. package/src/__tests__/rhi-backend-package-boundary.unit.test.ts +11 -0
  934. package/src/__tests__/scene-temporal-coverage.unit.test.ts +259 -0
  935. package/src/__tests__/scriptable-pack-consumer.test-d.ts +14 -0
  936. package/src/__tests__/shader-stage-surface.unit.test.ts +38 -0
  937. package/src/__tests__/ssao-kernel-surface.unit.test.ts +15 -0
  938. package/src/__tests__/sun-snapshot-consumers.test.ts +35 -0
  939. package/src/__tests__/surface-backend-kind-owner.test-d.ts +42 -0
  940. package/src/__tests__/surface-configuration.unit.test.ts +92 -0
  941. package/src/__tests__/taa-history-store.unit.test.ts +196 -0
  942. package/src/__tests__/temporal-frame-transaction.integration.test.ts +537 -0
  943. package/src/__tests__/temporal-inspection.unit.test.ts +138 -0
  944. package/src/__tests__/texture-usage-surface.unit.test.ts +61 -0
  945. package/src/__tests__/typed-pipeline-topology.unit.test.ts +389 -0
  946. package/src/__tests__/urp-pipeline-targets.unit.test.ts +52 -0
  947. package/src/__tests__/urp-pipeline.unit.test.ts +14 -0
  948. package/src/__tests__/vertex-color-pipeline.unit.test.ts +124 -0
  949. package/src/__tests__/vertex-layout-consumer.unit.test.ts +25 -0
  950. package/src/__tests__/visibility-diagnostics.integration.test.ts +66 -0
  951. package/src/__tests__/visibility-extract.integration.test.ts +89 -0
  952. package/src/__tests__/visibility-extract.perf.test.ts +96 -0
  953. package/src/__tests__/visibility-feature-dedup.integration.test.ts +57 -0
  954. package/src/__tests__/visibility-hidden-report.unit.test.ts +37 -0
  955. package/src/__tests__/visibility-instances.integration.test.ts +50 -0
  956. package/src/__tests__/visibility-multi-world.integration.test.ts +54 -0
  957. package/src/__tests__/visibility-producer-matrix.integration.test.ts +191 -0
  958. package/src/__tests__/visibility-producer-matrix.unit.test.ts +96 -0
  959. package/src/__tests__/visibility-public-surface.test-d.ts +26 -0
  960. package/src/__tests__/visibility-resolver.unit.test.ts +84 -0
  961. package/src/__tests__/visibility-snapshot-contract.unit.test.ts +59 -0
  962. package/src/__tests__/vocabulary.unit.test.ts +21 -0
  963. package/src/assets/__tests__/asset-decoders.unit.test.ts +92 -0
  964. package/src/assets/__tests__/mipmap-generator.unit.test.ts +52 -0
  965. package/src/assets/__tests__/render-asset-port.unit.test.ts +54 -0
  966. package/src/assets/__tests__/resolve-render-asset.unit.test.ts +47 -0
  967. package/src/assets/asset-decoders.ts +158 -0
  968. package/src/assets/render-asset-port.ts +44 -0
  969. package/src/assets/resolve-render-asset.ts +13 -0
  970. package/src/authoring.ts +24 -0
  971. package/src/cluster-binner.ts +700 -0
  972. package/src/components/__tests__/atmosphere-red.test.ts +51 -0
  973. package/src/components/__tests__/atmosphere.test.ts +79 -0
  974. package/src/components/__tests__/fog.test-d.ts +49 -0
  975. package/src/components/__tests__/fog.test.ts +60 -0
  976. package/src/components/__tests__/schema-parity.unit.test.ts +25 -0
  977. package/src/components/__tests__/visibility-schema.unit.test.ts +35 -0
  978. package/src/components/atmosphere.ts +64 -0
  979. package/src/components/camera.ts +512 -0
  980. package/src/components/directional-light.ts +120 -0
  981. package/src/components/environment.ts +206 -0
  982. package/src/components/glyph-text.ts +63 -0
  983. package/src/components/index.ts +49 -0
  984. package/src/components/instances.ts +207 -0
  985. package/src/components/layer.ts +69 -0
  986. package/src/components/light-helpers.ts +188 -0
  987. package/src/components/mesh-filter.ts +59 -0
  988. package/src/components/mesh-renderer.ts +61 -0
  989. package/src/components/point-light-shadow.ts +43 -0
  990. package/src/components/point-light.ts +65 -0
  991. package/src/components/post-process-params.ts +35 -0
  992. package/src/components/scene-instance.ts +193 -0
  993. package/src/components/sort-key.ts +75 -0
  994. package/src/components/spot-light.ts +124 -0
  995. package/src/components/sprite-animation.ts +169 -0
  996. package/src/components/sprite-instances.ts +179 -0
  997. package/src/components/sprite-playback-mode.ts +73 -0
  998. package/src/components/sprite-region-override.ts +106 -0
  999. package/src/components/tile-layer.ts +161 -0
  1000. package/src/components/tilemap.ts +48 -0
  1001. package/src/components/visibility.ts +53 -0
  1002. package/src/construct-renderer.ts +4 -0
  1003. package/src/debug-draw-glue.ts +169 -0
  1004. package/src/deferred-lighting.ts +92 -0
  1005. package/src/dynamic-texture-store.ts +111 -0
  1006. package/src/engine-metrics.ts +89 -0
  1007. package/src/environment/README.md +76 -0
  1008. package/src/environment/__tests__/failure-injection.test.ts +50 -0
  1009. package/src/environment/__tests__/generation-red.test.ts +64 -0
  1010. package/src/environment/__tests__/generation.test.ts +37 -0
  1011. package/src/environment/__tests__/graph-transaction.test.ts +85 -0
  1012. package/src/environment/__tests__/inspection-red.test.ts +53 -0
  1013. package/src/environment/__tests__/lifecycle-evidence.test.ts +40 -0
  1014. package/src/environment/__tests__/pipeline-topology.test.ts +33 -0
  1015. package/src/environment/__tests__/readiness.test.ts +42 -0
  1016. package/src/environment/__tests__/recovery.test.ts +62 -0
  1017. package/src/environment/__tests__/resize-dispose.test.ts +30 -0
  1018. package/src/environment/__tests__/signature-red.test.ts +45 -0
  1019. package/src/environment/__tests__/signature.test.ts +60 -0
  1020. package/src/environment/descriptors.ts +7 -0
  1021. package/src/environment/extracted-environment.ts +239 -0
  1022. package/src/environment/generation.ts +158 -0
  1023. package/src/environment/gpu-bundle.ts +144 -0
  1024. package/src/environment/graph.ts +588 -0
  1025. package/src/environment/inspection.ts +107 -0
  1026. package/src/environment/lifecycle.ts +124 -0
  1027. package/src/environment/readiness.ts +76 -0
  1028. package/src/environment/signature.ts +185 -0
  1029. package/src/errors/ecs-validation.ts +16 -0
  1030. package/src/errors/index.ts +3 -0
  1031. package/src/errors/recover.ts +119 -0
  1032. package/src/errors/render.ts +1244 -0
  1033. package/src/extract/__tests__/directional-csm-domain.unit.test.ts +391 -0
  1034. package/src/extract/__tests__/environment-source.test.ts +105 -0
  1035. package/src/extract/__tests__/schema-readers.unit.test.ts +16 -0
  1036. package/src/extract/directional-csm.ts +959 -0
  1037. package/src/extract/index.ts +10 -0
  1038. package/src/extract/material-interface.ts +604 -0
  1039. package/src/extract/schema-readers.ts +27 -0
  1040. package/src/extract/visibility.ts +120 -0
  1041. package/src/features/graph-contribution.ts +577 -0
  1042. package/src/features/host.ts +1097 -0
  1043. package/src/features/index.ts +100 -0
  1044. package/src/features/morph/index.ts +24 -0
  1045. package/src/features/morph/morph-bounds.ts +123 -0
  1046. package/src/features/morph/morph-feature.ts +287 -0
  1047. package/src/features/prepared-gpu-work.ts +902 -0
  1048. package/src/features/prepared-graphics-store.ts +435 -0
  1049. package/src/features/prepared-graphics.ts +479 -0
  1050. package/src/features/render-graph-compute.ts +60 -0
  1051. package/src/features/render-graph-contribution.ts +95 -0
  1052. package/src/features/render-graph-raster.ts +308 -0
  1053. package/src/features/render-graph-resources.ts +36 -0
  1054. package/src/features/scene-temporal.ts +274 -0
  1055. package/src/features/taa-resolve.ts +244 -0
  1056. package/src/features/targets.ts +83 -0
  1057. package/src/features/types.ts +291 -0
  1058. package/src/frame-chain.ts +21 -0
  1059. package/src/fullscreen-post-process-pass.ts +406 -0
  1060. package/src/glyph-text-layout-system.ts +447 -0
  1061. package/src/gpu-driven/batch-topology.ts +423 -0
  1062. package/src/gpu-driven/production-raster.ts +1705 -0
  1063. package/src/gpu-driven/view-gpu.ts +849 -0
  1064. package/src/gpu-driven/view-reference.ts +110 -0
  1065. package/src/gpu-resource-store.ts +1921 -0
  1066. package/src/gpu-resource.ts +159 -0
  1067. package/src/gpu-scene-schema.ts +224 -0
  1068. package/src/gpu-scene.ts +855 -0
  1069. package/src/gpu-stage.ts +9 -0
  1070. package/src/gpu-texture-usage.ts +12 -0
  1071. package/src/gpu-usage.ts +14 -0
  1072. package/src/hdrp-buffers.ts +689 -0
  1073. package/src/hdrp-cluster-membership.ts +70 -0
  1074. package/src/hdrp-pipeline.ts +525 -0
  1075. package/src/ibl/IblPipelineCache.ts +1246 -0
  1076. package/src/ibl/cubemap-projection.ts +60 -0
  1077. package/src/ibl/face-uniforms.ts +150 -0
  1078. package/src/ibl/skylight-bind-group.ts +513 -0
  1079. package/src/index.ts +271 -0
  1080. package/src/instance-buffer-cache.ts +123 -0
  1081. package/src/internal.ts +88 -0
  1082. package/src/lifecycle.ts +123 -0
  1083. package/src/light-buffer-layout.ts +346 -0
  1084. package/src/materials.ts +236 -0
  1085. package/src/mesh-material-bindings.ts +104 -0
  1086. package/src/mesh-update-errors.ts +113 -0
  1087. package/src/mipmap-generator.ts +244 -0
  1088. package/src/param-schema-projection-census.ts +73 -0
  1089. package/src/pbr-pipeline.ts +749 -0
  1090. package/src/persistent-render-scene.ts +1752 -0
  1091. package/src/pipeline/index.ts +40 -0
  1092. package/src/pipeline-builder.ts +386 -0
  1093. package/src/pipeline-errors.ts +172 -0
  1094. package/src/pipeline-spec.ts +1768 -0
  1095. package/src/plugin.ts +137 -0
  1096. package/src/post-process-errors.ts +304 -0
  1097. package/src/prepare/__tests__/schema-readers.unit.test.ts +16 -0
  1098. package/src/prepare/index.ts +8 -0
  1099. package/src/prepare/prepared-graphics-resolver.ts +455 -0
  1100. package/src/prepare/schema-readers.ts +20 -0
  1101. package/src/record/__tests__/environment-record.test.ts +35 -0
  1102. package/src/record/__tests__/frame-targets.unit.test.ts +54 -0
  1103. package/src/record/__tests__/material-bg-cache.unit.test.ts +41 -0
  1104. package/src/record/__tests__/material-slot-plan.unit.test.ts +76 -0
  1105. package/src/record/__tests__/membership-timing.unit.test.ts +524 -0
  1106. package/src/record/__tests__/render-submission.integration.test.ts +76 -0
  1107. package/src/record/__tests__/render-submission.perf.test.ts +141 -0
  1108. package/src/record/__tests__/shadow-submit-mode.unit.test.ts +88 -0
  1109. package/src/record/__tests__/video-texture-view.unit.test.ts +90 -0
  1110. package/src/record/__tests__/view-ubo-layout.unit.test.ts +101 -0
  1111. package/src/record/frame-lighting.ts +1183 -0
  1112. package/src/record/frame-observation.ts +122 -0
  1113. package/src/record/frame-snapshot.ts +515 -0
  1114. package/src/record/frame-targets.ts +372 -0
  1115. package/src/record/frame.ts +1874 -0
  1116. package/src/record/helpers.ts +289 -0
  1117. package/src/record/index.ts +15 -0
  1118. package/src/record/main-pass-geometry.ts +1014 -0
  1119. package/src/record/main-pass-material.ts +716 -0
  1120. package/src/record/main-pass-skin.ts +51 -0
  1121. package/src/record/main-pass-sprite-draws.ts +1056 -0
  1122. package/src/record/main-pass-sprite.ts +166 -0
  1123. package/src/record/main-pass.ts +588 -0
  1124. package/src/record/material-payload.ts +292 -0
  1125. package/src/record/material-slot-plan.ts +68 -0
  1126. package/src/record/membership-timing.ts +1012 -0
  1127. package/src/record/mesh-ssbo.ts +406 -0
  1128. package/src/record/shadow-caster-uniform.ts +37 -0
  1129. package/src/record/shadow-pass.ts +2387 -0
  1130. package/src/record/shadow-submit-mode.ts +277 -0
  1131. package/src/record/skybox-post-pass.ts +594 -0
  1132. package/src/record/typed-frame-graph.ts +499 -0
  1133. package/src/record/view-ubo.ts +206 -0
  1134. package/src/render-data.ts +385 -0
  1135. package/src/render-dispatch-membership.ts +155 -0
  1136. package/src/render-graph-primitives.ts +1586 -0
  1137. package/src/render-pipeline-context.ts +332 -0
  1138. package/src/render-pipeline-target.ts +96 -0
  1139. package/src/render-pipeline.ts +343 -0
  1140. package/src/render-scene-projection.ts +1738 -0
  1141. package/src/render-system-extract.ts +5203 -0
  1142. package/src/render-system-fold.ts +531 -0
  1143. package/src/render-system.ts +3258 -0
  1144. package/src/renderer/asset-service.ts +32 -0
  1145. package/src/renderer/backend-selection.ts +121 -0
  1146. package/src/renderer/environment-classify.ts +30 -0
  1147. package/src/renderer/environment-error.ts +19 -0
  1148. package/src/renderer/material/assembly.ts +53 -0
  1149. package/src/renderer/material/pipeline-projection.ts +140 -0
  1150. package/src/renderer/renderer-factory.ts +9062 -0
  1151. package/src/renderer.ts +940 -0
  1152. package/src/scene-instances/post-spawn-resolve-joints.ts +168 -0
  1153. package/src/scene-utils/collect-subtree.ts +40 -0
  1154. package/src/shadow-atlas.ts +244 -0
  1155. package/src/ssao-buffers.ts +175 -0
  1156. package/src/ssao-config.ts +61 -0
  1157. package/src/ssao-data.ts +106 -0
  1158. package/src/surface-format.ts +37 -0
  1159. package/src/systems/active-camera.ts +116 -0
  1160. package/src/systems/pass-selector.ts +49 -0
  1161. package/src/systems/skin-palette-allocator.ts +294 -0
  1162. package/src/systems/transparent-sort-config.ts +211 -0
  1163. package/src/taa-history-store.ts +429 -0
  1164. package/src/temporal-coverage.ts +106 -0
  1165. package/src/temporal-frame-transaction.ts +301 -0
  1166. package/src/temporal-inspection.ts +194 -0
  1167. package/src/temporal-view.ts +174 -0
  1168. package/src/tilemap/resolve-tileset-runtime.ts +72 -0
  1169. package/src/tilemap-chunk-extract-system.ts +1307 -0
  1170. package/src/typed-render-graph-primitives.ts +530 -0
  1171. package/src/typed-shadow-passes.ts +195 -0
  1172. package/src/urp-pipeline.ts +340 -0
@@ -0,0 +1,3258 @@
1
+ // @forgeax/engine-runtime - RenderSystem main entry (D-S2 three-stage Extract ->
2
+ // Prepare -> Record + 4-tier error fan-out).
3
+ //
4
+ // Engine-internal phase: NOT registered to World schedule (AC-09);
5
+ // `Renderer.draw([world], { cameraOwner: 0, resourceOwner: 0 })` invokes once per frame. See `Renderer` JSDoc in
6
+ // `./renderer.ts` for the full error tier table (D-S4..D-S8) and AGENTS.md
7
+ // "ECS render bridge" section for the AI-user-facing contract.
8
+ //
9
+ // Stage carve-out (review round 1 finding #3 - 505 line cap fallback):
10
+ // - render-system.ts (this file) types + orchestration
11
+ // - render-system-extract.ts Extract ECS query phase + snapshot helpers
12
+ // - render-system-record.ts Prepare + Record GPU phase + matrix helpers
13
+ //
14
+ // @forgeax/engine-math is referenced through render-system-record.ts which builds
15
+ // view/proj matrices and worldFromLocal via `mat4.compose / .multiply /
16
+ // .invert` (charter proposition 5: no math reinvention; render-system.test.ts
17
+ // asserts `/@forgeax\/engine-math/` shows up in render-system.ts source).
18
+
19
+ import type { EntityHandle, World } from '@forgeax/engine-ecs';
20
+ import type { VertexLayoutProjection } from '@forgeax/engine-geometry';
21
+ import type { Profiler, RecorderSession } from '@forgeax/engine-profiler';
22
+ import type {
23
+ BindGroupEntry,
24
+ BindGroupLayout,
25
+ Buffer,
26
+ ComputePipeline,
27
+ PipelineLayout,
28
+ RenderPipeline,
29
+ RhiCanvasContext,
30
+ RhiDevice,
31
+ Sampler,
32
+ TextureView,
33
+ } from '@forgeax/engine-rhi';
34
+ import { err, ok, type Result, RhiError } from '@forgeax/engine-rhi';
35
+ import type { MaterialRuntimeArtifact } from '@forgeax/engine-shader';
36
+ import {
37
+ type Handle,
38
+ type ImmutableParamSchemaProjection,
39
+ type MaterialAsset,
40
+ type MaterialRenderState,
41
+ type MaterialTextureValue,
42
+ type ParamSchemaEntry,
43
+ type PassKind,
44
+ type PrimitiveTopology,
45
+ type RenderPipelineAsset,
46
+ RenderQueue,
47
+ type SamplerAsset,
48
+ } from '@forgeax/engine-types';
49
+ import type { RenderAssetPort } from './assets/render-asset-port';
50
+ import { resolveRenderAsset } from './assets/resolve-render-asset';
51
+ import { createClusterBinScratch } from './cluster-binner';
52
+ import type { DynamicTextureStore } from './dynamic-texture-store';
53
+ import type { EngineMetrics } from './engine-metrics';
54
+ import {
55
+ createEnvironmentGenerationState,
56
+ environmentConsumerSnapshot,
57
+ } from './environment/generation';
58
+ import { isEnvironmentGpuBundle } from './environment/gpu-bundle';
59
+ import { type EnvironmentInspection, inspectEnvironmentGeneration } from './environment/inspection';
60
+ import { abandonEnvironmentDevice, disposeEnvironmentGeneration } from './environment/lifecycle';
61
+ import {
62
+ HdrpCapsInsufficientError,
63
+ type ObservationUnavailableError,
64
+ type RenderError,
65
+ } from './errors/render';
66
+ import { resolveMaterialFromPort } from './extract/material-interface';
67
+ import {
68
+ createRenderFeatureContributionStaging,
69
+ mergeRenderFeatureContributions,
70
+ type RenderFeatureGraphComposition,
71
+ type RenderFeatureGraphContribution,
72
+ } from './features/graph-contribution';
73
+ import {
74
+ type RenderFeatureHost,
75
+ type RenderFeaturePreparedGraphicsResolverInput,
76
+ runRenderFeatureFrame,
77
+ settlePreparedGraphicsCompletion,
78
+ } from './features/host';
79
+ import {
80
+ createRenderFeatureGpuWorkResolver,
81
+ type RenderFeatureGpuWorkResolver,
82
+ } from './features/prepared-gpu-work';
83
+ import { sceneTemporalCoverage } from './features/scene-temporal';
84
+ import { resolveStandardRenderFeatureTargets } from './features/targets';
85
+ import type { RenderFeaturePassContext } from './features/types';
86
+ import {
87
+ buildFullscreenPostProcessPass,
88
+ DEPTH_MIN_PARAMS_BYTE_SIZE,
89
+ entryHasDepthRead,
90
+ type PostProcessShaderEntry,
91
+ } from './fullscreen-post-process-pass';
92
+ import {
93
+ GpuDrivenProduction,
94
+ type GpuDrivenProductionInspection,
95
+ } from './gpu-driven/production-raster';
96
+ import type { GpuBuffer } from './gpu-resource';
97
+ import type { GpuResourceStore } from './gpu-resource-store';
98
+ import {
99
+ GPU_TEXTURE_USAGE_COPY_SRC,
100
+ GPU_TEXTURE_USAGE_RENDER_ATTACHMENT,
101
+ GPU_TEXTURE_USAGE_TEXTURE_BINDING,
102
+ } from './gpu-texture-usage';
103
+ import { GPU_BUFFER_USAGE_COPY_DST, GPU_BUFFER_USAGE_UNIFORM } from './gpu-usage';
104
+ import { validateClusterGrid } from './hdrp-pipeline';
105
+ import { assembleMaterialWithSkylightEntries } from './ibl/skylight-bind-group';
106
+ import { disposeInstanceBuffers, disposeTransientInstanceBuffers } from './instance-buffer-cache';
107
+ import type { RhiErrorListenerRegistry } from './lifecycle';
108
+ import type { MeshMaterialBindingObservation } from './mesh-material-bindings';
109
+ import {
110
+ deriveParamSchemaForCensus,
111
+ type ParamSchemaProjectionCensus,
112
+ } from './param-schema-projection-census';
113
+ import {
114
+ PersistentRenderScene,
115
+ type PersistentRenderSceneInspection,
116
+ } from './persistent-render-scene';
117
+ import { PipelineError } from './pipeline-errors';
118
+ import {
119
+ PostProcessError,
120
+ type PostProcessError as PostProcessErrorType,
121
+ } from './post-process-errors';
122
+ import {
123
+ createPreparedGraphicsResolver,
124
+ type PreparedGraphicsResolver,
125
+ } from './prepare/prepared-graphics-resolver';
126
+ import { type RecordProfileRunner, type RenderFrameState, recordFrame } from './record';
127
+ import { buildPerFrameBindGroups } from './record/frame-lighting';
128
+ import {
129
+ type FrameObservation,
130
+ type FrameObservationOptions,
131
+ observeCurrentFrame,
132
+ } from './record/frame-observation';
133
+ import { applyParamSnapshotToUbo, residentTextureView } from './record/main-pass-material';
134
+ import type { MembershipTimingController } from './record/membership-timing';
135
+ import {
136
+ applyShadowSubmitMode,
137
+ createShadowSubmitModeState,
138
+ restoreShadowSubmitMode,
139
+ type ShadowSubmitMode,
140
+ type ShadowSubmitModeState,
141
+ type ShadowSubmitResult,
142
+ } from './record/shadow-submit-mode';
143
+ import { retireCompiledFrameGraph } from './record/typed-frame-graph';
144
+ // The forgeax-concept RenderPipeline (registrable / installable unit) - aliased to avoid
145
+ // the name collision with the RHI opaque `RenderPipeline` handle imported above. The RHI
146
+ // handle stays internal (requirements line 155); this concept type is the public surface.
147
+ import type { RenderPipeline as RenderPipelineDef } from './render-pipeline';
148
+ import type { RenderPipelineContext } from './render-pipeline-context';
149
+ import type {
150
+ CameraSnapshot,
151
+ DispatchEntry,
152
+ ExtractedFrame,
153
+ MaterialSnapshotCachesByWorld,
154
+ RenderableSnapshot,
155
+ } from './render-system-extract';
156
+ import { TaaHistoryStore } from './taa-history-store';
157
+ import { TemporalFrameTransaction } from './temporal-frame-transaction';
158
+ import { projectTemporalInspection, type TemporalInspection } from './temporal-inspection';
159
+
160
+ export type RenderSceneInspection = PersistentRenderSceneInspection & {
161
+ readonly gpuDriven: GpuDrivenProductionInspection;
162
+ readonly temporal: TemporalInspection;
163
+ readonly environment: EnvironmentInspection;
164
+ };
165
+
166
+ import {
167
+ extractFrame,
168
+ extractFrames,
169
+ extractRenderableEntity,
170
+ prepareExtractContext,
171
+ refreshExtractedFrameCameras,
172
+ refreshExtractedFrameLights,
173
+ refreshExtractedFramePostProcessParams,
174
+ refreshRenderableMaterialSnapshot,
175
+ selectFog,
176
+ } from './render-system-extract';
177
+ import {
178
+ type DrawOwnerOptions,
179
+ RENDER_PHASE_CATALOG,
180
+ type RenderPhase,
181
+ type RenderPhaseSkipReason,
182
+ type RenderRecordPhase,
183
+ } from './renderer';
184
+ import type { MaterialRenderProjection } from './renderer/material/assembly';
185
+ import type { MaterialReadiness } from './renderer/material/pipeline-projection';
186
+ import { resolveSurfaceFormatPair } from './surface-format';
187
+ import type { SkinPaletteAllocator } from './systems/skin-palette-allocator';
188
+ import {
189
+ getTransparentSortConfig,
190
+ TRANSPARENT_SORT_MODE_DISTANCE,
191
+ TRANSPARENT_SORT_MODE_LAYER_Y,
192
+ TRANSPARENT_SORT_MODE_LAYER_YZ,
193
+ TRANSPARENT_SORT_MODE_LAYER_Z,
194
+ } from './systems/transparent-sort-config';
195
+ import { URP_PIPELINE_ID, urpPipeline } from './urp-pipeline';
196
+
197
+ /**
198
+ * Unified transparent-queue sub-sort covering all four
199
+ * {@link TransparentSortConfig} modes. Reorders the
200
+ * `queue === RenderQueue.Transparent` segment of the dispatch list;
201
+ * all other queue segments keep their relative order.
202
+ *
203
+ * | mode | primary key | secondary key | tertiary key |
204
+ * |:--:|:--|:--|:--|
205
+ * | 0 (LAYER_Z) | `layer` ASC | `posZ` ASC | `materialHandle` ASC |
206
+ * | 1 (LAYER_Y) | `layer` ASC | `-(posY - pivotY * sizeY)` ASC | `materialHandle` ASC |
207
+ * | 2 (LAYER_YZ) | `layer` ASC | `(posY - pivotY * sizeY) + yzAlpha * posZ` ASC | `materialHandle` ASC |
208
+ * | 3 (DISTANCE) | `-(dist² from camera)` ASC (back-to-front, layer ignored) | — |
209
+ *
210
+ * The `materialHandle` tertiary key for modes 0/1/2 groups same-material
211
+ * entries together whenever the primary+secondary sort values are equal
212
+ * (e.g. tilemap tiles in the same row/layer share `posY` in LAYER_Y mode).
213
+ * Consecutive same-material groups then collapse into fold buckets in the
214
+ * record-stage fold operator, significantly reducing draw call count for
215
+ * tilemap-heavy scenes.
216
+ *
217
+ * `posX/Y/Z` = translation column of the entity's world mat4 (indices 12/13/14).
218
+ * `pivotY` = `RenderableSnapshot.material.paramSnapshot.pivotAndSize[1]` (default 0.5).
219
+ * `sizeY` = length of the Y-axis column of the world mat4 (indices 4/5/6).
220
+ */
221
+ function sortTransparentDispatch(
222
+ dispatch: DispatchEntry[],
223
+ world: World,
224
+ cameras: readonly CameraSnapshot[],
225
+ renderables: readonly RenderableSnapshot[],
226
+ ): DispatchEntry[] {
227
+ const cfg = getTransparentSortConfig(world);
228
+ const mode = cfg.mode;
229
+
230
+ // Indices of Transparent-queue entries within the dispatch list.
231
+ const transparentSlots: number[] = [];
232
+ for (let i = 0; i < dispatch.length; i++) {
233
+ if (dispatch[i]?.queue === RenderQueue.Transparent) transparentSlots.push(i);
234
+ }
235
+ if (transparentSlots.length <= 1) return dispatch;
236
+
237
+ let sortedSlotOrder: number[];
238
+
239
+ if (mode === TRANSPARENT_SORT_MODE_DISTANCE) {
240
+ const camera = cameras[0];
241
+ if (camera === undefined) return dispatch;
242
+ const camPos = camera.position;
243
+
244
+ // Squared camera distance per entry (negated → ascending = back-to-front).
245
+ // D-3: world position = translation column of Transform.world (m[12,13,14]).
246
+ const negDistSq = (entry: DispatchEntry): number => {
247
+ const tx = renderables[entry.renderableIndex]?.transform;
248
+ if (tx === undefined) return 0;
249
+ const w = tx.world;
250
+ const dx = (w[12] ?? 0) - (camPos[0] ?? 0);
251
+ const dy = (w[13] ?? 0) - (camPos[1] ?? 0);
252
+ const dz = (w[14] ?? 0) - (camPos[2] ?? 0);
253
+ return -(dx * dx + dy * dy + dz * dz);
254
+ };
255
+
256
+ sortedSlotOrder = transparentSlots.slice().sort((a, b) => {
257
+ const da = negDistSq(dispatch[a] as DispatchEntry);
258
+ const db = negDistSq(dispatch[b] as DispatchEntry);
259
+ if (da < db) return -1;
260
+ if (da > db) return 1;
261
+ return 0;
262
+ });
263
+ } else {
264
+ // Modes 0/1/2: primary = layer ASC, secondary = mode-formula ASC.
265
+ // sizeY = length of the Y-axis column (col1 = indices 4,5,6) of the
266
+ // world mat4; rotation-invariant and handles flipV sign correctly.
267
+ const sortVal = (entry: DispatchEntry): number => {
268
+ const tx = renderables[entry.renderableIndex]?.transform;
269
+ const w = tx?.world;
270
+ const posY = (w?.[13] ?? 0) as number;
271
+ const posZ = (w?.[14] ?? 0) as number;
272
+ if (mode === TRANSPARENT_SORT_MODE_LAYER_Z) return posZ;
273
+ const mat = renderables[entry.renderableIndex]?.material;
274
+ // feat-20260625-refactor-sprite-as-transparent-mesh M3 / w15: post
275
+ // SpriteFieldsSnapshot ablation, pivot lives in paramSnapshot
276
+ // .pivotAndSize[0..1] (UBO-aligned vec4 slot 2, plan D-6). Non-sprite
277
+ // materials carry paramSnapshot=undefined and fall back to 0.5.
278
+ const pivotAndSize = mat?.paramSnapshot?.pivotAndSize as readonly number[] | undefined;
279
+ const pivotY = (pivotAndSize?.[1] ?? 0.5) as number;
280
+ const wy4 = (w?.[4] ?? 0) as number;
281
+ const wy5 = (w?.[5] ?? 1) as number;
282
+ const wy6 = (w?.[6] ?? 0) as number;
283
+ const sizeY = Math.sqrt(wy4 * wy4 + wy5 * wy5 + wy6 * wy6);
284
+ const footY = posY - pivotY * sizeY;
285
+ if (mode === TRANSPARENT_SORT_MODE_LAYER_Y) return -footY;
286
+ if (mode === TRANSPARENT_SORT_MODE_LAYER_YZ) return footY + cfg.yzAlpha * posZ;
287
+ // Defensive fallback for any unknown mode that slips past setTransparentSortConfig.
288
+ return posZ;
289
+ };
290
+
291
+ sortedSlotOrder = transparentSlots.slice().sort((a, b) => {
292
+ const da = dispatch[a] as DispatchEntry;
293
+ const db = dispatch[b] as DispatchEntry;
294
+ const la = da.layer;
295
+ const lb = db.layer;
296
+ if (la !== lb) return la - lb;
297
+ const va = sortVal(da);
298
+ const vb = sortVal(db);
299
+ if (va < vb) return -1;
300
+ if (va > vb) return 1;
301
+ // Tertiary tiebreaker: group same-materialHandle entries together so
302
+ // fold-eligible consecutive runs form. Entries at equal (layer,
303
+ // sortVal) — e.g. tilemap tiles in the same row under LAYER_Y — are
304
+ // depth-equivalent; reordering them by material does not change the
305
+ // visual result but maximises fold-bucket width.
306
+ return da.materialHandle - db.materialHandle;
307
+ });
308
+ }
309
+
310
+ // Scatter the reordered Transparent entries back into their original slots.
311
+ const result = dispatch.slice();
312
+ for (let k = 0; k < transparentSlots.length; k++) {
313
+ const targetSlot = transparentSlots[k] as number;
314
+ const sourceSlot = sortedSlotOrder[k] as number;
315
+ result[targetSlot] = dispatch[sourceSlot] as DispatchEntry;
316
+ }
317
+ return result;
318
+ }
319
+
320
+ /** Dynamic-offset stride for one derived material UBO slot. */
321
+ export const MATERIAL_PER_ENTITY_STRIDE = 512;
322
+
323
+ /**
324
+ * Engine-internal Extract / Prepare / Record driver; constructed by createRenderer.
325
+ *
326
+ * w15 M5 dual-pipeline dispatch: `pipelineDispatchCounts` surfaces per-frame
327
+ * counters of how many entities were routed to each pipeline (plan-strategy
328
+ * D-P4 / requirements AC-07). The counts roll over monotonically — test
329
+ * callers read them after `draw([world], { cameraOwner: 0, resourceOwner: 0 })` to assert each tag saw >= 1 draw.
330
+ * Reset is intentional on every `draw([world], { cameraOwner: 0, resourceOwner: 0 })` entry so per-frame assertions
331
+ * stay local (charter proposition 4 explicit failure: test code sees exact
332
+ * per-draw counts, not stale cross-frame totals).
333
+ *
334
+ * bug-20260519: BUILTIN cube migrated to 12F so the legacy `unlitBuiltin`
335
+ * counter is gone; the surface collapses to `unlit` (every entity whose
336
+ * shader identity is `forgeax::default-unlit`) + `standard` (every entity
337
+ * whose shader identity is `forgeax::default-standard-pbr`).
338
+ */
339
+ export interface RenderSystem {
340
+ /** Returns true only when this invocation reached queue submission. */
341
+ draw(worlds: readonly World[], opts: DrawOwnerOptions): boolean;
342
+ /** Apply one renderer-owned shadow submission mode for one generation. */
343
+ applyShadowSubmitMode(
344
+ mode: ShadowSubmitMode,
345
+ rendererGeneration: string,
346
+ ): ShadowSubmitResult<ShadowSubmitModeState>;
347
+ /** Restore the renderer-owned mode to the independent baseline. */
348
+ restoreShadowSubmitMode(rendererGeneration: string): ShadowSubmitResult<ShadowSubmitModeState>;
349
+ /** Read the generation-bound mode and exact lifecycle counters. */
350
+ getShadowSubmitMode(): ShadowSubmitModeState;
351
+ /** Release renderer-owned persistent state for one detached World. */
352
+ detachWorld(world: World): void;
353
+ /** Release the profiler catalog contribution owned by this RenderSystem. */
354
+ releaseProfilerCatalog(): void;
355
+ observeCurrentFrame(
356
+ options: FrameObservationOptions,
357
+ ): Promise<Result<FrameObservation, ObservationUnavailableError>>;
358
+ readonly pipelineDispatchCounts: {
359
+ readonly unlit: number;
360
+ };
361
+ /**
362
+ * feat-20260528-frustum-culling M5 / w14: per-frame frustum-culling counters.
363
+ * Updated by `draw([world], { cameraOwner: 0, resourceOwner: 0 })` on every call from the Extract stage.
364
+ */
365
+ readonly frustumStats: { culled: number; total: number };
366
+ /** Per-frame candidate entities rejected by author visibility. */
367
+ readonly visibilityStats: { explicitlyHidden: number };
368
+ /** Persistent scene maintenance evidence from the ordinary single-World path. */
369
+ readonly renderScene: RenderSceneInspection;
370
+ /** Current mesh-slot provenance and active diagnostics from the last frame. */
371
+ readonly meshMaterialBindings: readonly MeshMaterialBindingObservation[];
372
+ /**
373
+ * feat-20260531-bloom-first-declarative-render-graph-pass M4 fix-up w19:
374
+ * per-frame render-graph pass names in declaration order. Empty array
375
+ * before the first `draw([world], { cameraOwner: 0, resourceOwner: 0 })` call; populated after the per-frame
376
+ * graph is built (lazily on first draw). Read-only introspection surface
377
+ * so smoke tests can assert the declarative pass chain is wired without
378
+ * reaching into engine internals.
379
+ */
380
+ readonly perFramePassNames: readonly string[];
381
+ /**
382
+ * feat-20260531-per-frame-bind-group-cache M1 / w4: per-frame
383
+ * createBindGroup counter. Reset to 0 on every `draw([world], { cameraOwner: 0, resourceOwner: 0 })` entry,
384
+ * bumped on each cache-miss createBindGroup call in the record stage.
385
+ * Aligns with pipelineDispatchCounts precedent: closure-mutable object
386
+ * + draw-entry reset + readonly getter. Stable-frame AC-03 asserts
387
+ * createBindGroup == 0 when all bind groups are cache-resident.
388
+ *
389
+ * M5 / w19 type-safe finalization: the return type is purposely the
390
+ * narrowest inline object literal `{ readonly createBindGroup: number }`
391
+ * rather than a wider Record/alias — this ensures TS language service
392
+ * hover shows the exact field name + type, and AC-09 consumption sites
393
+ * infer `number` without `as` casts (plan-strategy D-7 + sec.8
394
+ * discoverability).
395
+ */
396
+ readonly bindGroupCounts: {
397
+ readonly createBindGroup: number;
398
+ readonly keys: readonly string[];
399
+ };
400
+ /**
401
+ * feat-20260615-pipeline-spec-ssot M5-T2: latest URP shadow-atlas
402
+ * texture view resolved from the compiled typed frame graph. Returns `null` when no
403
+ * frame has been drawn yet, or when the active pipeline does not
404
+ * declare the `shadowDepth` color target. Read-only debug seam:
405
+ * the engine itself reads the same view inline in `recordFrame`;
406
+ * this getter exists so debug readback paths
407
+ * (`Renderer.debugSampleShadowFactor`) read the same SSOT view as
408
+ * the engine's record stage (D-2: graph owns the lifecycle; no
409
+ * mirror slot on `pipelineState.perPassResources`).
410
+ */
411
+ // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle
412
+ getCurrentShadowView(): any | null;
413
+ /**
414
+ * feat-20260601-customizable-render-pipeline-seam M1 / w7: register a render-pipeline
415
+ * logic under `id`. Same-id re-register THROWS a PipelineError
416
+ * (`'pipeline-already-registered'`) - programmer-error fail-fast, mirroring
417
+ * ShaderRegistry.installMaterialArtifact. Engine builtins use the `forgeax::` prefix.
418
+ */
419
+ registerPipeline(id: string, impl: RenderPipelineDef): void;
420
+ /**
421
+ * feat-20260601-customizable-render-pipeline-seam M1 / w7 (D-19): install the pipeline
422
+ * described by a `RenderPipelineAsset` POD. Looks up `pipelineId` in the registry; on an
423
+ * unregistered id returns `Result.err(PipelineError{code:'pipeline-not-found'})`. On
424
+ * success the next `draw` detects the install-epoch bump and rebuilds the memoized
425
+ * per-frame graph (hot-swap). Takes the payload directly because installation happens at
426
+ * boot/swap time before any World exists -- there is no handle to resolve.
427
+ */
428
+ installPipeline(asset: RenderPipelineAsset): Result<() => void, PipelineError>;
429
+ /**
430
+ * feat-20260604-resource-owning-render-graph-and-fullscreen-postpr M2 / w13:
431
+ * fullscreen post-process shader registry, parallel to ShaderRegistry.installMaterialArtifact
432
+ * (D-4: material shader handles 4-BGL / 12-float-vertex / depth / triangle-list, while
433
+ * fullscreen post-process uses 0-vertex-buffer / no-depth / input-texture-BGL).
434
+ * Same-id re-register THROWS PostProcessError ('post-process-already-registered').
435
+ * Engine builtins use the `forgeax::` prefix.
436
+ */
437
+ readonly postProcess: {
438
+ register(id: string, entry: PostProcessShaderEntry): () => void;
439
+ };
440
+ /**
441
+ * feat-20260612-rhi-destroy-renderer-dispose-gpu-lifecycle / M5 / w21:
442
+ * release the per-RenderSystem frame-state GPU bookkeeping during
443
+ * `Renderer.dispose()`. Retires the compiled graph and clears the instance-buffer cache.
444
+ *
445
+ * Idempotent (architecture-principles §6): a second call after both
446
+ * structures are cleared is a no-op. Per-step failures inside drain /
447
+ * disposeInstanceBuffers fall through silently -- the Renderer.dispose
448
+ * cascade owns the try/catch + errorRegistry.fire fan-out (D-3).
449
+ */
450
+ disposeFrameState(): void;
451
+
452
+ /**
453
+ * feat-20260622-s5 M3 / B-2 / w18: drop the device-bound state the recover()
454
+ * rebuild must shed before re-running the pipeline build against a fresh
455
+ * device. Two effects, both keyed to the lost device:
456
+ * 1. the per-frame render-graph's pendingDestroy queue (PooledTextures
457
+ * minted by the lost device — clearPendingDestroy skips destroyTexture);
458
+ * 2. post-process declarations + their eager param UBOs. Declarations are
459
+ * CPU-owned author intent and survive; UBOs are stale lost-device
460
+ * handles and are rebuilt after the replacement device is live.
461
+ * Idempotent and graph-optional (no-op when nothing has compiled yet).
462
+ */
463
+ resetForRecover(): void;
464
+ /** Recreate GPU-driven production state after internals.device is replaced. */
465
+ restoreGpuDrivenForRecover(): void;
466
+ /** Recreate post-process GPU parameter resources after a device rebuild. */
467
+ restorePostProcessResources(): void;
468
+ }
469
+
470
+ /**
471
+ * feat-20260601-customizable-render-pipeline-seam M2 / w10: the NARROW runtime-services
472
+ * surface a `RenderPipeline` pass closure consumes (UE `FRDGBuilder` runtime half). Bundles
473
+ * exactly the four `RenderSystemInternals` members the 9 urp closures reach
474
+ * directly: the GPU `device`, the structured-error sink `errorRegistry`, and the two
475
+ * per-MaterialShader pipeline-cache / param-schema lookups. `RenderPipelineContext.runtime`
476
+ * is typed as this interface, NOT the full `RenderSystemInternals` - a pipeline author
477
+ * cannot reach `context` / `getPipelineState` / `canvas` (charter P4: a
478
+ * consistent narrow abstraction over the runtime, not the kitchen-sink). `internals`
479
+ * itself is unreachable through the public ctx (the AC-08 oracle: `ctx.internals` is a
480
+ * compile error).
481
+ */
482
+ export interface RenderSystemRuntime {
483
+ readonly device: RhiDevice;
484
+ readonly errorRegistry: RhiErrorListenerRegistry;
485
+ /** @internal Emit directional shadow causal markers only for debug capture. */
486
+ readonly shadowDebugObservation?: boolean | undefined;
487
+ /** @internal Debug-only ParamSchema compatibility census; absent in production. */
488
+ readonly paramSchemaProjectionCensus?: ParamSchemaProjectionCensus | undefined;
489
+ /** @internal Depth-only fullscreen draw used to clear one invalid cascade tile. */
490
+ readonly getDirectionalShadowTileClearPipeline?: () => RenderPipeline | null;
491
+ /**
492
+ * feat-20260622-s5-device-surface-self-heal-recover M2 / w8: health registry
493
+ * threaded into the record stage so `recordFrame` can fire `internal-fault`
494
+ * when surface reconfigure+retry both fail (A-IN-2).
495
+ */
496
+ readonly healthRegistry: import('./lifecycle').HealthListenerRegistry;
497
+ /**
498
+ * Cooked material consumption boundary. Runtime record code may obtain a
499
+ * projection and content-addressed artifact here; it must not resolve an
500
+ * authored parent chain or compile a missing specialization.
501
+ */
502
+ readonly getMaterialProjection?: (materialGuid: string) => MaterialRenderProjection | undefined;
503
+ readonly getMaterialArtifact?: (specializationKey: string) => MaterialRuntimeArtifact | undefined;
504
+ /** Production MaterialReady/Error lookup used by the record draw gate. */
505
+ readonly getMaterialReadiness?: (materialGuid: string) => MaterialReadiness | undefined;
506
+ // feat-20260523-shader-template-instance-split M9-T03 (D-PipelineBuilder):
507
+ // per-MaterialShader pipeline cache lookup. Returns the cached pipeline
508
+ // for `materialShaderId`, lazily building on first miss via
509
+ // ShaderRegistry.findMaterialArtifact -> buildPipelineForMaterialShader.
510
+ // Returns `null` when:
511
+ // - the id is not registered in ShaderRegistry (authored materials skip
512
+ // the affected draw; feature-only callers may use the engine path)
513
+ // - the underlying async shader-module build is still pending (caller
514
+ // falls back for one frame and retries on the next; mirrors the
515
+ // `makeShaderDeviceAdapter` 1-frame-warmup idiom)
516
+ // - the pipeline build itself fails (caller fires a structured
517
+ // RhiError via errorRegistry; charter P3 explicit failure)
518
+ readonly getMaterialShaderPipeline?: (
519
+ materialShaderId: string,
520
+ isHdr: boolean,
521
+ renderState?: MaterialRenderState,
522
+ // feat-20260604 M3 / w9: per-mesh topology selects a per-topology PSO
523
+ // (WebGPU bakes topology into the immutable pipeline). Omitted resolves to
524
+ // 'triangle-list' (AC-03 zero-regression).
525
+ topology?: PrimitiveTopology,
526
+ // feat-20260604 M5 / w15: strip topologies bake the mesh's index width into
527
+ // primitive.stripIndexIndex. The record stage threads entry.mesh.indexFormat
528
+ // here so a uint16-indexed strip gets a uint16 PSO (not a hardcoded uint32).
529
+ // Ignored for list topologies (WebGPU spec: stripIndexFormat strip-only).
530
+ indexFormat?: 'uint16' | 'uint32',
531
+ // feat-20260609 M4 / w33: variantSet selects the per-variant WGSL from the
532
+ // shader manifest. When non-empty, the pipeline builder resolves the matching
533
+ // variant's composedWgsl instead of the boot-time default; the BGL is
534
+ // derived from paramSchema via derive() in pbr-pipeline (M3 / w12-w13).
535
+ // URP callers pass 'STORAGE_BUFFER_AVAILABLE=true'; HDRP callers pass
536
+ // 'CLUSTER_FORWARD_AVAILABLE=true+STORAGE_BUFFER_AVAILABLE=true'. Omitted
537
+ // (undefined / '') preserves backward-compatible behaviour (existing PSOs).
538
+ variantSet?: string,
539
+ // feat-20260609 M0 / T-002: passKind distinguishes forward (colour+DS)
540
+ // from shadow-caster passes in the PSO cache key. Defaults to
541
+ // 'forward' for backward compatibility (AC-06).
542
+ passKind?: PassKind,
543
+ // feat-20260611-fox-skinning-vertex-attribute-chain M4 / w16 (D-4):
544
+ // pbr-skin layoutKind reads its 6-attribute / 72-byte vertex buffer
545
+ // layout via `deriveVertexBufferLayout` (vertex-attribute-layout.ts SSOT).
546
+ // Callers with a resolved `MeshAsset.attributes` pass it through so the
547
+ // built PSO matches the mesh's real attribute set. Undefined falls
548
+ // through to the synthesized 6-key sentinel inside buildPipelineContext;
549
+ // non-skin layoutKinds ignore this parameter entirely.
550
+ meshAttributes?: import('@forgeax/engine-types').VertexAttributeMap,
551
+ // bug-20260615 M2 / m2-1: sampleCount drives the multisample descriptor
552
+ // field in the pipeline builder — it is a CAMERA fact (per-frame
553
+ // antialias setting). Default 1 preserves byte-identity of every
554
+ // pre-M2 cache slot + descriptor.
555
+ sampleCount?: number,
556
+ // feat-20260625-refactor-sprite-as-transparent-mesh R2 fix-up:
557
+ // LDR-color override for sub-passes whose attachment view is not the
558
+ // sRGB swap-chain view (LDR sprite split sub-pass writes through the
559
+ // storage / non-sRGB view of the same texture so premultiplied-alpha
560
+ // blends correctly). Threaded into the cache key + PSO descriptor.
561
+ // Undefined preserves the default sRGB view used by the geometry +
562
+ // tonemap + skybox callers. Ignored when `isHdr=true` or
563
+ // `passKind='shadow-caster'`.
564
+ colorFormatOverride?: GPUTextureFormat,
565
+ // Shader-declared UV count used by material pipeline cache aliases.
566
+ shaderUvSetCount?: number,
567
+ // `null` explicitly requests a color-only prepared-graphics pipeline;
568
+ // omitted keeps the normal forward material depth attachment.
569
+ depthFormatOverride?: GPUTextureFormat | null,
570
+ // Prepared graphics may select one of the host-owned canonical vertex
571
+ // layouts. Ordinary material callers leave this undefined.
572
+ vertexLayout?: string,
573
+ // Authored material GUID used to distinguish the publication-backed draw
574
+ // path from feature-only pipeline callers.
575
+ materialGuid?: string,
576
+ // Fragment entry point override for shaders with distinct color-domain
577
+ // entry points. Omitted keeps the shader's default `fs_main` entry.
578
+ fragmentEntry?: string,
579
+ /** Geometry-owned immutable projection carried to the renderer PSO seam. */
580
+ vertexLayoutProjection?: VertexLayoutProjection,
581
+ ) => RenderPipeline | null;
582
+ readonly getMaterialShaderBindingContract?: (
583
+ materialShaderId: string,
584
+ ) => 'group-0' | 'group-0-resource' | 'view-only' | 'view-with-resource' | 'render-material';
585
+ /**
586
+ * feat-20260527 M2 / w7: schema lookup for material param overlay.
587
+ * Returns the paramSchema for a registered material shader, or
588
+ * `undefined` when the shader is not in the ShaderRegistry.
589
+ * Record stage uses this instead of reading `MaterialSnapshot.paramSchema`.
590
+ */
591
+ readonly getParamSchema?: (materialShaderId: string) => readonly ParamSchemaEntry[] | undefined;
592
+ /**
593
+ * Runtime ParamSchema projection owner lookup. Registered shader consumers
594
+ * must prefer this immutable projection over deriving the same schema again.
595
+ * The optional seam keeps feature-only and legacy test runtimes compatible.
596
+ */
597
+ readonly getParamSchemaProjection?: (
598
+ materialShaderId: string,
599
+ ) => ImmutableParamSchemaProjection | undefined;
600
+ /**
601
+ * feat-20260621-learn-render-5-5-parallax M2 / w6 (D-1): the per-shader
602
+ * material BindGroupLayout for the given material shader. A custom shader
603
+ * declaring >3 user-region textures (e.g. parallax `heightTexture`) owns a
604
+ * material BGL whose entry count + injection start differ from the built-in
605
+ * 18-entry layout; the record stage must create the material bind group
606
+ * against THIS layout so the entry count matches. Returns `undefined` when
607
+ * the shader is unregistered or resolves to the shared built-in layout
608
+ * (3-texture shaders), in which case the caller falls back to
609
+ * `pipelineState.materialBindGroupLayout`.
610
+ */
611
+ readonly getMaterialBindGroupLayout?: (materialShaderId: string) => BindGroupLayout | undefined;
612
+ /**
613
+ * feat-20260527-sprite-nineslice M4 / w16 (D-5): per-Renderer metrics counter
614
+ * surfaced through `renderer.metrics`. Record-stage soft-warns (e.g.
615
+ * `nineslice.scale-too-small` when Transform.scale falls below the four
616
+ * 9-slice corner anchors) call `runtime.metrics.increment(name)` instead of
617
+ * a per-entity `console.warn` so AI users observe machine-readable counters
618
+ * (charter P3 over P-flooded text logs). Each Renderer owns its own
619
+ * EngineMetrics instance (D-5 candidate 1: multi-Renderer isolation).
620
+ */
621
+ readonly metrics: EngineMetrics;
622
+ /** Optional Render-owned membership timing capability. */
623
+ readonly membershipTiming?: MembershipTimingController | undefined;
624
+ /**
625
+ * feat-20260604-resource-owning-render-graph-and-fullscreen-postpr M3 / F-2 fix-up:
626
+ * post-process registry lookup. Returns the `PostProcessShaderEntry` registered
627
+ * via `renderer.postProcess.register(id, entry)`, or `undefined` when `id`
628
+ * resolves to no entry. `addFullscreenPass`'s execute closure dispatches on this
629
+ * to route to either the FXAA built-in path (id === 'fxaa') or the generic
630
+ * `buildFullscreenPostProcessPass + createFullscreenBindGroup` path; an
631
+ * unregistered id surfaces as a thrown `PostProcessError({code:'post-process-not-found'})`
632
+ * fail-fast (charter P3 / pipeline-errors throw template).
633
+ *
634
+ * Optional so a custom RenderSystemRuntime fixture (test doubles) need not
635
+ * supply it; the engine's own createRenderSystem populates it unconditionally.
636
+ */
637
+ readonly lookupPostProcess?: (id: string) => PostProcessShaderEntry | undefined;
638
+ /**
639
+ * feat-20260621-fullscreen-post-process-per-frame-uniform-params-l M-A2 / w8:
640
+ * per-shader params UBO accessor. Returns the eager-created (at register time,
641
+ * M-A1 / w5) GPU buffer for `id`, or `undefined` when the id has no params
642
+ * (param-less consumer) / is unregistered. dispatchFullscreenPass reads this to
643
+ * writeBuffer the per-frame snapshot bytes and bind the buffer at group(1)
644
+ * binding(2). Optional so test fixtures need not supply it; createRenderSystem
645
+ * populates it unconditionally (mirrors lookupPostProcess / getPostProcessPipeline).
646
+ */
647
+ readonly getPostProcessParamsBuffer?: (id: string) => Buffer | undefined;
648
+ /**
649
+ * feat-20260609-learn-render-4-5-framebuffers-demo-offscreen-rt-an M4 / T-10-a:
650
+ * post-process render-pipeline lookup with eager-on-first-call build. Returns a
651
+ * cached `RenderPipeline` (RHI handle) for `id`, lazily building on first call
652
+ * via the closure passed through `RenderSystemInternals.buildPostProcessPipeline`.
653
+ * Returns `null` when:
654
+ * - the id is not registered in the post-process registry (caller skips the
655
+ * pass — paired with the `'post-process-not-found'` throw site, this branch
656
+ * is unreachable on the happy path)
657
+ * - the underlying async shader-module compile is still pending (caller falls
658
+ * back for one frame and retries on the next; mirrors the
659
+ * `getMaterialShaderPipeline` 1-frame-warmup idiom)
660
+ * - the pipeline build itself fails (caller skips the pass; the build path
661
+ * fires a structured RhiError via errorRegistry; charter P3 explicit failure)
662
+ *
663
+ * Solves M1 CONCERN-1: the dispatcher in `dispatchFullscreenPass` previously
664
+ * passed `pipeline=null` to `built.createHandle` because the per-frame execute
665
+ * closure cannot await `createShaderModule` (async). With this lookup the
666
+ * dispatcher reads the pipeline synchronously; warm-up costs one frame.
667
+ *
668
+ * `bgl` is the fullscreen input-texture BGL the dispatcher already built via
669
+ * `buildFullscreenPostProcessPass`. The engine assumes a single static BGL
670
+ * shape (FULLSCREEN_BGL_DESCRIPTOR) so the pipeline cache keys on `id` only;
671
+ * subsequent calls reuse the cached pipeline regardless of which BGL identity
672
+ * is threaded.
673
+ *
674
+ * `colorFormat` is the swap-chain / target color format the post-process
675
+ * pipeline writes (`bgra8unorm-srgb` for swap-chain, the offscreen RT format
676
+ * otherwise). Cache key is `id|colorFormat`.
677
+ *
678
+ * Optional so a custom RenderSystemRuntime fixture (test doubles) need not
679
+ * supply it; the engine's own createRenderSystem populates it when
680
+ * `RenderSystemInternals.buildPostProcessPipeline` is provided.
681
+ */
682
+ readonly getPostProcessPipeline?: (
683
+ id: string,
684
+ bgl: BindGroupLayout,
685
+ colorFormat: GPUTextureFormat,
686
+ ) => RenderPipeline | null;
687
+ /**
688
+ * feat-20260623-world-space-video-asset M4 / w16 (D-3): transient per-frame
689
+ * texture store for VideoAsset sources. Independent of {@link gpuStore} — the
690
+ * record stage routes a `MaterialSnapshot.videoTextureFields` field through
691
+ * this store (per-frame copyExternalImageToTexture upload + current-frame view)
692
+ * instead of `gpuStore.ensureResident` (whose static cache video must never
693
+ * enter, AC-08). Optional so test fixtures that drive recordFrame manually
694
+ * need not supply one — a video field then degrades to the default view
695
+ * (charter P3). The production createRenderer always wires it.
696
+ */
697
+ readonly dynamicTextureStore?: DynamicTextureStore | undefined;
698
+ }
699
+
700
+ export interface RenderSystemInternals extends RenderSystemRuntime {
701
+ readonly canvas: HTMLCanvasElement | OffscreenCanvas;
702
+ /** Optional feature host supplied by the renderer assembly layer. */
703
+ readonly featureHost?: RenderFeatureHost | undefined;
704
+ readonly shaderModuleFactory?: import('./pipeline-builder').PipelineBuilderShaderModuleFactory;
705
+ /** Optional host profiler capability for the existing Render path. */
706
+ readonly profiler?: Profiler | undefined;
707
+ // M6 / w41 (feat-20260510-rhi-resource-creation): the canvas context is the
708
+ // forgeax `RhiCanvasContext` brand; render-system-record.ts uses
709
+ // `getCurrentTexture()` -> `device.createTextureView(...)` (K-4 two-step
710
+ // explicit form, charter proposition 5 consistent abstraction red line).
711
+ readonly context: RhiCanvasContext | null;
712
+ // feat-20260608-create-app-param-surface-trim / M1 / AC-02: the legacy
713
+ // `clearColor` field is removed. The record stage reads clear color
714
+ // straight from the Camera SoA (`camera.clearColor`, array<f32,4> as of
715
+ // feat-20260709 M3); zero-Camera fallback uses
716
+ // `ZERO_CAMERA_CLEAR_FALLBACK = [0, 0, 0, 1]`.
717
+ readonly getPipelineState: () => PipelineState | null;
718
+ readonly assets: RenderAssetPort;
719
+ // feat-20260601-gpu-resource-store-extraction M1: GPU residency layer
720
+ // extracted out of AssetRegistry. Record stage reads GPU texture / cubemap /
721
+ // mesh handles through the store; CPU POD reads stay on `assets`.
722
+ readonly gpuStore: GpuResourceStore;
723
+ // feat-20260608-mesh-ssbo-dynamic-grow-l1-lift-1024-entity-cap M3 / T-M3-04:
724
+ // mesh-SSBO grow hook + read-only state surface threaded into the record
725
+ // stage so `ensureMeshSsboCapacity(internals, validatedOrdered.length)` can
726
+ // bridge the recordFrame → growController seam without leaking the full
727
+ // controller object into RenderSystemRuntime (the narrow ctx). Both fields
728
+ // are optional for test fixtures that wire createRenderSystem manually
729
+ // without a controller (legacy path returns ok:true and short-circuits);
730
+ // the production createRenderer always sets both. The `| undefined`
731
+ // suffix keeps both fields assignable from the WebGPU-internals carrier
732
+ // whose own field is `?:` -- exactOptionalPropertyTypes ABI compat.
733
+ readonly growMeshSsbo?:
734
+ | ((neededSlots: number) =>
735
+ | { readonly ok: true }
736
+ | {
737
+ readonly ok: false;
738
+ readonly code: 'mesh-ssbo-ceiling-reached' | 'mesh-ssbo-capacity-exceeded';
739
+ readonly degradedToSlotCount: number;
740
+ })
741
+ | undefined;
742
+ readonly meshSsboState?: { readonly slotCount: number } | undefined;
743
+ /**
744
+ * feat-20260609 M4 / T-10-a: factory backing `getPostProcessPipeline`. Provided
745
+ * by `createRenderer.ts` (it owns the shared `getShaderModuleAdapter` and the
746
+ * fullscreen pipeline-layout builder); receives a registered
747
+ * `PostProcessShaderEntry` + the fullscreen BGL the dispatcher already
748
+ * composed + the target color format, returns a built `RenderPipeline`
749
+ * (RHI handle) or `null` (shader still compiling / build failed). The first
750
+ * call per id triggers the async shader compile; subsequent calls hit the
751
+ * RenderSystem-level cache and never reach this factory.
752
+ *
753
+ * Optional so test fixtures (createRenderSystem with a stub
754
+ * RenderSystemInternals) need not provide a real factory; without it
755
+ * `getPostProcessPipeline` resolves to `undefined` on the runtime surface
756
+ * and the dispatcher falls through to its existing `null`-skip branch.
757
+ */
758
+ readonly buildPostProcessPipeline?:
759
+ | ((
760
+ entry: PostProcessShaderEntry,
761
+ bgl: BindGroupLayout,
762
+ colorFormat: GPUTextureFormat,
763
+ label: string,
764
+ ) => RenderPipeline | null)
765
+ | undefined;
766
+ }
767
+
768
+ function isStructuredRendererError(
769
+ error: unknown,
770
+ ): error is RhiError | RenderError | PostProcessErrorType {
771
+ if (!(error instanceof Error)) return false;
772
+ const structured = error as {
773
+ readonly code?: unknown;
774
+ readonly expected?: unknown;
775
+ readonly hint?: unknown;
776
+ readonly detail?: unknown;
777
+ };
778
+ return (
779
+ typeof structured.code === 'string' &&
780
+ typeof structured.expected === 'string' &&
781
+ typeof structured.hint === 'string' &&
782
+ structured.detail !== undefined
783
+ );
784
+ }
785
+
786
+ function reportPreparedGraphicsCompletionError(
787
+ internals: RenderSystemInternals,
788
+ error: unknown,
789
+ ): void {
790
+ if (isStructuredRendererError(error)) {
791
+ internals.errorRegistry.fire(error);
792
+ return;
793
+ }
794
+ const innerError =
795
+ error instanceof RhiError
796
+ ? error
797
+ : { code: 'unknown' as const, message: String(error), name: (error as Error)?.name };
798
+ internals.errorRegistry.fire(
799
+ new RhiError({
800
+ code: 'webgpu-runtime-error',
801
+ expected: 'prepared graphics completion cleanup reports its errors',
802
+ hint: 'inspect detail.error for the underlying retirement or recovery failure',
803
+ detail: { error: innerError },
804
+ }),
805
+ );
806
+ }
807
+
808
+ export interface RenderFeatureGraphRuntimeState {
809
+ contributions: readonly RenderFeatureGraphContribution<RenderFeaturePassContext>[];
810
+ topologySignature: string | undefined;
811
+ composition:
812
+ | RenderFeatureGraphComposition<RenderPipelineContext, RenderFeaturePassContext>
813
+ | undefined;
814
+ }
815
+
816
+ const renderFeatureGraphStates = new WeakMap<
817
+ RenderSystemInternals,
818
+ RenderFeatureGraphRuntimeState
819
+ >();
820
+
821
+ export function getRenderFeatureGraphState(
822
+ internals: RenderSystemInternals,
823
+ ): RenderFeatureGraphRuntimeState {
824
+ const existing = renderFeatureGraphStates.get(internals);
825
+ if (existing !== undefined) return existing;
826
+ const created: RenderFeatureGraphRuntimeState = {
827
+ contributions: [],
828
+ topologySignature: undefined,
829
+ composition: undefined,
830
+ };
831
+ renderFeatureGraphStates.set(internals, created);
832
+ return created;
833
+ }
834
+
835
+ function resetRenderFeatureGraphState(internals: RenderSystemInternals): void {
836
+ const state = getRenderFeatureGraphState(internals);
837
+ state.contributions = [];
838
+ state.topologySignature = undefined;
839
+ state.composition = undefined;
840
+ }
841
+
842
+ export function reportRenderFeatureGraphError(
843
+ internals: RenderSystemInternals,
844
+ error: RenderError,
845
+ ): void {
846
+ if (internals.featureHost !== undefined && 'detail' in error) {
847
+ const detail = error.detail;
848
+ if (detail !== undefined && 'featureIdentity' in detail && 'order' in detail) {
849
+ const owned = internals.featureHost.recordError(detail.featureIdentity, error);
850
+ internals.errorRegistry.fire(owned);
851
+ return;
852
+ }
853
+ }
854
+ internals.errorRegistry.fire(error);
855
+ }
856
+
857
+ function isPendingRenderFeaturePreparation(error: RenderError): boolean {
858
+ return (
859
+ error.code === 'render-feature-preparation-failed' &&
860
+ error.detail.reason.startsWith('rhi-not-available:')
861
+ );
862
+ }
863
+
864
+ function makePreparedPipelinePendingError(): RhiError {
865
+ return new RhiError({
866
+ code: 'rhi-not-available',
867
+ expected: 'prepared pipeline shader module warm-up to finish asynchronously',
868
+ hint: 'retry the prepared graphics pass on the next frame',
869
+ });
870
+ }
871
+
872
+ export interface PipelineState {
873
+ readonly format: string;
874
+ // Color-attachment view format. May differ from `format` (canvas storage)
875
+ // when an sRGB-encoding view is requested over a linear storage texture.
876
+ // Backend-aware SSOT: selectSwapChainFormat in createRenderer.ts derives
877
+ // both format and colorAttachmentFormat from storageBufferCapable
878
+ // (Channel 2 UA-preferred bgra8unorm / Channel 3 GLES fallback rgba8unorm);
879
+ // bug-20260612-webgpu-canvas-format-prefer-bgra supersedes the previous
880
+ // module-level SWAP_CHAIN_VIEW_FORMAT constant (bug-20260519 / bug-20260610).
881
+ // Equal to `format` for offscreen render targets.
882
+ readonly colorAttachmentFormat: string;
883
+
884
+ // Per-frame uniform / storage buffers + bind group layouts used to compose
885
+ // the 3 BindGroups (view / material / mesh-array) the pbr.wgsl pipeline
886
+ // expects (D-S2 + plan-strategy 1 architecture). The view + material UBOs
887
+ // and the mesh SSBO are reused across frames; only the contents are
888
+ // queue.writeBuffer-updated each draw([world], { cameraOwner: 0, resourceOwner: 0 }) invocation.
889
+ readonly viewBindGroupLayout: BindGroupLayout;
890
+ readonly materialBindGroupLayout: BindGroupLayout;
891
+ readonly meshBindGroupLayout: BindGroupLayout;
892
+ readonly viewUniformBuffer: Buffer;
893
+ // feat-20260613-csm-cascaded-shadow-maps M5 / w28: per-pass shadow_caster
894
+ // cascade-index UBO. 16 B (1 u32 + 12 B pad to satisfy the 16 B uniform
895
+ // buffer alignment). The host writes `index = i` (0..3) before each
896
+ // cascade's recordShadowPass submit; shadow_caster.wgsl reads it via
897
+ // `@group(0) @binding(5) shadowCasterCascade.index` to pick the matching
898
+ // `view.lightViewProj_X`. Forward shaders declare the binding (so the
899
+ // shared view BGL accommodates both pipelines) but never reference it.
900
+ readonly shadowCasterCascadeBuffer: Buffer;
901
+ // feat-20260608-mesh-ssbo-dynamic-grow-l1-lift-1024-entity-cap M2 / T-M2-06:
902
+ // materialUniformBuffer + meshStorageBuffer fields hold wrapper objects
903
+ // (`{ buffer, sizeInBytes }`) instead of bare `Buffer` handles. The outer
904
+ // wrapper-object identity is stable across grow events (research §F8 R1)
905
+ // so PipelineState references survive grow without re-bind cycles; the
906
+ // inner `.buffer` is replaced by `growMeshSsbo` (createRenderer.ts /
907
+ // T-M2-05). Consumers must read `.buffer` to reach the underlying
908
+ // `Buffer` handle (M3-04: `pipelineState.meshStorageBuffer.buffer` /
909
+ // `.materialUniformBuffer.buffer`); using the wrapper directly as a
910
+ // WeakMap chain key would bind the cache to the wrapper object identity
911
+ // (which never changes) instead of the inner buffer identity (which DOES
912
+ // change on grow), defeating the cache miss -> re-bind path (D-3
913
+ // grep-gate guards this).
914
+ readonly materialUniformBuffer: { readonly buffer: Buffer; readonly sizeInBytes: number };
915
+ readonly meshStorageBuffer: { readonly buffer: Buffer; readonly sizeInBytes: number };
916
+ // feat-20260519-light-casters-point-spot-pbr M3 / w20 (D-S1 + D-S2):
917
+ // PointLight + SpotLight std430 storage buffers occupy two new
918
+ // viewBindGroupLayout entries (binding 1 + 2) alongside the existing
919
+ // viewUniformBuffer (binding 0). Each buffer carries a 16 B std430 header
920
+ // (count u32 + 12 B pad) followed by a fixed 4-slot first-slice cap
921
+ // (32 B per PointLight / 48 B per SpotLight; total 144 B / 208 B). The
922
+ // record stage rewrites both buffers per frame via `queue.writeBuffer`
923
+ // (D-S6 per-frame full rewrite); the bind-group layout entries exist
924
+ // even when shaders do not yet reference them so the M4 pbr.wgsl
925
+ // multi-light helper landing requires no further createRenderer
926
+ // changes (charter P5 consistent abstraction; AC-04 c byte-frozen
927
+ // layout). Cap-gate at createRenderer time
928
+ // (`assertStorageBufferCap >= 4`) keeps the layout reachable before any
929
+ // frame records (R-4 + plan-strategy 4 risk table).
930
+ readonly pointLightsBuffer: Buffer;
931
+ readonly spotLightsBuffer: Buffer;
932
+ // feat-20260513-instanced-mesh M3 (T-M3-2 / T-M3-3): SSBO single-branch
933
+ // record-stage. `meshStorageBuffer` carries one `entity_world` mat4 per
934
+ // renderable (256-byte stride for dynamic-offset alignment); the
935
+ // `instancesBindGroupLayout` + `identityInstanceBuffer` form the second
936
+ // tier of the chained transform: shader composes
937
+ // `world = entity_world * instances_local[instance_index]`. When a
938
+ // renderable does not carry an `Instances` component the record stage
939
+ // binds the shared 1-element identity-mat4 fallback (`drawIndexed
940
+ // instanceCount=1`); when it does, the per-entity GPU storage buffer
941
+ // owned by the record stage's `frameState.instanceBuffers` cache is
942
+ // bound (`drawIndexed instanceCount=Instances.transforms.count / 16`).
943
+ // feat-20260514 M3 / w15: the legacy
944
+ // `AssetRegistry.createInstancedBuffer` triplet is gone — Instances data
945
+ // flows entirely through the ECS-managed `array<f32>` field; the record
946
+ // stage owns GPU storage buffer allocation + `LimitExceededDetail`
947
+ // emit + `caps.storageBuffer` cap-gate.
948
+ readonly instancesBindGroupLayout: BindGroupLayout;
949
+ readonly identityInstanceBuffer: Buffer;
950
+
951
+ // feat-20260515 M3 / T-M3-05 (research F-6 fix): default sampler +
952
+ // fallback 1x1 white textureView seed the materialBindGroup binding=1 /
953
+ // binding=2 entries when MaterialAsset.baseColorTexture is undefined.
954
+ // The defaults follow research F-5 SSOT (linear min/mag/mipmap +
955
+ // repeat) so AI users that don't supply a texture still get a sensible
956
+ // sampling configuration without having to register a SamplerAsset
957
+ // (charter F2 minimal surface).
958
+ readonly defaultSampler: Sampler;
959
+ // Nearest-neighbour (mag=nearest, min=nearest, mip=nearest, clamp-to-edge)
960
+ // sampler used for sprite / tilemap materials so pixel-art tiles render sharp.
961
+ readonly nearestSampler: Sampler;
962
+ readonly fallbackTextureView: TextureView;
963
+
964
+ // bug-20260519: BUILTIN_CUBE / BUILTIN_TRIANGLE migrated to 12-floats
965
+ // (position + normal + uv + tangent) so a single (`unlit-procedural` /
966
+ // `standard`) pipeline pair handles all renderables. The legacy
967
+ // `unlitBuiltinPipeline` + zero-stride `unlitBuiltinDummyAttrBuffer`
968
+ // (which hard-coded uv = (0,0) for BUILTIN cubes) are deleted.
969
+ //
970
+ // - `unlitPipeline` : unlit module + 12F vertex stride.
971
+ // Routed to every entity whose
972
+ // shader identity is `forgeax::default-unlit`.
973
+ // - `standardPipeline` : pbr module + 12F vertex stride.
974
+ // Routed to every entity carrying a
975
+ // standard / GGX-PBR material.
976
+ //
977
+ // Both pipelines share the same 4-BindGroupLayout chain (view + material +
978
+ // mesh-array + instances). The record stage selects between them on
979
+ // `mat.materialShaderId` only (D-2 BUILTIN-vs-procedural distinction retired).
980
+ // bug-20260519 D-3: nullable when manifest carries zero entries (Camera-
981
+ // only / clear-pass-only path; D-1 + D-2 + plan-strategy section 1
982
+ // mermaid). The render-time access point in `render-system-record.ts`
983
+ // narrows on `=== null` and fires a structured `RhiError
984
+ // shader-compile-failed` (charter P3 explicit failure; AC-03).
985
+ readonly unlitPipeline: RenderPipeline | null;
986
+ readonly standardPipeline: RenderPipeline | null;
987
+ /**
988
+ * feat-20260604-learn-render-4.10-anti-aliasing-msaa M2 / w8: count=4
989
+ * multisample variants of the 7 geometry pipelines that write the screen
990
+ * or HDR colour target. A pipeline's `multisample.count` must match the
991
+ * sampleCount of the colour attachment it writes (WebGPU validation),
992
+ * so a count=4 pass cannot reuse a count=1 pipeline -- the record stage
993
+ * picks the `*Msaa` variant when the active camera carries
994
+ * `antialias === 'msaa'`. Post-process + shadow pipelines stay single-
995
+ * sample (AC-06) and have no MSAA variant. `null` when the base pipeline
996
+ * is null (empty-manifest path).
997
+ */
998
+ readonly unlitPipelineMsaa: RenderPipeline | null;
999
+ readonly standardPipelineMsaa: RenderPipeline | null;
1000
+ // feat-20260625-refactor-sprite-as-transparent-mesh M3 / w14 (D-7 / AC-12):
1001
+ // the four sprite-dedicated PSO fields are gone — sprite PSO now flows
1002
+ // through `runtime.getMaterialShaderPipeline('forgeax::sprite', ...)`
1003
+ // keyed on the premultiplied-alpha renderState the record stage
1004
+ // assembles for any transparent material (plan-strategy D-7). Concept
1005
+ // count -4 fields on PipelineState; sprite's "is a transparent mesh"
1006
+ // story is told entirely by the generic cache + `material.transparent`
1007
+ // (derived by the extract stage from `passes[0].renderState.blend !==
1008
+ // undefined`, the post-feat-20260626-collapse SSOT).
1009
+ readonly unlitPipelineHdrMsaa: RenderPipeline | null;
1010
+ readonly standardPipelineHdrMsaa: RenderPipeline | null;
1011
+ /**
1012
+ * feat-20260523-shader-template-instance-split M9-T03 (D-PipelineBuilder):
1013
+ * the shared 4-BindGroupLayout chain pipeline layout (`[view, material,
1014
+ * mesh-array, instances]`) -- same handle the standard / unlit / sprite
1015
+ * pipelines share. M9 exposes it on PipelineState so the per-MaterialShader
1016
+ * pipeline cache (`getMaterialShaderPipeline`) can reuse it at lazy build
1017
+ * time without re-running pbrLayouts construction (charter P4 consistent
1018
+ * abstraction). `null` when the manifest is empty (Camera-only / clear-
1019
+ * pass-only path; bug-20260519 D-3 nullable).
1020
+ */
1021
+ readonly pbrPipelineLayout: PipelineLayout | null;
1022
+ /**
1023
+ * feat-20260609-hdrp-cluster-fragment-ggx M4.5 / w36 (D-10 option A):
1024
+ * per-variant PipelineLayout for HDRP. Mirrors `pbrPipelineLayout` but
1025
+ * substitutes the HDRP unified 7-slot group(2) BGL
1026
+ * (`createHdrpBindGroupLayoutDescriptor`) for the 1-slot pbr-mesh-array
1027
+ * BGL. Built once at boot and reused for any HDRP variant PSO. `null`
1028
+ * when the manifest is empty (parallel to `pbrPipelineLayout`) or when
1029
+ * the boot-time createBindGroupLayout / createPipelineLayout fails (in
1030
+ * which case `selectPipelineLayoutForVariant` falls back to the URP
1031
+ * `pbrPipelineLayout` instead of hard-disabling the build path).
1032
+ */
1033
+ readonly hdrpPbrPipelineLayout: PipelineLayout | null;
1034
+ /** WebGPU storage-path producer for ordered HDRP cluster memberships. */
1035
+ readonly hdrpClusterMembershipPipeline: ComputePipeline | null;
1036
+ /** Compute bind-group layout paired with the membership producer pipeline. */
1037
+ readonly hdrpClusterMembershipBindGroupLayout: BindGroupLayout | null;
1038
+ /**
1039
+ * bug-20260611-skin-pipeline-layout: dedicated PipelineLayout for the
1040
+ * `forgeax::pbr-skin` material shader. Mirrors `pbrPipelineLayout` but
1041
+ * substitutes a 3-entry mesh-array BGL (binding 0 = meshes, bindings 1/2 =
1042
+ * current/previous palettes) for standard PBR's 1-entry mesh-array BGL. Built once at boot
1043
+ * by `buildPbrSkinLayouts` and selected by
1044
+ * `selectPipelineLayoutForVariant` when the caller passes
1045
+ * `LayoutKind = 'pbr-skin'`. `null` when manifest is empty or the skin
1046
+ * shader is not registered (storage-buffer cap gate / register failure);
1047
+ * `selectPipelineLayoutForVariant` returns `null` rather than silently
1048
+ * falling back to URP layout (charter P3 explicit failure, mirroring the
1049
+ * `hdrp-active-must-not-fallback-to-urp-pipeline` guard).
1050
+ */
1051
+ readonly pbrSkinPipelineLayout: PipelineLayout | null;
1052
+ /**
1053
+ * feat-20260611 R2 / M8 / w28 (IS-14): record-stage handle to the
1054
+ * 3-binding `pbr-skin-mesh-array-bgl` returned by `buildPbrSkinLayouts`
1055
+ * (binding 0 mesh-array UBO, bindings 1/2 current/previous palette UBOs;
1056
+ * all `hasDynamicOffset: true`). The record stage builds a BG against this
1057
+ * BGL for skin entries (`entry.source.skin !== undefined`) and binds it
1058
+ * at group(2) when the entry's pipeline layout is `pbr-skin-pl`. The
1059
+ * URP path keeps using `meshBindGroupLayout` (1-binding) at group(2),
1060
+ * so `pbr-mesh-array-bgl` is unchanged. Stays `null` when
1061
+ * `pbrSkinPipelineLayout` itself failed to build (charter P3 explicit
1062
+ * failure -- skin path is hard-disabled, mirroring the pipeline-layout
1063
+ * fallback in `selectPipelineLayoutForVariant`).
1064
+ */
1065
+ readonly pbrSkinMeshBindGroupLayout: BindGroupLayout | null;
1066
+ /**
1067
+ * feat-20260612-skin-palette-per-frame-upload M1 / m1-2: animator-ready
1068
+ * skin-palette storage allocator. Replaces the prior identity-buffer
1069
+ * stub (PR #353 / feat-20260611 R2 / M8 / w28 IS-14) -- a single 16320 B
1070
+ * identity-seeded UBO shared by every skin entry. The allocator owns the
1071
+ * lifecycle of the per-frame palette buffer (`createSkinPaletteAllocator`
1072
+ * from `./systems/skin-palette-allocator`); the record stage reads the
1073
+ * GPU buffer through `skinPaletteAllocator.buffer` and the extract stage
1074
+ * (M2) calls `allocateSlice` + `writeJointPalette` to land animated
1075
+ * palette data per skinned entity. Per plan-strategy D-1 candidate (b) the
1076
+ * allocator is the single authoritative carrier -- no parallel fallback
1077
+ * stub. `null` when `pbrSkinPipelineLayout` itself failed (skin path
1078
+ * hard-disabled, mirroring the prior stub field's gating).
1079
+ */
1080
+ readonly skinPaletteAllocator: SkinPaletteAllocator | null;
1081
+ // 1x1 white texture view (feat-20260518 M3 / w13 + AC-06): seeds the
1082
+ // baseColorTexture (binding 2) and metallicRoughnessTexture (binding 4)
1083
+ // entries when the schema-driven MaterialAsset values omit the optional textures.
1084
+ // Reuses the same sampling-friendly default as `fallbackTextureView`
1085
+ // (above); the alias keeps the new MVP code path declarative without
1086
+ // renaming the existing field. Note: normalTexture (binding 6) does
1087
+ // NOT use this view -- it has its own RG-encoded fallback below.
1088
+ readonly defaultWhiteTextureView: TextureView;
1089
+ // 1x1 RGBA8 (128,128,255,255) view dedicated to the normalTexture slot
1090
+ // (binding 6). pbr.wgsl decodes sample.rg * 2 - 1 + z = sqrt(1-x^2-y^2),
1091
+ // so RG=(128,128)=0.5 maps to tangent (0,0,1) -- zero perturbation when
1092
+ // normalTexture is absent. White (255,255) would yield sqrt(1-2)=NaN
1093
+ // under saturate (clamps to 0) -> tangent.z=0 -> N rotated into the
1094
+ // tangent plane (severely wrong). Separate view because baseColor /
1095
+ // metallicRoughness require white-on-missing, normal requires (0,0,1).
1096
+ readonly defaultNormalTextureView: TextureView;
1097
+
1098
+ // ── feat-20260519-tonemap-reinhard-mvp / M2 / T-M2.5 ──────────────────────
1099
+ //
1100
+ // HDR (rgba16float) variants of `unlitPipeline` / `standardPipeline`. AI
1101
+ // users opt in via `Camera.tonemap === 'reinhard-extended'`; the record
1102
+ // stage picks `unlitPipelineHdr` / `standardPipelineHdr` when the active
1103
+ // camera's tonemap field is non-'none', and writes the geometry pass into
1104
+ // `hdrColorView` instead of the swap-chain view. The post-process tonemap
1105
+ // pass then reads `hdrColorView` and writes the final LDR pixels into the
1106
+ // swap-chain view (charter P3 explicit failure: a wrong format combination
1107
+ // would otherwise silently produce mis-tonemapped pixels).
1108
+ //
1109
+ // Both HDR pipelines share the same 4-BindGroupLayout chain as their
1110
+ // sRGB siblings — only the colour-attachment format differs (D-2 +
1111
+ // plan-strategy D-3).
1112
+ //
1113
+ // bug-20260519 D-3 nullable extension: when the renderer starts with a
1114
+ // zero-entry shader manifest the entire HDR + tonemap-resource block in
1115
+ // `createRenderer.ts` is skipped (Camera-only / clear-pass-only path),
1116
+ // so these fields stay `null`. Record-stage HDR pipeline dispatch +
1117
+ // fullscreen tonemap pass narrow on `=== null` and fire structured
1118
+ // `shader-compile-failed` (charter P3 explicit failure; AC-03).
1119
+ readonly unlitPipelineHdr: RenderPipeline | null;
1120
+ readonly standardPipelineHdr: RenderPipeline | null;
1121
+
1122
+ /**
1123
+ * feat-20260520-directional-light-shadow-mapping M2 / w14 (D-1):
1124
+ * 1x1 depth32float fallback bound at viewBindGroup binding(3) when no
1125
+ * shadow RT exists (castShadow:false or allocation failed).
1126
+ * Cleared to 1.0 (far plane) so comparison-sampler always returns fully lit.
1127
+ */
1128
+ readonly shadowFallbackTextureView: TextureView;
1129
+
1130
+ /**
1131
+ * feat-20260612-point-light-shadows-urp-hdrp Round-2 F-1: 1x1x6
1132
+ * depth32float `texture_depth_cube_array` (layers=1) fallback bound at
1133
+ * viewBindGroup binding(5) when no PointLightShadow snapshots are active
1134
+ * (zero-shadow scene = AC-09 zero allocation -- the real cube_array atlas
1135
+ * stays in `ShadowAtlas` and is only allocated when the extract stage
1136
+ * sees its first PointLightShadow). Cleared to 1.0 so the
1137
+ * comparison-sampler returns fully lit on the no-shadow path. The view
1138
+ * dimension is `cube-array` to satisfy the BGL `viewDimension:
1139
+ * 'cube-array'`; the underlying texture has 6 layers (one cube).
1140
+ */
1141
+ readonly shadowAtlasFallbackTextureView: TextureView;
1142
+
1143
+ /**
1144
+ * feat-20260612-point-light-shadows-urp-hdrp Round-2 F-1: 64 B uniform
1145
+ * buffer carrying `array<vec4<f32>, 4>` -- one lane per shadow-casting
1146
+ * point light slot. Lane N stores `(near, far, 1/(far-near), 0)` for the
1147
+ * point light with `shadowAtlasLayer === N`. Lanes for non-shadow-casting
1148
+ * slots stay zeroed; the WGSL sample path is gated by
1149
+ * `PointLight.shadowAtlasLayer >= 0` so zeroed lanes are never read.
1150
+ * Bound at viewBindGroup binding(6); written per frame from the
1151
+ * `pointShadowSnapshots` array.
1152
+ */
1153
+ readonly shadowParamsBuffer: Buffer;
1154
+
1155
+ // feat-20260625-spot-light-shadow-mapping w25 (scope-amend webkit-fallback):
1156
+ // the per-spot fragment-read perspective lightViewProj matrices no longer
1157
+ // occupy a dedicated `spotLightViewProjBuffer` / view-BG binding 9 — they fold
1158
+ // into the View UBO tail (`view.spotLightViewProj`, bytes 528..784) written by
1159
+ // render-system-record's viewPayload. The standalone uniform buffer pushed the
1160
+ // WebGL2 fallback fragment uniform-buffer count to 12, over GLES 3.0's
1161
+ // `max_uniform_buffers_per_shader_stage = 11`. Caster vertex channel (binding
1162
+ // 7) is untouched: same-frame write contention only applies to casters (D-1).
1163
+
1164
+ // ── feat-20260520-directional-light-shadow-mapping M2 / w15 (AC-12) ─────
1165
+ //
1166
+ // GPU shadow-factor probe pipeline. `debugSampleShadowFactor` packs N world
1167
+ // positions into `shadowProbeInputBuf` (`array<vec4<f32>, PROBE_MAX_COUNT>`),
1168
+ // writes the active lightSpaceMatrix into `shadowProbeLsmUbo`, builds a
1169
+ // transient BindGroup binding the active shadow texture + comparison
1170
+ // sampler, and renders 1 pixel per probe into `shadowProbeOutputTex`
1171
+ // (1xN rgba32float). The fragment stage runs the same atlas-depth PCF path
1172
+ // as `pbr.wgsl::evalDirectional()` and returns factor, center depth,
1173
+ // cascade index, and receiver depth in the four channels. The 1-row staging
1174
+ // buffer (1024 B = PROBE_MAX_COUNT * 16 B; already 256B-aligned) is mapped
1175
+ // and the leading N vec4 records returned. Compiled once at pipeline build
1176
+ // time; null when the shader manifest is empty (no probe possible).
1177
+ readonly shadowProbePipeline: RenderPipeline | null;
1178
+ readonly shadowProbeBindGroupLayout: BindGroupLayout | null;
1179
+ readonly shadowProbeLsmUbo: Buffer | null;
1180
+ readonly shadowProbeInputBuf: Buffer | null;
1181
+ // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle (matches sibling fields)
1182
+ readonly shadowProbeOutputTex: any | null;
1183
+ readonly shadowProbeOutputView: TextureView | null;
1184
+ readonly shadowProbeStagingBuf: Buffer | null;
1185
+
1186
+ /**
1187
+ * Fallback Skylight resource bundle (feat-20260520-skylight-ibl-cubemap
1188
+ * M2 round-2 / t40, plan-strategy D-5). 1x1 all-zero rgba16float
1189
+ * texture_cube * 2 (irradiance + prefilter) + 1x1 approximate rg16float
1190
+ * brdfLut + intensity=0 16 B uniform buffer + 7-entry BindGroup compose
1191
+ * the @group(4) skylight binding for the "no Skylight ECS entity"
1192
+ * branch. The M4 round-2 recordFrame branch binds `bindGroup` when
1193
+ * `skylightCount === 0` so `standardPipeline` / `standardPipelineHdr`
1194
+ * (which keep a 4-slot pipeline layout per D-5 round-4) dispatch with
1195
+ * ambient=0 -- physical convergence with D-4 (charter F1: AI users
1196
+ * writing demos do not need a "is there a skylight?" branch).
1197
+ *
1198
+ * D-5 round-4: the fallback bundle no longer carries a stand-alone
1199
+ * BindGroup. The PBR material BindGroupLayout now holds 14 entries
1200
+ * (material 0..6 + Skylight 7..13) and the per-frame material
1201
+ * BindGroup assembly site (render-system-record) merges Skylight
1202
+ * resources at binding 7..13 -- active when a Skylight component
1203
+ * exists, fallback identity when `skylightCount === 0`.
1204
+ *
1205
+ * bug-20260519 D-3 nullable extension: the empty-manifest path
1206
+ * (Camera-only / clear-pass-only) skips the entire PBR pipeline build
1207
+ * block; we still allocate the fallback bundle in the normal path,
1208
+ * but tests / OOS paths that mock the manifest empty land here with
1209
+ * `null` (charter P3 explicit failure: M4 record-stage gates on
1210
+ * `skylightFallback !== null` before binding fallback resources at
1211
+ * material BG entries 7..13).
1212
+ */
1213
+ // biome-ignore lint/suspicious/noExplicitAny: opaque SkylightFallback shape
1214
+ readonly skylightFallback: any | null;
1215
+
1216
+ /**
1217
+ * feat-20260529-rendergraph-pass-abstraction M3 / w11 (D-2 + Finding 3):
1218
+ * per-pass mutable texture cache slots extracted from the global
1219
+ * PipelineState. These fields are the lazily-allocated texture attachments
1220
+ * + pass-specific pipelines and bindgroups that belong to a single render
1221
+ * pass (depth / shadow / tonemap / FXAA). M4 render-graph resource
1222
+ * declarations will read these descriptors to derive transient/persistent
1223
+ * resources; shadow probe (OOS-4) stays on PipelineState directly.
1224
+ */
1225
+ readonly perPassResources: PerPassResources;
1226
+ }
1227
+
1228
+ /**
1229
+ * Configure a canvas surface from the two PipelineState format fields, applying
1230
+ * the WebGL2-fallback gate: native WebGPU uses the storage format plus an sRGB
1231
+ * view format, while the wgpu WebGL2 surface uses its direct sRGB format and
1232
+ * COLOR_TARGET-only usage because its GLES surface rejects COPY_SRC. The
1233
+ * storage-buffer capability still controls TEXTURE_BINDING usage, but it does
1234
+ * not determine whether native WebGPU supports viewFormats. Single SSOT for
1235
+ * the configure descriptor consumed by both the
1236
+ * lazy first-frame path (ensureContextConfigured in createRenderer.ts) and the
1237
+ * F2 surface-outdated reconfigure-and-retry branch (render-system-record.ts) so
1238
+ * the two cannot drift (architecture-principles #1 SSOT). Returns the configure
1239
+ * Result; callers own the `state.perPassResources.configured` flag + the
1240
+ * `__forgeaxSwapChainFormat` probe write (those differ per call site).
1241
+ */
1242
+ export function configureSurface(
1243
+ context: RhiCanvasContext,
1244
+ device: RhiDevice,
1245
+ format: string,
1246
+ colorAttachmentFormat: string,
1247
+ ): Result<void, RhiError> {
1248
+ const backendKind = device.caps?.backendKind ?? 'webgpu';
1249
+ const isWebGl2 = backendKind === 'wgpu-webgl2';
1250
+ const surfaceFormats = resolveSurfaceFormatPair(
1251
+ backendKind,
1252
+ format as GPUTextureFormat,
1253
+ colorAttachmentFormat as GPUTextureFormat,
1254
+ );
1255
+ const supportsTextureBinding = device.caps?.storageBuffer ?? true;
1256
+ return context.configure({
1257
+ device,
1258
+ format: surfaceFormats.storage,
1259
+ alphaMode: isWebGl2 ? 'opaque' : 'premultiplied',
1260
+ usage:
1261
+ GPU_TEXTURE_USAGE_RENDER_ATTACHMENT |
1262
+ (supportsTextureBinding ? GPU_TEXTURE_USAGE_TEXTURE_BINDING : 0) |
1263
+ (isWebGl2 ? 0 : GPU_TEXTURE_USAGE_COPY_SRC),
1264
+ ...(!isWebGl2 ? { viewFormats: [surfaceFormats.view] } : {}),
1265
+ });
1266
+ }
1267
+
1268
+ /**
1269
+ * feat-20260529-rendergraph-pass-abstraction M3 / w11 (D-2):
1270
+ * per-pass mutable resource slots extracted from PipelineState per
1271
+ * research Finding 3 fact-based grouping (depth / shadow / tonemap / fxaa).
1272
+ * These fields are the lazily-allocated texture caches + pass-specific
1273
+ * pipeline/bindgroup handles that belong to a single render pass.
1274
+ * Mutable (non-readonly) because the record stage writes back after
1275
+ * lazy-alloc on size drift.
1276
+ */
1277
+ export interface PerPassResources {
1278
+ /**
1279
+ * Per-frame depth attachment. Lazily allocated by
1280
+ * `ensureContextConfigured` and recreated whenever the canvas resizes
1281
+ * (see `ensureDepthTexture` in createRenderer.ts). Bound at the
1282
+ * `beginRenderPass.depthStencilAttachment` slot with `depthLoadOp:'clear'`
1283
+ * + `clearValue:1` so each frame starts with a far-plane depth buffer
1284
+ * and the back-face / inside-of-cube fragments are correctly occluded
1285
+ * (bug-20260519).
1286
+ *
1287
+ * `depthTextureView` is `null` until the canvas dimensions are known
1288
+ * (first draw); the record stage skips the frame and fires
1289
+ * `webgpu-runtime-error` if it stays null past configure.
1290
+ */
1291
+ // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle (matches sibling fields)
1292
+ depthTexture: any | null;
1293
+ // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle
1294
+ depthTextureView: any | null;
1295
+ depthTextureWidth: number;
1296
+ depthTextureHeight: number;
1297
+ configured: boolean;
1298
+
1299
+ // ── feat-20260519-tonemap-reinhard-mvp / M2 / T-M2.5 ──────────────────────
1300
+ // feat-20260621 M-A3 (D-5): the dedicated tonemap pipeline / BGL / sampler /
1301
+ // params-UBO fields are deleted — the built-in tonemap now flows through the
1302
+ // unified fullscreen post-process channel (`postProcess.register(
1303
+ // 'forgeax::tonemap', { source, params })` + the per-frame PostProcessParams
1304
+ // channel). dispatchFullscreenPass owns the pipeline (getPostProcessPipeline
1305
+ // cache), the BGL + sampler (buildFullscreenPostProcessPass), and the params
1306
+ // UBO (eager-created at register). Only the HDR colour/depth attachments below
1307
+ // remain here — they belong to the geometry pass, not the tonemap pass.
1308
+
1309
+ /**
1310
+ * Lazy HDR colour + depth attachments for the opt-in tonemap path. Both
1311
+ * are `null` until the first frame whose active camera carries
1312
+ * `tonemap !== 'none'`; the record stage allocates them at the swap-chain
1313
+ * size and re-creates on resize (mirrors `depthTexture` / `depthTextureView`
1314
+ * idiom; AC-12).
1315
+ *
1316
+ * `hdrColor`'s format is `rgba16float` (AC-03(d)); the depth attachment is
1317
+ * the same `depth24plus-stencil8` format the geometry pipelines already declare
1318
+ * (`DEPTH_TEXTURE_FORMAT` SSOT in `createRenderer.ts`). When a camera
1319
+ * downgrades to `tonemap === 'none'` between frames the textures stay
1320
+ * allocated for cheap re-opt-in; full dispose happens via
1321
+ * `Renderer.dispose()` -> browser GC (matches the `depthTexture` fix-f6
1322
+ * placeholder).
1323
+ */
1324
+ // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle (matches sibling fields)
1325
+ hdrColorTexture: any | null;
1326
+ // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle
1327
+ hdrColorView: any | null;
1328
+ // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle
1329
+ hdrDepthTexture: any | null;
1330
+ // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle
1331
+ hdrDepthView: any | null;
1332
+ hdrTextureWidth: number;
1333
+ hdrTextureHeight: number;
1334
+ /**
1335
+ * feat-20260604 M2 / w10: sampleCount the `hdrDepth` attachment was last
1336
+ * allocated at (1 or 4). The HDR colour target is always sampled
1337
+ * single-sample (`hdrColorView`); the depth pairs with the geometry colour
1338
+ * target's sampleCount, which flips with `antialias === 'msaa'`. Tracking it
1339
+ * lets the record stage reallocate depth when MSAA toggles between frames
1340
+ * (a stale count=4 depth under a count=1 pipeline fails WebGPU validation).
1341
+ */
1342
+ hdrDepthSampleCount: number;
1343
+
1344
+ // -- feat-20260528-fxaa-post-processing M2 / w7 ----------------------------------
1345
+ //
1346
+ // FXAA fullscreen post-process pipeline resources. Mirrors the tonemap
1347
+ // pipeline shape: compiled at buildReadyWebGPU step 2 alongside the tonemap
1348
+ // pipeline and stored on PipelineState for per-frame consumption in the
1349
+ // record stage.
1350
+ //
1351
+ // D-2: 2-entry BGL (texture + sampler), no UBO. D-3: intermediate texture
1352
+ // format = bgra8unorm (swap-chain storage format). D-7: antialias=0
1353
+ // zero-overhead -- all FXAA fields stay null/0 until the first frame with
1354
+ // antialias='fxaa'.
1355
+ readonly fxaaPipeline: RenderPipeline | null;
1356
+ readonly fxaaBindGroupLayout: BindGroupLayout | null;
1357
+ readonly fxaaSampler: Sampler | null;
1358
+
1359
+ /** Fixed two-attachment linear TAA resolve resources, owned by this renderer. */
1360
+ readonly taaResolvePipeline: RenderPipeline | null;
1361
+ readonly taaResolveBindGroupLayout: BindGroupLayout | null;
1362
+ readonly taaResolveSampler: Sampler | null;
1363
+ taaResolveParamsBuffer: Buffer | null;
1364
+
1365
+ // ── feat-20260604-learn-render-4.10-anti-aliasing-msaa M2 / w7 ──────────
1366
+ //
1367
+ // MSAA (4x multisample) attachment slots. All `null`/0 until the first
1368
+ // frame whose active camera carries `antialias === 'msaa'`; the record
1369
+ // stage allocates them at the swap-chain size and re-creates on resize
1370
+ // (mirrors the hdrColor size-drift idiom; D-1). When
1371
+ // antialias is none/fxaa these stay null with zero allocation (C-9: MSAA
1372
+ // is a per-Camera switch derived from `camera.antialias === 'msaa'`, D-6).
1373
+ //
1374
+ // LDR swap-chain path (tonemapActive=false):
1375
+ // ONE count=4 multisample texture backs both the geometry and sprite
1376
+ // sub-passes. Two views of that same texture are taken: an srgb view
1377
+ // (msaaColorView, geometry pass) and an unorm view (msaaSpriteColorView,
1378
+ // sprite-split sub-pass; F-1). The single texture's storage format is
1379
+ // bgra8unorm, so the srgb and unorm views are both valid view formats of
1380
+ // it (same trick as the non-MSAA split path). The srgb view resolves to
1381
+ // the swap-chain srgb view; the unorm view resolves to the swap-chain
1382
+ // unorm view. No second multisample texture is allocated.
1383
+ // msaaDepth (depth24plus-stencil8, count=4) -> paired, never resolved (D-3).
1384
+ //
1385
+ // HDR path (tonemapActive=true): hdrColor/hdrDepth are themselves
1386
+ // allocated count=4 (record stage); hdrColorResolve is the single-sample
1387
+ // resolve output the tonemap/bloom passes sample (AC-03).
1388
+ // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle (matches sibling fields)
1389
+ msaaColorTexture: any | null;
1390
+ // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle
1391
+ msaaColorView: any | null;
1392
+ // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle
1393
+ msaaSpriteColorTexture: any | null;
1394
+ // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle
1395
+ msaaSpriteColorView: any | null;
1396
+ // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle
1397
+ msaaDepthTexture: any | null;
1398
+ // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle
1399
+ msaaDepthView: any | null;
1400
+ msaaTextureWidth: number;
1401
+ msaaTextureHeight: number;
1402
+ // HDR path MSAA: the count=4 multisample rgba16float geometry target. The
1403
+ // geometry + skybox passes write it; it resolves to the single-sample
1404
+ // `hdrColorView` (which the tonemap / bloom passes keep sampling unchanged).
1405
+ // Allocated alongside hdrColor when antialias='msaa' && tonemap!='none'.
1406
+ // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle (HDR multisample target)
1407
+ hdrColorMsaaTexture: any | null;
1408
+ // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle
1409
+ hdrColorMsaaView: any | null;
1410
+
1411
+ // ── feat-20260531-skybox-env-background M3 / w15 ─────────────────────────
1412
+ //
1413
+ // Skybox fullscreen cubemap pipeline resources. Mirrors tonemap/fxaa
1414
+ // construction: 4-entry BGL (texture_cube + sampler + View UBO + rotation UBO), fullscreen
1415
+ // triangle vertex stage, cubemap-sample fragment stage. Skybox writes HDR to
1416
+ // hdrColor rgba16float (targeted by the hdrColor render target); the tonemap
1417
+ // pass later reads hdrColor and maps to the LDR swap-chain. Fields are null
1418
+ // when the manifest has no skybox entry (D-7 optional, legacy manifests
1419
+ // continue to boot).
1420
+ readonly skyboxPipeline: RenderPipeline | null;
1421
+ // feat-20260604 M2 / w8: count=4 multisample variant of the skybox pipeline.
1422
+ // Used when the active camera carries antialias='msaa' (the skybox writes the
1423
+ // count=4 hdrColorMsaa target alongside the main geometry pass). null when
1424
+ // the base skybox pipeline is null (legacy manifest) or its MSAA build failed.
1425
+ readonly skyboxPipelineMsaa: RenderPipeline | null;
1426
+ readonly skyboxBindGroupLayout: BindGroupLayout | null;
1427
+ readonly skyboxSampler: Sampler | null;
1428
+ /** Stable 16 B quaternion UBO updated by the skybox record pass. */
1429
+ readonly skyboxRotationBuffer: Buffer | null;
1430
+
1431
+ /** Executable analytic-atmosphere producer and background resources. */
1432
+ readonly atmosphereCubemapPipeline?: RenderPipeline | null;
1433
+ readonly atmosphereCubemapBindGroupLayout?: BindGroupLayout | null;
1434
+ readonly atmosphereIrradiancePipeline?: RenderPipeline | null;
1435
+ readonly atmospherePrefilterPipeline?: RenderPipeline | null;
1436
+ readonly atmosphereIblParamsBindGroupLayout?: BindGroupLayout | null;
1437
+ readonly atmosphereIblSkyBindGroupLayout?: BindGroupLayout | null;
1438
+ readonly atmosphereBackgroundPipeline?: RenderPipeline | null;
1439
+ readonly atmosphereBackgroundBindGroupLayout?: BindGroupLayout | null;
1440
+ readonly atmosphereParamsBuffer?: Buffer | null;
1441
+ readonly atmosphereCubeVertexBuffer?: Buffer | null;
1442
+
1443
+ // ── feat-20260520-directional-light-shadow-mapping M1c / w8 ────────────
1444
+ //
1445
+ // Shadow RT (depth32float) lazy-allocated per mapSize; recreated on mapSize
1446
+ // drift. Used by the shadow depth pass (colorAttachments: []) and sampled
1447
+ // by the main pass as @group(0) binding(3) in M2/M3. debugReadback copies
1448
+ // the depth texture to a staging buffer for Inspector readback (D-2/D-5).
1449
+ //
1450
+ // feat-20260609 M4 / T-009: shadowCasterPipeline / shadowCasterPipelineLayout
1451
+ // removed — shadow PSO now obtained via frameState.pipelineCache lookup
1452
+ // (runtime.getMaterialShaderPipeline, passKind: 'shadow-caster'), same
1453
+ // path as forward passes (charter P4 consistent abstraction).
1454
+ // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle
1455
+ shadowTexture: any | null;
1456
+ shadowMapSize: number;
1457
+ shadowCascadeCount: number;
1458
+ /** Exact dimensions of the compiled directional cascade atlas. */
1459
+ shadowAtlasWidth: number;
1460
+ shadowAtlasHeight: number;
1461
+ // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle
1462
+ shadowSampler: any | null;
1463
+ /**
1464
+ * feat-20260520-directional-light-shadow-mapping M1c / w11 +
1465
+ * feat-20260613-csm-cascaded-shadow-maps M5 / w28:
1466
+ * latest cascade-0 lightViewProj mat4 (16 f32, col-major). Kept under
1467
+ * the legacy field name as an Inspector backward-compat surface
1468
+ * (`runtime.lights.directionalShadow.lightSpaceMatrix` JSON-RPC), per
1469
+ * AGENTS.md §Change stance exception for external-visible wire
1470
+ * protocols with known downstream consumers. Populated each frame
1471
+ * from `lights.lightViewProj[0]`. Null before the first extract with
1472
+ * an active shadow-casting DirectionalLight.
1473
+ */
1474
+ shadowLightSpaceMatrix: Float32Array | null;
1475
+ /**
1476
+ * feat-20260613-csm-cascaded-shadow-maps M5 / w28: full 4-cascade
1477
+ * lightViewProj concatenation (4 × 16 = 64 f32, col-major) consumed by
1478
+ * `debugSampleShadowFactor` so the probe can project against the selected
1479
+ * cascade. Null before the first extract
1480
+ * with an active shadow-casting DirectionalLight.
1481
+ */
1482
+ shadowCsmLightViewProj: Float32Array | null;
1483
+ /**
1484
+ * Producer-owned CSM receiver-selection facts. The debug probe must use the
1485
+ * same view-space depth + split-plane selector as the main receiver path;
1486
+ * keeping the two inputs together prevents a selector mirror from silently
1487
+ * drifting at cascade boundaries.
1488
+ */
1489
+ shadowCsmSelection: {
1490
+ readonly viewMatrix: Float32Array;
1491
+ readonly splitPlanes: Float32Array;
1492
+ readonly cascadeBlend: number;
1493
+ } | null;
1494
+ /** Producer-owned directional shadow comparison parameters for GPU probes. */
1495
+ shadowLightDirection: Float32Array | null;
1496
+ shadowDepthBias: number;
1497
+ shadowNormalBias: number;
1498
+ shadowPcfKernelSize: number;
1499
+
1500
+ // ── feat-20260531-bloom-first-declarative-render-graph-pass w13/w16 ────
1501
+ //
1502
+ // Bloom post-processing chain: 4 passes (bright / blur-H / blur-V / composite)
1503
+ // operating in HDR rgba16float domain. Pipeline handles assembled at
1504
+ // buildReadyWebGPU (optional — legacy manifests without bloom.wgsl leave
1505
+ // these null). Intermediate textures are graph-owned transient targets
1506
+ // resolved per-frame; the bloom bind groups are identity-cached on those
1507
+ // views (frameState.postProcessBgCache) and rebuild automatically when a
1508
+ // resize retires the old textures.
1509
+ //
1510
+ // D-1: blur H/V share the same module, per-axis texelSize baked at UBO write.
1511
+ // D-4: 3 distinct BGL layouts (bright/blur: 1-tex+UBO, composite: 2-tex+UBO).
1512
+ // D-6: all intermediate textures use rgba16float format.
1513
+ readonly bloomBrightPipeline: RenderPipeline | null;
1514
+ readonly bloomBlurHPipeline: RenderPipeline | null;
1515
+ readonly bloomBlurVPipeline: RenderPipeline | null;
1516
+ readonly bloomCompositePipeline: RenderPipeline | null;
1517
+ readonly bloomBrightBindGroupLayout: BindGroupLayout | null;
1518
+ readonly bloomBlurBindGroupLayout: BindGroupLayout | null;
1519
+ readonly bloomCompositeBindGroupLayout: BindGroupLayout | null;
1520
+ readonly bloomSampler: Sampler | null;
1521
+ readonly bloomBrightParamsBuffer: Buffer | null;
1522
+ // bug-20260625: H and V blur passes need SEPARATE params UBOs. They run in
1523
+ // the same frame encoder; with one shared buffer the later writeBuffer (V's
1524
+ // texelSize=(0,1/h)) clobbers H's (texelSize=(1/w,0)) before the GPU runs the
1525
+ // H pass, so both passes blurred vertically -> only vertical bloom, no
1526
+ // horizontal spread. One buffer per axis keeps each pass's params intact.
1527
+ readonly bloomBlurHParamsBuffer: Buffer | null;
1528
+ readonly bloomBlurVParamsBuffer: Buffer | null;
1529
+ readonly bloomCompositeParamsBuffer: Buffer | null;
1530
+
1531
+ // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle
1532
+ bloomBrightTexture: any | null;
1533
+ // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle
1534
+ bloomBrightView: any | null;
1535
+ bloomBrightWidth: number;
1536
+ bloomBrightHeight: number;
1537
+
1538
+ // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle
1539
+ bloomBlurHTexture: any | null;
1540
+ // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle
1541
+ bloomBlurHView: any | null;
1542
+ bloomBlurHWidth: number;
1543
+ bloomBlurHHeight: number;
1544
+
1545
+ // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle
1546
+ bloomBlurVTexture: any | null;
1547
+ // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle
1548
+ bloomBlurVView: any | null;
1549
+ bloomBlurVWidth: number;
1550
+ bloomBlurVHeight: number;
1551
+
1552
+ // ── feat-20260612-hdrp-ssao M6 / w26 + M8 / w37 + w38 ───────────────────
1553
+ //
1554
+ // SSAO post-processing chain: 2 passes (calc + blur) operating on
1555
+ // half-resolution R8 single-channel textures. RenderPipeline handles
1556
+ // assembled at buildReadyWebGPU (optional — manifests without
1557
+ // hdrp-ssao.wgsl leave these null). Dedicated BGL (9 entries matching
1558
+ // current WGSL @group(0) bindings 0-8) shared by both pipelines: calc
1559
+ // and blur both bind all 9 entries; the blur uses ssaoRaw (binding 7) +
1560
+ // ssaoSampler (binding 8) while the calc binds a 1x1 fallback view at
1561
+ // 7 (the calc shader never samples ssaoRaw).
1562
+ // plan-strategy D-A; D-D; D-E.
1563
+ //
1564
+ // Samplers (filtering + non-filtering depth) and the 1x1 ssaoRaw fallback
1565
+ // view used by the calc pass are lazy-allocated inside the record closure
1566
+ // on first frame and cached on the mutable slots below — keeps createRenderer
1567
+ // free of additional state and matches bloom's lazy bind-group pattern.
1568
+ readonly ssaoCalcPipeline: RenderPipeline | null;
1569
+ readonly ssaoBlurPipeline: RenderPipeline | null;
1570
+ readonly ssaoBgl: BindGroupLayout | null;
1571
+ /** Filtering sampler shared by ssao_noise_sampler (binding 3) + ssaoSampler (binding 8). */
1572
+ ssaoFilteringSampler: Sampler | null;
1573
+ /** Non-filtering sampler dedicated to hdr_depth (binding 6); WebGPU validation. */
1574
+ ssaoDepthSampler: Sampler | null;
1575
+ /** 1x1 fallback view bound at ssaoRaw (binding 7) in the calc pass. */
1576
+ // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle
1577
+ ssaoFallbackRawView: any | null;
1578
+ }
1579
+
1580
+ export interface MeshGpuHandles {
1581
+ /**
1582
+ * Vertex buffer wrapped as a GpuBuffer (M-3 / w11). Consumers reach the
1583
+ * raw RHI Buffer via `.handle` for `setVertexBuffer` etc.; `.destroy()`
1584
+ * routes through the RHI shim's lifecycle SSOT (charter §F1 single-entry
1585
+ * indexability + plan-strategy D-9 wrapper migration).
1586
+ */
1587
+ readonly vertexBuffer: GpuBuffer;
1588
+ /**
1589
+ * Index buffer wrapper, or `null` for a vertex-only mesh (no
1590
+ * `MeshAsset.indices`). When `null` the record stage takes the non-indexed
1591
+ * `pass.draw(vertexCount)` path and never calls `setIndexBuffer`. Gated
1592
+ * on `indexed` below.
1593
+ */
1594
+ readonly indexBuffer: GpuBuffer | null;
1595
+ /** Allocation byte size of the vertex buffer (mirrors GPUBuffer.size). */
1596
+ readonly vboBytes: number;
1597
+ /** Allocation byte size of the index buffer, or 0 when `indexBuffer` is null. */
1598
+ readonly iboBytes: number;
1599
+ readonly indexCount: number;
1600
+ /**
1601
+ * Index buffer format inferred from the source `MeshAsset.indices` typed
1602
+ * array (`Uint16Array` -> `'uint16'`, `Uint32Array` -> `'uint32'`). The
1603
+ * record stage threads this into `pass.setIndexBuffer(..., format)` so
1604
+ * the GPU reads the correct stride per index. bug-20260519: the prior
1605
+ * hard-coded `'uint16'` corrupted procedural meshes whose factories
1606
+ * (`createBoxGeometry` etc) emit Uint32Array indices.
1607
+ */
1608
+ readonly indexFormat: 'uint16' | 'uint32';
1609
+ /** Geometry-owned immutable projection carried through every GPU consumer. */
1610
+ readonly layoutProjection: VertexLayoutProjection;
1611
+ /**
1612
+ * Vertex count is derived from the projection stride at upload time. The
1613
+ * non-indexed draw path passes this to `pass.draw(vertexCount)`.
1614
+ */
1615
+ readonly vertexCount: number;
1616
+ /**
1617
+ * True when the mesh carries an index buffer (`MeshAsset.indices` present).
1618
+ * `false` for vertex-only meshes. The record stage branches on this to pick
1619
+ * `drawIndexed` vs `draw` and to gate `setIndexBuffer`.
1620
+ */
1621
+ readonly indexed: boolean;
1622
+ /**
1623
+ * Primitive topology of this mesh (first submesh's topology, default
1624
+ * 'triangle-list'). WebGPU bakes topology into the immutable PSO, so the
1625
+ * record stage threads this into `getMaterialShaderPipeline` to select a
1626
+ * per-topology PSO (feat-20260604 M3 / w9).
1627
+ *
1628
+ * feat-20260608 M4 / w16: topology is per-submesh; this field reflects
1629
+ * `submeshes[0].topology` for backward compat. Use `submeshes` field for
1630
+ * per-submesh draw iteration.
1631
+ */
1632
+ readonly topology: PrimitiveTopology;
1633
+ /**
1634
+ * Submeshes from MeshAsset.submeshes, carried through from the GPU store
1635
+ * so the record stage can iterate per-submesh drawIndexed (feat-20260608 M4 / w16).
1636
+ */
1637
+ readonly submeshes: readonly import('@forgeax/engine-types').Submesh[];
1638
+ }
1639
+
1640
+ const DIRECTIONAL_SHADOW_TILE_CLEAR_WGSL = /* wgsl */ `
1641
+ @vertex
1642
+ fn vs_main(@builtin(vertex_index) vertexIndex: u32) -> @builtin(position) vec4<f32> {
1643
+ var positions = array<vec2<f32>, 3>(
1644
+ vec2<f32>(-1.0, -1.0),
1645
+ vec2<f32>(3.0, -1.0),
1646
+ vec2<f32>(-1.0, 3.0),
1647
+ );
1648
+ return vec4<f32>(positions[vertexIndex], 1.0, 1.0);
1649
+ }
1650
+ `;
1651
+
1652
+ export function createRenderSystem(internals: RenderSystemInternals): RenderSystem {
1653
+ const phaseCatalogRegistration = internals.profiler?.registerPhaseCatalog(
1654
+ 'render',
1655
+ RENDER_PHASE_CATALOG,
1656
+ );
1657
+ let releaseProfilerCatalog =
1658
+ phaseCatalogRegistration?.ok === true ? phaseCatalogRegistration.value : undefined;
1659
+ // Material handles are scoped to a World. Keep resolved snapshots scoped to
1660
+ // this RenderSystem and this World so Edit/Play handles can never collide;
1661
+ // WeakMap also lets a dropped Play world release its cache with the world.
1662
+ const materialSnapshotCachesByWorld: MaterialSnapshotCachesByWorld = new WeakMap();
1663
+ const persistentRenderScene = new PersistentRenderScene({
1664
+ getDevice: () => internals.device,
1665
+ onGpuError: (error) => internals.errorRegistry.fire(error),
1666
+ collectShadowDebugCandidates: () => internals.shadowDebugObservation === true,
1667
+ });
1668
+ const taaHistoryStore = new TaaHistoryStore(internals.device);
1669
+ const temporalFrameTransaction = new TemporalFrameTransaction(taaHistoryStore);
1670
+ const gpuDrivenShaderFactory =
1671
+ internals.shaderModuleFactory ??
1672
+ ({
1673
+ createShaderModule: () =>
1674
+ err(
1675
+ new RhiError({
1676
+ code: 'rhi-not-available',
1677
+ expected: 'the renderer backend exposes shader module creation',
1678
+ hint: 'construct the renderer through the backend pack before activating GPU-driven rendering',
1679
+ }),
1680
+ ),
1681
+ } satisfies import('./pipeline-builder').PipelineBuilderShaderModuleFactory);
1682
+ let directionalShadowTileClear:
1683
+ | { readonly device: RhiDevice; readonly pipeline: RenderPipeline }
1684
+ | undefined;
1685
+ const getDirectionalShadowTileClearPipeline = (): RenderPipeline | null => {
1686
+ const device = internals.device;
1687
+ if (directionalShadowTileClear?.device === device) {
1688
+ return directionalShadowTileClear.pipeline;
1689
+ }
1690
+ const module = gpuDrivenShaderFactory.createShaderModule({
1691
+ label: 'directional-shadow-tile-clear',
1692
+ code: DIRECTIONAL_SHADOW_TILE_CLEAR_WGSL,
1693
+ });
1694
+ if (!module.ok) {
1695
+ if (module.error.code !== 'rhi-not-available') internals.errorRegistry.fire(module.error);
1696
+ return null;
1697
+ }
1698
+ const layout = device.createPipelineLayout({
1699
+ label: 'directional-shadow-tile-clear-layout',
1700
+ bindGroupLayouts: [],
1701
+ });
1702
+ if (!layout.ok) {
1703
+ internals.errorRegistry.fire(layout.error);
1704
+ return null;
1705
+ }
1706
+ const pipeline = device.createRenderPipeline({
1707
+ label: 'directional-shadow-tile-clear',
1708
+ layout: layout.value as unknown as GPUPipelineLayout,
1709
+ vertex: {
1710
+ module: module.value as unknown as GPUShaderModule,
1711
+ entryPoint: 'vs_main',
1712
+ buffers: [],
1713
+ },
1714
+ fragment: undefined,
1715
+ primitive: { topology: 'triangle-list', cullMode: 'none' },
1716
+ depthStencil: {
1717
+ format: 'depth32float',
1718
+ depthWriteEnabled: true,
1719
+ depthCompare: 'always',
1720
+ },
1721
+ });
1722
+ if (!pipeline.ok) {
1723
+ internals.errorRegistry.fire(pipeline.error);
1724
+ return null;
1725
+ }
1726
+ directionalShadowTileClear = { device, pipeline: pipeline.value };
1727
+ return pipeline.value;
1728
+ };
1729
+ (
1730
+ internals as unknown as {
1731
+ getDirectionalShadowTileClearPipeline: typeof getDirectionalShadowTileClearPipeline;
1732
+ }
1733
+ ).getDirectionalShadowTileClearPipeline = getDirectionalShadowTileClearPipeline;
1734
+ let gpuDrivenProduction = new GpuDrivenProduction(internals.device, gpuDrivenShaderFactory);
1735
+ const featureGpuWork = new Map<string, RenderFeatureGpuWorkResolver>();
1736
+ const getFeatureGpuWork = (featureIdentity: string): RenderFeatureGpuWorkResolver => {
1737
+ const existing = featureGpuWork.get(featureIdentity);
1738
+ if (existing !== undefined) return existing;
1739
+ const created = createRenderFeatureGpuWorkResolver({
1740
+ device: internals.device,
1741
+ shaderModuleFactory:
1742
+ internals.shaderModuleFactory ??
1743
+ ({
1744
+ createShaderModule: () =>
1745
+ err(
1746
+ new RhiError({
1747
+ code: 'rhi-not-available',
1748
+ expected: 'the renderer backend exposes shader module creation',
1749
+ hint: 'construct the renderer through the backend pack before installing GPU features',
1750
+ }),
1751
+ ),
1752
+ } satisfies import('./pipeline-builder').PipelineBuilderShaderModuleFactory),
1753
+ generation: internals.featureHost?.preparedGeneration ?? 0,
1754
+ featureIdentity,
1755
+ });
1756
+ featureGpuWork.set(featureIdentity, created);
1757
+ return created;
1758
+ };
1759
+ const disposeFeatureGpuWork = (): void => {
1760
+ for (const resolver of featureGpuWork.values()) {
1761
+ const disposed = resolver.dispose();
1762
+ if (!disposed.ok) internals.errorRegistry.fire(disposed.error);
1763
+ }
1764
+ featureGpuWork.clear();
1765
+ };
1766
+ // Per-RenderSystem frame state: closure-internal frameNumber + the
1767
+ // per-entity instance GPU buffer cache (feat-20260514 M3 / w15: the
1768
+ // record stage owns GPU storage buffer allocation for Instances entities;
1769
+ // the `instanceBuffers` map is keyed by the packed Entity u32 surfaced
1770
+ // through `InstancesSnapshot.cacheKey` and rebuilds buffers on archetype
1771
+ // version bump or byte-length change). The legacy
1772
+ // `lastFiredLimitExceededFrame` engine-side dedup field was removed in
1773
+ // feat-20260513-instanced-mesh M5 (T-M5-1 + T-M5-3); the active
1774
+ // `'limit-exceeded'` emit point is now the record stage upload path.
1775
+ //
1776
+ // feat-20260708 M1 / D-1a #1: positive-half keys are worldEntityKey(worldId,
1777
+ // cacheKey) composites. Negative-half fold-bucket keys (sprite fold) stay
1778
+ // raw (material-handle-based, cross-world collision semantically correct).
1779
+ const frameState: RenderFrameState = {
1780
+ frameNumber: 0,
1781
+ environmentGeneration: createEnvironmentGenerationState(0),
1782
+ shadowSubmitModeState: createShadowSubmitModeState(),
1783
+ pendingShadowCommandBuffers: [],
1784
+ directionalShadowCache: null,
1785
+ directionalShadowCacheRecorded: false,
1786
+ compiledFrameGraph: null,
1787
+ compiledFrameGraphTopologyKey: null,
1788
+ retiredCompiledFrameGraphs: new Set(),
1789
+ currentFrameObservationSource: undefined,
1790
+ currentDirectionalShadowView: null,
1791
+ currentSpotShadowView: null,
1792
+ instanceBuffers: new Map(),
1793
+ hdrpClusterBinScratch: createClusterBinScratch(),
1794
+ hdrpClusterGridScratch: null,
1795
+ hdrpLightIndexListScratch: null,
1796
+ hdrpClusterMembershipBindGroup: null,
1797
+ transientInstanceBuffers: [],
1798
+ warnedZeroLightStandard: false,
1799
+ warnedMultiLightDirectional: false,
1800
+ warnedMultiLightPoint: false,
1801
+ warnedMultiLightSpot: false,
1802
+ // feat-20260630-equirect-kind-internalized-ibl-declarative-skyligh M3 / w19:
1803
+ // once-warn latches for >1 Skylight / >1 SkyboxBackground (names winner).
1804
+ warnedMultiSkylight: false,
1805
+ warnedMultiSkybox: false,
1806
+ warnedSkyboxTonemapNone: false,
1807
+ // feat-20260520-2d-sprite-layer-mvp M-3 / w25 (AC-18 path 4): per-
1808
+ // handle warn-once anchor for the sprite-bucket missing-texture
1809
+ // fallback. Set<number> keyed by raw Handle<TextureAsset>; never
1810
+ // cleared (charter F1 minimal surface — the per-RenderSystem lifetime
1811
+ // is the natural upper bound).
1812
+ warnedMissingBaseColorTextureHandles: new Set<number>(),
1813
+ reportedMaterialDiagnosticKeys: new Set<string>(),
1814
+ // feat-20260527-sprite-nineslice M2 / w11 + M4 / w16 (AC-16): once-per-
1815
+ // renderable guard for the runtime `nineslice.scale-too-small` metric
1816
+ // counter (`runtime.metrics.increment(...)` in render-system-record.ts).
1817
+ warnedNineSliceScaleEntities: new Set<number>(),
1818
+ // feat-20260630-equirect-kind-internalized-ibl-declarative-skyligh M3 / w18:
1819
+ // per-handle fire-once anchor for the lazy equirect projection failure
1820
+ // (EquirectProjectionFailedError). Set<number> keyed by raw
1821
+ // Handle<EquirectAsset>; never cleared (per-RenderSystem lifetime upper bound).
1822
+ firedEquirectProjectionFailedHandles: new Set<number>(),
1823
+ // feat-20260622-handle-to-id-allocator-elimination M1 / w3: per-frame
1824
+ // bind group caches as nested WeakMap chain roots. viewBindGroupCache
1825
+ // covers main and shadow variants; meshBindGroupCache keys on inner
1826
+ // buffer handles (D-3). Roots are stable between device recoveries.
1827
+ viewBindGroupCache: new WeakMap(),
1828
+ meshBindGroupCache: new WeakMap(),
1829
+ // feat-20260622-handle-to-id-allocator-elimination M1 / w2: per-entity
1830
+ // material and instances caches (outer Map<entityKey, WeakMap>).
1831
+ materialBgPerEntity: new Map(),
1832
+ instancesBgPerEntity: new Map(),
1833
+ instancesBgShared: new WeakMap(),
1834
+ // cross-entity shared material cache (outer Map<shaderId, WeakMap>).
1835
+ materialBgShared: new Map(),
1836
+ // cross-frame material assembly cache; entries are only retained when all
1837
+ // explicit texture/sampler handles resolved to resident GPU resources.
1838
+ materialBgAssemblyCache: new Map(),
1839
+ // singleton material cache (flat Map<variant, BindGroup>; D-6).
1840
+ singletonMaterialCache: new Map(),
1841
+ // post-process bind group cache (bloom / fxaa / ssao): identity-keyed
1842
+ // WeakMap chain so resize-retired transient targets rebuild automatically.
1843
+ postProcessBgCache: new WeakMap(),
1844
+ // feat-20260601-customizable-render-pipeline-seam M1 / w7: installed-pipeline state.
1845
+ // 0 = nothing installed yet (createRenderer dogfood installs the default before any
1846
+ // draw). activePipeline defaults to the built-in forward pipeline.
1847
+ installedPipelineHandle: 0,
1848
+ activePipelineId: URP_PIPELINE_ID,
1849
+ activePipeline: urpPipeline,
1850
+ // feat-20260601 verify round 2: the standard forward pipeline installs with no config
1851
+ // (its topology is frame-invariant). installPipeline overwrites this with the resolved
1852
+ // asset's `config` on every swap so a custom pipeline reads its install-time config.
1853
+ installedPipelineConfig: undefined,
1854
+ // feat-20260608-cluster-lighting M2 / w10 + M5 / w20: HDRP active flag + once-per-frame
1855
+ // warn dedup set for hdrp-light-budget-exceeded / hdrp-index-list-overflow.
1856
+ isHdrpActive: false,
1857
+ hdrpOncePerFrameFired: new Set(),
1858
+ // feat-20260612-point-light-shadows-urp-hdrp M3 / T-M3-2 (plan-strategy §D-1):
1859
+ // cube_array shadow atlas + per-frame snapshot list. Atlas is null until the
1860
+ // first frame whose extracted lights.pointShadow is non-empty (zero-shadow
1861
+ // scenes never allocate; AC-09); the snapshot list defaults to an empty
1862
+ // tuple so the URP `addPointShadowPass` gate sees zero shadow lights as the
1863
+ // initial steady state.
1864
+ pointShadowAtlas: null,
1865
+ pointShadowSnapshots: [],
1866
+ // feat-20260622-chunk-gpu-instancing-sprite-tilemap M1 / w4 (D-1):
1867
+ // initial fold-bucket count is 0; recordFrame writes the per-frame
1868
+ // value from foldDispatchBuckets(...) before dispatch.
1869
+ lastFoldBucketCount: 0,
1870
+ // feat-20260625-spot-light-shadow-mapping M2 / w9 (D-2): empty initial spot
1871
+ // shadow snapshot list so the spotShadowDepth caster pass renders zero
1872
+ // tiles until the first frame with a castShadow spot (AC-03).
1873
+ spotShadowSnapshots: [],
1874
+ };
1875
+ let directFrameId = 0;
1876
+
1877
+ function beginProfilePhase(session: RecorderSession | undefined, phase: RenderPhase): boolean {
1878
+ if (session === undefined) return false;
1879
+ try {
1880
+ return session.beginPhase('render', phase).ok;
1881
+ } catch {
1882
+ return false;
1883
+ }
1884
+ }
1885
+
1886
+ function endProfilePhase(session: RecorderSession | undefined): void {
1887
+ if (session === undefined) return;
1888
+ try {
1889
+ session.endPhase();
1890
+ } catch {
1891
+ // Profiler failures never alter rendering.
1892
+ }
1893
+ }
1894
+
1895
+ function recordProfileSkip(
1896
+ session: RecorderSession | undefined,
1897
+ phase: RenderPhase,
1898
+ reason: RenderPhaseSkipReason,
1899
+ ): void {
1900
+ if (session === undefined) return;
1901
+ try {
1902
+ session.recordSkip({ source: 'render', phase, reason });
1903
+ } catch {
1904
+ // Profiler failures never alter rendering.
1905
+ }
1906
+ }
1907
+
1908
+ function runProfiledRenderPhase<T>(
1909
+ session: RecorderSession | undefined,
1910
+ phase: RenderPhase,
1911
+ action: () => T,
1912
+ ): T {
1913
+ const opened = beginProfilePhase(session, phase);
1914
+ try {
1915
+ return action();
1916
+ } finally {
1917
+ if (opened) endProfilePhase(session);
1918
+ }
1919
+ }
1920
+ // Pipeline registry and current installation live in the RenderSystem closure
1921
+ // (plan-strategy D-D: all real logic on the RenderSystem layer; the Renderer facade
1922
+ // only forwards). The registry dedups same-id register (Map.has -> throw), mirroring
1923
+ // ShaderRegistry.installMaterialArtifact.
1924
+ const pipelineRegistry = new Map<string, RenderPipelineDef>();
1925
+ const pipelineInstalls: Array<{
1926
+ readonly token: object;
1927
+ readonly id: string;
1928
+ readonly pipeline: RenderPipelineDef;
1929
+ readonly config: RenderPipelineAsset['config'];
1930
+ readonly isHdrp: boolean;
1931
+ }> = [];
1932
+ let lastBuiltPipelineHandle = 0;
1933
+ // Monotonic install epoch: bumped on every installPipeline call to brand the
1934
+ // installed pipeline so `draw` can detect a swap and rebuild the per-frame
1935
+ // graph. Replaces the prior raw-handle brand (D-19: installPipeline takes a
1936
+ // POD, no handle).
1937
+ let installEpoch = 0;
1938
+ // feat-20260604-resource-owning-render-graph-and-fullscreen-postpr M2 / w13:
1939
+ // post-process shader registry (id -> PostProcessShaderEntry), parallel to pipelineRegistry.
1940
+ // Dedups same-id register (Map.has -> throw), mirroring ShaderRegistry.installMaterialArtifact.
1941
+ const postProcessRegistry = new Map<string, PostProcessShaderEntry>();
1942
+ // CPU post-process declarations are the logical registry and remain live
1943
+ // across recovery. Only device-bound buffers and pipelines are rebuilt.
1944
+ // D-3 / D-8: per-shader params UBO resource table (id -> GPU Buffer).
1945
+ // Eager-created at register time when entry.params is present (byteSize >= 16,
1946
+ // defaultValue.length === byteSize); reused frame-to-frame via queue.writeBuffer.
1947
+ const postProcessParamsBuffers = new Map<string, Buffer>();
1948
+ // F-2 fix-up: expose registry lookup through the narrow runtime surface so
1949
+ // addFullscreenPass's execute closure (in render-graph-primitives.ts) can
1950
+ // resolve a registered shader id without reaching into RenderSystemInternals.
1951
+ // Inject as a post-construction property on `internals` (typed as readonly
1952
+ // optional on RenderSystemRuntime, so a one-time cast is the only path);
1953
+ // every consumer that types `RenderPipelineContext.runtime` will see it.
1954
+ const lookupPostProcess = (id: string): PostProcessShaderEntry | undefined =>
1955
+ postProcessRegistry.get(id);
1956
+ (internals as unknown as { lookupPostProcess: typeof lookupPostProcess }).lookupPostProcess =
1957
+ lookupPostProcess;
1958
+ // feat-20260621 M-A2 / w8: expose the eager-created per-id params UBO through
1959
+ // the narrow runtime surface so dispatchFullscreenPass can writeBuffer the
1960
+ // per-frame snapshot + bind it at group(1) binding(2).
1961
+ const getPostProcessParamsBuffer = (id: string): Buffer | undefined =>
1962
+ postProcessParamsBuffers.get(id);
1963
+ (
1964
+ internals as unknown as { getPostProcessParamsBuffer: typeof getPostProcessParamsBuffer }
1965
+ ).getPostProcessParamsBuffer = getPostProcessParamsBuffer;
1966
+ // feat-20260609 M4 / T-10-a: post-process pipeline cache (id|colorFormat -> RhiRenderPipeline).
1967
+ // Solves CONCERN-1: dispatcher previously passed `pipeline=null` to
1968
+ // built.createHandle because per-frame execute closures cannot await async
1969
+ // shader compile. The cache here delegates the actual build to
1970
+ // `internals.buildPostProcessPipeline` (sync wrapper over the shared shader
1971
+ // adapter; 1-frame warmup), then memoizes by `id|colorFormat`.
1972
+ const postProcessPipelineCache = new Map<string, RenderPipeline>();
1973
+ const getPostProcessPipeline = (
1974
+ id: string,
1975
+ bgl: BindGroupLayout,
1976
+ colorFormat: GPUTextureFormat,
1977
+ ): RenderPipeline | null => {
1978
+ const key = `${id}|${colorFormat}`;
1979
+ const cached = postProcessPipelineCache.get(key);
1980
+ if (cached !== undefined) return cached;
1981
+ const entry = postProcessRegistry.get(id);
1982
+ if (entry === undefined) return null;
1983
+ const factory = internals.buildPostProcessPipeline;
1984
+ if (factory === undefined) return null;
1985
+ const built = factory(entry, bgl, colorFormat, `post-process-${id}`);
1986
+ if (built === null) return null;
1987
+ postProcessPipelineCache.set(key, built);
1988
+ return built;
1989
+ };
1990
+ (
1991
+ internals as unknown as { getPostProcessPipeline: typeof getPostProcessPipeline }
1992
+ ).getPostProcessPipeline = getPostProcessPipeline;
1993
+ // w15 M5 (plan-strategy D-P4 / AC-07): per-frame dispatch counters. Reset
1994
+ // on every `draw([world], { cameraOwner: 0, resourceOwner: 0 })` entry; bumped once per actual `pass.setPipeline`
1995
+ // dispatch in render-system-record.ts. Two-way split mirrors the two
1996
+ // render pipelines on PipelineState (bug-20260519: BUILTIN cube migrated
1997
+ // to 12F so `unlitBuiltin` retired): `unlit` covers every
1998
+ // unlit material, `standard` covers every PBR material.
1999
+ const dispatchCounts: { unlit: number } = {
2000
+ unlit: 0,
2001
+ };
2002
+ // feat-20260531-per-frame-bind-group-cache M1 / w4: per-frame
2003
+ // createBindGroup counter scaffolding. Reset on every draw([world], { cameraOwner: 0, resourceOwner: 0 }) entry,
2004
+ // bumped on cache-miss in render-system-record.ts (M2-M4 bump points).
2005
+ // Aligns with dispatchCounts precedent: closure-mutable object.
2006
+ const bindGroupCounts: { createBindGroup: number; keys: string[] } = {
2007
+ createBindGroup: 0,
2008
+ keys: [],
2009
+ };
2010
+ let preparedWorlds: readonly World[] = [];
2011
+ const preparedPipelineIds = new WeakMap<object, string>();
2012
+ const preparedMaterialPipelineShaders = new WeakMap<object, string>();
2013
+ const preparedGroup0Pipelines = new WeakSet<object>();
2014
+ const preparedViewOnlyPipelines = new WeakSet<object>();
2015
+ const preparedViewWithResourcePipelines = new WeakSet<object>();
2016
+ const preparedRenderMaterialPipelines = new WeakSet<object>();
2017
+ const preparedAssetHandles = new WeakMap<World, Map<string, number>>();
2018
+ const preparedHandle = <Brand extends string>(
2019
+ world: World,
2020
+ guid: string,
2021
+ brand: Brand,
2022
+ ): Handle<Brand, 'shared'> | undefined => {
2023
+ let handles = preparedAssetHandles.get(world);
2024
+ if (handles === undefined) {
2025
+ handles = new Map();
2026
+ preparedAssetHandles.set(world, handles);
2027
+ }
2028
+ const key = `${brand}:${guid.toLowerCase()}`;
2029
+ const cached = handles.get(key);
2030
+ if (cached !== undefined) return cached as Handle<Brand, 'shared'>;
2031
+ const asset = internals.assets.lookup(guid);
2032
+ if (asset === undefined) return undefined;
2033
+ const handle = world.allocSharedRef(brand, asset);
2034
+ handles.set(key, handle as number);
2035
+ return handle;
2036
+ };
2037
+ const preparedMaterialBindings = (
2038
+ materialShaderId: string,
2039
+ worldIndex: number,
2040
+ materialGuid: string,
2041
+ layout: BindGroupLayout,
2042
+ ) => {
2043
+ const world = preparedWorlds[worldIndex];
2044
+ const material = internals.assets.lookup(materialGuid) as MaterialAsset | undefined;
2045
+ const pipelineState = internals.getPipelineState();
2046
+ if (world === undefined || material?.kind !== 'material' || pipelineState === null) {
2047
+ return err(new Error('prepared material asset is unavailable'));
2048
+ }
2049
+ const schemaProjection = internals.getParamSchemaProjection?.(materialShaderId);
2050
+ const schema = schemaProjection?.schema ?? internals.getParamSchema?.(materialShaderId) ?? [];
2051
+ const values = material.values ?? {};
2052
+ const derived =
2053
+ schemaProjection?.derivedInterface ??
2054
+ deriveParamSchemaForCensus(
2055
+ schema,
2056
+ internals.paramSchemaProjectionCensus,
2057
+ 'prepared-material',
2058
+ );
2059
+ if (internals.paramSchemaProjectionCensus !== undefined && schemaProjection !== undefined) {
2060
+ internals.paramSchemaProjectionCensus.record(
2061
+ 'registered-projection-read',
2062
+ 'prepared-material',
2063
+ );
2064
+ if (
2065
+ schemaProjection.schema.length === 0 &&
2066
+ Object.keys(values).some((name) => name.endsWith('Texture'))
2067
+ ) {
2068
+ internals.paramSchemaProjectionCensus.record(
2069
+ 'empty-schema-legacy-inference',
2070
+ 'prepared-material',
2071
+ );
2072
+ }
2073
+ }
2074
+ const fields = [...derived.textureFieldNames];
2075
+ let buffer: Buffer | undefined;
2076
+ let payloadByteLength = 0;
2077
+ if (derived.uboLayout.totalBytes > 0) {
2078
+ const payload = new Uint8Array(Math.max(16, derived.uboLayout.totalBytes));
2079
+ applyParamSnapshotToUbo(
2080
+ payload,
2081
+ schema,
2082
+ values as Readonly<Record<string, number | readonly number[]>>,
2083
+ internals.paramSchemaProjectionCensus,
2084
+ );
2085
+ const created = internals.device.createBuffer({
2086
+ label: `prepared-material:${materialGuid}`,
2087
+ size: payload.byteLength,
2088
+ usage: GPU_BUFFER_USAGE_UNIFORM | GPU_BUFFER_USAGE_COPY_DST,
2089
+ });
2090
+ if (!created.ok) return created;
2091
+ buffer = created.value;
2092
+ payloadByteLength = payload.byteLength;
2093
+ const written = internals.device.queue.writeBuffer(buffer, 0, payload);
2094
+ if (!written.ok) {
2095
+ internals.device.destroyBuffer(buffer);
2096
+ return written;
2097
+ }
2098
+ }
2099
+ const textureResources: Array<{
2100
+ sampler: import('@forgeax/engine-rhi').Sampler;
2101
+ view: import('@forgeax/engine-rhi').TextureView;
2102
+ }> = [];
2103
+ for (let index = 0; index < fields.length; index += 1) {
2104
+ const field = fields[index];
2105
+ const value = field === undefined ? undefined : values[field];
2106
+ const textureValue =
2107
+ typeof value === 'object' && value !== null && 'texture' in value
2108
+ ? (value as MaterialTextureValue)
2109
+ : undefined;
2110
+ let sampler = pipelineState.defaultSampler;
2111
+ if (textureValue?.sampler !== undefined) {
2112
+ const handle = preparedHandle(world, String(textureValue.sampler), 'SamplerAsset');
2113
+ if (handle !== undefined) {
2114
+ const asset = resolveRenderAsset<SamplerAsset>(world, handle);
2115
+ if (asset.ok) {
2116
+ const resident = internals.gpuStore.ensureSamplerResident(
2117
+ handle,
2118
+ asset.value,
2119
+ worldIndex,
2120
+ );
2121
+ if (resident.ok) sampler = resident.value;
2122
+ }
2123
+ }
2124
+ }
2125
+ let view = pipelineState.defaultWhiteTextureView;
2126
+ if (textureValue !== undefined) {
2127
+ const handle = preparedHandle(world, String(textureValue.texture), 'TextureAsset');
2128
+ if (handle !== undefined) {
2129
+ view =
2130
+ residentTextureView(world, internals.gpuStore, internals, handle, worldIndex) ?? view;
2131
+ }
2132
+ }
2133
+ textureResources.push({ sampler, view });
2134
+ }
2135
+ const entries: BindGroupEntry[] = [];
2136
+ let textureIndex = 0;
2137
+ for (let index = 0; index < derived.bglEntries.length; index += 1) {
2138
+ const expected = derived.bglEntries[index];
2139
+ if (expected?.buffer?.type === 'uniform' && buffer !== undefined) {
2140
+ entries.push({
2141
+ binding: expected.binding,
2142
+ resource: { kind: 'buffer', value: { buffer, size: payloadByteLength } },
2143
+ });
2144
+ continue;
2145
+ }
2146
+ const textureResource = textureResources[textureIndex];
2147
+ if (
2148
+ expected?.sampler?.type === 'filtering' &&
2149
+ derived.bglEntries[index + 1]?.texture !== undefined &&
2150
+ textureResource !== undefined
2151
+ ) {
2152
+ entries.push({
2153
+ binding: expected.binding,
2154
+ resource: { kind: 'sampler', value: textureResource.sampler },
2155
+ });
2156
+ continue;
2157
+ }
2158
+ if (expected?.texture !== undefined && textureResource !== undefined) {
2159
+ entries.push({
2160
+ binding: expected.binding,
2161
+ resource: { kind: 'textureView', value: textureResource.view },
2162
+ });
2163
+ textureIndex += 1;
2164
+ continue;
2165
+ }
2166
+ if (buffer !== undefined) internals.device.destroyBuffer(buffer);
2167
+ return err(new Error('prepared material schema contains unsupported binding kinds'));
2168
+ }
2169
+ for (let index = fields.length; index < 4; index += 1) {
2170
+ const binding = derived.userRegionBindingEnd + (index - fields.length) * 2;
2171
+ entries.push(
2172
+ {
2173
+ binding,
2174
+ resource: { kind: 'sampler', value: pipelineState.defaultSampler },
2175
+ },
2176
+ {
2177
+ binding: binding + 1,
2178
+ resource: { kind: 'textureView', value: pipelineState.defaultWhiteTextureView },
2179
+ },
2180
+ );
2181
+ }
2182
+ const fallback = pipelineState.skylightFallback;
2183
+ if (fallback === null) {
2184
+ if (buffer !== undefined) internals.device.destroyBuffer(buffer);
2185
+ return err(new Error('prepared material skylight fallback is unavailable'));
2186
+ }
2187
+ const completeEntries = assembleMaterialWithSkylightEntries(
2188
+ entries,
2189
+ {
2190
+ irradianceView: fallback.irradianceView,
2191
+ irradianceSampler: fallback.sampler,
2192
+ prefilterView: fallback.prefilterView,
2193
+ prefilterSampler: fallback.sampler,
2194
+ brdfLutView: fallback.brdfLutView,
2195
+ brdfLutSampler: fallback.sampler,
2196
+ intensityBuffer: fallback.intensityBuffer,
2197
+ },
2198
+ {
2199
+ emissiveSampler: pipelineState.defaultSampler,
2200
+ emissiveView: pipelineState.defaultWhiteTextureView,
2201
+ occlusionSampler: pipelineState.defaultSampler,
2202
+ occlusionView: pipelineState.defaultWhiteTextureView,
2203
+ },
2204
+ );
2205
+ const group = internals.device.createBindGroup({ layout, entries: completeEntries });
2206
+ if (!group.ok) {
2207
+ if (buffer !== undefined) internals.device.destroyBuffer(buffer);
2208
+ return group;
2209
+ }
2210
+ if (buffer === undefined) return group;
2211
+ return ok({
2212
+ handle: group.value,
2213
+ dynamicOffsets: [0],
2214
+ release: () => internals.device.destroyBuffer(buffer),
2215
+ });
2216
+ };
2217
+ const lastFrustumStats: { culled: number; total: number } = { culled: 0, total: 0 };
2218
+ const lastVisibilityStats: { explicitlyHidden: number } = { explicitlyHidden: 0 };
2219
+ let lastMeshMaterialBindings: readonly MeshMaterialBindingObservation[] = [];
2220
+ let lastMeshMaterialBindingFrame: ExtractedFrame | undefined;
2221
+ const preparedResolverFactory = (
2222
+ input: RenderFeaturePreparedGraphicsResolverInput,
2223
+ ): PreparedGraphicsResolver =>
2224
+ createPreparedGraphicsResolver({
2225
+ device: internals.device,
2226
+ featureIdentity: input.featureIdentity,
2227
+ generation: input.generation,
2228
+ capabilityAvailable: true,
2229
+ featureOrder: input.order,
2230
+ lookup: input.lookup,
2231
+ resolveGpuBuffer: (reference) =>
2232
+ getFeatureGpuWork(input.featureIdentity).resolveBuffer(reference),
2233
+ resolvePipeline: (descriptor) => {
2234
+ const postProcessEntry = internals.lookupPostProcess?.(descriptor.shader);
2235
+ if (postProcessEntry !== undefined) {
2236
+ const fullscreen = buildFullscreenPostProcessPass(
2237
+ { device: internals.device, errorRegistry: internals.errorRegistry },
2238
+ postProcessEntry,
2239
+ );
2240
+ if (fullscreen === null) return err(new Error('prepared post-process layout failed'));
2241
+ const pipeline = internals.getPostProcessPipeline?.(
2242
+ descriptor.shader,
2243
+ fullscreen.bindGroupLayout,
2244
+ descriptor.colorFormats[0] as GPUTextureFormat,
2245
+ );
2246
+ if (pipeline !== null && pipeline !== undefined) {
2247
+ preparedPipelineIds.set(pipeline as object, descriptor.shader);
2248
+ if (internals.getMaterialShaderBindingContract?.(descriptor.shader) === 'group-0') {
2249
+ preparedGroup0Pipelines.add(pipeline as object);
2250
+ }
2251
+ }
2252
+ return pipeline === null || pipeline === undefined
2253
+ ? err(makePreparedPipelinePendingError())
2254
+ : ok(pipeline);
2255
+ }
2256
+ const preparedPipeline = internals.getMaterialShaderPipeline?.(
2257
+ descriptor.shader,
2258
+ descriptor.colorFormats[0] === 'rgba16float',
2259
+ descriptor.renderState,
2260
+ descriptor.topology,
2261
+ descriptor.indexFormat,
2262
+ undefined,
2263
+ 'forward',
2264
+ undefined,
2265
+ descriptor.sampleCount ?? 1,
2266
+ // Prepared graphics own their declared attachment format. Passing
2267
+ // it through keeps the PSO compatible with feature-target views
2268
+ // (the ordinary material path intentionally defaults to the
2269
+ // swap-chain view format).
2270
+ descriptor.colorFormats[0] as GPUTextureFormat,
2271
+ undefined,
2272
+ descriptor.depthFormat === undefined
2273
+ ? null
2274
+ : (descriptor.depthFormat as GPUTextureFormat),
2275
+ descriptor.vertexLayout,
2276
+ );
2277
+ // A requested material shader is an exact pipeline contract. During
2278
+ // async shader warmup, substituting the generic unlit pipeline can
2279
+ // mismatch vertex layouts and HDR attachment formats, turning a
2280
+ // retryable next-frame prepare into an invalid GPU command buffer.
2281
+ const pipeline = preparedPipeline ?? null;
2282
+ if (pipeline !== null) {
2283
+ preparedMaterialPipelineShaders.set(pipeline as object, descriptor.shader);
2284
+ const bindingContract = internals.getMaterialShaderBindingContract?.(descriptor.shader);
2285
+ if (bindingContract === 'group-0') {
2286
+ preparedGroup0Pipelines.add(pipeline as object);
2287
+ } else if (bindingContract === 'view-only') {
2288
+ preparedViewOnlyPipelines.add(pipeline as object);
2289
+ } else if (bindingContract === 'view-with-resource') {
2290
+ preparedViewWithResourcePipelines.add(pipeline as object);
2291
+ } else {
2292
+ preparedRenderMaterialPipelines.add(pipeline as object);
2293
+ }
2294
+ }
2295
+ return pipeline === null ? err(makePreparedPipelinePendingError()) : ok(pipeline);
2296
+ },
2297
+ resolveBindings: (descriptor, pipeline) => {
2298
+ const materialShaderId = preparedMaterialPipelineShaders.get(pipeline as object);
2299
+ const bindingContract =
2300
+ materialShaderId === undefined
2301
+ ? undefined
2302
+ : internals.getMaterialShaderBindingContract?.(materialShaderId);
2303
+ if (bindingContract === 'group-0-resource') {
2304
+ return descriptor.values.sceneDepth === undefined
2305
+ ? err(new Error('prepared group-0 resource pipeline requires a scene target'))
2306
+ : ok(undefined);
2307
+ }
2308
+ if (preparedGroup0Pipelines.has(pipeline as object)) {
2309
+ const layout =
2310
+ (materialShaderId === undefined
2311
+ ? undefined
2312
+ : internals.getMaterialBindGroupLayout?.(materialShaderId)) ??
2313
+ (
2314
+ pipeline as RenderPipeline & {
2315
+ getBindGroupLayout?: (index: number) => BindGroupLayout;
2316
+ }
2317
+ ).getBindGroupLayout?.(0);
2318
+ return layout === undefined
2319
+ ? err(new Error('prepared group-0 pipeline bind group layout is unavailable'))
2320
+ : internals.device.createBindGroup({ layout, entries: [] });
2321
+ }
2322
+ if (
2323
+ preparedViewOnlyPipelines.has(pipeline as object) ||
2324
+ preparedViewWithResourcePipelines.has(pipeline as object) ||
2325
+ (preparedRenderMaterialPipelines.has(pipeline as object) &&
2326
+ descriptor.values.group === 0) ||
2327
+ pipeline === internals.getPipelineState()?.unlitPipeline
2328
+ ) {
2329
+ return ok(undefined);
2330
+ }
2331
+ const group = descriptor.values.group;
2332
+ const layout =
2333
+ (materialShaderId !== undefined
2334
+ ? (internals.getMaterialBindGroupLayout?.(materialShaderId) ??
2335
+ (group === 0 ? internals.getPipelineState()?.materialBindGroupLayout : undefined))
2336
+ : undefined) ??
2337
+ (
2338
+ pipeline as RenderPipeline & {
2339
+ getBindGroupLayout?: (index: number) => BindGroupLayout;
2340
+ }
2341
+ ).getBindGroupLayout?.(group === 1 ? 1 : 0);
2342
+ const material = descriptor.values.material;
2343
+ if (
2344
+ group === 1 &&
2345
+ layout !== undefined &&
2346
+ materialShaderId !== undefined &&
2347
+ typeof material === 'object' &&
2348
+ material !== null &&
2349
+ 'world' in material &&
2350
+ 'guid' in material &&
2351
+ typeof material.world === 'number' &&
2352
+ typeof material.guid === 'string'
2353
+ ) {
2354
+ return preparedMaterialBindings(materialShaderId, material.world, material.guid, layout);
2355
+ }
2356
+ return layout === undefined
2357
+ ? err(new Error('prepared pipeline bind group layout is unavailable'))
2358
+ : internals.device.createBindGroup({
2359
+ layout,
2360
+ entries:
2361
+ group === 1 && preparedPipelineIds.has(pipeline as object)
2362
+ ? [
2363
+ {
2364
+ binding: 0,
2365
+ resource: {
2366
+ kind: 'textureView',
2367
+ value: internals.getPipelineState()?.fallbackTextureView as never,
2368
+ },
2369
+ },
2370
+ {
2371
+ binding: 1,
2372
+ resource: {
2373
+ kind: 'sampler',
2374
+ value: internals.getPipelineState()?.defaultSampler as never,
2375
+ },
2376
+ },
2377
+ ...(internals.getPostProcessParamsBuffer?.(
2378
+ preparedPipelineIds.get(pipeline as object) ?? '',
2379
+ ) === undefined
2380
+ ? []
2381
+ : [
2382
+ {
2383
+ binding: 2,
2384
+ resource: {
2385
+ kind: 'buffer' as const,
2386
+ value: {
2387
+ buffer: internals.getPostProcessParamsBuffer?.(
2388
+ preparedPipelineIds.get(pipeline as object) ?? '',
2389
+ ) as never,
2390
+ },
2391
+ },
2392
+ },
2393
+ ]),
2394
+ ]
2395
+ : [],
2396
+ });
2397
+ },
2398
+ });
2399
+ return {
2400
+ applyShadowSubmitMode(
2401
+ mode: ShadowSubmitMode,
2402
+ rendererGeneration: string,
2403
+ ): ShadowSubmitResult<ShadowSubmitModeState> {
2404
+ const result = applyShadowSubmitMode(
2405
+ frameState.shadowSubmitModeState,
2406
+ mode,
2407
+ rendererGeneration,
2408
+ );
2409
+ if (result.ok) frameState.shadowSubmitModeState = result.value;
2410
+ return result;
2411
+ },
2412
+ restoreShadowSubmitMode(rendererGeneration: string): ShadowSubmitResult<ShadowSubmitModeState> {
2413
+ const result = restoreShadowSubmitMode(frameState.shadowSubmitModeState, rendererGeneration);
2414
+ if (result.ok) {
2415
+ frameState.shadowSubmitModeState = result.value;
2416
+ frameState.pendingShadowCommandBuffers = [];
2417
+ }
2418
+ return result;
2419
+ },
2420
+ getShadowSubmitMode(): ShadowSubmitModeState {
2421
+ return frameState.shadowSubmitModeState;
2422
+ },
2423
+ releaseProfilerCatalog(): void {
2424
+ releaseProfilerCatalog?.();
2425
+ releaseProfilerCatalog = undefined;
2426
+ },
2427
+ get renderScene(): RenderSceneInspection {
2428
+ const temporal = projectTemporalInspection(temporalFrameTransaction.inspect());
2429
+ return {
2430
+ ...persistentRenderScene.inspect(),
2431
+ gpuDriven: gpuDrivenProduction.inspect(),
2432
+ temporal,
2433
+ environment: inspectEnvironmentGeneration(frameState.environmentGeneration, {
2434
+ sourceWorldId: environmentConsumerSnapshot(frameState.environmentGeneration)?.source
2435
+ ?.worldId,
2436
+ sourceEntity: environmentConsumerSnapshot(frameState.environmentGeneration)?.source
2437
+ ?.entity,
2438
+ taa: {
2439
+ activeSignature: temporal.environmentSignature,
2440
+ publishCount: temporal.environmentPublishCount,
2441
+ resetCount: temporal.environmentResetCount,
2442
+ lastResetReason: temporal.resetReason,
2443
+ },
2444
+ }),
2445
+ };
2446
+ },
2447
+ detachWorld(world: World): void {
2448
+ taaHistoryStore.invalidate('world-detached');
2449
+ persistentRenderScene.detach(world);
2450
+ materialSnapshotCachesByWorld.delete(world);
2451
+ },
2452
+ draw(worlds: readonly World[], opts: DrawOwnerOptions): boolean {
2453
+ preparedWorlds = worlds;
2454
+ const profileSession = internals.profiler?.activeSession();
2455
+ let ownsProfileFrame = false;
2456
+ let submitted = false;
2457
+ if (profileSession !== undefined && opts.profileFrame === undefined) {
2458
+ try {
2459
+ ownsProfileFrame = profileSession.beginFrame(++directFrameId).ok;
2460
+ } catch {
2461
+ ownsProfileFrame = false;
2462
+ }
2463
+ }
2464
+ try {
2465
+ // cameraOwner drives the surfaced cameras + frustum
2466
+ // cull; resourceOwner drives skylight/skybox/postProcess + per-world
2467
+ // record config.
2468
+ const { cameraOwner, resourceOwner } = opts;
2469
+ // Keep the compiled graph as last-known-good until the candidate topology
2470
+ // compiles. The failed candidate frame does not execute it; successful
2471
+ // replacement retires it atomically in ensureCompiledFrameGraph.
2472
+ if (frameState.installedPipelineHandle !== lastBuiltPipelineHandle) {
2473
+ // Feature contributions describe the active pipeline graph. Drop the
2474
+ // old composition before the next frame re-runs feature contribution
2475
+ // so a hot-swap cannot reuse passes compiled for the retired pipeline.
2476
+ resetRenderFeatureGraphState(internals);
2477
+ lastBuiltPipelineHandle = frameState.installedPipelineHandle;
2478
+ persistentRenderScene.invalidate();
2479
+ }
2480
+ dispatchCounts.unlit = 0;
2481
+
2482
+ // feat-20260708-composited-multi-world-rendering M3 / D-2 / m3-i2:
2483
+ // extractFrames merges per-world snapshots (renderables + lights from
2484
+ // every world, cameras + singleton resources from the owner world),
2485
+ // runs read-only extractFrame per world over the already-updated World,
2486
+ // resets frame state once, and isolates
2487
+ // per-world errors (AC-09).
2488
+ // Single-world draw([world], { cameraOwner: 0, resourceOwner: 0 }) is the identity path
2489
+ // (worldId=0), byte-for-byte equivalent to the pre-M3 direct
2490
+ // extractFrame path (AC-03 regression guarantee).
2491
+ //
2492
+ // Entry validation (empty worlds / owner out of range) is enforced by
2493
+ // the public renderer.draw facade (createRenderer.ts, D-5) before this
2494
+ // internal method is reached; the owner world is guaranteed present.
2495
+ //
2496
+ // feat-20260709-editor-world-partition M1 / w5+w6 (D-3): per-world
2497
+ // record configuration (transparent-sort mode, fold buckets, skybox /
2498
+ // asset resolution) is read from the resource-owner world — the world
2499
+ // that owns skylight / skybox / postProcessParams. w6 sources it from
2500
+ // the dedicated resourceOwner index. The variable is named
2501
+ // `resourceWorld` so the record-stage reads are self-describing (they
2502
+ // are resource-owner reads, not camera reads).
2503
+ const resourceWorld = worlds[resourceOwner] as World;
2504
+ const frame = runProfiledRenderPhase(profileSession, 'extract', () => {
2505
+ const ordinaryWorld =
2506
+ worlds.length === 1 && cameraOwner === 0 && resourceOwner === 0 ? worlds[0] : undefined;
2507
+ if (ordinaryWorld === undefined) {
2508
+ return persistentRenderScene.extractComposition(
2509
+ worlds,
2510
+ { cameraOwner, resourceOwner },
2511
+ internals.assets.epoch,
2512
+ () =>
2513
+ extractFrames(
2514
+ worlds,
2515
+ { cameraOwner, resourceOwner },
2516
+ internals.assets,
2517
+ internals.getPipelineState(),
2518
+ internals.gpuStore,
2519
+ materialSnapshotCachesByWorld,
2520
+ {
2521
+ cull: 'none',
2522
+ ...(internals.paramSchemaProjectionCensus === undefined
2523
+ ? {}
2524
+ : { paramSchemaProjectionCensus: internals.paramSchemaProjectionCensus }),
2525
+ },
2526
+ ),
2527
+ (world, worldId, entity, currentFrame) => {
2528
+ let materialSnapshotCache = materialSnapshotCachesByWorld.get(world);
2529
+ if (materialSnapshotCache === undefined) {
2530
+ materialSnapshotCache = new Map();
2531
+ materialSnapshotCachesByWorld.set(world, materialSnapshotCache);
2532
+ }
2533
+ const visibility = currentFrame.featureVisibilitySnapshots.find(
2534
+ (entry) => entry.world === world,
2535
+ )?.snapshot ?? {
2536
+ diagnostics: [],
2537
+ hasAnyIntent: false,
2538
+ hasAnyHiddenIntent: false,
2539
+ get: () => undefined,
2540
+ effective: () => 'visible' as const,
2541
+ };
2542
+ const extracted = extractRenderableEntity(world, entity, {
2543
+ assets: internals.assets,
2544
+ pipelineState: internals.getPipelineState(),
2545
+ gpuStore: internals.gpuStore,
2546
+ materialSnapshotCache,
2547
+ ...(internals.paramSchemaProjectionCensus === undefined
2548
+ ? {}
2549
+ : { paramSchemaProjectionCensus: internals.paramSchemaProjectionCensus }),
2550
+ cull: 'none',
2551
+ cullCameras: undefined,
2552
+ hierarchy: {
2553
+ parentOf: new Map(),
2554
+ diagnostics: [],
2555
+ getParent: () => undefined,
2556
+ },
2557
+ visibility,
2558
+ });
2559
+ if (extracted === undefined) return undefined;
2560
+ return {
2561
+ snapshot:
2562
+ extracted.snapshot.worldId === worldId
2563
+ ? extracted.snapshot
2564
+ : { ...extracted.snapshot, worldId },
2565
+ candidateDispatch: extracted.candidateDispatch,
2566
+ };
2567
+ },
2568
+ );
2569
+ }
2570
+ const pipelineState = internals.getPipelineState();
2571
+ pipelineState?.skinPaletteAllocator?.resetForFrame();
2572
+ let materialSnapshotCache = materialSnapshotCachesByWorld.get(ordinaryWorld);
2573
+ if (materialSnapshotCache === undefined) {
2574
+ materialSnapshotCache = new Map();
2575
+ materialSnapshotCachesByWorld.set(ordinaryWorld, materialSnapshotCache);
2576
+ }
2577
+ return persistentRenderScene.extract(
2578
+ ordinaryWorld,
2579
+ internals.assets.epoch,
2580
+ () =>
2581
+ extractFrame(
2582
+ ordinaryWorld,
2583
+ prepareExtractContext(ordinaryWorld, {
2584
+ assets: internals.assets,
2585
+ pipelineState,
2586
+ gpuStore: internals.gpuStore,
2587
+ materialSnapshotCache,
2588
+ ...(internals.paramSchemaProjectionCensus === undefined
2589
+ ? {}
2590
+ : { paramSchemaProjectionCensus: internals.paramSchemaProjectionCensus }),
2591
+ cull: 'none',
2592
+ }),
2593
+ ),
2594
+ (snapshot, materialHandle) =>
2595
+ refreshRenderableMaterialSnapshot(
2596
+ snapshot,
2597
+ materialHandle,
2598
+ ordinaryWorld,
2599
+ internals.assets,
2600
+ internals.gpuStore,
2601
+ materialSnapshotCache,
2602
+ internals.paramSchemaProjectionCensus,
2603
+ ),
2604
+ (current) => refreshExtractedFrameCameras(ordinaryWorld, current),
2605
+ `${internals.gpuStore.meshResidencyEpoch}:${frameState.isHdrpActive ? 'hdrp' : 'urp'}`,
2606
+ (current) => refreshExtractedFramePostProcessParams(ordinaryWorld, current),
2607
+ (current) => refreshExtractedFrameLights(ordinaryWorld, current),
2608
+ (entity: EntityHandle, currentFrame) =>
2609
+ extractRenderableEntity(ordinaryWorld, entity, {
2610
+ assets: internals.assets,
2611
+ pipelineState,
2612
+ gpuStore: internals.gpuStore,
2613
+ materialSnapshotCache,
2614
+ cull: 'none',
2615
+ cullCameras: undefined,
2616
+ hierarchy: {
2617
+ parentOf: new Map(),
2618
+ diagnostics: [],
2619
+ getParent: () => undefined,
2620
+ },
2621
+ visibility: currentFrame.visibilitySnapshots[0] ?? {
2622
+ diagnostics: [],
2623
+ hasAnyIntent: false,
2624
+ hasAnyHiddenIntent: false,
2625
+ get: () => undefined,
2626
+ effective: () => 'visible',
2627
+ },
2628
+ }),
2629
+ );
2630
+ });
2631
+ const fogSelection = selectFog(resourceWorld, resourceOwner);
2632
+ if (fogSelection.ok) {
2633
+ persistentRenderScene.stageFogCandidate(fogSelection.value);
2634
+ } else {
2635
+ // Fog authoring failures are renderer-owned structured errors. Keep
2636
+ // the retained LKG candidate while publishing the same error object
2637
+ // through Renderer.onError for AI recovery.
2638
+ internals.errorRegistry.fire(fogSelection.error);
2639
+ persistentRenderScene.stageFogFailure({
2640
+ code: fogSelection.error.code,
2641
+ resourceOwner,
2642
+ });
2643
+ }
2644
+ const {
2645
+ cameras,
2646
+ lights,
2647
+ renderables: extractedRenderables,
2648
+ dispatch,
2649
+ environment,
2650
+ frustumStats,
2651
+ visibilityStats,
2652
+ postProcessParams,
2653
+ } = frame;
2654
+ const temporalProjection = persistentRenderScene.temporalProjection(worlds);
2655
+ const renderables =
2656
+ temporalProjection === undefined
2657
+ ? extractedRenderables
2658
+ : extractedRenderables.map((snapshot) => temporalProjection.withTemporal(snapshot));
2659
+ const skinPaletteAllocator = internals.getPipelineState()?.skinPaletteAllocator;
2660
+ if (skinPaletteAllocator !== null && skinPaletteAllocator !== undefined) {
2661
+ for (const renderable of renderables) {
2662
+ const skin = renderable.skin;
2663
+ if (skin === undefined) continue;
2664
+ skinPaletteAllocator.writePreviousJointPalette(
2665
+ skin,
2666
+ renderable.temporal?.previousSkin?.jointMatrices ?? skin.jointMatrices,
2667
+ );
2668
+ }
2669
+ }
2670
+ const gpuDrivenVisibilityScene =
2671
+ worlds.length === 1 && cameraOwner === 0 && resourceOwner === 0
2672
+ ? persistentRenderScene.gpuDrivenState(worlds[0])
2673
+ : persistentRenderScene.compositionGpuDrivenState();
2674
+ // Publish one main + three-cascade visibility result before record.
2675
+ // The production batch topology joins these stable IDs once and both
2676
+ // indirect-capable and direct-RHI executors consume that submission.
2677
+ gpuDrivenProduction.prepareCpuVisibility({
2678
+ scene: gpuDrivenVisibilityScene,
2679
+ frame,
2680
+ camera: cameras[0],
2681
+ });
2682
+ if (lastMeshMaterialBindingFrame !== frame) {
2683
+ lastMeshMaterialBindingFrame = frame;
2684
+ lastMeshMaterialBindings = renderables.map((renderable) => ({
2685
+ worldId: renderable.worldId,
2686
+ entityKey: renderable.entityKey,
2687
+ bindings: renderable.materials.map((material, slotIndex) => ({
2688
+ handle: material.materialHandle ?? 0,
2689
+ source: renderable.materialBindingSources[slotIndex] ?? 'engine-default',
2690
+ })),
2691
+ diagnostics: renderable.materialBindingDiagnostics ?? [],
2692
+ }));
2693
+ }
2694
+
2695
+ bindGroupCounts.createBindGroup = 0;
2696
+ bindGroupCounts.keys = [];
2697
+ const preparedPipelineState = internals.getPipelineState();
2698
+ const bindGroupSkipReason: RenderPhaseSkipReason | undefined =
2699
+ internals.featureHost === undefined
2700
+ ? 'feature-host-unavailable'
2701
+ : internals.featureHost.size === 0
2702
+ ? 'feature-host-empty'
2703
+ : preparedPipelineState === null
2704
+ ? 'pipeline-state-unavailable'
2705
+ : frame.cameras.length === 0
2706
+ ? 'camera-unavailable'
2707
+ : undefined;
2708
+ if (bindGroupSkipReason !== undefined || preparedPipelineState === null) {
2709
+ recordProfileSkip(
2710
+ profileSession,
2711
+ 'bind-groups',
2712
+ bindGroupSkipReason ?? 'pipeline-state-unavailable',
2713
+ );
2714
+ } else {
2715
+ runProfiledRenderPhase(profileSession, 'bind-groups', () =>
2716
+ buildPerFrameBindGroups(
2717
+ internals,
2718
+ frameState,
2719
+ preparedPipelineState,
2720
+ true,
2721
+ bindGroupCounts,
2722
+ undefined,
2723
+ false,
2724
+ ),
2725
+ );
2726
+ }
2727
+ lastFrustumStats.culled = frustumStats.culled;
2728
+ lastFrustumStats.total = frustumStats.total;
2729
+ lastVisibilityStats.explicitlyHidden = visibilityStats.explicitlyHidden;
2730
+ const featureTargets =
2731
+ preparedPipelineState === null || cameras[0] === undefined
2732
+ ? []
2733
+ : resolveStandardRenderFeatureTargets({
2734
+ pipelineId: frameState.isHdrpActive ? 'forgeax::hdrp' : 'forgeax::urp',
2735
+ tonemap: cameras[0].tonemap,
2736
+ antialias: cameras[0].antialias,
2737
+ colorAttachmentFormat: preparedPipelineState.colorAttachmentFormat,
2738
+ storageBuffer: internals.device.caps.storageBuffer,
2739
+ multisample: internals.device.caps.backendKind !== 'wgpu-webgl2',
2740
+ });
2741
+ const preparedResourceBatches = runProfiledRenderPhase(profileSession, 'features', () => {
2742
+ if (internals.featureHost === undefined) return [];
2743
+ const featureFrame = runRenderFeatureFrame(internals.featureHost, {
2744
+ worlds,
2745
+ owner: resourceOwner,
2746
+ frameNumber: frameState.frameNumber,
2747
+ visibilitySnapshots: frame.featureVisibilitySnapshots,
2748
+ hiddenEntityReports: frame.hiddenEntityReports,
2749
+ targets: featureTargets,
2750
+ generation: internals.featureHost?.preparedGeneration ?? 0,
2751
+ caps: internals.device.caps,
2752
+ createContributionStaging: (
2753
+ identity,
2754
+ order,
2755
+ validateGraphics,
2756
+ resolveGraphics,
2757
+ resolveGpuCompute,
2758
+ ) =>
2759
+ createRenderFeatureContributionStaging<RenderFeaturePassContext>(
2760
+ identity,
2761
+ order,
2762
+ validateGraphics,
2763
+ resolveGraphics,
2764
+ resolveGpuCompute,
2765
+ ),
2766
+ createPreparedGraphicsResolver: preparedResolverFactory,
2767
+ ...(internals.getMaterialShaderBindingContract === undefined
2768
+ ? {}
2769
+ : { getMaterialShaderBindingContract: internals.getMaterialShaderBindingContract }),
2770
+ resolveMaterialAsset: (material) => resolveMaterialFromPort(material, internals.assets),
2771
+ getGpuWorkResolver: getFeatureGpuWork,
2772
+ });
2773
+ lastVisibilityStats.explicitlyHidden = featureFrame.hiddenEntityReports.length;
2774
+ for (const featureError of featureFrame.errors) {
2775
+ if (!isPendingRenderFeaturePreparation(featureError)) {
2776
+ internals.errorRegistry.fire(featureError);
2777
+ }
2778
+ }
2779
+ const featureGraphState = getRenderFeatureGraphState(internals);
2780
+ const merged = mergeRenderFeatureContributions(featureFrame.contributions);
2781
+ if (!merged.ok) {
2782
+ reportRenderFeatureGraphError(internals, merged.error);
2783
+ if (featureGraphState.composition !== undefined) {
2784
+ retireCompiledFrameGraph(frameState, taaHistoryStore);
2785
+ featureGraphState.composition = undefined;
2786
+ }
2787
+ featureGraphState.contributions = [];
2788
+ featureGraphState.topologySignature = undefined;
2789
+ } else {
2790
+ const topologyChanged =
2791
+ featureGraphState.topologySignature !== undefined &&
2792
+ featureGraphState.topologySignature !== merged.value.topologySignature;
2793
+ featureGraphState.contributions = featureFrame.contributions;
2794
+ featureGraphState.topologySignature = merged.value.topologySignature;
2795
+ if (topologyChanged) {
2796
+ retireCompiledFrameGraph(frameState, taaHistoryStore);
2797
+ featureGraphState.composition = undefined;
2798
+ }
2799
+ }
2800
+ return featureFrame.preparedResourceBatches;
2801
+ });
2802
+
2803
+ // Unified transparent-sort: (layer ASC, sortValue ASC) for modes 0/1/2;
2804
+ // distance back-to-front for mode=3. The transparent-sort config is a
2805
+ // per-world resource; it is read from the resource-owner world (the
2806
+ // world that owns skylight / skybox / singleton render state, w5 / D-3).
2807
+ // Only the Transparent segment is reordered; queue ordering between
2808
+ // segments (sortDispatchByQueue, stable) is preserved.
2809
+ const orderedDispatch = runProfiledRenderPhase(profileSession, 'sort', () =>
2810
+ sortTransparentDispatch(dispatch, resourceWorld, cameras, renderables),
2811
+ );
2812
+ const temporalCoverage = sceneTemporalCoverage({
2813
+ renderables,
2814
+ dispatch: orderedDispatch,
2815
+ features: getRenderFeatureGraphState(internals).contributions,
2816
+ });
2817
+
2818
+ // M3 / w26: single dispatch list replaces old three-bucket model.
2819
+ // Pass dispatch to recordFrame — the record stage iterates dispatch
2820
+ // entries in queue order per plan-strategy D-3.
2821
+ //
2822
+ // feat-20260709-editor-world-partition ENGINE-fix-round2 (defect 2):
2823
+ // the record stage must resolve each renderable's mesh + material
2824
+ // textures against the world it was EXTRACTED from — never the single
2825
+ // resourceWorld. PersistentRenderScene remaps extractFrames' temporary
2826
+ // array index to renderer-local WorldRenderId before record; resolving
2827
+ // everything against resourceWorld would make a shared mesh in the
2828
+ // cameraOwner world
2829
+ // (e.g. an editor gizmo handle) resolves against resourceWorld's
2830
+ // sharedRefs — either a miss (asset-not-registered) or, when that slot
2831
+ // is occupied by an unrelated payload (equirect), a
2832
+ // wrong-kind resolve that throws in ensureResident. `worlds` is threaded
2833
+ // so the record stage receives the stable WorldRenderId lookup.
2834
+ // `resourceWorld` stays the singleton-resource owner (skybox equirect /
2835
+ // transparent-sort config / video provider) — those ARE resource-owner reads.
2836
+ const recordProfilePhase: RecordProfileRunner | undefined =
2837
+ profileSession === undefined || profileSession.detail === 'owner'
2838
+ ? undefined
2839
+ : function recordProfilePhase<T>(phase: RenderRecordPhase, action: () => T): T {
2840
+ // `passes` deliberately keeps only the graph-pass boundary.
2841
+ // The same runner is also called by geometry/material helpers;
2842
+ // invoking those wrappers would turn a pass probe into the
2843
+ // high-overhead per-draw `nested` probe.
2844
+ if (
2845
+ profileSession.detail === 'passes' &&
2846
+ (!phase.startsWith('record/graph-execute/') ||
2847
+ (phase.slice('record/graph-execute/'.length).includes('/') &&
2848
+ !phase.endsWith('/geometry-loop')))
2849
+ ) {
2850
+ return action();
2851
+ }
2852
+ return runProfiledRenderPhase(profileSession, phase, action);
2853
+ };
2854
+ submitted = runProfiledRenderPhase(profileSession, 'record', () =>
2855
+ recordFrame(
2856
+ internals,
2857
+ resourceWorld,
2858
+ cameras,
2859
+ lights,
2860
+ renderables,
2861
+ orderedDispatch,
2862
+ frameState,
2863
+ dispatchCounts,
2864
+ bindGroupCounts,
2865
+ environment,
2866
+ postProcessParams,
2867
+ worlds,
2868
+ recordProfilePhase,
2869
+ {
2870
+ owner: gpuDrivenProduction,
2871
+ scene:
2872
+ worlds.length === 1 && cameraOwner === 0 && resourceOwner === 0
2873
+ ? persistentRenderScene.gpuDrivenState(worlds[0])
2874
+ : persistentRenderScene.compositionGpuDrivenState(),
2875
+ onCoverage: (ownsAll) => {
2876
+ const key = `${internals.gpuStore.meshResidencyEpoch}:${frameState.isHdrpActive ? 'hdrp' : 'urp'}`;
2877
+ if (worlds.length === 1 && cameraOwner === 0 && resourceOwner === 0) {
2878
+ const ordinaryWorld = worlds[0];
2879
+ if (ordinaryWorld !== undefined) {
2880
+ persistentRenderScene.setGpuDrivenCoverage(ordinaryWorld, key, ownsAll);
2881
+ }
2882
+ } else {
2883
+ persistentRenderScene.setCompositionGpuDrivenCoverage(key, ownsAll);
2884
+ }
2885
+ },
2886
+ },
2887
+ persistentRenderScene.worldForRenderId,
2888
+ temporalProjection === undefined
2889
+ ? undefined
2890
+ : {
2891
+ transaction: temporalFrameTransaction,
2892
+ projection: temporalProjection,
2893
+ coverage: temporalCoverage,
2894
+ ...(fogSelection.ok
2895
+ ? { reactiveRevision: fogSelection.value.snapshot?.revision }
2896
+ : {}),
2897
+ onSceneSubmitted: (delta) => persistentRenderScene.stageTemporalSubmission(delta),
2898
+ },
2899
+ fogSelection.ok ? fogSelection.value.snapshot : persistentRenderScene.fogSnapshot(),
2900
+ ),
2901
+ );
2902
+ if (internals.featureHost !== undefined && preparedResourceBatches.length > 0) {
2903
+ const batches = preparedResourceBatches;
2904
+ if (submitted) {
2905
+ internals.featureHost.markPreparedGraphicsSubmitted(batches);
2906
+ settlePreparedGraphicsCompletion(
2907
+ internals.featureHost,
2908
+ batches,
2909
+ internals.device.queue.onSubmittedWorkDone(),
2910
+ (error) => reportPreparedGraphicsCompletionError(internals, error),
2911
+ );
2912
+ } else {
2913
+ const retired = internals.featureHost.retirePreparedGraphics();
2914
+ if (!retired.ok) internals.errorRegistry.fire(retired.error);
2915
+ }
2916
+ }
2917
+ } catch (err) {
2918
+ if (isStructuredRendererError(err)) {
2919
+ internals.errorRegistry.fire(err);
2920
+ } else {
2921
+ const innerError =
2922
+ err instanceof RhiError
2923
+ ? err
2924
+ : { code: 'unknown' as const, message: String(err), name: (err as Error)?.name };
2925
+ internals.errorRegistry.fire(
2926
+ new RhiError({
2927
+ code: 'webgpu-runtime-error',
2928
+ expected: 'RenderSystem to record one frame without an internal exception',
2929
+ hint: 'inspect detail.error for the underlying cause; next frame will retry',
2930
+ detail: { error: innerError },
2931
+ }),
2932
+ );
2933
+ }
2934
+ } finally {
2935
+ if (submitted) persistentRenderScene.stageFogSubmission();
2936
+ else persistentRenderScene.discardFogCandidate();
2937
+ if (ownsProfileFrame) {
2938
+ try {
2939
+ profileSession?.endFrame();
2940
+ } catch {
2941
+ // Profiler failures never alter rendering.
2942
+ }
2943
+ }
2944
+ }
2945
+ return submitted;
2946
+ },
2947
+ pipelineDispatchCounts: dispatchCounts,
2948
+ observeCurrentFrame(options: FrameObservationOptions) {
2949
+ const currentFrameId = frameState.frameNumber - 1;
2950
+ return observeCurrentFrame(options, frameState.currentFrameObservationSource, currentFrameId);
2951
+ },
2952
+ bindGroupCounts: bindGroupCounts,
2953
+ frustumStats: lastFrustumStats,
2954
+ visibilityStats: lastVisibilityStats,
2955
+ get meshMaterialBindings(): readonly MeshMaterialBindingObservation[] {
2956
+ return lastMeshMaterialBindings;
2957
+ },
2958
+ get perFramePassNames(): readonly string[] {
2959
+ return frameState.compiledFrameGraph?.inspect().passes.map((pass) => pass.name) ?? [];
2960
+ },
2961
+ // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle
2962
+ getCurrentShadowView(): any | null {
2963
+ return frameState.currentDirectionalShadowView;
2964
+ },
2965
+ registerPipeline(id: string, impl: RenderPipelineDef): void {
2966
+ if (pipelineRegistry.has(id)) {
2967
+ throw new PipelineError({ code: 'pipeline-already-registered', detail: { id } });
2968
+ }
2969
+ pipelineRegistry.set(id, impl);
2970
+ },
2971
+ installPipeline(asset: RenderPipelineAsset): Result<() => void, PipelineError> {
2972
+ const impl = pipelineRegistry.get(asset.pipelineId);
2973
+ if (impl === undefined) {
2974
+ return err(
2975
+ new PipelineError({ code: 'pipeline-not-found', detail: { handle: installEpoch } }),
2976
+ );
2977
+ }
2978
+ // feat-20260608-cluster-lighting M2 / w10: HDRP grid validation.
2979
+ // When the pipelineId is 'forgeax::hdrp', validate clusterGrid dimensions
2980
+ // before installing. Grid-invalid throws a standalone HdrpInstallError
2981
+ // (NOT in RuntimeErrorCode; synchronous install-time config error).
2982
+ //
2983
+ // feat-20260608-cluster-lighting M5 / w20: HDRP caps gate.
2984
+ // A zero storage-buffer ceiling is the supported WebGL2 downlevel path:
2985
+ // HDRP's cluster light list is transported through a bounded uniform
2986
+ // array. Partial storage support (1..3 slots) is still unsupported
2987
+ // because it cannot satisfy either the clustered or the complete
2988
+ // uniform fallback contract.
2989
+ if (asset.pipelineId === 'forgeax::hdrp') {
2990
+ const storageBuffersCap = internals.device.limits.maxStorageBuffersPerShaderStage;
2991
+ if (storageBuffersCap > 0 && storageBuffersCap < 4) {
2992
+ throw new HdrpCapsInsufficientError(
2993
+ 'maxStorageBuffersPerShaderStage',
2994
+ storageBuffersCap,
2995
+ 4,
2996
+ );
2997
+ }
2998
+ const grid = asset.config?.clusterGrid ?? { x: 16, y: 9, z: 24 };
2999
+ const gridResult = validateClusterGrid(grid);
3000
+ if (!gridResult.ok) {
3001
+ throw gridResult.error;
3002
+ }
3003
+ }
3004
+ const install = {
3005
+ token: {},
3006
+ id: asset.pipelineId,
3007
+ pipeline: impl,
3008
+ config: asset.config,
3009
+ isHdrp: asset.pipelineId === 'forgeax::hdrp',
3010
+ };
3011
+ pipelineInstalls.push(install);
3012
+ frameState.activePipeline = install.pipeline;
3013
+ frameState.activePipelineId = asset.pipelineId;
3014
+ // installPipeline no longer carries a handle (D-19: RenderPipelineAsset is
3015
+ // installed as a POD at boot/swap time before any World exists). The
3016
+ // brand-number that `draw` compares to force a per-frame graph rebuild is
3017
+ // now a monotonic epoch bumped on every install -- distinct configs (and
3018
+ // even identical re-installs) trigger the rebuild, which is correct: install
3019
+ // is a rare boot/swap event, never a per-frame cost.
3020
+ installEpoch += 1;
3021
+ frameState.installedPipelineHandle = installEpoch;
3022
+ frameState.isHdrpActive = install.isHdrp;
3023
+ // The install-time config becomes part of the next typed topology key.
3024
+ frameState.installedPipelineConfig = install.config;
3025
+ let active = true;
3026
+ return ok(() => {
3027
+ if (!active) return;
3028
+ active = false;
3029
+ const index = pipelineInstalls.findIndex((candidate) => candidate.token === install.token);
3030
+ if (index < 0) return;
3031
+ const wasCurrent = index === pipelineInstalls.length - 1;
3032
+ pipelineInstalls.splice(index, 1);
3033
+ if (!wasCurrent) return;
3034
+ const current = pipelineInstalls.at(-1);
3035
+ frameState.activePipeline = current?.pipeline ?? urpPipeline;
3036
+ frameState.activePipelineId = current?.id ?? URP_PIPELINE_ID;
3037
+ frameState.isHdrpActive = current?.isHdrp ?? false;
3038
+ frameState.installedPipelineConfig = current?.config;
3039
+ installEpoch += 1;
3040
+ frameState.installedPipelineHandle = installEpoch;
3041
+ });
3042
+ },
3043
+ postProcess: {
3044
+ register(id: string, entry: PostProcessShaderEntry): () => void {
3045
+ if (postProcessRegistry.has(id)) {
3046
+ throw new PostProcessError({
3047
+ code: 'post-process-already-registered',
3048
+ detail: { id },
3049
+ });
3050
+ }
3051
+ // D-3: eager-create params UBO at register time + fail-fast
3052
+ // byteSize / defaultValue validation (q5=A).
3053
+ let paramsBuffer: Buffer | undefined;
3054
+ try {
3055
+ if (entry.params !== undefined) {
3056
+ const { byteSize, defaultValue } = entry.params;
3057
+ if (byteSize < 16 || defaultValue.length !== byteSize) {
3058
+ throw new PostProcessError({
3059
+ code: 'params-size-mismatch',
3060
+ detail: { byteSize, actualLength: defaultValue.length },
3061
+ });
3062
+ }
3063
+ const paramsBufferResult = internals.device.createBuffer({
3064
+ label: `post-process-params-${id}`,
3065
+ size: byteSize,
3066
+ usage: GPU_BUFFER_USAGE_UNIFORM | GPU_BUFFER_USAGE_COPY_DST,
3067
+ mappedAtCreation: false,
3068
+ });
3069
+ if (!paramsBufferResult.ok) throw paramsBufferResult.error;
3070
+ paramsBuffer = paramsBufferResult.value;
3071
+ const writeResult = internals.device.queue.writeBuffer(paramsBuffer, 0, defaultValue);
3072
+ if (!writeResult.ok) throw writeResult.error;
3073
+ } else if (entryHasDepthRead(entry)) {
3074
+ const paramsBufferResult = internals.device.createBuffer({
3075
+ label: `post-process-params-${id}`,
3076
+ size: DEPTH_MIN_PARAMS_BYTE_SIZE,
3077
+ usage: GPU_BUFFER_USAGE_UNIFORM | GPU_BUFFER_USAGE_COPY_DST,
3078
+ mappedAtCreation: false,
3079
+ });
3080
+ if (!paramsBufferResult.ok) throw paramsBufferResult.error;
3081
+ paramsBuffer = paramsBufferResult.value;
3082
+ }
3083
+ postProcessRegistry.set(id, entry);
3084
+ if (paramsBuffer !== undefined) postProcessParamsBuffers.set(id, paramsBuffer);
3085
+ } catch (cause) {
3086
+ if (paramsBuffer !== undefined) internals.device.destroyBuffer(paramsBuffer);
3087
+ throw cause;
3088
+ }
3089
+ return () => {
3090
+ if (postProcessRegistry.get(id) !== entry) return;
3091
+ postProcessRegistry.delete(id);
3092
+ const paramsBuffer = postProcessParamsBuffers.get(id);
3093
+ if (paramsBuffer !== undefined) {
3094
+ internals.device.destroyBuffer(paramsBuffer);
3095
+ postProcessParamsBuffers.delete(id);
3096
+ }
3097
+ for (const key of postProcessPipelineCache.keys()) {
3098
+ if (key.startsWith(`${id}|`)) postProcessPipelineCache.delete(key);
3099
+ }
3100
+ };
3101
+ },
3102
+ },
3103
+ disposeFrameState(): void {
3104
+ const environmentHandles = [
3105
+ frameState.environmentGeneration.active?.handle,
3106
+ frameState.environmentGeneration.candidate?.handle,
3107
+ ];
3108
+ disposeEnvironmentGeneration(frameState.environmentGeneration);
3109
+ for (const handle of environmentHandles) {
3110
+ if (isEnvironmentGpuBundle(handle)) handle.destroy(internals.device);
3111
+ }
3112
+ temporalFrameTransaction.dispose();
3113
+ persistentRenderScene.dispose();
3114
+ gpuDrivenProduction.dispose();
3115
+ disposeFeatureGpuWork();
3116
+ // Retire graph-owned resources and dispose instance-buffer caches.
3117
+ // Both calls are idempotent + tolerate per-handle errors silently;
3118
+ // the Renderer.dispose() cascade owns the surrounding try/catch
3119
+ // (D-3 method A: void signature, sub-errors fan out via
3120
+ // errorRegistry.fire at the cascade layer, dispose still walks all
3121
+ // 6 steps).
3122
+ frameState.directionalShadowCache = null;
3123
+ frameState.directionalShadowCacheRecorded = false;
3124
+ frameState.pendingShadowCommandBuffers = [];
3125
+ frameState.shadowSubmitModeState = createShadowSubmitModeState();
3126
+ frameState.currentFrameObservationSource = undefined;
3127
+ frameState.currentDirectionalShadowView = null;
3128
+ frameState.currentSpotShadowView = null;
3129
+ const compiled = frameState.compiledFrameGraph;
3130
+ frameState.compiledFrameGraph = null;
3131
+ frameState.compiledFrameGraphTopologyKey = null;
3132
+ if (compiled !== null) taaHistoryStore.retireGraph(compiled).catch(() => undefined);
3133
+ for (const retired of frameState.retiredCompiledFrameGraphs) {
3134
+ taaHistoryStore.retireGraph(retired).catch(() => undefined);
3135
+ }
3136
+ frameState.retiredCompiledFrameGraphs.clear();
3137
+ // feat-20260619 M4 (D-6): pass errorRegistry to disposeInstanceBuffers
3138
+ // so destroy failures fire structured errors (unified per-frame +
3139
+ // dispose error strategy).
3140
+ disposeInstanceBuffers(frameState.instanceBuffers, internals.errorRegistry);
3141
+ disposeTransientInstanceBuffers(frameState.transientInstanceBuffers, internals.errorRegistry);
3142
+ // feat-20260612-point-light-shadows-urp-hdrp M4 / T-M4-2: dispose the
3143
+ // cube_array shadow atlas owned by the RenderSystem closure. The atlas
3144
+ // is per-RenderSystem (= per Renderer) and is shared transparently
3145
+ // between URP and HDRP pipelines.
3146
+ // Idempotent: dispose() on a null / already-disposed atlas is a no-op.
3147
+ if (frameState.pointShadowAtlas !== null) {
3148
+ frameState.pointShadowAtlas.dispose();
3149
+ frameState.pointShadowAtlas = null;
3150
+ }
3151
+ const taaParams = internals.getPipelineState()?.perPassResources.taaResolveParamsBuffer;
3152
+ if (taaParams !== null && taaParams !== undefined) {
3153
+ internals.device.destroyBuffer(taaParams);
3154
+ const pipelineState = internals.getPipelineState();
3155
+ if (pipelineState !== null) pipelineState.perPassResources.taaResolveParamsBuffer = null;
3156
+ }
3157
+ },
3158
+ resetForRecover(): void {
3159
+ abandonEnvironmentDevice(
3160
+ frameState.environmentGeneration,
3161
+ frameState.environmentGeneration.deviceGeneration,
3162
+ );
3163
+ temporalFrameTransaction.resetForRecover();
3164
+ const pipelineState = internals.getPipelineState();
3165
+ if (pipelineState !== null) pipelineState.perPassResources.taaResolveParamsBuffer = null;
3166
+ persistentRenderScene.resetGpuForRecover();
3167
+ gpuDrivenProduction.dispose();
3168
+ disposeFeatureGpuWork();
3169
+ // feat-20260622-s5 M3 / B-2 / w18: recover() rebuild drops device-bound
3170
+ // state minted by the lost device. The active graph and per-entity caches
3171
+ // must be discarded, not merely marked for destruction: their opaque
3172
+ // handles cannot be used on the fresh device and the next draw must
3173
+ // lazily build a new graph from the preserved ECS / asset POD caches.
3174
+ if (frameState.compiledFrameGraph !== null) {
3175
+ taaHistoryStore.retireGraph(frameState.compiledFrameGraph).catch(() => undefined);
3176
+ }
3177
+ frameState.compiledFrameGraph = null;
3178
+ frameState.compiledFrameGraphTopologyKey = null;
3179
+ frameState.directionalShadowCache = null;
3180
+ frameState.directionalShadowCacheRecorded = false;
3181
+ frameState.pendingShadowCommandBuffers = [];
3182
+ frameState.shadowSubmitModeState = createShadowSubmitModeState();
3183
+ frameState.currentFrameObservationSource = undefined;
3184
+ frameState.currentDirectionalShadowView = null;
3185
+ frameState.currentSpotShadowView = null;
3186
+ for (const retired of frameState.retiredCompiledFrameGraphs) {
3187
+ taaHistoryStore.retireGraph(retired).catch(() => undefined);
3188
+ }
3189
+ frameState.retiredCompiledFrameGraphs.clear();
3190
+ frameState.instanceBuffers.clear();
3191
+ frameState.transientInstanceBuffers = [];
3192
+ frameState.pointShadowAtlas = null;
3193
+ // Bind groups retain opaque handles from the lost device. WeakMap roots
3194
+ // cannot be cleared, so replace them; the Map-backed caches can be
3195
+ // emptied in place. The next frame recreates every binding from the
3196
+ // rebuilt PipelineState and fresh residency handles.
3197
+ frameState.viewBindGroupCache = new WeakMap();
3198
+ frameState.meshBindGroupCache = new WeakMap();
3199
+ frameState.materialBgPerEntity.clear();
3200
+ frameState.instancesBgPerEntity.clear();
3201
+ frameState.materialBgShared.clear();
3202
+ frameState.materialBgAssemblyCache.clear();
3203
+ frameState.singletonMaterialCache.clear();
3204
+ frameState.postProcessBgCache = new WeakMap();
3205
+ // Post-process PSOs are cached outside frameState because the normal
3206
+ // path reuses them across frames. They still carry opaque handles from
3207
+ // the lost device, so recovery must invalidate this cache alongside the
3208
+ // post-process registry/UBOs below.
3209
+ postProcessPipelineCache.clear();
3210
+ // Logical declarations stay live so unregister remains authoritative
3211
+ // while a replacement device is being requested.
3212
+ postProcessParamsBuffers.clear();
3213
+ resetRenderFeatureGraphState(internals);
3214
+ },
3215
+ restoreGpuDrivenForRecover(): void {
3216
+ // resetForRecover() runs before Renderer.recover() acquires the
3217
+ // replacement device. Rebinding here is deliberately a separate phase;
3218
+ // constructing GpuDrivenProduction during reset would capture the lost
3219
+ // device and make the first eligible post-recovery frame submit stale
3220
+ // buffers/pipelines.
3221
+ gpuDrivenProduction = new GpuDrivenProduction(internals.device, gpuDrivenShaderFactory);
3222
+ },
3223
+ restorePostProcessResources(): void {
3224
+ for (const [id, entry] of postProcessRegistry) {
3225
+ let buffer: Buffer | undefined;
3226
+ if (entry.params !== undefined) {
3227
+ const created = internals.device.createBuffer({
3228
+ label: `post-process-params-${id}`,
3229
+ size: entry.params.byteSize,
3230
+ usage: GPU_BUFFER_USAGE_UNIFORM | GPU_BUFFER_USAGE_COPY_DST,
3231
+ mappedAtCreation: false,
3232
+ });
3233
+ if (!created.ok) throw created.error;
3234
+ buffer = created.value;
3235
+ const written = internals.device.queue.writeBuffer(buffer, 0, entry.params.defaultValue);
3236
+ if (!written.ok) {
3237
+ internals.device.destroyBuffer(buffer);
3238
+ throw written.error;
3239
+ }
3240
+ } else if (entryHasDepthRead(entry)) {
3241
+ const created = internals.device.createBuffer({
3242
+ label: `post-process-params-${id}`,
3243
+ size: DEPTH_MIN_PARAMS_BYTE_SIZE,
3244
+ usage: GPU_BUFFER_USAGE_UNIFORM | GPU_BUFFER_USAGE_COPY_DST,
3245
+ mappedAtCreation: false,
3246
+ });
3247
+ if (!created.ok) throw created.error;
3248
+ buffer = created.value;
3249
+ }
3250
+ if (buffer !== undefined && postProcessRegistry.get(id) === entry) {
3251
+ postProcessParamsBuffers.set(id, buffer);
3252
+ } else if (buffer !== undefined) {
3253
+ internals.device.destroyBuffer(buffer);
3254
+ }
3255
+ }
3256
+ },
3257
+ };
3258
+ }