rayzee 10.0.0 → 11.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/README.md +252 -44
  2. package/dist/ActiveColor-YvuQq44O.js +13 -0
  3. package/dist/ArchiveImporter-Hn35o6Z5.js +5145 -0
  4. package/dist/AssetConfig-DSEntE65.js +30 -0
  5. package/dist/BidirectionalIntegrator-CBw8hkeu.js +946 -0
  6. package/dist/BufferLayout-D_IBo2ci.js +150 -0
  7. package/dist/ColorManagement-oeEk7oSu.js +1488 -0
  8. package/dist/EngineEvents-Ci8dVWCP.js +73 -0
  9. package/dist/EngineIssues-CIZnXHsF.js +72 -0
  10. package/dist/FileFormats-sPGJeCRc.js +102 -0
  11. package/dist/Logger-dDDGj9Av.js +97 -0
  12. package/dist/{NeuralRetouch-CYgkQY8Z.js → NeuralRetouch-BzNpiVHZ.js} +8 -6
  13. package/dist/{NeuralSuperRes-PkgDLQcD.js → NeuralSuperRes-Bk7bHg2B.js} +55 -120
  14. package/dist/PathTracer-72XufKAr.js +29976 -0
  15. package/dist/PhysicalSky-BgjdV88k.js +1219 -0
  16. package/dist/RayzeeRenderer-1QRO97eq.js +3551 -0
  17. package/dist/SolarLimb-CPaeZVwz.js +721 -0
  18. package/dist/ToneMapGPU-CjU3osDd.js +177 -0
  19. package/dist/ViewTransforms-CYN7bq2w.js +255 -0
  20. package/dist/WorkingMatrix-C6y233hT.js +27 -0
  21. package/dist/ZipReader-gDSWr0I5.js +98 -0
  22. package/dist/addons/archives.es.js +3 -0
  23. package/dist/addons/bidirectional.es.js +2 -0
  24. package/dist/addons/color.es.js +3 -0
  25. package/dist/addons/formats.es.js +2 -0
  26. package/dist/addons/physical-sky.es.js +2 -0
  27. package/dist/addons/storage.es.js +3 -0
  28. package/dist/archiveFormats-tnAoUL1j.js +94 -0
  29. package/dist/identity-DrQsGT2o.js +39 -0
  30. package/dist/openStorage-DwcBRUj7.js +820 -0
  31. package/dist/rayzee-core.es.js +12 -0
  32. package/dist/rayzee.es.js +2551 -44024
  33. package/dist/rayzee.umd.js +528 -487
  34. package/dist/sceneCachePolicy-C67jbci-.js +443 -0
  35. package/dist/shared-BGBcSxBQ.js +17 -0
  36. package/package.json +23 -2
  37. package/src/Color/ActiveColor.js +34 -0
  38. package/src/Color/BasicColor.js +147 -0
  39. package/src/Color/ColorManagement.js +7 -31
  40. package/src/Color/ViewTransforms.js +5 -1
  41. package/src/EngineDefaults.js +62 -1029
  42. package/src/EngineEvents.js +2 -0
  43. package/src/EngineIssues.js +2 -0
  44. package/src/Headless.js +6 -5
  45. package/src/Passes/AIUpscaler.js +58 -141
  46. package/src/Passes/OIDNDenoiser.js +92 -65
  47. package/src/Passes/OIDNTemporalHistory.js +1 -1
  48. package/src/PathTracerApp.js +620 -4026
  49. package/src/Pipeline/PipelineContext.js +0 -4
  50. package/src/Platform.js +36 -0
  51. package/src/Processor/ArchiveCache.js +20 -7
  52. package/src/Processor/ArchiveImporter.js +1265 -0
  53. package/src/Processor/ArchiveReader.js +22 -4
  54. package/src/Processor/AssetLoader.js +327 -1763
  55. package/src/Processor/AtmosphereModel.js +1 -2
  56. package/src/Processor/BVHBuilder.js +14 -126
  57. package/src/Processor/BVHLeafFold.js +4 -6
  58. package/src/Processor/BVHRefitter.js +67 -46
  59. package/src/Processor/BufferLayout.js +291 -0
  60. package/src/Processor/EmissiveTriangleBuilder.js +1 -1
  61. package/src/Processor/EnvironmentExactTable.js +187 -0
  62. package/src/Processor/EquirectHDRInfo.js +30 -223
  63. package/src/Processor/FileFormats.js +116 -0
  64. package/src/Processor/GLTFDecoders.js +85 -0
  65. package/src/Processor/GLTFDiffuseTransmission.js +63 -0
  66. package/src/Processor/GeometryExtractor.js +15 -5
  67. package/src/Processor/HostMemory.js +7 -1
  68. package/src/Processor/IESParser.js +47 -35
  69. package/src/Processor/InstanceTable.js +1 -1
  70. package/src/Processor/KernelManager.js +35 -2
  71. package/src/Processor/MaterialPacking.js +10 -8
  72. package/src/Processor/PBRT/PBRTMaterials.js +254 -42
  73. package/src/Processor/PBRT/PBRTParser.js +49 -19
  74. package/src/Processor/PBRT/PBRTScattering.js +93 -0
  75. package/src/Processor/PBRT/PBRTSceneBuilder.js +1050 -75
  76. package/src/Processor/PBRT/PBRTTextureBake.js +179 -0
  77. package/src/Processor/PBRT/PFM.js +59 -0
  78. package/src/Processor/PackedRayBuffer.js +116 -9
  79. package/src/Processor/ParallelBVHBuilder.js +3 -6
  80. package/src/Processor/PhysicalSky.js +5 -4
  81. package/src/Processor/PlatformImageLoader.js +50 -6
  82. package/src/Processor/QueueManager.js +39 -5
  83. package/src/Processor/ReinsertionOptimizer.js +2 -2
  84. package/src/Processor/SceneMetadata.js +30 -5
  85. package/src/Processor/SceneProcessor.js +53 -62
  86. package/src/Processor/ShaderBuilder.js +6 -16
  87. package/src/Processor/SimpleSky.js +1 -62
  88. package/src/Processor/SolarLimb.js +3 -0
  89. package/src/Processor/SplitBLAS.js +1 -1
  90. package/src/Processor/StorageTexturePool.js +22 -1
  91. package/src/Processor/TLASBuilder.js +1 -3
  92. package/src/Processor/TextureBuckets.js +237 -0
  93. package/src/Processor/TextureCreator.js +181 -8
  94. package/src/Processor/ToneMapGPU.js +64 -15
  95. package/src/Processor/Workers/BVHRefitWorker.js +5 -2
  96. package/src/Processor/Workers/BVHSubtreeWorker.js +1 -34
  97. package/src/Processor/Workers/BVHWorker.js +5 -18
  98. package/src/Processor/Workers/CDFWorker.js +6 -183
  99. package/src/Processor/Workers/TexturesWorker.js +103 -18
  100. package/src/Processor/archiveFormats.js +7 -0
  101. package/src/Processor/utils.js +2 -1
  102. package/src/RayzeeRenderer.js +3900 -0
  103. package/src/RenderSettings.js +68 -62
  104. package/src/Stages/ASVGF.js +13 -14
  105. package/src/Stages/AutoExposure.js +17 -17
  106. package/src/Stages/BilateralFilter.js +2 -1
  107. package/src/Stages/Compositor.js +8 -23
  108. package/src/Stages/DenoiserSettings.js +182 -0
  109. package/src/Stages/EdgeFilter.js +2 -1
  110. package/src/Stages/MotionVector.js +1 -1
  111. package/src/Stages/NRD.js +11 -5
  112. package/src/Stages/NormalDepth.js +12 -8
  113. package/src/Stages/PathTracer.js +336 -43
  114. package/src/Stages/PathTracerStage.js +69 -66
  115. package/src/Stages/Variance.js +1 -1
  116. package/src/Storage/BLASCache.js +1 -1
  117. package/src/Storage/CDFCache.js +18 -17
  118. package/src/Storage/DownloadCache.js +1 -1
  119. package/src/Storage/SceneGraphCodec.js +46 -3
  120. package/src/Storage/SpillStore.js +1 -1
  121. package/src/Storage/StorageManager.js +45 -9
  122. package/src/Storage/areas.js +4 -0
  123. package/src/TSL/BVHTraversal.js +50 -25
  124. package/src/TSL/Bidirectional.js +208 -0
  125. package/src/TSL/BidirectionalLamps.js +132 -0
  126. package/src/TSL/Clearcoat.js +15 -6
  127. package/src/TSL/Common.js +20 -15
  128. package/src/TSL/ConnectKernel.js +167 -0
  129. package/src/TSL/Debugger.js +1 -1
  130. package/src/TSL/Displacement.js +4 -3
  131. package/src/TSL/EmissiveSampling.js +65 -18
  132. package/src/TSL/Environment.js +77 -106
  133. package/src/TSL/EnvironmentCDF.js +85 -39
  134. package/src/TSL/ExtendKernel.js +8 -3
  135. package/src/TSL/FinalWriteKernel.js +4 -4
  136. package/src/TSL/GenerateKernel.js +18 -4
  137. package/src/TSL/HitFacet.js +35 -5
  138. package/src/TSL/LightBVHSampling.js +40 -9
  139. package/src/TSL/LightGenerateKernel.js +293 -0
  140. package/src/TSL/LightGuide.js +198 -0
  141. package/src/TSL/LightSplatKernel.js +180 -0
  142. package/src/TSL/LightVisibility.js +111 -0
  143. package/src/TSL/LightsCore.js +13 -38
  144. package/src/TSL/LightsDirect.js +28 -29
  145. package/src/TSL/LightsIndirect.js +3 -1
  146. package/src/TSL/LightsSampling.js +239 -51
  147. package/src/TSL/MaterialEvaluation.js +113 -31
  148. package/src/TSL/MaterialProperties.js +44 -17
  149. package/src/TSL/MaterialTransmission.js +52 -47
  150. package/src/TSL/MergeKernel.js +224 -0
  151. package/src/TSL/PathTracerCore.js +65 -29
  152. package/src/TSL/Random.js +5 -1
  153. package/src/TSL/SceneResources.js +51 -0
  154. package/src/TSL/ShadeKernel.js +985 -101
  155. package/src/TSL/Struct.js +10 -0
  156. package/src/TSL/Sun.js +1 -1
  157. package/src/TSL/TextureSampling.js +66 -61
  158. package/src/addons/archives.js +14 -0
  159. package/src/addons/bidirectional.js +13 -0
  160. package/src/addons/color.js +32 -0
  161. package/src/addons/formats.js +16 -0
  162. package/src/addons/physicalSky.js +14 -0
  163. package/src/addons/storage.js +19 -0
  164. package/src/core.js +31 -0
  165. package/src/index.js +13 -23
  166. package/src/integrators/BidirectionalIntegrator.js +838 -0
  167. package/src/managers/AnimationManager.js +88 -6
  168. package/src/managers/CameraManager.js +103 -46
  169. package/src/managers/DenoisingManager.js +14 -10
  170. package/src/managers/EnvironmentManager.js +125 -103
  171. package/src/managers/GoboManager.js +9 -0
  172. package/src/managers/MaterialDataManager.js +48 -37
  173. package/src/managers/UniformManager.js +32 -10
  174. package/dist/ToneMapGPU-B6XIe3DU.js +0 -544
  175. package/dist/rolldown-runtime-CAFD8bLK.js +0 -11
  176. package/src/Processor/TreeletOptimizer.js +0 -574
@@ -0,0 +1,3551 @@
1
+ import { dt as e } from "./SolarLimb-CPaeZVwz.js";
2
+ import { Bt as t, Et as n, It as r, Lt as i, Tt as a, Vt as o, _t as s, bt as c, ct as l, gt as u, ht as d, n as f, ot as ee, st as p, vt as m, xt as h, zt as te } from "./PathTracer-72XufKAr.js";
3
+ import { n as ne, t as g } from "./EngineEvents-Ci8dVWCP.js";
4
+ import { A as _, C as re, D as v, E as ie, O as ae, T as oe, d as se, g as ce, j as le, l as ue, r as de, u as fe, w as pe } from "./sceneCachePolicy-C67jbci-.js";
5
+ import { i as y, r as me } from "./Logger-dDDGj9Av.js";
6
+ import { n as he, s as ge } from "./BufferLayout-D_IBo2ci.js";
7
+ import { i as _e, n as b, t as ve } from "./EngineIssues-CIZnXHsF.js";
8
+ import { n as ye, r as be } from "./shared-BGBcSxBQ.js";
9
+ import { a as xe } from "./WorkingMatrix-C6y233hT.js";
10
+ import { i as x, r as Se, t as S } from "./ActiveColor-YvuQq44O.js";
11
+ import { n as C, r as Ce } from "./AssetConfig-DSEntE65.js";
12
+ import { d as we, l as Te, m as Ee, p as De, t as Oe, u as w } from "./ViewTransforms-CYN7bq2w.js";
13
+ import { n as ke, r as T } from "./identity-DrQsGT2o.js";
14
+ import { t as Ae } from "./ToneMapGPU-CjU3osDd.js";
15
+ import { n as je } from "./archiveFormats-tnAoUL1j.js";
16
+ import { LinearSRGBColorSpace as Me, MeshBasicNodeMaterial as Ne, NodeMaterial as Pe, QuadMesh as E, RectAreaLightNode as Fe, SRGBColorSpace as Ie, TextureNode as Le, WebGPURenderer as Re } from "three/webgpu";
17
+ import { Fn as ze, If as Be, cubeTexture as Ve, dot as He, float as D, int as O, ivec2 as Ue, mix as k, screenCoordinate as We, select as A, storage as Ge, texture as Ke, uint as qe, uniform as j, uv as M, vec3 as N, vec4 as Je } from "three/tsl";
18
+ import { Box3 as Ye, BufferGeometry as Xe, CircleGeometry as Ze, Color as P, DataTexture as Qe, DirectionalLight as $e, DirectionalLightHelper as et, EquirectangularReflectionMapping as tt, EventDispatcher as F, FloatType as nt, LinearFilter as rt, LinearSRGBColorSpace as it, LoaderUtils as I, LoadingManager as at, MathUtils as L, Mesh as ot, MeshPhysicalMaterial as st, NearestFilter as ct, NoBlending as lt, NoToneMapping as ut, Object3D as R, OrthographicCamera as dt, PerspectiveCamera as ft, PointLight as pt, PointLightHelper as mt, REVISION as ht, RGBAFormat as gt, RectAreaLight as z, RenderTarget as _t, SRGBColorSpace as B, Scene as vt, SpotLight as yt, SpotLightHelper as bt, TextureLoader as xt, UnsignedByteType as St, Vector2 as Ct, Vector3 as V } from "three";
19
+ import { RectAreaLightTexturesLib as wt } from "three/addons/lights/RectAreaLightTexturesLib.js";
20
+ import { RectAreaLightHelper as Tt } from "three/addons/helpers/RectAreaLightHelper.js";
21
+ import { GLTFLoader as Et } from "three/addons/loaders/GLTFLoader.js";
22
+ import { HDRLoader as Dt } from "three/addons/loaders/HDRLoader.js";
23
+ import { createMeshesFromMultiMaterialMesh as Ot } from "three/addons/utils/SceneUtils.js";
24
+ import { clone as kt } from "three/addons/utils/SkeletonUtils.js";
25
+ //#region src/SceneHelpers.js
26
+ var At = class {
27
+ constructor() {
28
+ this.scene = new vt(), this._helpers = /* @__PURE__ */ new Map(), this.visible = !1;
29
+ }
30
+ add(e) {
31
+ if (this._helpers.has(e.uuid)) return this._helpers.get(e.uuid);
32
+ let t = this._createHelper(e);
33
+ return t ? (this._helpers.set(e.uuid, t), this.scene.add(t), t) : null;
34
+ }
35
+ remove(e) {
36
+ let t = this._helpers.get(e.uuid);
37
+ t && (t.dispose(), this.scene.remove(t), this._helpers.delete(e.uuid));
38
+ }
39
+ has(e) {
40
+ return this._helpers.has(e.uuid);
41
+ }
42
+ get isDrawing() {
43
+ return this.visible && this._helpers.size > 0;
44
+ }
45
+ update() {
46
+ for (let e of this._helpers.values()) e.update?.();
47
+ }
48
+ sync(e) {
49
+ let t = new Set(e.map((e) => e.uuid));
50
+ for (let [e, n] of this._helpers) t.has(e) || (n.dispose(), this.scene.remove(n), this._helpers.delete(e));
51
+ for (let t of e) this.add(t);
52
+ }
53
+ clear() {
54
+ for (let e of this._helpers.values()) e.dispose(), this.scene.remove(e);
55
+ this._helpers.clear();
56
+ }
57
+ render(e, t) {
58
+ if (!this.isDrawing) return;
59
+ let n = e.autoClear;
60
+ e.autoClear = !1, e.clearDepth(), e.setRenderTarget(null), e.render(this.scene, t), e.autoClear = n;
61
+ }
62
+ dispose() {
63
+ this.clear();
64
+ }
65
+ _createHelper(e) {
66
+ return e.isRectAreaLight ? new Tt(e) : e.isPointLight ? new mt(e, .5) : e.isSpotLight ? new bt(e) : e.isDirectionalLight ? new et(e, .5) : null;
67
+ }
68
+ }, jt = class extends t {
69
+ constructor(t, n = {}) {
70
+ super("Compositor", {
71
+ ...n,
72
+ executionMode: o.ALWAYS
73
+ }), this.renderer = t, this._lightSources = [...n.displaySources ?? [], "pathtracer:color"], this.saturation = j(n.saturation ?? 1), this._transparentBackground = j(0, "int"), this._pathTracer = n.pathTracer ?? null, this._convergenceOverlay = !1, this._debugMaterial = null, this._debugQuad = null, this._debugTexNode = null, this._debugM2Attr = null, this._debugMaskAttr = null, this._debugExposureComp = j(1), this._sourceTexNode = new Le();
74
+ let r = this._sourceTexNode.sample(M()), i = k(N(He(r.xyz, e)), r.xyz, this.saturation), a = A(this._transparentBackground, r.w, 1);
75
+ this.compositorMaterial = new Ne(), this.compositorMaterial.colorNode = Je(i, a), this.compositorMaterial.blending = lt, this.compositorQuad = new E(this.compositorMaterial);
76
+ }
77
+ resolveLightTexture(e) {
78
+ return this.resolveLightSource(e)?.texture ?? null;
79
+ }
80
+ resolveLightSource(e) {
81
+ for (let t of this._lightSources) {
82
+ let n = e.getTexture(t);
83
+ if (n) return {
84
+ key: t,
85
+ texture: n
86
+ };
87
+ }
88
+ return null;
89
+ }
90
+ _ensureDebugMaterial() {
91
+ let t = this._pathTracer?.getConvergenceDebugSource?.();
92
+ if (!t) return !1;
93
+ if (this._debugMaterial && this._debugM2Attr === t.m2 && this._debugMaskAttr === t.frozenMask) return !0;
94
+ this._debugMaterial?.dispose(), this._debugTexNode?.dispose(), this._debugM2Attr = t.m2, this._debugMaskAttr = t.frozenMask, this._debugTexNode = new Le();
95
+ let n = ze(() => {
96
+ let n = He(this._debugTexNode.sample(M()).toVar().xyz, e).toVar(), r = t.renderWidth, i = t.renderHeight, a = O(M().x.mul(D(r))).min(r.sub(O(1))).max(O(0)), o = qe(O(M().y.mul(D(i))).min(i.sub(O(1))).max(O(0)).mul(r).add(a)).toVar(), s = Ge(t.m2, "float").toReadOnly().element(o).toVar(), c = Ge(t.frozenMask, "uint").toReadOnly().element(o).toVar(), l = s.sub(n.mul(n)).max(D(0)).div(D(t.frame).add(1)).sqrt().toVar(), u = t.usePixelFreeze.greaterThan(O(0)), d = A(n.lessThan(D(1)), n.sqrt(), n).toVar(), f = A(u, l.div(n.add(D(1e-4))), l.div(d.add(D(1e-4)))).toVar(), ee = A(u, t.pixelFreezeThreshold, t.noiseThreshold).toVar(), p = f.div(ee.max(D(1e-6))).toVar(), m = N(n.div(n.add(D(1))).sqrt().mul(.55)).toVar(), h = m.toVar(), te = D(t.frame).greaterThanEqual(D(t.adaptiveMinSamples));
97
+ return Be(p.greaterThanEqual(D(1)).or(te.not()), () => {
98
+ let e = k(N(1, .8, .1), N(1, .1, .05), p.sub(1).div(3).clamp(0, 1));
99
+ h.assign(k(m, e, .85));
100
+ }), Be(c.equal(qe(1)).and(u), () => {
101
+ h.assign(k(m, N(.1, .45, 1), .55));
102
+ }), h;
103
+ });
104
+ return this._debugMaterial = new Ne(), this._debugMaterial.colorNode = Je(n().pow(2.2).mul(this._debugExposureComp), 1), this._debugMaterial.blending = lt, this._debugQuad = new E(this._debugMaterial), !0;
105
+ }
106
+ render(e) {
107
+ if (!this.enabled) return;
108
+ if (this._convergenceOverlay && this._ensureDebugMaterial()) {
109
+ let t = e.getTexture("pathtracer:color");
110
+ if (t) {
111
+ this._debugTexNode.value = t;
112
+ let e = this.renderer.toneMapping !== ut;
113
+ this._debugExposureComp.value = e ? 1 / Math.max(this.renderer.toneMappingExposure, 1e-4) : 1, this.renderer.setRenderTarget(null), this._debugQuad.render(this.renderer);
114
+ return;
115
+ }
116
+ }
117
+ let t = this.resolveLightTexture(e);
118
+ t && (this._sourceTexNode.value = t, this.renderer.setRenderTarget(null), this.compositorQuad.render(this.renderer));
119
+ }
120
+ setConvergenceOverlay(e) {
121
+ this._convergenceOverlay = !!e;
122
+ }
123
+ setSaturation(e) {
124
+ this.saturation.value = e;
125
+ }
126
+ setTransparentBackground(e) {
127
+ this._transparentBackground.value = +!!e;
128
+ }
129
+ dispose() {
130
+ this._sourceTexNode?.dispose(), this.compositorMaterial?.dispose(), this._debugTexNode?.dispose(), this._debugMaterial?.dispose(), this.compositorQuad = null, this._debugQuad = null, this._debugMaterial = null, this._debugTexNode = null, this._pathTracer = null;
131
+ }
132
+ }, Mt = class {
133
+ constructor() {
134
+ this.textures = /* @__PURE__ */ new Map(), this.renderTargets = /* @__PURE__ */ new Map(), this.uniforms = /* @__PURE__ */ new Map(), this.state = {
135
+ frame: 0,
136
+ accumulatedFrames: 0,
137
+ renderMode: 0,
138
+ interactionMode: !1,
139
+ isComplete: !1,
140
+ tileInfo: null,
141
+ currentTile: 0,
142
+ totalTiles: 0,
143
+ cameraChanged: !1,
144
+ cameraMoving: !1,
145
+ width: 0,
146
+ height: 0,
147
+ time: 0,
148
+ deltaTime: 0
149
+ }, this._stateChangeCallbacks = /* @__PURE__ */ new Map();
150
+ }
151
+ setTexture(e, t) {
152
+ this.textures.set(e, t);
153
+ }
154
+ getTexture(e) {
155
+ return this.textures.get(e);
156
+ }
157
+ hasTexture(e) {
158
+ return this.textures.has(e);
159
+ }
160
+ removeTexture(e) {
161
+ this.textures.delete(e);
162
+ }
163
+ getTextureNames() {
164
+ return Array.from(this.textures.keys());
165
+ }
166
+ clearTextures() {
167
+ this.textures.clear();
168
+ }
169
+ setRenderTarget(e, t) {
170
+ this.renderTargets.set(e, t);
171
+ }
172
+ getRenderTarget(e) {
173
+ return this.renderTargets.get(e);
174
+ }
175
+ hasRenderTarget(e) {
176
+ return this.renderTargets.has(e);
177
+ }
178
+ removeRenderTarget(e) {
179
+ this.renderTargets.delete(e);
180
+ }
181
+ getRenderTargetNames() {
182
+ return Array.from(this.renderTargets.keys());
183
+ }
184
+ clearRenderTargets() {
185
+ this.renderTargets.clear();
186
+ }
187
+ setUniform(e, t) {
188
+ this.uniforms.has(e) ? this.uniforms.get(e).value = t : this.uniforms.set(e, { value: t });
189
+ }
190
+ getUniform(e) {
191
+ return this.uniforms.get(e);
192
+ }
193
+ getUniformValue(e) {
194
+ return this.uniforms.get(e)?.value;
195
+ }
196
+ hasUniform(e) {
197
+ return this.uniforms.has(e);
198
+ }
199
+ removeUniform(e) {
200
+ this.uniforms.delete(e);
201
+ }
202
+ getUniformNames() {
203
+ return Array.from(this.uniforms.keys());
204
+ }
205
+ clearUniforms() {
206
+ this.uniforms.clear();
207
+ }
208
+ setState(e, t) {
209
+ let n = this.state[e], r = n !== t;
210
+ return r && (this.state[e] = t, this._notifyStateChange(e, t, n)), r;
211
+ }
212
+ getState(e) {
213
+ return this.state[e];
214
+ }
215
+ getAllState() {
216
+ return this.state;
217
+ }
218
+ setStates(e) {
219
+ let t = [];
220
+ for (let [n, r] of Object.entries(e)) this.setState(n, r) && t.push(n);
221
+ return t;
222
+ }
223
+ hasState(e) {
224
+ return e in this.state;
225
+ }
226
+ watchState(e, t) {
227
+ this._stateChangeCallbacks.has(e) || this._stateChangeCallbacks.set(e, []), this._stateChangeCallbacks.get(e).push(t);
228
+ }
229
+ unwatchState(e, t) {
230
+ if (!this._stateChangeCallbacks.has(e)) return;
231
+ let n = this._stateChangeCallbacks.get(e), r = n.indexOf(t);
232
+ r > -1 && n.splice(r, 1);
233
+ }
234
+ _notifyStateChange(e, t, n) {
235
+ if (!this._stateChangeCallbacks.has(e)) return;
236
+ let r = this._stateChangeCallbacks.get(e);
237
+ for (let i of r) try {
238
+ i(t, n);
239
+ } catch (t) {
240
+ console.error(`Error in state change callback for '${e}':`, t);
241
+ }
242
+ }
243
+ reset() {
244
+ this.state.frame = 0, this.state.accumulatedFrames = 0, this.state.isComplete = !1, this.state.cameraChanged = !0, this.state.currentTile = 0;
245
+ }
246
+ incrementFrame() {
247
+ return this.state.frame++, this.state.accumulatedFrames++, this.state.frame;
248
+ }
249
+ dispose() {
250
+ this.textures.clear(), this.renderTargets.clear(), this.uniforms.clear(), this._stateChangeCallbacks.clear(), this.state = {};
251
+ }
252
+ }, Nt = class extends F {
253
+ constructor() {
254
+ super(), this._onceCallbacks = /* @__PURE__ */ new Map();
255
+ }
256
+ on(e, t) {
257
+ this.addEventListener(e, t);
258
+ }
259
+ once(e, t) {
260
+ let n = (r) => {
261
+ t(r), this.off(e, n), this._onceCallbacks.delete(t);
262
+ };
263
+ this._onceCallbacks.set(t, n), this.on(e, n);
264
+ }
265
+ off(e, t) {
266
+ let n = this._onceCallbacks.get(t);
267
+ n ? (this.removeEventListener(e, n), this._onceCallbacks.delete(t)) : this.removeEventListener(e, t);
268
+ }
269
+ emit(e, t) {
270
+ t && typeof t == "object" && t.type ? this.dispatchEvent(t) : this.dispatchEvent({
271
+ type: e,
272
+ ...t
273
+ });
274
+ }
275
+ removeAllListeners(e) {
276
+ if (e) {
277
+ for (let [t, n] of this._onceCallbacks.entries()) this.hasEventListener(e, n) && (this.removeEventListener(e, n), this._onceCallbacks.delete(t));
278
+ this._listeners && this._listeners[e] && delete this._listeners[e];
279
+ } else this._onceCallbacks.clear(), this._listeners &&= {};
280
+ }
281
+ listenerCount(e) {
282
+ return !this._listeners || !this._listeners[e] ? 0 : this._listeners[e].length;
283
+ }
284
+ clear() {
285
+ this.removeAllListeners();
286
+ }
287
+ eventNames() {
288
+ return this._listeners ? Object.keys(this._listeners) : [];
289
+ }
290
+ }, Pt = !1, H = [], Ft = /* @__PURE__ */ new WeakMap();
291
+ function It(e) {
292
+ Pt = !!e;
293
+ }
294
+ function Lt() {
295
+ return H.slice();
296
+ }
297
+ function Rt() {
298
+ H.length = 0;
299
+ }
300
+ function zt(e) {
301
+ let t = [];
302
+ for (let n of Object.keys(e)) e[n]?.isTextureNode === !0 && t.push(n);
303
+ return t;
304
+ }
305
+ var Bt = (e) => !e || !e.image || !(e.image.width > 0);
306
+ function Vt(e, t, n) {
307
+ if (!Pt) {
308
+ n();
309
+ return;
310
+ }
311
+ let r = Ft.get(e);
312
+ if (r || (r = {
313
+ phase: "pending",
314
+ unboundAtCompile: []
315
+ }, Ft.set(e, r)), r.phase !== "pending") {
316
+ n(), r.phase === "watch" && Ht(e, r);
317
+ return;
318
+ }
319
+ let i = Object.prototype.hasOwnProperty.call(t, "compute"), a = t.compute;
320
+ t.compute = function(...t) {
321
+ return r.phase === "pending" && (r.unboundAtCompile = zt(e).filter((t) => Bt(e[t].value)), r.phase = r.unboundAtCompile.length < 2 ? "done" : "watch"), a.apply(this, t);
322
+ };
323
+ try {
324
+ n();
325
+ } finally {
326
+ i ? t.compute = a : delete t.compute;
327
+ }
328
+ }
329
+ function Ht(e, t) {
330
+ let n = [];
331
+ for (let r of t.unboundAtCompile) {
332
+ let t = e[r]?.value;
333
+ if (Bt(t)) return;
334
+ t.isStorageTexture !== !0 && n.push(r);
335
+ }
336
+ t.phase = "done", n.length !== 0 && H.push({
337
+ stage: e.name,
338
+ nodes: n,
339
+ unboundAtCompile: t.unboundAtCompile.slice(),
340
+ message: `${e.name}: ${n.join(", ")} ${n.length === 1 ? "was" : "were"} still holding EmptyTexture when the stage first dispatched, alongside ${t.unboundAtCompile.length - n.length} other unbound node(s), and later received a non-storage texture. Two nodes unbound at compile time can share one GPU binding and then both resolve to whichever is assigned last. Assign these before the first dispatch.`
341
+ });
342
+ }
343
+ //#endregion
344
+ //#region src/Pipeline/RenderPipeline.js
345
+ var Ut = class {
346
+ _reportStageFailure(e, t, n) {
347
+ console.error(`[Pipeline] Error in stage '${e}' (${t}):`, n);
348
+ let r = `${e}:${t}`;
349
+ this._reportedStageFailures.has(r) || (this._reportedStageFailures.add(r), this._issues?.record(b.STAGE_RENDER_FAILED, `stage "${e}" threw during ${t} — the frame is incomplete`, {
350
+ stage: e,
351
+ phase: t,
352
+ cause: String(n?.message ?? n)
353
+ }));
354
+ }
355
+ constructor(e, t, n, { issues: r = null } = {}) {
356
+ this.renderer = e, this._issues = r, this._reportedStageFailures = /* @__PURE__ */ new Set(), this.width = t, this.height = n, this.stages = [], this.context = new Mt(), this.eventBus = new Nt(), this.context.setState("width", t), this.context.setState("height", n), this.stats = {
357
+ enabled: !1,
358
+ logSkipped: !1,
359
+ timings: /* @__PURE__ */ new Map(),
360
+ frameCount: 0
361
+ };
362
+ }
363
+ addStage(e) {
364
+ this.stages.push(e), e.initialize(this.context, this.eventBus), this.stats.enabled && console.log(`[Pipeline] Added stage: ${e.name}`);
365
+ }
366
+ getStage(e) {
367
+ return this.stages.find((t) => t.name === e);
368
+ }
369
+ removeStage(e) {
370
+ let t = this.stages.findIndex((t) => t.name === e);
371
+ if (t > -1) {
372
+ let e = this.stages[t];
373
+ return this.stages.splice(t, 1), e.dispose && e.dispose(), this.stats.timings.delete(e.name), !0;
374
+ }
375
+ return !1;
376
+ }
377
+ setStageEnabled(e, t) {
378
+ let n = this.getStage(e);
379
+ n && (t ? n.enable() : n.disable());
380
+ }
381
+ render(e = null) {
382
+ let t = this.stats.enabled ? performance.now() : 0;
383
+ for (let t of this.stages) {
384
+ if (!t.shouldExecuteThisFrame(this.context)) {
385
+ this.stats.enabled && this.stats.logSkipped && console.log(`[Pipeline] Skipped stage '${t.name}' (executionMode: ${t.executionMode})`);
386
+ continue;
387
+ }
388
+ try {
389
+ let n = this.stats.enabled ? performance.now() : 0;
390
+ if (Vt(t, this.renderer, () => t.render(this.context, e)), this.stats.enabled) {
391
+ let e = performance.now() - n;
392
+ this.stats.timings.has(t.name) || this.stats.timings.set(t.name, []);
393
+ let r = this.stats.timings.get(t.name);
394
+ r.push(e), r.length > 60 && r.shift();
395
+ }
396
+ } catch (e) {
397
+ this._reportStageFailure(t.name, "render", e);
398
+ }
399
+ }
400
+ if (this.context.incrementFrame(), this.eventBus.emit("frame:complete", {
401
+ frame: this.context.getState("frame"),
402
+ accumulatedFrames: this.context.getState("accumulatedFrames")
403
+ }), this.stats.enabled) {
404
+ let e = performance.now() - t;
405
+ this.stats.timings.has("_total") || this.stats.timings.set("_total", []);
406
+ let n = this.stats.timings.get("_total");
407
+ n.push(e), n.length > 60 && n.shift(), this.stats.frameCount++;
408
+ }
409
+ }
410
+ reset() {
411
+ this.eventBus.emit("pipeline:reset");
412
+ for (let e of this.stages) if (e.reset) try {
413
+ e.reset();
414
+ } catch (t) {
415
+ this._reportStageFailure(e.name, "reset", t);
416
+ }
417
+ this.context.reset(), this.stats.enabled && (this.stats.timings.clear(), this.stats.frameCount = 0);
418
+ }
419
+ setSize(e, t) {
420
+ this.width = e, this.height = t, this.context.setState("width", e), this.context.setState("height", t), this.eventBus.emit("pipeline:resize", {
421
+ width: e,
422
+ height: t
423
+ });
424
+ for (let n of this.stages) if (n.setSize) try {
425
+ n.setSize(e, t);
426
+ } catch (e) {
427
+ console.error(`[Pipeline] Error resizing stage '${n.name}':`, e);
428
+ }
429
+ }
430
+ dispose() {
431
+ for (let e of this.stages) if (e.dispose) try {
432
+ e.dispose();
433
+ } catch (t) {
434
+ console.error(`[Pipeline] Error disposing stage '${e.name}':`, t);
435
+ }
436
+ this.stages = [], this.context.dispose(), this.eventBus.clear(), this.stats.timings.clear();
437
+ }
438
+ setStatsEnabled(e) {
439
+ this.stats.enabled = e, e || (this.stats.timings.clear(), this.stats.frameCount = 0);
440
+ }
441
+ getStats() {
442
+ if (!this.stats.enabled) return null;
443
+ let e = {
444
+ frameCount: this.stats.frameCount,
445
+ stages: {},
446
+ total: 0
447
+ };
448
+ for (let [t, n] of this.stats.timings.entries()) {
449
+ if (n.length === 0) continue;
450
+ let r = n.reduce((e, t) => e + t, 0) / n.length, i = Math.min(...n), a = Math.max(...n);
451
+ t === "_total" ? (e.total = r, e.totalMin = i, e.totalMax = a) : e.stages[t] = {
452
+ avg: r,
453
+ min: i,
454
+ max: a
455
+ };
456
+ }
457
+ return e;
458
+ }
459
+ logStats() {
460
+ let e = this.getStats();
461
+ if (!e) {
462
+ console.log("[Pipeline] Stats not enabled");
463
+ return;
464
+ }
465
+ console.group("[Pipeline] Performance Stats"), console.log(`Frames: ${e.frameCount}`), e.totalMin === void 0 ? console.log("Total: no frames recorded yet (pipeline.render() has not run since stats were enabled — the path tracer may have converged and stopped its animation loop)") : console.log(`Total: ${e.total.toFixed(2)}ms (min: ${e.totalMin.toFixed(2)}ms, max: ${e.totalMax.toFixed(2)}ms)`);
466
+ for (let [t, n] of Object.entries(e.stages)) console.log(` ${t}: ${n.avg.toFixed(2)}ms (min: ${n.min.toFixed(2)}ms, max: ${n.max.toFixed(2)}ms)`);
467
+ console.groupEnd();
468
+ }
469
+ getInfo() {
470
+ return {
471
+ stageCount: this.stages.length,
472
+ enabledStages: this.stages.filter((e) => e.enabled).length,
473
+ stages: this.stages.map((e) => ({
474
+ name: e.name,
475
+ enabled: e.enabled
476
+ })),
477
+ contextState: this.context.getAllState(),
478
+ textures: this.context.getTextureNames(),
479
+ renderTargets: this.context.getRenderTargetNames(),
480
+ uniforms: this.context.getUniformNames(),
481
+ events: this.eventBus.eventNames()
482
+ };
483
+ }
484
+ logInfo() {
485
+ let e = this.getInfo();
486
+ console.group("[Pipeline] Info"), console.log("Stages:", e.stages), console.log("Context Textures:", e.textures), console.log("Context Render Targets:", e.renderTargets), console.log("Context Uniforms:", e.uniforms), console.log("Event Types:", e.events), console.log("State:", e.contextState), console.groupEnd();
487
+ }
488
+ }, Wt = me("engine"), Gt = class {
489
+ constructor() {
490
+ this.timeElapsed = 0, this.lastResetTime = performance.now(), this.renderCompleteDispatched = !1, this.budgetOverrun = !1, this._budgetHeldWarned = !1;
491
+ }
492
+ updateTime() {
493
+ this.timeElapsed = (performance.now() - this.lastResetTime) / 1e3;
494
+ }
495
+ isTimeLimitReached(e, t, n) {
496
+ return t !== "time" || !(n > 0) || this.timeElapsed < n ? !1 : e?.frameCount > 0 ? (this.budgetOverrun = !0, !0) : (this._budgetHeldWarned || (this._budgetHeldWarned = !0, Wt.warn(`render time limit (${n}s) expired before the first sample landed — holding the deadline open to avoid capturing an empty frame`)), !1);
497
+ }
498
+ isLimitReached(e, t, n) {
499
+ return e ? this.isTimeLimitReached(e, t, n) ? !0 : this.stopCondition(e) !== null : !1;
500
+ }
501
+ stopCondition(e) {
502
+ return this.budgetOverrun ? "timeLimit" : e ? e.frameCount >= e.completionThreshold ? "samples" : e._isConvergedComplete?.() ? "converged" : null : null;
503
+ }
504
+ markComplete() {
505
+ return this.renderCompleteDispatched ? !1 : (this.renderCompleteDispatched = !0, !0);
506
+ }
507
+ reset() {
508
+ this.timeElapsed = 0, this.lastResetTime = performance.now(), this.renderCompleteDispatched = !1, this.budgetOverrun = !1, this._budgetHeldWarned = !1;
509
+ }
510
+ resumeFromPause() {
511
+ this.renderCompleteDispatched = !1, this.lastResetTime = performance.now() - this.timeElapsed * 1e3;
512
+ }
513
+ }, Kt = class {
514
+ constructor(e) {
515
+ this.renderer = e, this.target = null, this.material = new Pe(), this.material.name = "rayzee:texture-readback", this.quad = new E(this.material), this._node = null, this._source = null;
516
+ }
517
+ _ensureTarget(e, t) {
518
+ this.target && this.target.width === e && this.target.height === t || (this.target?.dispose(), this.target = new _t(e, t, {
519
+ type: nt,
520
+ format: gt,
521
+ depthBuffer: !1,
522
+ minFilter: ct,
523
+ magFilter: ct
524
+ }));
525
+ }
526
+ async read(e, t, n) {
527
+ try {
528
+ return await this.renderer.readRenderTargetPixelsAsync(this.draw(e, t, n), 0, 0, t, n);
529
+ } finally {
530
+ this.release();
531
+ }
532
+ }
533
+ draw(e, t, n) {
534
+ this._ensureTarget(t, n), this._source !== e && (this._node = Ke(e).load(Ue(We.xy)), this.material.outputNode = this._node, this.material.needsUpdate = !0, this._source = e);
535
+ let r = this.renderer.getRenderTarget();
536
+ return this.renderer.setRenderTarget(this.target), this.quad.render(this.renderer), this.renderer.setRenderTarget(r), this.target;
537
+ }
538
+ release() {
539
+ this.target?.dispose(), this.target = null;
540
+ }
541
+ dispose() {
542
+ this.target?.dispose(), this.material.dispose(), this.target = null, this._source = null, this._node = null;
543
+ }
544
+ }, qt = 864e5, U = Object.freeze({
545
+ IMMUTABLE: "immutable",
546
+ REVALIDATE: "revalidate",
547
+ NETWORK: "network"
548
+ }), W = (e, t) => ({
549
+ loaded: e,
550
+ total: t,
551
+ lengthComputable: t > 0 && e <= t
552
+ }), G = (e, t) => e.headers?.get?.(t) ?? null, Jt = (e) => e.reason ?? new DOMException("aborted", "AbortError");
553
+ function K(e) {
554
+ try {
555
+ let t = new URL(e, globalThis.location?.href ?? "http://localhost/").pathname;
556
+ return decodeURIComponent(t.split("/").pop()) || "download";
557
+ } catch {
558
+ return "download";
559
+ }
560
+ }
561
+ async function Yt(e, { onProgress: t, signal: n }) {
562
+ let r = Number(G(e, "content-length")) || 0, i = G(e, "content-type") ?? "";
563
+ if (!e.body) return new Blob([await e.arrayBuffer()], { type: i });
564
+ let a = e.body.getReader(), o = [], s = 0;
565
+ for (;;) {
566
+ if (n?.aborted) throw a.cancel().catch(() => {}), Jt(n);
567
+ let { done: e, value: i } = await a.read();
568
+ if (e) break;
569
+ o.push(i), s += i.length, t?.(W(s, r));
570
+ }
571
+ return new Blob(o, { type: i });
572
+ }
573
+ var q = (e, t, n) => new File([e], t, {
574
+ type: n || e.type,
575
+ lastModified: e.lastModified ?? Date.now()
576
+ }), Xt = () => {}, J = class {
577
+ constructor(e) {
578
+ this._storage = e, this._revalidating = /* @__PURE__ */ new Set();
579
+ }
580
+ get _area() {
581
+ return this._storage?.area(be.DOWNLOADS) ?? null;
582
+ }
583
+ async fetch(e, { key: t = e, name: n = K(e), policy: r = U.REVALIDATE, maxAgeMs: i = qt, onProgress: a = null, signal: o = null, fetchOptions: s = {} } = {}) {
584
+ let c = this._area;
585
+ if (c && r !== U.NETWORK) {
586
+ let o = await c.open(t);
587
+ if (o) {
588
+ let c = await o.file("data");
589
+ if (c) return r === U.REVALIDATE && Date.now() - (o.extra.checkedAt ?? 0) >= i && this._revalidate(e, t, n, o.extra, s), a?.(W(c.size, c.size)), {
590
+ file: q(c, n, o.extra.contentType),
591
+ release: () => o.release(),
592
+ fromCache: !0
593
+ };
594
+ o.release();
595
+ }
596
+ }
597
+ return this._download(e, t, n, {
598
+ onProgress: a,
599
+ signal: o,
600
+ fetchOptions: s,
601
+ cache: !!c
602
+ });
603
+ }
604
+ async has(e) {
605
+ return await this._area?.has(e) === !0;
606
+ }
607
+ async _download(e, t, n, { onProgress: r, signal: i, fetchOptions: a, cache: o }) {
608
+ if (i?.aborted) throw Jt(i);
609
+ let s = await fetch(e, {
610
+ ...a,
611
+ signal: i
612
+ });
613
+ if (!s.ok) throw Error(`HTTP ${s.status} fetching ${e}`);
614
+ let c = Number(G(s, "content-length")) || 0, l = {
615
+ url: e,
616
+ contentType: G(s, "content-type") ?? "",
617
+ lastModified: G(s, "last-modified"),
618
+ contentLength: c || null,
619
+ checkedAt: Date.now()
620
+ }, u = o && s.body ? await this._area.create(t, {
621
+ label: n,
622
+ expectedBytes: c
623
+ }) : null;
624
+ if (!u) return {
625
+ file: q(await Yt(s, {
626
+ onProgress: r,
627
+ signal: i
628
+ }), n, l.contentType),
629
+ release: Xt,
630
+ fromCache: !1
631
+ };
632
+ try {
633
+ await u.writeStream("data", s.body, {
634
+ signal: i,
635
+ onProgress: (e) => r?.(W(e, c))
636
+ }), await u.commit(l);
637
+ } catch (o) {
638
+ if (await u.abort(), o?.name !== "QuotaExceededError") throw o;
639
+ return this._download(e, t, n, {
640
+ onProgress: r,
641
+ signal: i,
642
+ fetchOptions: a,
643
+ cache: !1
644
+ });
645
+ }
646
+ let d = await this._area.open(t, { wait: !0 }), f = d && await d.file("data");
647
+ if (!f) throw d?.release(), Error(`storage: ${n} vanished right after it was saved`);
648
+ return {
649
+ file: q(f, n, l.contentType),
650
+ release: () => d.release(),
651
+ fromCache: !1
652
+ };
653
+ }
654
+ async _revalidate(e, t, n, r, i) {
655
+ if (this._revalidating.has(t)) return;
656
+ this._revalidating.add(t);
657
+ let a = !1;
658
+ try {
659
+ let t = new Headers(i?.headers);
660
+ t.set("Range", "bytes=0-0");
661
+ let n = await fetch(e, {
662
+ ...i,
663
+ headers: t
664
+ });
665
+ if (n.body?.cancel().catch(() => {}), n.ok) {
666
+ let e = G(n, "last-modified"), t = n.status === 206 ? Number(G(n, "content-range")?.match(/\/(\d+)$/)?.[1]) || null : Number(G(n, "content-length")) || null;
667
+ a = !!(e && r.lastModified && e !== r.lastModified || t && r.contentLength && t !== r.contentLength);
668
+ }
669
+ } catch {}
670
+ try {
671
+ if (a) {
672
+ let { release: r } = await this._download(e, t, n, {
673
+ fetchOptions: i,
674
+ cache: !0
675
+ });
676
+ r();
677
+ } else await this._area.patchMeta(t, { extra: {
678
+ ...r,
679
+ checkedAt: Date.now()
680
+ } });
681
+ } catch {} finally {
682
+ this._revalidating.delete(t);
683
+ }
684
+ }
685
+ };
686
+ function Zt(e, t, n) {
687
+ return new J(t).fetch(e, n);
688
+ }
689
+ function Qt() {
690
+ return new J(ye(C().cacheNamespace));
691
+ }
692
+ async function $t(e, { downloads: t = Qt(), ...n } = {}) {
693
+ if (!t._storage || !/^https?:/i.test(e)) return {
694
+ url: e,
695
+ release: Xt,
696
+ cached: !1
697
+ };
698
+ let { file: r, release: i } = await t.fetch(e, n), a = URL.createObjectURL(r);
699
+ return {
700
+ url: a,
701
+ cached: !0,
702
+ release: () => {
703
+ URL.revokeObjectURL(a), i();
704
+ }
705
+ };
706
+ }
707
+ //#endregion
708
+ //#region src/RenderSettings.js
709
+ var en = {
710
+ maxBounces: {
711
+ uniform: "maxBounces",
712
+ reset: !0
713
+ },
714
+ transmissiveBounces: {
715
+ uniform: "transmissiveBounces",
716
+ reset: !0
717
+ },
718
+ maxSubsurfaceSteps: {
719
+ uniform: "maxSubsurfaceSteps",
720
+ reset: !0
721
+ },
722
+ maxTransparentBounces: {
723
+ uniform: "maxTransparentBounces",
724
+ reset: !0
725
+ },
726
+ environmentIntensity: {
727
+ uniform: "environmentIntensity",
728
+ reset: !0
729
+ },
730
+ backgroundIntensity: {
731
+ uniform: "backgroundIntensity",
732
+ reset: !0
733
+ },
734
+ backgroundBlurriness: {
735
+ uniform: "backgroundBlurriness",
736
+ reset: !0
737
+ },
738
+ backgroundBlurSamples: {
739
+ uniform: "backgroundBlurSamples",
740
+ reset: !0
741
+ },
742
+ showBackground: {
743
+ uniform: "showBackground",
744
+ reset: !0
745
+ },
746
+ enableEnvironment: {
747
+ uniform: "enableEnvironment",
748
+ reset: !0
749
+ },
750
+ groundProjectionEnabled: {
751
+ uniform: "groundProjectionEnabled",
752
+ reset: !0
753
+ },
754
+ groundProjectionRadius: {
755
+ uniform: "groundProjectionRadius",
756
+ reset: !0
757
+ },
758
+ groundProjectionHeight: {
759
+ uniform: "groundProjectionHeight",
760
+ reset: !0
761
+ },
762
+ groundProjectionLevel: {
763
+ uniform: "groundProjectionLevel",
764
+ reset: !0
765
+ },
766
+ enableGroundCatcher: {
767
+ uniform: "enableGroundCatcher",
768
+ reset: !0
769
+ },
770
+ groundCatcherHeight: {
771
+ uniform: "groundCatcherHeight",
772
+ reset: !0
773
+ },
774
+ globalIlluminationIntensity: {
775
+ uniform: "globalIlluminationIntensity",
776
+ reset: !0
777
+ },
778
+ panoramaLevelHorizon: {
779
+ uniform: "panoLevelHorizon",
780
+ reset: !0
781
+ },
782
+ enableDOF: {
783
+ uniform: "enableDOF",
784
+ reset: !0
785
+ },
786
+ focusDistance: {
787
+ uniform: "focusDistance",
788
+ reset: !1
789
+ },
790
+ focalLength: {
791
+ uniform: "focalLength",
792
+ reset: !0
793
+ },
794
+ aperture: {
795
+ uniform: "aperture",
796
+ reset: !0
797
+ },
798
+ apertureScale: {
799
+ uniform: "apertureScale",
800
+ reset: !0
801
+ },
802
+ anamorphicRatio: {
803
+ uniform: "anamorphicRatio",
804
+ reset: !0
805
+ },
806
+ unitsPerMetre: {
807
+ uniform: "unitsPerMetre",
808
+ reset: !0
809
+ },
810
+ dofMode: {
811
+ handler: "handleDofMode",
812
+ reset: !0
813
+ },
814
+ dofBlur: {
815
+ uniform: "dofBlur",
816
+ reset: !0
817
+ },
818
+ samplingTechnique: {
819
+ uniform: "samplingTechnique",
820
+ reset: !0
821
+ },
822
+ fireflyThreshold: {
823
+ uniform: "fireflyThreshold",
824
+ reset: !0
825
+ },
826
+ shadowTerminatorOffset: {
827
+ uniform: "shadowTerminatorOffset",
828
+ reset: !0
829
+ },
830
+ enableAlphaShadows: {
831
+ uniform: "enableAlphaShadows",
832
+ reset: !0
833
+ },
834
+ useAdaptiveSampling: {
835
+ uniform: "useAdaptiveSampling",
836
+ reset: !0
837
+ },
838
+ noiseThreshold: {
839
+ uniform: "noiseThreshold",
840
+ reset: !0
841
+ },
842
+ adaptiveMinSamples: {
843
+ uniform: "adaptiveMinSamples",
844
+ reset: !0
845
+ },
846
+ adaptiveStopFraction: {
847
+ uniform: "adaptiveStopFraction",
848
+ reset: !0
849
+ },
850
+ usePixelFreeze: {
851
+ uniform: "usePixelFreeze",
852
+ reset: !0
853
+ },
854
+ pixelFreezeThreshold: {
855
+ uniform: "pixelFreezeThreshold",
856
+ reset: !0
857
+ },
858
+ pixelFreezeStability: {
859
+ uniform: "pixelFreezeStability",
860
+ reset: !0
861
+ },
862
+ convergenceOverlay: {
863
+ handler: "handleConvergenceOverlay",
864
+ reset: !1
865
+ },
866
+ enableEmissiveTriangleSampling: {
867
+ uniform: "enableEmissiveTriangleSampling",
868
+ reset: !0
869
+ },
870
+ emissiveBoost: {
871
+ uniform: "emissiveBoost",
872
+ reset: !0
873
+ },
874
+ visMode: {
875
+ uniform: "visMode",
876
+ reset: !0
877
+ },
878
+ debugVisScale: {
879
+ uniform: "debugVisScale",
880
+ reset: !0
881
+ },
882
+ cameraProjection: {
883
+ handler: "handleCameraProjection",
884
+ reset: !0
885
+ },
886
+ panoramaLonRange: {
887
+ handler: "handlePanoramaLonRange",
888
+ reset: !0
889
+ },
890
+ panoramaLatRange: {
891
+ handler: "handlePanoramaLatRange",
892
+ reset: !0
893
+ },
894
+ interactionModeEnabled: {
895
+ handler: "handleInteractionModeEnabled",
896
+ reset: !1
897
+ },
898
+ maxSamples: {
899
+ handler: "handleMaxSamples",
900
+ reset: !1
901
+ },
902
+ transparentBackground: { handler: "handleTransparentBackground" },
903
+ backgroundColor: {
904
+ handler: "handleBackgroundColor",
905
+ reset: !0
906
+ },
907
+ exposure: { handler: "handleExposure" },
908
+ saturation: { handler: "handleSaturation" },
909
+ renderLimitMode: { handler: "handleRenderLimitMode" },
910
+ renderTimeLimit: {
911
+ handler: "handleRenderTimeLimit",
912
+ reset: !1
913
+ },
914
+ renderMode: { handler: "handleRenderMode" },
915
+ integrator: {
916
+ handler: "handleIntegrator",
917
+ reset: !0
918
+ },
919
+ shadowRays: {
920
+ handler: "handleShadowRays",
921
+ reset: !0
922
+ },
923
+ environmentRotation: { handler: "handleEnvironmentRotation" },
924
+ wavefrontSortMaterials: {
925
+ handler: "handleWavefrontSortMaterials",
926
+ reset: !1
927
+ },
928
+ maxTextureSize: { reset: !1 },
929
+ areaLightIntensityScale: { reset: !1 }
930
+ }, Y = Object.freeze({
931
+ DEFAULT: "default",
932
+ HOST: "host",
933
+ SCENE_METADATA: "scene-metadata",
934
+ MODE_PRESET: "mode-preset"
935
+ }), tn = class extends F {
936
+ constructor(e = n, { issues: t = null } = {}) {
937
+ super(), this._issues = t, this._defaults = e, this._routes = new Map(Object.entries(en)), this._values = /* @__PURE__ */ new Map(), this._sources = /* @__PURE__ */ new Map(), this._pathTracer = null, this._resetCallback = null, this._handlers = {}, this._initDefaults(e);
938
+ }
939
+ bind(e) {
940
+ this._pathTracer = e.stages.pathTracer, this._resetCallback = e.resetCallback, this._handlers = this._buildHandlers(e);
941
+ }
942
+ define(e, { default: t, apply: n, reset: r = !0 }) {
943
+ if (this._routes.has(e)) throw Error(`setting "${e}" is already defined`);
944
+ this._routes.set(e, {
945
+ apply: n,
946
+ reset: r
947
+ });
948
+ let i = t === void 0 ? this._defaults[e] : t;
949
+ !this._values.has(e) && i !== void 0 && (this._values.set(e, i), this._sources.set(e, Y.DEFAULT));
950
+ }
951
+ _buildHandlers({ stages: e, resetCallback: t, reconcileCompletion: n, applyExposure: r, onCameraProjection: i }) {
952
+ let o = new Ct(), s = (t, n) => {
953
+ o.set(n?.[0] ?? 0, n?.[1] ?? 0).multiplyScalar(L.DEG2RAD), e.pathTracer?.setUniform(t, o);
954
+ };
955
+ return {
956
+ handleCameraProjection: (t) => {
957
+ e.pathTracer?.setUniform("cameraProjection", a[t] ?? a.perspective), i?.(t);
958
+ },
959
+ handleDofMode: (t) => e.pathTracer?.setUniform("dofMode", +(t === "look")),
960
+ handlePanoramaLonRange: (e) => s("panoLonRange", e),
961
+ handlePanoramaLatRange: (e) => s("panoLatRange", e),
962
+ handleTransparentBackground: (t) => {
963
+ e.pathTracer?.setUniform("transparentBackground", t), e.compositor?.setTransparentBackground(t);
964
+ },
965
+ handleBackgroundColor: (t) => {
966
+ let n = t?.isColor ? t : new P(t);
967
+ e.pathTracer?.setUniform("backgroundColor", n);
968
+ },
969
+ handleExposure: (e) => {
970
+ r?.(e);
971
+ },
972
+ handleSaturation: (t) => {
973
+ e.compositor?.setSaturation(t);
974
+ },
975
+ handleConvergenceOverlay: (n) => {
976
+ e.pathTracer?.setUniform("convergenceOverlay", n), e.compositor?.setConvergenceOverlay(n), n && !this.get("useAdaptiveSampling") && t?.();
977
+ },
978
+ handleRenderLimitMode: (t) => {
979
+ e.pathTracer?.setRenderLimitMode?.(t), n?.();
980
+ },
981
+ handleMaxSamples: (t) => {
982
+ e.pathTracer?.setUniform("maxSamples", t), e.pathTracer?.updateCompletionThreshold(), n?.();
983
+ },
984
+ handleRenderTimeLimit: () => {
985
+ n?.();
986
+ },
987
+ handleRenderMode: (t) => {
988
+ e.pathTracer?.setUniform("renderMode", parseInt(t));
989
+ },
990
+ handleIntegrator: (t) => {
991
+ e.pathTracer?.setIntegrator?.(t);
992
+ },
993
+ handleShadowRays: (t) => {
994
+ e.pathTracer?.setShadowRays?.(t);
995
+ },
996
+ handleEnvironmentRotation: (t) => {
997
+ e.pathTracer?.environment.setEnvironmentRotation(t);
998
+ },
999
+ handleWavefrontSortMaterials: (t) => {
1000
+ e.pathTracer && (e.pathTracer.sortMaterials = t);
1001
+ },
1002
+ handleInteractionModeEnabled: (t) => {
1003
+ e.pathTracer?.setInteractionModeEnabled(t);
1004
+ }
1005
+ };
1006
+ }
1007
+ set(e, t, { reset: n, silent: r, source: i = Y.HOST } = {}) {
1008
+ let a = this._applyOne(e, t, i);
1009
+ a?.route && ((n === void 0 ? a.route.reset ?? !0 : n) && this._resetCallback?.(), r || this.dispatchEvent({
1010
+ type: g.SETTING_CHANGED,
1011
+ key: e,
1012
+ value: t,
1013
+ prev: a.prev
1014
+ }));
1015
+ }
1016
+ setMany(e, { silent: t, reset: n, source: r = Y.HOST } = {}) {
1017
+ let i = !1;
1018
+ for (let [n, a] of Object.entries(e)) {
1019
+ let e = this._applyOne(n, a, r);
1020
+ e?.route && ((e.route.reset ?? !0) && (i = !0), t || this.dispatchEvent({
1021
+ type: g.SETTING_CHANGED,
1022
+ key: n,
1023
+ value: a,
1024
+ prev: e.prev
1025
+ }));
1026
+ }
1027
+ (n === void 0 ? i : n) && this._resetCallback?.();
1028
+ }
1029
+ _applyOne(e, t, n) {
1030
+ let r = this._values.get(e);
1031
+ if (r === t) return null;
1032
+ this._values.set(e, t), this._sources.set(e, n);
1033
+ let i = this._routes.get(e);
1034
+ return i ? (this._applyRoute(i, t, r), {
1035
+ route: i,
1036
+ prev: r
1037
+ }) : (this._reportUnknownKey(e), {
1038
+ route: null,
1039
+ prev: r
1040
+ });
1041
+ }
1042
+ _reportUnknownKey(e) {
1043
+ this._issues?.record(b.SETTING_UNKNOWN_KEY, `unknown setting "${e}" — stored but never applied to any stage`, { key: e });
1044
+ }
1045
+ get(e) {
1046
+ return this._values.get(e);
1047
+ }
1048
+ getEffective() {
1049
+ let e = {};
1050
+ for (let [t, n] of this._values) e[t] = {
1051
+ value: n,
1052
+ source: this._sources.get(t) ?? Y.DEFAULT,
1053
+ routed: this._routes.has(t)
1054
+ };
1055
+ return e;
1056
+ }
1057
+ getAll() {
1058
+ return Object.fromEntries(this._values);
1059
+ }
1060
+ serialize() {
1061
+ let e = {};
1062
+ for (let [t, n] of this._values) {
1063
+ if (this._sources.get(t) !== Y.HOST || !this._routes.has(t)) continue;
1064
+ let r = h(n);
1065
+ r !== void 0 && (e[t] = r);
1066
+ }
1067
+ return e;
1068
+ }
1069
+ restore(e) {
1070
+ let t = {}, n = [];
1071
+ for (let [r, i] of Object.entries(e ?? {})) this._routes.has(r) ? t[r] = c(i) : n.push(r);
1072
+ return this.setMany(t), n;
1073
+ }
1074
+ applyAll() {
1075
+ for (let [e, t] of this._values) {
1076
+ let n = this._routes.get(e);
1077
+ n && this._applyRoute(n, t, void 0);
1078
+ }
1079
+ }
1080
+ _applyRoute(e, t, n) {
1081
+ e.uniform ? this._pathTracer?.setUniform(e.uniform, t) : e.handler ? this._handlers[e.handler]?.(t, n) : e.apply?.(t, n);
1082
+ }
1083
+ _initDefaults(e) {
1084
+ for (let t of Object.keys(en)) t in e && (this._values.set(t, e[t]), this._sources.set(t, Y.DEFAULT));
1085
+ }
1086
+ }, nn = class {
1087
+ constructor({ issues: e = null } = {}) {
1088
+ this._issues = e, this._renderer = null, this._offRegistry = De(() => {
1089
+ this._renderer && Ee(this._renderer);
1090
+ });
1091
+ }
1092
+ get hasConfig() {
1093
+ return !1;
1094
+ }
1095
+ get workingSpace() {
1096
+ return S;
1097
+ }
1098
+ get workingSpaceAdopted() {
1099
+ return !1;
1100
+ }
1101
+ get inputKey() {
1102
+ return "-";
1103
+ }
1104
+ attachRenderer(e) {
1105
+ this._renderer = e;
1106
+ let t = Ee(e);
1107
+ return e.outputColorSpace = B, t;
1108
+ }
1109
+ listViews() {
1110
+ return we();
1111
+ }
1112
+ get activeView() {
1113
+ return null;
1114
+ }
1115
+ setActiveView(e) {
1116
+ let t = w(e);
1117
+ if (!t) throw Error(`no view transform with id ${e}`);
1118
+ if (t.outputEncoded) throw Error(`"${t.name}" returns display-encoded colour: it needs rayzee/addons/color`);
1119
+ return this._renderer && (this._renderer.toneMapping = e), t;
1120
+ }
1121
+ _publishWorkingMatrix() {
1122
+ xe(null, S);
1123
+ }
1124
+ loadConfig() {
1125
+ let e = "colour configs need the OCIO pipeline: renderer.setColorManagement( ColorManagement ), from rayzee/addons/color";
1126
+ return this._issues?.record(b.CAPABILITY_MISSING, e, { capability: "color" }), Promise.reject(Error(e));
1127
+ }
1128
+ unloadConfig() {}
1129
+ setWorkingSpace() {}
1130
+ exportPixels(e) {
1131
+ return {
1132
+ rgba: e,
1133
+ colorSpace: S
1134
+ };
1135
+ }
1136
+ status() {
1137
+ let e = this._renderer ? w(this._renderer.toneMapping) : null;
1138
+ return {
1139
+ config: null,
1140
+ workingSpace: S,
1141
+ workingSpaceAdopted: !1,
1142
+ activeTransform: e ? {
1143
+ id: e.id,
1144
+ name: e.name,
1145
+ source: e.source
1146
+ } : null,
1147
+ activeView: null,
1148
+ context: null,
1149
+ exportSpace: null,
1150
+ views: we(),
1151
+ registryVersion: Te(),
1152
+ bakeError: e?.error ?? null
1153
+ };
1154
+ }
1155
+ dispose() {
1156
+ this._offRegistry?.(), this._renderer = null, this._issues = null, Se() === this && (xe(null), x(null));
1157
+ }
1158
+ }, rn = [
1159
+ [/\.jpe?g(\?|#|$)/i, "image/jpeg"],
1160
+ [/\.webp(\?|#|$)/i, "image/webp"],
1161
+ [/\.avif(\?|#|$)/i, "image/avif"]
1162
+ ];
1163
+ function an(e) {
1164
+ return e.mimeType ? e.mimeType : e.uri?.startsWith("data:") ? e.uri.slice(5, e.uri.indexOf(";")) : rn.find(([t]) => t.test(e.uri ?? ""))?.[1] ?? "image/png";
1165
+ }
1166
+ function on(e) {
1167
+ for (let t = 8; t + 12 <= e.length;) {
1168
+ let n = (e[t] << 24 | e[t + 1] << 16 | e[t + 2] << 8 | e[t + 3]) >>> 0, r = t + 12 + n;
1169
+ if (e[t + 4] === 73 && e[t + 5] === 69 && e[t + 6] === 78 && e[t + 7] === 68) return e.subarray(0, r);
1170
+ t = r;
1171
+ }
1172
+ return e;
1173
+ }
1174
+ function sn({ data: e, width: t, height: n }, { shared: r = !1 } = {}) {
1175
+ let i = new Uint8Array(e.buffer, e.byteOffset, t * n * 4), a = i;
1176
+ r && typeof SharedArrayBuffer < "u" && !(i.buffer instanceof SharedArrayBuffer) && (a = new Uint8Array(new SharedArrayBuffer(i.byteLength)), a.set(i));
1177
+ let o = new Qe(a, t, n, gt, St);
1178
+ return o.needsUpdate = !0, o;
1179
+ }
1180
+ function cn(e, t) {
1181
+ return d().decodeImage(t === "image/png" ? on(e) : e, t);
1182
+ }
1183
+ async function ln(e) {
1184
+ let t = await fetch(e);
1185
+ if (!t.ok) throw Error(`HTTP ${t.status}`);
1186
+ return new Uint8Array(await t.arrayBuffer());
1187
+ }
1188
+ function un(e, t) {
1189
+ return t.bufferView === void 0 ? ln(e.options.manager.resolveURL(I.resolveURL(t.uri, e.options.path))) : e.getDependency("bufferView", t.bufferView).then((e) => new Uint8Array(e));
1190
+ }
1191
+ var dn = (e, t) => !!t && t !== e.textureLoader && typeof t.parse == "function";
1192
+ function fn(e, t, n) {
1193
+ if (e.sourceCache[t] !== void 0) return e.sourceCache[t].then((e) => e.clone());
1194
+ let r = un(e, e.json.images[t]).then((e) => new Promise((t, r) => {
1195
+ n.parse(e.buffer.slice(e.byteOffset, e.byteOffset + e.byteLength), t, r);
1196
+ }));
1197
+ return e.sourceCache[t] = r, r;
1198
+ }
1199
+ async function pn(e, t = an({ uri: e })) {
1200
+ let n = sn(await cn(await ln(e), t));
1201
+ return n.flipY = !0, n;
1202
+ }
1203
+ function mn(e, t = null) {
1204
+ return e.loadImageSource = function(e, n) {
1205
+ if (dn(this, n)) return fn(this, e, n);
1206
+ let r = this.json.images[e], i = /* @__PURE__ */ Error("no image decoder in this runtime: configurePlatform( nodePlatform( { decodeImage } ) ) — see \"Running in Node\"");
1207
+ return t?.(r.uri ?? `bufferView ${r.bufferView}`, i), Promise.reject(i);
1208
+ }, { name: "RAYZEE_missing_image_decoder" };
1209
+ }
1210
+ function hn(e, t = null) {
1211
+ return e.loadImageSource = function(e, n) {
1212
+ if (dn(this, n)) return fn(this, e, n);
1213
+ if (this.sourceCache[e] !== void 0) return this.sourceCache[e].then((e) => e.clone());
1214
+ let r = this.json.images[e], i = an(r), a = r.uri ?? `bufferView ${r.bufferView}`, o = un(this, r).then((e) => cn(e, i)).then((e) => {
1215
+ let t = sn(e, { shared: !0 });
1216
+ return r.extras && typeof r.extras == "object" && Object.assign(t.userData, r.extras), t.userData.mimeType = i, t;
1217
+ }).catch((e) => {
1218
+ throw t?.(a, e), e;
1219
+ });
1220
+ return this.sourceCache[e] = o, o;
1221
+ }, { name: "RAYZEE_platform_images" };
1222
+ }
1223
+ //#endregion
1224
+ //#region src/Processor/GLTFDiffuseTransmission.js
1225
+ var gn = "KHR_materials_diffuse_transmission";
1226
+ function _n(e) {
1227
+ let t = (t, n, r, i) => {
1228
+ let a = {};
1229
+ return e.assignTexture(a, n, r, i).then(() => {
1230
+ a[n] && (t[n] = a[n]);
1231
+ });
1232
+ };
1233
+ return {
1234
+ name: gn,
1235
+ afterRoot(n) {
1236
+ let r = e.json.materials ?? [], i = /* @__PURE__ */ new Set(), a = [];
1237
+ for (let o of n.scenes ?? []) o.traverse((n) => {
1238
+ let o = Array.isArray(n.material) ? n.material : n.material ? [n.material] : [];
1239
+ for (let n of o) {
1240
+ if (i.has(n)) continue;
1241
+ i.add(n);
1242
+ let o = e.associations.get(n)?.materials, s = o === void 0 ? null : r[o]?.extensions?.[gn];
1243
+ if (!s) continue;
1244
+ n.diffuseTransmission = s.diffuseTransmissionFactor ?? 0;
1245
+ let [c, l, u] = s.diffuseTransmissionColorFactor ?? [
1246
+ 1,
1247
+ 1,
1248
+ 1
1249
+ ];
1250
+ n.diffuseTransmissionColor = new P().setRGB(c, l, u, it), s.diffuseTransmissionTexture && a.push(t(n, "diffuseTransmissionMap", s.diffuseTransmissionTexture)), s.diffuseTransmissionColorTexture && a.push(t(n, "diffuseTransmissionColorMap", s.diffuseTransmissionColorTexture, B));
1251
+ }
1252
+ });
1253
+ return Promise.all(a);
1254
+ }
1255
+ };
1256
+ }
1257
+ //#endregion
1258
+ //#region src/Processor/GLTFDecoders.js
1259
+ var vn = "KHR_draco_mesh_compression", yn = "KHR_texture_basisu", bn = ["EXT_meshopt_compression", "KHR_meshopt_compression"], xn = new TextDecoder();
1260
+ function Sn(e) {
1261
+ if (typeof e == "string") return e;
1262
+ if (!(e instanceof ArrayBuffer)) return JSON.stringify(e?.extensionsUsed ?? []);
1263
+ let t = new DataView(e);
1264
+ if (!(e.byteLength >= 20 && t.getUint32(0, !0) === 1179937895)) return xn.decode(e);
1265
+ let n = Math.min(t.getUint32(12, !0), e.byteLength - 20);
1266
+ return xn.decode(new Uint8Array(e, 20, n));
1267
+ }
1268
+ async function Cn(e, t, n) {
1269
+ let { dracoDecoderPath: r, ktx2TranscoderPath: i } = C(), [a, o, s] = await Promise.all([
1270
+ t.includes(vn) && !e.dracoLoader ? import("three/addons/loaders/DRACOLoader.js") : null,
1271
+ t.includes(yn) && !e.ktx2Loader ? import("three/addons/loaders/KTX2Loader.js") : null,
1272
+ bn.some((e) => t.includes(e)) && !e.meshoptDecoder ? import("three/addons/libs/meshopt_decoder.module.js") : null
1273
+ ]);
1274
+ if (a) {
1275
+ let t = new a.DRACOLoader();
1276
+ t.setDecoderConfig({ type: "js" }), t.setDecoderPath(r), e.setDRACOLoader(t);
1277
+ }
1278
+ if (o) {
1279
+ let t = new o.KTX2Loader();
1280
+ t.setTranscoderPath(i), n && (t.detectSupport(n), t.workerConfig = {
1281
+ astcSupported: !1,
1282
+ etc1Supported: !1,
1283
+ etc2Supported: !1,
1284
+ dxtSupported: !1,
1285
+ bptcSupported: !1,
1286
+ pvrtcSupported: !1
1287
+ }), e.setKTX2Loader(t);
1288
+ }
1289
+ s && e.setMeshoptDecoder(s.MeshoptDecoder);
1290
+ }
1291
+ function wn(e, t) {
1292
+ let n = e.parse.bind(e);
1293
+ return e.parse = (r, i, a, o) => {
1294
+ Cn(e, Sn(r), t).then(() => n(r, i, a, o), (e) => o?.(e));
1295
+ }, e;
1296
+ }
1297
+ //#endregion
1298
+ //#region src/Processor/AssetLoader.js
1299
+ var Tn = {
1300
+ glb: {
1301
+ type: "model",
1302
+ name: "GLB (GLTF Binary)"
1303
+ },
1304
+ gltf: {
1305
+ type: "model",
1306
+ name: "GLTF"
1307
+ },
1308
+ hdr: {
1309
+ type: "environment",
1310
+ name: "HDR (High Dynamic Range)"
1311
+ },
1312
+ png: {
1313
+ type: "image",
1314
+ name: "PNG"
1315
+ },
1316
+ jpg: {
1317
+ type: "image",
1318
+ name: "JPEG"
1319
+ },
1320
+ jpeg: {
1321
+ type: "image",
1322
+ name: "JPEG"
1323
+ },
1324
+ webp: {
1325
+ type: "image",
1326
+ name: "WebP"
1327
+ }
1328
+ }, X = {
1329
+ addOn: "rayzee/addons/archives",
1330
+ install: "assetLoader.setArchiveImporter()"
1331
+ }, Z = {
1332
+ addOn: "rayzee/addons/formats",
1333
+ install: "assetLoader.registerFormat()"
1334
+ }, En = {
1335
+ zip: X,
1336
+ gz: X,
1337
+ tgz: X,
1338
+ tar: X,
1339
+ fbx: Z,
1340
+ obj: Z,
1341
+ stl: Z,
1342
+ ply: Z,
1343
+ dae: Z,
1344
+ "3mf": Z,
1345
+ usd: Z,
1346
+ usda: Z,
1347
+ usdc: Z,
1348
+ usdz: Z,
1349
+ exr: Z
1350
+ };
1351
+ function Dn(e) {
1352
+ let t = new Xe();
1353
+ for (let n in e.attributes) t.setAttribute(n, e.attributes[n]);
1354
+ e.index && t.setIndex(e.index);
1355
+ for (let n of e.groups) t.addGroup(n.start, n.count, n.materialIndex);
1356
+ return t;
1357
+ }
1358
+ var On = 683;
1359
+ function kn(e, t, n, r) {
1360
+ if (!(r.normalize ?? !0)) return Math.PI;
1361
+ let i = r.shape === "ellipse" || r.shape === "disk" ? Math.PI / 4 : 1, a = e.getWorldScale(new V()), o = Math.PI * i * Math.abs(t * a.x * n * a.y);
1362
+ return Number.isFinite(o) ? o : Math.PI;
1363
+ }
1364
+ var An = class e extends F {
1365
+ constructor(e, t, r, { issues: i = null, areaLightIntensityScale: a = null } = {}) {
1366
+ super(), this.scene = e, this.camera = t, this.controls = r, this.targetModel = null, this.floorPlane = null, this.sceneScale = 1, this.sceneSize = new V(1, 1, 1), this.loaderCache = {}, this.uploadedFileInfo = null, this.animations = [], this.renderer = null, this.sceneMetadata = null, this._loadingManager = new at(), this._loadCancelled = !1, this._urlAbort = null, this.storage = null, this._downloads = null, this._sourceKey = null, this._appended = !1, this.archives = null, this._archiveLoader = null, this._formats = /* @__PURE__ */ new Map(), this._issues = i, this._areaLightIntensityScale = a ?? (() => n.areaLightIntensityScale), this._loadingManager.onError = (e) => {
1367
+ this._loadCancelled || this._issues?.record(b.ASSET_UNREACHABLE, `asset "${e}" could not be fetched — anything depending on it renders without it`, { url: e });
1368
+ };
1369
+ }
1370
+ cancelActiveLoad() {
1371
+ this._loadCancelled = !0, this._loadingManager.abort(), this._urlAbort?.abort();
1372
+ }
1373
+ async _viaCache(t, n, r, { cacheKey: i = t, cachePolicy: a } = {}) {
1374
+ if (!this.storage || !e._isNetworkUrl(t) || /\.gltf$/i.test(t.split(/[?#]/)[0])) return {
1375
+ url: t,
1376
+ release: () => {},
1377
+ cached: !1
1378
+ };
1379
+ let o = new AbortController();
1380
+ this._urlAbort = o;
1381
+ try {
1382
+ return await $t(t, {
1383
+ downloads: this.downloads,
1384
+ key: i,
1385
+ policy: a,
1386
+ name: K(t),
1387
+ signal: o.signal,
1388
+ onProgress: this._downloadProgress(n, r)
1389
+ });
1390
+ } catch (e) {
1391
+ throw this._isCancellation(e) ? this._cancellationError() : e;
1392
+ } finally {
1393
+ this._urlAbort = null;
1394
+ }
1395
+ }
1396
+ get sceneSourceKey() {
1397
+ return this._appended ? null : this._sourceKey;
1398
+ }
1399
+ _keyed(e, t) {
1400
+ return t ? `${e}::${t}` : null;
1401
+ }
1402
+ get downloads() {
1403
+ return this._downloads?._storage !== this.storage && (this._downloads = new J(this.storage)), this._downloads;
1404
+ }
1405
+ _isCancellation(e) {
1406
+ return this._loadCancelled || e?.name === "AbortError" || e?.code === "LOAD_CANCELLED";
1407
+ }
1408
+ _cancellationError() {
1409
+ let e = /* @__PURE__ */ Error("Load cancelled");
1410
+ return e.code = "LOAD_CANCELLED", e;
1411
+ }
1412
+ _downloadProgress(e, t) {
1413
+ return (n) => {
1414
+ let r = n?.loaded || 0, i = n?.lengthComputable && n.total || 0;
1415
+ _({
1416
+ isLoading: !0,
1417
+ status: e,
1418
+ loadedBytes: r,
1419
+ totalBytes: i,
1420
+ canCancel: !!t,
1421
+ progress: i ? Math.min(60, 2 + Math.round(r / i * 58)) : 2
1422
+ });
1423
+ };
1424
+ }
1425
+ _downloadComplete(e = "Processing Data...", t = 62) {
1426
+ _({
1427
+ status: e,
1428
+ progress: t,
1429
+ canCancel: !1,
1430
+ loadedBytes: null,
1431
+ totalBytes: null
1432
+ });
1433
+ }
1434
+ static _isNetworkUrl(e) {
1435
+ return typeof e == "string" && /^https?:/i.test(e);
1436
+ }
1437
+ _adoptExternalObject(e) {
1438
+ let t;
1439
+ try {
1440
+ t = kt(e);
1441
+ } catch (t) {
1442
+ throw Error(`Cannot render "${e.name || e.type}": its userData must be JSON-serializable.`, { cause: t });
1443
+ }
1444
+ return t.userData.__rayzeeExternal = !0, this.scene?.children.some((t) => t.uuid === e.uuid) || (t.uuid = e.uuid), e.parent && (e.parent.updateWorldMatrix(!0, !1), t.applyMatrix4(e.parent.matrixWorld)), t;
1445
+ }
1446
+ releaseTargetModel() {
1447
+ this.sceneMetadata = null, this._sourceKey = null, this._appended = !1, this.archives?.release(), this.targetModel && (this.removeModelRoot(this.targetModel), this.targetModel = null, this.animations = []);
1448
+ }
1449
+ setRenderer(e) {
1450
+ this.renderer = e;
1451
+ }
1452
+ setArchiveImporter(e) {
1453
+ this.archives = e;
1454
+ }
1455
+ setArchiveImporterLoader(e, t) {
1456
+ this._archiveLoader = {
1457
+ load: e,
1458
+ formats: t,
1459
+ pending: null
1460
+ };
1461
+ }
1462
+ async _archiveImporter() {
1463
+ return !this.archives && this._archiveLoader && (this.archives = await (this._archiveLoader.pending ??= this._archiveLoader.load())), this.archives;
1464
+ }
1465
+ get _archiveFormats() {
1466
+ return this.archives?.constructor.FORMATS ?? this._archiveLoader?.formats ?? null;
1467
+ }
1468
+ registerFormat(...e) {
1469
+ for (let t of e) for (let e of t.extensions) this._formats.set(e, t);
1470
+ return this;
1471
+ }
1472
+ getFileFormat(e) {
1473
+ let t = e.split(".").pop().toLowerCase();
1474
+ return Tn[t] || this._formats.get(t) || this._archiveFormats?.[t] || null;
1475
+ }
1476
+ formatError(e) {
1477
+ let t = En[e.split(".").pop().toLowerCase()];
1478
+ return /* @__PURE__ */ Error(t ? `${e}: this format is read by ${t.addOn} — install it with ${t.install}` : `Unsupported file format: ${e}`);
1479
+ }
1480
+ async inspectArchive(e) {
1481
+ let t = await this._archiveImporter();
1482
+ if (!t) throw this.formatError(e.name ?? "archive.zip");
1483
+ return await t.inspectArchive(e);
1484
+ }
1485
+ flushPendingGraph(e) {
1486
+ this.archives?.flushPendingGraph(e);
1487
+ }
1488
+ readFileAsArrayBuffer(e) {
1489
+ return e.arrayBuffer();
1490
+ }
1491
+ readFileAsText(e) {
1492
+ return e.text();
1493
+ }
1494
+ async loadAssetFromFile(e, t = {}) {
1495
+ let n = e.name, r = this.getFileFormat(n);
1496
+ if (!r) throw this.formatError(n);
1497
+ _({
1498
+ isLoading: !0,
1499
+ status: `Loading ${r.name}...`,
1500
+ progress: 2
1501
+ });
1502
+ try {
1503
+ let i;
1504
+ switch (r.type) {
1505
+ case "model":
1506
+ i = await this.loadModelFromFile(e, n);
1507
+ break;
1508
+ case "environment":
1509
+ case "image":
1510
+ i = await this.loadEnvironmentFromFile(e, n);
1511
+ break;
1512
+ case "archive":
1513
+ i = await (await this._archiveImporter()).loadArchiveFromFile(e, n, t);
1514
+ break;
1515
+ default: throw Error(`Unknown asset type: ${r.type}`);
1516
+ }
1517
+ return i;
1518
+ } catch (e) {
1519
+ throw this.dispatchEvent({
1520
+ type: "error",
1521
+ message: e.message,
1522
+ filename: n
1523
+ }), e;
1524
+ }
1525
+ }
1526
+ async loadAssetFromUrl(t, n = {}) {
1527
+ let { filename: r = K(t), cacheKey: i = t, cachePolicy: a, ...o } = n;
1528
+ if (!this.getFileFormat(r)) throw this.formatError(r);
1529
+ this._loadCancelled = !1;
1530
+ let s = e._isNetworkUrl(t), c = `Downloading ${r}...`, l = new AbortController();
1531
+ this._urlAbort = l, _({
1532
+ isLoading: !0,
1533
+ status: c,
1534
+ progress: 2,
1535
+ canCancel: s,
1536
+ loadedBytes: 0,
1537
+ totalBytes: 0
1538
+ });
1539
+ let u;
1540
+ try {
1541
+ u = await this.downloads.fetch(t, {
1542
+ key: i,
1543
+ name: r,
1544
+ policy: a,
1545
+ signal: l.signal,
1546
+ onProgress: this._downloadProgress(c, s)
1547
+ });
1548
+ } catch (e) {
1549
+ throw this._isCancellation(e) ? this._cancellationError() : e;
1550
+ } finally {
1551
+ this._urlAbort = null;
1552
+ }
1553
+ this._downloadComplete();
1554
+ try {
1555
+ return await this.loadAssetFromFile(u.file, o);
1556
+ } catch (e) {
1557
+ throw e?.code === "ARCHIVE_NEEDS_ELEMENT" && (e.file = u.file), e;
1558
+ } finally {
1559
+ u.release();
1560
+ }
1561
+ }
1562
+ async loadModelFromFile(e, t) {
1563
+ let n = this.storage ? this._keyed("file", T(await ke(e))) : null, r = await this._loadModelFileByExtension(e, t);
1564
+ return this._sourceKey = n, r;
1565
+ }
1566
+ async _loadModelFileByExtension(e, t) {
1567
+ let n = t.split(".").pop().toLowerCase();
1568
+ if (n === "glb" || n === "gltf") return await this.loadGLBFromArrayBuffer(await this.readFileAsArrayBuffer(e), t);
1569
+ let r = this._formats.get(n);
1570
+ if (r?.type !== "model") throw this.formatError(t);
1571
+ return await this._loadModelWithFormat(r, e, t);
1572
+ }
1573
+ async _loadModelWithFormat(e, t, n) {
1574
+ try {
1575
+ _({
1576
+ isLoading: !0,
1577
+ status: `Processing ${e.label} Data...`,
1578
+ progress: 5
1579
+ }), await new Promise((e) => setTimeout(e, 0));
1580
+ let { model: r, result: i = r } = await e.parse(t, {
1581
+ filename: n,
1582
+ cache: this.loaderCache
1583
+ });
1584
+ return this.releaseTargetModel(), this.targetModel = r, _({
1585
+ isLoading: !0,
1586
+ status: "Processing Data...",
1587
+ progress: 10
1588
+ }), await this.onModelLoad(this.targetModel), this.dispatchEvent({
1589
+ type: "load",
1590
+ model: r,
1591
+ filename: n
1592
+ }), i;
1593
+ } catch (t) {
1594
+ throw console.error(`Error loading ${e.label}:`, t), this.dispatchEvent({
1595
+ type: "error",
1596
+ message: t.message,
1597
+ filename: n
1598
+ }), t;
1599
+ }
1600
+ }
1601
+ async loadEnvironmentFromFile(e, t) {
1602
+ let n = URL.createObjectURL(e);
1603
+ this.uploadedFileInfo = {
1604
+ name: t,
1605
+ type: e.type,
1606
+ size: e.size
1607
+ };
1608
+ try {
1609
+ let r = await this.loadEnvironment(n);
1610
+ return ce(r, T(await ke(e))), this.dispatchEvent({
1611
+ type: "load",
1612
+ texture: r,
1613
+ filename: t
1614
+ }), r;
1615
+ } finally {
1616
+ URL.revokeObjectURL(n);
1617
+ }
1618
+ }
1619
+ async loadEnvironment(t) {
1620
+ this._loadCancelled = !1;
1621
+ try {
1622
+ this.dispatchEvent({
1623
+ type: "beforeEnvironmentLoad",
1624
+ url: t
1625
+ });
1626
+ let n;
1627
+ if (t.startsWith("blob:")) n = await this.loadEnvironmentFromBlob(t);
1628
+ else {
1629
+ let e = t.split(/[?#]/)[0].split(".").pop().toLowerCase();
1630
+ n = await this.loadEnvironmentByExtension(t, e);
1631
+ }
1632
+ return n.generateMipmaps = !0, e._isNetworkUrl(t) && ce(n, t), this.applyEnvironmentToScene(n), this.dispatchEvent({
1633
+ type: "load",
1634
+ texture: n,
1635
+ url: t,
1636
+ filename: t.split(/[?#]/)[0].split("/").pop()
1637
+ }), n;
1638
+ } catch (e) {
1639
+ throw this._isCancellation(e) ? this._cancellationError() : (console.error("Error loading environment:", e), this.dispatchEvent({
1640
+ type: "error",
1641
+ message: e.message,
1642
+ filename: t
1643
+ }), e);
1644
+ }
1645
+ }
1646
+ async loadEnvironmentFromBlob(e) {
1647
+ let t = await (await fetch(e)).blob(), n = this.determineEnvironmentExtension(t, e), r = URL.createObjectURL(t);
1648
+ try {
1649
+ return await this.loadEnvironmentByExtension(r, n);
1650
+ } finally {
1651
+ URL.revokeObjectURL(r);
1652
+ }
1653
+ }
1654
+ determineEnvironmentExtension(e, t) {
1655
+ let n;
1656
+ if (e.type === "image/x-exr" || e.type.includes("exr")) n = "exr";
1657
+ else if (e.type === "image/vnd.radiance" || e.type.includes("hdr")) n = "hdr";
1658
+ else {
1659
+ let e = t.split("/").pop();
1660
+ if (e) {
1661
+ let t = e.match(/\.([^.]+)$/);
1662
+ t && (n = t[1].toLowerCase());
1663
+ }
1664
+ }
1665
+ return !n && this.uploadedFileInfo && (n = this.uploadedFileInfo.name.split(".").pop().toLowerCase()), n;
1666
+ }
1667
+ async loadEnvironmentByExtension(t, n, { loader: r = null } = {}) {
1668
+ let i = this._formats.get(n);
1669
+ if (!r && i?.type === "environment" && (r = this.loaderCache[n] ??= await i.createLoader(this._loadingManager)), !r && n === "hdr" && (r = this.loaderCache.hdr ??= new Dt(this._loadingManager).setDataType(nt)), !r && En[n]) throw this.formatError(`environment.${n}`);
1670
+ let a = e._isNetworkUrl(t), o = "Downloading Environment...", s = await this._viaCache(t, o, a), c = s.cached ? void 0 : this._downloadProgress(o, a), l;
1671
+ try {
1672
+ r ? l = await r.loadAsync(s.url, c) : d().decodeImage ? (l = await pn(s.url, `image/${n === "jpg" ? "jpeg" : n}`), l.colorSpace = B) : (this.loaderCache.texture || (this.loaderCache.texture = new xt(this._loadingManager)), l = await this.loaderCache.texture.loadAsync(s.url, c), l.colorSpace = B);
1673
+ } finally {
1674
+ s.release();
1675
+ }
1676
+ return this._downloadComplete("Processing Environment...", 62), l.mapping = tt, l.minFilter = rt, l.magFilter = rt, l;
1677
+ }
1678
+ applyEnvironmentToScene(e) {
1679
+ this.scene.background = e, this.scene.environment = e;
1680
+ }
1681
+ async createGLTFLoader() {
1682
+ let e = wn(new Et(this._loadingManager), this.renderer), t = (e, t) => this._reportImageFailure(e, t);
1683
+ return d().decodeImage ? e.register((e) => hn(e, t)) : u() || e.register((e) => mn(e, t)), e.register((e) => _n(e)), e;
1684
+ }
1685
+ _reportImageFailure(e, t) {
1686
+ try {
1687
+ this._issues?.record(b.TEXTURE_BUILD_FAILED, `image ${e} could not be decoded (${t?.message ?? t}) — the surfaces using it render untextured`, {
1688
+ image: e,
1689
+ cause: String(t?.message ?? t)
1690
+ });
1691
+ } catch (e) {
1692
+ this._deferredError ??= e;
1693
+ }
1694
+ }
1695
+ _throwDeferred() {
1696
+ let e = this._deferredError;
1697
+ if (this._deferredError = null, e) throw e;
1698
+ }
1699
+ _disposeGLTFLoader(e) {
1700
+ e && (e.dracoLoader?.dispose(), e.ktx2Loader?.dispose());
1701
+ }
1702
+ async loadExampleModels(e, t) {
1703
+ if (!t || !t[e]) throw Error(`No model file at index ${e}`);
1704
+ let n = `${t[e].url}`;
1705
+ return await this.loadModel(n);
1706
+ }
1707
+ async loadModel(t, n = {}) {
1708
+ this._loadCancelled = !1;
1709
+ let r = await this.createGLTFLoader(), i = e._isNetworkUrl(t), a = null;
1710
+ try {
1711
+ _({
1712
+ isLoading: !0,
1713
+ status: "Downloading Model...",
1714
+ progress: 2,
1715
+ canCancel: i,
1716
+ loadedBytes: 0,
1717
+ totalBytes: 0
1718
+ }), a = await this._viaCache(t, "Downloading Model...", i, n), a.cached && r.setResourcePath(I.extractUrlBase(t));
1719
+ let e = await s(() => r.loadAsync(a.url, a.cached ? void 0 : this._downloadProgress("Downloading Model...", i)));
1720
+ return this._downloadComplete(), this._throwDeferred(), this.releaseTargetModel(), this._sourceKey = i ? this._keyed("url", n.cacheKey ?? t) : null, this.targetModel = e.scene, this.animations = e.animations || [], this.sceneMetadata = je(e), await this.onModelLoad(this.targetModel), this.dispatchEvent({
1721
+ type: "load",
1722
+ model: e.scene,
1723
+ filename: t.split("/").pop()
1724
+ }), e;
1725
+ } catch (e) {
1726
+ throw this._isCancellation(e) ? this._cancellationError() : (console.error("Error loading model:", e), this.dispatchEvent({
1727
+ type: "error",
1728
+ message: e.message,
1729
+ filename: t
1730
+ }), e);
1731
+ } finally {
1732
+ a?.release(), this._disposeGLTFLoader(r);
1733
+ }
1734
+ }
1735
+ _processAndParent(e) {
1736
+ this.processModelObjects(e), this.scene.add(e), e.updateMatrixWorld(!0);
1737
+ }
1738
+ async appendModel(t, n = {}) {
1739
+ this._loadCancelled = !1;
1740
+ let r = await this.createGLTFLoader(), i = e._isNetworkUrl(t), a = null;
1741
+ try {
1742
+ _({
1743
+ isLoading: !0,
1744
+ status: "Downloading Model...",
1745
+ progress: 2,
1746
+ canCancel: i,
1747
+ loadedBytes: 0,
1748
+ totalBytes: 0
1749
+ }), a = await this._viaCache(t, "Downloading Model...", i, n), a.cached && r.setResourcePath(I.extractUrlBase(t));
1750
+ let e = await s(() => r.loadAsync(a.url, a.cached ? void 0 : this._downloadProgress("Downloading Model...", i)));
1751
+ return this._downloadComplete(), this._throwDeferred(), this._appended = !0, this._processAndParent(e.scene), {
1752
+ root: e.scene,
1753
+ animations: e.animations || []
1754
+ };
1755
+ } catch (e) {
1756
+ throw this._isCancellation(e) ? this._cancellationError() : e;
1757
+ } finally {
1758
+ a?.release(), this._disposeGLTFLoader(r);
1759
+ }
1760
+ }
1761
+ appendObject3D(e, t = "object3d") {
1762
+ this._appended = !0;
1763
+ let n = this._adoptExternalObject(e);
1764
+ return n.name = e.name || t, this._processAndParent(n), { root: n };
1765
+ }
1766
+ removeModelRoot(e) {
1767
+ e && (e.userData.__rayzeeExternal ? (re(e), e.parent?.remove(e)) : pe(e));
1768
+ }
1769
+ async loadGLBFromArrayBuffer(e, t = "model.glb") {
1770
+ let n = await this.createGLTFLoader();
1771
+ try {
1772
+ _({
1773
+ isLoading: !0,
1774
+ status: "Processing GLB Data...",
1775
+ progress: 5
1776
+ }), await new Promise((e) => setTimeout(e, 0));
1777
+ let r = await s(() => n.parseAsync(e, ""));
1778
+ return this._throwDeferred(), this.releaseTargetModel(), this.targetModel = r.scene, this.animations = r.animations || [], this.sceneMetadata = je(r), _({
1779
+ isLoading: !0,
1780
+ status: "Processing Data...",
1781
+ progress: 10
1782
+ }), await this.onModelLoad(this.targetModel), this.dispatchEvent({
1783
+ type: "load",
1784
+ model: r.scene,
1785
+ filename: t
1786
+ }), r;
1787
+ } catch (e) {
1788
+ throw console.error("Error loading GLB:", e), this.dispatchEvent({
1789
+ type: "error",
1790
+ message: e.message,
1791
+ filename: t
1792
+ }), e;
1793
+ } finally {
1794
+ this._disposeGLTFLoader(n);
1795
+ }
1796
+ }
1797
+ async loadObject3D(e, t = "object3d") {
1798
+ this.releaseTargetModel();
1799
+ let n = this._adoptExternalObject(e);
1800
+ return n.name = e.name || t, this.targetModel = n, _({
1801
+ isLoading: !0,
1802
+ status: "Processing Data...",
1803
+ progress: 10
1804
+ }), await this.onModelLoad(this.targetModel), this.dispatchEvent({
1805
+ type: "load",
1806
+ model: n,
1807
+ filename: t
1808
+ }), n;
1809
+ }
1810
+ async onModelLoad(e) {
1811
+ let t = new p("onModelLoad");
1812
+ t.start("Camera extraction");
1813
+ let n = this.extractCamerasFromModel(e);
1814
+ t.end("Camera extraction"), t.start("Camera setup");
1815
+ let r = new Ye().setFromObject(e), i = r.getCenter(new V()), a = r.getSize(new V());
1816
+ this.controls?.target.copy(i);
1817
+ let o = Math.max(a.x, a.y, a.z), s = this.camera.fov * (Math.PI / 180), c = Math.abs(o / Math.sin(s / 2) / 2), l = Math.PI / 6, u = new V(Math.cos(l) * c, c / Math.sqrt(2), Math.sin(l) * c);
1818
+ if (this.camera.position.copy(u.add(i)), this.camera.lookAt(i), this.camera.near = o / 100, this.camera.far = o * 100, this.camera.updateProjectionMatrix(), this.controls && (this.controls.maxDistance = c * 10, this.controls.saveState(), this.controls.update()), t.end("Camera setup"), this.floorPlane) {
1819
+ let e = r.min.y;
1820
+ this.floorPlane.position.y = e, this.floorPlane.rotation.x = -Math.PI / 2, this.floorPlane.scale.setScalar(o * 5);
1821
+ }
1822
+ t.start("Process model objects"), this.processModelObjects(e), t.end("Process model objects"), t.start("Scene add"), this.scene.add(e), t.end("Scene add");
1823
+ let d = o;
1824
+ return this.sceneSize.copy(a), t.start("setupPathTracing"), await this.setupPathTracing(e, d), t.end("setupPathTracing"), t.print(), this.dispatchEvent({
1825
+ type: "modelProcessed",
1826
+ model: e,
1827
+ cameras: n,
1828
+ sceneData: {
1829
+ center: i,
1830
+ size: a,
1831
+ maxDim: o,
1832
+ sceneScale: d
1833
+ }
1834
+ }), this.dispatchEvent({ type: "SceneRebuild" }), {
1835
+ center: i,
1836
+ size: a,
1837
+ maxDim: o,
1838
+ sceneScale: d
1839
+ };
1840
+ }
1841
+ extractCamerasFromModel(e) {
1842
+ let t = [];
1843
+ return e.updateWorldMatrix(!0, !0), e.traverse((e) => {
1844
+ if (e.isCamera) {
1845
+ let n = e.clone();
1846
+ n.userData.__rayzeeSourceUuid = e.uuid, e.getWorldPosition(n.position), e.getWorldQuaternion(n.quaternion), e.getWorldScale(n.scale), n.scale.set(Math.sign(n.scale.x) || 1, Math.sign(n.scale.y) || 1, Math.sign(n.scale.z) || 1), (!n.name || n.name === "") && (n.name = `Model Camera ${t.length + 1}`), n.isPerspectiveCamera && (n.aspect = this.camera.aspect, n.updateProjectionMatrix()), t.push(n);
1847
+ }
1848
+ }), t;
1849
+ }
1850
+ processModelObjects(e) {
1851
+ let t = [], n = [];
1852
+ e.traverse((e) => {
1853
+ let r = e.userData;
1854
+ e.isRectAreaLight && !r.__radianceConverted && (e.intensity *= kn(e, e.width, e.height, r), r.__radianceConverted = !0), (e.isPointLight || e.isSpotLight) && !r.__candelaConverted && (e.intensity *= 4 * Math.PI / On, r.__candelaConverted = !0), e.isDirectionalLight && !r.__luxConverted && (e.intensity /= On, r.__luxConverted = !0);
1855
+ let i = e.name.startsWith("RectAreaLightPlaceholder");
1856
+ if (i && !(r.name && r.type === "RectAreaLight") && !e.parent?.name?.startsWith("RectAreaLightPlaceholder") && n.push(e.name), i && r.name && r.type === "RectAreaLight") {
1857
+ let t = r.normalize ?? !0, n = r.shape ?? "rectangle", i = r.intensity * kn(e, r.width, r.height, r), a = new z(new P(...r.color), i * this._areaLightIntensityScale(), r.width, r.height);
1858
+ a.userData.normalize = t, a.userData.spread = Number.isFinite(r.spread) ? r.spread : Math.PI, a.userData.shape = n, a.userData.__radianceConverted = !0, a.name = r.name, e.add(a);
1859
+ }
1860
+ e.isMesh && Array.isArray(e.material) && t.push(e);
1861
+ }), n.length && this._issues?.record(b.LIGHT_PLACEHOLDER_SKIPPED, `${n.length} area-light placeholder(s) lack userData.name or userData.type 'RectAreaLight' — no light was made for them`, {
1862
+ count: n.length,
1863
+ names: n.slice(0, 10)
1864
+ });
1865
+ let r = e.userData.__rayzeeExternal === !0;
1866
+ for (let e of t) {
1867
+ if (!e.parent) continue;
1868
+ console.log("Found multi-material mesh:", e.name), r && (e.geometry = Dn(e.geometry));
1869
+ let t = Ot(e);
1870
+ for (let e of t.children) e.geometry.userData.__rayzeeOwned = !0;
1871
+ e.parent.add(t), e.parent.remove(e);
1872
+ }
1873
+ }
1874
+ async setupPathTracing(e, t) {
1875
+ this.sceneScale = t;
1876
+ }
1877
+ createFloorPlane() {
1878
+ this.floorPlane = new ot(new Ze(), new st({
1879
+ transparent: !1,
1880
+ color: 3158064,
1881
+ roughness: 1,
1882
+ metalness: 0,
1883
+ opacity: 0,
1884
+ transmission: 0
1885
+ })), this.floorPlane.name = "Ground", this.floorPlane.visible = !1, this.scene.add(this.floorPlane);
1886
+ }
1887
+ setFloorPlane(e) {
1888
+ this.floorPlane = e;
1889
+ }
1890
+ getSceneScale() {
1891
+ return this.sceneScale;
1892
+ }
1893
+ getSceneSize() {
1894
+ return this.sceneSize.clone();
1895
+ }
1896
+ getTargetModel() {
1897
+ return this.targetModel;
1898
+ }
1899
+ getSupportedFormats(e = null) {
1900
+ let t = {
1901
+ ...Tn,
1902
+ ...this._archiveFormats
1903
+ };
1904
+ for (let [e, { type: n, name: r }] of this._formats) t[e] = {
1905
+ type: n,
1906
+ name: r
1907
+ };
1908
+ if (e) {
1909
+ let n = {};
1910
+ for (let [r, i] of Object.entries(t)) i.type === e && (n[r] = i);
1911
+ return n;
1912
+ }
1913
+ return t;
1914
+ }
1915
+ dispose() {
1916
+ for (let e in this.loaderCache) {
1917
+ let t = this.loaderCache[e];
1918
+ t && typeof t.dispose == "function" && t.dispose();
1919
+ }
1920
+ this.loaderCache = {}, this._listeners = void 0, this._loadingManager.onError = void 0, this._issues = null, this._urlAbort?.abort(), this._urlAbort = null, this.storage = null, this._downloads = null, this.archives?.release(), this.archives = null, this._archiveLoader = null, this.releaseTargetModel();
1921
+ }
1922
+ removeAllEventListeners() {
1923
+ this._listeners = void 0;
1924
+ }
1925
+ }, jn = {
1926
+ addEventListener() {},
1927
+ removeEventListener() {},
1928
+ dispatchEvent() {
1929
+ return !0;
1930
+ }
1931
+ }, Mn = class {
1932
+ constructor(e) {
1933
+ this.canvas = e, this._configuration = null, this._texture = null;
1934
+ }
1935
+ configure(e) {
1936
+ this.unconfigure(), this._configuration = e;
1937
+ }
1938
+ unconfigure() {
1939
+ this._texture?.destroy(), this._texture = null, this._configuration = null;
1940
+ }
1941
+ getConfiguration() {
1942
+ return this._configuration;
1943
+ }
1944
+ getCurrentTexture() {
1945
+ if (!this._configuration) throw Error("HeadlessGPUContext: getCurrentTexture() before configure()");
1946
+ let e = Math.max(1, this.canvas.width), t = Math.max(1, this.canvas.height);
1947
+ if (this._texture?.width !== e || this._texture?.height !== t) {
1948
+ let { device: n, format: r, usage: i } = this._configuration;
1949
+ this._texture?.destroy(), this._texture = n.createTexture({
1950
+ label: "headless-canvas",
1951
+ size: [e, t],
1952
+ format: r,
1953
+ usage: i
1954
+ });
1955
+ }
1956
+ return this._texture;
1957
+ }
1958
+ };
1959
+ function Nn(e = 1, t = 1) {
1960
+ let n = {
1961
+ ...jn,
1962
+ defaultView: null
1963
+ }, r = {
1964
+ ...jn,
1965
+ isHeadlessCanvas: !0,
1966
+ width: e,
1967
+ height: t,
1968
+ clientWidth: 0,
1969
+ clientHeight: 0,
1970
+ style: {},
1971
+ parentNode: null,
1972
+ ownerDocument: n,
1973
+ getRootNode: () => n,
1974
+ getBoundingClientRect() {
1975
+ return {
1976
+ x: 0,
1977
+ y: 0,
1978
+ left: 0,
1979
+ top: 0,
1980
+ right: this.width,
1981
+ bottom: this.height,
1982
+ width: this.width,
1983
+ height: this.height
1984
+ };
1985
+ },
1986
+ setPointerCapture() {},
1987
+ releasePointerCapture() {},
1988
+ hasPointerCapture: () => !1,
1989
+ focus() {},
1990
+ getContext: (e) => e === "webgpu" ? i : null
1991
+ }, i = new Mn(r);
1992
+ return r;
1993
+ }
1994
+ //#endregion
1995
+ //#region src/managers/ViewCamera.js
1996
+ var Pn = class extends ft {
1997
+ constructor(e, t, n, r) {
1998
+ super(e, t, n, r), this.orthographic = !1, this.orthoHalfHeight = 1;
1999
+ }
2000
+ get isPerspectiveCamera() {
2001
+ return !this.orthographic;
2002
+ }
2003
+ set isPerspectiveCamera(e) {}
2004
+ get isOrthographicCamera() {
2005
+ return this.orthographic;
2006
+ }
2007
+ get top() {
2008
+ return this.orthoHalfHeight;
2009
+ }
2010
+ get bottom() {
2011
+ return -this.orthoHalfHeight;
2012
+ }
2013
+ get right() {
2014
+ return this.orthoHalfHeight * this.aspect;
2015
+ }
2016
+ get left() {
2017
+ return -this.orthoHalfHeight * this.aspect;
2018
+ }
2019
+ updateProjectionMatrix() {
2020
+ this.orthographic ? dt.prototype.updateProjectionMatrix.call(this) : super.updateProjectionMatrix();
2021
+ }
2022
+ copy(e, t) {
2023
+ return super.copy(e, t), this.orthographic = e.orthographic === !0, this.orthoHalfHeight = e.orthoHalfHeight ?? this.orthoHalfHeight, this;
2024
+ }
2025
+ }, Fn = "__rayzeeUserLight", In = {
2026
+ DirectionalLight: $e,
2027
+ PointLight: pt,
2028
+ SpotLight: yt,
2029
+ RectAreaLight: z
2030
+ }, Ln = class extends F {
2031
+ constructor(e, t, n, r = {}) {
2032
+ super(), this.scene = e, this.sceneHelpers = t, this.pathTracer = n, this._onReset = r.onReset || null, this._onLightRemoved = r.onLightRemoved || null;
2033
+ }
2034
+ addLight(e) {
2035
+ let t = {
2036
+ DirectionalLight: {
2037
+ position: [
2038
+ 1,
2039
+ 1,
2040
+ 1
2041
+ ],
2042
+ intensity: 1,
2043
+ color: "#ffffff"
2044
+ },
2045
+ PointLight: {
2046
+ position: [
2047
+ 0,
2048
+ 2,
2049
+ 0
2050
+ ],
2051
+ intensity: 1e3,
2052
+ color: "#ffffff"
2053
+ },
2054
+ SpotLight: {
2055
+ position: [
2056
+ 0,
2057
+ 1,
2058
+ 0
2059
+ ],
2060
+ intensity: 1e3,
2061
+ color: "#ffffff",
2062
+ angle: 15
2063
+ },
2064
+ RectAreaLight: {
2065
+ position: [
2066
+ 0,
2067
+ 2,
2068
+ 0
2069
+ ],
2070
+ intensity: 100,
2071
+ color: "#ffffff",
2072
+ width: 2,
2073
+ height: 2
2074
+ }
2075
+ }[e];
2076
+ if (!t) return null;
2077
+ let n;
2078
+ if (e === "DirectionalLight") n = new $e(t.color, t.intensity), n.position.fromArray(t.position);
2079
+ else if (e === "PointLight") n = new pt(t.color, t.intensity), n.position.fromArray(t.position);
2080
+ else if (e === "SpotLight") {
2081
+ n = new yt(t.color, t.intensity), n.position.fromArray(t.position), n.angle = L.degToRad(t.angle);
2082
+ let e = new R();
2083
+ this.scene.add(e), n.target = e;
2084
+ } else e === "RectAreaLight" && (n = new z(t.color, t.intensity, t.width, t.height), n.position.fromArray(t.position), n.lookAt(0, 0, 0), n.userData.normalize = !0, n.userData.spread = Math.PI, n.userData.shape = "rectangle");
2085
+ n.userData[Fn] = !0, n.userData.temperature = 6500, n.userData.useTemperature = !1, n.userData.exposure = 0;
2086
+ let r = this.scene.getObjectsByProperty("isLight", !0).length;
2087
+ return n.name = `${e.replace("Light", "")} ${r + 1}`, this.scene.add(n), this.updateLights(), this._syncHelpers(), this._onReset?.(), this._buildDescriptor(n);
2088
+ }
2089
+ getLight(e) {
2090
+ let t = this.scene.getObjectByProperty("uuid", e);
2091
+ return t?.isLight ? t : null;
2092
+ }
2093
+ setIntensity(e, t) {
2094
+ let n = this.getLight(e);
2095
+ return n ? (n.intensity = t, this.updateLights(), this._onReset?.(), !0) : !1;
2096
+ }
2097
+ removeLight(e) {
2098
+ let t = this.scene.getObjectByProperty("uuid", e);
2099
+ return !t || !t.isLight ? !1 : (this._onLightRemoved?.(t), this.sceneHelpers.remove(t), t.target && t.target.removeFromParent(), t.removeFromParent(), this.updateLights(), this._onReset?.(), !0);
2100
+ }
2101
+ clearLights() {
2102
+ this.sceneHelpers.clear(), this._removeAllLights(), this.updateLights(), this._onReset?.();
2103
+ }
2104
+ getLights() {
2105
+ return this.scene.getObjectsByProperty("isLight", !0).map((e) => this._buildDescriptor(e));
2106
+ }
2107
+ updateLights() {
2108
+ this.pathTracer?.updateLights(), this.sceneHelpers?.visible && this.sceneHelpers.update();
2109
+ }
2110
+ transferSceneLights(e, { keepUserLights: t = !1 } = {}) {
2111
+ this._removeAllLights(t ? (e) => !e.userData?.[Fn] : void 0);
2112
+ let n = e.getObjectsByProperty("isLight", !0);
2113
+ if (!n || n.length === 0) {
2114
+ this.updateLights();
2115
+ return;
2116
+ }
2117
+ for (let e of n) {
2118
+ let t = e.clone();
2119
+ if (e.updateWorldMatrix(!0, !1), e.getWorldPosition(t.position), e.getWorldQuaternion(t.quaternion), e.getWorldScale(t.scale), t.isRectAreaLight && (t.width *= t.scale.x, t.height *= t.scale.y, t.scale.set(1, 1, 1)), (e.isSpotLight || e.isDirectionalLight) && e.target) {
2120
+ let n = new R();
2121
+ e.target.updateWorldMatrix(!0, !1), e.target.getWorldPosition(n.position), this.scene.add(n), t.target = n;
2122
+ }
2123
+ this.scene.add(t);
2124
+ }
2125
+ this.updateLights(), this._syncHelpers();
2126
+ }
2127
+ setShowLightHelper(e) {
2128
+ this.sceneHelpers.visible = e, e ? this._syncHelpers() : this.sceneHelpers.clear();
2129
+ }
2130
+ serialize() {
2131
+ return this.scene.getObjectsByProperty("isLight", !0).map((e) => {
2132
+ let t = {
2133
+ type: e.type,
2134
+ name: e.name,
2135
+ visible: e.visible,
2136
+ color: [
2137
+ e.color.r,
2138
+ e.color.g,
2139
+ e.color.b
2140
+ ],
2141
+ intensity: e.intensity,
2142
+ position: e.position.toArray(),
2143
+ quaternion: e.quaternion.toArray(),
2144
+ scale: e.scale.toArray(),
2145
+ userData: h(e.userData) ?? {}
2146
+ };
2147
+ return e.isSpotLight && Object.assign(t, {
2148
+ angle: e.angle,
2149
+ penumbra: e.penumbra,
2150
+ distance: e.distance,
2151
+ decay: e.decay
2152
+ }), e.isPointLight && Object.assign(t, {
2153
+ distance: e.distance,
2154
+ decay: e.decay
2155
+ }), e.isRectAreaLight && Object.assign(t, {
2156
+ width: e.width,
2157
+ height: e.height
2158
+ }), e.target && (e.isSpotLight || e.isDirectionalLight) && (t.target = e.target.position.toArray()), t;
2159
+ });
2160
+ }
2161
+ restore(e) {
2162
+ this.sceneHelpers?.clear(), this._removeAllLights();
2163
+ let t = [];
2164
+ for (let n of e ?? []) {
2165
+ let e = In[n.type];
2166
+ if (!e) continue;
2167
+ let r = new e();
2168
+ r.name = n.name ?? "", r.visible = n.visible !== !1, r.color.setRGB(...n.color), r.intensity = n.intensity, r.position.fromArray(n.position), r.quaternion.fromArray(n.quaternion), r.scale.fromArray(n.scale ?? [
2169
+ 1,
2170
+ 1,
2171
+ 1
2172
+ ]), r.userData = c(n.userData) ?? {};
2173
+ for (let e of [
2174
+ "angle",
2175
+ "penumbra",
2176
+ "distance",
2177
+ "decay",
2178
+ "width",
2179
+ "height"
2180
+ ]) typeof n[e] == "number" && (r[e] = n[e]);
2181
+ if (n.target) {
2182
+ let e = new R();
2183
+ e.position.fromArray(n.target), this.scene.add(e), r.target = e;
2184
+ }
2185
+ this.scene.add(r), t.push(r);
2186
+ }
2187
+ return this.updateLights(), this._syncHelpers(), this._onReset?.(), t;
2188
+ }
2189
+ add(e) {
2190
+ return this.addLight(e);
2191
+ }
2192
+ remove(e) {
2193
+ return this.removeLight(e);
2194
+ }
2195
+ clear() {
2196
+ this.clearLights();
2197
+ }
2198
+ getAll() {
2199
+ return this.getLights();
2200
+ }
2201
+ sync() {
2202
+ this.updateLights();
2203
+ }
2204
+ showHelpers(e) {
2205
+ this.setShowLightHelper(e);
2206
+ }
2207
+ dispose() {
2208
+ this._disposed || (this._disposed = !0, this._onLightRemoved = null, this.sceneHelpers?.clear(), this._removeAllLights(), this._onReset = null, this.pathTracer = null, this.sceneHelpers = null, this.scene = null);
2209
+ }
2210
+ _removeAllLights(e) {
2211
+ this.scene.getObjectsByProperty("isLight", !0).filter((t) => !e || e(t)).forEach((e) => {
2212
+ this._onLightRemoved?.(e), e.target && this.scene.remove(e.target), this.scene.remove(e);
2213
+ });
2214
+ }
2215
+ _syncHelpers() {
2216
+ if (!this.sceneHelpers.visible) return;
2217
+ let e = this.scene.getObjectsByProperty("isLight", !0);
2218
+ this.sceneHelpers.sync(e);
2219
+ }
2220
+ _buildDescriptor(e) {
2221
+ let t = 0;
2222
+ e.type === "SpotLight" && e.angle !== void 0 ? t = L.radToDeg(e.angle) : e.type === "DirectionalLight" && (t = L.radToDeg(e.userData?.angle ?? 0));
2223
+ let n = {
2224
+ uuid: e.uuid,
2225
+ name: e.name,
2226
+ type: e.type,
2227
+ visible: e.visible,
2228
+ intensity: e.intensity,
2229
+ color: `#${e.color.getHexString()}`,
2230
+ position: [
2231
+ e.position.x,
2232
+ e.position.y,
2233
+ e.position.z
2234
+ ],
2235
+ angle: t,
2236
+ temperature: e.userData?.temperature ?? 6500,
2237
+ useTemperature: e.userData?.useTemperature ?? !1,
2238
+ exposure: e.userData?.exposure ?? 0
2239
+ };
2240
+ if (e.type === "RectAreaLight") {
2241
+ n.width = e.width, n.height = e.height, n.normalize = e.userData?.normalize ?? !0, n.spread = L.radToDeg(e.userData?.spread ?? Math.PI);
2242
+ let t = e.userData?.shape;
2243
+ n.shape = t === "square" || t === "rectangle" || t === "disk" || t === "ellipse" ? t : t === 1 ? "ellipse" : "rectangle";
2244
+ let r = e.getWorldDirection(e.position.clone());
2245
+ n.target = [
2246
+ e.position.x + r.x,
2247
+ e.position.y + r.y,
2248
+ e.position.z + r.z
2249
+ ];
2250
+ } else e.type === "SpotLight" && e.target ? (n.target = [
2251
+ e.target.position.x,
2252
+ e.target.position.y,
2253
+ e.target.position.z
2254
+ ], n.distance = e.distance ?? 0, n.penumbra = e.penumbra ?? 0, n.decay = e.decay ?? 2) : e.type === "PointLight" && (n.distance = e.distance ?? 0, n.decay = e.decay ?? 2);
2255
+ return (e.type === "SpotLight" || e.type === "DirectionalLight") && e.userData?.gobo && (n.gobo = e.userData.gobo.name, n.goboIntensity = e.userData.gobo.intensity, n.goboInverted = !!e.userData.gobo.inverted, e.type === "DirectionalLight" && (n.goboScale = e.userData.gobo.scale ?? 5)), e.type === "SpotLight" && e.userData?.ies && (n.ies = e.userData.ies.name, n.iesIntensity = e.userData.ies.intensity ?? 1, n.fixtureLumens = e.userData.ies.fixtureLumens ?? null), n;
2256
+ }
2257
+ }, Rn = ({ element: e, pbrtEntry: t } = {}) => ({
2258
+ ...e === void 0 ? {} : { element: e },
2259
+ ...t === void 0 ? {} : { pbrtEntry: t }
2260
+ }), Q = /* @__PURE__ */ new WeakMap(), zn = new Set([...Object.values(g), ...Object.values(ne)]), Bn = /* @__PURE__ */ new Set();
2261
+ async function Vn(e, t) {
2262
+ if (!t || typeof self < "u") return e.init();
2263
+ globalThis.self = {
2264
+ requestAnimationFrame: () => 0,
2265
+ cancelAnimationFrame: () => {}
2266
+ };
2267
+ try {
2268
+ return await e.init();
2269
+ } finally {
2270
+ delete globalThis.self;
2271
+ }
2272
+ }
2273
+ var $ = me("engine");
2274
+ function Hn() {
2275
+ let e = new Float32Array(16);
2276
+ return new Uint32Array(e.buffer)[3] = he.TRIANGLE_LEAF, e;
2277
+ }
2278
+ function Un(e, t) {
2279
+ e.lost.then((e) => {
2280
+ t.app && t.app._handleDeviceLost(e);
2281
+ });
2282
+ }
2283
+ var Wn = /swiftshader|llvmpipe|lavapipe|basic render|microsoft basic|warp/i;
2284
+ function Gn(e) {
2285
+ let t = e.info ?? {}, n = `${t.vendor ?? ""} ${t.architecture ?? ""} ${t.device ?? ""} ${t.description ?? ""}`;
2286
+ return {
2287
+ vendor: t.vendor ?? "",
2288
+ architecture: t.architecture ?? "",
2289
+ device: t.device ?? "",
2290
+ description: t.description ?? "",
2291
+ isSoftware: t.isFallbackAdapter === !0 || e.isFallbackAdapter === !0 || Wn.test(n)
2292
+ };
2293
+ }
2294
+ var Kn = class extends F {
2295
+ constructor(e, t = {}) {
2296
+ super(), this._headless = t.headless === !0 || !e, e ??= Nn();
2297
+ try {
2298
+ Q.get(e)?.dispose();
2299
+ } catch (e) {
2300
+ $.warn("prior canvas owner dispose failed", e);
2301
+ }
2302
+ if (Q.set(e, this), this.canvas = e, this._autoResize = !this._headless && t.autoResize !== !1, this._maxSceneBytes = t.maxSceneBytes, this._hostMemoryGB = t.hostMemoryGB, this._storageOption = t.storage, this._storageOpener = null, this._memorySpill = t.memorySpill === !0, this.storage = null, this._storageRelease = null, this._applySceneMetadataEnabled = t.applySceneMetadata !== !1, this._unlitRestore = null, this._applyingSceneMetadata = !1, t.profile !== void 0) throw Error("the `profile` option was removed: the engine has one set of defaults. For the old 'physical' profile set `areaLightIntensityScale: 1` and `dofMode: 'physical'` through `settings`.");
2303
+ this._issues = new _e({
2304
+ strict: t.strict === !0,
2305
+ onIssue: (e) => this.dispatchEvent({
2306
+ type: g.ISSUE,
2307
+ issue: e
2308
+ })
2309
+ }), this.color = new nn({ issues: this._issues }), x(this.color), this.settings = new tn(n, { issues: this._issues }), this.renderer = null, this.scene = null, this.meshScene = null, this._sceneHelpers = null, this.assetLoader = null, this._sdf = null, this.pipeline = null, this._pendingReservedRenderSize = null, this.stages = {}, this.camera = null, this.lightManager = null, this.environmentManager = null, this.isInitialized = !1, this.pauseRendering = !1, this._pathTracerEnabled = !0, this._rasterPrecompile = null, this.animationManagerId = null, this.needsReset = !1, this._loadingInProgress = !1, this._needsDisplayRefresh = !1, this._paused = !1, this._emissiveSamplingUserSet = !1, this.completion = new Gt(), this._resizeDebounceTimer = null, this._displayWidth = 0, this._displayHeight = 0, this._renderScale = 1, this._renderWidth = 0, this._renderHeight = 0, this._trackedListeners = [], this._disposed = !1, this._deviceLost = !1, this._gpuDevice = null, this._deviceLostHolder = null, this._deterministic = !1, this._dispatchPinned = !1, this._deterministicRestore = null, this.adapterInfo = null;
2310
+ }
2311
+ _addTrackedListener(e, t, n) {
2312
+ e && (e.addEventListener(t, n), this._trackedListeners.push({
2313
+ target: e,
2314
+ type: t,
2315
+ handler: n
2316
+ }));
2317
+ }
2318
+ _removeTrackedListeners() {
2319
+ for (let { target: e, type: t, handler: n } of this._trackedListeners) try {
2320
+ e.removeEventListener(t, n);
2321
+ } catch (e) {
2322
+ $.warn("failed to remove listener", t, e);
2323
+ }
2324
+ this._trackedListeners.length = 0;
2325
+ }
2326
+ async init() {
2327
+ let e = this._initStorage();
2328
+ return await this._initRenderer(), this._applyPendingReservedRenderSize(), this.camera = this._createCamera(), this._initScenes(), this._initAssetPipeline(), this._initPipeline(), await this._initManagers(), this._wireEvents(), await e, this._attachStorage(), this.stages.pathTracer.setTriangleData(new Uint32Array(ge.FLOATS_PER_TRIANGLE), 0), this.stages.pathTracer.setBVHData(Hn()), this.stages.pathTracer.materialData.setMaterialData(new Float32Array(16)), this.stages.pathTracer.setupMaterial(), this.isInitialized = !0, $.debug("WebGPU path tracer app initialized"), this;
2329
+ }
2330
+ async setStorageOpener(e) {
2331
+ this._storageOpener = e, !(!this.isInitialized || this.storage || this._disposed) && (await this._initStorage(), this._attachStorage());
2332
+ }
2333
+ async _initStorage() {
2334
+ let e = this._storageOption ?? (this._issues.strict && !Ce("storage") ? !1 : C().storage);
2335
+ if (e !== !1) {
2336
+ if (e && typeof e == "object") this.storage = e;
2337
+ else {
2338
+ if (!this._storageOpener) {
2339
+ (this._storageOption !== void 0 || Ce("storage")) && this._issues.warn(b.CAPABILITY_MISSING, "on-disk storage needs rayzee/addons/storage: setStorageOpener( acquireSharedStorage )");
2340
+ return;
2341
+ }
2342
+ let { storage: e, reason: t, release: n } = await this._storageOpener(C().cacheNamespace);
2343
+ if (this._disposed) {
2344
+ n();
2345
+ return;
2346
+ }
2347
+ if (!e) {
2348
+ this._issues.warn(b.STORAGE_UNAVAILABLE, `on-disk storage is off: ${t}`, { reason: t });
2349
+ return;
2350
+ }
2351
+ this.storage = e, this._storageRelease = n;
2352
+ }
2353
+ this._addTrackedListener(this.storage, "change", (e) => this.dispatchEvent({
2354
+ type: g.STORAGE_CHANGED,
2355
+ area: e.area
2356
+ })), this._addTrackedListener(this.storage, "issue", (e) => this._issues.warn(e.code, e.message, e.detail));
2357
+ }
2358
+ }
2359
+ _attachStorage() {
2360
+ this.assetLoader && (this.assetLoader.storage = this.storage);
2361
+ }
2362
+ dispatchEvent(e) {
2363
+ super.dispatchEvent(e);
2364
+ let t = ne[e.type];
2365
+ t && super.dispatchEvent({
2366
+ ...e,
2367
+ type: t
2368
+ });
2369
+ }
2370
+ addEventListener(e, t) {
2371
+ !zn.has(e) && !Bn.has(e) && (Bn.add(e), $.warn(`no engine event is named "${e}", so this listener will never fire — see EngineEvents`)), super.addEventListener(e, t);
2372
+ }
2373
+ animate() {
2374
+ if (this._headless) throw Error("a headless app has no render loop — drive it with renderFrames() or renderUntilComplete()");
2375
+ if (this._deviceLost) return;
2376
+ if (this.animationManagerId = requestAnimationFrame(() => this.animate()), this._loadingInProgress || this._sdf?.isProcessing) {
2377
+ this.dispatchEvent({ type: g.FRAME });
2378
+ return;
2379
+ }
2380
+ this._beginFrame();
2381
+ let e = this.needsReset;
2382
+ if (this.needsReset &&= (this.stages.pathTracer?.noteViewChanged(), this.reset(!0), !1), this.camera.updateMatrixWorld(), !this.pathTracerEnabled) {
2383
+ this.renderer.render(this.meshScene, this.camera), this._renderHelperOverlay();
2384
+ return;
2385
+ }
2386
+ if (!this.pauseRendering) {
2387
+ if (this._beforeTrace(), this.stages.pathTracer?.isReady) {
2388
+ if (this.stages.pathTracer.isComplete && this.completion.renderCompleteDispatched) {
2389
+ this._needsDisplayRefresh && (this._needsDisplayRefresh = !1, this.stages.compositor.render(this.pipeline.context), this._renderHelperOverlay()), this.stopAnimation();
2390
+ return;
2391
+ }
2392
+ if (this._holdTrace(e)) {
2393
+ this._renderHelperOverlay(), this.dispatchEvent({ type: g.FRAME });
2394
+ return;
2395
+ }
2396
+ if (this.stages.pathTracer.readbackWait()) {
2397
+ this.dispatchEvent({ type: g.FRAME });
2398
+ return;
2399
+ }
2400
+ this._traceFrame({ liveDenoise: !0 }), this.stages.pathTracer.isComplete && this.completion.markComplete() && (this._renderCompleted(), this.dispatchEvent({
2401
+ type: g.RENDER_COMPLETE,
2402
+ ...this._completionInfo()
2403
+ }));
2404
+ }
2405
+ this._renderHelperOverlay(), this.dispatchEvent({ type: g.FRAME });
2406
+ }
2407
+ }
2408
+ _traceFrame({ liveDenoise: e = !1 } = {}) {
2409
+ let t = this.stages.pathTracer;
2410
+ this.pipeline.render(), this._afterTrace(t, e), t.isComplete || this.completion.updateTime(), this._ensureVRAMWiring();
2411
+ let n = t.vramTracker, r = t.frameCount ?? 0;
2412
+ n && (r <= 1 || r % 30 == 0) && n.measure(), le({
2413
+ timeElapsed: this.completion.timeElapsed,
2414
+ samples: ie(t),
2415
+ memoryUsed: n?.current ?? 0,
2416
+ memoryPeak: n?.peak ?? 0
2417
+ }), this.completion.isTimeLimitReached(t, this.settings.get("renderLimitMode"), this.settings.get("renderTimeLimit")) && (t.isComplete = !0);
2418
+ }
2419
+ _completionInfo() {
2420
+ return {
2421
+ samples: this.stages.pathTracer.frameCount,
2422
+ timeElapsed: this.completion.timeElapsed,
2423
+ budgetOverrun: this.completion.budgetOverrun,
2424
+ reason: this.completion.stopCondition(this.stages.pathTracer) ?? "samples"
2425
+ };
2426
+ }
2427
+ stopAnimation() {
2428
+ this.animationManagerId &&= (cancelAnimationFrame(this.animationManagerId), null);
2429
+ }
2430
+ _handleDeviceLost(e) {
2431
+ this._deviceLost || (this._deviceLost = !0, $.error(`WebGPU device lost (${e?.reason || "unknown"}): ${e?.message || ""}`), this.stopAnimation(), this.dispatchEvent({
2432
+ type: g.DEVICE_LOST,
2433
+ reason: e?.reason,
2434
+ message: e?.message
2435
+ }));
2436
+ }
2437
+ wake() {
2438
+ this._deviceLost || this._headless || !this.animationManagerId && this.isInitialized && !this._paused && this.animate();
2439
+ }
2440
+ pause() {
2441
+ this._paused = !0, this.stopAnimation();
2442
+ }
2443
+ resume() {
2444
+ this._paused = !1, !this.animationManagerId && !this._headless && this.animate();
2445
+ }
2446
+ reset(e = !1, { motion: t = !1 } = {}) {
2447
+ t && this.stages.pathTracer?.noteViewChanged(), this._beforeReset(e || t), this.pipeline && (this.pipeline.reset(), e || this.pipeline.eventBus.emit("pipeline:historyReset")), this._afterReset(), this.completion.reset(), this.wake(), this.dispatchEvent({ type: g.RENDER_RESET });
2448
+ }
2449
+ dispose() {
2450
+ if (!this._disposed) {
2451
+ if (this._disposed = !0, this.dispatchEvent({ type: g.DISPOSE }), this.stopAnimation(), clearTimeout(this._resizeDebounceTimer), this._resizeDebounceTimer = null, this._removeTrackedListeners(), ae(null), this._storageRelease?.(), this._storageRelease = null, this.storage = null, this._sceneSource = this._sceneSourceFile = null, this._issues.detach(), this.color?.dispose(), this.color = null, this._textureReadback?.dispose(), this._textureReadback = null, this._readbackToneMapper?.dispose(), this._readbackToneMapper = null, this._disposeExtensions(), this.lightManager?.dispose(), this.pipeline?.dispose(), this._sdf?.dispose(), this._sdf = null, this.assetLoader?.dispose(), this.assetLoader = null, this.meshScene) {
2452
+ this.meshScene.environment?.dispose(), this.meshScene.environment = null;
2453
+ for (let e of [...this.meshScene.children]) pe(e);
2454
+ this.meshScene.clear(), this.meshScene = null;
2455
+ }
2456
+ this._sceneHelpers?.clear(), this._sceneHelpers = null, this.scene?.clear(), this.scene = null;
2457
+ try {
2458
+ let e = Ke().value, t = Ve().value;
2459
+ e?._listeners?.dispose && (e._listeners.dispose.length = 0), t?._listeners?.dispose && (t._listeners.dispose.length = 0);
2460
+ } catch (e) {
2461
+ $.warn("failed to clear TSL texture singleton listeners", e);
2462
+ }
2463
+ this.canvas && Q.get(this.canvas) === this && Q.delete(this.canvas), this._gpuDevice &&= (this._gpuDevice.onuncapturederror = null, null), this._deviceLostHolder &&= (this._deviceLostHolder.app = null, null), oe(this.renderer), this.renderer = null, this.stages = {}, this.isInitialized = !1;
2464
+ }
2465
+ }
2466
+ unloadScene() {
2467
+ if (this.isInitialized) {
2468
+ if (this._loadingInProgress) throw Error("PathTracerApp.unloadScene: cannot unload while a load is in progress");
2469
+ this._disposed || (this._releaseSceneState(), this.assetLoader?.releaseTargetModel(), this._sceneSource = this._sceneSourceFile = null, this.lightManager?.clearLights?.(), this.stages.pathTracer && (this.stages.pathTracer.setTriangleData(new Uint32Array(ge.FLOATS_PER_TRIANGLE), 0), this.stages.pathTracer.setBVHData(Hn()), this.stages.pathTracer.materialData.setMaterialData(new Float32Array(16)), this.stages.pathTracer.setEmissiveTriangleData?.(new Float32Array(), 0, 0), this.stages.pathTracer.setupMaterial()), this._dropDisplay(), this.reset(), this.dispatchEvent({ type: g.SCENE_UNLOADED }));
2470
+ }
2471
+ }
2472
+ async loadModel(e, t = {}) {
2473
+ await this._loadWithSceneRebuild(() => this.assetLoader.loadModel(e, t), {
2474
+ type: g.MODEL_LOADED,
2475
+ url: e
2476
+ }, {
2477
+ kind: "url",
2478
+ url: e,
2479
+ cacheKey: t.cacheKey ?? null
2480
+ });
2481
+ }
2482
+ async loadObject3D(e, t = "object3d") {
2483
+ await this._loadWithSceneRebuild(() => this.assetLoader.loadObject3D(e, t), {
2484
+ type: g.OBJECT3D_LOADED,
2485
+ name: t
2486
+ }, {
2487
+ kind: "object3d",
2488
+ name: t
2489
+ });
2490
+ }
2491
+ _busyError(e) {
2492
+ let t = /* @__PURE__ */ Error(`${e}: another load is already in progress`);
2493
+ return t.code = "LOAD_IN_PROGRESS", t;
2494
+ }
2495
+ async loadEnvironment(e) {
2496
+ if (this._loadingInProgress) throw this._busyError("PathTracerApp.loadEnvironment");
2497
+ this._loadingInProgress = !0;
2498
+ try {
2499
+ await this.assetLoader.loadEnvironment(e);
2500
+ let t = this.meshScene.environment;
2501
+ t && this.stages.pathTracer && await this.stages.pathTracer.environment.setEnvironmentMap(t), this.pipeline?.eventBus.emit("pipeline:lightingChanged"), this.reset(), this.dispatchEvent({
2502
+ type: g.ENVIRONMENT_LOADED,
2503
+ url: e
2504
+ });
2505
+ } finally {
2506
+ this._loadingInProgress = !1;
2507
+ }
2508
+ }
2509
+ async inspectArchive(e) {
2510
+ return await this.assetLoader.inspectArchive(e);
2511
+ }
2512
+ async loadFile(e, t = {}) {
2513
+ if (t = this._sceneBudgets(t), typeof e == "string") {
2514
+ let n = t.filename ?? K(e), r = this.assetLoader?.getFileFormat(n);
2515
+ if (!r) throw this.assetLoader.formatError(n);
2516
+ if (r.type === "environment" || r.type === "image") return this.loadEnvironment(e);
2517
+ await this._loadWithSceneRebuild(() => this.assetLoader.loadAssetFromUrl(e, {
2518
+ ...t,
2519
+ filename: n
2520
+ }), {
2521
+ type: g.MODEL_LOADED,
2522
+ filename: n
2523
+ }, {
2524
+ kind: "url",
2525
+ url: e,
2526
+ filename: n,
2527
+ cacheKey: t.cacheKey ?? null,
2528
+ ...Rn(t)
2529
+ });
2530
+ return;
2531
+ }
2532
+ let n = this.assetLoader?.getFileFormat(e?.name || "");
2533
+ if (!n) throw this.assetLoader.formatError(e?.name || "");
2534
+ if (n.type !== "environment" && n.type !== "image") {
2535
+ let n = ke(e).catch(() => ({
2536
+ name: e.name,
2537
+ size: e.size,
2538
+ lastModified: e.lastModified ?? 0,
2539
+ sample: null
2540
+ }));
2541
+ await this._loadWithSceneRebuild(() => this.assetLoader.loadAssetFromFile(e, t), {
2542
+ type: g.MODEL_LOADED,
2543
+ filename: e.name
2544
+ }, async () => {
2545
+ let e = await n;
2546
+ return {
2547
+ kind: "local-file",
2548
+ file: e,
2549
+ key: e.sample ? T(e) : null,
2550
+ ...Rn(t)
2551
+ };
2552
+ }), this._sceneSourceFile = e;
2553
+ return;
2554
+ }
2555
+ if (this._loadingInProgress) throw this._busyError("PathTracerApp.loadFile");
2556
+ this._loadingInProgress = !0;
2557
+ try {
2558
+ await this.assetLoader.loadAssetFromFile(e);
2559
+ let t = this.meshScene.environment;
2560
+ t && this.stages.pathTracer && await this.stages.pathTracer.environment.applyHDRI(t), this.pipeline?.eventBus.emit("pipeline:lightingChanged"), this.reset(), this.dispatchEvent({
2561
+ type: g.ENVIRONMENT_LOADED,
2562
+ filename: e.name
2563
+ });
2564
+ } finally {
2565
+ this._loadingInProgress = !1;
2566
+ }
2567
+ }
2568
+ async loadExampleModels(e, t) {
2569
+ await this._loadWithSceneRebuild(() => this.assetLoader.loadExampleModels(e, t), {
2570
+ type: g.MODEL_LOADED,
2571
+ index: e
2572
+ }, {
2573
+ kind: "url",
2574
+ url: t[e]?.url ?? null,
2575
+ cacheKey: null
2576
+ });
2577
+ }
2578
+ cancelLoad() {
2579
+ this._loadingInProgress && this.assetLoader?.cancelActiveLoad();
2580
+ }
2581
+ async setMaxTextureSize(e, { reprocess: t = !0 } = {}) {
2582
+ let n = this.settings.get("maxTextureSize"), r = this._sdf?.setMaxTextureSize(e) ?? e;
2583
+ if (this.settings.set("maxTextureSize", r, { reset: !1 }), typeof this.stages?.pathTracer?.sdfs?.setMaxTextureSize == "function" && this.stages.pathTracer.sdfs.setMaxTextureSize(r), t && r !== n && this._sdf?.triangles && !this._loadingInProgress) {
2584
+ this._loadingInProgress = !0;
2585
+ try {
2586
+ await this.loadSceneData(), this.reset(), this.dispatchEvent({
2587
+ type: g.TEXTURES_REPROCESSED,
2588
+ maxTextureSize: r
2589
+ });
2590
+ } finally {
2591
+ this._loadingInProgress = !1;
2592
+ }
2593
+ }
2594
+ }
2595
+ get sceneSource() {
2596
+ return this._sceneSource ?? null;
2597
+ }
2598
+ get sceneSourceFile() {
2599
+ return this._sceneSourceFile ?? null;
2600
+ }
2601
+ async _loadWithSceneRebuild(e, t, n = null) {
2602
+ if (this._loadingInProgress) throw this._busyError("PathTracerApp");
2603
+ this._loadingInProgress = !0;
2604
+ try {
2605
+ await e(), this._sceneSource = typeof n == "function" ? await n() : n, this._sceneSourceFile = null, this._emissiveSamplingUserSet = !1, this._clearAppendedModels(), this._modelReplaced(), await this.loadSceneData({ pendingEnvironment: this._beginSceneMetadataEnvironment() }), this._maybeSpill(), this.pipeline?.eventBus.emit("pipeline:lightingChanged"), this._dropDisplay(), this.reset(), this.dispatchEvent(t), this._modelAnnounced();
2606
+ } catch (e) {
2607
+ throw (!e || e.code !== "LOAD_IN_PROGRESS") && this._discardFailedLoad(), e?.code === "ARCHIVE_NEEDS_ELEMENT" ? v() : e?.code !== "LOAD_IN_PROGRESS" && _({
2608
+ status: `Error: ${e?.message ?? e}`,
2609
+ failed: !0,
2610
+ progress: 100
2611
+ }), e;
2612
+ } finally {
2613
+ this._loadingInProgress = !1;
2614
+ }
2615
+ }
2616
+ _discardFailedLoad() {
2617
+ this._sceneSource = this._sceneSourceFile = null;
2618
+ try {
2619
+ this._clearAppendedModels(), this.assetLoader?.releaseTargetModel(), this._dropDisplay(), this.reset();
2620
+ } catch (e) {
2621
+ console.warn("PathTracerApp: could not clear the scene after a failed load", e);
2622
+ }
2623
+ }
2624
+ get sceneMetadata() {
2625
+ return this.assetLoader?.sceneMetadata ?? null;
2626
+ }
2627
+ _beginSceneMetadataEnvironment() {
2628
+ this._restoreUnlitSettings();
2629
+ let e = this.sceneMetadata?.environment;
2630
+ return this._applySceneMetadataEnabled && e?.enabled === !1 ? (this._applyUnlitSettings(), null) : !this._applySceneMetadataEnabled || !e?.sourceFile || !this.stages.pathTracer ? null : (this.stages.pathTracer.environment.beginHDRI(), this._applyingSceneMetadata = !0, this.assetLoader.loadEnvironment(e.sourceFile).catch((t) => (this._issues.record(b.ENVIRONMENT_LOAD_FAILED, `authored environment "${e.sourceFile}" failed to load — lighting falls back to the previous environment`, {
2631
+ sourceFile: e.sourceFile,
2632
+ cause: String(t?.message ?? t)
2633
+ }), null)).finally(() => {
2634
+ this._applyingSceneMetadata = !1;
2635
+ }));
2636
+ }
2637
+ _applySceneMetadataSettings(e) {
2638
+ let t = this.sceneMetadata, n = t?.environment;
2639
+ if (!n || n.enabled === !1) return;
2640
+ let r = {
2641
+ enableEnvironment: !0,
2642
+ showBackground: !0,
2643
+ transparentBackground: !1
2644
+ };
2645
+ n.intensity !== void 0 && (r.environmentIntensity = n.intensity, r.backgroundIntensity = n.intensity), n.rotation !== void 0 && (r.environmentRotation = n.rotation), this.settings.setMany(r, {
2646
+ reset: !1,
2647
+ source: Y.SCENE_METADATA
2648
+ }), this.scene && (this.scene.background = e), this.dispatchEvent({
2649
+ type: g.SCENE_METADATA_APPLIED,
2650
+ metadata: t,
2651
+ environment: { ...n }
2652
+ });
2653
+ }
2654
+ _applyUnlitSettings() {
2655
+ let e = this.settings.getEffective(), t = {
2656
+ enableEnvironment: !1,
2657
+ showBackground: !1
2658
+ };
2659
+ this._unlitRestore = Object.fromEntries(Object.keys(t).map((t) => [t, {
2660
+ value: e[t].value,
2661
+ source: e[t].source
2662
+ }])), this.settings.setMany(t, {
2663
+ reset: !1,
2664
+ source: Y.SCENE_METADATA
2665
+ }), this.dispatchEvent({
2666
+ type: g.SCENE_METADATA_APPLIED,
2667
+ metadata: this.sceneMetadata,
2668
+ environment: { enabled: !1 }
2669
+ });
2670
+ }
2671
+ _restoreUnlitSettings() {
2672
+ let e = this._unlitRestore;
2673
+ if (!e) return;
2674
+ this._unlitRestore = null;
2675
+ let t = this.settings.getEffective();
2676
+ for (let [n, { value: r, source: i }] of Object.entries(e)) t[n]?.source === Y.SCENE_METADATA && this.settings.set(n, r, {
2677
+ reset: !1,
2678
+ source: i
2679
+ });
2680
+ this.dispatchEvent({
2681
+ type: g.SCENE_METADATA_APPLIED,
2682
+ metadata: this.sceneMetadata,
2683
+ environment: { enabled: this.settings.get("enableEnvironment") }
2684
+ });
2685
+ }
2686
+ async loadSceneData({ pendingEnvironment: e = null, keepUserLights: t = !1 } = {}) {
2687
+ this._releaseSceneState({ keepSelection: !!this._preserveSelectionOnRebuild }), this._tagPrimarySceneObject();
2688
+ let n = new p("", {
2689
+ namespace: "scene",
2690
+ level: "info"
2691
+ }), r = () => this.stages.pathTracer.environment.envParams.mode === "hdri" ? this.meshScene.environment : null, i = r(), a = null;
2692
+ if (e ? (n.start("Environment fetch + CDF (concurrent)"), a = e.then(async (e) => {
2693
+ e && (await this.stages.pathTracer.environment.applyHDRI(e), this._applySceneMetadataSettings(e));
2694
+ }).catch((e) => this._issues.record(b.ENVIRONMENT_LOAD_FAILED, "authored environment failed to install — the scene is lit by whatever was already loaded", { cause: String(e?.message ?? e) })).finally(() => n.end("Environment fetch + CDF (concurrent)"))) : i?.image?.data && (n.start("Environment CDF build (worker)"), this.stages.pathTracer.scene.environment = i, a = this.stages.pathTracer.environment.buildEnvironmentCDF().then(() => {
2695
+ n.end("Environment CDF build (worker)"), this._applySceneMetadataEnabled && this._applySceneMetadataSettings(i);
2696
+ })), n.start("BVH build (SceneProcessor)"), this._sdf.setMaxTextureSize(this.settings.get("maxTextureSize")), await this._sdf.buildBVH(this.meshScene, {
2697
+ sceneKey: this.assetLoader?.sceneSourceKey ?? null,
2698
+ progressive: this._progressiveSpill()
2699
+ }), this.assetLoader?.flushPendingGraph(this._sdf.performanceMetrics.totalProcessingTime), n.end("BVH build (SceneProcessor)"), _({
2700
+ status: "Transferring data to GPU...",
2701
+ progress: 86
2702
+ }), await new Promise((e) => setTimeout(e, 0)), n.start("GPU data transfer"), !this._sdf.uploadToPathTracer(this.stages.pathTracer, this.lightManager, this.meshScene, r(), { keepUserLights: t })) return !1;
2703
+ this.stages.pathTracer._meshRefs = this.stages.pathTracer._collectMeshRefs(this.meshScene), this.stages.pathTracer.setMeshVisibilityData(this.stages.pathTracer._meshRefs), this._refreshEmissiveForVisibility(), n.end("GPU data transfer"), _({
2704
+ status: "Compiling shaders...",
2705
+ progress: 90
2706
+ }), await new Promise((e) => setTimeout(e, 0)), n.start("Material setup (TSL compile)"), this.stages.pathTracer.setupMaterial(), n.end("Material setup (TSL compile)"), this._rasterPrecompile = null, this._pathTracerEnabled || (n.start("Pipeline precompile"), await this.precompileRaster(), n.end("Pipeline precompile")), a && (_({
2707
+ status: "Finalizing environment map...",
2708
+ progress: 95
2709
+ }), await a, this.stages.pathTracer.environment.applyCDFResults());
2710
+ let o = this.getSceneMinY();
2711
+ if (this.settings.set("groundProjectionLevel", o, { reset: !1 }), this.settings.set("groundCatcherHeight", o, { reset: !1 }), !this._emissiveSamplingUserSet) {
2712
+ let e = (this._sdf?.emissiveTriangleBuilder?.emissiveTriangles?.length ?? this._sdf?.emissiveTriangleCount ?? 0) > 0;
2713
+ this.settings.set("enableEmissiveTriangleSampling", e, { reset: !1 });
2714
+ }
2715
+ return n.start("Apply settings"), this.settings.applyAll(), this.stages.compositor.setTransparentBackground(this.settings.get("transparentBackground")), n.end("Apply settings"), n.print(this._sceneSummaryParts()), v(), this._sceneRebuilt(), this.dispatchEvent({ type: g.SCENE_REBUILD }), !0;
2716
+ }
2717
+ _sceneSummaryParts() {
2718
+ let e = this.stages.pathTracer, t = this._sdf?.instanceTable?.setCount ?? 0, n = this._sdf?.geometryExtractor?.maps?.length ?? 0;
2719
+ return [
2720
+ y.count(e.triangleCount, "tri"),
2721
+ t ? y.count(t, "mesh", "meshes") : null,
2722
+ y.count(e.materialData.materialCount, "material"),
2723
+ n ? y.count(n, "map") : null,
2724
+ y.count(e.bvhNodeCount, "BVH node")
2725
+ ];
2726
+ }
2727
+ _tagPrimarySceneObject() {
2728
+ let e = this.sceneModel;
2729
+ e && (e.userData.__rayzeeSceneObject = !0);
2730
+ }
2731
+ _clearAppendedModels() {
2732
+ let e = this.meshScene;
2733
+ if (!e) return;
2734
+ let t = this.assetLoader?.floorPlane, n = this.sceneModel;
2735
+ for (let r of [...e.children]) r === t || r === n || r.userData?.__rayzeeSceneObject && this.assetLoader.removeModelRoot(r);
2736
+ }
2737
+ async _finishRebuildNoReframe(e) {
2738
+ await this.loadSceneData({ keepUserLights: !0 }), this._maybeSpill(), this._sceneBoundsChanged(), this.pipeline?.eventBus.emit("pipeline:lightingChanged"), this.reset(), e && this.dispatchEvent(e);
2739
+ }
2740
+ async addModel(e, { name: t, cacheKey: n } = {}) {
2741
+ if (this._loadingInProgress) throw Error("PathTracerApp.addModel: another load is already in progress");
2742
+ this._loadingInProgress = !0, this._preserveSelectionOnRebuild = !0;
2743
+ try {
2744
+ let { root: r } = await this.assetLoader.appendModel(e, { cacheKey: n });
2745
+ return r.userData.__rayzeeSceneObject = !0, r.userData.__rayzeeSourceUrl = e, n && (r.userData.__rayzeeCacheKey = n), t && (r.userData.__rayzeeName = t), await this._finishRebuildNoReframe({
2746
+ type: g.MODEL_ADDED,
2747
+ url: e,
2748
+ id: r.uuid
2749
+ }), r.uuid;
2750
+ } finally {
2751
+ this._preserveSelectionOnRebuild = !1, this._loadingInProgress = !1;
2752
+ }
2753
+ }
2754
+ async addModelFromObject3D(e, { name: t } = {}) {
2755
+ if (this._loadingInProgress) throw Error("PathTracerApp.addModelFromObject3D: another load is already in progress");
2756
+ this._loadingInProgress = !0, this._preserveSelectionOnRebuild = !0;
2757
+ try {
2758
+ let { root: n } = this.assetLoader.appendObject3D(e, t || "object3d");
2759
+ return n.userData.__rayzeeSceneObject = !0, t && (n.userData.__rayzeeName = t), await this._finishRebuildNoReframe({
2760
+ type: g.MODEL_ADDED,
2761
+ id: n.uuid
2762
+ }), n.uuid;
2763
+ } finally {
2764
+ this._preserveSelectionOnRebuild = !1, this._loadingInProgress = !1;
2765
+ }
2766
+ }
2767
+ async removeSceneObject(e) {
2768
+ if (!this.meshScene) return !1;
2769
+ let t = this.assetLoader?.floorPlane;
2770
+ if (t && t.uuid === e) return !1;
2771
+ let n = this.getSceneObject(e);
2772
+ if (!n) return !1;
2773
+ if (this._loadingInProgress) throw Error("PathTracerApp.removeSceneObject: another load is already in progress");
2774
+ this._loadingInProgress = !0;
2775
+ try {
2776
+ return this._releaseSceneState(), n === this.sceneModel ? this.assetLoader.releaseTargetModel() : this.assetLoader.removeModelRoot(n), await this._finishRebuildNoReframe({
2777
+ type: g.SCENE_OBJECT_REMOVED,
2778
+ id: e
2779
+ }), !0;
2780
+ } finally {
2781
+ this._loadingInProgress = !1;
2782
+ }
2783
+ }
2784
+ setSceneObjectVisibility(e, t) {
2785
+ return this.setMeshVisibilityByUuid(e, t);
2786
+ }
2787
+ _sceneBudgets(e) {
2788
+ return !this._memorySpill || !this.storage ? e : {
2789
+ maxTriangles: fe,
2790
+ maxPlacements: ue,
2791
+ ...e
2792
+ };
2793
+ }
2794
+ _progressiveSpill() {
2795
+ if (!this._memorySpill || !this.storage || (this.assetLoader?.animations?.length ?? 0) > 0) return null;
2796
+ let e = this.stages.pathTracer;
2797
+ return {
2798
+ storage: this.storage,
2799
+ uploader: (t, n) => n === "triangles" ? e.createTriangleChunkUploader(t) : e.createChunkUploader(t)
2800
+ };
2801
+ }
2802
+ _maybeSpill() {
2803
+ !this._memorySpill || !this.storage || (this.assetLoader?.animations?.length ?? 0) > 0 || this._sdf?.spillToDisk(this.storage).then((e) => e && this.dispatchEvent({
2804
+ type: g.SCENE_SPILLED,
2805
+ ...e
2806
+ })).catch((e) => this._issues.warn(b.STORAGE_WRITE_FAILED, `memory spill failed: ${e.message}`));
2807
+ }
2808
+ async ensureSceneResident() {
2809
+ this._sdf?.spilled && await this._sdf.ensureResident();
2810
+ }
2811
+ get sceneMeshes() {
2812
+ return this._sdf?.meshes ?? [];
2813
+ }
2814
+ get sceneModel() {
2815
+ return this.assetLoader?.targetModel ?? null;
2816
+ }
2817
+ getSceneObject(e) {
2818
+ let t = this.meshScene?.children.find((t) => t.uuid === e);
2819
+ return t?.userData?.__rayzeeSceneObject ? t : null;
2820
+ }
2821
+ async refitBVH(e, t) {
2822
+ await this.ensureSceneResident();
2823
+ let { triRanges: n, bvhRanges: r, ...i } = await this._sdf.refitBVH(e, t);
2824
+ return this.stages.pathTracer.updateTriangleData(this._sdf.triangles, n), this.stages.pathTracer.updateBVHData(this._sdf.bvh, r), this.reset(!1, { motion: !0 }), i;
2825
+ }
2826
+ refitBLASes(e, t, n) {
2827
+ if (this._sdf?.spilled) throw Error("refitBLASes: the scene is spilled to disk — await app.ensureSceneResident() first");
2828
+ let r = this._sdf.refitBLASes(e, t, n), { triRanges: i, bvhRanges: a } = this._sdf.computeBLASDirtyRanges(e);
2829
+ return this.stages.pathTracer.updateBufferRanges(i, a), this.reset(!1, { motion: !0 }), this._sdf.scheduleBackgroundRebuild(e, (e) => {
2830
+ let t = this._sdf.computeBLASDirtyRanges([e]);
2831
+ this.stages.pathTracer.updateBufferRanges(t.triRanges, t.bvhRanges), this.reset(!1, { motion: !0 });
2832
+ }), r;
2833
+ }
2834
+ updateMeshTransforms(e) {
2835
+ this._notePlacementsMoving(e);
2836
+ let t = this._sdf.updateMeshTransforms(e);
2837
+ return this.stages.pathTracer.updateBufferRanges([], [this._sdf.computeTLASDirtyRange()]), this.reset(!1, { motion: !0 }), t;
2838
+ }
2839
+ setReservedRenderResolution(e, { allowLower: t = !1 } = {}) {
2840
+ let n = t ? e : Math.max(e, i);
2841
+ if (!this.renderer) return this._pendingReservedRenderSize = {
2842
+ requestedPx: e,
2843
+ allowLower: t
2844
+ }, Math.max(256, Math.min(r, Math.floor(n) || 256));
2845
+ let a = this.renderer.backend?.device?.limits?.maxStorageBufferBindingSize || 128 * 1024 * 1024, o = se(this._hostMemoryGB), s = o.gb >= 8 && a >= 1024 * 1024 * 1024 ? r : 2048, c = te(Math.min(n, s));
2846
+ if (c < Math.floor(e) && this._issues.warn(b.RENDER_RESERVE_CAPPED, `reserved render size ${y.n(e)}px was capped to ${y.n(c)}px by this device's limits — renders above ${y.n(c)}px will be declined` + (o.assumed && o.gb < 8 ? " (host memory unknown, 4 GB assumed: pass hostMemoryGB)" : ""), {
2847
+ requested: e,
2848
+ applied: c,
2849
+ deviceMemoryGB: o.gb,
2850
+ assumed: o.assumed,
2851
+ maxStorageBufferBindingSize: a
2852
+ }), (this.stages?.pathTracer?.storageTextures?.writeColor?.image?.width ?? c) !== c) {
2853
+ let e = this.pauseRendering;
2854
+ this.pauseRendering = !0;
2855
+ try {
2856
+ let e = this.renderer.domElement;
2857
+ (e.width > c || e.height > c) && this.renderer.setSize(Math.min(e.width, c), Math.min(e.height, c), !1);
2858
+ for (let e of Object.values(this.stages)) e?.reallocateReservedStorage?.();
2859
+ } finally {
2860
+ this.pauseRendering = e;
2861
+ }
2862
+ this.reset(), this.dispatchEvent({
2863
+ type: g.RESERVED_RENDER_SIZE_CHANGED,
2864
+ size: c
2865
+ });
2866
+ }
2867
+ return c;
2868
+ }
2869
+ _applyPendingReservedRenderSize() {
2870
+ let e = this._pendingReservedRenderSize;
2871
+ if (!e) return;
2872
+ this._pendingReservedRenderSize = null;
2873
+ let t = this.setReservedRenderResolution(e.requestedPx, { allowLower: e.allowLower });
2874
+ this.dispatchEvent({
2875
+ type: g.RESERVED_RENDER_SIZE_CHANGED,
2876
+ size: t
2877
+ });
2878
+ }
2879
+ getReservedRenderResolution() {
2880
+ return i;
2881
+ }
2882
+ _isRenderSizeSupported(e, t) {
2883
+ return e > i || t > i ? (this._issues.record(b.RENDER_SIZE_DECLINED, `render resolution ${e}×${t} exceeds the ${i}px storage reserve — resize ignored, so output stays at the previous size. Raise it with setReservedRenderResolution( ${Math.max(e, t)} ) before init().`, {
2884
+ width: e,
2885
+ height: t,
2886
+ reserve: i
2887
+ }), !1) : !0;
2888
+ }
2889
+ onResize() {
2890
+ let e = this.canvas.clientWidth, t = this.canvas.clientHeight;
2891
+ e === 0 || t === 0 || this._isRenderSizeSupported(e, t) && (this.renderer.setPixelRatio(1), this._setDisplaySize(e, t), !(e === this._renderWidth && t === this._renderHeight) && (clearTimeout(this._resizeDebounceTimer), this._resizeDebounceTimer = setTimeout(() => {
2892
+ this._applyRenderResize(e, t);
2893
+ }, 300)));
2894
+ }
2895
+ _applyRenderResize(e, t) {
2896
+ this._isRenderSizeSupported(e, t) && (this.pipeline?.setSize(this._scaled(e), this._scaled(t)), this._renderWidth = e, this._renderHeight = t, this._renderSizeChanged(e, t), this.needsReset = !0, this.dispatchEvent({
2897
+ type: g.RESOLUTION_CHANGED,
2898
+ width: e,
2899
+ height: t
2900
+ }));
2901
+ }
2902
+ setCanvasSize(e, t) {
2903
+ return e === 0 || t === 0 || !this._isRenderSizeSupported(e, t) ? null : (this.renderer.setPixelRatio(1), this._setDisplaySize(e, t), clearTimeout(this._resizeDebounceTimer), this._applyRenderResize(e, t), {
2904
+ width: e,
2905
+ height: t
2906
+ });
2907
+ }
2908
+ _scaled(e) {
2909
+ return Math.max(1, Math.round(e * this._renderScale));
2910
+ }
2911
+ _setDisplaySize(e, t) {
2912
+ this._displayWidth = e, this._displayHeight = t, this.renderer.setSize(this._scaled(e), this._scaled(t), !1), this.camera.aspect = e / t, this.camera.updateProjectionMatrix();
2913
+ }
2914
+ refreshFrame() {
2915
+ this._needsDisplayRefresh = !0, this.wake();
2916
+ }
2917
+ setDeterministicMode(e = !0, { pinDispatch: t = !0 } = {}) {
2918
+ let n = this.stages.pathTracer;
2919
+ if (!n) return !1;
2920
+ if (e) this._deterministicRestore ||= {
2921
+ settings: {
2922
+ useAdaptiveSampling: this.settings.get("useAdaptiveSampling"),
2923
+ usePixelFreeze: this.settings.get("usePixelFreeze"),
2924
+ interactionModeEnabled: this.settings.get("interactionModeEnabled"),
2925
+ renderLimitMode: this.settings.get("renderLimitMode"),
2926
+ renderTimeLimit: this.settings.get("renderTimeLimit")
2927
+ },
2928
+ bounceEarlyExit: n._bounceEarlyExitThreshold,
2929
+ dynamicDispatch: n._useDynamicDispatch,
2930
+ extras: this._deterministicSnapshot()
2931
+ }, this.settings.setMany({
2932
+ useAdaptiveSampling: !1,
2933
+ usePixelFreeze: !1,
2934
+ interactionModeEnabled: !1,
2935
+ renderLimitMode: "frames",
2936
+ renderTimeLimit: 0
2937
+ }, { silent: !0 }), t ? (n._bounceEarlyExitThreshold = -1, n._useDynamicDispatch = !1) : (n._bounceEarlyExitThreshold = this._deterministicRestore.bounceEarlyExit, n._useDynamicDispatch = this._deterministicRestore.dynamicDispatch), this._setDeterministicExtras(!0, this._deterministicRestore.extras), n._pinSeedToFrame = !0, this._deterministic = !0, this._dispatchPinned = t;
2938
+ else if (this._deterministicRestore) {
2939
+ let e = this._deterministicRestore;
2940
+ this.settings.setMany(e.settings, { silent: !0 }), n._bounceEarlyExitThreshold = e.bounceEarlyExit, n._useDynamicDispatch = e.dynamicDispatch, this._setDeterministicExtras(!1, e.extras), n._pinSeedToFrame = !1, this._deterministicRestore = null, this._deterministic = !1, this._dispatchPinned = !1;
2941
+ }
2942
+ return this.reset(), this.stopAnimation(), this._deterministic;
2943
+ }
2944
+ get issues() {
2945
+ return this._issues.list;
2946
+ }
2947
+ get issueErrors() {
2948
+ return this._issues.errors;
2949
+ }
2950
+ clearIssues() {
2951
+ this._issues.clear();
2952
+ }
2953
+ get isDeterministic() {
2954
+ return this._deterministic && this._dispatchPinned;
2955
+ }
2956
+ async renderFrames(e, { reset: t = !0, yieldEvery: n = 8, onProgress: r, allowEarlyRetire: i = !1 } = {}) {
2957
+ let a = this.stages.pathTracer;
2958
+ if (!a) throw Error("renderFrames: app is not initialized");
2959
+ if (!(e > 0)) throw Error(`renderFrames: count must be positive, got ${e}`);
2960
+ let o = (t ? 0 : a.frameCount) + e;
2961
+ this.settings.get("maxSamples") < o && this.settings.set("maxSamples", o, {
2962
+ silent: !0,
2963
+ reset: !1
2964
+ }), t && this.reset(), this.stopAnimation();
2965
+ let s = e + 64, c = 0, l = !1;
2966
+ for (; a.frameCount < o && c < s;) {
2967
+ if (this._deviceLost) throw Error("renderFrames: WebGPU device lost");
2968
+ if (!a.isReady) throw Error("renderFrames: path tracer stage is not ready");
2969
+ let e = a.readbackWait();
2970
+ if (e) {
2971
+ await this._awaitReadback(e);
2972
+ continue;
2973
+ }
2974
+ if (this.camera.updateMatrixWorld(), this.pipeline.render(), c++, a.isComplete && a.frameCount < o) {
2975
+ l = !0;
2976
+ break;
2977
+ }
2978
+ r?.(a.frameCount), n > 0 && c % n === 0 && await new Promise((e) => setTimeout(e, 0));
2979
+ }
2980
+ if (a.frameCount < o && !(l && i)) {
2981
+ let e = l ? "adaptive sampling retired the frame at the convergence threshold — pass `allowEarlyRetire: true`, or disable it with setDeterministicMode()" : "something retired the render (maxSamples, a stray reset, or a canvas resize)";
2982
+ throw Error(`renderFrames: stopped at ${a.frameCount}/${o} samples after ${c} passes — ${e}`);
2983
+ }
2984
+ return a.frameCount;
2985
+ }
2986
+ async renderUntilComplete({ reset: e = !0, denoise: t = !0, signal: n, drainEvery: r = 4, onProgress: i } = {}) {
2987
+ let a = this.stages.pathTracer;
2988
+ if (!a) throw Error("renderUntilComplete: app is not initialized");
2989
+ if (this._loadingInProgress || this._sdf?.isProcessing) throw Error("renderUntilComplete: a scene is still loading");
2990
+ let o = a.lockstepReadbacks;
2991
+ a.setLockstepReadbacks(!0);
2992
+ let s = this.settings.getEffective().interactionModeEnabled;
2993
+ this.settings.set("interactionModeEnabled", !1, {
2994
+ silent: !0,
2995
+ reset: !1
2996
+ });
2997
+ try {
2998
+ e && this.reset(), this.stopAnimation();
2999
+ let o = this.renderer.backend.device?.queue, s = 0, c = null;
3000
+ for (; !a.isComplete;) {
3001
+ if (n?.throwIfAborted(), this._deviceLost) throw Error("renderUntilComplete: WebGPU device lost");
3002
+ if (!a.isReady) throw Error("renderUntilComplete: path tracer stage is not ready");
3003
+ let e = a.readbackWait();
3004
+ if (e) {
3005
+ await this._awaitReadback(e);
3006
+ continue;
3007
+ }
3008
+ this.camera.updateMatrixWorld();
3009
+ let t = a.frameCount;
3010
+ if (this._traceFrame(), i?.(a.frameCount), a.frameCount === t && !a.isComplete && await new Promise((e) => setTimeout(e, 0)), o && r > 0 && ++s % r === 0) {
3011
+ let e = o.onSubmittedWorkDone();
3012
+ c && await c, c = e;
3013
+ }
3014
+ }
3015
+ let l = this._completionInfo();
3016
+ this.completion.markComplete() && this.dispatchEvent({
3017
+ type: g.RENDER_COMPLETE,
3018
+ ...l
3019
+ });
3020
+ let u = t ? await this._finalDenoise() : !1, { reason: d, ...f } = l;
3021
+ return {
3022
+ ...f,
3023
+ retiredBy: d,
3024
+ denoised: u
3025
+ };
3026
+ } finally {
3027
+ a.setLockstepReadbacks(o), s && this.settings.set("interactionModeEnabled", s.value, {
3028
+ silent: !0,
3029
+ reset: !1,
3030
+ source: s.source
3031
+ });
3032
+ }
3033
+ }
3034
+ getProvenance() {
3035
+ let e = this.stages.pathTracer, t = this.color?.status();
3036
+ return h({
3037
+ engine: de,
3038
+ three: ht,
3039
+ adapter: this.adapterInfo ?? null,
3040
+ mode: {
3041
+ headless: this._headless,
3042
+ strict: this._issues.strict,
3043
+ deterministic: this.isDeterministic,
3044
+ lockstep: !!e?.accumulationLockstep
3045
+ },
3046
+ render: e ? {
3047
+ width: e.width,
3048
+ height: e.height,
3049
+ samples: e.frameCount,
3050
+ complete: e.isComplete,
3051
+ retiredBy: e.isComplete ? this.completion.stopCondition(e) ?? "samples" : null
3052
+ } : null,
3053
+ color: t ? {
3054
+ config: t.config?.id ?? null,
3055
+ workingSpace: t.workingSpace,
3056
+ view: t.activeView ?? t.activeTransform?.id ?? null,
3057
+ context: t.context
3058
+ } : null,
3059
+ scene: this.sceneSource,
3060
+ settings: this.settings.getEffective(),
3061
+ issues: this.issues.map(({ code: e, severity: t }) => ({
3062
+ code: e,
3063
+ severity: t
3064
+ }))
3065
+ });
3066
+ }
3067
+ setLockstepReadbacks(e = !0) {
3068
+ this.stages.pathTracer?.setLockstepReadbacks(e);
3069
+ }
3070
+ async _awaitReadback(e) {
3071
+ let t = this.renderer.backend.device?.lost, n = await (t ? Promise.race([e.then(() => null), t]) : e);
3072
+ if (n) throw Error(`WebGPU device lost while awaiting a readback: ${n.message ?? n.reason}`);
3073
+ }
3074
+ async captureRenderCheckpoint() {
3075
+ let e = this.stages.pathTracer;
3076
+ if (!e) return null;
3077
+ let t = await e.captureAccumulation();
3078
+ return {
3079
+ v: 1,
3080
+ engine: de,
3081
+ savedAt: Date.now(),
3082
+ samples: t.state.frameCount,
3083
+ ...t
3084
+ };
3085
+ }
3086
+ restoreRenderCheckpoint(e) {
3087
+ if (e?.v !== 1) throw Error(`render checkpoint version ${e?.v} is not 1`);
3088
+ let t = this.stages.pathTracer;
3089
+ if (!t) throw Error("restoreRenderCheckpoint: app is not initialized");
3090
+ t.restoreAccumulation(e), this.needsReset = !1, this.dispatchEvent({
3091
+ type: g.RENDER_RESET,
3092
+ restored: e.samples
3093
+ });
3094
+ }
3095
+ async renderToBuffer({ colorSpace: e = "srgb", preserveAlpha: t = !1, source: n = "accumulation" } = {}) {
3096
+ if (e !== "linear" && e !== "srgb" && !this.color?.hasConfig) throw Error(`renderToBuffer: colorSpace must be 'linear' or 'srgb' without a colour config loaded, got "${e}"`);
3097
+ let r = this.stages?.pathTracer, i = r?.storageTextures?.readTarget;
3098
+ if (!i) throw Error("renderToBuffer: no render target — call init() and render at least one sample");
3099
+ let { width: a, height: o } = r;
3100
+ if (e === "srgb") {
3101
+ let r = n === "display" ? this._displaySource(i) : null, s = {
3102
+ exposure: this.renderer.toneMappingExposure,
3103
+ toneMapping: this.renderer.toneMapping,
3104
+ saturation: this.settings.get("saturation") ?? 1,
3105
+ preserveAlpha: t
3106
+ }, c = await this._toneMapOnGPU(r?.texture ?? null, i, a, o, s);
3107
+ return {
3108
+ data: c ?? l(r ? await this._readTexture(r.texture, a, o) : await this.renderer.readRenderTargetPixelsAsync(i, 0, 0, a, o, 0), s),
3109
+ width: a,
3110
+ height: o,
3111
+ colorSpace: e,
3112
+ source: r?.source ?? "accumulation",
3113
+ toneMappedOn: c ? "gpu" : "cpu"
3114
+ };
3115
+ }
3116
+ let { data: s, source: c } = n === "display" ? await this._readDisplaySource(i, a, o) : {
3117
+ data: await this.renderer.readRenderTargetPixelsAsync(i, 0, 0, a, o, 0),
3118
+ source: "accumulation"
3119
+ };
3120
+ if (e === "linear") return {
3121
+ data: s,
3122
+ width: a,
3123
+ height: o,
3124
+ colorSpace: e,
3125
+ workingSpace: this.color?.workingSpace ?? null,
3126
+ source: c
3127
+ };
3128
+ let { rgba: u, colorSpace: d } = this.color.exportPixels(s, e);
3129
+ return {
3130
+ data: u,
3131
+ width: a,
3132
+ height: o,
3133
+ colorSpace: d,
3134
+ source: c
3135
+ };
3136
+ }
3137
+ async _toneMapOnGPU(e, t, n, r, i) {
3138
+ let a = this.renderer?.backend;
3139
+ if (!a?.device) return this._toneMapFallback("the renderer has no WebGPU device");
3140
+ try {
3141
+ let o = e ? this._readbackPass().draw(e, n, r).texture : t.textures[0], s = a.get(o).texture;
3142
+ return s ? (this._readbackToneMapper ??= new Ae(a.device, "rayzee:readback-tonemap", { input: "texture" }), this._readbackToneMapper.ensureSize(n, r), await this._readbackToneMapper.toRGBA8(s, i)) : this._toneMapFallback("the picture has no GPU texture yet");
3143
+ } catch (e) {
3144
+ if (e instanceof ve) throw e;
3145
+ return this._toneMapFallback("the GPU pass threw", e);
3146
+ } finally {
3147
+ this._readbackToneMapper?.release(), e && this._textureReadback?.release();
3148
+ }
3149
+ }
3150
+ _toneMapFallback(e, t = null) {
3151
+ let n = t ? String(t?.message ?? t) : null, r = `renderToBuffer: tone mapped on the CPU — ${e}${n ? `: ${n}` : ""}`;
3152
+ return $.warn(r), this._issues.warn(b.OUTPUT_TONEMAP_FALLBACK, r, {
3153
+ reason: e,
3154
+ cause: n
3155
+ }), null;
3156
+ }
3157
+ enableGPUTiming(e = !0) {
3158
+ let t = this.renderer?.backend;
3159
+ return !t || e && t.hasFeature?.("timestamp-query") !== !0 ? !1 : (t.trackTimestamp = e, t.trackTimestamp === e);
3160
+ }
3161
+ async getGPUTimings() {
3162
+ let e = this.renderer;
3163
+ if (!e?.backend?.trackTimestamp) return null;
3164
+ await e.resolveTimestampsAsync("compute"), await e.resolveTimestampsAsync("render");
3165
+ let t = e.info.compute.timestamp || 0, n = e.info.render.timestamp || 0;
3166
+ return {
3167
+ compute: t,
3168
+ render: n,
3169
+ total: t + n
3170
+ };
3171
+ }
3172
+ async getKernelGPUTimings() {
3173
+ let e = this.renderer;
3174
+ if (!e?.backend?.trackTimestamp) return null;
3175
+ await e.resolveTimestampsAsync("compute");
3176
+ let t = e.backend.timestampQueryPool?.compute?.timestamps;
3177
+ if (!t || t.size === 0) return null;
3178
+ let n = /* @__PURE__ */ new Map(), r = this.stages?.pathTracer?._kernelManager?.kernels;
3179
+ if (r) for (let [e, t] of r) n.set(t.id, e);
3180
+ let i = [], a = -1;
3181
+ for (let [e, n] of t) {
3182
+ let t = e.split(":");
3183
+ if (t.length !== 4) continue;
3184
+ let r = Number(t[3].slice(1));
3185
+ Number.isFinite(r) && (i.push({
3186
+ nodeId: Number(t[2]),
3187
+ f: r,
3188
+ ms: n
3189
+ }), r > a && (a = r));
3190
+ }
3191
+ let o = {}, s = 0, c = 0;
3192
+ for (let e of i) {
3193
+ if (e.f !== a) continue;
3194
+ s += e.ms;
3195
+ let t = n.get(e.nodeId);
3196
+ t === void 0 ? c += e.ms : o[t] = (o[t] ?? 0) + e.ms;
3197
+ }
3198
+ return {
3199
+ kernels: o,
3200
+ total: s,
3201
+ unattributed: c,
3202
+ frame: a
3203
+ };
3204
+ }
3205
+ getCanvas() {
3206
+ return this.renderer?.domElement ? this._displayCanvas() || (this.stages.compositor && this.pipeline?.context && this.stages.compositor.render(this.pipeline.context), this.renderer.domElement) : null;
3207
+ }
3208
+ screenshot({ type: e = "image/png", quality: t } = {}) {
3209
+ let n = this.getCanvas();
3210
+ return n ? new Promise((r) => n.toBlob(r, e, t)) : Promise.resolve(null);
3211
+ }
3212
+ getStatistics() {
3213
+ try {
3214
+ return this._sdf?.getStatistics?.() ?? null;
3215
+ } catch {
3216
+ return null;
3217
+ }
3218
+ }
3219
+ get pathTracerEnabled() {
3220
+ return this._pathTracerEnabled;
3221
+ }
3222
+ set pathTracerEnabled(e) {
3223
+ this._pathTracerEnabled = e, e || this.precompileRaster();
3224
+ }
3225
+ precompileRaster() {
3226
+ return !this.renderer || !this.meshScene ? Promise.resolve() : (this._rasterPrecompile ??= this.renderer.compileAsync(this.meshScene, this.camera).catch((e) => $.warn("raster fallback precompile failed", e)), this._rasterPrecompile);
3227
+ }
3228
+ get isLoading() {
3229
+ return this._loadingInProgress;
3230
+ }
3231
+ isComplete() {
3232
+ return this.stages.pathTracer?.isComplete ?? !1;
3233
+ }
3234
+ getFrameCount() {
3235
+ return this.stages.pathTracer?.frameCount || 0;
3236
+ }
3237
+ getConvergenceStats() {
3238
+ return this.stages.pathTracer?.getConvergenceStats?.() ?? null;
3239
+ }
3240
+ get vram() {
3241
+ return this.stages.pathTracer?.vramTracker ?? null;
3242
+ }
3243
+ getMemoryInfo() {
3244
+ return this._ensureVRAMWiring(), this.stages.pathTracer?.vramTracker?.measure() ?? {
3245
+ current: 0,
3246
+ peak: 0,
3247
+ byCategory: {}
3248
+ };
3249
+ }
3250
+ getHostMemoryInfo() {
3251
+ let e = this._sdf;
3252
+ return e?.memory ? {
3253
+ preflight: e.memoryPreflight,
3254
+ ...e.memory.report
3255
+ } : null;
3256
+ }
3257
+ _ensureVRAMWiring() {
3258
+ if (this._vramWired) return;
3259
+ let e = this.stages.pathTracer?.vramTracker;
3260
+ if (!e) return;
3261
+ e.register("stages", () => this._collectStageTextures()), this._registerVRAM(e), e.register("canvas", () => [
3262
+ { bytes: this.canvas.width * this.canvas.height * 4 },
3263
+ ...this.renderer?._frameBufferTargets?.values() ?? [],
3264
+ ...this._canvasResources()
3265
+ ]);
3266
+ let t = () => e.measure();
3267
+ this._addTrackedListener(this, g.SCENE_REBUILD, t), this._addTrackedListener(this, g.ENVIRONMENT_LOADED, t), this._addTrackedListener(this, g.RESOLUTION_CHANGED, t), this._vramWired = !0;
3268
+ }
3269
+ _collectStageTextures() {
3270
+ let e = [], t = this.stages || {}, n = t.pathTracer;
3271
+ for (let r in t) {
3272
+ let i = t[r];
3273
+ if (!(!i || i === n || typeof i != "object")) for (let t in i) {
3274
+ let n = i[t];
3275
+ n && (n.isTexture || n.isRenderTarget) && e.push(n);
3276
+ }
3277
+ }
3278
+ return e;
3279
+ }
3280
+ getSceneMinY() {
3281
+ if (!this.meshScene) return 0;
3282
+ let e = new Ye().setFromObject(this.meshScene);
3283
+ return Number.isFinite(e.min.y) ? e.min.y : 0;
3284
+ }
3285
+ getMaterialProperty(e, t) {
3286
+ return this.stages.pathTracer?.materialData.getMaterialProperty(e, t);
3287
+ }
3288
+ getMaterialPropertySource(e, t) {
3289
+ return this.stages.pathTracer?.materialData.getMaterialPropertySource(e, t);
3290
+ }
3291
+ setMaterialProperty(e, t, n) {
3292
+ if (this._sdf?.spilled && m.has(t)) {
3293
+ this.ensureSceneResident().then(() => this.setMaterialProperty(e, t, n));
3294
+ return;
3295
+ }
3296
+ this.stages.pathTracer?.materialData.updateMaterialProperty(e, t, n), ["emissive", "emissiveIntensity"].includes(t) && this._sdf && this._uploadEmissivePayload(this._sdf.updateMaterialEmissive(e, t, n)), this.reset();
3297
+ }
3298
+ _uploadEmissivePayload(e) {
3299
+ !e || !this.stages.pathTracer || (this.stages.pathTracer.setEmissiveTriangleData(e.rawData, e.emissiveCount, e.totalPower, e.bitTrailMap), e.lightBVHNodeData && this.stages.pathTracer.setLightBVHData(e.lightBVHNodeData, e.lightBVHNodeCount));
3300
+ }
3301
+ _refreshEmissiveForVisibility() {
3302
+ let e = this._sdf?.instanceTable;
3303
+ if (!e) return;
3304
+ let t = /* @__PURE__ */ new Set();
3305
+ for (let n = 0; n < e.count; n++) e.isSet[n] && !e.visible[n] && t.add(e.sourceMesh[n]);
3306
+ this._uploadEmissivePayload(this._sdf.rebuildEmissiveForVisibility(t));
3307
+ }
3308
+ setEmissiveTriangleSampling(e) {
3309
+ this._emissiveSamplingUserSet = !0, this.settings.set("enableEmissiveTriangleSampling", e);
3310
+ }
3311
+ hasEmissiveGeometry() {
3312
+ return (this._sdf?.emissiveTriangleBuilder?.emissiveTriangles?.length ?? this._sdf?.emissiveTriangleCount ?? 0) > 0;
3313
+ }
3314
+ setMeshVisibility(e, t) {
3315
+ this.stages.pathTracer?.updateMeshVisibility(e, t), this._refreshEmissiveForVisibility(), this.reset();
3316
+ }
3317
+ updateAllMeshVisibility() {
3318
+ this.stages.pathTracer?.updateAllMeshVisibility(), this._refreshEmissiveForVisibility(), this.reset();
3319
+ }
3320
+ getScene() {
3321
+ return this.meshScene || this.scene;
3322
+ }
3323
+ setMeshVisibilityByUuid(e, t) {
3324
+ let n = this.getScene()?.getObjectByProperty("uuid", e);
3325
+ if (!n) return null;
3326
+ let r = typeof t == "function" ? !!t(n.visible) : !!t;
3327
+ return n.visible = r, this.updateAllMeshVisibility(), r;
3328
+ }
3329
+ setTextureTransform(e, t, n) {
3330
+ this.stages.pathTracer?.materialData.updateTextureTransform(e, t, n), this.reset();
3331
+ }
3332
+ _displaySource(e) {
3333
+ let t = this.pipeline?.context, n = t && this.stages.compositor?.resolveLightSource(t);
3334
+ return n && n.key !== "pathtracer:color" && n.texture !== e.texture ? {
3335
+ texture: n.texture,
3336
+ source: n.key.split(":")[0]
3337
+ } : (this._denoiserInUse() && this._issues.record(b.OUTPUT_SOURCE_FALLBACK, "renderToBuffer: 'display' was asked for, but no denoiser has published a picture — returned the raw accumulation", {
3338
+ requested: "display",
3339
+ read: "accumulation"
3340
+ }), null);
3341
+ }
3342
+ async _readDisplaySource(e, t, n) {
3343
+ let r = this._displaySource(e);
3344
+ return r ? {
3345
+ data: await this._readTexture(r.texture, t, n),
3346
+ source: r.source
3347
+ } : {
3348
+ data: await this.renderer.readRenderTargetPixelsAsync(e, 0, 0, t, n, 0),
3349
+ source: "accumulation"
3350
+ };
3351
+ }
3352
+ _readbackPass() {
3353
+ return this._textureReadback ??= new Kt(this.renderer);
3354
+ }
3355
+ _readTexture(e, t, n) {
3356
+ return this._readbackPass().read(e, t, n);
3357
+ }
3358
+ async setTextureColorSpace(e, t) {
3359
+ if (!e?.isTexture) throw Error("setTextureColorSpace wants a three.js texture");
3360
+ let n = e.userData ??= {};
3361
+ n.__rayzeeOriginalColorSpace === void 0 && (n.__rayzeeOriginalColorSpace = e.colorSpace);
3362
+ let r = n.__rayzeeOriginalColorSpace;
3363
+ if (delete n.ocioColorSpace, delete n.__rayzeeColorSpaceChoice, t == null) e.colorSpace = r, delete n.__rayzeeOriginalColorSpace;
3364
+ else if (t === "srgb" || t === "linear") e.colorSpace = t === "srgb" ? Ie : Me, n.__rayzeeColorSpaceChoice = t;
3365
+ else {
3366
+ if (!this.color?.hasConfig) throw Error(`"${t}" needs a colour config loaded`);
3367
+ n.ocioColorSpace = t, e.colorSpace = Ie;
3368
+ }
3369
+ e.needsUpdate = !0, this.stages.pathTracer?.sdfs && await this.rebuildMaterials();
3370
+ }
3371
+ setColorManagement(e) {
3372
+ this.color?.dispose(), this.color = new e({ issues: this._issues }), x(this.color), this.renderer && this.color.attachRenderer(this.renderer);
3373
+ }
3374
+ async loadColorConfig(e = {}) {
3375
+ await this._leaveColorWorkingSpace();
3376
+ let t = w(this.renderer?.toneMapping), n = await this.color.loadConfig(e);
3377
+ return this.color.workingSpaceAdopted && await this.applyColorWorkingSpace(), (!(t?.source === "ocio" && w(this.renderer?.toneMapping) === t) || this.color.workingSpaceAdopted) && this.reset(), n;
3378
+ }
3379
+ async unloadColorConfig() {
3380
+ await this._leaveColorWorkingSpace(), this.color.unloadConfig(), this.reset();
3381
+ }
3382
+ async _leaveColorWorkingSpace() {
3383
+ this.color?.workingSpaceAdopted && (this.color.setWorkingSpace(null), await this.applyColorWorkingSpace());
3384
+ }
3385
+ async applyColorWorkingSpace() {
3386
+ let e = this.environmentManager?.getEnvironmentTexture?.(), t = !1;
3387
+ if (e && this.color?.hasConfig) try {
3388
+ t = this.color.convertTexturePixels(e);
3389
+ } catch (e) {
3390
+ $.warn(`environment colour conversion failed: ${e.message}`);
3391
+ }
3392
+ this.stages.pathTracer?.sdfs && (await this.rebuildMaterials(), this._uploadEmissivePayload(this._sdf?.rebuildEmissiveColors?.() ?? null)), t && await this.environmentManager?.buildEnvironmentCDF?.(), e?._isPhysicalSky && await this.environmentManager.generateProceduralSkyTexture(), this.environmentManager?.refreshSun?.(), this.reset();
3393
+ }
3394
+ async rebuildMaterials(e) {
3395
+ await this.ensureSceneResident(), await this.stages.pathTracer?.rebuildMaterials(e || this.meshScene), this.reset();
3396
+ }
3397
+ async _initRenderer() {
3398
+ if (ae((e) => this.dispatchEvent(e)), typeof navigator > "u" || !navigator.gpu) throw Error("WebGPU is not available — outside a browser, install one as navigator.gpu (for Node, the `webgpu` package)");
3399
+ let e = await navigator.gpu.requestAdapter({ powerPreference: "high-performance" });
3400
+ if (!e) throw Error("Failed to get WebGPU adapter");
3401
+ this.adapterInfo = Gn(e), this.adapterInfo.isSoftware && (this._issues.warn(b.ADAPTER_SOFTWARE, `software GPU adapter "${this.adapterInfo.description || this.adapterInfo.vendor}" — renders are correct but orders of magnitude slower than hardware`, { ...this.adapterInfo }), $.warn(`software GPU adapter — check app.adapterInfo.isSoftware. ${this.adapterInfo.description}`));
3402
+ let t = e.limits, n = { maxColorAttachmentBytesPerSample: 128 };
3403
+ for (let e of [
3404
+ "maxBufferSize",
3405
+ "maxStorageBufferBindingSize",
3406
+ "maxSampledTexturesPerShaderStage",
3407
+ "maxStorageTexturesPerShaderStage",
3408
+ "maxTextureArrayLayers",
3409
+ "maxTextureDimension2D",
3410
+ "maxComputeInvocationsPerWorkgroup",
3411
+ "maxComputeWorkgroupStorageSize",
3412
+ "maxComputeWorkgroupSizeX",
3413
+ "maxComputeWorkgroupSizeY",
3414
+ "maxComputeWorkgroupSizeZ"
3415
+ ]) {
3416
+ let r = t[e];
3417
+ r !== void 0 && (n[e] = r);
3418
+ }
3419
+ if (n.maxStorageBuffersPerShaderStage = Math.min(t.maxStorageBuffersPerShaderStage, 10), this.renderer = new Re({
3420
+ canvas: this.canvas,
3421
+ alpha: !0,
3422
+ powerPreference: "high-performance",
3423
+ requiredLimits: n
3424
+ }), await Vn(this.renderer, this._headless), !this.renderer.backend?.isWebGPUBackend) throw Error("WebGPU backend unavailable — three.js fell back to WebGL2, which cannot run the path tracer's compute kernels. Check GPU process flags and driver support.");
3425
+ let r = this.renderer.backend?.device;
3426
+ r?.lost && (this._gpuDevice = r, this._deviceLostHolder = { app: this }, Un(r, this._deviceLostHolder), r.onuncapturederror = (e) => $.error("WebGPU uncaptured error:", e.error)), Fe.setLTC(wt.init()), this.renderer.outputColorSpace = Ie, this.renderer.toneMapping = Oe, this.renderer.toneMappingExposure = 1, this.renderer.setPixelRatio(1), this.color.attachRenderer(this.renderer);
3427
+ }
3428
+ _initScenes() {
3429
+ this.scene = new vt(), this.meshScene = new vt(), this._sceneHelpers = new At();
3430
+ }
3431
+ _initAssetPipeline() {
3432
+ this._sdf = new ee({
3433
+ issues: this._issues,
3434
+ ...this._maxSceneBytes === void 0 ? {} : { maxSceneBytes: this._maxSceneBytes }
3435
+ }), this.assetLoader = new An(this.meshScene, this.camera, null, {
3436
+ issues: this._issues,
3437
+ areaLightIntensityScale: () => this.settings.get("areaLightIntensityScale")
3438
+ }), this.assetLoader.setRenderer(this.renderer), this.assetLoader.createFloorPlane();
3439
+ }
3440
+ _initPipeline() {
3441
+ this._createStages();
3442
+ let { clientWidth: e, clientHeight: t } = this.canvas;
3443
+ this.pipeline = new Ut(this.renderer, e || 1, t || 1, { issues: this._issues }), this.pipeline.addStage(this.stages.pathTracer);
3444
+ for (let e of this._extraStages) this.pipeline.addStage(e);
3445
+ this.pipeline.addStage(this.stages.compositor);
3446
+ let n = this.canvas.clientWidth || 1, r = this.canvas.clientHeight || 1;
3447
+ this._displayWidth = n, this._displayHeight = r, this._renderWidth = n, this._renderHeight = r, this.pipeline.setSize(n, r);
3448
+ }
3449
+ async _initManagers() {
3450
+ this.lightManager = new Ln(this.scene, this._sceneHelpers, this.stages.pathTracer, {
3451
+ onReset: () => this.reset(),
3452
+ onLightRemoved: (e) => this._lightRemoved(e)
3453
+ }), this.environmentManager = this.stages.pathTracer.environment, this.environmentManager.issues = this._issues, this.stages.pathTracer.issues = this._issues, this.environmentManager.callbacks.onLightingChanged = () => this.pipeline.eventBus.emit("pipeline:lightingChanged"), this.environmentManager.callbacks.onReset = () => this.reset();
3454
+ }
3455
+ _wireEvents() {
3456
+ this.settings.bind(this._settingsBindings()), this.renderer.toneMappingExposure = this.settings.get("exposure") ?? 1, this.onResize(), this.resizeHandler = () => this.onResize(), this._autoResize && this._addTrackedListener(window, "resize", this.resizeHandler), this._onAssetLoaded = async (e) => {
3457
+ if (!this._loadingInProgress && !(this._applyingSceneMetadata && e.texture)) {
3458
+ if (e.model) this._clearAppendedModels(), await this.loadSceneData({ pendingEnvironment: this._beginSceneMetadataEnvironment() });
3459
+ else if (e.texture) {
3460
+ let e = this.meshScene.environment;
3461
+ e && this.stages.pathTracer && await this.stages.pathTracer.environment.setEnvironmentMap(e), v();
3462
+ }
3463
+ this.pauseRendering = !1, this.reset();
3464
+ }
3465
+ }, this._addTrackedListener(this.assetLoader, "load", this._onAssetLoaded), this.pipeline.eventBus.on("pathtracer:compiling", ({ compiling: e }) => this.dispatchEvent({
3466
+ type: g.SHADERS_COMPILING,
3467
+ compiling: e
3468
+ }));
3469
+ }
3470
+ _createStages() {
3471
+ this.stages.pathTracer = new f(this.renderer, this.scene, this.camera, {
3472
+ hostMemoryGB: this._hostMemoryGB,
3473
+ sortMaterials: this.settings.get("wavefrontSortMaterials")
3474
+ }), this._extraStages = this._createExtraStages(), this.stages.compositor = new jt(this.renderer, {
3475
+ saturation: this.settings.get("saturation") ?? n.saturation,
3476
+ pathTracer: this.stages.pathTracer,
3477
+ displaySources: this._displaySources()
3478
+ });
3479
+ }
3480
+ _reconcileCompletion() {
3481
+ let e = this.stages.pathTracer;
3482
+ if (!e) return;
3483
+ let t = this.completion.isLimitReached(e, this.settings.get("renderLimitMode"), this.settings.get("renderTimeLimit"));
3484
+ t && !e.isComplete ? e.isComplete = !0 : !t && e.isComplete && (e.isComplete = !1, this.completion.resumeFromPause(), this._completionReopened(), this.dispatchEvent({ type: g.RENDER_RESET }), this.wake());
3485
+ }
3486
+ _forwardEvents(e, t) {
3487
+ if (e) for (let n of t) this._addTrackedListener(e, n, (e) => this.dispatchEvent(e));
3488
+ }
3489
+ _createCamera() {
3490
+ let e = new Pn(60, this.canvas.clientWidth / this.canvas.clientHeight || 1, .01, 1e3);
3491
+ return e.position.set(0, 0, 5), e;
3492
+ }
3493
+ _createExtraStages() {
3494
+ return [];
3495
+ }
3496
+ _displaySources() {
3497
+ return [];
3498
+ }
3499
+ _settingsBindings() {
3500
+ return {
3501
+ stages: this.stages,
3502
+ resetCallback: () => this.reset(),
3503
+ reconcileCompletion: () => this._reconcileCompletion(),
3504
+ applyExposure: (e) => {
3505
+ this.renderer.toneMappingExposure = e;
3506
+ }
3507
+ };
3508
+ }
3509
+ _beginFrame() {}
3510
+ _beforeTrace() {}
3511
+ _holdTrace() {
3512
+ return !1;
3513
+ }
3514
+ _afterTrace() {}
3515
+ _renderCompleted() {}
3516
+ _renderHelperOverlay() {
3517
+ this.scene.updateMatrixWorld();
3518
+ }
3519
+ _beforeReset() {}
3520
+ _afterReset() {}
3521
+ _dropDisplay() {}
3522
+ _releaseSceneState() {}
3523
+ _modelReplaced() {}
3524
+ _modelAnnounced() {}
3525
+ _sceneRebuilt() {}
3526
+ _sceneBoundsChanged() {}
3527
+ _notePlacementsMoving() {}
3528
+ _lightRemoved() {}
3529
+ _renderSizeChanged() {}
3530
+ _completionReopened() {}
3531
+ async _finalDenoise() {
3532
+ return !1;
3533
+ }
3534
+ _denoiserInUse() {
3535
+ return !1;
3536
+ }
3537
+ _displayCanvas() {
3538
+ return null;
3539
+ }
3540
+ _registerVRAM() {}
3541
+ _canvasResources() {
3542
+ return [];
3543
+ }
3544
+ _deterministicSnapshot() {
3545
+ return null;
3546
+ }
3547
+ _setDeterministicExtras() {}
3548
+ _disposeExtensions() {}
3549
+ };
3550
+ //#endregion
3551
+ export { Mt as _, tn as a, J as c, K as d, Qt as f, It as g, Lt as h, Pn as i, $t as l, Rt as m, Gn as n, Y as o, Ut as p, Ln as r, U as s, Kn as t, Zt as u };