@forgeax/engine-render 0.1.34 → 0.1.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +69 -3
- package/dist/assembly/device-feature-admission.d.ts +2 -2
- package/dist/assembly/host-contract.d.ts +3 -2
- package/dist/assembly/host-contract.d.ts.map +1 -1
- package/dist/assembly/recovery/renderer-recover.d.ts.map +1 -1
- package/dist/assembly/render-target-host.d.ts +5 -0
- package/dist/assembly/render-target-host.d.ts.map +1 -1
- package/dist/assembly/renderer-facade.d.ts.map +1 -1
- package/dist/assembly/webgpu-renderer.d.ts +1 -0
- package/dist/assembly/webgpu-renderer.d.ts.map +1 -1
- package/dist/assembly/webgpu-vertex-layouts.d.ts.map +1 -1
- package/dist/authoring.mjs +2 -4
- package/dist/authoring.mjs.map +1 -1
- package/dist/chunk-2OZAS3WU.mjs +3489 -0
- package/dist/chunk-2OZAS3WU.mjs.map +1 -0
- package/dist/{chunk-UI5SFODX.mjs → chunk-BZQ4CDRF.mjs} +2338 -1991
- package/dist/chunk-BZQ4CDRF.mjs.map +1 -0
- package/dist/{chunk-MKDIT2EM.mjs → chunk-CJOV2XLO.mjs} +216 -261
- package/dist/chunk-CJOV2XLO.mjs.map +1 -0
- package/dist/chunk-D6WSBXJ2.mjs +1842 -0
- package/dist/chunk-D6WSBXJ2.mjs.map +1 -0
- package/dist/{chunk-HEB564WF.mjs → chunk-DRF6OULX.mjs} +4 -4
- package/dist/{chunk-HEB564WF.mjs.map → chunk-DRF6OULX.mjs.map} +1 -1
- package/dist/{chunk-OCDLEI6I.mjs → chunk-OB5WAFYH.mjs} +117 -5
- package/dist/chunk-OB5WAFYH.mjs.map +1 -0
- package/dist/{chunk-ODZWR6JQ.mjs → chunk-OEYKKMXG.mjs} +2042 -27
- package/dist/chunk-OEYKKMXG.mjs.map +1 -0
- package/dist/chunk-RIPAEGI6.mjs +48 -0
- package/dist/chunk-RIPAEGI6.mjs.map +1 -0
- package/dist/{chunk-ELJFJ2BU.mjs → chunk-X2KA6WHM.mjs} +29 -4
- package/dist/chunk-X2KA6WHM.mjs.map +1 -0
- package/dist/{chunk-BLXGONR2.mjs → chunk-XSFB7XXQ.mjs} +51 -4
- package/dist/chunk-XSFB7XXQ.mjs.map +1 -0
- package/dist/cloud/frame-context.d.ts +2 -2
- package/dist/cloud/frame-context.d.ts.map +1 -1
- package/dist/construct-renderer.mjs +936 -2140
- package/dist/construct-renderer.mjs.map +1 -1
- package/dist/device/device-scope.d.ts.map +1 -1
- package/dist/device/gpu-residency.d.ts +19 -19
- package/dist/device/gpu-residency.d.ts.map +1 -1
- package/dist/errors/render.d.ts +3 -2
- package/dist/errors/render.d.ts.map +1 -1
- package/dist/extract/material-context.d.ts +7 -0
- package/dist/extract/material-context.d.ts.map +1 -0
- package/dist/features/host.d.ts +5 -0
- package/dist/features/host.d.ts.map +1 -1
- package/dist/features/particle-mesh-layout.d.ts +19 -0
- package/dist/features/particle-mesh-layout.d.ts.map +1 -0
- package/dist/features/plan.d.ts +2 -0
- package/dist/features/plan.d.ts.map +1 -1
- package/dist/features/types.d.ts +8 -0
- package/dist/features/types.d.ts.map +1 -1
- package/dist/glyph-text-layout-system.d.ts +1 -1
- package/dist/glyph-text-layout-system.d.ts.map +1 -1
- package/dist/gpu-driven/production-raster.d.ts +1 -1
- package/dist/gpu-driven/production-raster.d.ts.map +1 -1
- package/dist/gpu-driven/shadow-ownership.d.ts +3 -3
- package/dist/gpu-driven/shadow-ownership.d.ts.map +1 -1
- package/dist/gpu-driven/shadow-views.d.ts +1 -1
- package/dist/gpu-driven/shadow-views.d.ts.map +1 -1
- package/dist/gpu-driven/view-gpu.d.ts +1 -1
- package/dist/gpu-driven/view-gpu.d.ts.map +1 -1
- package/dist/ibl/frame-resources.d.ts.map +1 -1
- package/dist/ibl/skylight-bind-group.d.ts +4 -4
- package/dist/ibl/skylight-bind-group.d.ts.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +542 -9
- package/dist/index.mjs.map +1 -1
- package/dist/instances.d.ts +3 -4
- package/dist/instances.d.ts.map +1 -1
- package/dist/internal.mjs +7 -8
- package/dist/internal.mjs.map +1 -1
- package/dist/pbr-pipeline.d.ts +3 -3
- package/dist/pbr-pipeline.d.ts.map +1 -1
- package/dist/pipeline/standard-output/lut-gpu.d.ts +2 -2
- package/dist/pipeline/standard-output/lut-gpu.d.ts.map +1 -1
- package/dist/pipeline/standard-output/resources.d.ts +2 -2
- package/dist/pipeline/standard-output/resources.d.ts.map +1 -1
- package/dist/publication/contract.d.ts +77 -0
- package/dist/publication/contract.d.ts.map +1 -0
- package/dist/publication/dependencies.d.ts +7 -0
- package/dist/publication/dependencies.d.ts.map +1 -0
- package/dist/publication/prepare-geometry.d.ts +9 -0
- package/dist/publication/prepare-geometry.d.ts.map +1 -0
- package/dist/publication/programs.d.ts +5 -0
- package/dist/publication/programs.d.ts.map +1 -0
- package/dist/publication/publisher.d.ts +34 -0
- package/dist/publication/publisher.d.ts.map +1 -0
- package/dist/publication/receiver.d.ts +29 -0
- package/dist/publication/receiver.d.ts.map +1 -0
- package/dist/publication/resource-scope.d.ts +18 -0
- package/dist/publication/resource-scope.d.ts.map +1 -0
- package/dist/publication/targets.d.ts +33 -0
- package/dist/publication/targets.d.ts.map +1 -0
- package/dist/publication/video.d.ts +5 -0
- package/dist/publication/video.d.ts.map +1 -0
- package/dist/record/fold-buckets.d.ts +3 -3
- package/dist/record/fold-buckets.d.ts.map +1 -1
- package/dist/record/frame-snapshot.d.ts +6 -6
- package/dist/record/frame-snapshot.d.ts.map +1 -1
- package/dist/record/frame.d.ts +5 -4
- package/dist/record/frame.d.ts.map +1 -1
- package/dist/record/helpers.d.ts +2 -2
- package/dist/record/helpers.d.ts.map +1 -1
- package/dist/record/main-pass-geometry.d.ts +2 -2
- package/dist/record/main-pass-geometry.d.ts.map +1 -1
- package/dist/record/main-pass-material.d.ts +7 -9
- package/dist/record/main-pass-material.d.ts.map +1 -1
- package/dist/record/main-pass-sprite-draws.d.ts +3 -16
- package/dist/record/main-pass-sprite-draws.d.ts.map +1 -1
- package/dist/record/main-pass.d.ts.map +1 -1
- package/dist/record/prepared-material-bindings.d.ts +2 -3
- package/dist/record/prepared-material-bindings.d.ts.map +1 -1
- package/dist/record/render-context.d.ts +4 -2
- package/dist/record/render-context.d.ts.map +1 -1
- package/dist/record/shadow-pass.d.ts +2 -2
- package/dist/record/shadow-pass.d.ts.map +1 -1
- package/dist/record/sprite-instance-buffer.d.ts +31 -0
- package/dist/record/sprite-instance-buffer.d.ts.map +1 -0
- package/dist/record/target-capture-graph.d.ts +19 -0
- package/dist/record/target-capture-graph.d.ts.map +1 -0
- package/dist/record/typed-frame-graph.d.ts +2 -13
- package/dist/record/typed-frame-graph.d.ts.map +1 -1
- package/dist/record/view-ubo.d.ts.map +1 -1
- package/dist/record/volume-params.d.ts +2 -2
- package/dist/record/volume-params.d.ts.map +1 -1
- package/dist/recovery/render-system-candidate.d.ts +5 -12
- package/dist/recovery/render-system-candidate.d.ts.map +1 -1
- package/dist/render-contract.d.ts +4 -1
- package/dist/render-contract.d.ts.map +1 -1
- package/dist/render-system-extract-tail.d.ts.map +1 -1
- package/dist/render-system-extract.d.ts +2 -0
- package/dist/render-system-extract.d.ts.map +1 -1
- package/dist/render-system-presentation.d.ts +2 -2
- package/dist/render-system-presentation.d.ts.map +1 -1
- package/dist/render-system-projections.d.ts +3 -2
- package/dist/render-system-projections.d.ts.map +1 -1
- package/dist/render-system-residency.d.ts +2 -2
- package/dist/render-system-residency.d.ts.map +1 -1
- package/dist/render-system.d.ts +3 -7
- package/dist/render-system.d.ts.map +1 -1
- package/dist/scene/render-scene.d.ts +8 -4
- package/dist/scene/render-scene.d.ts.map +1 -1
- package/dist/scene/render-source.d.ts +42 -0
- package/dist/scene/render-source.d.ts.map +1 -0
- package/dist/scene/source-systems.d.ts +6 -0
- package/dist/scene/source-systems.d.ts.map +1 -0
- package/dist/systems/skin-palette-allocator.d.ts.map +1 -1
- package/dist/systems/skin-palette-types.d.ts +10 -0
- package/dist/systems/skin-palette-types.d.ts.map +1 -1
- package/dist/systems/transparent-dispatch.d.ts +2 -2
- package/dist/systems/transparent-dispatch.d.ts.map +1 -1
- package/dist/systems/transparent-sort-config.d.ts +2 -1
- package/dist/systems/transparent-sort-config.d.ts.map +1 -1
- package/dist/temporal/index.mjs +6 -7
- package/dist/typed-shadow-passes.d.ts.map +1 -1
- package/package.json +21 -21
- package/src/__tests__/auto-exposure-transaction.integration.test.ts +4 -9
- package/src/__tests__/device-feature-admission.unit.test.ts +3 -2
- package/src/__tests__/device-scope-lifecycle.unit.test.ts +26 -0
- package/src/__tests__/gpu-driven-pbr.dawn.test.ts +3 -4
- package/src/__tests__/gpu-driven-production.integration.test.ts +18 -1
- package/src/__tests__/gpu-driven-shadow-views.unit.test.ts +23 -0
- package/src/__tests__/ktx2-basis-gpu-consumer.dawn.test.ts +4 -1
- package/src/__tests__/main-pass-material-medium-selection.unit.test.ts +0 -1
- package/src/__tests__/material-vertex-texture.browser.test.ts +7 -0
- package/src/__tests__/material-vertex-texture.dawn.test.ts +7 -0
- package/src/__tests__/material-vertex-texture.fixture.ts +31 -0
- package/src/__tests__/materials-standard-contract.unit.test.ts +0 -1
- package/src/__tests__/physical-clearcoat.integration.test.ts +23 -23
- package/src/__tests__/physical-material-budget.unit.test.ts +40 -0
- package/src/__tests__/recovery-candidate-prepare.contract.test.ts +5 -0
- package/src/__tests__/render-error-code-owner.test-d.ts +1 -0
- package/src/__tests__/renderer-factory-material-contract.unit.test.ts +107 -5
- package/src/__tests__/runtime-material-program.integration.test.ts +79 -0
- package/src/__tests__/vertex-layouts-ssot.unit.test.ts +23 -3
- package/src/assembly/device-feature-admission.ts +2 -2
- package/src/assembly/host-contract.ts +5 -2
- package/src/assembly/recovery/renderer-recover.ts +9 -0
- package/src/assembly/render-target-host.ts +57 -47
- package/src/assembly/renderer-facade.ts +3 -1
- package/src/assembly/webgpu-ready.ts +1 -1
- package/src/assembly/webgpu-renderer.ts +101 -70
- package/src/assembly/webgpu-vertex-layouts.ts +2 -9
- package/src/cloud/frame-context.ts +2 -2
- package/src/device/device-scope.ts +3 -0
- package/src/device/gpu-residency.ts +26 -25
- package/src/errors/render.ts +3 -1
- package/src/extract/material-context.ts +21 -0
- package/src/features/host.ts +13 -5
- package/src/features/particle-mesh-layout.ts +25 -0
- package/src/features/plan.ts +2 -0
- package/src/features/types.ts +8 -0
- package/src/glyph-text-layout-system.ts +2 -2
- package/src/gpu-driven/production-raster.ts +9 -3
- package/src/gpu-driven/shadow-ownership.ts +3 -3
- package/src/gpu-driven/shadow-views.ts +27 -2
- package/src/gpu-driven/view-gpu.ts +5 -0
- package/src/ibl/frame-resources.ts +0 -1
- package/src/ibl/skylight-bind-group.ts +13 -25
- package/src/index.ts +9 -0
- package/src/instances.ts +9 -6
- package/src/pbr-pipeline.ts +15 -18
- package/src/pipeline/standard-output/lut-gpu.ts +3 -3
- package/src/pipeline/standard-output/resources.ts +2 -2
- package/src/publication/__tests__/derived-geometry.integration.test.ts +177 -0
- package/src/publication/__tests__/features.integration.test.ts +173 -0
- package/src/publication/__tests__/programs.unit.test.ts +25 -0
- package/src/publication/__tests__/publication.integration.test.ts +415 -0
- package/src/publication/__tests__/targets.integration.test.ts +120 -0
- package/src/publication/__tests__/video.browser.test.ts +50 -0
- package/src/publication/contract.ts +104 -0
- package/src/publication/dependencies.ts +54 -0
- package/src/publication/prepare-geometry.ts +94 -0
- package/src/publication/programs.ts +45 -0
- package/src/publication/publisher.ts +645 -0
- package/src/publication/receiver.ts +297 -0
- package/src/publication/resource-scope.ts +31 -0
- package/src/publication/targets.ts +182 -0
- package/src/publication/video.ts +33 -0
- package/src/record/__tests__/material-bg-cache.unit.test.ts +15 -1
- package/src/record/__tests__/prepared-runtime-material.integration.test.ts +134 -0
- package/src/record/__tests__/sprite-material-abi.unit.test.ts +8 -10
- package/src/record/__tests__/video-texture-view.unit.test.ts +9 -9
- package/src/record/fold-buckets.ts +8 -5
- package/src/record/frame-snapshot.ts +6 -6
- package/src/record/frame.ts +87 -28
- package/src/record/helpers.ts +2 -2
- package/src/record/main-pass-geometry.ts +21 -2
- package/src/record/main-pass-material.ts +37 -33
- package/src/record/main-pass-sprite-draws.ts +6 -152
- package/src/record/main-pass.ts +8 -7
- package/src/record/prepared-material-bindings.ts +16 -37
- package/src/record/render-context.ts +4 -2
- package/src/record/shadow-pass.ts +65 -7
- package/src/record/sprite-instance-buffer.ts +155 -0
- package/src/record/target-capture-graph.ts +258 -0
- package/src/record/typed-frame-graph.ts +11 -207
- package/src/record/view-ubo.ts +1 -1
- package/src/record/volume-params.ts +6 -6
- package/src/recovery/render-system-candidate.ts +10 -18
- package/src/render-contract.ts +6 -1
- package/src/render-system-extract-tail.ts +48 -23
- package/src/render-system-extract.ts +11 -2
- package/src/render-system-presentation.ts +2 -2
- package/src/render-system-projections.ts +3 -2
- package/src/render-system-residency.ts +2 -2
- package/src/render-system.ts +82 -54
- package/src/scene/render-scene.ts +110 -100
- package/src/scene/render-source.ts +90 -0
- package/src/scene/source-systems.ts +33 -0
- package/src/systems/skin-palette-allocator.ts +1 -0
- package/src/systems/skin-palette-types.ts +11 -0
- package/src/systems/transparent-dispatch.ts +2 -2
- package/src/systems/transparent-sort-config.ts +3 -1
- package/src/typed-shadow-passes.ts +36 -5
- package/dist/chunk-BLXGONR2.mjs.map +0 -1
- package/dist/chunk-ELJFJ2BU.mjs.map +0 -1
- package/dist/chunk-ILQ5MEZF.mjs +0 -32
- package/dist/chunk-ILQ5MEZF.mjs.map +0 -1
- package/dist/chunk-MKDIT2EM.mjs.map +0 -1
- package/dist/chunk-OCDLEI6I.mjs.map +0 -1
- package/dist/chunk-ODZWR6JQ.mjs.map +0 -1
- package/dist/chunk-RXZ3RGOU.mjs +0 -53
- package/dist/chunk-RXZ3RGOU.mjs.map +0 -1
- package/dist/chunk-SHFUFJ5N.mjs +0 -1781
- package/dist/chunk-SHFUFJ5N.mjs.map +0 -1
- package/dist/chunk-UI5SFODX.mjs.map +0 -1
- package/dist/chunk-UINHLCZA.mjs +0 -2389
- package/dist/chunk-UINHLCZA.mjs.map +0 -1
- package/dist/chunk-WEX45HKH.mjs +0 -1524
- package/dist/chunk-WEX45HKH.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/features/barrel-distortion.ts","../src/cloud/density.ts","../src/cloud/inspection.ts","../src/cloud/resources.ts","../src/cloud/optics.ts","../src/cloud/shadow.ts","../src/cloud/temporal.ts","../src/cloud/feature.ts","../src/surface/gpu-driven.ts","../src/points-lines/admission.ts","../src/point-shadow-inspection.ts","../src/ssr/admission.ts","../src/volume/inspection.ts","../src/surface/dynamic-input.ts","../src/reflection/filter.ts","../src/reflection/gpu-table.ts","../src/reflection/inspection.ts","../src/reflection/projection.ts","../src/scene/visibility/inspection.ts","../src/ssr/inspection.ts","../src/dynamic-geometry.ts"],"names":["wrapped","ok","x0","y0","z0","x1","y1","z1","fx","fy","fz","smoothstep","normalize","err","pass","failure","resourceStage","ERROR_POLICY","primitiveKey","invalid"],"mappings":";;;;;AACO,IAAM,iCAAA,GAAoC;AAC1C,IAAM,kCAAA,GAAqC;AAa3C,IAAM,iCAAA;AAAA;AAAA,EAA+C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoCrD,IAAM,sBAAA;AAAA;AAAA,EAAoC,GAAG,iCAAiC;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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A,EAAS,UAAA,KAAe,SAAA,CAAU,UAAA,GAAa,OAAA,GAAU,MAAA;AAAA,IAClE,CAAA;AAAA,IACA,OAAA,GAAU;AACR,MAAA,IAAI,QAAA,GAAW,CAAA;AACf,MAAA,IAAI,QAAA,GAAW,CAAA;AACf,MAAA,IAAI,SAAA,GAAY,CAAA;AAChB,MAAA,KAAA,MAAW,MAAA,IAAU,OAAA,CAAQ,MAAA,EAAO,EAAG;AACrC,QAAA,IAAI,MAAA,CAAO,SAAA,CAAU,KAAA,KAAU,UAAA,EAAY,QAAA,IAAY,CAAA;AAAA,aAAA,IAC9C,MAAA,CAAO,SAAA,CAAU,KAAA,KAAU,UAAA,EAAY,QAAA,IAAY,CAAA;AAAA,aAAA,IACnD,MAAA,CAAO,SAAA,CAAU,KAAA,KAAU,WAAA,EAAa,SAAA,IAAa,CAAA;AAAA,MAChE;AACA,MAAA,OAAO,OAAO,MAAA,CAAO;AAAA,QACnB,UAAA,EAAY,iBAAA;AAAA,QACZ,QAAA;AAAA,QACA,QAAA;AAAA,QACA,SAAA;AAAA,QACA,OAAA;AAAA,QACA,GAAI,cAAA,KAAmB,MAAA,GAAY,EAAC,GAAI,EAAE,cAAA,EAAe;AAAA,QACzD,GAAI,aAAA,KAAkB,MAAA,GAAY,EAAC,GAAI,EAAE,aAAA,EAAc;AAAA,QACvD,oBAAA;AAAA,QACA,WAAA;AAAA,QACA,SAAA;AAAA,QACA;AAAA,OACD,CAAA;AAAA,IACH,CAAA;AAAA,IACA,OAAA,GAAU;AACR,MAAA,QAAA,GAAW,IAAA;AACX,MAAA,OAAA,CAAQ,KAAA,EAAM;AACd,MAAA,iBAAA,CAAkB,KAAA,EAAM;AACxB,MAAA,SAAA,GAAY,CAAA;AAAA,IACd;AAAA,GACF;AACF","file":"chunk-ODZWR6JQ.mjs","sourcesContent":["/** One graph-valid identity for the barrel stage, feature and shader prewarm. */\nexport const BARREL_DISTORTION_POST_PROCESS_ID = 'fullscreen.forgeax.barrel-distortion';\nexport const BARREL_DISTORTION_FEATURE_IDENTITY = BARREL_DISTORTION_POST_PROCESS_ID;\n\nimport { ok, type Result } from '@forgeax/engine-types';\nimport type { RenderError } from '../errors/render';\nimport type { RenderFeaturePlan } from './plan';\nimport type { RenderFeature, RenderFeatureExtractContext, RenderFeaturePlanContext } from './types';\n\n/**\n * The coordinate function is exported beside the production shader so a real\n * f32 device probe can compile exactly the same implementation. Keeping the\n * probe source here avoids a second test-only equation that could drift from\n * the Standard pass.\n */\nexport const BARREL_DISTORTION_WGSL_COORDINATE = /* wgsl */ `\nstruct BarrelDistortionParams {\n strength : f32,\n centerX : f32,\n centerY : f32,\n radiusSquared : f32,\n};\n\nfn barrel_distortion_display_to_scene_uv(\n inputUv : vec2<f32>,\n params : BarrelDistortionParams,\n dimensions : vec2<f32>,\n) -> vec2<f32> {\n let aspect = dimensions.x / max(dimensions.y, 1.0);\n let p = vec2<f32>(\n 2.0 * aspect * (inputUv.x - params.centerX),\n 2.0 * (inputUv.y - params.centerY),\n );\n let t = dot(p, p) / max(params.radiusSquared, 1e-6);\n let scale = (1.0 - params.strength) / (1.0 - params.strength * t);\n return clamp(\n vec2<f32>(\n params.centerX + (inputUv.x - params.centerX) * scale,\n params.centerY + (inputUv.y - params.centerY) * scale,\n ),\n vec2<f32>(0.0),\n vec2<f32>(1.0),\n );\n}\n`;\n\n/**\n * Manifest-equivalent WGSL for the bounded analytic model. The Standard\n * owner registers this source once and keeps the graph, encoder, and submit\n * lifecycle shared with every other fullscreen stage.\n */\nexport const BARREL_DISTORTION_WGSL = /* wgsl */ `${BARREL_DISTORTION_WGSL_COORDINATE}\nstruct FullscreenOutput {\n @builtin(position) position : vec4<f32>,\n @location(0) uv : vec2<f32>,\n};\n\nfn fullscreen_triangle(vertex_index : u32) -> FullscreenOutput {\n var x : f32 = -1.0;\n var y : f32 = -1.0;\n if (vertex_index == 1u) { x = 3.0; }\n if (vertex_index == 2u) { y = 3.0; }\n let u : f32 = (x + 1.0) * 0.5;\n let v : f32 = 1.0 - (y + 1.0) * 0.5;\n var out : FullscreenOutput;\n out.position = vec4<f32>(x, y, 0.0, 1.0);\n out.uv = vec2<f32>(u, v);\n return out;\n}\n\n@group(1) @binding(0) var sceneColor : texture_2d<f32>;\n@group(1) @binding(1) var sceneSampler : sampler;\n\n@group(1) @binding(2) var<uniform> params : BarrelDistortionParams;\n\n@vertex\nfn vs_main(@builtin(vertex_index) vertex_index : u32) -> FullscreenOutput {\n return fullscreen_triangle(vertex_index);\n}\n\n@fragment\nfn fs_main(input : FullscreenOutput) -> @location(0) vec4<f32> {\n let dimensions = vec2<f32>(textureDimensions(sceneColor));\n let sampleUv = barrel_distortion_display_to_scene_uv(input.uv, params, dimensions);\n return textureSampleLevel(sceneColor, sceneSampler, sampleUv, 0.0);\n}\n`;\n\n/**\n * Ordinary feature registration for the Standard linear-LDR stage.\n * Standard still allocates the stage targets and chooses its position in the\n * post chain; this feature owns the executable fullscreen declaration that is\n * projected into that slot by the existing graph/encoder/submit path.\n */\nexport interface BarrelDistortionFeatureFrame {\n /** True only when the extracted camera requires a spatial warp this frame. */\n readonly active: boolean;\n}\n\nexport function createBarrelDistortionRenderFeature(): RenderFeature<BarrelDistortionFeatureFrame> {\n return Object.freeze({\n identity: BARREL_DISTORTION_FEATURE_IDENTITY,\n requiredCapabilities: ['rgba16floatRenderable'] as const,\n requiredFullscreenPostProcesses: [\n { identity: BARREL_DISTORTION_POST_PROCESS_ID, source: BARREL_DISTORTION_WGSL },\n ],\n extract: (\n context: RenderFeatureExtractContext,\n ): Result<BarrelDistortionFeatureFrame, RenderError> =>\n ok({ active: (context.selectedCamera?.barrelDistortion?.strength ?? 0) > 0 }),\n plan: (\n data: BarrelDistortionFeatureFrame,\n _context: RenderFeaturePlanContext,\n ): Result<RenderFeaturePlan, RenderError> =>\n ok({\n resources: data.active\n ? [\n {\n kind: 'fullscreen-program' as const,\n name: BARREL_DISTORTION_POST_PROCESS_ID,\n source: BARREL_DISTORTION_WGSL,\n reads: ['ldrColor'],\n params: { byteSize: 16, defaultValue: new Uint8Array(16) },\n },\n {\n kind: 'graphics-program' as const,\n name: 'barrel-distortion-pipeline',\n program: {\n shader: BARREL_DISTORTION_POST_PROCESS_ID,\n vertexLayout: 'none',\n colorFormats: ['rgba16float'],\n sampleCount: 1,\n },\n },\n {\n kind: 'graphics-bindings' as const,\n name: 'barrel-distortion-bindings',\n program: 'barrel-distortion-pipeline',\n values: {\n group: 1,\n fullscreen: true,\n shader: BARREL_DISTORTION_POST_PROCESS_ID,\n input: 'barrel-input',\n },\n logicalTargets: { input: 'barrel-input' },\n },\n ]\n : [],\n passes: data.active\n ? [\n {\n kind: 'raster' as const,\n name: 'barrel-distortion',\n colorAttachments: [\n { target: 'barrel-output', loadOp: 'clear' as const, storeOp: 'store' as const },\n ],\n sampledTargets: ['barrel-input'],\n draws: [\n {\n program: 'barrel-distortion-pipeline',\n bindings: ['barrel-distortion-bindings'],\n vertexData: [],\n vertexLayout: 'none' as const,\n draw: { kind: 'draw' as const, vertexCount: 3, instanceCount: 1 },\n },\n ],\n },\n ]\n : [],\n }),\n });\n}\n","import { err, ok, type Result } from '@forgeax/engine-types';\nimport { CloudLayerCacheInvalidError, type CloudLayerError } from '../errors/cloud';\nimport {\n CLOUD_QUALITY_PROFILES,\n type CloudQualityProfile,\n cloudLayerFormationKey,\n type ValidatedCloudLayer,\n} from './parameters';\n\nexport interface CloudDensityCache {\n readonly sourceKey: string;\n readonly resolution: number;\n /** R8 normalized density values in z-major, y, x order. */\n readonly data: Uint8Array;\n /**\n * Weather, body and erosion bases in three contiguous R8 planes. `data` is\n * retained as a diagnostic projection for callers that still need the\n * composed density; runtime sampling uses these formation planes so coverage,\n * density and wind remain evaluation controls.\n */\n readonly formationData: Uint8Array;\n readonly formationByteLength: number;\n /** Bytes uploaded for the reusable formation planes. */\n readonly byteLength: number;\n readonly digest: string;\n}\n\nexport interface CloudDensityCacheSnapshot {\n readonly sourceKey: string;\n readonly resolution: number;\n readonly data: Uint8Array;\n readonly formationData?: Uint8Array;\n readonly digest: string;\n}\n\nexport interface CloudDensitySample {\n readonly density: number;\n readonly heightFraction: number;\n readonly noise: number;\n readonly weather?: number;\n readonly body?: number;\n readonly erosion?: number;\n}\n\nexport interface CloudFormationSample {\n readonly weather: number;\n readonly body: number;\n readonly erosion: number;\n readonly noise: number;\n}\n\n/**\n * The cache is one world-space period. Keep several lattice cells inside that\n * period so a street view sees separate cloud bodies instead of one broad\n * slab. The lattice wraps at the same boundary as the cache, which prevents\n * the old seam from turning into a repeated horizontal band.\n */\nconst CLOUD_SHAPE_CELLS = 4;\nconst CLOUD_WEATHER_CELLS = 2;\nconst CLOUD_DETAIL_CELLS = CLOUD_SHAPE_CELLS * 3;\n// One advective cache period contains four horizontal and two vertical body cells.\n// Integer periods on every axis make the formation continuous when wind wraps\n// through the cache boundary instead of introducing a seam at y = 0/1.\nexport const CLOUD_VERTICAL_CELLS = 1;\n// The cache keeps one advective period, while the formation itself gets two\n// smooth vertical lobes inside that period so the street view does not read as\n// a single sheet. Both are integer-period fields, so the cache seam remains\n// exact.\nconst CLOUD_VERTICAL_NOISE_CELLS = 2;\nconst CLOUD_DETAIL_VERTICAL_CELLS = 3;\n\nfunction saturate(value: number): number {\n return Math.min(1, Math.max(0, value));\n}\n\nfunction smoothstep(edge0: number, edge1: number, value: number): number {\n const t = saturate((value - edge0) / Math.max(1e-6, edge1 - edge0));\n return t * t * (3 - 2 * t);\n}\n\nfunction fract(value: number): number {\n return value - Math.floor(value);\n}\n\nfunction wrapInteger(value: number, period: number): number {\n const wrapped = value % period;\n return wrapped < 0 ? wrapped + period : wrapped;\n}\n\n/** Deterministic integer hash. Every octave uses the same seeded function. */\nfunction hash3(x: number, y: number, z: number, seed: number): number {\n let value = Math.imul(x | 0, 0x45d9f3b);\n value = Math.imul(value ^ Math.imul(y | 0, 0x119de1f3), 0x45d9f3b);\n value = Math.imul(value ^ Math.imul(z | 0, 0x3449f), 0x45d9f3b);\n value ^= seed | 0;\n value = Math.imul(value ^ (value >>> 16), 0x45d9f3b);\n value = Math.imul(value ^ (value >>> 13), 0x27d4eb2d);\n return ((value ^ (value >>> 16)) >>> 0) / 0x100000000;\n}\n\nfunction valueNoise(\n x: number,\n y: number,\n z: number,\n seed: number,\n periodX = 0,\n periodY = 0,\n periodZ = 0,\n): number {\n const ix = Math.floor(x);\n const iy = Math.floor(y);\n const iz = Math.floor(z);\n const fx = x - ix;\n const fy = y - iy;\n const fz = z - iz;\n const ux = fx * fx * (3 - 2 * fx);\n const uy = fy * fy * (3 - 2 * fy);\n const uz = fz * fz * (3 - 2 * fz);\n const lattice = (cellX: number, cellY: number, cellZ: number): number =>\n hash3(\n periodX > 0 ? wrapInteger(cellX, periodX) : cellX,\n periodY > 0 ? wrapInteger(cellY, periodY) : cellY,\n periodZ > 0 ? wrapInteger(cellZ, periodZ) : cellZ,\n seed,\n );\n const c000 = lattice(ix, iy, iz);\n const c100 = lattice(ix + 1, iy, iz);\n const c010 = lattice(ix, iy + 1, iz);\n const c110 = lattice(ix + 1, iy + 1, iz);\n const c001 = lattice(ix, iy, iz + 1);\n const c101 = lattice(ix + 1, iy, iz + 1);\n const c011 = lattice(ix, iy + 1, iz + 1);\n const c111 = lattice(ix + 1, iy + 1, iz + 1);\n const x00 = c000 + (c100 - c000) * ux;\n const x10 = c010 + (c110 - c010) * ux;\n const x01 = c001 + (c101 - c001) * ux;\n const x11 = c011 + (c111 - c011) * ux;\n return x00 + (x10 - x00) * uy + (x01 + (x11 - x01) * uy - (x00 + (x10 - x00) * uy)) * uz;\n}\n\n/** Bounded Worley-like cellular term used to erode the high frequency field. */\nfunction cellularNoise(\n x: number,\n y: number,\n z: number,\n seed: number,\n periodXZ = CLOUD_DETAIL_CELLS,\n periodY = 0,\n): number {\n const ix = Math.floor(x);\n const iy = Math.floor(y);\n const iz = Math.floor(z);\n const fx = x - ix;\n const fy = y - iy;\n const fz = z - iz;\n let nearest = Number.POSITIVE_INFINITY;\n for (let dz = -1; dz <= 1; dz += 1) {\n for (let dy = -1; dy <= 1; dy += 1) {\n for (let dx = -1; dx <= 1; dx += 1) {\n const random = hash3(\n wrapInteger(ix + dx, periodXZ),\n periodY > 0 ? wrapInteger(iy + dy, periodY) : iy + dy,\n wrapInteger(iz + dz, periodXZ),\n seed ^ 0x9e3779b9,\n );\n const px = dx + fract(random * 17.0) - fx;\n const py = dy + fract(random * 31.0) - fy;\n const pz = dz + fract(random * 47.0) - fz;\n nearest = Math.min(nearest, px * px + py * py + pz * pz);\n }\n }\n }\n return 1 - saturate(Math.sqrt(nearest) * 1.25);\n}\n\nfunction heightEnvelope(height: number, body: number, weather: number): number {\n // Let each body choose its own crown height. A fixed upper edge reads as a\n // horizontal slab from the street camera; tying the crown to the cached body\n // makes dense cells grow upward while sparse cells dissolve earlier.\n const lowerEdge = 0.05 + (1 - body) * 0.1;\n const crownEdge = Math.min(0.96, 0.6 + body * 0.3 + weather * 0.08);\n return (\n smoothstep(lowerEdge, Math.min(1, lowerEdge + 0.12), height) *\n (1 - smoothstep(crownEdge, Math.min(1, crownEdge + 0.14), height))\n );\n}\n\n/** Coverage shapes the macro body; detail removes material only at its boundary. */\nfunction composeCloudDensity(\n height: number,\n formation: CloudFormationSample,\n coverage: number,\n): number {\n const threshold = 1 - coverage * (0.45 + formation.weather * 0.55);\n const covered = smoothstep(0, 0.4, (formation.body - threshold) / Math.max(0.001, 1 - threshold));\n const shaped = covered * heightEnvelope(height, formation.body, formation.weather);\n const erosion = (1 - formation.erosion) * 0.18;\n return saturate((shaped - erosion) / (1 - erosion));\n}\n\nfunction formationField(\n x: number,\n y: number,\n z: number,\n seed: number,\n detailRepeat = 1,\n): CloudFormationSample {\n // A low-frequency height-aware warp breaks axis-aligned horizontal sheets\n // while keeping the cache periodic on every axis. The warp is evaluated once while\n // the reusable formation cache is built, so runtime ray steps pay no extra\n // noise cost.\n const macroWarpX =\n valueNoise(\n x * CLOUD_WEATHER_CELLS,\n y * CLOUD_VERTICAL_NOISE_CELLS + 3.0,\n z * CLOUD_WEATHER_CELLS,\n seed + 41023,\n CLOUD_WEATHER_CELLS,\n 2,\n CLOUD_WEATHER_CELLS,\n ) - 0.5;\n const macroWarpZ =\n valueNoise(\n x * CLOUD_WEATHER_CELLS + 5.0,\n y * CLOUD_VERTICAL_NOISE_CELLS - 7.0,\n z * CLOUD_WEATHER_CELLS,\n seed + 41023,\n CLOUD_WEATHER_CELLS,\n 2,\n CLOUD_WEATHER_CELLS,\n ) - 0.5;\n const bodyX = x + macroWarpX * 0.3;\n const bodyZ = z + macroWarpZ * 0.3;\n let amplitude = 0.5;\n let frequency = 1;\n let sum = 0;\n let weight = 0;\n for (let octave = 0; octave < 4; octave += 1) {\n const tilePeriod = CLOUD_SHAPE_CELLS * frequency;\n sum +=\n valueNoise(\n bodyX * tilePeriod,\n y * frequency * CLOUD_VERTICAL_NOISE_CELLS,\n bodyZ * tilePeriod,\n seed + octave * 1013,\n tilePeriod,\n frequency * CLOUD_VERTICAL_NOISE_CELLS,\n tilePeriod,\n ) * amplitude;\n weight += amplitude;\n amplitude *= 0.4;\n frequency *= 2;\n }\n // Perlin-Worley-style body remapping: the broad fBm controls the volume and\n // the cellular field only breaks its boundary. Keeping these values\n // separate is what lets a runtime coverage edit preserve the authored cloud\n // bodies instead of regenerating a final alpha volume.\n const broad = sum / weight;\n // Periodic Worley cells provide bounded breakup. The broad field remains\n // dominant so one cache period reads as a few connected formations instead\n // of a repeated grid of small spheres.\n const cells = cellularNoise(\n bodyX * CLOUD_SHAPE_CELLS,\n y * CLOUD_VERTICAL_NOISE_CELLS,\n bodyZ * CLOUD_SHAPE_CELLS,\n seed + 5011,\n CLOUD_SHAPE_CELLS,\n CLOUD_VERTICAL_NOISE_CELLS,\n );\n // Let the broad field carry the silhouette and use cellular noise as a\n // bounded breakup term. A broad-dominant mix keeps the same cache and ray\n // budget while yielding fewer, wider and less spherical cumulus masses.\n const body = saturate(broad * 0.85 + cells * 0.15 + 0.15);\n const weather = smoothstep(\n 0.34,\n 0.66,\n valueNoise(\n x * CLOUD_WEATHER_CELLS,\n 0.37,\n z * CLOUD_WEATHER_CELLS,\n seed + 17041,\n CLOUD_WEATHER_CELLS,\n 1,\n CLOUD_WEATHER_CELLS,\n ),\n );\n const detailX = x * detailRepeat;\n const detailY = y * detailRepeat;\n const detailZ = z * detailRepeat;\n const warpX =\n valueNoise(\n detailX * CLOUD_WEATHER_CELLS,\n detailY * 2 + 11.0,\n detailZ * CLOUD_WEATHER_CELLS,\n seed + 29011,\n CLOUD_WEATHER_CELLS,\n 2,\n CLOUD_WEATHER_CELLS,\n ) - 0.5;\n const warpZ =\n valueNoise(\n detailX * CLOUD_WEATHER_CELLS + 7.0,\n detailY * 2 - 5.0,\n detailZ * CLOUD_WEATHER_CELLS,\n seed + 29011,\n CLOUD_WEATHER_CELLS,\n 2,\n CLOUD_WEATHER_CELLS,\n ) - 0.5;\n const erosion = cellularNoise(\n (detailX + warpX * 0.22) * CLOUD_DETAIL_CELLS,\n detailY * CLOUD_DETAIL_VERTICAL_CELLS,\n (detailZ + warpZ * 0.22) * CLOUD_DETAIL_CELLS,\n seed + 7919,\n CLOUD_DETAIL_CELLS,\n CLOUD_DETAIL_VERTICAL_CELLS,\n );\n const noise = body;\n return { weather, body, erosion, noise };\n}\n\n/** Evaluate the reusable weather/body/erosion bases at one world position. */\nexport function evaluateCloudFormation(\n params: ValidatedCloudLayer,\n position: ArrayLike<number>,\n timeSeconds = 0,\n): CloudFormationSample {\n const windX = (params.wind[0] ?? 0) * timeSeconds;\n const windY = (params.wind[1] ?? 0) * timeSeconds;\n const windZ = (params.wind[2] ?? 0) * timeSeconds;\n const relativeHeight =\n ((position[1] ?? 0) - params.baseHeight) / Math.max(1e-6, params.thickness);\n const advectedHeight =\n relativeHeight + (windY * params.scale) / Math.max(1e-6, CLOUD_VERTICAL_CELLS);\n return formationField(\n ((position[0] ?? 0) + windX) * params.scale,\n fract(advectedHeight) * CLOUD_VERTICAL_CELLS,\n ((position[2] ?? 0) + windZ) * params.scale,\n params.seed,\n );\n}\n\n/** Analytic field used for cache generation, CPU diagnostics and recovery. */\nexport function evaluateCloudDensity(\n params: ValidatedCloudLayer,\n position: ArrayLike<number>,\n timeSeconds = 0,\n): CloudDensitySample {\n const relativeHeight =\n ((position[1] ?? 0) - params.baseHeight) / Math.max(1e-6, params.thickness);\n if (relativeHeight <= 0 || relativeHeight >= 1 || params.density <= 0 || params.coverage <= 0) {\n return { density: 0, heightFraction: saturate(relativeHeight), noise: 0 };\n }\n const windX = (params.wind[0] ?? 0) * timeSeconds;\n const windY = (params.wind[1] ?? 0) * timeSeconds;\n const windZ = (params.wind[2] ?? 0) * timeSeconds;\n const x = ((position[0] ?? 0) + windX) * params.scale;\n const advectedHeight =\n relativeHeight + (windY * params.scale) / Math.max(1e-6, CLOUD_VERTICAL_CELLS);\n const y = fract(advectedHeight) * CLOUD_VERTICAL_CELLS;\n const z = ((position[2] ?? 0) + windZ) * params.scale;\n const formation = formationField(x, y, z, params.seed, 3);\n const noise = formation.noise;\n return {\n density: composeCloudDensity(relativeHeight, formation, params.coverage) * params.density,\n heightFraction: relativeHeight,\n noise,\n weather: formation.weather,\n body: formation.body,\n erosion: formation.erosion,\n };\n}\n\nfunction cacheIndex(resolution: number, x: number, y: number, z: number): number {\n return z * resolution * resolution + y * resolution + x;\n}\n\nfunction digestBytes(data: Uint8Array): string {\n // FNV-1a is stable and intentionally cheap; this is an identity receipt,\n // not a cryptographic integrity boundary.\n let hash = 0x811c9dc5;\n for (const byte of data) {\n hash ^= byte;\n hash = Math.imul(hash, 0x01000193);\n }\n return (hash >>> 0).toString(16).padStart(8, '0');\n}\n\n/** Build one canonical, periodic formation cache. */\nexport function buildCloudDensityCache(\n params: ValidatedCloudLayer,\n profile: CloudQualityProfile = CLOUD_QUALITY_PROFILES[params.quality],\n): CloudDensityCache {\n const resolution = Math.max(4, Math.floor(profile.cacheResolution));\n const data = new Uint8Array(resolution * resolution * resolution);\n const formationData = new Uint8Array(data.byteLength * 3);\n const position = [0, 0, 0];\n for (let z = 0; z < resolution; z += 1) {\n for (let y = 0; y < resolution; y += 1) {\n position[1] = params.baseHeight + ((y + 0.5) / resolution) * params.thickness;\n for (let x = 0; x < resolution; x += 1) {\n // One cache period is one noise period in world space. This makes the\n // x/z addressing periodic and lets advection wrap without seams.\n position[0] = (x + 0.5) / resolution / params.scale;\n position[2] = (z + 0.5) / resolution / params.scale;\n const index = cacheIndex(resolution, x, y, z);\n const formation = evaluateCloudFormation(params, position, 0);\n formationData[index] = Math.round(saturate(formation.weather) * 255);\n formationData[data.byteLength + index] = Math.round(saturate(formation.body) * 255);\n formationData[data.byteLength * 2 + index] = Math.round(saturate(formation.erosion) * 255);\n }\n }\n }\n const cache: CloudDensityCache = {\n sourceKey: cloudLayerFormationKey(params),\n resolution,\n data,\n formationData,\n formationByteLength: formationData.byteLength,\n byteLength: formationData.byteLength,\n digest: digestBytes(formationData),\n };\n for (let z = 0; z < resolution; z++) {\n for (let y = 0; y < resolution; y++) {\n for (let x = 0; x < resolution; x++) {\n position[0] = (x + 0.5) / resolution / params.scale;\n position[1] = params.baseHeight + ((y + 0.5) / resolution) * params.thickness;\n position[2] = (z + 0.5) / resolution / params.scale;\n data[cacheIndex(resolution, x, y, z)] = Math.round(\n saturate(sampleCloudDensity(cache, params, position)) * 255,\n );\n }\n }\n }\n return Object.freeze(cache);\n}\n\n/** Export a detached snapshot suitable for persistence or a worker boundary. */\nexport function snapshotCloudDensityCache(cache: CloudDensityCache): CloudDensityCacheSnapshot {\n return Object.freeze({\n sourceKey: cache.sourceKey,\n resolution: cache.resolution,\n data: new Uint8Array(cache.data),\n formationData: new Uint8Array(cache.formationData),\n digest: cache.digest,\n });\n}\n\n/** Reconstruct a cache without running the procedural generator again. */\nexport function reconstructCloudDensityCache(\n params: ValidatedCloudLayer,\n snapshot: CloudDensityCacheSnapshot,\n): Result<CloudDensityCache, CloudLayerError> {\n const expectedKey = cloudLayerFormationKey(params);\n if (snapshot.sourceKey !== expectedKey) {\n return err(new CloudLayerCacheInvalidError(snapshot.sourceKey, 'source key mismatch'));\n }\n if (\n !Number.isInteger(snapshot.resolution) ||\n snapshot.resolution < 4 ||\n snapshot.resolution > 256 ||\n snapshot.data.byteLength !== snapshot.resolution ** 3 ||\n (snapshot.formationData !== undefined &&\n snapshot.formationData.byteLength !== snapshot.resolution ** 3 * 3)\n ) {\n return err(\n new CloudLayerCacheInvalidError(snapshot.sourceKey, 'resolution and payload length mismatch'),\n );\n }\n const formationData =\n snapshot.formationData === undefined\n ? new Uint8Array(snapshot.data.length * 3).fill(0)\n : new Uint8Array(snapshot.formationData);\n const digest = digestBytes(formationData);\n if (digest !== snapshot.digest) {\n return err(new CloudLayerCacheInvalidError(snapshot.sourceKey, 'payload digest mismatch'));\n }\n const data = new Uint8Array(snapshot.data);\n return ok(\n Object.freeze({\n sourceKey: snapshot.sourceKey,\n resolution: snapshot.resolution,\n data,\n formationData,\n formationByteLength: formationData.byteLength,\n byteLength: formationData.byteLength,\n digest,\n }),\n );\n}\n\nfunction wrapped(value: number, resolution: number): number {\n const result = value - Math.floor(value);\n return Math.min(resolution - 1e-6, Math.max(0, result * resolution));\n}\n\n/** Sample the cached field with periodic x/z addressing and wind advection. */\nexport function sampleCloudDensity(\n cache: CloudDensityCache,\n params: ValidatedCloudLayer,\n position: ArrayLike<number>,\n timeSeconds = 0,\n): number {\n const height = ((position[1] ?? 0) - params.baseHeight) / Math.max(1e-6, params.thickness);\n if (height <= 0 || height >= 1 || params.coverage <= 0 || params.density <= 0) return 0;\n const period = 1 / Math.max(1e-6, params.scale);\n const x = wrapped(\n ((position[0] ?? 0) + (params.wind[0] ?? 0) * timeSeconds) / period - 0.5 / cache.resolution,\n cache.resolution,\n );\n const z = wrapped(\n ((position[2] ?? 0) + (params.wind[2] ?? 0) * timeSeconds) / period - 0.5 / cache.resolution,\n cache.resolution,\n );\n // The cache's y axis stores the normalized formation coordinate before\n // vertical advection. Map the authored noise shift back through the same\n // vertical cell aspect used by formationField; the world-space envelope\n // below remains anchored to the current receiver height.\n const advectedHeight =\n height +\n ((params.wind[1] ?? 0) * timeSeconds * params.scale) / Math.max(1e-6, CLOUD_VERTICAL_CELLS);\n const y = wrapped(advectedHeight - 0.5 / cache.resolution, cache.resolution);\n const x0 = Math.floor(x);\n const y0 = Math.floor(y);\n const z0 = Math.floor(z);\n const x1 = (x0 + 1) % cache.resolution;\n const y1 = (y0 + 1) % cache.resolution;\n const z1 = (z0 + 1) % cache.resolution;\n const fx = x - x0;\n const fy = y - y0;\n const fz = z - z0;\n const stride = cache.resolution ** 3;\n if (cache.formationData === undefined || cache.formationData.byteLength < stride * 3) {\n const sampleLegacy = (sx: number, sy: number, sz: number): number =>\n (cache.data[cacheIndex(cache.resolution, sx, sy, sz)] ?? 0) / 255;\n const c00 =\n sampleLegacy(x0, y0, z0) + (sampleLegacy(x1, y0, z0) - sampleLegacy(x0, y0, z0)) * fx;\n const c10 =\n sampleLegacy(x0, y1, z0) + (sampleLegacy(x1, y1, z0) - sampleLegacy(x0, y1, z0)) * fx;\n const c01 =\n sampleLegacy(x0, y0, z1) + (sampleLegacy(x1, y0, z1) - sampleLegacy(x0, y0, z1)) * fx;\n const c11 =\n sampleLegacy(x0, y1, z1) + (sampleLegacy(x1, y1, z1) - sampleLegacy(x0, y1, z1)) * fx;\n return (\n (c00 + (c10 - c00) * fy + (c01 + (c11 - c01) * fy - (c00 + (c10 - c00) * fy)) * fz) *\n heightEnvelope(height, 1, 0.5) *\n params.density\n );\n }\n const samplePlane = (plane: number, sx: number, sy: number, sz: number): number => {\n const payload = cache.formationData;\n const offset = plane * stride + cacheIndex(cache.resolution, sx, sy, sz);\n return (payload[offset] ?? 0) / 255;\n };\n const sample = (plane: number): number => {\n const repeat = plane === 2 ? 3 : 1;\n const sx = wrapped(\n ((x + 0.5) / cache.resolution) * repeat - 0.5 / cache.resolution,\n cache.resolution,\n );\n const sy = wrapped(\n ((y + 0.5) / cache.resolution) * repeat - 0.5 / cache.resolution,\n cache.resolution,\n );\n const sz = wrapped(\n ((z + 0.5) / cache.resolution) * repeat - 0.5 / cache.resolution,\n cache.resolution,\n );\n const x0 = Math.floor(sx),\n y0 = Math.floor(sy),\n z0 = Math.floor(sz);\n const x1 = (x0 + 1) % cache.resolution,\n y1 = (y0 + 1) % cache.resolution,\n z1 = (z0 + 1) % cache.resolution;\n const fx = sx - x0,\n fy = sy - y0,\n fz = sz - z0;\n\n const c00 =\n samplePlane(plane, x0, y0, z0) +\n (samplePlane(plane, x1, y0, z0) - samplePlane(plane, x0, y0, z0)) * fx;\n const c10 =\n samplePlane(plane, x0, y1, z0) +\n (samplePlane(plane, x1, y1, z0) - samplePlane(plane, x0, y1, z0)) * fx;\n const c01 =\n samplePlane(plane, x0, y0, z1) +\n (samplePlane(plane, x1, y0, z1) - samplePlane(plane, x0, y0, z1)) * fx;\n const c11 =\n samplePlane(plane, x0, y1, z1) +\n (samplePlane(plane, x1, y1, z1) - samplePlane(plane, x0, y1, z1)) * fx;\n return c00 + (c10 - c00) * fy + (c01 + (c11 - c01) * fy - (c00 + (c10 - c00) * fy)) * fz;\n };\n const weather = sample(0);\n const body = sample(1);\n const erosion = sample(2);\n return (\n composeCloudDensity(height, { weather, body, erosion, noise: body }, params.coverage) *\n params.density\n );\n}\n","import type { RhiCaps } from '@forgeax/engine-rhi';\nimport type { CloudLayerResourceFacts } from './resources';\nimport type { CloudTemporalResetReason } from './temporal';\n\nexport type CloudLayerInspectionStatus = 'off' | 'available' | 'unavailable' | 'degraded';\nexport type CloudLayerResourceStage = 'none' | 'candidate' | 'accepted' | 'lkg' | 'recovering';\n/** Physical-adapter evidence is explicit; RHI backend labels cannot prove it. */\nexport type CloudPhysicalGpuEvidence = 'unknown' | 'available' | 'unavailable';\n\nexport interface CloudLayerBudgetObservation {\n readonly measured: boolean;\n readonly physicalGpu: CloudPhysicalGpuEvidence;\n readonly gpuTimestamp: boolean;\n readonly quality: 'low' | 'medium' | 'high' | undefined;\n readonly warmupFrames: number;\n readonly sampleFrames: number;\n readonly p50GpuMs: number | undefined;\n readonly p95GpuMs: number | undefined;\n readonly coldGenerationMs: number | undefined;\n readonly frameBudgetMs: number | undefined;\n readonly reason?: string;\n}\n\nexport interface CloudLayerInspection {\n readonly status: CloudLayerInspectionStatus;\n readonly resourceStage: CloudLayerResourceStage;\n readonly sourceKey: string | undefined;\n readonly generation: number | undefined;\n readonly candidateGeneration: number | undefined;\n readonly lkgGeneration: number | undefined;\n readonly shadowRevision: number | undefined;\n readonly temporalResets: number;\n readonly lastTemporalReset: CloudTemporalResetReason | undefined;\n readonly resourceFacts: CloudLayerResourceFacts | undefined;\n readonly capability: {\n readonly compute: boolean;\n readonly storageBuffer: boolean;\n readonly rgba16floatRenderable: boolean;\n readonly physicalGpu: CloudPhysicalGpuEvidence;\n readonly timestampQuery: boolean;\n };\n readonly budget: CloudLayerBudgetObservation;\n}\n\nexport interface CloudLayerInspectionInput {\n readonly authored: boolean;\n readonly sourceKey?: string;\n readonly generation?: number;\n readonly candidateGeneration?: number;\n readonly lkgGeneration?: number;\n readonly shadowRevision?: number;\n readonly temporalResets?: number;\n readonly lastTemporalReset?: CloudTemporalResetReason;\n readonly resourceFacts?: CloudLayerResourceFacts;\n readonly capability?: Partial<CloudLayerInspection['capability']>;\n readonly degraded?: boolean;\n readonly budget?: Partial<CloudLayerBudgetObservation>;\n}\n\nfunction resourceStage(input: CloudLayerInspectionInput): CloudLayerResourceStage {\n if (!input.authored || input.generation === undefined) return 'none';\n if (input.candidateGeneration !== undefined) return 'candidate';\n if (input.degraded === true || input.lkgGeneration !== undefined) return 'lkg';\n return 'accepted';\n}\n\n/** Capability and lifecycle facts are inspectable even when the lane is unavailable. */\nexport function inspectCloudLayer(input: CloudLayerInspectionInput): CloudLayerInspection {\n const capability = {\n compute: input.capability?.compute ?? false,\n storageBuffer: input.capability?.storageBuffer ?? false,\n rgba16floatRenderable: input.capability?.rgba16floatRenderable ?? false,\n physicalGpu: input.capability?.physicalGpu ?? 'unknown',\n timestampQuery: input.capability?.timestampQuery ?? false,\n };\n const budget: CloudLayerBudgetObservation = {\n measured: input.budget?.measured ?? false,\n physicalGpu: input.budget?.physicalGpu ?? capability.physicalGpu,\n gpuTimestamp: input.budget?.gpuTimestamp ?? capability.timestampQuery,\n quality: input.budget?.quality,\n warmupFrames: input.budget?.warmupFrames ?? 0,\n sampleFrames: input.budget?.sampleFrames ?? 0,\n p50GpuMs: input.budget?.p50GpuMs,\n p95GpuMs: input.budget?.p95GpuMs,\n coldGenerationMs: input.budget?.coldGenerationMs,\n frameBudgetMs: input.budget?.frameBudgetMs,\n ...(input.budget?.reason === undefined ? {} : { reason: input.budget.reason }),\n };\n // CloudLayer's production plan allocates an HDR shadow/composite target and\n // therefore requires the complete feature capability tuple. Reporting\n // `available` from compute/storage alone lets inspection lie while the graph\n // admission correctly disables the feature on LDR-only adapters.\n const available =\n capability.compute && capability.storageBuffer && capability.rgba16floatRenderable;\n return Object.freeze({\n status: !input.authored\n ? 'off'\n : !available\n ? 'unavailable'\n : input.degraded === true\n ? 'degraded'\n : 'available',\n resourceStage: resourceStage(input),\n sourceKey: input.sourceKey,\n generation: input.generation,\n candidateGeneration: input.candidateGeneration,\n lkgGeneration: input.lkgGeneration,\n shadowRevision: input.shadowRevision,\n temporalResets: input.temporalResets ?? 0,\n lastTemporalReset: input.lastTemporalReset,\n resourceFacts: input.resourceFacts,\n capability,\n budget,\n });\n}\n\n/** Convert RHI facts without letting inspection invent physical measurements. */\nexport function cloudCapabilitiesFromRhi(\n caps: Readonly<RhiCaps>,\n): CloudLayerInspection['capability'] {\n return Object.freeze({\n compute: caps.compute === true,\n storageBuffer: caps.storageBuffer === true,\n rgba16floatRenderable: caps.rgba16floatRenderable === true,\n // RHI caps intentionally do not claim a physical adapter. A browser or\n // Dawn receipt must promote this fact to available/unavailable.\n physicalGpu: 'unknown',\n timestampQuery: caps.timestampQuery === true,\n });\n}\n","import type { CloudDensityCache } from './density';\nimport type { CloudShadowProjection } from './shadow';\nimport type { CloudHistory } from './temporal';\n\n/** Evidence level for bytes owned by the prepared GPU path. */\nexport type CloudGpuResourceEvidence = 'unavailable' | 'declared' | 'measured';\n\n/** rgba16float is four 16-bit channels (8 bytes per texel). */\nexport const CLOUD_RGBA16FLOAT_BYTES_PER_TEXEL = 8;\n/** Two ping-pong surfaces for each of radiance/transmittance/depth. */\nexport const CLOUD_HISTORY_SURFACE_COUNT = 6;\n\nexport interface CloudLayerResourceFacts {\n readonly generation: number;\n /** CPU-side packed formation payload; this is not GPU residency. */\n readonly cacheBytes: number;\n /** Measured GPU bytes, or zero when no prepared-owner receipt was supplied. */\n readonly shadowBytes: number;\n readonly historyBytes: number;\n readonly inFlightBytes: number;\n readonly residentBytes: number;\n readonly resourceCount: number;\n /** Whether the GPU byte fields are measured, only graph-declared, or unknown. */\n readonly gpuEvidence: CloudGpuResourceEvidence;\n /** Descriptor-derived allocation sizes, independent from physical residency. */\n readonly declaredShadowBytes: number;\n readonly declaredHistoryBytes: number;\n readonly declaredResidentBytes: number;\n readonly declaredResourceCount: number;\n /** Measured GPU resource count, kept separate from logical declarations. */\n readonly measuredGpuResourceCount: number;\n readonly cacheResolution: number;\n readonly shadowResolution: number;\n}\n\nexport interface CloudLayerResourceInputs {\n readonly generation: number;\n readonly cache?: CloudDensityCache;\n readonly shadow?: CloudShadowProjection;\n readonly history?: CloudHistory;\n /** Bytes reported by the prepared GPU owner; absent means unavailable. */\n readonly shadowBytes?: number;\n readonly historyBytes?: number;\n readonly inFlightBytes?: number;\n}\n\n/** Derive one inspection receipt from the resources owned by the current generation. */\nexport function inspectCloudLayerResources(\n input: CloudLayerResourceInputs,\n): CloudLayerResourceFacts {\n const cacheBytes = input.cache?.byteLength ?? 0;\n const shadowResolution = input.shadow?.resolution ?? 0;\n const declaredShadowBytes =\n shadowResolution * shadowResolution * CLOUD_RGBA16FLOAT_BYTES_PER_TEXEL;\n const historyWidth = input.history?.width ?? 0;\n const historyHeight = input.history?.height ?? 0;\n const declaredHistoryBytes =\n historyWidth * historyHeight * CLOUD_HISTORY_SURFACE_COUNT * CLOUD_RGBA16FLOAT_BYTES_PER_TEXEL;\n const shadowBytes = input.shadowBytes ?? 0;\n const historyBytes = input.historyBytes ?? 0;\n const inFlightBytes = Math.max(0, input.inFlightBytes ?? 0);\n const residentBytes = cacheBytes + shadowBytes + historyBytes;\n const measuredGpuResourceCount =\n Number(input.shadowBytes !== undefined) + Number(input.historyBytes !== undefined);\n const gpuEvidence: CloudGpuResourceEvidence =\n measuredGpuResourceCount > 0 || input.inFlightBytes !== undefined\n ? 'measured'\n : input.shadow !== undefined || input.history !== undefined\n ? 'declared'\n : 'unavailable';\n const resourceCount =\n Number(input.cache !== undefined) +\n Number(input.shadow !== undefined) +\n Number(input.history !== undefined);\n return Object.freeze({\n generation: input.generation,\n cacheBytes,\n shadowBytes,\n historyBytes,\n inFlightBytes,\n residentBytes,\n resourceCount,\n gpuEvidence,\n declaredShadowBytes,\n declaredHistoryBytes,\n declaredResidentBytes: cacheBytes + declaredShadowBytes + declaredHistoryBytes,\n declaredResourceCount: resourceCount,\n measuredGpuResourceCount,\n cacheResolution: input.cache?.resolution ?? 0,\n shadowResolution,\n });\n}\n\nexport interface CloudLayerGeneration {\n readonly generation: number;\n readonly sourceKey: string;\n readonly resourceFacts: CloudLayerResourceFacts;\n readonly status: 'candidate' | 'active' | 'lkg' | 'retiring';\n}\n\n/** Candidate -> active transition used by the renderer's existing graph owner. */\nexport function acceptCloudLayerGeneration(\n candidate: CloudLayerGeneration,\n previous: CloudLayerGeneration | undefined,\n): { readonly active: CloudLayerGeneration; readonly lkg: CloudLayerGeneration | undefined } {\n return Object.freeze({\n active: Object.freeze({ ...candidate, status: 'active' as const }),\n lkg:\n previous === undefined ? undefined : Object.freeze({ ...previous, status: 'lkg' as const }),\n });\n}\n\n/** A failed candidate never replaces the LKG; retirement is fence-owned by Render. */\nexport function retainCloudLayerAfterFailure(\n active: CloudLayerGeneration | undefined,\n candidate: CloudLayerGeneration,\n): { readonly active: CloudLayerGeneration | undefined; readonly retiring: CloudLayerGeneration } {\n return Object.freeze({\n active,\n retiring: Object.freeze({ ...candidate, status: 'retiring' as const }),\n });\n}\n","import type { CloudDensityCache } from './density';\nimport { evaluateCloudDensity, sampleCloudDensity } from './density';\nimport { CLOUD_EXTINCTION_COEFFICIENT, type ValidatedCloudLayer } from './parameters';\n\nexport type CloudOpticalPath = 'camera' | 'solar-column' | 'cloud-interior';\n\nexport interface CloudRay {\n readonly origin: readonly [number, number, number];\n readonly direction: readonly [number, number, number];\n readonly maxDistance: number;\n}\n\nexport interface CloudOpticalResult {\n readonly path: CloudOpticalPath;\n readonly transmittance: number;\n readonly scattering: readonly [number, number, number];\n readonly opticalDepth: number;\n readonly representativeDepth: number;\n readonly steps: number;\n readonly entered: boolean;\n readonly exited: boolean;\n}\n\nexport interface CloudInteriorLighting {\n readonly sunRadiance: readonly [number, number, number];\n readonly sunDirection: readonly [number, number, number];\n readonly phaseG?: number;\n}\n\nexport interface CloudOpticsInput {\n readonly params: ValidatedCloudLayer;\n readonly ray: CloudRay;\n readonly path: CloudOpticalPath;\n readonly timeSeconds?: number;\n readonly cache?: CloudDensityCache;\n readonly steps?: number;\n readonly lighting?: CloudInteriorLighting;\n}\n\nconst EMPTY_SCATTERING: readonly [number, number, number] = [0, 0, 0];\n\nfunction normalize(vector: ArrayLike<number>): readonly [number, number, number] {\n const x = vector[0] ?? 0;\n const y = vector[1] ?? 0;\n const z = vector[2] ?? 0;\n const length = Math.hypot(x, y, z);\n return length <= 1e-8 ? [0, 1, 0] : [x / length, y / length, z / length];\n}\n\nfunction rayBoxInterval(\n ray: CloudRay,\n params: ValidatedCloudLayer,\n): { readonly start: number; readonly end: number } | undefined {\n const min = [Number.NEGATIVE_INFINITY, params.baseHeight, Number.NEGATIVE_INFINITY];\n const max = [\n Number.POSITIVE_INFINITY,\n params.baseHeight + params.thickness,\n Number.POSITIVE_INFINITY,\n ];\n let start = 0;\n let end = Math.max(0, ray.maxDistance);\n for (let axis = 0; axis < 3; axis += 1) {\n const origin = ray.origin[axis] ?? 0;\n const direction = ray.direction[axis] ?? 0;\n const lower = min[axis] ?? 0;\n const upper = max[axis] ?? 0;\n if (Math.abs(direction) < 1e-8) {\n if (origin < lower || origin > upper) return undefined;\n continue;\n }\n const a = (lower - origin) / direction;\n const b = (upper - origin) / direction;\n start = Math.max(start, Math.min(a, b));\n end = Math.min(end, Math.max(a, b));\n if (end <= start) return undefined;\n }\n return end > start ? { start, end } : undefined;\n}\n\nexport function intersectCloudLayer(\n ray: CloudRay,\n params: ValidatedCloudLayer,\n): { readonly start: number; readonly end: number } | undefined {\n return rayBoxInterval(ray, params);\n}\n\nfunction phaseFunction(cosTheta: number, g: number): number {\n const boundedG = Math.max(-0.95, Math.min(0.95, g));\n const denominator = Math.max(1e-4, 1 + boundedG * boundedG - 2 * boundedG * cosTheta);\n return ((1 - boundedG * boundedG) / denominator ** 1.5) * (1 / (4 * Math.PI));\n}\n\nfunction cloudPhase(cosTheta: number, forwardG: number): number {\n // Match the bounded dual-lobe phase used by the fullscreen WGSL path.\n return phaseFunction(cosTheta, forwardG) * 0.8 + phaseFunction(cosTheta, -0.2) * 0.2;\n}\n\nfunction smoothstep(edge0: number, edge1: number, value: number): number {\n const t = Math.max(0, Math.min(1, (value - edge0) / Math.max(1e-6, edge1 - edge0)));\n return t * t * (3 - 2 * t);\n}\n\n/** Unit-sun incident light, using the same phase basis as production volumes. */\nexport function cloudIncidentLight(\n solarT: number,\n cosTheta: number,\n height: number,\n forwardG = 0.55,\n): readonly [number, number, number] {\n const direct = solarT * cloudPhase(cosTheta, forwardG);\n const multiple = (0.5 * Math.sqrt(solarT) + 0.25 * solarT ** 0.25) / (4 * Math.PI);\n const energy = (direct + multiple) * (4 * Math.PI);\n const skyFill = 0.025 + 0.05 * smoothstep(0.1, 0.85, height);\n return [energy + 0.72 * skyFill, energy + 0.84 * skyFill, energy + skyFill];\n}\n\nfunction densityAt(input: CloudOpticsInput, position: readonly [number, number, number]): number {\n return input.cache === undefined\n ? evaluateCloudDensity(input.params, position, input.timeSeconds ?? 0).density\n : sampleCloudDensity(input.cache, input.params, position, input.timeSeconds ?? 0);\n}\n\n/**\n * Integrate one explicitly named optical path through the layer.\n *\n * Camera, solar-column and cloud-interior paths are intentionally separate\n * call sites. A caller cannot accidentally use a camera interval as the\n * light interval and apply the same cloud attenuation twice.\n */\nexport function integrateCloudPath(input: CloudOpticsInput): CloudOpticalResult {\n const direction = normalize(input.ray.direction);\n const interval = rayBoxInterval({ ...input.ray, direction }, input.params);\n if (interval === undefined || input.params.density <= 0) {\n return {\n path: input.path,\n transmittance: 1,\n scattering: EMPTY_SCATTERING,\n opticalDepth: 0,\n representativeDepth: input.ray.maxDistance,\n steps: 0,\n entered: false,\n exited: false,\n };\n }\n const steps = Math.max(1, Math.floor(input.steps ?? 32));\n const length = interval.end - interval.start;\n const stepLength = length / steps;\n let opticalDepth = 0;\n const scattering: [number, number, number] = [0, 0, 0];\n let weightedDepth = 0;\n let scatteringWeight = 0;\n const lighting = input.lighting;\n const lightDirection = lighting === undefined ? undefined : normalize(lighting.sunDirection);\n const viewDirection = normalize(input.ray.direction);\n for (let index = 0; index < steps; index += 1) {\n const distance = interval.start + (index + 0.5) * stepLength;\n const position: [number, number, number] = [\n (input.ray.origin[0] ?? 0) + direction[0] * distance,\n (input.ray.origin[1] ?? 0) + direction[1] * distance,\n (input.ray.origin[2] ?? 0) + direction[2] * distance,\n ];\n const localDensity = Math.max(0, densityAt(input, position));\n const extinction = localDensity * CLOUD_EXTINCTION_COEFFICIENT * stepLength;\n const transmittanceBefore = Math.exp(-opticalDepth);\n opticalDepth += extinction;\n if (lighting !== undefined && lightDirection !== undefined && localDensity > 0) {\n const localShadow = integrateCloudPath({\n params: input.params,\n path: 'solar-column',\n ray: {\n origin: position,\n direction: lightDirection,\n maxDistance: input.params.shadowRange,\n },\n steps: Math.max(4, Math.ceil((input.steps ?? 32) * 0.5)),\n ...(input.timeSeconds === undefined ? {} : { timeSeconds: input.timeSeconds }),\n ...(input.cache === undefined ? {} : { cache: input.cache }),\n });\n const cosTheta =\n viewDirection[0] * lightDirection[0] +\n viewDirection[1] * lightDirection[1] +\n viewDirection[2] * lightDirection[2];\n const segmentWeight = transmittanceBefore * (1 - Math.exp(-extinction));\n const heightFraction = Math.max(\n 0,\n Math.min(1, ((position[1] ?? 0) - input.params.baseHeight) / input.params.thickness),\n );\n const incident = cloudIncidentLight(\n localShadow.transmittance,\n cosTheta,\n heightFraction,\n lighting.phaseG,\n );\n for (let channel = 0; channel < 3; channel++) {\n scattering[channel] =\n (scattering[channel] ?? 0) +\n (lighting.sunRadiance[channel] ?? 0) * (incident[channel] ?? 0) * segmentWeight;\n }\n const weight = segmentWeight;\n scatteringWeight += weight;\n weightedDepth += distance * weight;\n }\n }\n const transmittance = Math.exp(-opticalDepth);\n return {\n path: input.path,\n transmittance,\n scattering,\n opticalDepth,\n representativeDepth:\n scatteringWeight > 1e-6 ? weightedDepth / scatteringWeight : interval.start,\n steps,\n entered: true,\n exited: interval.end < input.ray.maxDistance,\n };\n}\n\nexport function integrateCloudCameraPath(\n params: ValidatedCloudLayer,\n ray: CloudRay,\n options: Omit<CloudOpticsInput, 'params' | 'ray' | 'path'> = {},\n): CloudOpticalResult {\n return integrateCloudPath({ ...options, params, ray, path: 'camera' });\n}\n\nexport function integrateCloudSolarColumn(\n params: ValidatedCloudLayer,\n origin: readonly [number, number, number],\n sunDirection: readonly [number, number, number],\n options: Omit<CloudOpticsInput, 'params' | 'ray' | 'path'> & {\n readonly maxDistance?: number;\n } = {},\n): CloudOpticalResult {\n return integrateCloudPath({\n ...options,\n params,\n path: 'solar-column',\n ray: {\n origin,\n direction: sunDirection,\n maxDistance: options.maxDistance ?? params.shadowRange,\n },\n });\n}\n\nexport function integrateCloudInterior(\n params: ValidatedCloudLayer,\n ray: CloudRay,\n lighting: CloudInteriorLighting,\n options: Omit<CloudOpticsInput, 'params' | 'ray' | 'path' | 'lighting'> = {},\n): CloudOpticalResult {\n return integrateCloudPath({ ...options, params, ray, path: 'cloud-interior', lighting });\n}\n\n/** Standard's one selected sun term consumes this factor exactly once. */\nexport function applyCloudSolarTransmittance(\n directSunRadiance: readonly [number, number, number],\n cloudTransmittance: number,\n meshVisibility = 1,\n): readonly [number, number, number] {\n const factor =\n Math.min(1, Math.max(0, cloudTransmittance)) * Math.min(1, Math.max(0, meshVisibility));\n return [\n (directSunRadiance[0] ?? 0) * factor,\n (directSunRadiance[1] ?? 0) * factor,\n (directSunRadiance[2] ?? 0) * factor,\n ];\n}\n\n/** Scene-linear HDR composition at the cloud interval/depth boundary. */\nexport function compositeCloudRadiance(\n sceneLinearHdr: readonly [number, number, number, number],\n cloud: CloudOpticalResult,\n sceneDepth: number,\n cloudDepth = cloud.representativeDepth,\n): readonly [number, number, number, number] {\n if (!Number.isFinite(sceneDepth) || cloudDepth > sceneDepth) return sceneLinearHdr;\n const transmittance = Math.min(1, Math.max(0, cloud.transmittance));\n return [\n (sceneLinearHdr[0] ?? 0) * transmittance + (cloud.scattering[0] ?? 0),\n (sceneLinearHdr[1] ?? 0) * transmittance + (cloud.scattering[1] ?? 0),\n (sceneLinearHdr[2] ?? 0) * transmittance + (cloud.scattering[2] ?? 0),\n 1,\n ];\n}\n","import type { CloudDensityCache } from './density';\nimport { integrateCloudSolarColumn } from './optics';\nimport type { ValidatedCloudLayer } from './parameters';\n\nexport interface CloudShadowProjection {\n readonly revision: number;\n readonly resolution: number;\n readonly range: number;\n readonly texelSize: number;\n readonly center: readonly [number, number, number];\n readonly origin: readonly [number, number, number];\n readonly right: readonly [number, number, number];\n readonly up: readonly [number, number, number];\n readonly sunDirection: readonly [number, number, number];\n readonly lowSun: boolean;\n}\n\nexport interface CloudShadowSample {\n readonly transmittance: number;\n readonly uv: readonly [number, number] | undefined;\n readonly valid: boolean;\n readonly fallback: 'none' | 'low-sun' | 'outside-range' | 'empty-coverage';\n readonly revision: number;\n}\n\nfunction normalize(vector: ArrayLike<number>): readonly [number, number, number] {\n const x = vector[0] ?? 0;\n const y = vector[1] ?? 0;\n const z = vector[2] ?? 0;\n const length = Math.hypot(x, y, z);\n return length <= 1e-8 ? [0, 1, 0] : [x / length, y / length, z / length];\n}\n\nfunction cross(\n a: readonly [number, number, number],\n b: readonly [number, number, number],\n): readonly [number, number, number] {\n return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];\n}\n\nfunction dot(a: ArrayLike<number>, b: ArrayLike<number>): number {\n return (a[0] ?? 0) * (b[0] ?? 0) + (a[1] ?? 0) * (b[1] ?? 0) + (a[2] ?? 0) * (b[2] ?? 0);\n}\n\nfunction stableRevision(input: {\n readonly center: readonly [number, number, number];\n readonly sunDirection: readonly [number, number, number];\n readonly range: number;\n readonly resolution: number;\n}): number {\n let hash = 2166136261;\n const values = [...input.center, ...input.sunDirection, input.range, input.resolution];\n for (const value of values) {\n const bits = new Float32Array([value]);\n const bytes = new Uint8Array(bits.buffer);\n for (const byte of bytes) hash = Math.imul(hash ^ byte, 16777619);\n }\n return hash >>> 0;\n}\n\n/**\n * Build a camera-independent light-space projection. The center is a world\n * anchor chosen by Render (usually the active scene bounds), and is snapped to\n * one texel so camera motion cannot crawl the cloud shadow.\n */\nexport function createCloudShadowProjection(input: {\n readonly center: readonly [number, number, number];\n readonly sunDirection: readonly [number, number, number];\n readonly range: number;\n readonly resolution?: number;\n}): CloudShadowProjection {\n const sunDirection = normalize(input.sunDirection);\n const resolution = Math.max(16, Math.floor(input.resolution ?? 1024));\n const range = Math.max(1, input.range);\n const texelSize = range / resolution;\n const reference = Math.abs(sunDirection[1]) < 0.95 ? ([0, 1, 0] as const) : ([1, 0, 0] as const);\n const right = normalize(cross(reference, sunDirection));\n const up = normalize(cross(sunDirection, right));\n const center = input.center;\n const lightX = dot(center, right);\n const lightY = dot(center, up);\n const lightZ = dot(center, sunDirection);\n const snappedX = Math.floor(lightX / texelSize + 0.5) * texelSize;\n const snappedY = Math.floor(lightY / texelSize + 0.5) * texelSize;\n const origin: [number, number, number] = [\n right[0] * snappedX + up[0] * snappedY + sunDirection[0] * lightZ,\n right[1] * snappedX + up[1] * snappedY + sunDirection[1] * lightZ,\n right[2] * snappedX + up[2] * snappedY + sunDirection[2] * lightZ,\n ];\n return Object.freeze({\n revision: stableRevision({ center, sunDirection, range, resolution }),\n resolution,\n range,\n texelSize,\n center: Object.freeze([...center] as [number, number, number]),\n origin: Object.freeze(origin),\n right,\n up,\n sunDirection,\n lowSun: sunDirection[1] <= 0.08,\n });\n}\n\nexport function projectCloudShadowUv(\n projection: CloudShadowProjection,\n position: readonly [number, number, number],\n): { readonly uv: readonly [number, number]; readonly inRange: boolean } {\n const relative: [number, number, number] = [\n position[0] - projection.origin[0],\n position[1] - projection.origin[1],\n position[2] - projection.origin[2],\n ];\n const x = dot(relative, projection.right);\n const y = dot(relative, projection.up);\n const uv: [number, number] = [0.5 + x / projection.range, 0.5 + y / projection.range];\n return { uv, inRange: uv[0] >= 0 && uv[0] <= 1 && uv[1] >= 0 && uv[1] <= 1 };\n}\n\n/** Evaluate the stable world-space shadow term used by surface and volume sun paths. */\nexport function sampleCloudShadow(\n params: ValidatedCloudLayer,\n projection: CloudShadowProjection,\n worldPosition: readonly [number, number, number],\n options: { readonly cache?: CloudDensityCache; readonly timeSeconds?: number } = {},\n): CloudShadowSample {\n const projected = projectCloudShadowUv(projection, worldPosition);\n if (projection.lowSun) {\n return {\n transmittance: 1,\n uv: projected.uv,\n valid: false,\n fallback: 'low-sun',\n revision: projection.revision,\n };\n }\n if (!projected.inRange) {\n return {\n transmittance: 1,\n uv: projected.uv,\n valid: false,\n fallback: 'outside-range',\n revision: projection.revision,\n };\n }\n if (params.coverage >= 1 || params.density <= 0) {\n return {\n transmittance: 1,\n uv: projected.uv,\n valid: false,\n fallback: 'empty-coverage',\n revision: projection.revision,\n };\n }\n const integrated = integrateCloudSolarColumn(params, worldPosition, projection.sunDirection, {\n steps: 20,\n maxDistance: projection.range,\n ...(options.cache === undefined ? {} : { cache: options.cache }),\n ...(options.timeSeconds === undefined ? {} : { timeSeconds: options.timeSeconds }),\n });\n return {\n transmittance: integrated.transmittance,\n uv: projected.uv,\n valid: integrated.entered,\n fallback: 'none',\n revision: projection.revision,\n };\n}\n","import type { CloudQuality } from '../components/cloud-layer';\n\nexport type CloudTemporalResetReason =\n | 'authoring-generation'\n | 'camera-cut'\n | 'resize'\n | 'recovery'\n | 'time-discontinuity'\n | 'cloud-shadow-revision'\n | 'device-generation'\n | 'history-missing'\n | 'reprojection-outside'\n | 'scene-depth-disocclusion';\n\nexport interface CloudTemporalSignature {\n readonly sourceKey: string;\n readonly viewId: string;\n readonly authoringGeneration: number;\n readonly cloudShadowRevision: number;\n readonly cameraRevision: number;\n readonly deviceGeneration: number;\n readonly width: number;\n readonly height: number;\n readonly timeSeconds: number;\n readonly quality: CloudQuality;\n /** Scene-depth producer revision used to reject disoccluded history. */\n readonly sceneDepthVersion?: number;\n}\n\nexport interface CloudHistory {\n readonly width: number;\n readonly height: number;\n readonly signature: string;\n readonly temporal: CloudTemporalSignature;\n readonly generation: number;\n readonly valid: boolean;\n}\n\nexport interface CloudTemporalDecision {\n readonly reset: boolean;\n readonly reasons: readonly CloudTemporalResetReason[];\n readonly signature: string;\n readonly history: CloudHistory | undefined;\n}\n\nexport interface CloudTemporalFrame {\n readonly signature: CloudTemporalSignature;\n readonly history: CloudHistory | undefined;\n readonly reset: boolean;\n readonly reasons: readonly CloudTemporalResetReason[];\n}\n\nexport interface CloudHistoryReprojectionInput {\n readonly currentDepth: number;\n readonly historyDepth: number;\n readonly motion: readonly [number, number];\n readonly currentPixel: readonly [number, number];\n readonly historySize: readonly [number, number];\n readonly depthTolerance?: number;\n}\n\nexport interface CloudHistoryReprojection {\n readonly accepted: boolean;\n readonly historyUv: readonly [number, number];\n readonly weight: number;\n readonly reason: 'accepted' | 'outside' | 'depth-disocclusion';\n}\n\nexport function cloudTemporalSignature(input: CloudTemporalSignature): string {\n return [\n 'cloud-temporal-v1',\n input.viewId,\n input.sourceKey,\n input.authoringGeneration,\n input.cloudShadowRevision,\n input.cameraRevision,\n input.deviceGeneration,\n input.width,\n input.height,\n input.timeSeconds,\n input.quality,\n input.sceneDepthVersion ?? 0,\n ].join(':');\n}\n\nfunction sameLayout(left: CloudTemporalSignature, right: CloudTemporalSignature): boolean {\n return left.viewId === right.viewId && left.width === right.width && left.height === right.height;\n}\n\n/** Compare the facts that make a cloud history safe to reuse. */\nexport function cloudTemporalResetReasons(\n previous: CloudTemporalSignature | undefined,\n next: CloudTemporalSignature,\n options: { readonly cameraCut?: boolean; readonly recovery?: boolean } = {},\n): readonly CloudTemporalResetReason[] {\n if (previous === undefined) return ['history-missing'];\n const reasons: CloudTemporalResetReason[] = [];\n if (\n previous.sourceKey !== next.sourceKey ||\n previous.authoringGeneration !== next.authoringGeneration\n ) {\n reasons.push('authoring-generation');\n }\n if (previous.cloudShadowRevision !== next.cloudShadowRevision)\n reasons.push('cloud-shadow-revision');\n if (previous.deviceGeneration !== next.deviceGeneration) reasons.push('device-generation');\n if (\n previous.sceneDepthVersion !== undefined &&\n next.sceneDepthVersion !== undefined &&\n previous.sceneDepthVersion !== next.sceneDepthVersion\n ) {\n reasons.push('scene-depth-disocclusion');\n }\n if (!sameLayout(previous, next)) reasons.push('resize');\n if (options.cameraCut === true || previous.cameraRevision !== next.cameraRevision)\n reasons.push('camera-cut');\n const dt = next.timeSeconds - previous.timeSeconds;\n if (!Number.isFinite(dt) || dt < 0 || dt > 0.5) reasons.push('time-discontinuity');\n if (options.recovery === true) reasons.push('recovery');\n return Object.freeze(reasons);\n}\n\nexport function createCloudHistory(\n signature: CloudTemporalSignature,\n generation: number,\n valid = false,\n): CloudHistory {\n return Object.freeze({\n width: Math.max(1, Math.floor(signature.width)),\n height: Math.max(1, Math.floor(signature.height)),\n signature: cloudTemporalSignature(signature),\n temporal: Object.freeze({ ...signature }),\n generation,\n valid,\n });\n}\n\n/** Per-view histories are keyed by the renderer's view identity. */\nexport class CloudHistoryStore {\n private readonly maxViews: number;\n private readonly entries = new Map<\n string,\n { readonly history: CloudHistory; readonly signature: CloudTemporalSignature }\n >();\n\n constructor(maxViews = 4) {\n this.maxViews = Math.max(1, Math.floor(maxViews));\n }\n\n begin(\n signature: CloudTemporalSignature,\n options: { readonly cameraCut?: boolean; readonly recovery?: boolean } = {},\n ): CloudTemporalDecision {\n const key = signature.viewId;\n const previousEntry = this.entries.get(key);\n const previous = previousEntry?.history;\n const reasons = cloudTemporalResetReasons(previousEntry?.signature, signature, options);\n const reset = reasons.length > 0;\n return Object.freeze({\n reset,\n reasons,\n signature: cloudTemporalSignature(signature),\n history: reset ? undefined : previous,\n });\n }\n\n commit(signature: CloudTemporalSignature, history: CloudHistory): void {\n if (\n history.width !== Math.max(1, Math.floor(signature.width)) ||\n history.height !== Math.max(1, Math.floor(signature.height))\n ) {\n this.entries.delete(signature.viewId);\n return;\n }\n this.entries.set(signature.viewId, { history, signature: Object.freeze({ ...signature }) });\n while (this.entries.size > this.maxViews) {\n const oldest = this.entries.keys().next().value as string | undefined;\n if (oldest === undefined) break;\n this.entries.delete(oldest);\n }\n }\n\n reset(viewId?: string): void {\n if (viewId === undefined) this.entries.clear();\n else this.entries.delete(viewId);\n }\n\n get(viewId: string): CloudHistory | undefined {\n return this.entries.get(viewId)?.history;\n }\n\n dispose(): void {\n this.entries.clear();\n }\n}\n\n/** Project one current pixel into the previous cloud history. */\nexport function reprojectCloudHistory(\n input: CloudHistoryReprojectionInput,\n historyWeight = 0.9,\n): CloudHistoryReprojection {\n const width = Math.max(1, input.historySize[0] ?? 1);\n const height = Math.max(1, input.historySize[1] ?? 1);\n const uv: [number, number] = [\n ((input.currentPixel[0] ?? 0) - (input.motion[0] ?? 0)) / width,\n ((input.currentPixel[1] ?? 0) - (input.motion[1] ?? 0)) / height,\n ];\n if (uv[0] < 0 || uv[0] > 1 || uv[1] < 0 || uv[1] > 1) {\n return { accepted: false, historyUv: uv, weight: 0, reason: 'outside' };\n }\n const depthTolerance =\n input.depthTolerance ?? Math.max(0.01, Math.abs(input.currentDepth) * 0.02);\n if (\n !Number.isFinite(input.currentDepth) ||\n !Number.isFinite(input.historyDepth) ||\n Math.abs(input.currentDepth - input.historyDepth) > depthTolerance\n ) {\n return { accepted: false, historyUv: uv, weight: 0, reason: 'depth-disocclusion' };\n }\n return {\n accepted: true,\n historyUv: uv,\n weight: Math.min(0.99, Math.max(0, historyWeight)),\n reason: 'accepted',\n };\n}\n","import { ok, type Result } from '@forgeax/engine-types';\nimport type { RenderError } from '../errors/render';\nimport type { RenderFeaturePlan, RenderFeaturePlanContext } from '../features/plan';\nimport type { RenderFeature, RenderFeatureExtractContext } from '../features/types';\nimport { buildCloudDensityCache, CLOUD_VERTICAL_CELLS, type CloudDensityCache } from './density';\nimport {\n type CloudLayerInspection,\n cloudCapabilitiesFromRhi,\n inspectCloudLayer,\n} from './inspection';\nimport {\n CLOUD_EXTINCTION_COEFFICIENT,\n CLOUD_QUALITY_PROFILES,\n cloudLayerFormationKey,\n cloudShadowResolutionForQuality,\n cloudViewDistanceForQuality,\n type ValidatedCloudLayer,\n} from './parameters';\nimport { inspectCloudLayerResources } from './resources';\nimport { type CloudShadowProjection, createCloudShadowProjection } from './shadow';\nimport {\n CloudHistoryStore,\n type CloudTemporalFrame,\n type CloudTemporalSignature,\n createCloudHistory,\n} from './temporal';\n\nexport const CLOUD_LAYER_FEATURE_IDENTITY = 'forgeax.cloud-layer';\nexport const CLOUD_LAYER_DENSITY_PROGRAM = 'cloud-layer-density';\nexport const CLOUD_LAYER_DENSITY_BINDINGS = 'cloud-layer-density-bindings';\nexport const CLOUD_LAYER_DENSITY_CACHE = 'cloud-layer-density-cache';\nexport const CLOUD_LAYER_DENSITY_OUTPUT = 'cloud-layer-density-output';\n\nconst COMPUTE_STAGE = 0x4;\nconst CLOUD_WORKGROUP_SIZE = 64;\n// 24 vec4/u32 lanes: authored field, sun, integration mode and the\n// renderer-owned stable light-space shadow projection. The same POD is used by\n// the display and shadow entry points so they cannot drift in their density or\n// cache addressing contract.\n// The final lane carries temporal validity/reset/blend. Keep the payload\n// explicitly 16-byte aligned so the public schema, prepared UBO and WGSL stay\n// one contract.\nexport const CLOUD_VIEW_PARAMS_BYTES = 176;\n\n/** R8 cache bytes are packed into little-endian u32 storage elements. */\nfunction packCloudDensityCache(cache: CloudDensityCache): Uint32Array {\n const packed = new Uint32Array(Math.max(1, Math.ceil(cache.formationData.byteLength / 4)));\n for (let index = 0; index < cache.formationData.byteLength; index += 1) {\n const wordIndex = index >>> 2;\n packed[wordIndex] =\n (packed[wordIndex] ?? 0) | ((cache.formationData[index] ?? 0) << ((index & 3) * 8));\n }\n return packed;\n}\n\n/** Minimal copy compute; one invocation owns one packed u32 cache element. */\nexport const CLOUD_DENSITY_COMPUTE_WGSL = /* wgsl */ `\nstruct CloudCacheParams { count: u32, }\n@group(0) @binding(0) var<storage, read> sourceDensity: array<u32>;\n@group(0) @binding(1) var<storage, read_write> cachedDensity: array<u32>;\n@group(0) @binding(2) var<uniform> params: CloudCacheParams;\n@compute @workgroup_size(64)\nfn cloud_density_cache(@builtin(global_invocation_id) id: vec3<u32>) {\n if (id.x >= params.count) { return; }\n cachedDensity[id.x] = sourceDensity[id.x];\n}\n`;\n\n/**\n * Cloud view transport. The View group is the renderer-owned camera/light\n * source of truth; group(1) carries frame-local cloud parameters, depth and\n * the bounded packed 3D cache. Camera, solar-column and cloud-interior\n * integration all call cloud_density(), so wind only changes the sample\n * coordinate and never the authored field.\n */\nexport const CLOUD_VIEW_FULLSCREEN_WGSL = /* wgsl */ `\nconst CLOUD_VERTICAL_CELLS: f32 = ${CLOUD_VERTICAL_CELLS};\nconst CLOUD_VERTICAL_NOISE_CELLS: f32 = 2.0;\n\nstruct CloudCameraView {\n worldViewProj: mat4x4<f32>,\n lightDir: vec3<f32>,\n lightColor: vec3<f32>,\n cameraPos: vec3<f32>,\n lightViewProj_A: mat4x4<f32>,\n inverseViewProj: mat4x4<f32>,\n lightViewProj_B: mat4x4<f32>,\n lightViewProj_C: mat4x4<f32>,\n lightViewProj_D: mat4x4<f32>,\n splitPlanes: array<vec4<f32>, 4>,\n cascadeCount: f32,\n cascadeBlend: f32,\n depthBias: f32,\n normalBias: f32,\n directionalShadowFilter: vec4<f32>,\n spotLightViewProj: array<mat4x4<f32>, 4>,\n temporalCurrentViewProj: mat4x4<f32>,\n temporalPreviousViewProj: mat4x4<f32>,\n temporalProjection: vec4<f32>,\n temporalPreviousCameraPos: vec4<f32>,\n ssrParams: vec4<f32>,\n};\n\nstruct CloudViewParams {\n layer: vec4<f32>, // baseHeight, thickness, scale, density\n field: vec4<f32>, // coverage, timeSeconds, maxDistance, seed\n wind: vec4<f32>, // xyz m/s\n sunDirection: vec4<f32>,\n sunRadiance: vec4<f32>,\n integration: vec4<u32>, // cacheResolution, viewSteps, solarSteps, reserved\n shadowOrigin: vec4<f32>,\n shadowRight: vec4<f32>,\n shadowUp: vec4<f32>,\n shadowProjection: vec4<f32>, // range, valid, lowSun, texelSize\n temporal: vec4<f32>, // valid, reset, historyWeight, reserved\n};\n\n@group(0) @binding(0) var<uniform> view: CloudCameraView;\n@group(1) @binding(0) var sceneColor: texture_2d<f32>;\n@group(1) @binding(1) var sceneSampler: sampler;\n@group(1) @binding(2) var<uniform> cloud: CloudViewParams;\n@group(1) @binding(3) var sceneDepth: texture_depth_2d;\n@group(1) @binding(4) var depthSampler: sampler;\n@group(1) @binding(5) var previousRadiance: texture_2d<f32>;\n@group(1) @binding(6) var previousTransmittance: texture_2d<f32>;\n@group(1) @binding(7) var previousDepth: texture_2d<f32>;\n@group(1) @binding(8) var<storage, read> densityCache: array<u32>;\n\nstruct CloudViewOut {\n @builtin(position) position: vec4<f32>,\n @location(0) uv: vec2<f32>,\n};\n\nfn cloud_hash3(cell: vec3<i32>, seed: u32) -> f32 {\n var h = bitcast<u32>(cell.x) * 0x45d9f3bu;\n h = (h ^ (bitcast<u32>(cell.y) * 0x119de1f3u)) * 0x45d9f3bu;\n h = (h ^ (bitcast<u32>(cell.z) * 0x3449fu)) * 0x45d9f3bu;\n h = h ^ seed;\n h = (h ^ (h >> 16u)) * 0x45d9f3bu;\n h = (h ^ (h >> 13u)) * 0x27d4eb2du;\n return f32(h ^ (h >> 16u)) / 4294967296.0;\n}\n\nfn cloud_wrap_cell(value: i32, period: i32) -> i32 {\n let wrapped = value % period;\n return select(wrapped, wrapped + period, wrapped < 0);\n}\n\nfn cloud_hash3_periodic(\n cell: vec3<i32>,\n seed: u32,\n periodX: i32,\n periodY: i32,\n periodZ: i32,\n) -> f32 {\n return cloud_hash3(\n vec3<i32>(\n cloud_wrap_cell(cell.x, periodX),\n cloud_wrap_cell(cell.y, periodY),\n cloud_wrap_cell(cell.z, periodZ),\n ),\n seed,\n );\n}\n\nfn cloud_value_noise(\n position: vec3<f32>,\n seed: u32,\n periodX: i32,\n periodY: i32,\n periodZ: i32,\n) -> f32 {\n let cell = vec3<i32>(floor(position));\n let fraction = fract(position);\n let smoothFraction = fraction * fraction * (3.0 - 2.0 * fraction);\n let c000 = cloud_hash3_periodic(cell + vec3<i32>(0, 0, 0), seed, periodX, periodY, periodZ);\n let c100 = cloud_hash3_periodic(cell + vec3<i32>(1, 0, 0), seed, periodX, periodY, periodZ);\n let c010 = cloud_hash3_periodic(cell + vec3<i32>(0, 1, 0), seed, periodX, periodY, periodZ);\n let c110 = cloud_hash3_periodic(cell + vec3<i32>(1, 1, 0), seed, periodX, periodY, periodZ);\n let c001 = cloud_hash3_periodic(cell + vec3<i32>(0, 0, 1), seed, periodX, periodY, periodZ);\n let c101 = cloud_hash3_periodic(cell + vec3<i32>(1, 0, 1), seed, periodX, periodY, periodZ);\n let c011 = cloud_hash3_periodic(cell + vec3<i32>(0, 1, 1), seed, periodX, periodY, periodZ);\n let c111 = cloud_hash3_periodic(cell + vec3<i32>(1, 1, 1), seed, periodX, periodY, periodZ);\n let x00 = mix(c000, c100, smoothFraction.x);\n let x10 = mix(c010, c110, smoothFraction.x);\n let x01 = mix(c001, c101, smoothFraction.x);\n let x11 = mix(c011, c111, smoothFraction.x);\n return mix(mix(x00, x10, smoothFraction.y), mix(x01, x11, smoothFraction.y), smoothFraction.z);\n}\n\nfn cloud_cellular_noise(position: vec3<f32>, seed: u32, periodXZ: i32, periodY: i32) -> f32 {\n let cell = vec3<i32>(floor(position));\n let fraction = fract(position);\n var nearest = 1e9;\n var dz: i32 = -1;\n loop {\n var dy: i32 = -1;\n loop {\n var dx: i32 = -1;\n loop {\n let random = cloud_hash3_periodic(\n cell + vec3<i32>(dx, dy, dz),\n seed ^ 0x9e3779b9u,\n periodXZ,\n periodY,\n periodXZ,\n );\n let point = vec3<f32>(\n f32(dx) + fract(random * 17.0) - fraction.x,\n f32(dy) + fract(random * 31.0) - fraction.y,\n f32(dz) + fract(random * 47.0) - fraction.z,\n );\n nearest = min(nearest, dot(point, point));\n if (dx >= 1) { break; }\n dx = dx + 1;\n }\n if (dy >= 1) { break; }\n dy = dy + 1;\n }\n if (dz >= 1) { break; }\n dz = dz + 1;\n }\n return 1.0 - clamp(sqrt(nearest) * 1.25, 0.0, 1.0);\n}\n\nfn cloud_weather_field(position: vec3<f32>, seed: u32) -> f32 {\n return smoothstep(\n 0.34,\n 0.66,\n cloud_value_noise(\n vec3<f32>(position.x * 2.0, 0.37, position.z * 2.0),\n seed + 17041u,\n 2,\n 1,\n 2,\n ),\n );\n}\n\nfn cloud_formation_field(position: vec3<f32>, seed: u32) -> vec3<f32> {\n let macroWarpX = cloud_value_noise(\n vec3<f32>(position.x * 2.0, position.y * CLOUD_VERTICAL_NOISE_CELLS + 3.0, position.z * 2.0),\n seed + 41023u,\n 2,\n 2,\n 2,\n ) - 0.5;\n let macroWarpZ = cloud_value_noise(\n vec3<f32>(position.x * 2.0 + 5.0, position.y * CLOUD_VERTICAL_NOISE_CELLS - 7.0, position.z * 2.0),\n seed + 41023u,\n 2,\n 2,\n 2,\n ) - 0.5;\n let bodyX = position.x + macroWarpX * 0.3;\n let bodyZ = position.z + macroWarpZ * 0.3;\n var noise = 0.0;\n var weight = 0.0;\n var amplitude = 0.5;\n var frequency = 1.0;\n for (var octave = 0u; octave < 4u; octave = octave + 1u) {\n let tilePeriod = 4.0 * frequency;\n noise = noise + cloud_value_noise(\n vec3<f32>(bodyX * tilePeriod, position.y * frequency * CLOUD_VERTICAL_NOISE_CELLS, bodyZ * tilePeriod),\n seed + octave * 1013u,\n i32(tilePeriod),\n i32(frequency * CLOUD_VERTICAL_NOISE_CELLS),\n i32(tilePeriod),\n ) * amplitude;\n weight = weight + amplitude;\n amplitude = amplitude * 0.4;\n frequency = frequency * 2.0;\n }\n let broad = noise / max(0.0001, weight);\n let cells = cloud_cellular_noise(\n vec3<f32>(bodyX * 4.0, position.y * CLOUD_VERTICAL_NOISE_CELLS, bodyZ * 4.0),\n seed + 5011u,\n 4,\n i32(CLOUD_VERTICAL_NOISE_CELLS),\n );\n // Keep the broad field responsible for the cloud silhouette and use the\n // cellular term as bounded breakup. A broad-dominant mix reads as fewer,\n // wider formations instead of evenly spaced foam balls.\n let base = clamp(broad * 0.85 + cells * 0.15 + 0.15, 0.0, 1.0);\n let weather = cloud_weather_field(position, seed);\n let detailPosition = position * 3.0;\n let warpX = cloud_value_noise(\n vec3<f32>(detailPosition.x * 2.0, detailPosition.y * 2.0 + 11.0, detailPosition.z * 2.0),\n seed + 29011u,\n 2,\n 2,\n 2,\n ) - 0.5;\n let warpZ = cloud_value_noise(\n vec3<f32>(detailPosition.x * 2.0 + 7.0, detailPosition.y * 2.0 - 5.0, detailPosition.z * 2.0),\n seed + 29011u,\n 2,\n 2,\n 2,\n ) - 0.5;\n let erosion = cloud_cellular_noise(\n vec3<f32>(\n (detailPosition.x + warpX * 0.22) * 12.0,\n detailPosition.y * 3.0,\n (detailPosition.z + warpZ * 0.22) * 12.0,\n ),\n seed + 7919u,\n 12,\n 3,\n );\n return vec3<f32>(weather, base, erosion);\n}\n\nfn cloud_height_profile(height: f32, body: f32, weather: f32) -> f32 {\n // A body-dependent crown breaks the fixed horizontal slab silhouette while\n // keeping the profile smooth enough for the bounded ray step budget.\n let lowerEdge = 0.05 + (1.0 - body) * 0.1;\n let crownEdge = min(0.96, 0.6 + body * 0.3 + weather * 0.08);\n let lower = smoothstep(lowerEdge, min(1.0, lowerEdge + 0.12), height);\n let upper = 1.0 - smoothstep(crownEdge, min(1.0, crownEdge + 0.14), height);\n return lower * upper;\n}\n\nfn cloud_compose_density(height: f32, formation: vec3<f32>, coverage: f32) -> f32 {\n let threshold = 1.0 - coverage * (0.45 + formation.x * 0.55);\n let covered = smoothstep(0.0, 0.4, (formation.y - threshold) / max(0.001, 1.0 - threshold));\n let shaped = covered * cloud_height_profile(height, formation.y, formation.x);\n let erosion = (1.0 - formation.z) * 0.18;\n return clamp((shaped - erosion) / (1.0 - erosion), 0.0, 1.0);\n}\n\nfn cloud_analytic_density(position: vec3<f32>) -> f32 {\n let height = (position.y - cloud.layer.x) / max(0.000001, cloud.layer.y);\n if (height <= 0.0 || height >= 1.0 || cloud.layer.w <= 0.0 || cloud.field.x <= 0.0) { return 0.0; }\n let advected = position + cloud.wind.xyz * cloud.field.y;\n let advectedHeight = height +\n cloud.wind.y * cloud.field.y * cloud.layer.z / max(CLOUD_VERTICAL_CELLS, 0.000001);\n let p = vec3<f32>(\n advected.x * cloud.layer.z,\n fract(advectedHeight) * CLOUD_VERTICAL_CELLS,\n advected.z * cloud.layer.z,\n );\n let formation = cloud_formation_field(p, u32(round(cloud.field.w)));\n return cloud_compose_density(height, formation, cloud.field.x) * cloud.layer.w;\n}\n\nfn cloud_cache_byte(index: u32) -> f32 {\n let word = densityCache[index >> 2u];\n let shift = (index & 3u) * 8u;\n return f32((word >> shift) & 255u) / 255.0;\n}\n\nfn cloud_cache_component(plane: u32, index: u32, stride: u32) -> f32 {\n return cloud_cache_byte(plane * stride + index);\n}\n\nfn cloud_cache_trilinear(\n plane: u32,\n resolution: u32,\n x0: u32,\n x1: u32,\n y0: u32,\n y1: u32,\n z0: u32,\n z1: u32,\n fx: f32,\n fy: f32,\n fz: f32,\n) -> f32 {\n let stride = resolution * resolution * resolution;\n let layer = resolution * resolution;\n let c000 = cloud_cache_component(plane, z0 * layer + y0 * resolution + x0, stride);\n let c100 = cloud_cache_component(plane, z0 * layer + y0 * resolution + x1, stride);\n let c010 = cloud_cache_component(plane, z0 * layer + y1 * resolution + x0, stride);\n let c110 = cloud_cache_component(plane, z0 * layer + y1 * resolution + x1, stride);\n let c001 = cloud_cache_component(plane, z1 * layer + y0 * resolution + x0, stride);\n let c101 = cloud_cache_component(plane, z1 * layer + y0 * resolution + x1, stride);\n let c011 = cloud_cache_component(plane, z1 * layer + y1 * resolution + x0, stride);\n let c111 = cloud_cache_component(plane, z1 * layer + y1 * resolution + x1, stride);\n let x00 = mix(c000, c100, fx);\n let x10 = mix(c010, c110, fx);\n let x01 = mix(c001, c101, fx);\n let x11 = mix(c011, c111, fx);\n return mix(mix(x00, x10, fy), mix(x01, x11, fy), fz);\n}\n\nfn cloud_density(position: vec3<f32>) -> f32 {\n let height = (position.y - cloud.layer.x) / max(0.000001, cloud.layer.y);\n if (height <= 0.0 || height >= 1.0 || cloud.layer.w <= 0.0 || cloud.field.x <= 0.0) { return 0.0; }\n let resolution = cloud.integration.x;\n if (resolution < 4u) { return max(cloud_analytic_density(position), 0.0); }\n let periodCoordinate = fract((position.xz + cloud.wind.xz * cloud.field.y) * cloud.layer.z);\n let x = fract(periodCoordinate.x - 0.5 / f32(resolution)) * f32(resolution);\n let z = fract(periodCoordinate.y - 0.5 / f32(resolution)) * f32(resolution);\n let advectedHeight = height +\n cloud.wind.y * cloud.field.y * cloud.layer.z / max(CLOUD_VERTICAL_CELLS, 0.000001);\n let y = fract(advectedHeight - 0.5 / f32(resolution)) * f32(resolution);\n let x0 = u32(floor(x));\n let y0 = u32(floor(y));\n let z0 = u32(floor(z));\n let x1 = (x0 + 1u) % resolution;\n let y1 = (y0 + 1u) % resolution;\n let z1 = (z0 + 1u) % resolution;\n let fx = x - f32(x0);\n let fy = y - f32(y0);\n let fz = z - f32(z0);\n let weather = cloud_cache_trilinear(0u, resolution, x0, x1, y0, y1, z0, z1, fx, fy, fz);\n let body = cloud_cache_trilinear(1u, resolution, x0, x1, y0, y1, z0, z1, fx, fy, fz);\n // Repeat only the independent erosion plane: fine boundary structure with\n // the same eight packed reads and the same cache allocation.\n let detail = fract(vec3<f32>(periodCoordinate.x, advectedHeight, periodCoordinate.y) * 3.0 - vec3<f32>(0.5 / f32(resolution))) * f32(resolution);\n let d0 = vec3<u32>(floor(detail));\n let d1 = (d0 + vec3<u32>(1u)) % vec3<u32>(resolution);\n let df = fract(detail);\n let erosion = cloud_cache_trilinear(2u, resolution, d0.x, d1.x, d0.y, d1.y, d0.z, d1.z, df.x, df.y, df.z);\n return cloud_compose_density(height, vec3<f32>(weather, body, erosion), cloud.field.x) * cloud.layer.w;\n}\n\nfn cloud_layer_interval(origin: vec3<f32>, direction: vec3<f32>, maxDistance: f32) -> vec2<f32> {\n if (abs(direction.y) < 0.000001) {\n if (origin.y < cloud.layer.x || origin.y > cloud.layer.x + cloud.layer.y) {\n return vec2<f32>(1.0, 0.0);\n }\n return vec2<f32>(0.0, maxDistance);\n }\n let lower = (cloud.layer.x - origin.y) / direction.y;\n let upper = (cloud.layer.x + cloud.layer.y - origin.y) / direction.y;\n return vec2<f32>(\n max(0.0, min(lower, upper)),\n min(maxDistance, max(lower, upper)),\n );\n}\n\nfn cloud_solar_transmittance(position: vec3<f32>) -> f32 {\n let sunDirection = normalize(-view.lightDir);\n let solarDistance = select(cloud.field.z, cloud.shadowProjection.x, cloud.shadowProjection.x > 0.0);\n let interval = cloud_layer_interval(position, sunDirection, solarDistance);\n if (interval.y <= interval.x) { return 1.0; }\n let steps = min(cloud.integration.z, 64u);\n let stepLength = (interval.y - interval.x) / max(1.0, f32(steps));\n var opticalDepth = 0.0;\n let solarJitter = cloud_solar_jitter(position);\n for (var index = 0u; index < 64u; index = index + 1u) {\n if (index >= steps) { break; }\n let samplePosition = position + sunDirection * (interval.x + (f32(index) + solarJitter) * stepLength);\n opticalDepth = opticalDepth + cloud_density(samplePosition) * ${CLOUD_EXTINCTION_COEFFICIENT} * stepLength;\n }\n return exp(-max(opticalDepth, 0.0));\n}\n\nfn cloud_henyey_greenstein(cosTheta: f32, g: f32) -> f32 {\n let denominator = max(0.0001, 1.0 + g * g - 2.0 * g * cosTheta);\n return (1.0 - g * g) / (denominator * sqrt(denominator)) * 0.0795774715;\n}\n\nfn cloud_phase(cosTheta: f32) -> f32 {\n // A bounded dual lobe gives a readable forward highlight and a small\n // back-scatter rim without another solar march.\n return cloud_henyey_greenstein(cosTheta, 0.55) * 0.8 +\n cloud_henyey_greenstein(cosTheta, -0.2) * 0.2;\n}\n\n// Reuse the same remaining-path optical depth for two bounded scattering\n// orders. This adds arithmetic only; no extra density or light-ray samples.\nfn cloud_incident_light(solarT: f32, cosTheta: f32, height: f32) -> vec3<f32> {\n let direct = solarT * cloud_phase(cosTheta);\n let multiple = (0.5 * pow(solarT, 0.5) + 0.25 * pow(solarT, 0.25)) * 0.0795774715;\n let skyFill = mix(0.025, 0.075, smoothstep(0.1, 0.85, height));\n // Match volume-integrate: the shared DirectionalLight value uses the\n // unnormalized phase convention. Convert the normalized HG basis once.\n return cloud.sunRadiance.xyz *\n (vec3<f32>((direct + multiple) * 12.5663706144) + vec3<f32>(0.72, 0.84, 1.0) * skyFill);\n}\n\nfn cloud_ray_jitter(pixel: vec2<f32>) -> f32 {\n // A stable per-pixel offset removes view-step contour bands without adding\n // a frame-varying noise source that would fight temporal reprojection.\n return fract(sin(dot(pixel, vec2<f32>(12.9898, 78.233))) * 43758.5453);\n}\n\nfn cloud_solar_jitter(position: vec3<f32>) -> f32 {\n // Dither the light-column samples in world space so low shadow-step\n // profiles do not paint parallel contour bands across cloud bases.\n return fract(sin(dot(position.xz, vec2<f32>(19.193, 47.117))) * 15731.743);\n}\n\nfn reconstruct_world(uv: vec2<f32>, depth: f32) -> vec3<f32> {\n let ndc = vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0);\n let world = view.inverseViewProj * ndc;\n return world.xyz / max(abs(world.w), 0.00001);\n}\n\n@vertex\nfn vs_main(@builtin(vertex_index) index: u32) -> CloudViewOut {\n var positions = array<vec2<f32>, 3>(\n vec2<f32>(-1.0, -1.0),\n vec2<f32>(3.0, -1.0),\n vec2<f32>(-1.0, 3.0),\n );\n var output: CloudViewOut;\n output.position = vec4<f32>(positions[index], 0.0, 1.0);\n // WebGPU clip-space Y grows upward while sampled framebuffer rows and the\n // depth texture use a top-left origin. Keep this one top-left UV for color,\n // depth and inverse-projection reconstruction; flipping only the final\n // color would leave the camera ray and depth cut mirrored.\n output.uv = vec2<f32>(\n positions[index].x * 0.5 + 0.5,\n 1.0 - (positions[index].y * 0.5 + 0.5),\n );\n return output;\n}\n\n@fragment\nfn fs_main(input: CloudViewOut) -> @location(0) vec4<f32> {\n // The shadow producer uses this same production density/cache contract but\n // rasterizes a camera-independent, texel-snapped light-space map. It does\n // not consume scene colour; the generic fullscreen host still supplies the\n // input binding to keep the feature binding ABI single and validated.\n if (cloud.integration.w == 1u) {\n let projection = cloud.shadowProjection;\n if (projection.y < 0.5 || projection.z > 0.5 || projection.x <= 0.0) {\n return vec4<f32>(1.0);\n }\n let offset = (input.uv - vec2<f32>(0.5)) * projection.x;\n let receiver = cloud.shadowOrigin.xyz +\n cloud.shadowRight.xyz * offset.x + cloud.shadowUp.xyz * offset.y;\n let sunDirection = normalize(-view.lightDir);\n let interval = cloud_layer_interval(receiver, sunDirection, projection.x);\n if (interval.y <= interval.x) { return vec4<f32>(1.0); }\n let steps = min(cloud.integration.z, 64u);\n let stepLength = (interval.y - interval.x) / max(1.0, f32(steps));\n var opticalDepth = 0.0;\n var firstHeight = 1.0;\n var lastHeight = 0.0;\n var occupied = false;\n let solarJitter = cloud_solar_jitter(receiver);\n for (var index = 0u; index < 64u; index = index + 1u) {\n if (index >= steps) { break; }\n let samplePosition = receiver + sunDirection *\n (interval.x + (f32(index) + solarJitter) * stepLength);\n let localDensity = cloud_density(samplePosition);\n opticalDepth = opticalDepth + localDensity * ${CLOUD_EXTINCTION_COEFFICIENT} * stepLength;\n if (localDensity > 0.0001) {\n let sampleHeight = clamp(\n (samplePosition.y - cloud.layer.x) / max(0.0001, cloud.layer.y),\n 0.0,\n 1.0,\n );\n if (!occupied) { firstHeight = sampleHeight; }\n lastHeight = sampleHeight;\n occupied = true;\n }\n }\n let transmittance = exp(-max(opticalDepth, 0.0));\n // R stores full-column transmittance. G/B preserve the first/last\n // occupied normalized layer heights so interior samples can estimate the\n // remaining segment without pretending optical depth is uniform through\n // the whole layer. A stores the integrated optical depth and distinguishes\n // an empty projected column from a valid, nearly-clear one.\n return vec4<f32>(\n transmittance,\n select(1.0, firstHeight, occupied),\n select(0.0, lastHeight, occupied),\n select(0.0, opticalDepth, occupied),\n );\n }\n // The shadow producer branch above is per-fragment (its light-space\n // interval depends on the rasterized receiver), so derivative-based\n // sampling here would violate WGSL uniform-control-flow rules. The cloud\n // scene path already owns an explicit level-0 sampler contract.\n // Keep point semantics for the current full-resolution scene path. The\n // half-resolution transport contract is introduced with its own resolve\n // shader so this path retains the established depth convention.\n let depthPixel = vec2<i32>(input.position.xy);\n let depth = textureLoad(sceneDepth, depthPixel, 0);\n let farWorld = reconstruct_world(input.uv, 1.0);\n let sceneWorld = reconstruct_world(input.uv, clamp(depth, 0.0, 1.0));\n let ray = normalize(farWorld - view.cameraPos);\n let rayJitter = cloud_ray_jitter(input.position.xy);\n let sceneDistance = select(cloud.field.z, length(sceneWorld - view.cameraPos), depth < 0.999999);\n let interval = cloud_layer_interval(view.cameraPos, ray, sceneDistance);\n\n // The depth producer shares the same camera ray, interval and density\n // contract as the display path. It writes a cloud representative world\n // position and a validity bit so history remains comparable after camera\n // translation or rotation and never uses an opaque scene distance as a\n // proxy for a participating medium.\n if (cloud.integration.w == 2u) {\n if (interval.y <= interval.x) { return vec4<f32>(sceneWorld, 0.0); }\n let depthSteps = min(cloud.integration.y, 64u);\n let depthStepLength = (interval.y - interval.x) / max(1.0, f32(depthSteps));\n var depthTransmittance = 1.0;\n var weightedDistance = 0.0;\n var opticalWeight = 0.0;\n for (var depthIndex = 0u; depthIndex < 64u; depthIndex = depthIndex + 1u) {\n if (depthIndex >= depthSteps) { break; }\n let sampleDistance = interval.x + (f32(depthIndex) + rayJitter) * depthStepLength;\n let samplePosition = view.cameraPos + ray * sampleDistance;\n let localDensity = cloud_density(samplePosition);\n let localTransmittance = exp(-max(localDensity * ${CLOUD_EXTINCTION_COEFFICIENT} * depthStepLength, 0.0));\n let weight = depthTransmittance * (1.0 - localTransmittance);\n weightedDistance = weightedDistance + sampleDistance * weight;\n opticalWeight = opticalWeight + weight;\n depthTransmittance = depthTransmittance * localTransmittance;\n }\n let hasCloud = opticalWeight > 0.00001;\n let representativeDistance = select(sceneDistance, weightedDistance / opticalWeight, hasCloud);\n let representativeWorld = view.cameraPos + ray * representativeDistance;\n return vec4<f32>(representativeWorld, select(0.0, 1.0, hasCloud));\n }\n\n let scene = textureSampleLevel(sceneColor, sceneSampler, input.uv, 0.0);\n if (interval.y <= interval.x) { return scene; }\n let steps = min(cloud.integration.y, 64u);\n let stepLength = (interval.y - interval.x) / max(1.0, f32(steps));\n var transmittance = 1.0;\n var scattering = vec3<f32>(0.0);\n var weightedDistance = 0.0;\n var opticalWeight = 0.0;\n let sunDirection = normalize(-view.lightDir);\n for (var index = 0u; index < 64u; index = index + 1u) {\n if (index >= steps) { break; }\n let distance = interval.x + (f32(index) + rayJitter) * stepLength;\n let samplePosition = view.cameraPos + ray * distance;\n let localDensity = cloud_density(samplePosition);\n let extinction = localDensity * ${CLOUD_EXTINCTION_COEFFICIENT} * stepLength;\n let localTransmittance = exp(-max(extinction, 0.0));\n let depthWeight = transmittance * (1.0 - localTransmittance);\n weightedDistance = weightedDistance + distance * depthWeight;\n opticalWeight = opticalWeight + depthWeight;\n // Empty samples are common in the separated-cloud field. Avoid a nested\n // solar march for them and stop once the camera path is effectively opaque.\n if (localDensity > 0.0001 && transmittance > 0.01) {\n let solarTransmittance = cloud_solar_transmittance(samplePosition);\n let cloudHeight = clamp(\n (samplePosition.y - cloud.layer.x) / max(0.0001, cloud.layer.y), 0.0, 1.0,\n );\n scattering = scattering + cloud_incident_light(\n solarTransmittance, dot(ray, sunDirection), cloudHeight,\n ) * depthWeight;\n }\n transmittance = transmittance * localTransmittance;\n if (transmittance < 0.01) { break; }\n }\n let hasCloud = opticalWeight > 0.00001;\n let representativeDistance = select(sceneDistance, weightedDistance / opticalWeight, hasCloud);\n let representativeWorld = view.cameraPos + ray * representativeDistance;\n // Wind is an advective coordinate change. Reproject the cloud point into\n // the previous frame's world before applying the previous camera matrix;\n // authored field values remain immutable.\n let windDelta = cloud.wind.xyz * max(0.0, cloud.field.y - cloud.temporal.w);\n // cloud_density evaluates the authored field at position + wind*time.\n // Keeping the same field sample in the previous frame therefore advances\n // the previous world point by the elapsed wind delta as well.\n let previousCloudWorld = representativeWorld + windDelta;\n let previousCloudClip = view.temporalPreviousViewProj * vec4<f32>(previousCloudWorld, 1.0);\n let previousCloudNdc = previousCloudClip.xyz / max(abs(previousCloudClip.w), 0.00001);\n let previousCloudUv = vec2<f32>(\n previousCloudNdc.x * 0.5 + 0.5,\n 1.0 - (previousCloudNdc.y * 0.5 + 0.5),\n );\n let cloudInBounds = all(previousCloudUv >= vec2<f32>(0.0)) && all(previousCloudUv <= vec2<f32>(1.0));\n let cloudHistoryUv = clamp(previousCloudUv, vec2<f32>(0.0), vec2<f32>(1.0));\n let cloudHistoryDepthSample = textureSampleLevel(previousDepth, depthSampler, cloudHistoryUv, 0.0);\n let cloudHistoryWorld = cloudHistoryDepthSample.xyz;\n let previous = textureSampleLevel(previousRadiance, sceneSampler, cloudHistoryUv, 0.0);\n let previousTransport = textureSampleLevel(\n previousTransmittance,\n sceneSampler,\n cloudHistoryUv,\n 0.0,\n );\n let worldTolerance = max(0.05, length(previousCloudWorld - view.cameraPos) * 0.02);\n let depthAccepted = cloudHistoryDepthSample.a > 0.5 &&\n distance(cloudHistoryWorld, previousCloudWorld) <= worldTolerance;\n let accepted =\n hasCloud && cloud.temporal.x > 0.5 && cloud.temporal.y < 0.5 && cloudInBounds &&\n depthAccepted && previousTransport.a > 0.0;\n let historyWeight = select(0.0, clamp(cloud.temporal.z, 0.0, 0.95), accepted);\n let cloudRadiance = mix(scattering, previous.rgb, historyWeight);\n // Preserve scene-linear HDR output for the downstream material lane. The\n // history owner receives cloudRadiance separately through the history pass.\n return vec4<f32>(scene.rgb * transmittance + cloudRadiance, transmittance);\n}\n\n// The light-space shadow producer already paid for a bounded column integral.\n// Reuse that texel for camera samples instead of starting a full solar march\n// for every occupied camera step. Outside the occupied interval the cached\n// full-column transmittance is exact for the projected column. Inside the\n// interval, the cache supplies the stable projection/bounds and a short\n// residual march resolves the non-uniform density that a linear optical-depth\n// interpolation would lose. Invalid/out-of-range projections retain the\n// analytic path as an explicit fallback.\nfn cloud_solar_cached_transmittance(position: vec3<f32>) -> f32 {\n let projection = cloud.shadowProjection;\n if (projection.y < 0.5 || projection.x <= 0.0) {\n return cloud_solar_transmittance(position);\n }\n let relative = position - cloud.shadowOrigin.xyz;\n let uv = vec2<f32>(\n dot(relative, cloud.shadowRight.xyz) / projection.x + 0.5,\n dot(relative, cloud.shadowUp.xyz) / projection.x + 0.5,\n );\n if (any(uv < vec2<f32>(0.0)) || any(uv > vec2<f32>(1.0))) {\n return cloud_solar_transmittance(position);\n }\n let cachedShadow = textureSampleLevel(previousRadiance, sceneSampler, uv, 0.0);\n let cachedOpticalDepth = max(cachedShadow.a, 0.0);\n let layerHeight = clamp(\n (position.y - cloud.layer.x) / max(0.0001, cloud.layer.y),\n 0.0,\n 1.0,\n );\n if (cachedOpticalDepth <= 0.0001) { return 1.0; }\n let firstHeight = clamp(cachedShadow.g, 0.0, 1.0);\n let lastHeight = clamp(cachedShadow.b, 0.0, 1.0);\n let occupiedMin = min(firstHeight, lastHeight);\n let occupiedMax = max(firstHeight, lastHeight);\n let sunDirection = normalize(-view.lightDir);\n // G/B are ordered along the light ray, not necessarily bottom-to-top. Only\n // use the cached full/empty fast paths when the light has enough vertical\n // component to make that ordering meaningful; grazing light stays on the\n // residual path so a low-sun column cannot invert the cache bounds.\n if (abs(sunDirection.y) > 0.2) {\n if (sunDirection.y > 0.0) {\n if (layerHeight <= occupiedMin) { return exp(-cachedOpticalDepth); }\n if (layerHeight >= occupiedMax) { return 1.0; }\n } else {\n if (layerHeight >= occupiedMax) { return exp(-cachedOpticalDepth); }\n if (layerHeight <= occupiedMin) { return 1.0; }\n }\n }\n\n // A short residual march is only paid for samples inside the projected\n // cloud span. Vertical light uses twelve taps, oblique light sixteen, and\n // grazing light up to thirty-two because the same layer projects across a\n // much longer solar segment. This removes the large error caused by\n // assuming optical depth is uniform between the first and last occupied\n // heights while keeping the normal camera path far below a second full\n // solar integration.\n let solarDistance = select(cloud.field.z, projection.x, projection.x > 0.0);\n let interval = cloud_layer_interval(position, sunDirection, solarDistance);\n if (interval.y <= interval.x) { return 1.0; }\n let absLightY = abs(sunDirection.y);\n let directionBudget = select(\n 32u,\n select(16u, 12u, absLightY > 0.5),\n absLightY > 0.2,\n );\n let residualSteps = min(directionBudget, max(8u, cloud.integration.z * 3u));\n let stepLength = (interval.y - interval.x) / max(1.0, f32(residualSteps));\n var opticalDepth = 0.0;\n let solarJitter = cloud_solar_jitter(position);\n for (var index = 0u; index < 32u; index = index + 1u) {\n if (index >= residualSteps) { break; }\n let samplePosition = position + sunDirection *\n (interval.x + (f32(index) + solarJitter) * stepLength);\n opticalDepth = opticalDepth + cloud_density(samplePosition) *\n ${CLOUD_EXTINCTION_COEFFICIENT} * stepLength;\n }\n return exp(-max(opticalDepth, 0.0));\n}\n\nstruct CloudTransportOutput {\n @location(0) radiance: vec4<f32>,\n @location(1) transmittance: vec4<f32>,\n @location(2) depth: vec4<f32>,\n};\n\n// One half-resolution transport pass writes all three reusable cloud fields.\n// The full-resolution resolve below reconstructs colour and applies temporal\n// history; no second full raymarch exists solely to obtain cloud depth.\n@fragment\nfn fs_transport(input: CloudViewOut) -> CloudTransportOutput {\n let depth = textureSampleLevel(sceneDepth, depthSampler, input.uv, 0u);\n let farWorld = reconstruct_world(input.uv, 1.0);\n let sceneWorld = reconstruct_world(input.uv, clamp(depth, 0.0, 1.0));\n let ray = normalize(farWorld - view.cameraPos);\n let rayJitter = cloud_ray_jitter(input.position.xy);\n let sceneDistance = select(cloud.field.z, length(sceneWorld - view.cameraPos), depth < 0.999999);\n let interval = cloud_layer_interval(view.cameraPos, ray, sceneDistance);\n var output: CloudTransportOutput;\n output.radiance = vec4<f32>(0.0, 0.0, 0.0, 0.0);\n output.transmittance = vec4<f32>(1.0, 1.0, 1.0, 1.0);\n output.depth = vec4<f32>(sceneWorld, 0.0);\n if (interval.y <= interval.x) { return output; }\n\n let steps = min(cloud.integration.y, 64u);\n let stepLength = (interval.y - interval.x) / max(1.0, f32(steps));\n var transmittance = 1.0;\n var scattering = vec3<f32>(0.0);\n var weightedDistance = 0.0;\n var opticalWeight = 0.0;\n let sunDirection = normalize(-view.lightDir);\n for (var index = 0u; index < 64u; index = index + 1u) {\n if (index >= steps) { break; }\n let distance = interval.x + (f32(index) + rayJitter) * stepLength;\n let samplePosition = view.cameraPos + ray * distance;\n let localDensity = cloud_density(samplePosition);\n let extinction = localDensity * ${CLOUD_EXTINCTION_COEFFICIENT} * stepLength;\n let localTransmittance = exp(-max(extinction, 0.0));\n let depthWeight = transmittance * (1.0 - localTransmittance);\n weightedDistance = weightedDistance + distance * depthWeight;\n opticalWeight = opticalWeight + depthWeight;\n if (localDensity > 0.0001 && transmittance > 0.01) {\n let solarTransmittance = cloud_solar_cached_transmittance(samplePosition);\n let cloudHeight = clamp(\n (samplePosition.y - cloud.layer.x) / max(0.0001, cloud.layer.y), 0.0, 1.0,\n );\n scattering = scattering + cloud_incident_light(\n solarTransmittance, dot(ray, sunDirection), cloudHeight,\n ) * depthWeight;\n }\n transmittance = transmittance * localTransmittance;\n if (transmittance < 0.01) { break; }\n }\n let hasCloud = opticalWeight > 0.00001;\n let representativeDistance = select(sceneDistance, weightedDistance / max(opticalWeight, 0.00001), hasCloud);\n output.radiance = vec4<f32>(scattering, select(0.0, 1.0, hasCloud));\n output.transmittance = vec4<f32>(transmittance, transmittance, transmittance, 1.0);\n output.depth = vec4<f32>(view.cameraPos + ray * representativeDistance, select(0.0, 1.0, hasCloud));\n return output;\n}\n`;\n\n/** Shared cloud transport module; `fs_transport` is selected by the MRT PSO. */\nexport const CLOUD_TRANSPORT_FULLSCREEN_WGSL = CLOUD_VIEW_FULLSCREEN_WGSL;\n/** Analytic fallback for adapters without a projected cloud-shadow target. */\nexport const CLOUD_TRANSPORT_ANALYTIC_FULLSCREEN_WGSL = CLOUD_VIEW_FULLSCREEN_WGSL.replace(\n 'cloud_solar_cached_transmittance(samplePosition)',\n 'cloud_solar_transmittance(samplePosition)',\n);\n\n/**\n * History writer. It is a separate MRT pass so the cloud composite remains a\n * normal scene-linear color producer while the renderer owns the ping-pong\n * radiance/transmittance/depth attachments and advances them only on submit.\n */\nexport const CLOUD_HISTORY_FULLSCREEN_WGSL = /* wgsl */ `\nstruct CloudCameraView {\n worldViewProj: mat4x4<f32>,\n lightDir: vec3<f32>,\n lightColor: vec3<f32>,\n cameraPos: vec3<f32>,\n lightViewProj_A: mat4x4<f32>,\n inverseViewProj: mat4x4<f32>,\n lightViewProj_B: mat4x4<f32>,\n lightViewProj_C: mat4x4<f32>,\n lightViewProj_D: mat4x4<f32>,\n splitPlanes: array<vec4<f32>, 4>,\n cascadeCount: f32,\n cascadeBlend: f32,\n depthBias: f32,\n normalBias: f32,\n directionalShadowFilter: vec4<f32>,\n spotLightViewProj: array<mat4x4<f32>, 4>,\n temporalCurrentViewProj: mat4x4<f32>,\n temporalPreviousViewProj: mat4x4<f32>,\n temporalProjection: vec4<f32>,\n temporalPreviousCameraPos: vec4<f32>,\n ssrParams: vec4<f32>,\n};\n\nstruct CloudHistoryParams {\n temporal: vec4<f32>, // valid, reset, historyWeight, reserved\n windTime: vec4<f32>, // wind.xyz, elapsed seconds since previous submit\n};\n\n@group(0) @binding(0) var<uniform> view: CloudCameraView;\n@group(1) @binding(0) var currentRadiance: texture_2d<f32>;\n@group(1) @binding(1) var sceneSampler: sampler;\n@group(1) @binding(2) var<uniform> params: CloudHistoryParams;\n@group(1) @binding(3) var sceneDepth: texture_depth_2d;\n@group(1) @binding(4) var depthSampler: sampler;\n@group(1) @binding(5) var currentCloudDepth: texture_2d<f32>;\n@group(1) @binding(6) var sceneBackground: texture_2d<f32>;\n\nstruct CloudHistoryInput {\n @builtin(position) position: vec4<f32>,\n @location(0) uv: vec2<f32>,\n};\n\nstruct CloudHistoryOutput {\n @location(0) radiance: vec4<f32>,\n @location(1) transmittance: vec4<f32>,\n};\n\nfn reconstruct_world(uv: vec2<f32>, depth: f32) -> vec3<f32> {\n let ndc = vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0);\n let world = view.inverseViewProj * ndc;\n return world.xyz / max(abs(world.w), 0.00001);\n}\n\n@vertex\nfn vs_main(@builtin(vertex_index) index: u32) -> CloudHistoryInput {\n var positions = array<vec2<f32>, 3>(\n vec2<f32>(-1.0, -1.0),\n vec2<f32>(3.0, -1.0),\n vec2<f32>(-1.0, 3.0),\n );\n var output: CloudHistoryInput;\n output.position = vec4<f32>(positions[index], 0.0, 1.0);\n output.uv = vec2<f32>(\n positions[index].x * 0.5 + 0.5,\n 1.0 - (positions[index].y * 0.5 + 0.5),\n );\n return output;\n}\n\n@fragment\nfn fs_main(input: CloudHistoryInput) -> CloudHistoryOutput {\n let current = textureSampleLevel(currentRadiance, sceneSampler, input.uv, 0.0);\n let background = textureSampleLevel(sceneBackground, sceneSampler, input.uv, 0.0);\n let cloudDepth = textureSampleLevel(currentCloudDepth, depthSampler, input.uv, 0.0);\n let currentValid = cloudDepth.a > 0.5;\n // currentRadiance is the scene-linear cloud composite. Remove the\n // unchanged scene background before writing history so the persistent owner\n // stores raw cloud radiance only. The view pass is the sole temporal blend\n // owner; blending here as well would accumulate history twice per frame.\n let currentCloudRadiance = max(current.rgb - background.rgb * current.a, vec3<f32>(0.0));\n let currentTransmittance = vec4<f32>(current.a, current.a, current.a, 1.0);\n var output: CloudHistoryOutput;\n output.radiance = vec4<f32>(currentCloudRadiance, select(0.0, 1.0, currentValid));\n output.transmittance = currentTransmittance;\n return output;\n}\n`;\n\n/** Full-resolution resolve for the half-resolution transport MRT. */\nexport const CLOUD_RESOLVE_FULLSCREEN_WGSL = /* wgsl */ `\nstruct CloudCameraView {\n worldViewProj: mat4x4<f32>,\n lightDir: vec3<f32>,\n lightColor: vec3<f32>,\n cameraPos: vec3<f32>,\n lightViewProj_A: mat4x4<f32>,\n inverseViewProj: mat4x4<f32>,\n lightViewProj_B: mat4x4<f32>,\n lightViewProj_C: mat4x4<f32>,\n lightViewProj_D: mat4x4<f32>,\n splitPlanes: array<vec4<f32>, 4>,\n cascadeCount: f32,\n cascadeBlend: f32,\n depthBias: f32,\n normalBias: f32,\n directionalShadowFilter: vec4<f32>,\n spotLightViewProj: array<mat4x4<f32>, 4>,\n temporalCurrentViewProj: mat4x4<f32>,\n temporalPreviousViewProj: mat4x4<f32>,\n temporalProjection: vec4<f32>,\n temporalPreviousCameraPos: vec4<f32>,\n ssrParams: vec4<f32>,\n};\n\nstruct CloudResolveParams {\n layer: vec4<f32>,\n field: vec4<f32>,\n wind: vec4<f32>,\n sunDirection: vec4<f32>,\n sunRadiance: vec4<f32>,\n integration: vec4<u32>,\n shadowOrigin: vec4<f32>,\n shadowRight: vec4<f32>,\n shadowUp: vec4<f32>,\n shadowProjection: vec4<f32>,\n temporal: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> view: CloudCameraView;\n@group(1) @binding(0) var sceneColor: texture_2d<f32>;\n@group(1) @binding(1) var sceneSampler: sampler;\n@group(1) @binding(2) var<uniform> cloud: CloudResolveParams;\n@group(1) @binding(3) var sceneDepth: texture_depth_2d;\n@group(1) @binding(4) var depthSampler: sampler;\n@group(1) @binding(5) var currentRadiance: texture_2d<f32>;\n@group(1) @binding(6) var currentTransmittance: texture_2d<f32>;\n@group(1) @binding(7) var currentDepth: texture_2d<f32>;\n@group(1) @binding(8) var previousRadiance: texture_2d<f32>;\n@group(1) @binding(9) var previousTransmittance: texture_2d<f32>;\n@group(1) @binding(10) var previousDepth: texture_2d<f32>;\n\nstruct CloudResolveInput {\n @builtin(position) position: vec4<f32>,\n @location(0) uv: vec2<f32>,\n};\n\nfn reconstruct_world(uv: vec2<f32>, depth: f32) -> vec3<f32> {\n let ndc = vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0);\n let world = view.inverseViewProj * ndc;\n return world.xyz / max(abs(world.w), 0.00001);\n}\n\n@vertex\nfn vs_main(@builtin(vertex_index) index: u32) -> CloudResolveInput {\n var positions = array<vec2<f32>, 3>(\n vec2<f32>(-1.0, -1.0),\n vec2<f32>(3.0, -1.0),\n vec2<f32>(-1.0, 3.0),\n );\n var output: CloudResolveInput;\n output.position = vec4<f32>(positions[index], 0.0, 1.0);\n output.uv = vec2<f32>(\n positions[index].x * 0.5 + 0.5,\n 1.0 - (positions[index].y * 0.5 + 0.5),\n );\n return output;\n}\n\n@fragment\nfn fs_main(input: CloudResolveInput) -> @location(0) vec4<f32> {\n let scene = textureSampleLevel(sceneColor, sceneSampler, input.uv, 0.0);\n // The resolve owns the full-resolution foreground test. Reject the current\n // low-resolution transport before any history or radiance is composited;\n // gating history alone still lets a newly sampled cloud bleed over geometry.\n let sceneDepthValue = textureLoad(sceneDepth, vec2<i32>(input.position.xy), 0);\n let sceneWorld = reconstruct_world(input.uv, clamp(sceneDepthValue, 0.0, 1.0));\n let sceneDistance = length(sceneWorld - view.cameraPos);\n let transport = textureSampleLevel(currentRadiance, sceneSampler, input.uv, 0.0);\n let transportT = textureSampleLevel(currentTransmittance, sceneSampler, input.uv, 0.0);\n // The transport depth is an rgba16float color attachment, not the scene's\n // depth texture. Sample it with the filtering color sampler; binding the\n // non-filtering scene-depth sampler here makes the shader contract depend on\n // an incompatible sampler/texture pair on strict WebGPU implementations.\n let cloudDepth = textureSampleLevel(currentDepth, sceneSampler, input.uv, 0.0);\n let currentValid = transport.a > 0.5 && cloudDepth.a > 0.5;\n let cloudDistance = length(cloudDepth.xyz - view.cameraPos);\n let foregroundAccepted = sceneDepthValue >= 0.999999 ||\n cloudDistance <= sceneDistance + max(0.05, sceneDistance * 0.01);\n if (!currentValid || !foregroundAccepted) { return scene; }\n\n let previousClip = view.temporalPreviousViewProj * vec4<f32>(\n cloudDepth.xyz + cloud.wind.xyz * max(0.0, cloud.field.y - cloud.temporal.w),\n 1.0,\n );\n let previousNdc = previousClip.xyz / max(abs(previousClip.w), 0.00001);\n let previousUv = vec2<f32>(\n previousNdc.x * 0.5 + 0.5,\n 1.0 - (previousNdc.y * 0.5 + 0.5),\n );\n let inBounds = all(previousUv >= vec2<f32>(0.0)) && all(previousUv <= vec2<f32>(1.0));\n let historyUv = clamp(previousUv, vec2<f32>(0.0), vec2<f32>(1.0));\n let historyDepth = textureSampleLevel(previousDepth, sceneSampler, historyUv, 0.0);\n let previous = textureSampleLevel(previousRadiance, sceneSampler, historyUv, 0.0);\n let previousTransport = textureSampleLevel(previousTransmittance, sceneSampler, historyUv, 0.0);\n let dims = vec2<f32>(textureDimensions(previousRadiance));\n let texel = 1.0 / max(dims, vec2<f32>(1.0));\n // Clamp reprojected history against the current low-resolution transport\n // neighborhood. Using only previous-frame neighbors (and including the\n // previous center in both extrema) is a no-op and lets stale bright cloud\n // pixels leak across a newly exposed edge.\n let c0 = transport.rgb;\n let c1 = textureSampleLevel(currentRadiance, sceneSampler, clamp(input.uv + vec2<f32>(-texel.x, 0.0), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).rgb;\n let c2 = textureSampleLevel(currentRadiance, sceneSampler, clamp(input.uv + vec2<f32>(texel.x, 0.0), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).rgb;\n let c3 = textureSampleLevel(currentRadiance, sceneSampler, clamp(input.uv + vec2<f32>(0.0, -texel.y), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).rgb;\n let c4 = textureSampleLevel(currentRadiance, sceneSampler, clamp(input.uv + vec2<f32>(0.0, texel.y), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).rgb;\n let minRadiance = min(c0, min(min(c1, c2), min(c3, c4)));\n let maxRadiance = max(c0, max(max(c1, c2), max(c3, c4)));\n let t1 = textureSampleLevel(currentTransmittance, sceneSampler, clamp(input.uv + vec2<f32>(-texel.x, 0.0), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).r;\n let t2 = textureSampleLevel(currentTransmittance, sceneSampler, clamp(input.uv + vec2<f32>(texel.x, 0.0), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).r;\n let t3 = textureSampleLevel(currentTransmittance, sceneSampler, clamp(input.uv + vec2<f32>(0.0, -texel.y), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).r;\n let t4 = textureSampleLevel(currentTransmittance, sceneSampler, clamp(input.uv + vec2<f32>(0.0, texel.y), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).r;\n let minTransport = min(transportT.r, min(min(t1, t2), min(t3, t4)));\n let maxTransport = max(transportT.r, max(max(t1, t2), max(t3, t4)));\n let worldTolerance = max(0.05, distance(cloudDepth.xyz, view.cameraPos) * 0.02);\n let depthAccepted = historyDepth.a > 0.5 && distance(historyDepth.xyz, cloudDepth.xyz) <= worldTolerance;\n let accepted = cloud.temporal.x > 0.5 && cloud.temporal.y < 0.5 && inBounds && depthAccepted;\n let historyWeight = select(0.0, clamp(cloud.temporal.z, 0.0, 0.92), accepted);\n let stableHistory = clamp(previous.rgb, minRadiance, maxRadiance);\n let stableTransport = clamp(previousTransport.r, minTransport, maxTransport);\n let radiance = mix(transport.rgb, stableHistory, historyWeight);\n let transmittance = mix(transportT.r, stableTransport, historyWeight);\n return vec4<f32>(scene.rgb * transmittance + radiance, transmittance);\n}\n`;\n\nexport interface CloudLayerFeatureFrame {\n readonly params: ValidatedCloudLayer | undefined;\n readonly cache: CloudDensityCache | undefined;\n readonly sourceKey: string | undefined;\n readonly timeSeconds: number;\n readonly sunDirection: readonly [number, number, number] | undefined;\n readonly sunRadiance: readonly [number, number, number] | undefined;\n readonly shadowProjection: CloudShadowProjection | undefined;\n readonly temporal: CloudTemporalFrame | undefined;\n readonly generation: number;\n readonly inspection: CloudLayerInspection;\n}\n\nexport interface CloudLayerFeatureOptions {\n /** Disable the renderer-owned CloudLayer projection while retaining the component. */\n readonly enabled?: boolean;\n}\n\nfunction makeCloudViewParams(\n frame: CloudLayerFeatureFrame,\n cache: CloudDensityCache,\n mode: 0 | 1 | 2 = 0,\n): Uint8Array {\n const params = new ArrayBuffer(CLOUD_VIEW_PARAMS_BYTES);\n const floats = new Float32Array(params);\n const integers = new Uint32Array(params);\n const profile = CLOUD_QUALITY_PROFILES[frame.params?.quality ?? 'medium'];\n const authored = frame.params;\n floats[0] = authored?.baseHeight ?? 0;\n floats[1] = authored?.thickness ?? 1;\n floats[2] = authored?.scale ?? 1;\n floats[3] = authored?.density ?? 0;\n floats[4] = authored?.coverage ?? 1;\n floats[5] = frame.timeSeconds;\n floats[6] =\n mode === 1\n ? (authored?.shadowRange ?? 0)\n : cloudViewDistanceForQuality(authored?.quality ?? 'medium');\n floats[7] = authored?.seed ?? 0;\n floats[8] = authored?.wind[0] ?? 0;\n floats[9] = authored?.wind[1] ?? 0;\n floats[10] = authored?.wind[2] ?? 0;\n floats[12] = frame.sunDirection?.[0] ?? 0;\n floats[13] = frame.sunDirection?.[1] ?? -1;\n floats[14] = frame.sunDirection?.[2] ?? 0;\n floats[15] = 0.2;\n floats[16] = frame.sunRadiance?.[0] ?? 0;\n floats[17] = frame.sunRadiance?.[1] ?? 0;\n floats[18] = frame.sunRadiance?.[2] ?? 0;\n integers[20] = cache.resolution;\n integers[21] = Math.max(1, Math.min(64, Math.floor(profile.viewSteps)));\n integers[22] = Math.max(1, Math.min(64, Math.floor(profile.shadowSteps)));\n integers[23] = mode;\n const projection = frame.shadowProjection;\n if (projection !== undefined) {\n floats[24] = projection.origin[0];\n floats[25] = projection.origin[1];\n floats[26] = projection.origin[2];\n floats[28] = projection.right[0];\n floats[29] = projection.right[1];\n floats[30] = projection.right[2];\n floats[32] = projection.up[0];\n floats[33] = projection.up[1];\n floats[34] = projection.up[2];\n floats[36] = projection.range;\n floats[37] = projection.lowSun ? 0 : 1;\n floats[38] = projection.lowSun ? 1 : 0;\n floats[39] = projection.texelSize;\n }\n const temporal = frame.temporal;\n floats[40] = temporal !== undefined && temporal.reset === false ? 1 : 0;\n floats[41] = temporal?.reset === true ? 1 : 0;\n floats[42] = temporal === undefined ? 0 : profile.historyWeight;\n // The history entry is the last successfully submitted signature. Carry its\n // timestamp so the shader can advect the representative cloud point by the\n // exact elapsed time during reprojection.\n floats[43] = temporal?.history?.temporal.timeSeconds ?? frame.timeSeconds;\n return new Uint8Array(params);\n}\n\nfunction planCloudDensity(\n frame: CloudLayerFeatureFrame,\n packedCache: Uint32Array,\n context: RenderFeaturePlanContext,\n): RenderFeaturePlan {\n const cacheCount = packedCache.length;\n const params = new Uint32Array([cacheCount]);\n const inputTarget = context.targets.find((target) => target.name === 'motion-input');\n const outputTarget = context.targets.find((target) => target.name === 'motion-output');\n const historyRadiancePrevious = context.targets.find(\n (target) => target.name === 'cloud-history-radiance-previous',\n );\n const historyTransmittancePrevious = context.targets.find(\n (target) => target.name === 'cloud-history-transmittance-previous',\n );\n const historyDepthPrevious = context.targets.find(\n (target) => target.name === 'cloud-history-depth-previous',\n );\n const historyRadianceCurrent = context.targets.find(\n (target) => target.name === 'cloud-history-radiance-current',\n );\n const historyTransmittanceCurrent = context.targets.find(\n (target) => target.name === 'cloud-history-transmittance-current',\n );\n const historyDepthCurrent = context.targets.find(\n (target) => target.name === 'cloud-history-depth-current',\n );\n const hasHistoryTargets =\n historyRadiancePrevious !== undefined &&\n historyTransmittancePrevious !== undefined &&\n historyDepthPrevious !== undefined &&\n historyRadianceCurrent !== undefined &&\n historyTransmittanceCurrent !== undefined &&\n historyDepthCurrent !== undefined;\n const shadowTarget = context.targets.find((target) => target.name === 'cloud-shadow');\n const canShadow =\n shadowTarget !== undefined &&\n shadowTarget.sampleCount === 1 &&\n frame.shadowProjection !== undefined &&\n hasHistoryTargets;\n const canCompose =\n inputTarget !== undefined &&\n outputTarget !== undefined &&\n inputTarget.sampleCount === 1 &&\n outputTarget.sampleCount === 1 &&\n hasHistoryTargets;\n const transportReads = ['motion-input', { key: 'depth', sampleType: 'depth' as const }] as const;\n const transportCacheReads = [\n 'motion-input',\n 'cloud-shadow',\n { key: 'depth', sampleType: 'depth' as const },\n ] as const;\n const historyReads = [\n 'motion-input',\n 'cloud-history-radiance-previous',\n 'cloud-history-transmittance-previous',\n 'cloud-history-depth-previous',\n { key: 'depth', sampleType: 'depth' as const },\n ] as const;\n const historyAdditionalTextures = [\n 'cloud-history-radiance-previous',\n 'cloud-history-transmittance-previous',\n 'cloud-history-depth-previous',\n ] as const;\n const viewParams = makeCloudViewParams(frame, frame.cache as CloudDensityCache);\n const shadowParams = canShadow\n ? makeCloudViewParams(frame, frame.cache as CloudDensityCache, 1)\n : undefined;\n const transportUsesShadowCache = canCompose && canShadow;\n return {\n resources: [\n {\n kind: 'compute-program',\n name: CLOUD_LAYER_DENSITY_PROGRAM,\n program: {\n wgsl: CLOUD_DENSITY_COMPUTE_WGSL,\n entryPoints: ['cloud_density_cache'],\n bindings: [\n {\n label: 'forgeax.cloud-layer.cache',\n entries: [\n { binding: 0, visibility: COMPUTE_STAGE, buffer: { type: 'read-only-storage' } },\n { binding: 1, visibility: COMPUTE_STAGE, buffer: { type: 'storage' } },\n { binding: 2, visibility: COMPUTE_STAGE, buffer: { type: 'uniform' } },\n ],\n },\n ],\n },\n },\n {\n kind: 'buffer',\n name: CLOUD_LAYER_DENSITY_CACHE,\n size: packedCache.byteLength,\n usage: ['storage', 'copy-src'],\n data: packedCache,\n },\n {\n kind: 'buffer',\n name: CLOUD_LAYER_DENSITY_OUTPUT,\n size: packedCache.byteLength,\n usage: ['storage', 'copy-src'],\n },\n {\n kind: 'buffer',\n name: 'cloud-layer-density-params',\n size: params.byteLength,\n usage: ['uniform'],\n data: params,\n },\n {\n kind: 'compute-bindings',\n name: CLOUD_LAYER_DENSITY_BINDINGS,\n program: CLOUD_LAYER_DENSITY_PROGRAM,\n entries: [\n { binding: 0, resource: CLOUD_LAYER_DENSITY_CACHE },\n { binding: 1, resource: CLOUD_LAYER_DENSITY_OUTPUT },\n { binding: 2, resource: 'cloud-layer-density-params' },\n ],\n },\n {\n kind: 'fullscreen-program',\n name: 'cloud-layer-view',\n source: CLOUD_VIEW_FULLSCREEN_WGSL,\n usesView: true,\n storageBindings: [8],\n reads: historyReads,\n params: {\n byteSize: viewParams.byteLength,\n defaultValue: viewParams,\n },\n },\n ...(shadowParams === undefined\n ? []\n : [\n {\n kind: 'fullscreen-program' as const,\n name: 'cloud-layer-shadow',\n source: CLOUD_VIEW_FULLSCREEN_WGSL,\n usesView: true,\n storageBindings: [8],\n reads: historyReads,\n params: {\n byteSize: shadowParams.byteLength,\n defaultValue: shadowParams,\n },\n },\n ]),\n ...(canCompose\n ? [\n {\n kind: 'fullscreen-program' as const,\n name: 'cloud-layer-transport',\n source: transportUsesShadowCache\n ? CLOUD_TRANSPORT_FULLSCREEN_WGSL\n : CLOUD_TRANSPORT_ANALYTIC_FULLSCREEN_WGSL,\n fragmentEntryPoint: 'fs_transport',\n usesView: true,\n storageBindings: [8],\n reads: transportUsesShadowCache ? transportCacheReads : transportReads,\n params: {\n byteSize: viewParams.byteLength,\n defaultValue: viewParams,\n },\n },\n {\n kind: 'fullscreen-program' as const,\n name: 'cloud-layer-resolve',\n source: CLOUD_RESOLVE_FULLSCREEN_WGSL,\n usesView: true,\n reads: [\n 'motion-input',\n 'cloud-history-radiance-current',\n 'cloud-history-transmittance-current',\n 'cloud-history-depth-current',\n 'cloud-history-radiance-previous',\n 'cloud-history-transmittance-previous',\n 'cloud-history-depth-previous',\n { key: 'depth', sampleType: 'depth' as const },\n ],\n params: {\n byteSize: viewParams.byteLength,\n defaultValue: viewParams,\n },\n },\n ]\n : []),\n ...(canCompose\n ? [\n {\n kind: 'graphics-program' as const,\n name: 'cloud-layer-transport-pipeline',\n program: {\n shader: 'cloud-layer-transport',\n vertexLayout: 'none',\n colorFormats: [\n historyRadianceCurrent.format,\n historyTransmittanceCurrent.format,\n historyDepthCurrent.format,\n ],\n sampleCount: 1 as const,\n renderState: {\n depthWriteEnabled: false,\n depthCompare: 'always' as const,\n },\n },\n },\n {\n kind: 'graphics-bindings' as const,\n name: 'cloud-layer-transport-view-bindings',\n program: 'cloud-layer-transport-pipeline',\n values: { group: 0, view: true },\n },\n {\n kind: 'graphics-bindings' as const,\n name: 'cloud-layer-transport-bindings',\n program: 'cloud-layer-transport-pipeline',\n values: {\n group: 1,\n fullscreen: true,\n shader: 'cloud-layer-transport',\n input: 'motion-input',\n depth: 'depth',\n additionalTextures: transportUsesShadowCache ? ['cloud-shadow'] : [],\n storageBuffers: [CLOUD_LAYER_DENSITY_OUTPUT],\n },\n logicalTargets: { input: 'motion-input' },\n },\n {\n kind: 'graphics-program' as const,\n name: 'cloud-layer-resolve-pipeline',\n program: {\n shader: 'cloud-layer-resolve',\n vertexLayout: 'none',\n colorFormats: [outputTarget.format],\n sampleCount: 1 as const,\n renderState: {\n depthWriteEnabled: false,\n depthCompare: 'always' as const,\n },\n },\n },\n {\n kind: 'graphics-bindings' as const,\n name: 'cloud-layer-resolve-view-bindings',\n program: 'cloud-layer-resolve-pipeline',\n values: { group: 0, view: true },\n },\n {\n kind: 'graphics-bindings' as const,\n name: 'cloud-layer-resolve-bindings',\n program: 'cloud-layer-resolve-pipeline',\n values: {\n group: 1,\n fullscreen: true,\n shader: 'cloud-layer-resolve',\n input: 'motion-input',\n depth: 'depth',\n additionalTextures: [\n 'cloud-history-radiance-current',\n 'cloud-history-transmittance-current',\n 'cloud-history-depth-current',\n 'cloud-history-radiance-previous',\n 'cloud-history-transmittance-previous',\n 'cloud-history-depth-previous',\n ],\n },\n },\n ]\n : []),\n ...(canShadow\n ? [\n {\n kind: 'graphics-program' as const,\n name: 'cloud-layer-shadow-pipeline',\n program: {\n shader: 'cloud-layer-shadow',\n vertexLayout: 'none',\n colorFormats: [shadowTarget.format],\n sampleCount: 1 as const,\n renderState: {\n depthWriteEnabled: false,\n depthCompare: 'always' as const,\n blend: {\n color: {\n srcFactor: 'one' as const,\n dstFactor: 'zero' as const,\n operation: 'add' as const,\n },\n alpha: {\n srcFactor: 'one' as const,\n dstFactor: 'zero' as const,\n operation: 'add' as const,\n },\n },\n },\n },\n },\n {\n kind: 'graphics-bindings' as const,\n name: 'cloud-layer-shadow-view-bindings',\n program: 'cloud-layer-shadow-pipeline',\n values: { group: 0, view: true },\n },\n {\n kind: 'graphics-bindings' as const,\n name: 'cloud-layer-shadow-bindings',\n program: 'cloud-layer-shadow-pipeline',\n values: {\n group: 1,\n fullscreen: true,\n shader: 'cloud-layer-shadow',\n input: false,\n depth: 'depth',\n // The shadow branch's WGSL keeps the shared depth binding\n // shape, but its light-space path never samples scene depth.\n // Bind the renderer-owned far-depth fallback instead of\n // introducing a read-before-main graph dependency.\n depthFallback: true,\n additionalTextures: historyAdditionalTextures,\n storageBuffers: [CLOUD_LAYER_DENSITY_OUTPUT],\n },\n },\n ]\n : []),\n ],\n passes:\n context.caps.compute && context.caps.storageBuffer\n ? [\n {\n kind: 'compute' as const,\n name: 'cloud-layer-density-cache',\n program: CLOUD_LAYER_DENSITY_PROGRAM,\n bindings: CLOUD_LAYER_DENSITY_BINDINGS,\n dispatches: [\n {\n kind: 'direct' as const,\n entryPoint: 'cloud_density_cache',\n workgroups: [Math.max(1, Math.ceil(cacheCount / CLOUD_WORKGROUP_SIZE))],\n },\n ],\n },\n ...(canShadow\n ? [\n {\n kind: 'raster' as const,\n name: 'cloud-layer-shadow',\n colorAttachments: [\n {\n target: 'cloud-shadow',\n loadOp: 'clear' as const,\n storeOp: 'store' as const,\n },\n ],\n sampledTargets: [\n 'cloud-history-radiance-previous',\n 'cloud-history-transmittance-previous',\n 'cloud-history-depth-previous',\n ],\n draws: [\n {\n program: 'cloud-layer-shadow-pipeline',\n bindings: [\n 'cloud-layer-shadow-view-bindings',\n 'cloud-layer-shadow-bindings',\n ],\n vertexData: [],\n vertexLayout: 'none' as const,\n draw: { kind: 'draw' as const, vertexCount: 3, instanceCount: 1 },\n },\n ],\n },\n ]\n : []),\n ...(canCompose\n ? [\n {\n kind: 'raster' as const,\n name: 'cloud-layer-transport',\n colorAttachments: [\n {\n target: 'cloud-history-radiance-current',\n loadOp: 'clear' as const,\n storeOp: 'store' as const,\n },\n {\n target: 'cloud-history-transmittance-current',\n loadOp: 'clear' as const,\n storeOp: 'store' as const,\n },\n {\n target: 'cloud-history-depth-current',\n loadOp: 'clear' as const,\n storeOp: 'store' as const,\n },\n ],\n sampledTargets: [\n 'motion-input',\n 'depth',\n ...(transportUsesShadowCache ? ['cloud-shadow'] : []),\n ],\n draws: [\n {\n program: 'cloud-layer-transport-pipeline',\n bindings: [\n 'cloud-layer-transport-view-bindings',\n 'cloud-layer-transport-bindings',\n ],\n vertexData: [],\n vertexLayout: 'none' as const,\n draw: { kind: 'draw' as const, vertexCount: 3, instanceCount: 1 },\n },\n ],\n },\n {\n kind: 'raster' as const,\n name: 'cloud-layer-resolve',\n colorAttachments: [\n {\n target: 'motion-output',\n loadOp: 'clear' as const,\n storeOp: 'store' as const,\n },\n ],\n sampledTargets: [\n 'motion-input',\n 'depth',\n 'cloud-history-radiance-current',\n 'cloud-history-transmittance-current',\n 'cloud-history-depth-current',\n 'cloud-history-radiance-previous',\n 'cloud-history-transmittance-previous',\n 'cloud-history-depth-previous',\n ],\n draws: [\n {\n program: 'cloud-layer-resolve-pipeline',\n bindings: [\n 'cloud-layer-resolve-view-bindings',\n 'cloud-layer-resolve-bindings',\n ],\n vertexData: [],\n vertexLayout: 'none' as const,\n draw: { kind: 'draw' as const, vertexCount: 3, instanceCount: 1 },\n },\n ],\n },\n ]\n : []),\n ]\n : [],\n };\n}\n\n/**\n * Renderer-installed cloud producer. Authoring is read once from World at\n * extraction; resource preparation, graph ordering and retirement stay with\n * RenderFeatureHost.\n */\nexport function createCloudLayerFeature(\n options: CloudLayerFeatureOptions = {},\n): RenderFeature<CloudLayerFeatureFrame> {\n let cachedSourceKey: string | undefined;\n let cached: CloudDensityCache | undefined;\n let packedCache: Uint32Array | undefined;\n let generation = 0;\n const histories = new CloudHistoryStore();\n let temporalResetCount = 0;\n let lastTemporalReset: CloudTemporalFrame['reasons'][number] | undefined;\n return Object.freeze({\n identity: CLOUD_LAYER_FEATURE_IDENTITY,\n placement: 'scene' as const,\n requiredCapabilities: ['compute', 'storageBuffer', 'rgba16floatRenderable'] as const,\n // Cloud programs are generated by the feature and have no user-authored\n // manifest entry to await. Use the immediate module path so first-frame\n // feature admission does not publish a transient pending-shader failure;\n // pipeline creation remains the validation boundary for this WGSL.\n shaderModuleMode: 'immediate' as const,\n extract: (\n context: RenderFeatureExtractContext,\n ): Result<CloudLayerFeatureFrame, RenderError> => {\n if (options.enabled === false) {\n histories.reset();\n return ok({\n params: undefined,\n cache: undefined,\n sourceKey: undefined,\n timeSeconds: 0,\n sunDirection: undefined,\n sunRadiance: undefined,\n shadowProjection: undefined,\n temporal: undefined,\n generation,\n inspection: inspectCloudLayer({ authored: false }),\n });\n }\n const world = context.worlds[context.owner];\n if (world === undefined) {\n histories.reset();\n return ok({\n params: undefined,\n cache: undefined,\n sourceKey: undefined,\n timeSeconds: 0,\n sunDirection: undefined,\n sunRadiance: undefined,\n shadowProjection: undefined,\n temporal: undefined,\n generation,\n inspection: inspectCloudLayer({ authored: false }),\n });\n }\n // The normal RenderSystem extract owns World reads and selected-sun\n // resolution. Direct feature probes must provide the same frame facts;\n // this keeps the feature from growing a detached authoring callback or\n // a second per-feature ECS registry.\n const cloud = context.frame?.cloudLayer;\n const capability =\n context.caps === undefined ? undefined : cloudCapabilitiesFromRhi(context.caps);\n if (cloud === undefined) {\n histories.reset();\n return ok({\n params: undefined,\n cache: undefined,\n sourceKey: undefined,\n timeSeconds: 0,\n sunDirection: undefined,\n sunRadiance: undefined,\n shadowProjection: undefined,\n temporal: undefined,\n generation,\n inspection: inspectCloudLayer({\n authored: false,\n ...(capability === undefined ? {} : { capability }),\n }),\n });\n }\n const formationKey = cloudLayerFormationKey(cloud.params);\n if (cached === undefined || cachedSourceKey !== formationKey) {\n cached = buildCloudDensityCache(cloud.params);\n packedCache = packCloudDensityCache(cached);\n cachedSourceKey = formationKey;\n generation += 1;\n }\n const view = context.frame?.view;\n const shadowProjection =\n view === undefined || cloud.sunDirection === undefined\n ? undefined\n : createCloudShadowProjection({\n center: view.shadowAnchor ?? view.cameraPosition,\n sunDirection: cloud.sunDirection,\n range: cloud.params.shadowRange,\n resolution: cloudShadowResolutionForQuality(cloud.params.quality),\n });\n const temporalSignature: CloudTemporalSignature | undefined =\n view === undefined\n ? undefined\n : {\n sourceKey: cloud.sourceKey,\n viewId: view.identity,\n authoringGeneration: generation,\n cloudShadowRevision: shadowProjection?.revision ?? 0,\n cameraRevision: view.cameraRevision,\n deviceGeneration: view.deviceGeneration,\n width: view.width,\n height: view.height,\n timeSeconds: cloud.worldTimeSeconds,\n quality: cloud.params.quality,\n ...(view.sceneDepthVersion === undefined\n ? {}\n : { sceneDepthVersion: view.sceneDepthVersion }),\n };\n const temporal =\n temporalSignature === undefined\n ? undefined\n : (() => {\n const decision = histories.begin(temporalSignature, {\n ...(view?.cameraCut === undefined ? {} : { cameraCut: view.cameraCut }),\n ...(view?.recovery === undefined ? {} : { recovery: view.recovery }),\n });\n const history =\n decision.history ?? createCloudHistory(temporalSignature, generation, false);\n return Object.freeze({\n signature: temporalSignature,\n history,\n reset: decision.reset,\n reasons: decision.reasons,\n });\n })();\n const resourceFacts = inspectCloudLayerResources({\n generation,\n cache: cached,\n ...(shadowProjection === undefined ? {} : { shadow: shadowProjection }),\n ...(temporal?.history === undefined ? {} : { history: temporal.history }),\n });\n const temporalReset = temporal?.reasons.at(-1);\n if (temporal?.reset === true) temporalResetCount += 1;\n if (temporalReset !== undefined) lastTemporalReset = temporalReset;\n return ok({\n params: cloud.params,\n cache: cached,\n sourceKey: cloud.sourceKey,\n timeSeconds: cloud.worldTimeSeconds,\n sunDirection: cloud.sunDirection,\n sunRadiance: cloud.sunRadiance,\n shadowProjection,\n temporal,\n generation,\n inspection: inspectCloudLayer({\n authored: true,\n sourceKey: cloud.sourceKey,\n generation,\n resourceFacts,\n ...(shadowProjection === undefined ? {} : { shadowRevision: shadowProjection.revision }),\n ...(temporal === undefined\n ? {}\n : {\n temporalResets: temporalResetCount,\n ...(lastTemporalReset === undefined ? {} : { lastTemporalReset }),\n }),\n ...(capability === undefined ? {} : { capability }),\n budget: {\n quality: cloud.params.quality,\n reason:\n 'physical GPU timing and residency receipts are unavailable until a prepared adapter submits them',\n },\n }),\n });\n },\n onFrameSubmitted: (frame: CloudLayerFeatureFrame) => {\n if (frame.temporal?.history !== undefined) {\n // Advance the metadata timestamp only after submit. The next frame's\n // GPU reprojection then receives the elapsed time since this exact\n // submitted signature, while an aborted frame keeps the old entry.\n histories.commit(\n frame.temporal.signature,\n createCloudHistory(frame.temporal.signature, frame.generation, true),\n );\n }\n },\n onFrameAborted: (frame: CloudLayerFeatureFrame) => {\n // A reset candidate is committed only after queue submission. The store\n // still contains the previous entry while this frame is rejected.\n void frame;\n },\n plan: (\n frame: CloudLayerFeatureFrame,\n context: RenderFeaturePlanContext,\n ): Result<RenderFeaturePlan, RenderError> => {\n if (frame.cache === undefined || packedCache === undefined || frame.params === undefined) {\n return ok({ resources: [], passes: [] });\n }\n return ok(planCloudDensity(frame, packedCache, context));\n },\n });\n}\n","import type { RhiCaps } from '@forgeax/engine-rhi';\nimport type { MaterialProgramAbi, MaterialSurfacePassKind } from '@forgeax/engine-types';\nimport { err, ok, type Result } from '@forgeax/engine-types';\n\nexport type SurfaceGpuCapability = 'compute' | 'storageBuffer' | 'indirectDrawing';\nexport type SurfaceGpuFallbackReason = SurfaceGpuCapability;\n\nexport type SurfaceGpuSubmissionErrorCode =\n | 'surface-abi-missing'\n | 'surface-pass-missing'\n | 'surface-producer-not-ready'\n | 'surface-generation-stale';\n\nexport interface SurfaceGpuSubmissionError {\n readonly code: SurfaceGpuSubmissionErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly pass: MaterialSurfacePassKind;\n readonly owner: 'surface-producer' | 'render-scene' | 'render-generation';\n readonly actual?: unknown;\n}\n\nexport interface SurfaceGpuPassAdmission {\n readonly pass: MaterialSurfacePassKind;\n readonly lane: 'gpu-driven' | 'direct';\n readonly reason?: SurfaceGpuFallbackReason;\n}\n\nexport interface SurfaceGpuSubmissionAdmission {\n readonly model: 'single-layer-medium';\n readonly lane: 'gpu-driven' | 'direct';\n readonly passes: readonly [SurfaceGpuPassAdmission, SurfaceGpuPassAdmission];\n readonly deviceGeneration: number;\n}\n\nexport interface SurfaceGpuSubmissionInput {\n readonly abi: MaterialProgramAbi;\n readonly caps: Pick<RhiCaps, 'compute' | 'storageBuffer' | 'indirectDrawing'>;\n readonly sceneIndexReady: boolean;\n readonly resourcesReady: boolean;\n readonly dynamicInputReady: boolean;\n readonly deviceGeneration: number;\n readonly preparedDeviceGeneration: number;\n}\n\nconst ERROR_POLICY: Readonly<\n Record<SurfaceGpuSubmissionErrorCode, { readonly expected: string; readonly hint: string }>\n> = {\n 'surface-abi-missing': {\n expected: 'a producer-published single-layer-medium ABI is present',\n hint: 'compose, reflect, and publish the Surface model before preparing the draw',\n },\n 'surface-pass-missing': {\n expected: 'the published model contains both nearest-layer and color passes',\n hint: 'recook the complete model publication; do not synthesize a missing pass',\n },\n 'surface-producer-not-ready': {\n expected: 'scene-index, resources, and dynamic input facts are ready for the published model',\n hint: 'repair the owning producer publication and retry; capability fallback does not cover stale assets',\n },\n 'surface-generation-stale': {\n expected: 'prepared Surface facts belong to the current device generation',\n hint: 'rebuild the prepared surface resources for the current device generation',\n },\n};\n\nfunction failure(\n code: SurfaceGpuSubmissionErrorCode,\n pass: MaterialSurfacePassKind,\n owner: SurfaceGpuSubmissionError['owner'],\n actual?: unknown,\n): SurfaceGpuSubmissionError {\n return {\n code,\n expected: ERROR_POLICY[code].expected,\n hint: ERROR_POLICY[code].hint,\n pass,\n owner,\n ...(actual === undefined ? {} : { actual }),\n };\n}\n\nfunction capabilityFallback(\n caps: SurfaceGpuSubmissionInput['caps'],\n): SurfaceGpuFallbackReason | undefined {\n if (!caps.compute) return 'compute';\n if (!caps.storageBuffer) return 'storageBuffer';\n if (!caps.indirectDrawing) return 'indirectDrawing';\n return undefined;\n}\n\n/**\n * Admit the two Surface passes together. Capability fallback is explicit and\n * symmetric; a missing promised publication is a producer error and never a\n * silent direct fallback.\n */\nexport function admitSingleLayerMediumSubmission(\n input: SurfaceGpuSubmissionInput,\n): Result<SurfaceGpuSubmissionAdmission, SurfaceGpuSubmissionError> {\n const firstPass: MaterialSurfacePassKind = 'nearest-layer';\n const surface = input.abi.surface;\n if (surface === undefined || surface.model !== 'single-layer-medium') {\n return err(failure('surface-abi-missing', firstPass, 'surface-producer', surface));\n }\n if (!surface.passes.includes('nearest-layer') || !surface.passes.includes('color')) {\n return err(failure('surface-pass-missing', firstPass, 'surface-producer', surface.passes));\n }\n if (input.deviceGeneration !== input.preparedDeviceGeneration) {\n return err(\n failure('surface-generation-stale', firstPass, 'render-generation', {\n deviceGeneration: input.deviceGeneration,\n preparedDeviceGeneration: input.preparedDeviceGeneration,\n }),\n );\n }\n const dynamicRequired = surface.dynamicInput !== undefined;\n if (\n !input.sceneIndexReady ||\n !input.resourcesReady ||\n (dynamicRequired && !input.dynamicInputReady)\n ) {\n return err(\n failure('surface-producer-not-ready', firstPass, 'surface-producer', {\n sceneIndexReady: input.sceneIndexReady,\n resourcesReady: input.resourcesReady,\n dynamicInputReady: input.dynamicInputReady,\n }),\n );\n }\n const fallback = capabilityFallback(input.caps);\n const admitted: [SurfaceGpuPassAdmission, SurfaceGpuPassAdmission] =\n fallback === undefined\n ? [\n { pass: firstPass, lane: 'gpu-driven' },\n { pass: 'color', lane: 'gpu-driven' },\n ]\n : [\n { pass: firstPass, lane: 'direct', reason: fallback },\n { pass: 'color', lane: 'direct', reason: fallback },\n ];\n return ok({\n model: 'single-layer-medium',\n lane: fallback === undefined ? 'gpu-driven' : 'direct',\n passes: admitted,\n deviceGeneration: input.deviceGeneration,\n });\n}\n","import { err, type MaterialAsset, type MeshAsset, ok, type Result } from '@forgeax/engine-types';\nimport { type PointShape, PointShapeValue, pointShapeFromU32 } from '../components/points';\nimport type {\n PointsLinesBudgetExceededError,\n PointsLinesInvalidStyleError,\n PointsLinesMaterialUnsupportedError,\n PointsLinesStyleUnsupportedError,\n PointsLinesTopologyMismatchError,\n} from '../errors/render';\nimport {\n PointsLinesBudgetExceededError as BudgetError,\n PointsLinesInvalidStyleError as InvalidStyleError,\n PointsLinesMaterialUnsupportedError as MaterialError,\n PointsLinesStyleUnsupportedError as StyleError,\n PointsLinesTopologyMismatchError as TopologyError,\n} from '../errors/render';\n\nexport interface PointsStyleInput {\n readonly sizePx?: number;\n readonly shape?: number;\n}\n\nexport interface LinesStyleInput {\n readonly widthPx?: number;\n}\n\nexport interface PointsLinesAdmissionLimits {\n readonly maxPoints?: number;\n readonly maxSegments?: number;\n}\n\nexport interface PointsLinesAdmissionInput {\n readonly entity: number;\n readonly points?: PointsStyleInput;\n readonly lines?: LinesStyleInput;\n readonly mesh: MeshAsset;\n readonly material: MaterialAsset;\n readonly limits?: PointsLinesAdmissionLimits;\n readonly materialId?: string;\n}\n\nexport interface PointsLinesAdmission {\n readonly component: 'Points' | 'Lines';\n readonly shape?: PointShape;\n readonly sizePx?: number;\n readonly widthPx?: number;\n readonly pointCount: number;\n readonly segmentCount: number;\n readonly submeshes: readonly number[];\n}\n\nexport type PointsLinesAdmissionError =\n | PointsLinesInvalidStyleError\n | PointsLinesTopologyMismatchError\n | PointsLinesStyleUnsupportedError\n | PointsLinesMaterialUnsupportedError\n | PointsLinesBudgetExceededError;\n\nfunction invalidStyle(\n input: PointsLinesAdmissionInput,\n component: 'Points' | 'Lines' | 'Points/Lines',\n field: string,\n value: number | string | undefined,\n expected: string,\n): Result<never, PointsLinesAdmissionError> {\n return err(new InvalidStyleError({ entity: input.entity, component, field, value, expected }));\n}\n\nfunction topologyMismatch(\n input: PointsLinesAdmissionInput,\n submesh: number,\n expected: string,\n actual: string,\n): Result<never, PointsLinesAdmissionError> {\n return err(new TopologyError({ entity: input.entity, submesh, expected, actual }));\n}\n\nfunction checkStyle(\n input: PointsLinesAdmissionInput,\n): Result<\n { component: 'Points' | 'Lines'; shape?: PointShape; sizePx?: number; widthPx?: number },\n PointsLinesAdmissionError\n> {\n const hasPoints = input.points !== undefined;\n const hasLines = input.lines !== undefined;\n if (hasPoints && hasLines) {\n return invalidStyle(\n input,\n 'Points/Lines',\n 'components',\n 'Points + Lines',\n 'exactly one style component',\n );\n }\n if (!hasPoints && !hasLines) {\n return invalidStyle(input, 'Points/Lines', 'components', undefined, 'one style component');\n }\n\n if (hasPoints) {\n const sizePx = input.points?.sizePx ?? 4;\n const shapeValue = input.points?.shape ?? PointShapeValue.square;\n const shape = pointShapeFromU32(shapeValue);\n if (!Number.isFinite(sizePx) || sizePx <= 0) {\n return invalidStyle(input, 'Points', 'sizePx', sizePx, 'finite sizePx > 0');\n }\n if (shape === undefined) {\n return invalidStyle(input, 'Points', 'shape', shapeValue, \"shape is 'square' or 'circle'\");\n }\n return ok({ component: 'Points', shape, sizePx });\n }\n\n const widthPx = input.lines?.widthPx ?? 1;\n if (!Number.isFinite(widthPx) || widthPx <= 0) {\n return invalidStyle(input, 'Lines', 'widthPx', widthPx, 'finite widthPx > 0');\n }\n return ok({ component: 'Lines', widthPx });\n}\n\nfunction checkTopology(\n input: PointsLinesAdmissionInput,\n component: 'Points' | 'Lines',\n): Result<\n { pointCount: number; segmentCount: number; submeshes: readonly number[] },\n PointsLinesAdmissionError\n> {\n const expected = component === 'Points' ? 'point-list' : 'line-list';\n let pointCount = 0;\n let segmentCount = 0;\n const acceptedSubmeshes: number[] = [];\n let sawNonEmpty = false;\n\n for (const [submeshIndex, submesh] of input.mesh.submeshes.entries()) {\n const indexed = input.mesh.indices !== undefined && submesh.indexCount > 0;\n const elementCount = indexed ? submesh.indexCount : submesh.vertexCount;\n if (elementCount === 0) continue;\n sawNonEmpty = true;\n\n if (component === 'Lines' && submesh.topology === 'line-strip') {\n return err(\n new StyleError({\n lane: 'admission',\n field: 'topology',\n member: 'line-strip',\n supported: ['line-list'],\n }),\n );\n }\n if (submesh.topology !== expected) {\n return topologyMismatch(input, submeshIndex, expected, submesh.topology);\n }\n if (component === 'Lines' && elementCount % 2 !== 0) {\n return topologyMismatch(input, submeshIndex, 'line-list pairs', 'line-list odd tail');\n }\n acceptedSubmeshes.push(submeshIndex);\n if (component === 'Points') pointCount += elementCount;\n else segmentCount += elementCount / 2;\n }\n\n if (!sawNonEmpty) return topologyMismatch(input, 0, expected, 'empty-range');\n return ok({ pointCount, segmentCount, submeshes: acceptedSubmeshes });\n}\n\nfunction checkMaterial(input: PointsLinesAdmissionInput): Result<void, PointsLinesAdmissionError> {\n const passes = input.material.passes ?? [];\n const unlitModules = new Set(['forgeax_material::unlit', 'forgeax::default-unlit']);\n if (passes.length !== 1 || passes[0] === undefined) {\n const pass =\n passes.find(\n (candidate) => candidate.name === 'deferred' || candidate.name === 'shadow-caster',\n ) ?? passes[0];\n return err(\n new MaterialError({\n entity: input.entity,\n material: input.materialId ?? '<anonymous>',\n pass: pass?.name ?? '<empty>',\n module: pass?.program.module ?? '<empty>',\n reason: 'points-lines admission requires one unlit forward pass',\n }),\n );\n }\n const pass = passes[0];\n const lightMode = (pass.renderState?.tags as Record<string, unknown> | undefined)?.LightMode;\n if (\n !unlitModules.has(pass.program.module) ||\n pass.name !== 'forward' ||\n lightMode === 'ShadowCaster'\n ) {\n return err(\n new MaterialError({\n entity: input.entity,\n material: input.materialId ?? '<anonymous>',\n pass: pass.name,\n module: pass.program.module,\n reason: 'points-lines admission requires an engine-owned unlit forward pass',\n }),\n );\n }\n return ok(undefined);\n}\n\n/** Validate one complete Points/Lines candidate before any renderer publication. */\nexport function admitPointsLines(\n input: PointsLinesAdmissionInput,\n): Result<PointsLinesAdmission, PointsLinesAdmissionError> {\n const style = checkStyle(input);\n if (!style.ok) return style;\n const topology = checkTopology(input, style.value.component);\n if (!topology.ok) return topology;\n const material = checkMaterial(input);\n if (!material.ok) return material;\n\n if (style.value.component === 'Points' && input.limits?.maxPoints !== undefined) {\n if (topology.value.pointCount > input.limits.maxPoints) {\n return err(\n new BudgetError({\n lane: 'admission',\n requested: topology.value.pointCount,\n limit: input.limits.maxPoints,\n unit: 'points',\n }),\n );\n }\n }\n if (style.value.component === 'Lines' && input.limits?.maxSegments !== undefined) {\n if (topology.value.segmentCount > input.limits.maxSegments) {\n return err(\n new BudgetError({\n lane: 'admission',\n requested: topology.value.segmentCount,\n limit: input.limits.maxSegments,\n unit: 'segments',\n }),\n );\n }\n }\n\n return ok({ ...style.value, ...topology.value });\n}\n","import type { PointShadowSnapshot } from './render-system-extract';\n\n/**\n * Detached point-shadow budget facts from one completed extract/record frame.\n *\n * `requested` is the number of PointLight + PointLightShadow pairs. The\n * renderer owns the bounded cube-array atlas, so `admitted`, `shadowed`, and\n * `shadowAtlasOccupancy` are all derived from the layer sentinel emitted by\n * the same extract owner. No consumer needs to maintain a second budget\n * ledger.\n */\nexport interface PointShadowInspection {\n readonly status: 'inactive' | 'ready' | 'over-budget';\n readonly requested: number;\n readonly admitted: number;\n readonly shadowed: number;\n readonly shadowAtlasOccupancy: number;\n readonly shadowAtlasCapacity: number;\n}\n\n/** Project point-shadow snapshots to the public, JSON-safe inspection shape. */\nexport function inspectPointShadow(\n snapshots: readonly PointShadowSnapshot[],\n shadowAtlasCapacity: number,\n): PointShadowInspection {\n const requested = snapshots.length;\n const admitted = snapshots.reduce(\n (count, snapshot) =>\n snapshot.shadowAtlasLayer >= 0 && snapshot.shadowAtlasLayer < shadowAtlasCapacity\n ? count + 1\n : count,\n 0,\n );\n // Never publish a misleading `ready` state when any requested shadow owns\n // no atlas layer. The extract sentinel is the single admission projection;\n // a partial or all-sentinel frame is therefore a failed/over-budget\n // admission, not an active shadow path with incomplete output.\n const status =\n requested === 0\n ? ('inactive' as const)\n : requested > shadowAtlasCapacity || admitted !== requested\n ? ('over-budget' as const)\n : ('ready' as const);\n return Object.freeze({\n status,\n requested,\n admitted,\n // A point shadow only samples an atlas after it owns an atlas layer. Keep\n // these names explicit for AI diagnostics while deriving both from the\n // one layer projection above.\n shadowed: admitted,\n shadowAtlasOccupancy: admitted,\n shadowAtlasCapacity,\n });\n}\n","/**\n * Consumer-only SSR M0 admission.\n *\n * This module consumes detached producer receipts. It owns no capture,\n * device, graph, or recovery handle and therefore cannot repair a missing\n * producer. A complete receipt set is the only route to an admitted result.\n */\n\nimport {\n type RhiTextureFormatCapabilityReceipt,\n validateR32FloatReceipt,\n} from '@forgeax/engine-rhi';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport type { ScreenSpaceReflectionData } from '../components/screen-space-reflection';\nimport type { ReflectionFallbackReceipt } from '../inspection-types';\nimport type {\n SsrConfigField,\n SsrConfigInvalidError,\n SsrConfigRange,\n SsrOwnerRecoveryAction,\n SsrSpatialUnavailableReason,\n SsrUnavailableError,\n} from './errors';\nimport type { SsrAdmissionIdentity } from './identity';\n\nexport const SSR_FORMAT_PROFILE = 'r32float-mip-sampled-storage' as const;\n\nexport const SSR_FORMAT_STAGES = Object.freeze([\n 'texture-create',\n 'mip-view',\n 'sampled-storage-bind-group',\n 'pipeline-bind',\n 'finish',\n 'submit',\n 'completion',\n 'readback',\n] as const);\n\nexport type { SsrAdmissionIdentity } from './identity';\n\nexport type SsrFormatStage = (typeof SSR_FORMAT_STAGES)[number];\n\n/**\n * The admission input is the real renderer owner receipt plus the one\n * integration identity supplied by the host. It deliberately does not\n * recreate submitted/source/LKG boolean flags.\n */\nexport type SsrReflectionFallbackReceipt = ReflectionFallbackReceipt & {\n readonly identity: SsrAdmissionIdentity;\n};\n\n/** RHI capability receipt with the same host-supplied integration identity. */\nexport type SsrFormatReceipt = RhiTextureFormatCapabilityReceipt & {\n readonly identity: SsrAdmissionIdentity;\n};\n\nexport interface SsrTemporalReceipt {\n readonly identity: SsrAdmissionIdentity;\n readonly successfulSubmit: true;\n readonly generation: number;\n}\n\nexport interface SsrAdmissionWork {\n readonly attachmentCount: number;\n readonly passCount: number;\n readonly bindingCount: number;\n readonly resourceCount: number;\n readonly historyCount: 0;\n readonly temporalDemand: 0;\n}\n\nexport interface SsrAdmissionBudget {\n readonly probeExecutions: 0 | 1;\n readonly resetCount: 0;\n readonly rebuildCount: 0;\n}\n\nexport interface SsrAdmissionFailure {\n readonly code:\n | 'ssr-not-requested'\n | 'ssr-reflection-fallback-unavailable'\n | 'ssr-format-unavailable'\n | 'ssr-temporal-unavailable'\n | 'ssr-receipt-identity-mismatch'\n | 'ssr-receipt-stale';\n readonly expected: string;\n readonly hint: string;\n readonly detail: Readonly<{\n readonly owner: 'producer' | 'format' | 'temporal' | 'consumer';\n /** Owner-directed action an AI consumer can take without parsing hint text. */\n readonly action: SsrOwnerRecoveryAction;\n readonly generation?: number;\n readonly identityField?: keyof SsrAdmissionIdentity;\n }>;\n}\n\nexport type SsrAdmissionResult =\n | {\n readonly status: 'admitted';\n readonly identity: SsrAdmissionIdentity | undefined;\n readonly generation: number;\n readonly work: SsrAdmissionWork;\n readonly budget: SsrAdmissionBudget;\n readonly failure?: undefined;\n }\n | {\n readonly status: 'fallback-only';\n readonly identity: SsrAdmissionIdentity | undefined;\n readonly generation: number;\n readonly work: SsrAdmissionWork;\n readonly budget: SsrAdmissionBudget;\n readonly failure: SsrAdmissionFailure;\n };\n\nexport interface SsrAdmissionInput {\n readonly requested: boolean;\n readonly identity: SsrAdmissionIdentity;\n readonly reflectionFallback?: SsrReflectionFallbackReceipt;\n readonly format?: SsrFormatReceipt;\n readonly temporal?: SsrTemporalReceipt;\n readonly previousGeneration?: number;\n}\n\n/** Public renderer projection consumed by the parent SSR feature. */\nexport interface SsrDependenciesInspection {\n readonly status: 'admitted' | 'fallback-only';\n /** Absent until the host binds an exact source/tree/lock/build identity. */\n readonly identity: SsrAdmissionIdentity | undefined;\n readonly requested: boolean;\n readonly reflectionFallback: ReflectionFallbackReceipt | undefined;\n readonly format: SsrFormatReceipt | undefined;\n readonly temporal: SsrTemporalReceipt | undefined;\n readonly admission: SsrAdmissionResult;\n readonly work: SsrAdmissionWork;\n readonly budget: SsrAdmissionBudget;\n readonly failure: SsrAdmissionFailure | undefined;\n}\n\nconst ZERO_WORK: SsrAdmissionWork = Object.freeze({\n attachmentCount: 0,\n passCount: 0,\n bindingCount: 0,\n resourceCount: 0,\n historyCount: 0,\n temporalDemand: 0,\n});\n\nconst ADMITTED_WORK: SsrAdmissionWork = Object.freeze({\n attachmentCount: 1,\n passCount: 1,\n bindingCount: 1,\n resourceCount: 1,\n historyCount: 0,\n temporalDemand: 0,\n});\n\nconst ZERO_BUDGET: SsrAdmissionBudget = Object.freeze({\n probeExecutions: 0,\n resetCount: 0,\n rebuildCount: 0,\n});\n\nconst ADMITTED_BUDGET: SsrAdmissionBudget = Object.freeze({\n probeExecutions: 1,\n resetCount: 0,\n rebuildCount: 0,\n});\n\nfunction identityFieldMismatch(\n expected: SsrAdmissionIdentity,\n actual: SsrAdmissionIdentity,\n): keyof SsrAdmissionIdentity | undefined {\n for (const field of ['sourceHead', 'sourceTree', 'lockSha256', 'buildSha256'] as const) {\n if (expected[field] !== actual[field]) return field;\n }\n return undefined;\n}\n\nfunction blocked(\n identity: SsrAdmissionIdentity | undefined,\n failure: SsrAdmissionFailure,\n generation = 0,\n): SsrAdmissionResult {\n return Object.freeze({\n status: 'fallback-only',\n identity,\n generation,\n work: ZERO_WORK,\n budget: ZERO_BUDGET,\n failure,\n });\n}\n\nfunction failure(\n code: SsrAdmissionFailure['code'],\n owner: SsrAdmissionFailure['detail']['owner'],\n hint: string,\n detail: Omit<SsrAdmissionFailure['detail'], 'owner' | 'action'> = {},\n): SsrAdmissionFailure {\n const action: SsrOwnerRecoveryAction = recoveryActionFor(code);\n return Object.freeze({\n code,\n expected: 'all producer, format, and temporal receipts share one admitted identity',\n hint,\n detail: Object.freeze({ owner, action, ...detail }),\n });\n}\n\nfunction recoveryActionFor(code: SsrAdmissionFailure['code']): SsrOwnerRecoveryAction {\n switch (code) {\n case 'ssr-reflection-fallback-unavailable':\n case 'ssr-receipt-identity-mismatch':\n return 'rebuild';\n case 'ssr-not-requested':\n case 'ssr-format-unavailable':\n case 'ssr-temporal-unavailable':\n case 'ssr-receipt-stale':\n return 'retry';\n }\n}\n\nfunction receiptFailure(\n input: SsrAdmissionInput,\n receipt: { readonly identity: SsrAdmissionIdentity },\n owner: SsrAdmissionFailure['detail']['owner'],\n): SsrAdmissionResult | undefined {\n const field = identityFieldMismatch(input.identity, receipt.identity);\n if (field === undefined) return undefined;\n return blocked(\n input.identity,\n failure('ssr-receipt-identity-mismatch', owner, 'rebuild the owner receipt for this identity', {\n identityField: field,\n }),\n );\n}\n\nfunction validFallback(receipt: SsrReflectionFallbackReceipt | undefined): boolean {\n return (\n receipt !== undefined &&\n receipt.candidateVisible === false &&\n Number.isFinite(receipt.coverage) &&\n receipt.coverage >= 0 &&\n receipt.coverage <= 1 &&\n (receipt.sourceKey === undefined || receipt.sourceKey.length > 0) &&\n (receipt.extent === undefined ||\n (receipt.extent.length === 3 &&\n receipt.extent.every((value) => Number.isFinite(value) && value > 0))) &&\n Number.isInteger(receipt.sourceGeneration) &&\n receipt.sourceGeneration >= 0 &&\n Number.isInteger(receipt.projectionGeneration) &&\n receipt.projectionGeneration >= 0 &&\n Number.isInteger(receipt.deviceGeneration) &&\n receipt.deviceGeneration >= 0 &&\n receipt.brdfSignature === 'standard-pbr-ibl-v1' &&\n ((receipt.source === 'probe' && (receipt.state === 'active' || receipt.state === 'lkg')) ||\n (receipt.source === 'skylight' && (receipt.state === 'active' || receipt.state === 'lkg')) ||\n (receipt.source === 'neutral' && receipt.state === 'neutral'))\n );\n}\n\nfunction validFormat(receipt: SsrFormatReceipt | undefined): boolean {\n if (\n receipt?.profile !== SSR_FORMAT_PROFILE ||\n receipt.verdict !== 'admitted' ||\n receipt.evidence !== 'real' ||\n !Number.isInteger(receipt.deviceGeneration) ||\n receipt.deviceGeneration < 0\n ) {\n return false;\n }\n if (\n !SSR_FORMAT_STAGES.every((stage) =>\n receipt.stages.some((entry) => entry.stage === stage && entry.verdict === 'admitted'),\n )\n ) {\n return false;\n }\n return validateR32FloatReceipt(receipt).ok;\n}\n\nfunction validTemporal(receipt: SsrTemporalReceipt | undefined): boolean {\n return (\n receipt?.successfulSubmit === true &&\n Number.isInteger(receipt.generation) &&\n receipt.generation >= 0\n );\n}\n\nexport function admitSsrM0(input: SsrAdmissionInput): SsrAdmissionResult {\n if (!input.requested) {\n return blocked(\n input.identity,\n failure('ssr-not-requested', 'consumer', 'request SSR before evaluating M0 admission'),\n );\n }\n if (input.reflectionFallback === undefined) {\n return blocked(\n input.identity,\n failure('ssr-reflection-fallback-unavailable', 'producer', 'use LKG, Skylight, or neutral'),\n );\n }\n const fallbackIdentityFailure = receiptFailure(input, input.reflectionFallback, 'producer');\n if (fallbackIdentityFailure !== undefined) return fallbackIdentityFailure;\n if (!validFallback(input.reflectionFallback)) {\n return blocked(\n input.identity,\n failure(\n 'ssr-reflection-fallback-unavailable',\n 'producer',\n 'inspect and rebuild the producer receipt',\n ),\n input.reflectionFallback.projectionGeneration,\n );\n }\n if (input.format === undefined) {\n return blocked(\n input.identity,\n failure('ssr-format-unavailable', 'format', 'probe the exact format profile for this device'),\n input.reflectionFallback.projectionGeneration,\n );\n }\n const formatIdentityFailure = receiptFailure(input, input.format, 'format');\n if (formatIdentityFailure !== undefined) return formatIdentityFailure;\n if (!validFormat(input.format)) {\n return blocked(\n input.identity,\n failure('ssr-format-unavailable', 'format', 'complete the full r32float profile probe'),\n input.reflectionFallback.projectionGeneration,\n );\n }\n // Prior submitted history is optional for fresh spatial SSR. If supplied,\n // its identity and validity still obey the temporal owner's contract.\n const temporalIdentityFailure =\n input.temporal === undefined ? undefined : receiptFailure(input, input.temporal, 'temporal');\n if (temporalIdentityFailure !== undefined) return temporalIdentityFailure;\n if (input.temporal !== undefined && !validTemporal(input.temporal)) {\n return blocked(\n input.identity,\n failure('ssr-temporal-unavailable', 'temporal', 'inspect and rebuild the temporal receipt'),\n input.reflectionFallback.projectionGeneration,\n );\n }\n if (\n input.previousGeneration !== undefined &&\n input.previousGeneration !== input.reflectionFallback.projectionGeneration\n ) {\n return blocked(\n input.identity,\n failure(\n 'ssr-receipt-stale',\n 'consumer',\n 'discard stale completion and reinspect the owners',\n {\n generation: input.reflectionFallback.projectionGeneration,\n },\n ),\n input.reflectionFallback.projectionGeneration,\n );\n }\n return Object.freeze({\n status: 'admitted',\n identity: input.identity,\n generation: input.reflectionFallback.projectionGeneration,\n work: ADMITTED_WORK,\n budget: ADMITTED_BUDGET,\n });\n}\n\n/**\n * Joins the live owner projections at the renderer boundary. The only casts\n * here add the host identity to receipts that otherwise remain canonical RHI\n * or ReflectionProbe PODs; no producer fact is copied or renamed.\n */\nexport function projectSsrDependencies(input: {\n readonly requested: boolean;\n readonly identity: SsrAdmissionIdentity | undefined;\n readonly reflectionFallback: ReflectionFallbackReceipt | undefined;\n readonly format: RhiTextureFormatCapabilityReceipt | undefined;\n readonly temporal: { readonly successfulSubmit: true; readonly generation: number } | undefined;\n readonly previousGeneration?: number;\n}): SsrDependenciesInspection {\n const identity = input.identity;\n const reflectionFallback =\n identity === undefined || input.reflectionFallback?.identity === undefined\n ? undefined\n : (input.reflectionFallback as SsrReflectionFallbackReceipt);\n const format =\n identity === undefined || input.format === undefined\n ? undefined\n : ({ ...input.format, identity } satisfies SsrFormatReceipt);\n const temporal =\n identity === undefined || input.temporal === undefined\n ? undefined\n : ({ identity, ...input.temporal } satisfies SsrTemporalReceipt);\n const admission =\n identity === undefined\n ? blocked(\n undefined,\n failure(\n input.requested ? 'ssr-receipt-identity-mismatch' : 'ssr-not-requested',\n 'consumer',\n input.requested\n ? 'bind the exact source, tree, lock, and build identity before admission'\n : 'request SSR before evaluating M0 admission',\n input.requested ? { identityField: 'sourceHead' } : {},\n ),\n )\n : admitSsrM0({\n requested: input.requested,\n identity,\n ...(reflectionFallback === undefined ? {} : { reflectionFallback }),\n ...(format === undefined ? {} : { format }),\n ...(temporal === undefined ? {} : { temporal }),\n ...(input.previousGeneration === undefined\n ? {}\n : { previousGeneration: input.previousGeneration }),\n });\n return Object.freeze({\n status: admission.status,\n identity,\n requested: input.requested,\n reflectionFallback: input.reflectionFallback,\n format,\n temporal,\n admission,\n work: admission.work,\n budget: admission.budget,\n failure: admission.failure,\n });\n}\n\nexport function zeroSsrAdmissionWork(): SsrAdmissionWork {\n return ZERO_WORK;\n}\n\n/**\n * Projects the admission decision into the existing temporal reset seam.\n * Admission never creates temporal history; only a changed committed\n * producer generation can request a reset through the coordinator.\n */\nexport function resolveSsrAdmissionGeneration(\n previousGeneration: number | undefined,\n nextGeneration: number | undefined,\n): { readonly changed: boolean; readonly generation: number | undefined } {\n return {\n changed:\n previousGeneration !== undefined &&\n nextGeneration !== undefined &&\n previousGeneration !== nextGeneration,\n generation: nextGeneration,\n };\n}\n\n/** Standard spatial lanes that may consume an SSR candidate. */\nexport type SsrSpatialLane = 'clustered' | 'deferred' | 'direct' | 'cpu-webgl2' | 'forward';\n\n/** Capability facts required by the M1 spatial path. */\nexport interface SsrSpatialCapabilities {\n readonly compute: boolean;\n readonly storageTexture: boolean;\n readonly rgba16floatRenderable: boolean;\n readonly r32floatSampledStorage: boolean;\n}\n\n/** Detached owner facts consumed by spatial admission. */\nexport interface SsrSpatialEnvironment {\n readonly lane: SsrSpatialLane;\n readonly m0: Pick<SsrAdmissionResult, 'status'>;\n readonly sceneInputs: boolean;\n /** Current-frame motion/coverage producer, not reusable previous-frame history. */\n readonly temporal: boolean;\n readonly reflectionFallback: boolean;\n readonly capabilities: SsrSpatialCapabilities;\n /** Recovery readiness is optional for callers that have no recovery fault. */\n readonly recovery?: boolean;\n}\n\n/** The only camera fields used by the spatial admission owner. */\nexport interface SsrSpatialCamera {\n readonly projection: 'perspective' | 'orthographic';\n readonly near: number;\n readonly far: number;\n readonly screenSpaceReflection?: ScreenSpaceReflectionData;\n}\n\nexport interface SsrSpatialWork {\n readonly attachmentCount: number;\n readonly passCount: number;\n readonly bindingCount: number;\n readonly resourceCount: number;\n readonly historyCount: 0;\n readonly temporalDemand: 0;\n}\n\nexport type SsrSpatialStatus =\n | 'not-requested'\n | 'requested'\n | 'admitted'\n | 'fallback-only'\n | 'structural-only';\n\nexport interface SsrSpatialAdmissionBase {\n readonly status: SsrSpatialStatus;\n readonly lane: SsrSpatialLane;\n readonly config: ScreenSpaceReflectionData | undefined;\n readonly viewRange: number;\n readonly work: SsrSpatialWork;\n}\n\nexport type SsrSpatialAdmission =\n | (SsrSpatialAdmissionBase & {\n readonly status: 'not-requested' | 'requested';\n readonly failure?: undefined;\n })\n | (SsrSpatialAdmissionBase & {\n readonly status: 'admitted';\n readonly config: ScreenSpaceReflectionData;\n readonly failure?: undefined;\n })\n | (SsrSpatialAdmissionBase & {\n readonly status: 'fallback-only' | 'structural-only';\n readonly failure: SsrConfigInvalidError | SsrUnavailableError;\n });\n\nconst ZERO_SPATIAL_WORK: SsrSpatialWork = Object.freeze({\n attachmentCount: 0,\n passCount: 0,\n bindingCount: 0,\n resourceCount: 0,\n historyCount: 0,\n temporalDemand: 0,\n});\n\nconst ADMITTED_SPATIAL_WORK: SsrSpatialWork = Object.freeze({\n attachmentCount: 3,\n passCount: 4,\n bindingCount: 4,\n resourceCount: 3,\n historyCount: 0,\n temporalDemand: 0,\n});\n\nfunction configRange(\n field: SsrConfigField,\n viewRange: number,\n maxDistance: number,\n): SsrConfigRange {\n switch (field) {\n case 'maxDistance':\n return { min: 0, minInclusive: false, max: viewRange, maxInclusive: true };\n case 'thickness':\n return { min: 0, minInclusive: false, max: maxDistance, maxInclusive: true };\n case 'maxRoughness':\n return { min: 0, minInclusive: true, max: 1, maxInclusive: true };\n }\n}\n\nfunction configError(\n field: SsrConfigField,\n value: number,\n range: SsrConfigRange,\n): SsrConfigInvalidError {\n const left = range.minInclusive ? '[' : '(';\n const right = range.maxInclusive ? ']' : ')';\n return Object.freeze({\n code: 'ssr-config-invalid',\n expected: `finite ${field} in ${left}${range.min}, ${range.max}${right}`,\n hint: `set ${field} to a finite value inside the reported range before retrying`,\n detail: Object.freeze({ field, value, range: Object.freeze(range) }),\n });\n}\n\n/** Validate one schema-derived component value against the active view. */\nexport function validateScreenSpaceReflection(\n config: ScreenSpaceReflectionData,\n input: { readonly viewRange: number },\n): Result<ScreenSpaceReflectionData, SsrConfigInvalidError> {\n const viewRange = input.viewRange;\n if (!Number.isFinite(viewRange) || viewRange <= 0) {\n return err(\n configError('maxDistance', config.maxDistance, configRange('maxDistance', viewRange, 0)),\n );\n }\n if (\n !Number.isFinite(config.maxDistance) ||\n config.maxDistance <= 0 ||\n config.maxDistance > viewRange\n ) {\n return err(\n configError(\n 'maxDistance',\n config.maxDistance,\n configRange('maxDistance', viewRange, config.maxDistance),\n ),\n );\n }\n if (\n !Number.isFinite(config.thickness) ||\n config.thickness <= 0 ||\n config.thickness > config.maxDistance\n ) {\n return err(\n configError(\n 'thickness',\n config.thickness,\n configRange('thickness', viewRange, config.maxDistance),\n ),\n );\n }\n if (!Number.isFinite(config.maxRoughness) || config.maxRoughness < 0 || config.maxRoughness > 1) {\n return err(\n configError(\n 'maxRoughness',\n config.maxRoughness,\n configRange('maxRoughness', viewRange, config.maxDistance),\n ),\n );\n }\n return ok(\n Object.freeze({\n maxDistance: config.maxDistance,\n thickness: config.thickness,\n maxRoughness: config.maxRoughness,\n }),\n );\n}\n\nfunction unavailable(\n lane: SsrSpatialLane,\n reason: SsrSpatialUnavailableReason,\n required: readonly string[],\n actual: Readonly<Record<string, boolean | number | string>>,\n): SsrUnavailableError {\n const recovery =\n reason === 'lane-unsupported' || reason === 'projection-unsupported'\n ? 'select a perspective clustered or deferred Standard lane'\n : reason === 'reflection-fallback-unavailable'\n ? 'repair the submitted reflection fallback owner receipt'\n : reason === 'temporal-unavailable'\n ? 'submit the matching temporal-v1 producer receipt'\n : reason === 'recovery-unavailable'\n ? 'complete device and producer recovery before retrying'\n : 'restore the required scene, capability, or format input before retrying';\n return Object.freeze({\n code: 'ssr-unavailable',\n expected: 'SSR spatial admission has a complete Standard input and capability set',\n hint: recovery,\n detail: Object.freeze({\n lane,\n reason,\n required: Object.freeze([...required]),\n actual: Object.freeze({ ...actual }),\n recovery,\n }),\n });\n}\n\nfunction unavailableResult(\n lane: SsrSpatialLane,\n viewRange: number,\n failure: SsrUnavailableError,\n): SsrSpatialAdmission {\n return Object.freeze({\n status: 'fallback-only',\n lane,\n config: undefined,\n viewRange,\n work: ZERO_SPATIAL_WORK,\n failure,\n });\n}\n\n/**\n * Admit the active camera's schema-derived component into the M1 spatial\n * path. No graph/resource handle crosses this boundary.\n */\nexport function admitSsrSpatial(input: {\n readonly camera: SsrSpatialCamera;\n readonly environment: SsrSpatialEnvironment;\n}): SsrSpatialAdmission {\n const camera = input.camera;\n const environment = input.environment;\n const viewRange = camera.far - camera.near;\n const config = camera.screenSpaceReflection;\n if (config === undefined) {\n return Object.freeze({\n status: 'not-requested',\n lane: environment.lane,\n config: undefined,\n viewRange,\n work: ZERO_SPATIAL_WORK,\n });\n }\n\n const valid = validateScreenSpaceReflection(config, { viewRange });\n if (!valid.ok) {\n return Object.freeze({\n status: 'fallback-only',\n lane: environment.lane,\n config,\n viewRange,\n work: ZERO_SPATIAL_WORK,\n failure: valid.error,\n });\n }\n\n if (environment.m0.status !== 'admitted') {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(\n environment.lane,\n 'reflection-fallback-unavailable',\n ['admitted M0 dependency receipt'],\n { m0: false },\n ),\n );\n }\n if (environment.lane !== 'clustered' && environment.lane !== 'deferred') {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(environment.lane, 'lane-unsupported', ['clustered or deferred Standard lane'], {\n lane: environment.lane,\n }),\n );\n }\n if (camera.projection !== 'perspective') {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(environment.lane, 'projection-unsupported', ['perspective camera'], {\n projection: camera.projection,\n }),\n );\n }\n if (!environment.sceneInputs) {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(\n environment.lane,\n 'scene-input-unavailable',\n ['deferred Standard scene/material/fallback inputs'],\n { sceneInputs: false },\n ),\n );\n }\n if (!environment.temporal) {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(environment.lane, 'temporal-unavailable', ['temporal-v1'], { temporal: false }),\n );\n }\n if (!environment.reflectionFallback) {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(\n environment.lane,\n 'reflection-fallback-unavailable',\n ['submitted BRDF-projected fallback'],\n { reflectionFallback: false },\n ),\n );\n }\n if (environment.recovery === false) {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(environment.lane, 'recovery-unavailable', ['ready device and owners'], {\n recovery: false,\n }),\n );\n }\n const capabilities = environment.capabilities;\n if (\n !capabilities.compute ||\n !capabilities.storageTexture ||\n !capabilities.rgba16floatRenderable\n ) {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(\n environment.lane,\n 'capability-unavailable',\n ['compute', 'storageTexture', 'rgba16floatRenderable'],\n {\n compute: capabilities.compute,\n storageTexture: capabilities.storageTexture,\n rgba16floatRenderable: capabilities.rgba16floatRenderable,\n },\n ),\n );\n }\n if (!capabilities.r32floatSampledStorage) {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(\n environment.lane,\n 'format-unavailable',\n ['r32float sampled and storage mip chain'],\n { r32floatSampledStorage: false },\n ),\n );\n }\n return Object.freeze({\n status: 'admitted',\n lane: environment.lane,\n config: valid.value,\n viewRange,\n work: ADMITTED_SPATIAL_WORK,\n });\n}\n","import type { TextureFormat } from '@forgeax/engine-rhi';\nimport type { VolumeRecoveryState, VolumeSelectedLightFacts } from './recovery';\nimport type { VolumetricFogResourceFacts } from './resources';\n\nexport type VolumetricFogInspectionStatus = 'off' | 'available' | 'unavailable' | 'degraded';\n\nexport type VolumetricFogResourceStage = 'none' | 'candidate' | 'accepted' | 'lkg' | 'recovering';\n\nexport interface VolumetricFogInspection {\n /** Owners in the last successfully submitted volume collection. */\n readonly ownerCount: number;\n readonly status: VolumetricFogInspectionStatus;\n readonly resourceStage: VolumetricFogResourceStage;\n readonly guid: string | undefined;\n readonly generation: number | undefined;\n readonly digest: string | undefined;\n readonly candidateGeneration: number | undefined;\n readonly candidateDigest: string | undefined;\n readonly lkgGeneration: number | undefined;\n readonly candidateFailure: VolumeRecoveryState['candidateFailure'];\n readonly deviceEpoch: number;\n readonly format: TextureFormat | undefined;\n readonly passCount: number;\n readonly sampleCount: number;\n readonly memoryBytes: number;\n readonly resourceFacts: VolumetricFogResourceFacts | undefined;\n readonly selectedLight: VolumeSelectedLightFacts | undefined;\n readonly candidateSelectedLight: VolumeSelectedLightFacts | undefined;\n}\n\nexport interface VolumetricFogInspectionInput {\n readonly authored: boolean;\n readonly capability: 'available' | 'unavailable';\n readonly degraded?: boolean;\n readonly recovery?: VolumeRecoveryState;\n readonly acceptedDigest?: string;\n readonly format?: TextureFormat;\n readonly passCount?: number;\n readonly sampleCount?: number;\n readonly memoryBytes?: number;\n readonly resourceFacts?: VolumetricFogResourceFacts;\n}\n\nfunction resourceStage(input: VolumetricFogInspectionInput): VolumetricFogResourceStage {\n if (!input.authored || input.recovery === undefined) return 'none';\n if (input.recovery.status === 'candidate') return 'candidate';\n if (input.recovery.status === 'recovering') return 'recovering';\n if (input.recovery.status === 'degraded') return 'lkg';\n return 'accepted';\n}\n\nexport function inspectVolumetricFog(input: VolumetricFogInspectionInput): VolumetricFogInspection {\n const recovery = input.recovery;\n const status: VolumetricFogInspectionStatus = !input.authored\n ? 'off'\n : input.capability === 'unavailable'\n ? 'unavailable'\n : input.degraded === true || recovery?.status === 'degraded'\n ? 'degraded'\n : 'available';\n return Object.freeze({\n ownerCount: 0,\n status,\n resourceStage: resourceStage(input),\n guid: recovery?.guid,\n generation: recovery?.generation,\n digest: input.acceptedDigest,\n candidateGeneration: recovery?.candidateGeneration,\n candidateDigest: recovery?.candidateDigest,\n lkgGeneration: recovery?.lkgGeneration,\n candidateFailure: recovery?.candidateFailure,\n deviceEpoch: recovery?.deviceEpoch ?? 0,\n format: input.format,\n passCount: input.passCount ?? 0,\n sampleCount: input.sampleCount ?? 0,\n memoryBytes: input.memoryBytes ?? 0,\n resourceFacts: input.resourceFacts,\n selectedLight: recovery?.selectedLight,\n candidateSelectedLight: recovery?.candidateSelectedLight,\n });\n}\n","import type {\n MaterialDynamicFieldType,\n MaterialDynamicInputLayout,\n MaterialDynamicInputSchema,\n} from '@forgeax/engine-types';\nimport { deriveMaterialDynamicInputLayout, err, ok, type Result } from '@forgeax/engine-types';\n\nexport type DynamicInputValue = number | readonly number[];\n\n/** Stable public address of one admitted Surface draw member. */\nexport interface SurfaceDynamicInputMemberIdentity {\n /** `World.identity`; stable across renderer-local World reordering. */\n readonly worldIdentity: string;\n readonly entityKey: number;\n readonly drawItemIndex: number;\n readonly instanceOrdinal: number;\n}\n\nexport interface DynamicInputRange {\n readonly pageId: number;\n readonly sourceId: string;\n /** Producer-owned domain identity retained across device regeneration. */\n readonly domain: string;\n readonly byteOffset: number;\n readonly recordStart: number;\n readonly recordCount: number;\n readonly instanceIndex: number;\n readonly member: SurfaceDynamicInputMemberIdentity;\n readonly contentRevision: number;\n readonly bufferGeneration: number;\n readonly deviceGeneration: number;\n}\n\nexport interface DynamicInputDirtyRange {\n readonly byteStart: number;\n readonly byteEnd: number;\n}\n\nexport interface DynamicInputUploadReceipt {\n readonly sourceId: string;\n readonly pageId: number;\n readonly contentRevision: number;\n readonly bufferGeneration: number;\n readonly deviceGeneration: number;\n readonly ranges: readonly DynamicInputDirtyRange[];\n readonly bytes: number;\n}\n\nexport interface DynamicInputConsumptionReceipt extends DynamicInputRange {\n readonly frameNumber: number;\n readonly uploadedRevision: number;\n}\n\n/**\n * Renderer input for one frame of a published Surface dynamic page.\n *\n * `ranges` join by their stable World/entity/draw/instance member identity.\n * Producer order is irrelevant and cannot redirect one member's dynamic\n * records to another member after culling or World reordering.\n */\nexport interface SurfaceDynamicInputFrame {\n readonly page: ReadonlyDynamicInputPage;\n readonly ranges?: readonly DynamicInputRange[];\n /** Producer-owned membership/address revision; time and record values do not advance it. */\n readonly projectionRevision: number;\n readonly frameTime: number;\n}\n\nexport type DynamicInputErrorCode =\n | 'invalid-schema'\n | 'invalid-record'\n | 'range-overflow'\n | 'domain-overflow'\n | 'not-uploaded'\n | 'stale-generation'\n | 'released';\n\nexport interface DynamicInputErrorDetail {\n readonly operation:\n | 'create'\n | 'write'\n | 'reserve'\n | 'upload'\n | 'consume'\n | 'reconfigure'\n | 'release';\n readonly field?: string;\n readonly expected: string;\n readonly actual?: unknown;\n readonly sourceId?: string;\n readonly pageId?: number;\n}\n\nconst ERROR_POLICY: Readonly<\n Record<DynamicInputErrorCode, { readonly expected: string; readonly hint: string }>\n> = {\n 'invalid-schema': {\n expected: 'the dynamic input schema has one derived bounded record layout',\n hint: 'repair the root MaterialSurface dynamicInput declaration and recook it',\n },\n 'invalid-record': {\n expected: 'each dynamic record matches the derived scalar/vector fields',\n hint: 'write finite values using the field names and types declared by the material',\n },\n 'range-overflow': {\n expected: 'the instance range stays within the declared read-only page',\n hint: 'reduce the range or increase the producer page budget before publication',\n },\n 'domain-overflow': {\n expected: 'the page stays within its declared number of producer domains',\n hint: 'reuse an existing domain or publish a larger bounded declaration',\n },\n 'not-uploaded': {\n expected: 'the current page revision was uploaded before frame consumption',\n hint: 'submit the page upload receipt and retry the same frame',\n },\n 'stale-generation': {\n expected: 'the range, upload, and device use one current page generation',\n hint: 'discard stale addresses and rebuild the producer projection for the current device',\n },\n released: {\n expected: 'the read-only page is still attached to its owning Render lifecycle',\n hint: 'create a new page after releasing the old owner',\n },\n};\n\nexport class DynamicInputError extends Error {\n readonly code: DynamicInputErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: DynamicInputErrorDetail;\n\n constructor(code: DynamicInputErrorCode, detail: DynamicInputErrorDetail) {\n super(`${code}: ${ERROR_POLICY[code].expected}`);\n this.name = 'DynamicInputError';\n this.code = code;\n this.expected = ERROR_POLICY[code].expected;\n this.hint = ERROR_POLICY[code].hint;\n this.detail = Object.freeze({ ...detail });\n }\n}\n\nexport type DynamicInputResult<T> = Result<T, DynamicInputError>;\n\ninterface DomainRecord {\n readonly name: string;\n readonly start: number;\n readonly end: number;\n}\n\nfunction alignRange(ranges: DynamicInputDirtyRange[], start: number, end: number): void {\n if (start >= end) return;\n let index = 0;\n while (index < ranges.length && (ranges[index]?.byteEnd ?? 0) < start) index += 1;\n while (index < ranges.length) {\n const existing = ranges[index];\n if (existing === undefined || existing.byteStart > end) break;\n start = Math.min(start, existing.byteStart);\n end = Math.max(end, existing.byteEnd);\n ranges.splice(index, 1);\n }\n ranges.splice(index, 0, { byteStart: start, byteEnd: end });\n}\n\nfunction fieldWidth(type: MaterialDynamicFieldType): number {\n switch (type) {\n case 'f32':\n case 'u32':\n return 1;\n case 'vec2<f32>':\n return 2;\n case 'vec3<f32>':\n return 3;\n case 'vec4<f32>':\n return 4;\n }\n}\n\nfunction finiteNumber(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value);\n}\n\nfunction invalid(\n code: DynamicInputErrorCode,\n operation: DynamicInputErrorDetail['operation'],\n expected: string,\n actual?: unknown,\n field?: string,\n page?: Readonly<{ sourceId: string; pageId: number }>,\n): DynamicInputError {\n return new DynamicInputError(code, {\n operation,\n expected,\n ...(actual === undefined ? {} : { actual }),\n ...(field === undefined ? {} : { field }),\n ...(page === undefined ? {} : page),\n });\n}\n\n/**\n * Generic Render-owned CPU side of a read-only dynamic input page. The page\n * has no GPU handle: the renderer's existing resource owner can upload the\n * detached bytes and attach the receipt to a prepared pass.\n */\nexport class ReadonlyDynamicInputPage {\n readonly sourceId: string;\n readonly pageId: number;\n readonly schema: MaterialDynamicInputSchema;\n readonly layout: MaterialDynamicInputLayout;\n readonly bytes: Uint8Array;\n private contentRevisionValue = 1;\n private bufferGenerationValue = 1;\n private deviceGenerationValue = 1;\n private uploadedRevisionValue = 0;\n private lastUploadedBytesValue = 0;\n private released = false;\n private readonly ownedRanges = new WeakSet<object>();\n private readonly ownedUploads = new WeakSet<object>();\n private readonly dirty = [\n {\n byteStart: 0,\n byteEnd: 0,\n } as DynamicInputDirtyRange,\n ];\n private readonly domains = new Map<string, DomainRecord>();\n\n private constructor(\n sourceId: string,\n pageId: number,\n schema: MaterialDynamicInputSchema,\n layout: MaterialDynamicInputLayout,\n ) {\n this.sourceId = sourceId;\n this.pageId = pageId;\n this.schema = schema;\n this.layout = layout;\n this.bytes = new Uint8Array(schema.maxPageBytes);\n this.dirty.length = 0;\n }\n\n static create(input: {\n readonly sourceId: string;\n readonly pageId: number;\n readonly schema: MaterialDynamicInputSchema;\n }): DynamicInputResult<ReadonlyDynamicInputPage> {\n if (input.sourceId.length === 0 || !Number.isSafeInteger(input.pageId) || input.pageId < 0) {\n return err(\n invalid(\n 'invalid-schema',\n 'create',\n 'sourceId is non-empty and pageId is non-negative',\n input.pageId,\n ),\n );\n }\n const layout = deriveMaterialDynamicInputLayout(input.schema);\n if (!layout.ok) {\n return err(\n invalid(\n 'invalid-schema',\n 'create',\n layout.error.expected,\n layout.error.actual,\n layout.error.field,\n ),\n );\n }\n return ok(\n new ReadonlyDynamicInputPage(input.sourceId, input.pageId, input.schema, layout.value),\n );\n }\n\n get contentRevision(): number {\n return this.contentRevisionValue;\n }\n\n get bufferGeneration(): number {\n return this.bufferGenerationValue;\n }\n\n get deviceGeneration(): number {\n return this.deviceGenerationValue;\n }\n\n get uploadedRevision(): number {\n return this.uploadedRevisionValue;\n }\n\n get lastUploadedBytes(): number {\n return this.lastUploadedBytesValue;\n }\n\n /** Write one complete record and mark only its byte interval dirty. */\n writeRecord(\n index: number,\n values: Readonly<Record<string, DynamicInputValue>>,\n ): DynamicInputResult<number> {\n const live = this.assertLive('write');\n if (!live.ok) return live;\n if (!Number.isSafeInteger(index) || index < 0 || index >= this.schema.maxRecords) {\n return err(\n invalid(\n 'range-overflow',\n 'write',\n `record index is within [0, ${this.schema.maxRecords})`,\n index,\n 'index',\n this,\n ),\n );\n }\n const recordOffset = index * this.layout.stride;\n // Encode into detached bytes first. A malformed later field must leave the\n // previously published record and its dirty/revision state untouched.\n const encoded = new Uint8Array(this.layout.stride);\n const view = new DataView(encoded.buffer, encoded.byteOffset, encoded.byteLength);\n for (const field of this.layout.fields) {\n const value = values[field.name];\n if (value === undefined) {\n return err(\n invalid(\n 'invalid-record',\n 'write',\n `record contains field ${field.name}`,\n value,\n field.name,\n this,\n ),\n );\n }\n const width = fieldWidth(field.type);\n const numbers = typeof value === 'number' ? [value] : value;\n if (numbers.length !== width || numbers.some((candidate) => !finiteNumber(candidate))) {\n return err(\n invalid(\n 'invalid-record',\n 'write',\n `${field.name} is a finite ${field.type}`,\n value,\n field.name,\n this,\n ),\n );\n }\n if (\n field.type === 'u32' &&\n (!Number.isInteger(numbers[0]) ||\n (numbers[0] as number) < 0 ||\n (numbers[0] as number) > 0xffffffff)\n ) {\n return err(\n invalid(\n 'invalid-record',\n 'write',\n `${field.name} is an unsigned 32-bit integer`,\n value,\n field.name,\n this,\n ),\n );\n }\n for (const [component, number] of numbers.entries()) {\n const offset = field.offset + component * 4;\n if (field.type === 'u32') view.setUint32(offset, number as number, true);\n else view.setFloat32(offset, number as number, true);\n }\n }\n this.bytes.set(encoded, recordOffset);\n this.contentRevisionValue += 1;\n alignRange(this.dirty, recordOffset, recordOffset + this.layout.stride);\n return ok(this.contentRevisionValue);\n }\n\n /** Reserve one explicit instance range; no skin address field is involved. */\n reserveRange(input: {\n readonly domain: string;\n readonly recordStart: number;\n readonly recordCount: number;\n readonly instanceIndex: number;\n readonly member: SurfaceDynamicInputMemberIdentity;\n }): DynamicInputResult<DynamicInputRange> {\n const live = this.assertLive('reserve');\n if (!live.ok) return live;\n if (input.domain.length === 0) {\n return err(\n invalid(\n 'domain-overflow',\n 'reserve',\n 'domain is a non-empty identity',\n input.domain,\n 'domain',\n this,\n ),\n );\n }\n if (!this.domains.has(input.domain) && this.domains.size >= this.schema.maxDomains) {\n return err(\n invalid(\n 'domain-overflow',\n 'reserve',\n `at most ${this.schema.maxDomains} domains are active`,\n this.domains.size + 1,\n 'domain',\n this,\n ),\n );\n }\n if (\n !Number.isSafeInteger(input.instanceIndex) ||\n input.instanceIndex < 0 ||\n input.instanceIndex > 0xffffffff\n ) {\n return err(\n invalid(\n 'range-overflow',\n 'reserve',\n 'instance index is an exact unsigned 32-bit integer',\n input.instanceIndex,\n 'instanceIndex',\n this,\n ),\n );\n }\n if (\n input.member.worldIdentity.length === 0 ||\n !Number.isSafeInteger(input.member.entityKey) ||\n input.member.entityKey < 0 ||\n input.member.entityKey > 0xffffffff ||\n !Number.isSafeInteger(input.member.drawItemIndex) ||\n input.member.drawItemIndex < 0 ||\n input.member.drawItemIndex > 0xffffffff ||\n !Number.isSafeInteger(input.member.instanceOrdinal) ||\n input.member.instanceOrdinal < 0 ||\n input.member.instanceOrdinal > 0xffffffff\n ) {\n return err(\n invalid(\n 'range-overflow',\n 'reserve',\n 'member is a stable World identity plus exact unsigned 32-bit entity, draw-item, and instance identities',\n input.member,\n 'member',\n this,\n ),\n );\n }\n if (\n !Number.isSafeInteger(input.recordStart) ||\n !Number.isSafeInteger(input.recordCount) ||\n input.recordStart < 0 ||\n input.recordCount <= 0 ||\n input.recordStart + input.recordCount > this.schema.maxRecords\n ) {\n return err(\n invalid(\n 'range-overflow',\n 'reserve',\n 'record range and instance index fit the declared page',\n input,\n 'recordStart',\n this,\n ),\n );\n }\n const range: DynamicInputRange = {\n pageId: this.pageId,\n sourceId: this.sourceId,\n domain: input.domain,\n byteOffset: input.recordStart * this.layout.stride,\n recordStart: input.recordStart,\n recordCount: input.recordCount,\n instanceIndex: input.instanceIndex,\n member: Object.freeze({ ...input.member }),\n contentRevision: this.contentRevisionValue,\n bufferGeneration: this.bufferGenerationValue,\n deviceGeneration: this.deviceGenerationValue,\n };\n this.ownedRanges.add(range);\n this.domains.set(input.domain, {\n name: input.domain,\n start: input.recordStart,\n end: input.recordStart + input.recordCount,\n });\n return ok(range);\n }\n\n /** Return detached dirty bytes for the existing resource owner to upload. */\n beginUpload(): DynamicInputResult<DynamicInputUploadReceipt> {\n const live = this.assertLive('upload');\n if (!live.ok) return live;\n const ranges = this.dirty.map((range) => ({ ...range }));\n const bytes = ranges.reduce((sum, range) => sum + range.byteEnd - range.byteStart, 0);\n const receipt: DynamicInputUploadReceipt = {\n sourceId: this.sourceId,\n pageId: this.pageId,\n contentRevision: this.contentRevisionValue,\n bufferGeneration: this.bufferGenerationValue,\n deviceGeneration: this.deviceGenerationValue,\n ranges,\n bytes,\n };\n this.ownedUploads.add(receipt);\n return ok(receipt);\n }\n\n /**\n * Commit an upload only after the owning queue write has succeeded. A\n * producer that changed the page while a write was in flight leaves the\n * dirty bytes pending and must retry the new revision.\n */\n commitUpload(receipt: DynamicInputUploadReceipt): DynamicInputResult<true> {\n const live = this.assertLive('upload');\n if (!live.ok) return live;\n if (\n !this.ownedUploads.has(receipt) ||\n receipt.sourceId !== this.sourceId ||\n receipt.pageId !== this.pageId ||\n receipt.bufferGeneration !== this.bufferGenerationValue ||\n receipt.deviceGeneration !== this.deviceGenerationValue ||\n receipt.contentRevision !== this.contentRevisionValue\n ) {\n return err(\n invalid(\n 'stale-generation',\n 'upload',\n 'the upload receipt still describes the current page revision and generation',\n receipt,\n 'receipt',\n this,\n ),\n );\n }\n this.uploadedRevisionValue = receipt.contentRevision;\n this.lastUploadedBytesValue = receipt.bytes;\n for (const range of receipt.ranges) {\n const index = this.dirty.findIndex(\n (candidate) =>\n candidate.byteStart === range.byteStart && candidate.byteEnd === range.byteEnd,\n );\n if (index >= 0) this.dirty.splice(index, 1);\n }\n return ok(true);\n }\n\n /** CPU-only convenience: begin and commit are still explicit in production. */\n upload(): DynamicInputResult<DynamicInputUploadReceipt> {\n const receipt = this.beginUpload();\n if (!receipt.ok) return receipt;\n const committed = this.commitUpload(receipt.value);\n if (!committed.ok) return committed;\n return receipt;\n }\n\n /** Consume an uploaded range after graph submission has completed. */\n consume(\n range: DynamicInputRange,\n frameNumber: number,\n ): DynamicInputResult<DynamicInputConsumptionReceipt> {\n const live = this.assertLive('consume');\n if (!live.ok) return live;\n if (\n !this.ownedRanges.has(range) ||\n range.sourceId !== this.sourceId ||\n range.pageId !== this.pageId ||\n range.bufferGeneration !== this.bufferGenerationValue ||\n range.deviceGeneration !== this.deviceGenerationValue ||\n range.recordStart < 0 ||\n range.recordCount <= 0 ||\n range.recordStart + range.recordCount > this.schema.maxRecords\n ) {\n return err(\n invalid(\n 'stale-generation',\n 'consume',\n 'range belongs to this current page generation',\n range,\n 'generation',\n this,\n ),\n );\n }\n if (this.uploadedRevisionValue < range.contentRevision) {\n return err(\n invalid(\n 'not-uploaded',\n 'consume',\n 'range content revision was uploaded before consumption',\n this.uploadedRevisionValue,\n 'contentRevision',\n this,\n ),\n );\n }\n return ok({ ...range, frameNumber, uploadedRevision: this.uploadedRevisionValue });\n }\n\n /** Device loss/rebuild changes physical generations while source identity stays stable. */\n reconfigureDevice(deviceGeneration: number): DynamicInputResult<number> {\n const live = this.assertLive('reconfigure');\n if (!live.ok) return live;\n if (!Number.isSafeInteger(deviceGeneration) || deviceGeneration < 0) {\n return err(\n invalid(\n 'stale-generation',\n 'reconfigure',\n 'deviceGeneration is a non-negative safe integer',\n deviceGeneration,\n 'deviceGeneration',\n this,\n ),\n );\n }\n const rendererInitialGeneration =\n this.bufferGenerationValue === 1 &&\n this.deviceGenerationValue === 1 &&\n deviceGeneration === 0;\n if (deviceGeneration < this.deviceGenerationValue && !rendererInitialGeneration) {\n return err(\n invalid(\n 'stale-generation',\n 'reconfigure',\n 'deviceGeneration does not precede the current device generation',\n deviceGeneration,\n 'deviceGeneration',\n this,\n ),\n );\n }\n this.deviceGenerationValue = deviceGeneration;\n this.bufferGenerationValue += 1;\n this.uploadedRevisionValue = 0;\n alignRange(this.dirty, 0, this.schema.maxRecords * this.layout.stride);\n return ok(this.bufferGenerationValue);\n }\n\n release(): DynamicInputResult<true> {\n if (this.released) return ok(true);\n this.released = true;\n this.domains.clear();\n this.dirty.length = 0;\n return ok(true);\n }\n\n private assertLive(operation: DynamicInputErrorDetail['operation']): DynamicInputResult<true> {\n return this.released\n ? err(\n invalid(\n 'released',\n operation,\n ERROR_POLICY.released.expected,\n undefined,\n undefined,\n this,\n ),\n )\n : ok(true);\n }\n}\n","export interface ProbeFilterState {\n readonly probeIndex: number;\n readonly faceCount: number;\n readonly mipCount: number;\n readonly cursor: number;\n readonly activeGeneration: number;\n}\n\nexport function createProbeFilterState(input: {\n readonly probeIndex: number;\n readonly faceCount?: number;\n readonly mipCount: number;\n readonly activeGeneration?: number;\n}): ProbeFilterState {\n return {\n probeIndex: input.probeIndex,\n faceCount: input.faceCount ?? 6,\n mipCount: input.mipCount,\n cursor: 0,\n activeGeneration: input.activeGeneration ?? 0,\n };\n}\n\nexport function advanceProbeFilter(\n state: ProbeFilterState,\n):\n | { readonly probeIndex: number; readonly faceIndex: number; readonly mipLevel: number }\n | undefined {\n const total = state.faceCount * state.mipCount;\n if (state.cursor >= total) return undefined;\n return {\n probeIndex: state.probeIndex,\n faceIndex: state.cursor % state.faceCount,\n mipLevel: Math.floor(state.cursor / state.faceCount),\n };\n}\n\nexport function commitProbeFilterStep(state: ProbeFilterState, success: boolean): ProbeFilterState {\n if (!success) return state;\n const nextCursor = state.cursor + 1;\n const complete = nextCursor >= state.faceCount * state.mipCount;\n return {\n ...state,\n cursor: nextCursor,\n activeGeneration: complete ? state.activeGeneration + 1 : state.activeGeneration,\n };\n}\n\nexport function probeFilterIsSteady(state: ProbeFilterState): boolean {\n return state.cursor >= state.faceCount * state.mipCount;\n}\n\nfunction normalize(vector: readonly [number, number, number]): [number, number, number] {\n const length = Math.hypot(vector[0], vector[1], vector[2]);\n if (length === 0) return [0, 0, 1];\n return [vector[0] / length, vector[1] / length, vector[2] / length];\n}\n\nexport function boxProjectReflectionDirection(\n direction: readonly [number, number, number],\n boxCenter: readonly [number, number, number],\n halfExtents: readonly [number, number, number],\n point: readonly [number, number, number],\n): [number, number, number] {\n const ray = normalize(direction);\n for (const axis of [0, 1, 2] as const) {\n if (Math.abs(point[axis] - boxCenter[axis]) >= halfExtents[axis]) return ray;\n }\n let distance = Number.POSITIVE_INFINITY;\n for (let axis = 0; axis < 3; axis += 1) {\n const component = ray[axis] ?? 0;\n if (component === 0) continue;\n const extent = halfExtents[axis] ?? 0;\n const edge = component > 0 ? (boxCenter[axis] ?? 0) + extent : (boxCenter[axis] ?? 0) - extent;\n const candidate = (edge - (point[axis] ?? 0)) / component;\n if (candidate > 0) distance = Math.min(distance, candidate);\n }\n if (!Number.isFinite(distance)) return ray;\n return normalize([\n (point[0] ?? 0) + ray[0] * distance - (boxCenter[0] ?? 0),\n (point[1] ?? 0) + ray[1] * distance - (boxCenter[1] ?? 0),\n (point[2] ?? 0) + ray[2] * distance - (boxCenter[2] ?? 0),\n ]);\n}\n","import type { Buffer, Sampler, TextureView } from '@forgeax/engine-rhi';\n\nexport interface ReflectionProbeTableRow {\n readonly primitiveKey?: string;\n readonly index: number;\n readonly worldId: number;\n readonly entityKey: number;\n readonly center: readonly [number, number, number];\n readonly halfExtents: readonly [number, number, number];\n readonly intensity: number;\n readonly generation: number;\n /** Renderer-owned filtered cube used by the Standard material lane. */\n readonly filteredView?: TextureView;\n /** Renderer-owned sampler paired with filteredView. */\n readonly sampler?: Sampler;\n /** Per-probe uniform payload; keeps MaterialAsset ABI unchanged. */\n readonly uniformBuffer?: Buffer;\n}\n\nexport interface ReflectionProbeTable {\n readonly rows: readonly ReflectionProbeTableRow[];\n readonly cpuIndexByPrimitive: (primitiveKey: string) => number | undefined;\n readonly gpuIndexByPrimitive: (primitiveKey: string) => number | undefined;\n}\n\nexport function buildReflectionProbeTable(\n rows: readonly ReflectionProbeTableRow[],\n): ReflectionProbeTable {\n const ordered = rows.slice().sort((a, b) => a.index - b.index);\n const indices = new Map<string, number>();\n for (const row of ordered) {\n if (row.primitiveKey !== undefined) indices.set(row.primitiveKey, row.index);\n }\n const indexFor = (primitiveKey: string): number | undefined => indices.get(primitiveKey);\n return {\n rows: Object.freeze(ordered),\n cpuIndexByPrimitive: indexFor,\n gpuIndexByPrimitive: indexFor,\n };\n}\n\nexport function reflectionProbeTableBytes(table: ReflectionProbeTable): number {\n return table.rows.length * 48;\n}\n","import type {\n ReflectionFallbackFailureStage,\n ReflectionFallbackInspection,\n ReflectionFallbackReceipt,\n ReflectionFallbackRecoveryAction,\n} from '../inspection-types';\n\nexport interface ReflectionFallbackFailureInput {\n readonly stage: ReflectionFallbackFailureStage;\n readonly code: string;\n readonly expected: string;\n readonly detail?: Readonly<Record<string, unknown>>;\n}\n\nfunction recoveryFor(\n receipt: ReflectionFallbackReceipt,\n failure?: ReflectionFallbackFailureInput,\n): ReflectionFallbackRecoveryAction {\n if (failure !== undefined) {\n const code = failure.code.toLowerCase();\n if (code.includes('device') || code.includes('format') || code.includes('capability')) {\n return 'rebuild';\n }\n if (failure.stage === 'prepare' || failure.stage === 'filter') return 'recapture';\n if (failure.stage === 'build' || failure.stage === 'encode') return 'rebuild';\n if (failure.stage === 'finish' || failure.stage === 'submit') return 'retry';\n // Completion failures may still retain a source-identical committed row;\n // use it as LKG, otherwise retry the producer completion.\n if (failure.stage === 'completion') {\n if (receipt.source === 'probe' && (receipt.state === 'active' || receipt.state === 'lkg')) {\n return 'use-LKG';\n }\n if (\n receipt.source === 'skylight' &&\n (receipt.state === 'active' || receipt.state === 'lkg')\n ) {\n return 'use-Skylight';\n }\n if (receipt.source === 'neutral' && receipt.state === 'neutral') return 'use-neutral';\n return 'retry';\n }\n }\n if (receipt.source === 'probe' && (receipt.state === 'active' || receipt.state === 'lkg')) {\n return 'use-LKG';\n }\n if (receipt.source === 'skylight' || receipt.state === 'lkg') return 'use-Skylight';\n return 'use-neutral';\n}\n\n/** Projects producer state and the latest closed failure into detached facts. */\nexport function inspectReflectionFallback(\n receipt: ReflectionFallbackReceipt,\n failure?: ReflectionFallbackFailureInput,\n): ReflectionFallbackInspection {\n return {\n receipt,\n recoveryAction: recoveryFor(receipt, failure),\n ...(failure === undefined\n ? {}\n : {\n failureStage: failure.stage,\n failureCode: failure.code,\n expected: failure.expected,\n ...(failure.detail === undefined ? {} : { detail: failure.detail }),\n }),\n };\n}\n","import type { ReflectionProbeUpdateIntent } from '../components/reflection-probe';\n\nexport const REFLECTION_PROBE_BYTES_PER_TEXEL = 8;\nexport const DEFAULT_REFLECTION_PROBE_LIMITS = Object.freeze({\n maxProbes: 16,\n maxResolution: 256,\n maxBytes: 64 * 1024 * 1024,\n});\n\nexport interface ReflectionProbeInput {\n readonly halfExtents: readonly [number, number, number];\n readonly priority: number;\n readonly intensity: number;\n readonly resolution: number;\n readonly boxProjection?: boolean;\n}\n\nexport interface ReflectionProbeFact extends ReflectionProbeInput {\n readonly worldId: number;\n readonly entityKey: number;\n readonly center: readonly [number, number, number];\n readonly revision: number;\n readonly updateIntent?: ReflectionProbeUpdateIntent;\n readonly invalidationVersion?: number;\n}\n\nexport interface ReflectionProbeAdmissionLimits {\n readonly maxProbes?: number;\n readonly maxResolution?: number;\n readonly maxBytes?: number;\n}\n\nexport interface ReflectionProbeInvalidInput {\n readonly code: 'reflection-probe-input-invalid';\n readonly field: string;\n readonly value: unknown;\n readonly expected: string;\n}\n\nexport interface ReflectionProbeBudgetFailure {\n readonly code: 'reflection-probe-budget-exceeded';\n readonly requested: number;\n readonly activeCount: number;\n readonly activeBytes: number;\n readonly maxProbes: number;\n readonly maxBytes: number;\n}\n\nexport type ReflectionProbeAdmission =\n | { readonly ok: true; readonly acceptedBytes: number }\n | { readonly ok: false; readonly error: ReflectionProbeBudgetFailure };\n\nexport function validateReflectionProbeInput(\n input: ReflectionProbeInput,\n): { readonly ok: true } | { readonly ok: false; readonly error: ReflectionProbeInvalidInput } {\n for (let index = 0; index < input.halfExtents.length; index += 1) {\n const value = input.halfExtents[index];\n if (value === undefined || !Number.isFinite(value) || value <= 0) {\n return {\n ok: false,\n error: {\n code: 'reflection-probe-input-invalid',\n field: `halfExtents[${index}]`,\n value,\n expected: 'a finite number greater than zero',\n },\n };\n }\n }\n if (!Number.isFinite(input.priority)) {\n return {\n ok: false,\n error: {\n code: 'reflection-probe-input-invalid',\n field: 'priority',\n value: input.priority,\n expected: 'a finite number',\n },\n };\n }\n if (!Number.isFinite(input.intensity) || input.intensity < 0) {\n return {\n ok: false,\n error: {\n code: 'reflection-probe-input-invalid',\n field: 'intensity',\n value: input.intensity,\n expected: 'a finite number greater than or equal to zero',\n },\n };\n }\n if (\n !Number.isInteger(input.resolution) ||\n input.resolution < 16 ||\n (input.resolution & (input.resolution - 1)) !== 0\n ) {\n return {\n ok: false,\n error: {\n code: 'reflection-probe-input-invalid',\n field: 'resolution',\n value: input.resolution,\n expected: 'a power of two of at least 16 pixels',\n },\n };\n }\n return { ok: true };\n}\n\nexport function estimateReflectionProbeBytes(\n resolution: number,\n limits: ReflectionProbeAdmissionLimits = DEFAULT_REFLECTION_PROBE_LIMITS,\n): number {\n const maxResolution = limits.maxResolution ?? DEFAULT_REFLECTION_PROBE_LIMITS.maxResolution;\n const clamped = Math.min(resolution, maxResolution);\n let filteredTexels = 0;\n for (let mip = 0; mip < 5; mip++) {\n const size = Math.max(1, Math.floor(clamped / 2 ** mip));\n filteredTexels += size * size;\n }\n // Raw cube + two alternating filtered cubes + their depth attachments.\n return (\n (clamped * clamped + 2 * filteredTexels) * 6 * REFLECTION_PROBE_BYTES_PER_TEXEL +\n 3 * clamped * clamped * 4\n );\n}\n\nexport function admitReflectionProbe(\n input: ReflectionProbeInput,\n current: { readonly acceptedCount: number; readonly acceptedBytes: number },\n limits: ReflectionProbeAdmissionLimits = DEFAULT_REFLECTION_PROBE_LIMITS,\n): ReflectionProbeAdmission {\n const maxProbes = limits.maxProbes ?? DEFAULT_REFLECTION_PROBE_LIMITS.maxProbes;\n const maxBytes = limits.maxBytes ?? DEFAULT_REFLECTION_PROBE_LIMITS.maxBytes;\n const maxResolution = limits.maxResolution ?? DEFAULT_REFLECTION_PROBE_LIMITS.maxResolution;\n const requested = estimateReflectionProbeBytes(input.resolution, { maxResolution });\n if (\n input.resolution > maxResolution ||\n current.acceptedCount >= maxProbes ||\n current.acceptedBytes + requested > maxBytes\n ) {\n return {\n ok: false,\n error: {\n code: 'reflection-probe-budget-exceeded',\n requested,\n activeCount: current.acceptedCount,\n activeBytes: current.acceptedBytes,\n maxProbes,\n maxBytes,\n },\n };\n }\n return { ok: true, acceptedBytes: current.acceptedBytes + requested };\n}\n\nexport interface ReflectionProbeSelection {\n readonly kind: 'probe';\n readonly worldId: number;\n readonly entityKey: number;\n readonly normalizedDistance: number;\n}\n\nexport interface SkylightSelection {\n readonly kind: 'skylight';\n}\n\nexport type ReflectionProbeSelectionResult = ReflectionProbeSelection | SkylightSelection;\n\nexport type ReflectionFallbackSource = 'probe' | 'skylight' | 'neutral';\n\nexport interface ReflectionFallbackProjectionInput {\n /** Stable renderable identity used to join the main-pass projection. */\n readonly renderableKey?: string;\n /** Stable producer source identity; never a live GPU handle. */\n readonly sourceKey?: string;\n readonly source: ReflectionFallbackSource;\n readonly coverage: number;\n readonly extent?: readonly [number, number, number];\n readonly linearHdr: readonly [number, number, number, number];\n readonly brdfSignature: string;\n}\n\nexport interface ReflectionFallbackProjection extends ReflectionFallbackProjectionInput {\n readonly source: ReflectionFallbackSource;\n}\n\nexport type ReflectionFallbackMismatchKind = 'source' | 'coverage' | 'extent' | 'brdf';\n\nexport interface ReflectionFallbackMismatch {\n readonly code:\n | 'reflection-fallback-source-mismatch'\n | 'reflection-fallback-coverage-mismatch'\n | 'reflection-fallback-extent-mismatch'\n | 'reflection-fallback-brdf-mismatch';\n readonly expected: string;\n readonly actual: string;\n}\n\nexport interface ReflectionFallbackInputInvalid {\n readonly code: 'reflection-fallback-input-invalid';\n readonly field: string;\n readonly expected: string;\n}\n\nexport type ReflectionFallbackProjectionResult =\n | { readonly ok: true; readonly value: ReflectionFallbackProjection }\n | { readonly ok: false; readonly error: ReflectionFallbackInputInvalid };\n\nexport function resolveReflectionFallbackSource(\n selection: ReflectionProbeSelectionResult,\n probeReady: boolean,\n skylightAvailable = true,\n): ReflectionFallbackSource {\n if (selection.kind === 'probe' && probeReady) return 'probe';\n // An unavailable probe follows the producer recovery order: use the active\n // Skylight when one exists, then the producer-owned neutral zero. Returning\n // neutral directly here would make the main Standard lighting lane and the\n // detached fallback projection disagree.\n if (skylightAvailable) return 'skylight';\n return 'neutral';\n}\n\nexport function reflectionFallbackCoverage(\n source: ReflectionFallbackSource,\n fact: ReflectionProbeFact | undefined,\n selection: ReflectionProbeSelectionResult,\n): number {\n if (source === 'neutral') return 0;\n if (source === 'skylight') return 1;\n if (fact === undefined || selection.kind !== 'probe') return 0;\n const normalized = Math.sqrt(Math.max(0, selection.normalizedDistance));\n return Math.max(0, Math.min(1, 1 - normalized / Math.sqrt(3)));\n}\n\nexport function reflectionFallbackSourceKey(\n source: ReflectionFallbackSource,\n selection: ReflectionProbeSelectionResult,\n skylight?: { readonly entityHandle: number; readonly equirectHandle: number },\n): string {\n if (source === 'probe' && selection.kind === 'probe') {\n return `probe:${selection.worldId}:${selection.entityKey}`;\n }\n if (source === 'skylight' && skylight !== undefined) {\n return `skylight:${skylight.entityHandle}:${skylight.equirectHandle}`;\n }\n return source;\n}\n\nexport function reflectionFallbackProjectionSignature(\n input: ReflectionFallbackProjectionInput,\n): string {\n return JSON.stringify({\n renderableKey: input.renderableKey,\n sourceKey: input.sourceKey,\n source: input.source,\n coverage: input.coverage,\n extent: input.extent,\n brdfSignature: input.brdfSignature,\n });\n}\n\nexport function deriveReflectionFallbackProjection(\n input: ReflectionFallbackProjectionInput,\n): ReflectionFallbackProjectionResult {\n if (!Number.isFinite(input.coverage) || input.coverage < 0 || input.coverage > 1) {\n return {\n ok: false,\n error: {\n code: 'reflection-fallback-input-invalid',\n field: 'coverage',\n expected: 'a finite number between zero and one',\n },\n };\n }\n if (input.extent?.some((value) => !Number.isFinite(value) || value <= 0)) {\n return {\n ok: false,\n error: {\n code: 'reflection-fallback-input-invalid',\n field: 'extent',\n expected: 'three finite numbers greater than zero',\n },\n };\n }\n if (input.linearHdr.some((value) => !Number.isFinite(value))) {\n return {\n ok: false,\n error: {\n code: 'reflection-fallback-input-invalid',\n field: 'linearHdr',\n expected: 'four finite linear HDR values',\n },\n };\n }\n if (input.brdfSignature.length === 0) {\n return {\n ok: false,\n error: {\n code: 'reflection-fallback-input-invalid',\n field: 'brdfSignature',\n expected: 'a non-empty BRDF signature',\n },\n };\n }\n const linearHdr = input.source === 'neutral' ? ([0, 0, 0, 0] as const) : [...input.linearHdr];\n return {\n ok: true,\n value: Object.freeze({\n ...(input.renderableKey === undefined ? {} : { renderableKey: input.renderableKey }),\n ...(input.sourceKey === undefined ? {} : { sourceKey: input.sourceKey }),\n source: input.source,\n coverage: input.coverage,\n ...(input.extent === undefined\n ? {}\n : {\n extent: Object.freeze([...input.extent]) as readonly [number, number, number],\n }),\n linearHdr: Object.freeze(linearHdr) as ReflectionFallbackProjection['linearHdr'],\n brdfSignature: input.brdfSignature,\n }),\n };\n}\n\nexport function validateReflectionFallbackCompatibility(\n expected: ReflectionFallbackProjectionInput,\n actual: ReflectionFallbackProjectionInput,\n): { readonly ok: true } | { readonly ok: false; readonly error: ReflectionFallbackMismatch } {\n const mismatch = (\n kind: ReflectionFallbackMismatchKind,\n expectedValue: string,\n actualValue: string,\n ): { readonly ok: false; readonly error: ReflectionFallbackMismatch } => ({\n ok: false,\n error: {\n code: `reflection-fallback-${kind}-mismatch` as ReflectionFallbackMismatch['code'],\n expected: expectedValue,\n actual: actualValue,\n },\n });\n if (expected.source !== actual.source) {\n return mismatch('source', expected.source, actual.source);\n }\n if (expected.coverage !== actual.coverage) {\n return mismatch('coverage', String(expected.coverage), String(actual.coverage));\n }\n const expectedExtent = expected.extent;\n const actualExtent = actual.extent;\n if (\n (expectedExtent === undefined && actualExtent !== undefined) ||\n (expectedExtent !== undefined &&\n (actualExtent === undefined ||\n expectedExtent.some((value, index) => value !== actualExtent[index])))\n ) {\n return mismatch('extent', JSON.stringify(expectedExtent), JSON.stringify(actualExtent));\n }\n if (expected.brdfSignature !== actual.brdfSignature) {\n return mismatch('brdf', expected.brdfSignature, actual.brdfSignature);\n }\n return { ok: true };\n}\n\nfunction contains(fact: ReflectionProbeFact, point: readonly [number, number, number]): boolean {\n return fact.halfExtents.every((extent, axis) => {\n const center = fact.center[axis] ?? 0;\n const coordinate = point[axis] ?? 0;\n return Math.abs(coordinate - center) <= extent;\n });\n}\n\nfunction normalizedDistance(\n fact: ReflectionProbeFact,\n point: readonly [number, number, number],\n): number {\n let squared = 0;\n for (let axis = 0; axis < 3; axis += 1) {\n const delta = (point[axis] ?? 0) - (fact.center[axis] ?? 0);\n const extent = fact.halfExtents[axis] ?? 1;\n squared += (delta / extent) ** 2;\n }\n return squared;\n}\n\nfunction isBetter(\n candidate: ReflectionProbeSelection,\n current: ReflectionProbeSelection,\n facts: readonly ReflectionProbeFact[],\n): boolean {\n const candidateFact = facts.find(\n (fact) => fact.worldId === candidate.worldId && fact.entityKey === candidate.entityKey,\n );\n const currentFact = facts.find(\n (fact) => fact.worldId === current.worldId && fact.entityKey === current.entityKey,\n );\n if (candidateFact === undefined || currentFact === undefined) return false;\n if (candidateFact.priority !== currentFact.priority)\n return candidateFact.priority > currentFact.priority;\n if (candidate.normalizedDistance !== current.normalizedDistance) {\n return candidate.normalizedDistance < current.normalizedDistance;\n }\n return (\n candidate.worldId < current.worldId ||\n (candidate.worldId === current.worldId && candidate.entityKey < current.entityKey)\n );\n}\n\nexport function selectReflectionProbe(\n facts: readonly ReflectionProbeFact[],\n primitiveCenter: readonly [number, number, number],\n): ReflectionProbeSelectionResult {\n let selected: ReflectionProbeSelection | undefined;\n for (const fact of facts) {\n if (!contains(fact, primitiveCenter)) continue;\n const candidate: ReflectionProbeSelection = {\n kind: 'probe',\n worldId: fact.worldId,\n entityKey: fact.entityKey,\n normalizedDistance: normalizedDistance(fact, primitiveCenter),\n };\n if (selected === undefined || isBetter(candidate, selected, facts)) selected = candidate;\n }\n return selected ?? { kind: 'skylight' };\n}\n\nexport interface ReflectionProbePrimitive {\n readonly worldId: number;\n readonly entityKey: number;\n /** Main-pass renderable key; world/entity is retained as the compatibility fallback. */\n readonly renderableKey?: string;\n readonly center: readonly [number, number, number];\n}\n\nexport interface ReflectionProbeProjectionSnapshot {\n readonly revision: number;\n readonly facts: readonly ReflectionProbeFact[];\n readonly selected: ReadonlyMap<string, ReflectionProbeSelectionResult>;\n readonly scannedPrimitives: number;\n}\n\nfunction primitiveKey(worldId: number, entityKey: number): string {\n return `${worldId}:${entityKey}`;\n}\n\nexport class ReflectionProbeProjection {\n private revision = 0;\n private facts: readonly ReflectionProbeFact[] = [];\n private selected = new Map<string, ReflectionProbeSelectionResult>();\n private signature = '';\n private scannedPrimitives = 0;\n\n update(\n facts: readonly ReflectionProbeFact[],\n primitives: readonly ReflectionProbePrimitive[],\n ): ReflectionProbeProjectionSnapshot {\n const nextFacts = facts\n .slice()\n .sort((a, b) => a.worldId - b.worldId || a.entityKey - b.entityKey);\n const signature = JSON.stringify({ facts: nextFacts, primitives });\n if (signature === this.signature) return this.snapshot();\n this.signature = signature;\n this.facts = nextFacts;\n this.selected = new Map();\n for (const primitive of primitives) {\n this.selected.set(\n primitive.renderableKey ?? primitiveKey(primitive.worldId, primitive.entityKey),\n selectReflectionProbe(nextFacts, primitive.center),\n );\n }\n this.scannedPrimitives = primitives.length;\n this.revision += 1;\n return this.snapshot();\n }\n\n snapshot(): ReflectionProbeProjectionSnapshot {\n return {\n revision: this.revision,\n facts: this.facts,\n selected: this.selected,\n scannedPrimitives: this.scannedPrimitives,\n };\n }\n\n selection(worldId: number, entityKey: number): ReflectionProbeSelectionResult {\n return this.selected.get(primitiveKey(worldId, entityKey)) ?? { kind: 'skylight' };\n }\n}\n","import { createVisibilityBudget } from './budget';\n\n/** Detached, bounded LOD/occlusion facts for renderer inspection consumers. */\n\nexport const LOD_OCCLUSION_INSPECTION_SCHEMA = 'forgeax::lod-occlusion-inspection::v2' as const;\nexport const LOD_OCCLUSION_INSPECTION_MAX_BYTES = 16 * 1024;\nconst MAX_INSPECTION_SAMPLES = 64;\n\nexport type LodOcclusionInspectionError = {\n readonly code: string;\n readonly expected: string;\n readonly hint: string;\n readonly detail?: Readonly<Record<string, string | number | boolean>>;\n};\n\nexport type LodOcclusionFallback =\n | { readonly active: false }\n | {\n readonly active: true;\n readonly reason: 'producer-failed' | 'page-exhausted' | 'query-failed' | 'device-loss';\n readonly error: LodOcclusionInspectionError;\n };\n\nexport type LodOcclusionDegradation =\n | { readonly active: false }\n | { readonly active: true; readonly reason: 'all-visible' | 'query-unavailable' };\n\nexport interface LodOcclusionInspectionSample {\n readonly primitiveSlot: number;\n readonly level: number;\n readonly visible: boolean;\n}\n\nexport interface LodOcclusionInspectionRow {\n readonly root: { readonly guid: string; readonly sourceKey: string };\n readonly view: {\n readonly attachmentId: string;\n readonly cameraEntity: number;\n readonly viewRole: 'main' | 'shadow' | 'reflection' | 'probe';\n readonly viewGeneration: number;\n };\n readonly slot: { readonly primitiveSlot: number; readonly slotGeneration: number };\n readonly generation: number;\n readonly count: {\n readonly candidates: number;\n readonly visible: number;\n readonly occluded: number;\n };\n readonly lodHistogram: readonly { readonly level: number; readonly count: number }[];\n /** Map latency for the most recently completed query page (bounded POD). */\n readonly queryLatencyUs: {\n readonly median: number;\n readonly p95: number;\n readonly last: number;\n };\n readonly pagePressure: { readonly used: number; readonly capacity: number };\n readonly fallback: LodOcclusionFallback;\n readonly degradation: LodOcclusionDegradation;\n readonly samples: readonly LodOcclusionInspectionSample[];\n}\n\nexport interface LodOcclusionInspectionSubmit {\n readonly frameId: number;\n readonly build: string;\n readonly deviceGeneration: number;\n}\n\n/**\n * Per-World attribution is only authoritative when the renderer publishes\n * the GPU facts from the same submit that owns the parent inspection. The\n * normal projection path remains useful diagnostics, but it must not be used\n * as evidence for a World-reorder or per-World LOD claim.\n */\nexport type LodOcclusionWorldAttribution =\n | { readonly status: 'unavailable'; readonly reason: 'projection-only' }\n | { readonly status: 'same-submit'; readonly submit: LodOcclusionInspectionSubmit };\n\nexport interface LodOcclusionWorldInspection {\n readonly attachmentId: string;\n readonly rows: readonly LodOcclusionInspectionRow[];\n readonly attribution: LodOcclusionWorldAttribution;\n}\n\nexport interface LodOcclusionInspectionBudget {\n readonly configuredQueryBudget: number;\n readonly effectiveQueryBudget: number;\n readonly settleSubmits: number;\n readonly retestSubmits: number;\n readonly expirySubmits: number;\n}\n\nexport interface LodOcclusionInspection extends LodOcclusionInspectionRow {\n readonly schema: typeof LOD_OCCLUSION_INSPECTION_SCHEMA;\n /** Atomic identity for the submit that produced every row below. */\n readonly submit: LodOcclusionInspectionSubmit;\n /** Immutable budget values used by the query and confidence owners. */\n readonly budget: LodOcclusionInspectionBudget;\n /** Stable attachment identity; array order is never an attribution key. */\n readonly worlds: readonly LodOcclusionWorldInspection[];\n}\n\nexport type LodOcclusionInspectionInput = Omit<\n LodOcclusionInspection,\n 'schema' | 'submit' | 'budget' | 'worlds'\n> & {\n readonly submit?: LodOcclusionInspectionSubmit;\n readonly budget?: LodOcclusionInspectionBudget;\n readonly worlds?: readonly LodOcclusionWorldInspectionInput[];\n};\n\nexport type LodOcclusionWorldInspectionInput = Omit<LodOcclusionWorldInspection, 'attribution'> & {\n readonly attribution?: LodOcclusionWorldAttribution;\n};\n\nexport type LodOcclusionInspectionAction =\n | { readonly action: 'none' }\n | { readonly action: 'rebuild'; readonly sourceKey: string; readonly reason: string }\n | { readonly action: 'cold-cook'; readonly sourceKey: string; readonly reason: string }\n | { readonly action: 'retry'; readonly sourceKey: string; readonly reason: string };\n\nfunction nonNegativeInteger(name: string, value: number): number {\n if (!Number.isInteger(value) || value < 0)\n throw new Error(`${name} must be a non-negative integer`);\n return value;\n}\n\nfunction copyError(error: LodOcclusionInspectionError): LodOcclusionInspectionError {\n return Object.freeze({\n code: error.code,\n expected: error.expected,\n hint: error.hint,\n ...(error.detail === undefined ? {} : { detail: Object.freeze({ ...error.detail }) }),\n });\n}\n\nfunction copyFallback(fallback: LodOcclusionFallback): LodOcclusionFallback {\n return fallback.active\n ? Object.freeze({ ...fallback, error: copyError(fallback.error) })\n : Object.freeze({ active: false });\n}\n\nfunction copySamples(\n samples: readonly LodOcclusionInspectionSample[],\n): readonly LodOcclusionInspectionSample[] {\n return Object.freeze(\n [...samples]\n .sort((left, right) => left.primitiveSlot - right.primitiveSlot)\n .slice(0, MAX_INSPECTION_SAMPLES)\n .map((sample) =>\n Object.freeze({\n primitiveSlot: nonNegativeInteger('sample.primitiveSlot', sample.primitiveSlot),\n level: nonNegativeInteger('sample.level', sample.level),\n visible: sample.visible,\n }),\n ),\n );\n}\n\nfunction copyWorldAttribution(\n attribution: LodOcclusionWorldAttribution | undefined,\n): LodOcclusionWorldAttribution {\n if (attribution === undefined) {\n return Object.freeze({ status: 'unavailable', reason: 'projection-only' });\n }\n if (attribution.status === 'same-submit') {\n if (typeof attribution.submit.build !== 'string' || attribution.submit.build.length === 0) {\n throw new Error('world.attribution.submit.build must be a non-empty string');\n }\n nonNegativeInteger('world.attribution.submit.frameId', attribution.submit.frameId);\n nonNegativeInteger(\n 'world.attribution.submit.deviceGeneration',\n attribution.submit.deviceGeneration,\n );\n return Object.freeze({\n status: 'same-submit',\n submit: Object.freeze({ ...attribution.submit }),\n });\n }\n if (attribution.status !== 'unavailable' || attribution.reason !== 'projection-only') {\n throw new Error('world.attribution must declare same-submit or projection-only');\n }\n return Object.freeze({ status: 'unavailable', reason: 'projection-only' });\n}\n\nfunction copyRow(row: LodOcclusionInspectionRow): LodOcclusionInspectionRow {\n for (const [name, value] of Object.entries({\n generation: row.generation,\n candidates: row.count.candidates,\n visible: row.count.visible,\n occluded: row.count.occluded,\n median: row.queryLatencyUs.median,\n p95: row.queryLatencyUs.p95,\n last: row.queryLatencyUs.last,\n pageUsed: row.pagePressure.used,\n pageCapacity: row.pagePressure.capacity,\n }))\n nonNegativeInteger(`inspection.${name}`, value);\n if (\n row.view.cameraEntity < 0 ||\n row.view.viewGeneration < 0 ||\n row.slot.primitiveSlot < 0 ||\n row.slot.slotGeneration < 0\n ) {\n throw new Error('inspection identity values must be non-negative');\n }\n if (row.pagePressure.used > row.pagePressure.capacity) {\n throw new Error('inspection page pressure exceeds capacity');\n }\n return Object.freeze({\n root: Object.freeze({ ...row.root }),\n view: Object.freeze({ ...row.view }),\n slot: Object.freeze({ ...row.slot }),\n generation: row.generation,\n count: Object.freeze({ ...row.count }),\n lodHistogram: Object.freeze(\n row.lodHistogram.map((histogram) =>\n Object.freeze({\n level: nonNegativeInteger('histogram.level', histogram.level),\n count: nonNegativeInteger('histogram.count', histogram.count),\n }),\n ),\n ),\n queryLatencyUs: Object.freeze({ ...row.queryLatencyUs }),\n pagePressure: Object.freeze({ ...row.pagePressure }),\n fallback: copyFallback(row.fallback),\n degradation: Object.freeze({ ...row.degradation }),\n samples: copySamples(row.samples),\n });\n}\n\nfunction copyWorlds(\n worlds: readonly LodOcclusionWorldInspectionInput[] | undefined,\n fallback: LodOcclusionInspectionRow,\n): readonly LodOcclusionWorldInspection[] {\n const source = worlds ?? [{ attachmentId: fallback.view.attachmentId, rows: [fallback] }];\n return Object.freeze(\n source.map((world) =>\n Object.freeze({\n attachmentId: world.attachmentId,\n rows: Object.freeze(world.rows.map((row) => copyRow(row))),\n attribution: copyWorldAttribution(world.attribution),\n }),\n ),\n );\n}\n\nexport function inspectLodOcclusion(input: LodOcclusionInspectionInput): LodOcclusionInspection {\n const row = copyRow(input);\n const defaultBudget = createVisibilityBudget();\n const budget = input.budget ?? {\n configuredQueryBudget: defaultBudget.configuredQueryBudget,\n effectiveQueryBudget: defaultBudget.effectiveQueryBudget,\n settleSubmits: defaultBudget.settleSubmits,\n retestSubmits: defaultBudget.retestSubmits,\n expirySubmits: defaultBudget.expirySubmits,\n };\n for (const [name, value] of Object.entries(budget))\n nonNegativeInteger(`inspection.budget.${name}`, value);\n const submit = input.submit ?? {\n frameId: input.generation,\n build: 'unknown',\n deviceGeneration: 0,\n };\n nonNegativeInteger('inspection.submit.frameId', submit.frameId);\n nonNegativeInteger('inspection.submit.deviceGeneration', submit.deviceGeneration);\n if (typeof submit.build !== 'string' || submit.build.length === 0) {\n throw new Error('inspection.submit.build must be a non-empty string');\n }\n const worlds = copyWorlds(input.worlds, row);\n for (const world of worlds) {\n if (\n world.attribution.status === 'same-submit' &&\n (world.attribution.submit.frameId !== submit.frameId ||\n world.attribution.submit.build !== submit.build ||\n world.attribution.submit.deviceGeneration !== submit.deviceGeneration)\n ) {\n throw new Error('world attribution must reference the parent inspection submit');\n }\n }\n const inspection: LodOcclusionInspection = Object.freeze({\n schema: LOD_OCCLUSION_INSPECTION_SCHEMA,\n ...row,\n submit: Object.freeze({ ...submit }),\n budget: Object.freeze({ ...budget }),\n worlds,\n });\n if (JSON.stringify(inspection).length > LOD_OCCLUSION_INSPECTION_MAX_BYTES) {\n throw new Error(`LOD occlusion inspection exceeds ${LOD_OCCLUSION_INSPECTION_MAX_BYTES} bytes`);\n }\n return inspection;\n}\n\nexport function serializeLodOcclusionInspection(inspection: LodOcclusionInspection): string {\n const serialized = JSON.stringify(inspection);\n if (serialized.length > LOD_OCCLUSION_INSPECTION_MAX_BYTES) {\n throw new Error(`LOD occlusion inspection exceeds ${LOD_OCCLUSION_INSPECTION_MAX_BYTES} bytes`);\n }\n return serialized;\n}\n\nexport function consumeLodOcclusionInspection(\n inspection: LodOcclusionInspection,\n): LodOcclusionInspectionAction {\n if (!inspection.fallback.active) return { action: 'none' };\n const { reason, error } = inspection.fallback;\n const action =\n error.code.startsWith('asset-') || reason === 'producer-failed'\n ? 'rebuild'\n : reason === 'query-failed' || reason === 'page-exhausted' || reason === 'device-loss'\n ? 'retry'\n : 'cold-cook';\n return { action, sourceKey: inspection.root.sourceKey, reason };\n}\n","// @forgeax/engine-render - bounded SSR spatial inspection projection.\n\nimport type { ScreenSpaceReflectionData } from '../components/screen-space-reflection';\nimport type { ReflectionFallbackSource } from '../inspection-types';\nimport type { SsrSpatialAdmission, SsrSpatialLane, SsrSpatialWork } from './admission';\nimport type { SsrConfigInvalidError, SsrUnavailableError } from './errors';\nimport type { SsrHistoryState } from './history';\n\nexport type SsrSpatialInspectionFailure = SsrConfigInvalidError | SsrUnavailableError;\n\nexport interface SsrSpatialHistoryInspection {\n readonly state: 'not-owned' | SsrHistoryState;\n readonly bytes: number;\n readonly resetCount: number;\n}\n\nexport interface SsrSpatialInspectionProjection {\n readonly status?: SsrSpatialInspection['status'];\n readonly coverage?: Partial<SsrSpatialInspection['coverage']>;\n readonly history?: SsrSpatialHistoryInspection;\n readonly passRoster?: readonly string[];\n readonly fallbackSource?: ReflectionFallbackSource;\n readonly failure?: SsrSpatialInspectionFailure;\n}\n\n/** Keep the public projection bounded even if a graph owner supplies a bad list. */\nexport const SSR_INSPECTION_MAX_PASSES = 64 as const;\n\nfunction nonNegativeSafeInteger(name: string, value: number): number {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(`${name} must be a non-negative safe integer`);\n }\n return value;\n}\n\nfunction copyHistory(history: SsrSpatialHistoryInspection): SsrSpatialHistoryInspection {\n nonNegativeSafeInteger('SSR inspection history.bytes', history.bytes);\n nonNegativeSafeInteger('SSR inspection history.resetCount', history.resetCount);\n return Object.freeze({\n state: history.state,\n bytes: history.bytes,\n resetCount: history.resetCount,\n });\n}\n\nfunction copyCoverage(\n coverage: Partial<SsrSpatialInspection['coverage']> | undefined,\n): SsrSpatialInspection['coverage'] {\n const result = {\n hitCount: coverage?.hitCount ?? null,\n fallbackCount: coverage?.fallbackCount ?? null,\n excludedCount: coverage?.excludedCount ?? null,\n };\n for (const [key, value] of Object.entries(result)) {\n if (value !== null) nonNegativeSafeInteger(`SSR inspection coverage.${key}`, value);\n }\n return Object.freeze(result);\n}\n\nfunction copyPassRoster(passRoster: readonly string[] | undefined): readonly string[] {\n return Object.freeze(\n [...(passRoster ?? [])].slice(0, SSR_INSPECTION_MAX_PASSES).map((name, index) => {\n if (typeof name !== 'string' || name.length === 0) {\n throw new Error(`SSR inspection passRoster[${index}] must be a non-empty string`);\n }\n return name;\n }),\n );\n}\n\nexport interface SsrSpatialInspection {\n readonly status: 'not-requested' | 'requested' | 'admitted' | 'fallback-only' | 'structural-only';\n readonly lane: SsrSpatialLane;\n readonly config: ScreenSpaceReflectionData | undefined;\n readonly viewRange: number;\n readonly coverage: {\n /** Null means no GPU coverage measurement is available for this frame. */\n readonly hitCount: number | null;\n readonly fallbackCount: number | null;\n readonly excludedCount: number | null;\n };\n readonly history: SsrSpatialHistoryInspection;\n readonly work: SsrSpatialWork;\n readonly passRoster: readonly string[];\n readonly fallbackSource: ReflectionFallbackSource | undefined;\n readonly failure: SsrSpatialInspectionFailure | undefined;\n}\n\n/** Project only detached, bounded facts from the spatial admission result. */\nexport function projectSsrSpatialInspection(\n admission: SsrSpatialAdmission,\n projection: SsrSpatialInspectionProjection = {},\n): SsrSpatialInspection {\n const config = admission.config;\n return Object.freeze({\n status: projection.status ?? admission.status,\n lane: admission.lane,\n config:\n config === undefined\n ? undefined\n : Object.freeze({\n maxDistance: config.maxDistance,\n thickness: config.thickness,\n maxRoughness: config.maxRoughness,\n }),\n viewRange: admission.viewRange,\n coverage: copyCoverage(projection.coverage),\n history: copyHistory(\n projection.history ?? {\n state: 'not-owned' as const,\n bytes: 0,\n resetCount: 0,\n },\n ),\n work: Object.freeze({ ...admission.work }),\n passRoster: copyPassRoster(projection.passRoster),\n fallbackSource: projection.fallbackSource,\n failure: projection.failure ?? admission.failure,\n });\n}\n\nexport function serializeSsrSpatialInspection(inspection: SsrSpatialInspection): string {\n return JSON.stringify(inspection);\n}\n","import type { Handle, MeshAsset } from '@forgeax/engine-types';\nimport { err, ok, type Result } from '@forgeax/engine-types';\n\n/** A standard MeshAsset candidate prepared for one attached World generation. */\nexport interface DynamicGeometryPrepareInput {\n readonly world: object;\n /** Live ECS entity carrying MeshFilter + MeshRenderer on the attached World. */\n readonly entity?: number;\n /** Optional derived-physics entity whose fixed-step publication gates draw. */\n readonly physicsEntity?: number;\n readonly mesh: MeshAsset;\n /** Existing World.sharedRefs handle whose standard GPU residency is prepared. */\n readonly meshHandle?: Handle<'MeshAsset', 'shared'>;\n readonly revision: number;\n /** Material identity is a consumer fact; MaterialAsset stays in the World. */\n readonly materialIdentity?: string;\n /** Topology changes invalidate motion/history consumers. */\n readonly topologyRevision?: number;\n /** Captured by the Renderer host from the World FixedTime resource. */\n readonly fixedStep?: number;\n}\n\n/** Explicit ECS/fixed-step ordering proof used by Renderer admission. */\nexport interface DynamicGeometryOrdering {\n readonly world: object;\n readonly fixedStep: number;\n}\n\nexport type DynamicGeometryCandidateState =\n | 'prepared'\n | 'accepted'\n | 'published'\n | 'cancelled'\n | 'retired';\n\nexport interface DynamicGeometryCandidate {\n readonly candidateId: string;\n readonly generation: number;\n readonly owner: object;\n readonly world: object;\n readonly entity?: number;\n readonly physicsEntity?: number;\n /** False when the pure lifecycle was used without a shared MeshAsset handle. */\n readonly gpuReady: boolean;\n /** CPU/GPU geometry bytes reserved by this candidate budget. */\n readonly meshBytes: number;\n readonly revision: number;\n readonly topologyRevision: number;\n readonly materialIdentity?: string;\n readonly meshHandle?: Handle<'MeshAsset', 'shared'>;\n readonly fixedStep?: number;\n readonly mesh: MeshAsset;\n readonly state: DynamicGeometryCandidateState;\n}\n\n/** Record-stage lane that consumed a published dynamic-geometry candidate. */\nexport type DynamicGeometryRecordStageLane = 'cpu' | 'gpu' | 'mixed';\n\n/** Receipt that ties candidate publication to the sole Renderer FrameReceipt. */\nexport interface DynamicGeometryReceipt {\n readonly candidateId: string;\n readonly generation: number;\n readonly revision: number;\n readonly topologyRevision: number;\n readonly fixedStep?: number;\n readonly frameId: number;\n readonly deviceGeneration: number;\n readonly frame: {\n readonly frameId: number;\n readonly deviceGeneration: number;\n readonly completed?: Promise<unknown>;\n };\n /** Whether the Renderer record stage consumed this candidate for this frame. */\n readonly recordStageConsumed: boolean;\n /** Lane evidence from the exact submitted record stage, when attached. */\n readonly recordStageLane?: DynamicGeometryRecordStageLane;\n /** Actual frame fixed step; may be newer than the preparation step. */\n readonly publicationFixedStep?: number;\n}\n\nexport interface DynamicGeometryInspection {\n readonly generation: number;\n readonly prepared: number;\n readonly accepted: number;\n readonly published: number;\n readonly retired: number;\n readonly latestRevision?: number;\n readonly latestFrameId?: number;\n readonly historyInvalidations: number;\n readonly invalidated: number;\n readonly meshBytes: number;\n readonly maxMeshBytes: number;\n}\n\nexport type DynamicGeometryErrorCode =\n | 'dynamic-geometry-disposed'\n | 'dynamic-geometry-world-not-attached'\n | 'dynamic-geometry-invalid'\n | 'dynamic-geometry-gpu-failed'\n | 'dynamic-geometry-gpu-not-ready'\n | 'dynamic-geometry-budget-exceeded'\n | 'dynamic-geometry-stale'\n | 'dynamic-geometry-generation-mismatch'\n | 'dynamic-geometry-candidate-not-found'\n | 'dynamic-geometry-candidate-state'\n | 'dynamic-geometry-receipt-mismatch'\n | 'dynamic-geometry-ordering-required';\n\nexport interface DynamicGeometryErrorDetail {\n readonly code: DynamicGeometryErrorCode;\n readonly candidateId?: string;\n readonly revision?: number;\n readonly generation?: number;\n readonly actual?: unknown;\n}\n\nexport class DynamicGeometryError extends Error {\n readonly code: DynamicGeometryErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: DynamicGeometryErrorDetail;\n\n constructor(\n code: DynamicGeometryErrorCode,\n expected: string,\n hint: string,\n detail: Omit<DynamicGeometryErrorDetail, 'code'> = {},\n ) {\n super(`${code}: ${expected}`);\n this.name = 'DynamicGeometryError';\n this.code = code;\n this.expected = expected;\n this.hint = hint;\n this.detail = Object.freeze({ code, ...detail });\n }\n}\n\ninterface CandidateRecord {\n readonly world: object;\n candidate: DynamicGeometryCandidate;\n /** Published history remains queryable for its completion fence, but a\n * newer topology must prevent that history from being consumed again. */\n historyInvalidated: boolean;\n acceptedFrame?: { readonly frameId: number; readonly deviceGeneration: number };\n}\n\n/**\n * A public candidate is a credential, not a mutable state object. Keep the\n * owner/world check in `current` cheap, then compare every scalar admission\n * fact before a caller can cancel, retire, or inspect another record by\n * copying its candidate id. The renderer-owned MeshAsset copy remains the\n * content source for the actual draw.\n */\nexport function sameCandidateCredential(\n candidate: DynamicGeometryCandidate,\n committed: DynamicGeometryCandidate,\n): boolean {\n return (\n candidate.candidateId === committed.candidateId &&\n candidate.owner === committed.owner &&\n candidate.world === committed.world &&\n candidate.generation === committed.generation &&\n candidate.entity === committed.entity &&\n candidate.physicsEntity === committed.physicsEntity &&\n candidate.gpuReady === committed.gpuReady &&\n candidate.meshBytes === committed.meshBytes &&\n candidate.revision === committed.revision &&\n candidate.topologyRevision === committed.topologyRevision &&\n candidate.materialIdentity === committed.materialIdentity &&\n candidate.meshHandle === committed.meshHandle &&\n candidate.fixedStep === committed.fixedStep\n );\n}\n\nfunction cloneTypedArray<T extends Float32Array | Uint16Array | Uint32Array>(value: T): T {\n return new (value.constructor as new (source: T) => T)(value);\n}\n\nfunction cloneMesh(mesh: MeshAsset): MeshAsset {\n const attributes = Object.fromEntries(\n Object.entries(mesh.attributes).map(([key, value]) => [\n key,\n value instanceof ArrayBuffer\n ? value.slice(0)\n : value === undefined\n ? undefined\n : cloneTypedArray(value as never),\n ]),\n ) as MeshAsset['attributes'];\n return Object.freeze({\n ...mesh,\n vertices: new Float32Array(mesh.vertices),\n ...(mesh.indices === undefined ? {} : { indices: cloneTypedArray(mesh.indices) }),\n attributes,\n ...(mesh.aabb === undefined ? {} : { aabb: new Float32Array(mesh.aabb) }),\n submeshes: Object.freeze(mesh.submeshes.map((submesh) => Object.freeze({ ...submesh }))),\n materialSlots: Object.freeze(mesh.materialSlots.map((slot) => Object.freeze({ ...slot }))),\n });\n}\n\nfunction cloneCandidate(candidate: DynamicGeometryCandidate): DynamicGeometryCandidate {\n return Object.freeze({ ...candidate, mesh: cloneMesh(candidate.mesh) });\n}\n\nfunction validateMesh(mesh: MeshAsset): string | undefined {\n if (mesh.kind !== 'mesh') return 'MeshAsset.kind must be mesh';\n if (!(mesh.vertices instanceof Float32Array) || mesh.vertices.length === 0) {\n return 'MeshAsset.vertices must be a non-empty Float32Array';\n }\n // vertices may be interleaved. Attribute layout validation belongs to the\n // mesh producer/residency path; this gate must not assume an xyz-only stride.\n if (\n mesh.indices !== undefined &&\n !(mesh.indices instanceof Uint16Array || mesh.indices instanceof Uint32Array)\n ) {\n return 'MeshAsset.indices must be Uint16Array or Uint32Array';\n }\n if (mesh.submeshes.length === 0)\n return 'MeshAsset.submeshes must contain at least one topology range';\n if (\n mesh.submeshes.some(\n (submesh) =>\n !Number.isSafeInteger(submesh.materialSlot) ||\n submesh.materialSlot < 0 ||\n submesh.materialSlot >= mesh.materialSlots.length,\n )\n ) {\n return 'MeshAsset.materialSlots must cover every referenced materialSlot';\n }\n if (mesh.vertices.some((value) => !Number.isFinite(value)))\n return 'MeshAsset.vertices must be finite';\n return undefined;\n}\n\nfunction meshByteSize(mesh: MeshAsset): number {\n let bytes = mesh.vertices.byteLength + (mesh.indices?.byteLength ?? 0);\n for (const value of Object.values(mesh.attributes)) {\n if (value instanceof ArrayBuffer) bytes += value.byteLength;\n else if (value !== undefined && ArrayBuffer.isView(value)) bytes += value.byteLength;\n }\n if (mesh.aabb !== undefined) bytes += mesh.aabb.byteLength;\n // Submesh/material metadata is intentionally bounded by the candidate\n // count. The reserved byte budget is for typed geometry and GPU upload\n // inputs, which are the resources that can exhaust the renderer.\n return bytes;\n}\n\n/**\n * Renderer-owned lifecycle for standard MeshAsset candidates. It deliberately\n * has no device, buffer, queue, or frame clock; the host supplies generation\n * and FrameReceipt facts at the boundaries below.\n */\nexport interface DynamicGeometryLifecycle {\n prepare(\n input: DynamicGeometryPrepareInput,\n generation: number,\n ): Result<DynamicGeometryCandidate, DynamicGeometryError>;\n accept(\n candidate: DynamicGeometryCandidate,\n ordering?: DynamicGeometryOrdering,\n ): Result<DynamicGeometryCandidate, DynamicGeometryError>;\n cancel(\n candidate: DynamicGeometryCandidate,\n completion?: Promise<unknown>,\n ): Result<void, DynamicGeometryError>;\n retire(candidate: DynamicGeometryCandidate): Result<void, DynamicGeometryError>;\n /** Release the count/byte budget after receipt-bound GPU cleanup completes. */\n finalizeRetirement(candidate: DynamicGeometryCandidate): Result<void, DynamicGeometryError>;\n receipt(candidate: DynamicGeometryCandidate): DynamicGeometryReceipt | undefined;\n publishFrame(\n frame: {\n readonly frameId: number;\n readonly deviceGeneration: number;\n readonly completed?: Promise<unknown>;\n },\n worlds?: readonly object[],\n fixedStep?: number,\n canPublish?: (candidate: DynamicGeometryCandidate) => boolean,\n recordStageLane?: (\n candidate: DynamicGeometryCandidate,\n ) => DynamicGeometryRecordStageLane | undefined,\n ): readonly DynamicGeometryReceipt[];\n invalidateWorld(world: object, completion?: Promise<unknown>): void;\n invalidateGeneration(generation: number): void;\n inspect(): DynamicGeometryInspection;\n dispose(): void;\n}\n\nexport function createDynamicGeometryLifecycle(\n maxCandidates = 32,\n maxMeshBytes = 64 * 1024 * 1024,\n): DynamicGeometryLifecycle {\n const records = new Map<string, CandidateRecord>();\n const owner = {};\n let sequence = 0;\n let currentGeneration = 0;\n let disposed = false;\n let historyInvalidations = 0;\n let latestRevision: number | undefined;\n let latestFrameId: number | undefined;\n let retired = 0;\n let invalidated = 0;\n let meshBytes = 0;\n const latestRevisionByWorld = new WeakMap<object, Map<number | undefined, number>>();\n const latestTopologyRevisionByWorld = new WeakMap<object, Map<number | undefined, number>>();\n const publishedReceipts = new Map<string, DynamicGeometryReceipt>();\n\n const failure = (\n code: DynamicGeometryErrorCode,\n expected: string,\n hint: string,\n detail: Omit<DynamicGeometryErrorDetail, 'code'> = {},\n ): Result<never, DynamicGeometryError> =>\n err(new DynamicGeometryError(code, expected, hint, detail));\n\n const current = (candidate: DynamicGeometryCandidate): CandidateRecord | undefined => {\n const record = records.get(candidate.candidateId);\n if (\n record === undefined ||\n candidate.owner !== owner ||\n record.candidate.owner !== candidate.owner ||\n record.candidate.world !== candidate.world ||\n record.candidate.generation !== candidate.generation\n )\n return undefined;\n return record;\n };\n\n return {\n prepare(input, generation) {\n if (disposed)\n return failure('dynamic-geometry-disposed', 'renderer is alive', 'rebuild the Renderer');\n if (input.world === null || typeof input.world !== 'object') {\n return failure(\n 'dynamic-geometry-world-not-attached',\n 'candidate belongs to an attached World',\n 'attach the World before preparing geometry',\n );\n }\n if (!Number.isInteger(input.revision) || input.revision < 0) {\n return failure(\n 'dynamic-geometry-invalid',\n 'geometry revision is a non-negative integer',\n 'advance the consumer revision monotonically',\n { revision: input.revision },\n );\n }\n if (generation !== currentGeneration && currentGeneration !== 0) {\n return failure(\n 'dynamic-geometry-generation-mismatch',\n 'candidate uses the active renderer generation',\n 'discard stale generation work and prepare again',\n { generation, actual: currentGeneration },\n );\n }\n if (records.size >= maxCandidates) {\n return failure(\n 'dynamic-geometry-budget-exceeded',\n 'candidate count remains within the bounded renderer budget',\n 'cancel or retire an earlier candidate before retrying',\n { actual: records.size },\n );\n }\n const invalid = validateMesh(input.mesh);\n if (invalid !== undefined)\n return failure(\n 'dynamic-geometry-invalid',\n 'MeshAsset satisfies the standard geometry contract',\n invalid,\n );\n const candidateBytes = meshByteSize(input.mesh);\n if (\n !Number.isSafeInteger(candidateBytes) ||\n candidateBytes < 0 ||\n meshBytes > maxMeshBytes - candidateBytes\n ) {\n return failure(\n 'dynamic-geometry-budget-exceeded',\n 'candidate mesh bytes remain within the bounded renderer resource budget',\n 'cancel or retire an earlier candidate before retrying',\n { actual: { meshBytes, candidateBytes, maxMeshBytes } },\n );\n }\n const candidateId = `mesh:${generation}:${++sequence}:${input.revision}`;\n const candidate: DynamicGeometryCandidate = Object.freeze({\n candidateId,\n generation,\n owner,\n world: input.world,\n ...(input.entity === undefined ? {} : { entity: input.entity }),\n ...(input.physicsEntity === undefined ? {} : { physicsEntity: input.physicsEntity }),\n gpuReady: input.meshHandle !== undefined,\n meshBytes: candidateBytes,\n revision: input.revision,\n topologyRevision: input.topologyRevision ?? input.revision,\n ...(input.materialIdentity === undefined\n ? {}\n : { materialIdentity: input.materialIdentity }),\n ...(input.meshHandle === undefined ? {} : { meshHandle: input.meshHandle }),\n ...(input.fixedStep === undefined ? {} : { fixedStep: input.fixedStep }),\n mesh: cloneMesh(input.mesh),\n state: 'prepared',\n });\n records.set(candidateId, {\n world: input.world,\n candidate,\n historyInvalidated: false,\n });\n meshBytes += candidateBytes;\n currentGeneration = generation;\n // Keep the credential handed to the consumer separate from the\n // renderer-owned copy. Mesh typed arrays remain mutable at runtime even\n // when exposed through a readonly TypeScript field.\n return ok(cloneCandidate(candidate));\n },\n accept(candidate, ordering) {\n if (disposed)\n return failure('dynamic-geometry-disposed', 'renderer is alive', 'rebuild the Renderer');\n const record = current(candidate);\n if (record === undefined)\n return failure(\n 'dynamic-geometry-candidate-not-found',\n 'candidate is owned by this renderer',\n 'discard the stale credential',\n );\n if (candidate.generation !== currentGeneration) {\n return failure(\n 'dynamic-geometry-generation-mismatch',\n 'candidate generation matches the active renderer generation',\n 'prepare against the current renderer generation',\n { candidateId: candidate.candidateId },\n );\n }\n if (record.candidate.state !== 'prepared') {\n return failure(\n 'dynamic-geometry-candidate-state',\n 'candidate is prepared exactly once before acceptance',\n 'retain the accepted or published receipt',\n { candidateId: candidate.candidateId },\n );\n }\n if (!sameCandidateCredential(candidate, record.candidate)) {\n return failure(\n 'dynamic-geometry-receipt-mismatch',\n 'acceptance uses the exact prepared candidate credential',\n 'discard the altered credential and use the value returned by prepare',\n { candidateId: candidate.candidateId },\n );\n }\n if (ordering !== undefined) {\n if (\n ordering.world !== record.world ||\n !Number.isInteger(ordering.fixedStep) ||\n ordering.fixedStep < 0\n ) {\n return failure(\n 'dynamic-geometry-ordering-required',\n 'acceptance ordering names the candidate World and a non-negative fixed step',\n 'submit the PhysicsWorld publication ordering for the same attached World',\n { candidateId: candidate.candidateId, actual: ordering },\n );\n }\n }\n const newest = [...records.values()]\n .filter(\n (entry) =>\n entry.candidate.candidateId !== candidate.candidateId &&\n entry.world === record.world &&\n entry.candidate.entity === record.candidate.entity &&\n (entry.candidate.state === 'prepared' || entry.candidate.state === 'accepted'),\n )\n .map((entry) => entry.candidate.revision)\n .concat(latestRevisionByWorld.get(record.world)?.get(record.candidate.entity) ?? -1)\n .sort((a, b) => b - a)[0];\n if (newest !== undefined && record.candidate.revision <= newest) {\n return failure(\n 'dynamic-geometry-stale',\n 'accepted geometry revision is newer than the active candidate',\n 'advance topology revision before accepting',\n { candidateId: candidate.candidateId },\n );\n }\n const accepted = Object.freeze({\n ...record.candidate,\n ...(ordering === undefined ? {} : { fixedStep: ordering.fixedStep }),\n state: 'accepted' as const,\n });\n const previousTopologies = [...records.values()]\n .filter(\n (entry) =>\n entry.candidate.candidateId !== candidate.candidateId &&\n entry.world === record.world &&\n entry.candidate.entity === record.candidate.entity,\n )\n .map((entry) => entry.candidate.topologyRevision);\n const previousLatestTopology = latestTopologyRevisionByWorld\n .get(record.world)\n ?.get(record.candidate.entity);\n const newestTopology = previousTopologies\n .concat(previousLatestTopology === undefined ? [] : [previousLatestTopology])\n .sort((a, b) => b - a)[0];\n if (newestTopology !== undefined && accepted.topologyRevision < newestTopology) {\n return failure(\n 'dynamic-geometry-stale',\n 'accepted topology revision is not older than the active geometry history',\n 'advance topology revision before accepting a replacement candidate',\n { candidateId: candidate.candidateId },\n );\n }\n if (newestTopology !== undefined && accepted.topologyRevision > newestTopology) {\n historyInvalidations += 1;\n // Invalidate publication eligibility, not resource ownership. The host\n // cancels superseded candidates with their allocation completion fence.\n for (const previous of records.values()) {\n if (\n previous.world !== record.world ||\n previous.candidate.entity !== record.candidate.entity ||\n previous.candidate.candidateId === candidate.candidateId ||\n previous.candidate.topologyRevision >= accepted.topologyRevision\n )\n continue;\n if (!previous.historyInvalidated) {\n previous.historyInvalidated = true;\n invalidated += 1;\n }\n }\n }\n record.candidate = accepted;\n return ok(cloneCandidate(accepted));\n },\n cancel(candidate, completion) {\n const record = current(candidate);\n if (record === undefined)\n return failure(\n 'dynamic-geometry-candidate-not-found',\n 'candidate is owned by this renderer',\n 'discard the stale credential',\n );\n if (!sameCandidateCredential(candidate, record.candidate))\n return failure(\n 'dynamic-geometry-receipt-mismatch',\n 'cancellation uses the exact prepared candidate credential',\n 'discard the altered credential and use the value returned by prepare',\n { candidateId: candidate.candidateId },\n );\n if (record.candidate.state !== 'prepared' && record.candidate.state !== 'accepted') {\n return failure(\n 'dynamic-geometry-candidate-state',\n 'only prepared or accepted geometry can be cancelled once',\n 'retire published geometry or await the existing terminal cleanup',\n );\n }\n record.candidate = Object.freeze({ ...record.candidate, state: 'cancelled' as const });\n const release = (): void => {\n if (records.get(candidate.candidateId) !== record) return;\n records.delete(candidate.candidateId);\n meshBytes = Math.max(0, meshBytes - record.candidate.meshBytes);\n };\n if (completion === undefined) release();\n else void completion.then(release, release);\n return ok(undefined);\n },\n retire(candidate) {\n const record = current(candidate);\n if (record === undefined)\n return failure(\n 'dynamic-geometry-candidate-not-found',\n 'retirement uses a published candidate owned by this renderer',\n 'discard the stale credential and do not evict any unrelated mesh',\n { candidateId: candidate.candidateId },\n );\n if (!sameCandidateCredential(candidate, record.candidate))\n return failure(\n 'dynamic-geometry-receipt-mismatch',\n 'retirement uses the exact published candidate credential',\n 'discard the altered credential and use the value returned by publish',\n { candidateId: candidate.candidateId },\n );\n if (record.candidate.state !== 'published') {\n return failure(\n 'dynamic-geometry-candidate-state',\n 'only published geometry can enter receipt-bound retirement',\n 'publish the candidate from a submitted frame first',\n );\n }\n record.candidate = Object.freeze({ ...record.candidate, state: 'retired' as const });\n publishedReceipts.delete(candidate.candidateId);\n retired += 1;\n // Retiring is the logical state transition. Keep the candidate record\n // and its typed bytes until the owner calls `finalizeRetirement` after\n // every record-stage completion fence and GPU lease are gone. This is\n // what makes the declared count/byte budget include in-flight work.\n return ok(undefined);\n },\n finalizeRetirement(candidate) {\n const record = current(candidate);\n if (record === undefined)\n return failure(\n 'dynamic-geometry-candidate-not-found',\n 'retirement finalization uses a candidate retained by this lifecycle',\n 'discard the stale credential or finish the current receipt-bound retirement',\n );\n if (!sameCandidateCredential(candidate, record.candidate))\n return failure(\n 'dynamic-geometry-receipt-mismatch',\n 'retirement finalization uses the exact published candidate credential',\n 'discard the altered credential and use the value returned by publication',\n { candidateId: candidate.candidateId },\n );\n if (record.candidate.state !== 'retired')\n return failure(\n 'dynamic-geometry-candidate-state',\n 'only a retired candidate can release its deferred budget',\n 'retire the published candidate before finalizing its receipt-bound cleanup',\n { candidateId: candidate.candidateId },\n );\n records.delete(candidate.candidateId);\n meshBytes = Math.max(0, meshBytes - record.candidate.meshBytes);\n return ok(undefined);\n },\n publishFrame(frame, worlds, fixedStep, canPublish, recordStageLane) {\n if (disposed || frame.deviceGeneration !== currentGeneration) return [];\n const receipts: DynamicGeometryReceipt[] = [];\n for (const record of records.values()) {\n const canRepeatPublished =\n record.candidate.state === 'published' &&\n // Attached Renderer publication revalidates the entity binding in\n // `canPublish`, so a history-invalidated candidate can still record\n // a real draw for its live entity. Detached lifecycle publication\n // remains one-shot once that history is invalidated.\n (canPublish !== undefined || !record.historyInvalidated);\n if (record.candidate.state !== 'accepted' && !canRepeatPublished) continue;\n if (worlds !== undefined && !worlds.includes(record.world)) continue;\n if (\n record.candidate.fixedStep !== undefined &&\n (fixedStep === undefined || record.candidate.fixedStep > fixedStep)\n ) {\n continue;\n }\n if (canPublish !== undefined && !canPublish(record.candidate)) continue;\n const consumedLane =\n canPublish === undefined ? undefined : recordStageLane?.(record.candidate);\n record.candidate = Object.freeze({ ...record.candidate, state: 'published' as const });\n const receipt = Object.freeze({\n candidateId: record.candidate.candidateId,\n generation: record.candidate.generation,\n revision: record.candidate.revision,\n topologyRevision: record.candidate.topologyRevision,\n ...(record.candidate.fixedStep === undefined\n ? {}\n : { fixedStep: record.candidate.fixedStep }),\n frameId: frame.frameId,\n deviceGeneration: frame.deviceGeneration,\n recordStageConsumed: canPublish !== undefined,\n ...(consumedLane === undefined ? {} : { recordStageLane: consumedLane }),\n ...(fixedStep === undefined ? {} : { publicationFixedStep: fixedStep }),\n frame: Object.freeze({ ...frame }),\n });\n receipts.push(receipt);\n publishedReceipts.set(record.candidate.candidateId, receipt);\n latestRevision = record.candidate.revision;\n latestFrameId = frame.frameId;\n if (!latestRevisionByWorld.has(record.world))\n latestRevisionByWorld.set(record.world, new Map());\n latestRevisionByWorld\n .get(record.world)\n ?.set(record.candidate.entity, record.candidate.revision);\n if (!latestTopologyRevisionByWorld.has(record.world))\n latestTopologyRevisionByWorld.set(record.world, new Map());\n latestTopologyRevisionByWorld\n .get(record.world)\n ?.set(record.candidate.entity, record.candidate.topologyRevision);\n }\n return receipts;\n },\n invalidateWorld(world, completion) {\n for (const [id, record] of records) {\n if (record.world !== world) continue;\n // An earlier terminal operation already owns this reservation's fence.\n if (record.candidate.state === 'cancelled' || record.candidate.state === 'retired')\n continue;\n publishedReceipts.delete(id);\n record.candidate = Object.freeze({ ...record.candidate, state: 'cancelled' as const });\n const release = (): void => {\n if (records.get(id) !== record) return;\n records.delete(id);\n meshBytes = Math.max(0, meshBytes - record.candidate.meshBytes);\n };\n if (completion === undefined) release();\n else void completion.then(release, release);\n invalidated += 1;\n }\n latestRevisionByWorld.delete(world);\n latestTopologyRevisionByWorld.delete(world);\n },\n invalidateGeneration(generation) {\n if (generation === currentGeneration) return;\n currentGeneration = generation;\n const invalidatedWorlds = new Set<object>();\n for (const [id, record] of records) {\n if (record.candidate.generation !== generation) {\n records.delete(id);\n publishedReceipts.delete(id);\n meshBytes = Math.max(0, meshBytes - record.candidate.meshBytes);\n invalidatedWorlds.add(record.world);\n invalidated += 1;\n }\n }\n for (const world of invalidatedWorlds) {\n latestRevisionByWorld.delete(world);\n latestTopologyRevisionByWorld.delete(world);\n }\n },\n receipt(candidate) {\n const receipt = publishedReceipts.get(candidate.candidateId);\n const record = records.get(candidate.candidateId);\n if (record === undefined || !sameCandidateCredential(candidate, record.candidate)) {\n return undefined;\n }\n return receipt?.generation === candidate.generation ? receipt : undefined;\n },\n inspect() {\n let prepared = 0;\n let accepted = 0;\n let published = 0;\n for (const record of records.values()) {\n if (record.candidate.state === 'prepared') prepared += 1;\n else if (record.candidate.state === 'accepted') accepted += 1;\n else if (record.candidate.state === 'published') published += 1;\n }\n return Object.freeze({\n generation: currentGeneration,\n prepared,\n accepted,\n published,\n retired,\n ...(latestRevision === undefined ? {} : { latestRevision }),\n ...(latestFrameId === undefined ? {} : { latestFrameId }),\n historyInvalidations,\n invalidated,\n meshBytes,\n maxMeshBytes,\n });\n },\n dispose() {\n disposed = true;\n records.clear();\n publishedReceipts.clear();\n meshBytes = 0;\n },\n };\n}\n"]}
|