rayzee 11.9.0 → 11.10.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.
- package/dist/{ArchiveImporter-BJxszU_k.js → ArchiveImporter-B4Qz5BGT.js} +3 -3
- package/dist/{BidirectionalIntegrator-DWg66vAd.js → BidirectionalIntegrator-ZrCN3uyc.js} +2 -2
- package/dist/{NeuralRetouch-BD9E-Yht.js → NeuralRetouch-BtzPRZSB.js} +1 -1
- package/dist/{NeuralSuperRes-C8Mf3tJX.js → NeuralSuperRes-B2V-vlHN.js} +1 -1
- package/dist/{PathTracer-DeE9UJ1n.js → PathTracer-CuO_bS6Z.js} +1 -1
- package/dist/{PhysicalSky-cKy75-oR.js → PhysicalSky-NdPIyVqP.js} +1 -1
- package/dist/{RayzeeRenderer-CzLyBA3G.js → RayzeeRenderer-BOJsV6Sj.js} +3 -3
- package/dist/{SceneMetadata-C17UfOEp.js → SceneMetadata-DiQpoDtm.js} +1 -1
- package/dist/addons/archives.es.js +1 -1
- package/dist/addons/bidirectional.es.js +1 -1
- package/dist/addons/physical-sky.es.js +1 -1
- package/dist/rayzee-core.es.js +4 -4
- package/dist/rayzee.es.js +11 -11
- package/dist/rayzee.umd.js +1 -1
- package/dist/{sceneCachePolicy-ywbGKHD3.js → sceneCachePolicy-EwLlPi01.js} +1 -1
- package/package.json +1 -1
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { n as e } from "./BidirectionalIntegrator-
|
|
2
|
-
import { A as t, T as n, at as r, n as i, r as a, v as o, x as s } from "./sceneCachePolicy-
|
|
1
|
+
import { n as e } from "./BidirectionalIntegrator-ZrCN3uyc.js";
|
|
2
|
+
import { A as t, T as n, at as r, n as i, r as a, v as o, x as s } from "./sceneCachePolicy-EwLlPi01.js";
|
|
3
3
|
import { n as c, r as l, t as u } from "./EngineIssues-CfJiBaNj.js";
|
|
4
4
|
import { r as d } from "./shared-BGBcSxBQ.js";
|
|
5
5
|
import { i as f, n as p, o as m, r as h } from "./identity-C1cLD1C0.js";
|
|
6
|
-
import { a as g, s as _, t as v } from "./SceneMetadata-
|
|
6
|
+
import { a as g, s as _, t as v } from "./SceneMetadata-DiQpoDtm.js";
|
|
7
7
|
import { n as y, t as b } from "./ZipReader-gDSWr0I5.js";
|
|
8
8
|
import { AnimationClip as x, BooleanKeyframeTrack as S, BoxGeometry as C, BufferAttribute as w, BufferGeometry as T, CapsuleGeometry as ee, ClampToEdgeWrapping as E, Color as D, ConeGeometry as te, CylinderGeometry as ne, DataTexture as O, DirectionalLight as re, DoubleSide as k, EquirectangularReflectionMapping as ie, Euler as ae, Float32BufferAttribute as A, FloatType as oe, FrontSide as se, Group as ce, InstancedBufferAttribute as le, InstancedMesh as ue, LinearFilter as de, LoadingManager as fe, MaterialLoader as pe, Matrix4 as j, Mesh as me, MeshPhysicalMaterial as M, MirroredRepeatWrapping as he, NoColorSpace as ge, NumberKeyframeTrack as _e, Object3D as ve, OrthographicCamera as ye, PerspectiveCamera as be, PlaneGeometry as xe, PointLight as Se, Quaternion as Ce, QuaternionKeyframeTrack as we, RGBAFormat as Te, RectAreaLight as Ee, RepeatWrapping as De, SRGBColorSpace as N, SphereGeometry as Oe, SpotLight as ke, Texture as Ae, Uint32BufferAttribute as P, Vector3 as F, VectorKeyframeTrack as je } from "three";
|
|
9
9
|
import { HDRLoader as Me } from "three/addons/loaders/HDRLoader.js";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { $t as e, Bt as t, F as n, Ft as r, I as i, J as a, K as o, L as s, Mt as c, R as l, U as u, X as d, Y as f, Yt as p, Z as m, an as h, c as ee, ct as te, dt as ne, et as re, ft as g, i as _, j as ie, jt as ae, k as oe, lt as se, on as ce, q as v, r as le, tn as ue, wt as de, y as fe } from "./SolarLimb-DRYy8tln.js";
|
|
2
|
-
import { A as pe, C as y, Ct as b, D as me, Dt as he, E as x, Et as S, G as C, K as ge, L as w, M as T, N as E, O as _e, P as ve, R as ye, S as be, St as D, T as xe, Tt as Se, U as O, X as k, Y as A, Z as j, _ as M, a as Ce, b as N, c as we, ct as P, d as Te, f as F, g as Ee, h as De, j as Oe, k as ke, l as Ae, m as je, o as Me, ot as I, p as Ne, q as Pe, s as Fe, st as Ie, t as Le, u as Re, v as ze, w as Be, wt as Ve, x as He, y as L } from "./PathTracer-
|
|
3
|
-
import { W as Ue } from "./sceneCachePolicy-
|
|
2
|
+
import { A as pe, C as y, Ct as b, D as me, Dt as he, E as x, Et as S, G as C, K as ge, L as w, M as T, N as E, O as _e, P as ve, R as ye, S as be, St as D, T as xe, Tt as Se, U as O, X as k, Y as A, Z as j, _ as M, a as Ce, b as N, c as we, ct as P, d as Te, f as F, g as Ee, h as De, j as Oe, k as ke, l as Ae, m as je, o as Me, ot as I, p as Ne, q as Pe, s as Fe, st as Ie, t as Le, u as Re, v as ze, w as Be, wt as Ve, x as He, y as L } from "./PathTracer-CuO_bS6Z.js";
|
|
3
|
+
import { W as Ue } from "./sceneCachePolicy-EwLlPi01.js";
|
|
4
4
|
import { r as We } from "./BufferLayout-Bzgccg1o.js";
|
|
5
5
|
import { Break as Ge, Fn as R, If as z, Loop as Ke, Return as B, abs as V, atomicAdd as qe, atomicFunc as Je, atomicLoad as Ye, atomicStore as Xe, bool as Ze, cos as Qe, cross as $e, dot as H, exp2 as et, float as U, floor as tt, instanceIndex as nt, int as W, ivec2 as rt, ivec3 as it, length as at, localId as ot, log2 as st, max as G, min as ct, mix as lt, normalize as ut, sampler as dt, select as K, sin as ft, sqrt as pt, storage as mt, texture as ht, uint as q, uniform as J, uniformArray as gt, vec2 as _t, vec3 as Y, vec4 as vt, workgroupId as yt } from "three/tsl";
|
|
6
6
|
import { DataTexture as bt, FloatType as xt, RedFormat as St, Vector3 as Ct } from "three";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as e } from "./BidirectionalIntegrator-
|
|
1
|
+
import { n as e } from "./BidirectionalIntegrator-ZrCN3uyc.js";
|
|
2
2
|
import { r as t } from "./Logger-dDDGj9Av.js";
|
|
3
3
|
import { n } from "./AssetConfig-DSEntE65.js";
|
|
4
4
|
import { t as r } from "./ToneMapGPU-4GPwoG_c.js";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as e } from "./BidirectionalIntegrator-
|
|
1
|
+
import { n as e } from "./BidirectionalIntegrator-ZrCN3uyc.js";
|
|
2
2
|
import { t } from "./EngineEvents-CLckhYbL.js";
|
|
3
3
|
import { r as n } from "./Logger-dDDGj9Av.js";
|
|
4
4
|
import { n as r } from "./AssetConfig-DSEntE65.js";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { $ as e, $t as t, A as n, At as r, B as i, Bt as a, C as o, Ct as s, D as c, Dt as l, E as u, Et as d, G as f, Gt as p, H as m, Ht as h, It as g, J as _, Jt as v, K as y, Kt as b, Lt as x, M as S, Mt as C, N as w, Nt as T, O as E, Ot as D, P as O, Q as ee, Qt as k, Rt as te, S as ne, St as re, T as ie, Tt as A, Ut as ae, V as oe, Vt as se, W as ce, Wt as le, X as ue, Xt as de, Y as fe, Yt as pe, Z as me, Zt as he, _ as ge, _t as _e, a as ve, an as ye, at as be, b as xe, bt as Se, c as Ce, ct as we, d as Te, dt as Ee, en as De, f as Oe, ft as ke, g as Ae, gt as je, h as Me, ht as Ne, i as Pe, in as Fe, it as Ie, j as Le, jt as Re, k as ze, kt as Be, l as Ve, lt as He, m as Ue, mt as We, n as Ge, nn as Ke, nt as qe, o as Je, on as Ye, ot as Xe, p as Ze, pt as Qe, q as $e, qt as et, r as tt, rn as nt, s as rt, st as it, t as at, tn as ot, tt as st, u as ct, ut as lt, v as ut, vt as dt, w as ft, wt as pt, x as mt, xt as ht, yt as gt, z as _t, zt as vt } from "./SolarLimb-DRYy8tln.js";
|
|
2
|
-
import { B as yt, D as bt, E as xt, F as St, G as Ct, H as wt, L as Tt, M as Et, N as Dt, P as Ot, R as kt, S as At, U as jt, V as Mt, W as Nt, X as Pt, Z as Ft, _ as It, a as Lt, at as Rt, b as zt, c as Bt, f as j, g as Vt, h as Ht, i as Ut, it as Wt, j as M, k as Gt, m as Kt, p as qt, q as Jt, r as Yt, s as Xt, t as Zt, w as Qt, z as $t } from "./sceneCachePolicy-
|
|
2
|
+
import { B as yt, D as bt, E as xt, F as St, G as Ct, H as wt, L as Tt, M as Et, N as Dt, P as Ot, R as kt, S as At, U as jt, V as Mt, W as Nt, X as Pt, Z as Ft, _ as It, a as Lt, at as Rt, b as zt, c as Bt, f as j, g as Vt, h as Ht, i as Ut, it as Wt, j as M, k as Gt, m as Kt, p as qt, q as Jt, r as Yt, s as Xt, t as Zt, w as Qt, z as $t } from "./sceneCachePolicy-EwLlPi01.js";
|
|
3
3
|
import { i as N, o as en, r as tn } from "./Logger-dDDGj9Av.js";
|
|
4
4
|
import { _ as nn, a as rn, b as an, c as on, d as sn, f as P, g as cn, h as ln, i as un, l as F, m as dn, n as fn, o as pn, p as mn, r as hn, s as gn, t as _n, u as vn, v as yn } from "./BufferLayout-Bzgccg1o.js";
|
|
5
5
|
import { n as bn, t as xn } from "./EngineIssues-CfJiBaNj.js";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as e } from "./BidirectionalIntegrator-
|
|
1
|
+
import { n as e } from "./BidirectionalIntegrator-ZrCN3uyc.js";
|
|
2
2
|
import { an as t, dt as n, i as r } from "./SolarLimb-DRYy8tln.js";
|
|
3
3
|
import { r as i } from "./WorkingMatrix-C6y233hT.js";
|
|
4
4
|
import { StorageInstancedBufferAttribute as a } from "three/webgpu";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { dt as e } from "./SolarLimb-DRYy8tln.js";
|
|
2
|
-
import { Mt as t, Nt as n, Ot as r, bt as i, dt as a, ft as o, i as s, jt as c, kt as l, lt as u, n as d, r as f, ut as p, vt as ee, xt as m } from "./PathTracer-
|
|
2
|
+
import { Mt as t, Nt as n, Ot as r, bt as i, dt as a, ft as o, i as s, jt as c, kt as l, lt as u, n as d, r as f, ut as p, vt as ee, xt as m } from "./PathTracer-CuO_bS6Z.js";
|
|
3
3
|
import { n as h, t as g } from "./EngineEvents-CLckhYbL.js";
|
|
4
|
-
import { $ as te, C as ne, G as _, M as re, Q as ie, T as v, W as ae, at as y, d as oe, et as se, f as ce, l as le, nt as b, ot as ue, r as de, rt as fe, tt as pe, u as me, v as he, x as ge } from "./sceneCachePolicy-
|
|
4
|
+
import { $ as te, C as ne, G as _, M as re, Q as ie, T as v, W as ae, at as y, d as oe, et as se, f as ce, l as le, nt as b, ot as ue, r as de, rt as fe, tt as pe, u as me, v as he, x as ge } from "./sceneCachePolicy-EwLlPi01.js";
|
|
5
5
|
import { i as x, r as S } from "./Logger-dDDGj9Av.js";
|
|
6
6
|
import { f as _e, r as ve } from "./BufferLayout-Bzgccg1o.js";
|
|
7
7
|
import { i as ye, n as C, t as be } from "./EngineIssues-CfJiBaNj.js";
|
|
@@ -11,7 +11,7 @@ import { i as w, r as we, t as T } from "./ActiveColor-YvuQq44O.js";
|
|
|
11
11
|
import { n as E, r as Te } from "./AssetConfig-DSEntE65.js";
|
|
12
12
|
import { d as Ee, l as De, m as Oe, p as ke, t as Ae, u as D } from "./ViewTransforms-CYN7bq2w.js";
|
|
13
13
|
import { i as O, n as je, r as Me } from "./identity-C1cLD1C0.js";
|
|
14
|
-
import { c as Ne, i as Pe, l as Fe, o as Ie, r as Le, t as Re } from "./SceneMetadata-
|
|
14
|
+
import { c as Ne, i as Pe, l as Fe, o as Ie, r as Le, t as Re } from "./SceneMetadata-DiQpoDtm.js";
|
|
15
15
|
import { t as ze } from "./ToneMapGPU-4GPwoG_c.js";
|
|
16
16
|
import { LinearSRGBColorSpace as Be, MeshBasicNodeMaterial as Ve, QuadMesh as He, RectAreaLightNode as Ue, SRGBColorSpace as We, TextureNode as Ge, WebGPURenderer as Ke } from "three/webgpu";
|
|
17
17
|
import { Fn as qe, If as Je, cubeTexture as Ye, dot as Xe, float as k, int as A, mix as j, screenUV as Ze, select as M, storage as Qe, texture as $e, uint as et, uniform as N, uv as P, vec3 as F, vec4 as tt } from "three/tsl";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { x as e } from "./sceneCachePolicy-
|
|
1
|
+
import { x as e } from "./sceneCachePolicy-EwLlPi01.js";
|
|
2
2
|
import { DataTexture as t, LoaderUtils as n, RGBAFormat as r, UnsignedByteType as i } from "three";
|
|
3
3
|
//#region src/Processor/archiveFormats.js
|
|
4
4
|
var a = Object.freeze({
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { n as e, t } from "../ZipReader-gDSWr0I5.js";
|
|
2
|
-
import { n, t as r } from "../ArchiveImporter-
|
|
2
|
+
import { n, t as r } from "../ArchiveImporter-B4Qz5BGT.js";
|
|
3
3
|
export { r as ARCHIVE_ELEMENT_PROMPT_BYTES, n as ArchiveImporter, t as openZip, e as readZipDirectory };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as e } from "../BidirectionalIntegrator-
|
|
1
|
+
import { t as e } from "../BidirectionalIntegrator-ZrCN3uyc.js";
|
|
2
2
|
export { e as BidirectionalIntegrator };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as e } from "../PhysicalSky-
|
|
1
|
+
import { t as e } from "../PhysicalSky-NdPIyVqP.js";
|
|
2
2
|
export { e as PhysicalSky };
|
package/dist/rayzee-core.es.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import "./SolarLimb-DRYy8tln.js";
|
|
2
|
-
import { a as e, n as t, o as n, r, t as i } from "./RayzeeRenderer-
|
|
3
|
-
import { Ot as a, mt as o } from "./PathTracer-
|
|
2
|
+
import { a as e, n as t, o as n, r, t as i } from "./RayzeeRenderer-BOJsV6Sj.js";
|
|
3
|
+
import { Ot as a, mt as o } from "./PathTracer-CuO_bS6Z.js";
|
|
4
4
|
import { n as s, t as c } from "./EngineEvents-CLckhYbL.js";
|
|
5
|
-
import { G as l, q as u, r as d, x as f, y as p } from "./sceneCachePolicy-
|
|
5
|
+
import { G as l, q as u, r as d, x as f, y as p } from "./sceneCachePolicy-EwLlPi01.js";
|
|
6
6
|
import { i as m, n as h, r as g, t as _ } from "./Logger-dDDGj9Av.js";
|
|
7
7
|
import { f as v } from "./BufferLayout-Bzgccg1o.js";
|
|
8
8
|
import { i as y, n as b, r as x, t as S } from "./EngineIssues-CfJiBaNj.js";
|
|
9
9
|
import { n as C, t as w } from "./AssetConfig-DSEntE65.js";
|
|
10
10
|
import { d as T, p as E, t as D, u as O } from "./ViewTransforms-CYN7bq2w.js";
|
|
11
|
-
import { l as k, s as A } from "./SceneMetadata-
|
|
11
|
+
import { l as k, s as A } from "./SceneMetadata-DiQpoDtm.js";
|
|
12
12
|
export { A as ARCHIVE_FORMATS, D as DEFAULT_VIEW, l as ENGINE_DEFAULTS, c as EngineEvents, S as EngineIssueError, b as ISSUE_CODES, x as ISSUE_SEVERITY, y as IssueLog, s as LEGACY_EVENT_NAMES, _ as LOG_LEVELS, r as LightManager, h as Logger, u as MATERIAL_DEFAULTS, a as MAX_RESERVABLE_RENDER_SIZE, i as RayzeeRenderer, e as RenderSettings, n as SETTING_SOURCE, o as SKY_DEFAULTS, v as TRIANGLE_DATA_LAYOUT, d as VERSION, w as configureAssets, p as configurePlatform, g as createLogger, t as describeAdapter, m as fmt, C as getAssetConfig, f as getPlatform, O as getViewTransform, T as listViewTransforms, k as localFolder, E as onRegistryChange };
|
package/dist/rayzee.es.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { t as e } from "./BidirectionalIntegrator-
|
|
1
|
+
import { t as e } from "./BidirectionalIntegrator-ZrCN3uyc.js";
|
|
2
2
|
import { Ft as t, Pt as n, Xt as r, en as i, rn as a, rt as o, tn as s, wt as c } from "./SolarLimb-DRYy8tln.js";
|
|
3
|
-
import { _ as l, a as u, c as d, d as f, f as p, g as m, h, i as g, l as _, m as v, n as y, o as b, p as x, r as S, s as C, t as w, u as T } from "./RayzeeRenderer-
|
|
4
|
-
import { $ as E, At as D, B as O, F as k, H as ee, I as te, J as ne, Mt as A, Nt as j, Ot as re, Q as M, V as ie, W as ae, _t as oe, at as se, bt as ce, dt as le, et as N, gt as ue, ht as de, it as fe, kt as pe, mt as me, nt as he, pt as ge, rt as _e, tt as ve, xt as ye, yt as be, z as xe } from "./PathTracer-
|
|
3
|
+
import { _ as l, a as u, c as d, d as f, f as p, g as m, h, i as g, l as _, m as v, n as y, o as b, p as x, r as S, s as C, t as w, u as T } from "./RayzeeRenderer-BOJsV6Sj.js";
|
|
4
|
+
import { $ as E, At as D, B as O, F as k, H as ee, I as te, J as ne, Mt as A, Nt as j, Ot as re, Q as M, V as ie, W as ae, _t as oe, at as se, bt as ce, dt as le, et as N, gt as ue, ht as de, it as fe, kt as pe, mt as me, nt as he, pt as ge, rt as _e, tt as ve, xt as ye, yt as be, z as xe } from "./PathTracer-CuO_bS6Z.js";
|
|
5
5
|
import { n as Se, t as P } from "./EngineEvents-CLckhYbL.js";
|
|
6
|
-
import { D as Ce, G as we, J as Te, K as Ee, O as De, W as Oe, Y as ke, a as Ae, c as je, et as Me, i as Ne, m as Pe, ot as Fe, p as Ie, q as Le, r as Re, tt as ze, x as Be, y as Ve } from "./sceneCachePolicy-
|
|
6
|
+
import { D as Ce, G as we, J as Te, K as Ee, O as De, W as Oe, Y as ke, a as Ae, c as je, et as Me, i as Ne, m as Pe, ot as Fe, p as Ie, q as Le, r as Re, tt as ze, x as Be, y as Ve } from "./sceneCachePolicy-EwLlPi01.js";
|
|
7
7
|
import { i as He, n as Ue, r as We, t as Ge } from "./Logger-dDDGj9Av.js";
|
|
8
8
|
import { f as Ke, r as qe } from "./BufferLayout-Bzgccg1o.js";
|
|
9
9
|
import { i as Je, n as Ye, r as Xe, t as Ze } from "./EngineIssues-CfJiBaNj.js";
|
|
@@ -13,14 +13,14 @@ import { i as tt, r as nt, t as rt } from "./ActiveColor-YvuQq44O.js";
|
|
|
13
13
|
import { n as it, t as at } from "./AssetConfig-DSEntE65.js";
|
|
14
14
|
import { a as ot, d as st, g as ct, i as lt, l as ut, o as dt, p as ft, r as pt, s as mt, t as ht, u as gt } from "./ViewTransforms-CYN7bq2w.js";
|
|
15
15
|
import { a as _t, i as vt, n as yt, r as bt } from "./identity-C1cLD1C0.js";
|
|
16
|
-
import { l as xt, n as St, s as Ct, t as wt } from "./SceneMetadata-
|
|
16
|
+
import { l as xt, n as St, s as Ct, t as wt } from "./SceneMetadata-DiQpoDtm.js";
|
|
17
17
|
import { t as Tt } from "./ToneMapGPU-4GPwoG_c.js";
|
|
18
18
|
import { t as Et } from "./FileFormats-sPGJeCRc.js";
|
|
19
19
|
import { A as Dt, C as Ot, D as kt, E as At, O as jt, S as Mt, T as Nt, _ as Pt, a as Ft, b as It, c as Lt, d as Rt, f as zt, g as Bt, h as Vt, i as Ht, k as Ut, l as Wt, m as Gt, n as Kt, o as qt, p as Jt, r as Yt, s as Xt, t as Zt, u as Qt, v as $t, w as en, x as tn, y as nn } from "./ColorManagement-B_HjAiy2.js";
|
|
20
20
|
import { c as rn, l as an, n as on, o as sn, t as cn } from "./openStorage-CdyVjmps.js";
|
|
21
21
|
import { n as ln, t as un } from "./ZipReader-gDSWr0I5.js";
|
|
22
|
-
import { i as dn, n as fn, r as pn } from "./NeuralSuperRes-
|
|
23
|
-
import { i as mn, n as hn, r as gn } from "./NeuralRetouch-
|
|
22
|
+
import { i as dn, n as fn, r as pn } from "./NeuralSuperRes-B2V-vlHN.js";
|
|
23
|
+
import { i as mn, n as hn, r as gn } from "./NeuralRetouch-BtzPRZSB.js";
|
|
24
24
|
import { ExternalTexture as _n, MeshBasicNodeMaterial as vn, QuadMesh as yn, ReadbackBuffer as bn, RenderTarget as xn, StorageTexture as Sn, TextureNode as Cn, WebGPURenderer as wn } from "three/webgpu";
|
|
25
25
|
import { Fn as Tn, If as F, Loop as En, Return as Dn, atan as On, atomicAdd as kn, atomicLoad as An, atomicStore as jn, attributeArray as Mn, dot as I, exp as Nn, exp2 as Pn, float as L, floatBitsToUint as Fn, floor as In, fract as Ln, int as R, ivec2 as Rn, localId as z, log2 as zn, max as B, min as Bn, mix as V, normalize as Vn, pow as Hn, round as Un, saturate as H, select as U, smoothstep as Wn, sqrt as Gn, storage as Kn, textureLoad as W, textureStore as G, toneMappingExposure as qn, uint as K, uniform as q, uvec2 as Jn, uvec4 as Yn, vec2 as J, vec3 as Xn, vec4 as Y, workgroupArray as Zn, workgroupBarrier as Qn, workgroupId as X } from "three/tsl";
|
|
26
26
|
import { ACESFilmicToneMapping as $n, AddEquation as er, AnimationMixer as tr, Box2 as nr, Box3 as rr, ClampToEdgeWrapping as ir, Color as ar, Controls as or, CustomBlending as sr, DataArrayTexture as cr, DataTexture as lr, EventDispatcher as ur, FloatType as dr, HalfFloatType as fr, InterpolateSmooth as pr, LinearFilter as mr, LoopOnce as hr, LoopRepeat as gr, MathUtils as _r, Matrix3 as vr, Matrix4 as yr, Mesh as br, MeshBasicMaterial as xr, NearestFilter as Z, NoColorSpace as Sr, NumberKeyframeTrack as Cr, OneFactor as wr, OrthographicCamera as Tr, PerspectiveCamera as Er, PropertyBinding as Dr, Quaternion as Or, RGBAFormat as kr, Raycaster as Ar, RedIntegerFormat as jr, SRGBColorSpace as Mr, Scene as Nr, SphereGeometry as Pr, Timer as Fr, UnsignedByteType as Ir, UnsignedIntType as Lr, Vector2 as Rr, Vector3 as Q, Vector4 as zr, VectorKeyframeTrack as Br } from "three";
|
|
@@ -4457,9 +4457,9 @@ var Ts = {
|
|
|
4457
4457
|
}
|
|
4458
4458
|
this._neuralPostBusy = !0, this.dispatchEvent({ type: P.UPSCALING_START });
|
|
4459
4459
|
try {
|
|
4460
|
-
let i = await import("./NeuralSuperRes-
|
|
4460
|
+
let i = await import("./NeuralSuperRes-B2V-vlHN.js").then((e) => e.t);
|
|
4461
4461
|
this._superResModule = i;
|
|
4462
|
-
let a = n ? await import("./NeuralRetouch-
|
|
4462
|
+
let a = n ? await import("./NeuralRetouch-BtzPRZSB.js").then((e) => e.t) : null, o = this.denoiser?._outTexSize, s = (o?.width ?? 0) * (o?.height ?? 0), c = n && s <= a.RETOUCH_MAX_PIXELS;
|
|
4463
4463
|
if (n && !c && (Ds.warn(`Neural rendering skipped: the render is ${(s / 1e6).toFixed(1)} MP, above the ${(a.RETOUCH_MAX_PIXELS / 1e6).toFixed(1)} MP the pass survives.` + (t ? " The upscale still ran." : "")), this._releaseNeuralRetouch()), !t && !c) {
|
|
4464
4464
|
r && !this._postCancelled && await this.upscaler.start();
|
|
4465
4465
|
return;
|
|
@@ -5452,7 +5452,7 @@ var fc = We("engine"), pc = class extends w {
|
|
|
5452
5452
|
}), this.cameraManager.camera;
|
|
5453
5453
|
}
|
|
5454
5454
|
_initAssetPipeline() {
|
|
5455
|
-
super._initAssetPipeline(), this.assetLoader.controls = this.cameraManager.controls, this.assetLoader.registerFormat(...Et), this.assetLoader.setArchiveImporterLoader(() => import("./ArchiveImporter-
|
|
5455
|
+
super._initAssetPipeline(), this.assetLoader.controls = this.cameraManager.controls, this.assetLoader.registerFormat(...Et), this.assetLoader.setArchiveImporterLoader(() => import("./ArchiveImporter-B4Qz5BGT.js").then((e) => e.r).then((e) => new e.ArchiveImporter(this.assetLoader)), Ct);
|
|
5456
5456
|
let e = () => {
|
|
5457
5457
|
this.needsReset = !0, this.stages.pathTracer?.enterInteractionMode(), this.wake();
|
|
5458
5458
|
};
|
|
@@ -5475,7 +5475,7 @@ var fc = We("engine"), pc = class extends w {
|
|
|
5475
5475
|
super._initPipeline(), this.pipeline.eventBus.on("pathtracer:interactionStart", () => this._requestRenderScale(this._interactionRenderScale())), this.pipeline.eventBus.on("pathtracer:interactionEnd", () => this._applyRenderScale(1));
|
|
5476
5476
|
}
|
|
5477
5477
|
async _initManagers() {
|
|
5478
|
-
await super._initManagers(), this.environmentManager.setProceduralSkyLoader(() => import("./PhysicalSky-
|
|
5478
|
+
await super._initManagers(), this.environmentManager.setProceduralSkyLoader(() => import("./PhysicalSky-NdPIyVqP.js").then((e) => e.n).then((e) => e.PhysicalSky)), this.stages.pathTracer.registerIntegrator(["bidirectional", "vcm"], (t) => new e(t)), this.stages.pathTracer.requestOutput("gBuffer"), this.interactionManager = new qa({
|
|
5479
5479
|
scene: this.meshScene,
|
|
5480
5480
|
camera: this.camera,
|
|
5481
5481
|
canvas: this.canvas,
|
package/dist/rayzee.umd.js
CHANGED
|
@@ -244,7 +244,7 @@ fn rayzee_encode( mapped: vec3<f32>, mode: u32 ) -> vec3<f32> {
|
|
|
244
244
|
fn rayzee_to_u8( srgb: vec3<f32> ) -> vec3<u32> {
|
|
245
245
|
return vec3<u32>( clamp( round( srgb * 255.0 + vec3<f32>( 0.5 ) ), vec3<f32>( 0.0 ), vec3<f32>( 255.0 ) ) );
|
|
246
246
|
}
|
|
247
|
-
`,bindings:n}}function ss(){us.length=0,us.push(...qo),ds.clear();for(let e of us)ds.set(e.id,e);Yo()}var cs,ls,us,ds,fs,ps,ms,hs,gs,_s=g((()=>{Jo(),cs=200,ls=12,us=[...qo],ds=new Map(us.map(e=>[e.id,e])),fs=1,ps=new Set,ms=ds,hs=r.NoToneMapping,gs=r.AgXToneMapping}));_s();var vs=e=>(t,n,r,i,a)=>e(t>0?t:0,n>0?n:0,r>0?r:0,i,a),ys=new Map;function bs(){ys.clear();for(let e of ms.values())ys.set(e.id,vs(e.cpu))}bs(),Zo(bs);function xs(e){return Qo(e)?.outputEncoded===!0}function Ss(e){return e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055}function Cs(e,t){let n=Qo(t);return n?n.appliesExposure?e:1:t===r.NoToneMapping?1:e}function ws(e,t,n){return Cs(e,n)/Cs(t,n)}function Ts(e,t,n){return e+(t-e)*(1-Math.min(Math.max(n,0),1))}var Es=.2126,Ds=.7152,Os=.0722;function ks(e,t){if(t===1)return;let n=e[0]*Es+e[1]*Ds+e[2]*Os;e[0]=n+(e[0]-n)*t,e[1]=n+(e[1]-n)*t,e[2]=n+(e[2]-n)*t}function As(e,{exposure:t,toneMapping:n,saturation:i=1,preserveAlpha:a=!1,pixelGain:o=null}){let s=ys.get(n)??ys.get(r.NoToneMapping),c=Cs(t,n),l=xs(n),u=new Uint8ClampedArray(e.length),d=[0,0,0],f=Math.log2(t);for(let t=0;t<e.length;t+=4){let n=c;if(o){let r=1;if(o.fn){let n=t>>2,i=n%o.width,a=(n-i)/o.width,s=e[t]*.2126+e[t+1]*.7152+e[t+2]*.0722;r=o.fn((i+.5)/o.width,(a+.5)/o.height,s,f)}o.backdrop>0&&(r=Ts(r,o.backdrop,e[t+3])),n*=r}d[0]=e[t]*n,d[1]=e[t+1]*n,d[2]=e[t+2]*n,ks(d,i),s(d[0],d[1],d[2],1,d),l?(u[t]=d[0]*255+.5,u[t+1]=d[1]*255+.5,u[t+2]=d[2]*255+.5):(u[t]=Ss(d[0])*255+.5,u[t+1]=Ss(d[1])*255+.5,u[t+2]=Ss(d[2])*255+.5),u[t+3]=a?e[t+3]*255+.5:255}return u}It(),tn(),on(),ke(),Pr();var js=ve(`textures`),Ms={MAX_BUFFER_MEMORY:1024*1024*1024,MAX_TEXTURE_MEMORY:2048*1024*1024,CLEANUP_THRESHOLD:.8,STREAM_BATCH_SIZE:4},Ns=8*2**20,Ps=16,Fs=4,Is=8192*8192,Ls={busy:0,waiting:[]};async function Rs(){return Ls.busy<Math.max(1,Dr()-1)?Ls.busy++:await new Promise(e=>Ls.waiting.push(e)),()=>{let e=Ls.waiting.shift();e?e():Ls.busy--}}var zs={toSRGB:null,toLinear:null};function Bs(e){if(!zs[e]){let t=new Uint8Array(256);for(let n=0;n<256;n++){let r=n/255,i=e===`toSRGB`?Ss(r):r<=.04045?r/12.92:((r+.055)/1.055)**2.4;t[n]=Math.max(0,Math.min(255,Math.round(i*255)))}zs[e]=t}return zs[e]}var Vs=class{constructor(){this.canvasContextPairs=[],this.maxPoolSize=$t.CANVAS_POOL_SIZE}getCanvasWithContext(e,t,n=!1,r={}){let i={willReadFrequently:!0,alpha:!0,desynchronized:!0,...r},a=this.canvasContextPairs.pop();if(!a){let r;r=n&&typeof OffscreenCanvas<`u`?new OffscreenCanvas(e,t):document.createElement(`canvas`);let o=r.getContext(`2d`,i);a={canvas:r,context:o}}return a.canvas.width=e,a.canvas.height=t,a}releaseCanvasWithContext(e){this.canvasContextPairs.length<this.maxPoolSize&&(e.context.globalAlpha=1,e.context.globalCompositeOperation=`source-over`,e.context.imageSmoothingEnabled=!0,e.context.clearRect(0,0,e.canvas.width,e.canvas.height),e.canvas.width=1,e.canvas.height=1,this.canvasContextPairs.push(e))}getCanvas(e,t,n=!1){return this.getCanvasWithContext(e,t,n).canvas}getContext(e,t={}){let n=this.canvasContextPairs.find(t=>t.canvas===e);return n?n.context:e.getContext(`2d`,{willReadFrequently:!0,alpha:!0,desynchronized:!0,...t})}dispose(){this.canvasContextPairs=[]}},Hs=class{constructor(e={}){this.pools=new Map,this.memoryUsage=0,this.maxMemoryUsage=e.maxMemory||Ms.MAX_BUFFER_MEMORY,this.allocatedBuffers=new WeakMap,this.sizeStrategy=e.sizeStrategy||`adaptive`}getOptimalSize(e){switch(this.sizeStrategy){case`exact`:return e;case`power2`:return 2**Math.ceil(Math.log2(e));default:return e<1024?e:e<1024*1024?Math.ceil(e/1024)*1024:2**Math.ceil(Math.log2(e))}}getBuffer(e,t=Float32Array){let n=this.getOptimalSize(e),r=`${t.name}-${n}`,i=(this.pools.get(r)||[]).pop();if(!i)try{i=new t(n),this.memoryUsage+=i.byteLength,this.allocatedBuffers.set(i,!0)}catch{this.cleanup();try{i=new t(n),this.memoryUsage+=i.byteLength,this.allocatedBuffers.set(i,!0)}catch(e){let r=n*t.BYTES_PER_ELEMENT/(1024*1024),i=this.memoryUsage/(1024*1024);throw Error(`Buffer allocation failed: requested ${r.toFixed(1)}MB, current usage: ${i.toFixed(1)}MB, max: ${(this.maxMemoryUsage/(1024*1024)).toFixed(1)}MB. Original error: ${e.message}`)}}return this.memoryUsage>this.maxMemoryUsage*Ms.CLEANUP_THRESHOLD&&this.cleanup(),this.checkMemoryHealth(),i.byteOffset+e*t.BYTES_PER_ELEMENT>i.buffer.byteLength&&(i=new t(e),this.memoryUsage+=i.byteLength),new t(i.buffer,i.byteOffset,e)}forget(e){this.memoryUsage=Math.max(0,this.memoryUsage-e.buffer.byteLength)}releaseBuffer(e,t=Float32Array){let n=(e.buffer.byteLength-e.byteOffset)/t.BYTES_PER_ELEMENT,r=this.getOptimalSize(n),i=`${t.name}-${r}`,a=this.pools.get(i)||[];a.length<$t.BUFFER_POOL_SIZE?(a.push(new t(e.buffer,e.byteOffset,n)),this.pools.set(i,a)):this.allocatedBuffers.has(e)&&(this.memoryUsage-=e.byteLength,this.allocatedBuffers.delete(e))}cleanup(){let e=Array.from(this.pools.entries());e.slice(0,Math.floor(e.length/2)).forEach(([e,t])=>{t.forEach(e=>{this.allocatedBuffers.has(e)&&(this.memoryUsage-=e.byteLength,this.allocatedBuffers.delete(e))}),this.pools.delete(e)})}dispose(){this.pools.forEach(e=>{e.forEach(e=>{this.allocatedBuffers.has(e)&&this.allocatedBuffers.delete(e)})}),this.pools.clear(),this.memoryUsage=0}getMemoryStats(){return{currentUsage:this.memoryUsage,maxUsage:this.maxMemoryUsage,utilizationPercentage:this.memoryUsage/this.maxMemoryUsage*100,poolCount:this.pools.size,allocatedBufferCount:this.allocatedBuffers&&this.allocatedBuffers.size||0}}checkMemoryHealth(){let e=this.getMemoryStats();return e.utilizationPercentage>90?(console.warn(`Memory pool critical: ${e.utilizationPercentage.toFixed(1)}% used (${(e.currentUsage/(1024*1024)).toFixed(1)}MB / ${(e.maxUsage/(1024*1024)).toFixed(1)}MB)`),`critical`):e.utilizationPercentage>70?(console.warn(`Memory pool high: ${e.utilizationPercentage.toFixed(1)}% used (${(e.currentUsage/(1024*1024)).toFixed(1)}MB / ${(e.maxUsage/(1024*1024)).toFixed(1)}MB)`),`high`):`normal`}},Us=class{constructor(e=$t.CACHE_SIZE_LIMIT){this.cache=new Map,this.accessOrder=[],this.maxSize=e}generateHash(e){let t=``;for(let n of e)if(n?.image){let e=n.image.width||0,r=n.image.height||0,i=n.image.src||n.uuid||``,a=n.flipY===!1?`n`:`f`,o=`${n.colorSpace??``}|${n.userData?.ocioColorSpace??``}`;t+=`${e}x${r}_${i.slice(-8)}_${a}_${o}_`}return t+e.length}get(e){if(this.cache.has(e)){let t=this.cache.get(e);if(t?.userData&&t.userData.buffer===null){this.cache.delete(e);let t=this.accessOrder.indexOf(e);return t>-1&&this.accessOrder.splice(t,1),null}let n=this.accessOrder.indexOf(e);return n>-1&&this.accessOrder.splice(n,1),this.accessOrder.push(e),t}return null}set(e,t){if(this.cache.has(e)){let t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1)}else this.cache.size>=this.maxSize&&this.evictLRU();this.cache.set(e,t),this.accessOrder.push(e)}evictLRU(){if(this.accessOrder.length>0){let e=this.accessOrder.shift(),t=this.cache.get(e);t&&t.dispose&&t.dispose(),this.cache.delete(e)}}dispose(){this.cache.forEach(e=>{e&&e.dispose&&e.dispose()}),this.cache.clear(),this.accessOrder=[]}},Ws=class{constructor(e={}){this.useWorkers=typeof Worker<`u`,this.maxConcurrentWorkers=$t.MAX_CONCURRENT_WORKERS,this.activeWorkers=0,this._issues=e.issues??null,this.maxTextureSize=this._clampTextureSize(e.maxTextureSize??$t.DEFAULT_MAX_TEXTURE_SIZE),this.canvasPool=new Vs,this.bufferPool=new Hs({maxMemory:e.maxBufferMemory||Ms.MAX_BUFFER_MEMORY,sizeStrategy:e.bufferSizeStrategy||`adaptive`}),this.textureCache=new Us,this.capabilities=this.detectCapabilities(),this.optimalMethod=this.selectOptimalMethod()}_reportTextureFailure(e,t){if(t instanceof rn)throw t;this._issues?.record(Y.TEXTURE_BUILD_FAILED,`${e} texture array failed to build — those surfaces render untextured`,{map:e,cause:String(t?.message??t)})}_reportTextureLayer(e,t){this._issues?.record(Y.TEXTURE_BUILD_FAILED,`texture ${e} could not be read — its surfaces show a white placeholder`,{layer:e,cause:String(t?.message??t)})}_clampTextureSize(e){let t=Math.floor(Number(e)||$t.DEFAULT_MAX_TEXTURE_SIZE);return Math.max($t.MIN_TEXTURE_WIDTH,Math.min(t,$t.MAX_TEXTURE_SIZE))}setMaxTextureSize(e){let t=this._clampTextureSize(e);return t===this.maxTextureSize?t:(this.maxTextureSize=t,this.textureCache?.dispose(),this.textureCache=new Us,this.maxTextureSize)}detectCapabilities(){return{offscreenCanvas:typeof OffscreenCanvas<`u`,imageBitmap:typeof createImageBitmap<`u`,workers:typeof Worker<`u`,hardwareConcurrency:Dr()}}selectOptimalMethod(){return this.capabilities.workers&&this.capabilities.offscreenCanvas?`worker-offscreen`:this.capabilities.imageBitmap?`imageBitmap`:`canvas`}_applyColorManagement(e,t,n,i=new Set){let a=Qr();if(!a?.hasConfig)return;let o=e?.image?.data;if(!o||!n)return;let s=t.filter(e=>e?.image),c=e.image.width*e.image.height*4,l=0,u=0,d=[];for(let e=0;e<s.length;e++){let t=e*c,n=Math.min(t+c,o.length);if(t>=o.length)break;let f=s[e],p=o.subarray(t,n),m=null;try{m=a.resolveTexture(f)}catch(t){js.warn(`could not resolve the colour space of layer ${e}: ${t.message}`)}let h=m&&m.via!==`three`?m.colorSpace:null,g=f.type===r.FloatType||f.type===r.HalfFloatType;h&&(i.has(e)||g)&&(d.push(`${f.name||`layer ${e}`} (${h})`),h=null);try{a.convertTextureBytes(p,{space:h,encoding:`srgb`})&&(h?l++:u++)}catch(t){this._issues?.warn(Y.TEXTURE_PROCESSING_FALLBACK,`colour conversion failed for layer ${e} — left in its original space`,{cause:String(t?.message??t),space:h})}}d.length&&this._issues?.warn(Y.TEXTURE_PROCESSING_FALLBACK,`${d.length} colour map(s) name a colour space their stored bytes are no longer in (re-encoded or quantized on the way in); converted by primaries only`,{textures:d.slice(0,8)}),l+u!==0&&(e.needsUpdate=!0,js.info(`colour maps into ${a.workingSpace}: ${l} by named space, ${u} by primaries, of ${s.length}`))}_harmonizeTransfer(e,t,n){let i=new Set,a=e?.image?.data;if(!a)return i;let o=t.filter(e=>e?.image),s=n?r.SRGBColorSpace:r.LinearSRGBColorSpace,c=e.image.width*e.image.height*4,l=[];for(let e=0;e<o.length;e++){let t=o[e].colorSpace;if(t!==r.SRGBColorSpace&&t!==r.LinearSRGBColorSpace||t===s)continue;let u=Bs(n?`toSRGB`:`toLinear`),d=e*c,f=Math.min(d+c,a.length);for(let e=d;e<f;e+=4)a[e]=u[a[e]],a[e+1]=u[a[e+1]],a[e+2]=u[a[e+2]];l.push(o[e].name||o[e].source?.uuid?.slice(0,8)||`layer ${e}`),i.add(e)}if(l.length===0)return i;e.needsUpdate=!0;let u=l.slice(0,4).join(`, `)+(l.length>4?`, +${l.length-4} more`:``);return n?js.info(`re-encoded ${l.length}/${o.length} linear-declared colour map(s) to sRGB so the GPU decode round-trips: ${u}`):js.warn(`decoded ${l.length}/${o.length} sRGB-declared data map(s) to linear — precision is lost in the darks, check the asset: ${u}`),i}async createTexturesToDataTexture(e,{srgbPool:t=!1}={}){if(!e||e.length===0)return null;let n=Qr()?.inputKey??`-`,r=`${t?`s`:`l`}:${n}:${this.textureCache.generateHash(e)}`,i=this.textureCache.get(r);if(i)return i;if(typeof createImageBitmap>`u`){let n=await this.processOnCPU(e),i=this._harmonizeTransfer(n,e,t);return this._applyColorManagement(n,e,t,i),this.textureCache.set(r,n),n}let{normalized:a,bitmapsToClose:o}=await this._normalizeTexturesForProcessing(e),s=this.selectProcessingStrategy(a),c;try{switch(s.method){case`worker-direct`:c=await this.processWithWorkerDirect(a);break;case`worker-streaming`:c=await this.processInWorkerStreaming(a);break;case`main-batch`:c=await this.processOnMainThreadBatch(a,s.batchSize);break;case`main-streaming`:c=await this.processOnMainThreadStreaming(a);break;default:c=await this.processOnMainThreadSync(a)}if(c){let n=this._harmonizeTransfer(c,e,t);this._applyColorManagement(c,e,t,n),this.textureCache.set(r,c)}return c}catch(n){if(n instanceof rn)throw n;this._issues?.warn(Y.TEXTURE_PROCESSING_FALLBACK,`worker texture processing failed — retrying on the main thread`,{cause:String(n?.message??n)});let r=await this.processOnMainThreadSync(a),i=this._harmonizeTransfer(r,e,t);return this._applyColorManagement(r,e,t,i),r}finally{for(let e of o)e.close()}}selectProcessingStrategy(e){let t=e.reduce((e,t)=>e+(t.image?.width||0)*(t.image?.height||0),0),n=t*4;return this.capabilities.workers&&n>Ms.MAX_TEXTURE_MEMORY?{method:`worker-streaming`}:this.capabilities.workers&&t>2097152?{method:`worker-direct`}:t>524288?{method:`main-batch`,batchSize:Math.min(4,e.length)}:e.length>8?{method:`main-streaming`}:{method:`main-sync`}}async processWithWorkerDirect(e){for(;this.activeWorkers>=this.maxConcurrentWorkers;)await new Promise(e=>setTimeout(e,10));this.activeWorkers++;let t=1,n=null;try{let r=await this.prepareTexturesForWorkerDirect(e),i=this._sharedPackSlots(r);if(i>0)return t+=i,this.activeWorkers+=i,this.createDataArrayTextureFromResult(await this._packAcrossWorkers(r,t));n=new ko;let a=await new Promise((e,t)=>{n.onmessage=n=>{n.data.error?t(Error(n.data.error)):e(n.data)},n.onerror=t;let i=[];r.forEach(e=>{e.data instanceof ArrayBuffer?i.push(e.data):e.bitmap&&i.push(e.bitmap)}),n.postMessage({textures:r,maxTextureSize:this.maxTextureSize,method:`direct-transfer`},i)});return this.createDataArrayTextureFromResult(a)}finally{n?.terminate(),this.activeWorkers-=t}}_sharedPackSlots(e){if(typeof SharedArrayBuffer>`u`||!globalThis.crossOriginIsolated||e.reduce((e,t)=>e+t.width*t.height,0)<Is)return 0;let t=this.maxConcurrentWorkers-this.activeWorkers;return Math.max(0,Math.min(e.length,Fs,t+1)-1)}async _packAcrossWorkers(e,t){let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(e.map(e=>({image:e}))),i=e.length,a=new SharedArrayBuffer(n*r*i*4),o=Array.from({length:t},()=>({cost:0,layers:[],transfer:[]})),s=e.map((e,t)=>t),c=t=>e[t].width*e[t].height;s.sort((e,t)=>c(t)-c(e));for(let t of s){let n=o.reduce((e,t)=>t.cost<e.cost?t:e),r=e[t];n.layers.push({index:t,texture:r}),n.cost+=c(t),r.data instanceof ArrayBuffer?n.transfer.push(r.data):r.bitmap&&n.transfer.push(r.bitmap)}let l=[];try{await Promise.all(o.filter(e=>e.layers.length).map(e=>new Promise((t,i)=>{let o=jr(ko);l.push(o),o.onmessage=({data:e})=>e.error?i(Error(e.error)):t(),o.onerror=e=>i(Error(e.message||`texture worker failed`)),o.postMessage({shared:a,width:n,height:r,layers:e.layers,maxTextureSize:this.maxTextureSize},e.transfer)})))}finally{for(let e of l)e.terminate()}return{data:a,width:n,height:r,depth:i}}async processInWorkerStreaming(e){let t=e.filter(e=>e?.image);if(t.length===0)return this.createFallbackTexture();let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t),i=t.length;for(;this.activeWorkers>=this.maxConcurrentWorkers;)await new Promise(e=>setTimeout(e,10));this.activeWorkers++;let a=jr(ko);try{let e=0,o=null,s,c=new Promise((e,t)=>s={resolve:e,reject:t});c.catch(()=>{}),a.onmessage=({data:t})=>{t.error?s.reject(Error(t.error)):t.stream===`ack`?e++:s.resolve(t),o?.()},a.onerror=e=>{s.reject(Error(e.message||`texture worker failed`)),o?.()},a.postMessage({stream:`begin`,width:n,height:r,depth:i});let l=performance.now();for(let s=0;s<i;s++){for(;s-e>=Ms.STREAM_BATCH_SIZE;)await Promise.race([new Promise(e=>o=e),c]),l=performance.now();let i=t[s],u=await createImageBitmap(i.image,{resizeWidth:n,resizeHeight:r,resizeQuality:`high`,imageOrientation:i.flipY===!1?`none`:`flipY`});a.postMessage({stream:`layer`,index:s,bitmap:u},[u]),performance.now()-l>Ps&&(await new Promise(e=>setTimeout(e,0)),l=performance.now())}return a.postMessage({stream:`end`}),this.createDataArrayTextureFromResult(await c)}finally{a.terminate(),this.activeWorkers--}}async prepareTexturesForWorkerDirect(e){let t=[],n=()=>({data:new Uint8ClampedArray([255,255,255,255]).buffer,width:1,height:1,isImageData:!0});for(let r=0;r<e.length;r++){let i=e[r];if(!i?.image){this._reportTextureLayer(r,`no image`),t.push(n());continue}let a=i.flipY!==!1;try{let e=i.image;if(typeof createImageBitmap<`u`&&(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&e instanceof OffscreenCanvas)){let e=await createImageBitmap(i.image,{imageOrientation:a?`flipY`:`none`});t.push({bitmap:e,width:i.image.width,height:i.image.height,isDirect:!0})}else{let e=i.image.width,n=i.image.height,r=await createImageBitmap(i.image,{imageOrientation:a?`flipY`:`none`}),o=this.canvasPool.getCanvasWithContext(e,n);o.context.drawImage(r,0,0),r.close();let s=o.context.getImageData(0,0,e,n);t.push({data:s.data.buffer,width:e,height:n,isImageData:!0}),this.canvasPool.releaseCanvasWithContext(o)}}catch(e){this._reportTextureLayer(r,e),t.push(n())}}return t}async processOnCPU(e){let t=e.map((e,t)=>{let n=e?.image,r=e?.isCompressedTexture?e.mipmaps?.[0]:n,i=e?.isCompressedTexture?r?.data:Ks(e);return i&&r.width>0&&r.height>0&&i.byteLength>=r.width*r.height*4?{data:new Uint8Array(i.buffer,i.byteOffset,r.width*r.height*4),width:r.width,height:r.height,flipY:e.flipY!==!1}:(this._reportTextureLayer(t,n?`not decoded to pixels, and there is no browser to decode it`:`no image`),{data:new Uint8Array([255,255,255,255]),width:1,height:1,flipY:!1})}),{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t.map(e=>({image:e}))),i=n*r*4,a=kr()&&i*t.length>=Ns?await this._packInWorker(t,n,r):null;if(a)return this.createDataArrayTextureFromBuffer(a,n,r,t.length);let o=this.bufferPool.getBuffer(i*t.length,Uint8Array);return t.forEach((e,t)=>No(e,o,t*i,n,r)),this.createDataArrayTextureFromBuffer(o,n,r,t.length)}async _packInWorker(e,t,n){let r=await Rs(),i=null;try{let r=[],a=e.map(e=>{if(typeof SharedArrayBuffer<`u`&&e.data.buffer instanceof SharedArrayBuffer)return e;let t=e.data.slice();return r.push(t.buffer),{...e,data:t}});return i=jr(Mo),await new Promise((e,o)=>{i.onmessage=t=>t.data.error?o(Error(t.data.error)):e(t.data.data),i.onerror=e=>o(e.error??Error(e.message??`texture pack worker failed`)),i.postMessage({layers:a,width:t,height:n},r)})}catch(e){return this._issues?.warn(Y.TEXTURE_PROCESSING_FALLBACK,`worker texture packing failed — packing on the main thread`,{cause:String(e?.message??e)}),null}finally{i?.terminate(),r()}}async processOnMainThreadBatch(e,t){let n=e.filter(e=>e?.image);if(n.length===0)return this.createFallbackTexture();let{maxWidth:r,maxHeight:i}=this.calculateOptimalDimensions(n),a=n.length,o=this.bufferPool.getBuffer(r*i*a*4,Uint8Array);for(let e=0;e<n.length;e+=t){let a=Math.min(e+t,n.length),s=[];for(let t=e;t<a;t++){let e=n[t],a=e.flipY!==!1,o=createImageBitmap(e.image,{resizeWidth:r,resizeHeight:i,resizeQuality:`high`,imageOrientation:a?`flipY`:`none`});s.push(o.then(e=>({bitmap:e,index:t})))}let c=await Promise.all(s),l=this.canvasPool.getCanvasWithContext(r,i);l.context.imageSmoothingEnabled=!1;for(let{bitmap:e,index:t}of c){l.context.clearRect(0,0,r,i),l.context.drawImage(e,0,0);let n=l.context.getImageData(0,0,r,i),a=r*i*4*t;o.set(n.data,a),e.close()}this.canvasPool.releaseCanvasWithContext(l)}return this.createDataArrayTextureFromBuffer(o,r,i,a)}async processOnMainThreadStreaming(e){let t=e.filter(e=>e?.image);if(t.length===0)return this.createFallbackTexture();let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t),i=t.length,a=this.bufferPool.getBuffer(n*r*i*4,Uint8Array),o=this.canvasPool.getCanvasWithContext(n,r);o.context.imageSmoothingEnabled=!0,o.context.imageSmoothingQuality=`high`;for(let e=0;e<t.length;e++){let i=t[e],s=await createImageBitmap(i.image,{resizeWidth:n,resizeHeight:r,resizeQuality:`high`,imageOrientation:i.flipY===!1?`none`:`flipY`});o.context.clearRect(0,0,n,r),o.context.drawImage(s,0,0),s.close();let c=o.context.getImageData(0,0,n,r),l=n*r*4*e;a.set(c.data,l),e%Ms.STREAM_BATCH_SIZE===0&&await new Promise(e=>setTimeout(e,0))}return this.canvasPool.releaseCanvasWithContext(o),this.createDataArrayTextureFromBuffer(a,n,r,i)}async processOnMainThreadSync(e){let t=e.filter(e=>e?.image);if(t.length===0)return this.createFallbackTexture();let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t),i=t.length,a=this.bufferPool.getBuffer(n*r*i*4,Uint8Array),o=this.canvasPool.getCanvasWithContext(n,r);o.context.imageSmoothingEnabled=!0,o.context.imageSmoothingQuality=`high`;for(let e=0;e<t.length;e++){let i=t[e],s=await createImageBitmap(i.image,{resizeWidth:n,resizeHeight:r,resizeQuality:`high`,imageOrientation:i.flipY===!1?`none`:`flipY`});o.context.clearRect(0,0,n,r),o.context.drawImage(s,0,0),s.close();let c=o.context.getImageData(0,0,n,r),l=n*r*4*e;a.set(c.data,l)}return this.canvasPool.releaseCanvasWithContext(o),this.createDataArrayTextureFromBuffer(a,n,r,i)}createMaterialRawData(e){let t=K.FLOATS_PER_MATERIAL,n=new Float32Array(e.length*t);for(let r=0;r<e.length;r++)Ut(n,r*t,e[r]);return n}createBVHRawData(e){let t=[],n=e=>{let r=t.length;if(t.push(e),e.leftChild){let t=n(e.leftChild),r=n(e.rightChild);e.leftChild=t,e.rightChild=r}return r};n(e);let r=$t.VEC4_PER_BVH_NODE*$t.FLOATS_PER_VEC4;bt(t.length,`BVH node count`);let i=t.length*r,a=new Float32Array(i),o=yt(a);for(let e=0;e<t.length;e++){let n=e*r,i=t[e];if(i.leftChild!==null){let e=i.leftChild,r=i.rightChild,s=t[e],c=t[r];a[n]=s.boundsMin.x,a[n+1]=s.boundsMin.y,a[n+2]=s.boundsMin.z,o[n+3]=e,a[n+4]=s.boundsMax.x,a[n+5]=s.boundsMax.y,a[n+6]=s.boundsMax.z,o[n+7]=r,a[n+8]=c.boundsMin.x,a[n+9]=c.boundsMin.y,a[n+10]=c.boundsMin.z,a[n+12]=c.boundsMax.x,a[n+13]=c.boundsMax.y,a[n+14]=c.boundsMax.z}else o[n]=i.triangleOffset,o[n+1]=i.triangleCount,o[n+3]=Et.TRIANGLE_LEAF}return a}async createMaterialTextures(e){let{materials:t,maps:n,normalMaps:i,bumpMaps:a,roughnessMaps:o,metalnessMaps:s,emissiveMaps:c,displacementMaps:l}=e;console.log(`[TextureCreator] Creating material textures only`);let u=performance.now();try{if(!t||t.length===0)throw Error(`No materials provided for texture creation`);this.textureCache.dispose(),this.textureCache=new Us;let e=[];for(let[t,r]of[[`albedo`,n],[`normal`,i],[`bump`,a],[`roughness`,o],[`metalness`,s],[`emissive`,c],[`displacement`,l]])!r||r.length===0||e.push(this.createTexturesToDataTexture(r).then(e=>({type:t,texture:e})).catch(e=>(this._reportTextureFailure(t,e),{type:t,texture:null})));let d=await Promise.allSettled(e),f=d.find(e=>e.status===`rejected`);if(f)throw f.reason;let p={};d.forEach(e=>{if(e.status===`fulfilled`&&e.value){let{type:t,texture:n}=e.value;if(n)switch(t){case`albedo`:n.colorSpace=r.SRGBColorSpace,p.albedoTexture=n;break;case`normal`:p.normalTexture=n;break;case`bump`:p.bumpTexture=n;break;case`roughness`:p.roughnessTexture=n;break;case`metalness`:p.metalnessTexture=n;break;case`emissive`:n.colorSpace=r.SRGBColorSpace,p.emissiveTexture=n;break;case`displacement`:p.displacementTexture=n;break}}});let m=performance.now()-u;return console.log(`[TextureCreator] Material texture creation complete (${m.toFixed(2)}ms)`),p}catch(e){throw console.error(`[TextureCreator] Material texture creation error:`,e),Error(`Material texture creation failed: ${e.message}`)}}calculateOptimalDimensions(e){let t=0,n=0;for(let r of e)t=Math.max(t,r.image.width),n=Math.max(n,r.image.height);let r=Math.max(t,n);if(r>this.maxTextureSize){let e=this.maxTextureSize/r;t=Math.round(t*e),n=Math.round(n*e)}return{maxWidth:Wt(t,this.maxTextureSize),maxHeight:Math.max(1,n)}}createDataArrayTextureFromResult(e){let t=(e.data instanceof ArrayBuffer,new Uint8Array(e.data));return this.createDataArrayTextureFromBuffer(t,e.width,e.height,e.depth)}createDataArrayTextureFromBuffer(e,t,n,i){let a=new r.DataArrayTexture(e,t,n,i);a.minFilter=r.LinearFilter,a.magFilter=r.LinearFilter,a.wrapS=r.RepeatWrapping,a.wrapT=r.RepeatWrapping,a.format=r.RGBAFormat,a.type=r.UnsignedByteType,a.needsUpdate=!0,a.generateMipmaps=!1,a.userData={buffer:e,bufferType:Uint8Array},a.onUpdate=()=>{let e=a.userData.buffer;e&&(this.bufferPool.forget(e),a.userData.buffer=null,a.image.data=null)};let o=a.dispose.bind(a);return a.dispose=()=>{a.userData.buffer&&(this.bufferPool.releaseBuffer(a.userData.buffer,a.userData.bufferType),a.userData.buffer=null),o()},a}async _normalizeTexturesForProcessing(e){let t=[],n=[],i=[];for(let n of e){if(!n?.image){this._reportTextureLayer(t.length,`no image`),t.push(null);continue}if(n.isCompressedTexture&&n.format===r.RGBAFormat&&n.mipmaps?.[0]?.data){let e=n.mipmaps[0],r=t.length;t.push(null),i.push({index:r,flipY:n.flipY,promise:Gs(e.data,e.width,e.height)});continue}if(n.isCompressedTexture){console.warn(`[TextureCreator] GPU-compressed texture in mixed group — using placeholder`),t.push(null);continue}if(n.image.data&&!(typeof HTMLImageElement<`u`&&n.image instanceof HTMLImageElement)&&!(typeof HTMLCanvasElement<`u`&&n.image instanceof HTMLCanvasElement)&&!(typeof ImageBitmap<`u`&&n.image instanceof ImageBitmap)){let e=t.length;t.push(null);let r=Ks(n);i.push({index:e,flipY:n.flipY,promise:r?Gs(r,n.image.width,n.image.height):Promise.reject(Error(`pixels in a layout the texture arrays cannot take`))});continue}t.push(n)}if(i.length>0){let e=await Promise.allSettled(i.map(e=>e.promise));for(let r=0;r<i.length;r++){let{index:a,flipY:o}=i[r],s=e[r];if(s.status===`fulfilled`){let e=s.value;n.push(e),t[a]={image:e,flipY:o}}else this._reportTextureLayer(a,s.reason)}}for(let e=0;e<t.length;e++)if(t[e]===null){let r=new Uint8ClampedArray([255,255,255,255]),i=await createImageBitmap(new ImageData(r,1,1));n.push(i),t[e]={image:i,flipY:!1}}return{normalized:t,bitmapsToClose:n}}createFallbackTexture(){let e=new r.DataArrayTexture(new Uint8Array([255,255,255,255]),1,1,1);return e.minFilter=r.LinearFilter,e.magFilter=r.LinearFilter,e.format=r.RGBAFormat,e.type=r.UnsignedByteType,e.needsUpdate=!0,e.generateMipmaps=!1,e}dispose(){this.canvasPool.dispose(),this.bufferPool.dispose(),this.textureCache.dispose()}};async function Gs(e,t,n){let r=new Uint8ClampedArray(e.buffer,e.byteOffset,e.byteLength);return createImageBitmap(new ImageData(r,t,n))}function Ks(e){let t=e?.image,n=t?.data;if(!n||!(t.width>0)||!(t.height>0))return null;let i=t.width*t.height;if(n instanceof Uint8Array||n instanceof Uint8ClampedArray)return n.byteLength>=i*4?new Uint8Array(n.buffer,n.byteOffset,i*4):null;let a={[r.RGBAFormat]:4,[r.RGFormat]:2,[r.RedFormat]:1}[e.format]??Math.round(n.length/i);if(!(a>=1&&a<=4)||n.length<i*a)return null;let o=e.type===r.HalfFloatType,s=e.type===r.UnsignedShortType?1/65535:1,c=new Uint8Array(i*4);for(let e=0;e<i;e++)for(let t=0;t<4;t++){let i=t<a?n[e*a+t]:null,l=i===null?t===3?1:c[e*4]/255:o?r.DataUtils.fromHalfFloat(i):i*s;c[e*4+t]=Math.max(0,Math.min(255,Math.round(l*255)))}return c}var qs=class{constructor(){this.maxLeafSize=8}build(e){let t=e.length;if(t===0){let e=new Float32Array(16);return e[7]=1,e[14]=1,e[15]=-1,{nodeData:e,nodeCount:1,sortedPerm:new Int32Array,bitTrails:new Float32Array}}let n=new Int32Array(t);for(let e=0;e<t;e++)n[e]=e;let r=2*t+4,i=new Float32Array(r*16),a=0,o=new Float32Array(t),s=(t,r,c,l)=>{let u=a++,d=u*16,f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,_=-1/0,v=0,y=1/0,b=1/0,x=1/0,S=-1/0,C=-1/0,w=-1/0;for(let i=t;i<r;i++){let t=e[n[i]];f=Math.min(f,t.bMinX),p=Math.min(p,t.bMinY),m=Math.min(m,t.bMinZ),h=Math.max(h,t.bMaxX),g=Math.max(g,t.bMaxY),_=Math.max(_,t.bMaxZ),v+=t.power,y=Math.min(y,t.cx),b=Math.min(b,t.cy),x=Math.min(x,t.cz),S=Math.max(S,t.cx),C=Math.max(C,t.cy),w=Math.max(w,t.cz)}i[d+0]=f,i[d+1]=p,i[d+2]=m,i[d+3]=v,i[d+4]=h,i[d+5]=g,i[d+6]=_;let T=r-t,E;if(T<=this.maxLeafSize){i[d+7]=1,i[d+8]=t,i[d+9]=T,i[d+10]=0,i[d+11]=0,E=null;for(let i=t;i<r;i++){let t=e[n[i]];E=Ys(E,Js(t)),o[i]=c}E||={ax:0,ay:0,az:1,cosO:-1}}else{let a=S-y,o=C-b,u=w-x,f;f=a>=o&&a>=u?0:o>=u?1:2;let p=[`cx`,`cy`,`cz`][f],m=t+r>>1;this._nthElement(n,e,t,r,m,p),i[d+7]=0;let h=s(t,m,c,l+1),g=s(m,r,c+2**l,l+1);i[d+8]=h.nodeIndex,i[d+9]=g.nodeIndex,i[d+10]=0,i[d+11]=0,E=Ys(h.cone,g.cone)}return i[d+12]=E.ax,i[d+13]=E.ay,i[d+14]=E.az,i[d+15]=E.cosO,{nodeIndex:u,cone:E}};s(0,t,0,0);let c=new Int32Array(t);for(let e=0;e<t;e++)c[e]=n[e];let l=new Float32Array(a*16);return l.set(i.subarray(0,a*16)),console.log(`[LightBVHBuilder] Built BVH: ${a} nodes for ${t} emissive triangles`),{nodeData:l,nodeCount:a,sortedPerm:c,bitTrails:o}}_nthElement(e,t,n,r,i,a){for(;n<r-1;){let o=n+r>>1,s=t[e[o]][a],c=e[o];e[o]=e[r-1],e[r-1]=c;let l=n;for(let i=n;i<r-1;i++)t[e[i]][a]<s&&(c=e[i],e[i]=e[l],e[l]=c,l++);if(c=e[l],e[l]=e[r-1],e[r-1]=c,l===i)return;l<i?n=l+1:r=l}}};function Js(e){return e.twoSided?{ax:e.nx,ay:e.ny,az:e.nz,cosO:-1}:{ax:e.nx,ay:e.ny,az:e.nz,cosO:1}}function Ys(e,t){if(!e)return t;if(!t||e.cosO<=-1)return e;if(t.cosO<=-1)return t;let n=Math.min(Math.max(e.cosO,-1),1),r=Math.min(Math.max(t.cosO,-1),1),i=Math.acos(n),a=Math.acos(r),o=Math.min(Math.max(e.ax*t.ax+e.ay*t.ay+e.az*t.az,-1),1),s=Math.acos(o);if(Math.min(s+a,Math.PI)<=i)return e;if(Math.min(s+i,Math.PI)<=a)return t;let c=(i+a+s)*.5;if(c>=Math.PI)return{ax:e.ax,ay:e.ay,az:e.az,cosO:-1};let l=c-i,u=e.ay*t.az-e.az*t.ay,d=e.az*t.ax-e.ax*t.az,f=e.ax*t.ay-e.ay*t.ax,p=Math.sqrt(u*u+d*d+f*f);if(p<1e-8)return{ax:e.ax,ay:e.ay,az:e.az,cosO:-1};u/=p,d/=p,f/=p;let m=Math.cos(l),h=Math.sin(l),g=u*e.ax+d*e.ay+f*e.az,_=d*e.az-f*e.ay,v=f*e.ax-u*e.az,y=u*e.ay-d*e.ax,b=e.ax*m+_*h+u*g*(1-m),x=e.ay*m+v*h+d*g*(1-m),S=e.az*m+y*h+f*g*(1-m),C=Math.sqrt(b*b+x*x+S*S)||1;return{ax:b/C,ay:x/C,az:S/C,cosO:Math.cos(c)}}It(),ke(),nr();var Xs=Object.freeze({r:0,g:0,b:0});function Zs(e){if(!e)return Xs;if(!Xn())return e;let t=[e.r,e.g,e.b];return Qn(t),{r:t[0],g:t[1],b:t[2]}}var Qs=ve(`emissive`),$s=class{constructor(){this.emissiveTriangles=[],this.emissiveCount=0,this.totalEmissivePower=0,this.emissiveIndicesArray=null,this.emissivePowerArray=null,this.cdfArray=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this._totalTriangleCount=0,this._hiddenMeshes=new Set}extractEmissiveTriangles(e,t,n,r=null){this.emissiveTriangles=[],this._emissiveMeshes=null,this.totalEmissivePower=0,this._totalTriangleCount=n;let i=G.FLOATS_PER_TRIANGLE,a=G.MATERIAL_FLAGS_OFFSET,o=G.MESH_INDEX_OFFSET,s=e&&e.chunks?e:null,c=s?s.viewAs(Float32Array):null,l=s?null:e,u=s?null:new Float32Array(e.buffer,e.byteOffset,e.length),d=new Map;for(let e=0;e<n;e++){if(s?.spilledChunks&&!s.isResident(e,1)){e=((e/s.recordsPerChunk|0)+1)*s.recordsPerChunk-1;continue}let n=s?s.chunkFor(e):l,f=s?c.chunkFor(e):u,p=s?s.baseOf(e):e*i,m=n[p+a]&xt,h=n[p+o],g=t[m];if(!g)continue;let _=d.get(g);_===void 0&&(_=Zs(g.emissive),d.set(g,_));let v=g.emissiveIntensity||0;if(v>0&&(_.r>0||_.g>0||_.b>0)){let t=r?.placementRunOf?.(h)?.start??-1,n=t>=0&&r.isSet[t],i=n?r.matrixRow(t):0,a=n?r.rowArray:null,o=(e,t,n)=>a?a[i]*e+a[i+4]*t+a[i+8]*n+a[i+12]:e,s=(e,t,n)=>a?a[i+1]*e+a[i+5]*t+a[i+9]*n+a[i+13]:t,c=(e,t,n)=>a?a[i+2]*e+a[i+6]*t+a[i+10]*n+a[i+14]:n,l=f[p+0],u=f[p+1],d=f[p+2],y=f[p+4],b=f[p+5],x=f[p+6],S=f[p+8],C=f[p+9],w=f[p+10],T=o(l,u,d),E=s(l,u,d),D=c(l,u,d),O=o(y,b,x),k=s(y,b,x),A=c(y,b,x),j=o(S,C,w),M=s(S,C,w),N=c(S,C,w),P=this._calculateTriangleArea(T,E,D,O,k,A,j,M,N),F=(.2126*_.r+.7152*_.g+.0722*_.b)*v*P,I=(k-E)*(N-D)-(A-D)*(M-E),L=(A-D)*(j-T)-(O-T)*(N-D),ee=(O-T)*(M-E)-(k-E)*(j-T),te=Math.sqrt(I*I+L*L+ee*ee)||1,R=g.side===1?-1:1;I=I/te*R,L=L/te*R,ee=ee/te*R;let ne=g.side===2,re=(T+O+j)/3,ie=(E+k+M)/3,ae=(D+A+N)/3,oe=Math.min(T,O,j),se=Math.min(E,k,M),ce=Math.min(D,A,N),le=Math.max(T,O,j),z=Math.max(E,k,M),ue=Math.max(D,A,N);this.emissiveTriangles.push({triangleIndex:e,materialIndex:m,meshIndex:h,sideSign:R,instanceLeaf:n?r.tlasLeafIndex[t]:-1,power:F,area:P,emissive:{r:_.r,g:_.g,b:_.b},emissiveIntensity:v,cx:re,cy:ie,cz:ae,bMinX:oe,bMinY:se,bMinZ:ce,bMaxX:le,bMaxY:z,bMaxZ:ue,nx:I,ny:L,nz:ee,twoSided:ne}),this.totalEmissivePower+=F}}return this.emissiveCount=this.emissiveTriangles.length,this.emissiveCount>0&&Qs.debug(`${H.n(this.emissiveCount)} emissive tris (${(this.emissiveCount/n*100).toFixed(2)}%) · total power ${this.totalEmissivePower.toFixed(2)}`),this._buildDataArrays(),this.emissiveCount}get emissiveMeshes(){return this._emissiveMeshes??=new Set(this.emissiveTriangles.map(e=>e.meshIndex))}refreshTransforms(e,t){let n=e&&e.chunks?e:null,r=n?n.viewAs(Float32Array):null,i=n?null:new Float32Array(e.buffer,e.byteOffset,e.length),a=G.FLOATS_PER_TRIANGLE;this.totalEmissivePower=0;for(let e of this.emissiveTriangles){let o=n?r.chunkFor(e.triangleIndex):i,s=n?n.baseOf(e.triangleIndex):e.triangleIndex*a,c=[o[s],o[s+1],o[s+2],o[s+4],o[s+5],o[s+6],o[s+8],o[s+9],o[s+10]],l=t.placementRunOf?.(e.meshIndex)?.start??-1;if(l>=0&&t.isSet[l]){let e=t.matrixRow(l),n=t.rowArray;for(let t=0;t<9;t+=3){let r=c[t],i=c[t+1],a=c[t+2];c[t]=n[e]*r+n[e+4]*i+n[e+8]*a+n[e+12],c[t+1]=n[e+1]*r+n[e+5]*i+n[e+9]*a+n[e+13],c[t+2]=n[e+2]*r+n[e+6]*i+n[e+10]*a+n[e+14]}}let[u,d,f,p,m,h,g,_,v]=c,y=this._calculateTriangleArea(u,d,f,p,m,h,g,_,v),b=e.emissive;e.power=(.2126*b.r+.7152*b.g+.0722*b.b)*e.emissiveIntensity*y,e.area=y;let x=(m-d)*(v-f)-(h-f)*(_-d),S=(h-f)*(g-u)-(p-u)*(v-f),C=(p-u)*(_-d)-(m-d)*(g-u),w=(Math.sqrt(x*x+S*S+C*C)||1)/e.sideSign;e.nx=x/w,e.ny=S/w,e.nz=C/w,e.cx=(u+p+g)/3,e.cy=(d+m+_)/3,e.cz=(f+h+v)/3,e.bMinX=Math.min(u,p,g),e.bMinY=Math.min(d,m,_),e.bMinZ=Math.min(f,h,v),e.bMaxX=Math.max(u,p,g),e.bMaxY=Math.max(d,m,_),e.bMaxZ=Math.max(f,h,v),this.totalEmissivePower+=e.power}this._buildDataArrays()}_calculateTriangleArea(e,t,n,r,i,a,o,s,c){let l=r-e,u=i-t,d=a-n,f=o-e,p=s-t,m=c-n,h=u*m-d*p,g=d*f-l*m,_=l*p-u*f;return Math.sqrt(h*h+g*g+_*_)*.5}_buildDataArrays(){this.emissiveIndicesArray=new Int32Array(this.emissiveCount),this.emissivePowerArray=new Float32Array(this.emissiveCount);for(let e=0;e<this.emissiveCount;e++)this.emissiveIndicesArray[e]=this.emissiveTriangles[e].triangleIndex,this.emissivePowerArray[e]=this.emissiveTriangles[e].power;this._buildCDF()}_buildCDF(){if(this.emissiveCount===0){this.cdfArray=new Float32Array(1),this.cdfArray[0]=0;return}this.cdfArray=new Float32Array(this.emissiveCount);let e=0;for(let t=0;t<this.emissiveCount;t++)e+=this.emissivePowerArray[t],this.cdfArray[t]=e;if(e>0)for(let t=0;t<this.emissiveCount;t++)this.cdfArray[t]/=e}sampleCDF(e){if(this.emissiveCount===0)return-1;if(this.emissiveCount===1)return 0;let t=0,n=this.emissiveCount-1;for(;t<n;){let r=Math.floor((t+n)/2);this.cdfArray[r]<e?t=r+1:n=r}return t}getGPUData(){return{emissiveIndices:this.emissiveIndicesArray,emissivePower:this.emissivePowerArray,emissiveCDF:this.cdfArray,emissiveCount:this.emissiveCount,totalPower:this.totalEmissivePower}}createEmissiveTexture(){if(this.emissiveCount===0)return new r.DataTexture(new Float32Array(4),1,1,r.RGBAFormat,r.FloatType);let e=new Float32Array(this.emissiveCount*4);for(let t=0;t<this.emissiveCount;t++){let n=t*4;e[n+0]=this.emissiveIndicesArray[t],e[n+1]=this.emissivePowerArray[t],e[n+2]=this.cdfArray[t],e[n+3]=0}let t=Math.ceil(Math.sqrt(this.emissiveCount)),n=Math.ceil(this.emissiveCount/t),i=t*n*4,a=new Float32Array(i);a.set(e);let o=new r.DataTexture(a,t,n,r.RGBAFormat,r.FloatType);return o.needsUpdate=!0,o.generateMipmaps=!1,o.minFilter=r.NearestFilter,o.magFilter=r.NearestFilter,Qs.debug(`emissive texture ${H.px(t,n)} · ${H.n(this.emissiveCount)} entries`),o}createEmissiveRawData(){if(this.emissiveCount===0)return new Float32Array(8);let e=new Float32Array(this.emissiveCount*8);for(let t=0;t<this.emissiveCount;t++){let n=this.emissiveTriangles[t],r=t*8;e[r+0]=n.triangleIndex,e[r+1]=n.power,e[r+2]=this.cdfArray[t],e[r+3]=n.instanceLeaf,e[r+4]=n.emissive.r*n.emissiveIntensity,e[r+5]=n.emissive.g*n.emissiveIntensity,e[r+6]=n.emissive.b*n.emissiveIntensity,e[r+7]=n.area}return Qs.debug(`emissive raw data ${H.n(this.emissiveCount)} entries (${H.mb(e.byteLength)})`),e}getStats(){if(this.emissiveCount===0)return{count:0,totalPower:0,averagePower:0,minPower:0,maxPower:0};let e=1/0,t=-1/0;for(let n=0;n<this.emissiveCount;n++){let r=this.emissivePowerArray[n];e=Math.min(e,r),t=Math.max(t,r)}return{count:this.emissiveCount,totalPower:this.totalEmissivePower,averagePower:this.totalEmissivePower/this.emissiveCount,minPower:e,maxPower:t}}updateMaterialEmissive(e,t,n,r,i){let a=Zs(t.emissive),o=t.emissiveIntensity||0,s=o>0&&(a.r>0||a.g>0||a.b>0);if(s!==this.emissiveTriangles.some(t=>t.materialIndex===e))return this.extractEmissiveTriangles(n,r,i),!0;if(!s)return!1;let c=.2126*a.r+.7152*a.g+.0722*a.b;for(let t of this.emissiveTriangles)t.materialIndex===e&&(t.power=c*o*t.area,t.emissive={r:a.r,g:a.g,b:a.b},t.emissiveIntensity=o);return!0}setHiddenMeshes(e){let t=new Set;for(let e of this.emissiveTriangles)t.add(e.meshIndex);let n=new Set;for(let r of e)t.has(r)&&n.add(r);let r=this._hiddenMeshes,i=n.size!==r.size;if(!i){for(let e of n)if(!r.has(e)){i=!0;break}}return this._hiddenMeshes=n,i}buildLightBVH(){let e=this._hiddenMeshes.size===0?this.emissiveTriangles:this.emissiveTriangles.filter(e=>!this._hiddenMeshes.has(e.meshIndex));this.emissiveCount=e.length,this.totalEmissivePower=0;for(let t of e)this.totalEmissivePower+=t.power;if(e.length===0)return this.lightBVHNodeData=new Float32Array(16),this.lightBVHNodeData[7]=1,this.lightBVHNodeData[14]=1,this.lightBVHNodeData[15]=-1,this.lightBVHNodeCount=1,this.emissiveBitTrailMap=new Float32Array(4).fill(-1),this.emissiveIndicesArray=new Int32Array,this.emissivePowerArray=new Float32Array,this._buildCDF(),this.emissiveTriangleData=new Float32Array(8),1;let{nodeData:t,nodeCount:n,sortedPerm:r,bitTrails:i}=new qs().build(e);this.lightBVHNodeData=t,this.lightBVHNodeCount=n,this._rebuildSortedEmissiveData(r,e),this.emissiveBitTrailMap=new Float32Array(Math.max(this._totalTriangleCount,1)).fill(-1);for(let t=0;t<r.length;t++){let n=e[r[t]].triangleIndex;this.emissiveBitTrailMap[n]=i[t]}return n}_rebuildSortedEmissiveData(e,t){let n=e.length;this.emissiveIndicesArray=new Int32Array(n),this.emissivePowerArray=new Float32Array(n);for(let r=0;r<n;r++){let n=e[r];this.emissiveIndicesArray[r]=t[n].triangleIndex,this.emissivePowerArray[r]=t[n].power}this._buildCDF();let r=new Float32Array(n*8);for(let i=0;i<n;i++){let n=t[e[i]],a=i*8;r[a+0]=n.triangleIndex,r[a+1]=n.power,r[a+2]=this.cdfArray[i],r[a+3]=n.instanceLeaf,r[a+4]=n.emissive.r*n.emissiveIntensity,r[a+5]=n.emissive.g*n.emissiveIntensity,r[a+6]=n.emissive.b*n.emissiveIntensity,r[a+7]=n.area}this.emissiveTriangleData=r,Qs.debug(`rebuilt sorted emissive data · ${H.n(n)} entries`)}clear(){this.emissiveTriangles=[],this.emissiveCount=0,this.totalEmissivePower=0,this.emissiveIndicesArray=null,this.emissivePowerArray=null,this.cdfArray=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this._totalTriangleCount=0,this._hiddenMeshes=new Set}};ke();var ec=class{constructor(e=`Build`,{namespace:t=`build`,level:n=`debug`}={}){this.label=e,this.level=n,this.logger=ve(t),this.entries=new Map,this.order=[],this.totalStart=performance.now()}start(e){return this.entries.set(e,{start:performance.now(),end:null}),this.order.includes(e)||this.order.push(e),this}end(e){let t=this.entries.get(e);return t&&(t.end=performance.now(),t.duration=t.end-t.start),this}getDuration(e){return this.entries.get(e)?.duration??0}print(e=[]){let t=performance.now()-this.totalStart,n=this.order.map(e=>{let t=this.entries.get(e)?.duration??0;return t>=1?`${e} ${Math.round(t)}ms`:null}).filter(Boolean),r=H.list([this.label,...e,H.ms(t)]);return this.level===`info`?this.logger.summary(r,n):this.logger.debug(H.list([r,n.join(` · `)])),{steps:Object.fromEntries(this.order.map(e=>[e,Math.round(this.entries.get(e)?.duration??0)])),total:Math.round(t)}}};gn();var tc=1<<20,nc=1<<21,rc=()=>new Promise(e=>setTimeout(e,0)),ic=[0,1,2,4,5,6,8,9,10];function ac(e,t,n,r=ic){let i=e.lanesPerRecord,a=r.length,o=0,s=0,c=0;for(;c<n;){let l=t+c,u=e.chunkFor(l),d=Math.min(e.recordsPerChunk-l%e.recordsPerChunk,n-c),f=e.baseOf(l);for(let e=0;e<d;e++,f+=i){let e=2166136261,t=2654435769;for(let n=0;n<a;n++){let i=u[f+r[n]];e=Math.imul(e^i,16777619),t=Math.imul(t+i|0,2246822507)^t>>>13}o=o+e>>>0,s=s+t>>>0}c+=d}return`${o.toString(16)}.${s.toString(16)}`}async function oc(e,t){let n=[],r=0;for(let{triOffset:i,triCount:a}of t)n.push(ac(e,i,a)),r+=a,r>=nc&&(r=0,await rc());return n}async function sc(e,t){let n=await e?.area(hn.SCENES).open(t);if(!n)return null;try{let e=await n.json(`index.json`),t=await n.file(`nodes.f32`),r=await n.file(`order.u32`);return e?.v!==2||!t||!r?(n.release(),null):{index:e,nodes:t,order:r,release:()=>n.release()}}catch{return n.release(),null}}async function cc(e,t,{index:n,bvh:r,orders:i,isStale:a,label:o=``}){let s=e?.area(hn.SCENES);if(!s)return!1;let c=n.totalNodes-n.tlasNodeCount,l=i.reduce((e,t)=>e+(t?.byteLength??0),0),u=await s.create(t,{label:`${o} (BVH)`,expectedBytes:c*64+l});if(!u)return!1;try{for(let e=n.tlasNodeCount;e<n.totalNodes;){if(a())throw Error(`scene changed while it was being stored`);let t=r.chunkFor(e),i=r.recordsPerChunk-e%r.recordsPerChunk,o=Math.min(i,n.totalNodes-e,tc),s=r.baseOf(e);await u.write(`nodes.f32`,t.subarray(s,s+o*16)),e+=o}for(let e of i)if(e)for(let t=0;t<e.length;t+=tc*4)await u.write(`order.u32`,e.subarray(t,Math.min(e.length,t+tc*4)));if(l===0&&await u.write(`order.u32`,new Uint8Array),a())throw Error(`scene changed while it was being stored`);return await u.writeJSON(`index.json`,n),await u.commit(),!0}catch{return await u.abort(),!1}}async function lc(e,t,n,r){for(let i=0;i<r;i+=tc){let a=Math.min(tc,r-i),o=await e.slice(i*64,(i+a)*64).arrayBuffer();t.setRecords(n+i,new Float32Array(o))}}async function uc(e,t,n){return new Uint32Array(await e.slice(t*4,(t+n)*4).arrayBuffer())}It();var dc=16,fc=G.POSITION_A_OFFSET,pc=G.POSITION_B_OFFSET,mc=G.POSITION_C_OFFSET;async function hc(e,t,n,r,{pause:i=null}={}){let a=e.lanesPerRecord,o=[new Float32Array(n),new Float32Array(n),new Float32Array(n)],[s,c,l]=o;for(let r=0;r<n;){let i=e.chunkFor(t+r),o=new Float32Array(i.buffer,i.byteOffset,i.length),u=Math.min(n,(((t+r)/e.recordsPerChunk|0)+1)*e.recordsPerChunk-t);for(let n=e.baseOf(t+r);r<u;r++,n+=a)s[r]=o[n+fc]+o[n+pc]+o[n+mc],c[r]=o[n+fc+1]+o[n+pc+1]+o[n+mc+1],l[r]=o[n+fc+2]+o[n+pc+2]+o[n+mc+2]}let u=new Uint32Array(n);for(let e=0;e<n;e++)u[e]=e;let d=[],f=(e,t)=>{if(t-e<=r)return d.push({start:e,count:t-e}),{piece:d.length-1};let n=e+(t-e>>1);return _c(u,o,gc(o,e,t),e,t,n),{left:f(e,n),right:f(n,t)}},p=f(0,n);return await i?.(),await vc(e,t,n,u,i),{order:u,pieces:d,tree:p}}function gc(e,t,n){let r=0,i=-1;for(let a=0;a<3;a++){let o=e[a],s=1/0,c=-1/0;for(let e=t;e<n;e++){let t=o[e];t<s&&(s=t),t>c&&(c=t)}c-s>i&&(i=c-s,r=a)}return r}function _c(e,t,n,r,i,a){let o=t[n],[s,c,l]=t,u=(t,n)=>{let r=e[t];e[t]=e[n],e[n]=r,r=s[t],s[t]=s[n],s[n]=r,r=c[t],c[t]=c[n],c[n]=r,r=l[t],l[t]=l[n],l[n]=r},d=2654435769,f=()=>(d^=d<<13,d^=d>>>17,d^=d<<5,o[r+(d>>>0)%(i-r)]);for(;i-r>1;){let e=f(),t=f(),n=f(),s=e<t?t<n?t:e<n?n:e:e<n?e:t<n?n:t,c=r,l=r,d=i;for(;l<d;){let e=o[l];e<s?u(c++,l++):e>s?u(l,--d):l++}if(a<c)i=c;else if(a>=d)r=d;else return}}async function vc(e,t,n,r,i){let a=e.lanesPerRecord,o=new Uint32Array(a),s=new Uint8Array(n),c=0;for(let l=0;l<n;l++){if(s[l]||(s[l]=1,r[l]===l))continue;let n=e.chunkFor(t+l),u=e.baseOf(t+l);for(let e=0;e<a;e++)o[e]=n[u+e];for(let d=l;;){let f=r[d],p=n,m=u;if(f===l){for(let e=0;e<a;e++)p[m+e]=o[e];break}n=e.chunkFor(t+f),u=e.baseOf(t+f);for(let e=0;e<a;e++)p[m+e]=n[u+e];s[f]=1,d=f,i&&!(++c&1048575)&&await i()}}}function yc(e,t,n,r){let i=t.length-1,a=[],o=i;for(let{bvhData:e}of n)a.push(o),o+=e.length/dc;let s=new Float32Array(i*dc),c=new Uint32Array(s.buffer),l=[s],u=new Uint32Array(r.length);for(let e=0;e<t.length;e++){let{bvhData:i,originalToBvh:o}=n[e];n[e].bvhData=n[e].originalToBvh=null;let s=a[e],{start:c,count:d}=t[e];Hi(new Uint32Array(i.buffer,i.byteOffset,i.length),s,c),l.push(i);for(let e=0;e<d;e++)u[r[c+e]]=c+(o?o[e]:e)}let d=0,f=e=>{if(e.piece!==void 0)return{index:a[e.piece],box:n[e.piece].aabb};let t=d++,r=f(e.left),i=f(e.right),o=t*dc;return s[o]=r.box[0],s[o+1]=r.box[1],s[o+2]=r.box[2],c[o+3]=r.index,s[o+4]=r.box[3],s[o+5]=r.box[4],s[o+6]=r.box[5],c[o+7]=i.index,s[o+8]=i.box[0],s[o+9]=i.box[1],s[o+10]=i.box[2],s[o+12]=i.box[3],s[o+13]=i.box[4],s[o+14]=i.box[5],{index:t,box:[0,1,2].map(e=>Math.min(r.box[e],i.box[e])).concat([3,4,5].map(e=>Math.max(r.box[e],i.box[e])))}};return f(e),{bvhData:l,nodeCount:o,originalToBvh:u}}var bc,xc=g((()=>{bc=`11.9.0`})),Sc,Cc=g((()=>{xc(),Sc=bc}));function wc(e,t,n=Tc){return e>=n&&t/Ec<e/3}var Tc,Ec,Dc=g((()=>{Tc=1e4,Ec=15e5}));Cc(),Dc();var Oc="const e={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_PACKED_OFFSET:3,NORMAL_B_PACKED_OFFSET:7,NORMAL_C_PACKED_OFFSET:11,UV_AB_OFFSET:12,UV_C_OFFSET:16,MATERIAL_FLAGS_OFFSET:18,MESH_INDEX_OFFSET:19};function t(e,t,n){let r=Math.sqrt(e*e+t*t+n*n);r>0?(e/=r,t/=r,n/=r):(e=0,t=0,n=1);let i=Math.abs(e)+Math.abs(t)+Math.abs(n),a=e/i,o=t/i;if(n<0){let e=a,t=o;a=(1-Math.abs(t))*(e>=0?1:-1),o=(1-Math.abs(e))*(t>=0?1:-1)}let s=Math.round(Math.min(1,Math.max(-1,a))*32767)&65535;return((Math.round(Math.min(1,Math.max(-1,o))*32767)&65535)<<16|s)>>>0}const n={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826,CLUSTER_LEAF:1073741827},r=new Float32Array(1),i=new Uint32Array(r.buffer);function a(e){let t=Math.fround(e);return t<=e?t:(r[0]=t,i[0]+=t>0?-1:1,r[0])}function o(e,t){return Math.max(Math.abs(e),Math.abs(t),1e-30)*2**-21}const s=[2,4,5];function c(e,t,n,r,i,c,u){let d=0;for(let f=0;f<3;f++){let p=1/0,m=-1/0;for(let e=0;e<i;e++)p=Math.min(p,r[e*6+f]),m=Math.max(m,r[e*6+3+f]);if(c&&(c[u+f]=p,c[u+3+f]=m),!(p<=m)){e[n+s[f]]=l,t[n+6+f]=0,t[n+9+f]=0;continue}let h=o(p,m),g=a(p-h),_=Math.max(-126,Math.ceil(Math.log2((m+h-g)/255)));for(;Math.fround(g+255*2**_)<m+h;)_++;let v=2**_;e[n+s[f]]=g,d|=_+127<<f*8;let y=0,b=0;for(let e=0;e<i;e++){let t=r[e*6+f],n=r[e*6+3+f],i=o(t,n);y|=Math.max(0,Math.min(255,Math.floor((t-i-g)/v)))<<e*8,b|=Math.max(0,Math.min(255,Math.ceil((n+i-g)/v)))<<e*8}t[n+6+f]=y>>>0,t[n+9+f]=b>>>0}t[n+1]=d>>>0}const l=1e30;n.TRIANGLE_LEAF;const u=e=>e>=2147483648,d=e=>~e>>>0>>>4,f=e=>~e&15,p=e.FLOATS_PER_TRIANGLE,m=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),h=e=>e instanceof Uint32Array?e:new Uint32Array(e.buffer,e.byteOffset,e.length),g=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:e,idx:t?e.viewAs(Uint32Array):h(e)}},_=(e,t)=>e.chunked?e.f.chunkFor(t):e.f,v=(e,t)=>e.chunked?e.idx.chunkFor(t):e.idx,y=(e,t)=>e.chunked?e.chunked.baseOf(t):t*x,b=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:t?t.viewAs(Float32Array):m(e),u:t?e:h(e)}},x=16,S=n.TRIANGLE_LEAF,C=n.BLAS_POINTER_LEAF,w=n.CLUSTER_LEAF;function T(e,t,n,r,i,a){if(n[r]>n[r+3]){for(let e=0;e<6;e++)i[a+e]=n[r+e];return}let o=e[t+4],s=e[t+5],c=e[t+6],l=e[t+7],u=e[t+8],d=e[t+9],f=e[t+10],p=e[t+11],m=e[t+12],h=e[t+13],g=e[t+14],_=e[t+15],v=d*g-f*h,y=f*m-u*g,b=u*h-d*m,x=o*v+s*y+c*b,S=o===1&&d===1&&g===1&&s===0&&c===0&&u===0&&f===0&&m===0&&h===0&&l===0&&p===0&&_===0,C=(Math.abs(o)+Math.abs(s)+Math.abs(c))*(Math.abs(u)+Math.abs(d)+Math.abs(f))*(Math.abs(m)+Math.abs(h)+Math.abs(g));if(S||!Number.isFinite(x)||Math.abs(x)<=1e-12*C){for(let e=0;e<6;e++)i[a+e]=n[r+e];return}let w=1/x,T=v*w,E=y*w,D=b*w,O=(c*h-s*g)*w,k=(o*g-c*m)*w,A=(s*m-o*h)*w,j=(s*f-c*d)*w,M=(c*u-o*f)*w,N=(o*d-s*u)*w,P=1/0,F=1/0,I=1/0,L=-1/0,R=-1/0,z=-1/0;for(let e=0;e<8;e++){let t=(e&1?n[r+3]:n[r])-l,i=(e&2?n[r+4]:n[r+1])-p,a=(e&4?n[r+5]:n[r+2])-_,o=T*t+O*i+j*a,s=E*t+k*i+M*a,c=D*t+A*i+N*a;o<P&&(P=o),o>L&&(L=o),s<F&&(F=s),s>R&&(R=s),c<I&&(I=c),c>z&&(z=c)}i[a]=P,i[a+1]=F,i[a+2]=I,i[a+3]=L,i[a+4]=R,i[a+5]=z}function E(t,n,r,i,a){let o=e.POSITION_A_OFFSET,s=e.POSITION_B_OFFSET,c=e.POSITION_C_OFFSET,l=1/0,u=1/0,d=1/0,f=-1/0,m=-1/0,h=-1/0;for(let e=0;e<r;e++){let r=n+e,i=t.chunked?t.f.chunkFor(r):t.f,a=t.chunked?t.chunked.baseOf(r):r*p;l=Math.min(l,i[a+o],i[a+s],i[a+c]),u=Math.min(u,i[a+o+1],i[a+s+1],i[a+c+1]),d=Math.min(d,i[a+o+2],i[a+s+2],i[a+c+2]),f=Math.max(f,i[a+o],i[a+s],i[a+c]),m=Math.max(m,i[a+o+1],i[a+s+1],i[a+c+1]),h=Math.max(h,i[a+o+2],i[a+s+2],i[a+c+2])}i[a]=l,i[a+1]=u,i[a+2]=d,i[a+3]=f,i[a+4]=m,i[a+5]=h}const D=new Float32Array(12),O=(e,t)=>e[t]>=l*.5;function k(e,t,n,r){let i=n[r]>n[r+3];e[t]=i?l:n[r],e[t+1]=i?l:n[r+1],e[t+2]=i?l:n[r+2],e[t+4]=i?l:n[r+3],e[t+5]=i?l:n[r+4],e[t+6]=i?l:n[r+5]}function A(e,t,n,r){let i=_(e,t),a=v(e,t),o=y(e,t);if(a[o+3]===S){E(n,a[o],a[o+1],r,0);return}let s=!O(i,o),c=!O(i,o+8);for(let e=0;e<3;e++)r[e]=Math.min(s?i[o+e]:1/0,c?i[o+8+e]:1/0),r[3+e]=Math.max(s?i[o+4+e]:-1/0,c?i[o+12+e]:-1/0)}const j=new Float32Array(16),M=new Float32Array(6),N=new Float32Array(24);function P(e,t,n,r,i,a){let o=_(e,t),s=v(e,t),l=y(e,t),u=s[l]&268435455,d=(s[l]>>>28&3)+1;for(let t=0;t<d;t++){let i=s[l+12+t];if(A(e,i&1073741823,n,M),i&1073741824){for(let e=0;e<6;e++)N[t*6+e]=M[e];continue}let a=r*16+(u+t)*3*4;for(let t=0;t<12;t++){let n=a+t>>4;j[4+t]=_(e,n)[y(e,n)+(a+t&15)]}T(j,0,M,0,N,t*6)}c(o,s,l,N,d,i,a)}function F(e,t,n,r,i,a=-1){let o=_(e,t),s=v(e,t),c=y(e,t),l=(t-i)*6,p=s[c+3];if(p===S){E(n,s[c],s[c+1],r,l);return}if(p===w){P(e,t,n,a,r,l);return}if(p===C){T(o,c,r,(s[c]-i)*6,r,l);return}let m=s[c+7],h=r,g=(p-i)*6;u(p)&&(E(n,d(p),f(p),D,0),h=D,g=0);let b=r,x=(m-i)*6;u(m)&&(E(n,d(m),f(m),D,6),b=D,x=6),k(o,c,h,g),k(o,c+8,b,x);for(let e=0;e<3;e++)r[l+e]=Math.min(h[g+e],b[x+e]),r[l+3+e]=Math.max(h[g+3+e],b[x+3+e])}var I=class{constructor(){this._bounds=null,this._boundsNodeCount=0,this._tlasBounds=null,this._rootBox=null}updateTrianglePositions(n,r,i){let a=i.length,o=b(n);for(let n=0;n<a;n++){let a=i[n],s=o.chunked?o.f.chunkFor(n):o.f,c=o.chunked?o.u.chunkFor(n):o.u,l=o.chunked?o.chunked.baseOf(n):n*p,u=a*9,d=r[u],f=r[u+1],m=r[u+2],h=r[u+3],g=r[u+4],_=r[u+5],v=r[u+6],y=r[u+7],b=r[u+8];s[l+e.POSITION_A_OFFSET]=d,s[l+e.POSITION_A_OFFSET+1]=f,s[l+e.POSITION_A_OFFSET+2]=m,s[l+e.POSITION_B_OFFSET]=h,s[l+e.POSITION_B_OFFSET+1]=g,s[l+e.POSITION_B_OFFSET+2]=_,s[l+e.POSITION_C_OFFSET]=v,s[l+e.POSITION_C_OFFSET+1]=y,s[l+e.POSITION_C_OFFSET+2]=b;let x=h-d,S=g-f,C=_-m,w=v-d,T=y-f,E=b-m,D=t(S*E-C*T,C*w-x*E,x*T-S*w);c[l+e.NORMAL_A_PACKED_OFFSET]=D,c[l+e.NORMAL_B_PACKED_OFFSET]=D,c[l+e.NORMAL_C_PACKED_OFFSET]=D}}refitRange(e,t,n,r){let i=b(t);r>this._boundsNodeCount&&(this._bounds=new Float32Array(r*6),this._boundsNodeCount=r);let a=g(e);for(let e=n+r-1;e>=n;e--)F(a,e,i,this._bounds,n)}refitPartial(e,t,n,r,i=null,a=-1){for(let r=0;r<n.length;r+=2)this.refitRange(e,t,n[r],n[r+1]);let o=b(t),s=g(e);i&&this.refitGroups(s,o,i[0],i[1]),(!this._tlasBounds||this._tlasBounds.length<r*6)&&(this._tlasBounds=new Float32Array(r*6));let c=this._tlasBounds;for(let e=r-1;e>=0;e--){let t=v(s,e),n=y(s,e);t[n+3]===C?(A(s,t[n],o,M),T(_(s,e),n,M,0,c,e*6)):F(s,e,o,c,0,a)}}refitGroups(e,t,n,r){let i=this._groupBox||=new Float32Array(6);for(let a=n+r-1;a>=n;a--){let n=_(e,a),r=v(e,a),o=y(e,a);r[o+3]!==S&&(A(e,r[o+3],t,i),k(n,o,i,0),A(e,r[o+7],t,i),k(n,o+8,i,0))}}refit(e,t,n,r=-1){let i=b(t);n!==this._boundsNodeCount&&(this._bounds=new Float32Array(n*6),this._boundsNodeCount=n);let a=g(e);for(let e=n-1;e>=0;e--)F(a,e,i,this._bounds,0,r)}};const L=64*1024*1024;function R(e,t,n){return n?new e(new SharedArrayBuffer(t*e.BYTES_PER_ELEMENT)):new e(t)}var z=class e{constructor(e,t,n,r=L,i=!1){let a=t*n.BYTES_PER_ELEMENT,o=Math.max(1,Math.floor(r/a));this.recordCount=e,this.lanesPerRecord=t,this.LaneType=n,this.recordsPerChunk=e<=o?Math.max(e,1):o,this.shared=i,this.chunks=[];let s=e;for(;s>0;){let e=Math.min(s,this.recordsPerChunk);this.chunks.push(R(n,e*t,i)),s-=e}this.chunks.length===0&&this.chunks.push(R(n,0,i))}static adopt(t,n,r,i){let a=Object.create(e.prototype);return a.recordCount=n,a.lanesPerRecord=r,a.LaneType=t[0]?.constructor??null,a.recordsPerChunk=i,a.chunks=t,a.shared=typeof SharedArrayBuffer<`u`&&t[0]?.buffer instanceof SharedArrayBuffer,a}static lazy(t,n,r,i=L,a=!1){let o=Math.max(1,Math.floor(i/(n*r.BYTES_PER_ELEMENT))),s=Object.create(e.prototype);return s.recordCount=t,s.lanesPerRecord=n,s.LaneType=r,s.recordsPerChunk=t<=o?Math.max(t,1):o,s.shared=a,s.chunks=Array(Math.max(1,Math.ceil(t/s.recordsPerChunk))),s._views=[],s}_materialize(e){if(this._owner)return this._owner._materialize(e),this.chunks[e];let t=e*this.recordsPerChunk,n=Math.min(this.recordsPerChunk,this.recordCount-t)*this.lanesPerRecord,r=this.chunks[e]=R(this.LaneType,n,this.shared);for(let t of this._liveViews())t.chunks[e]=new t.LaneType(r.buffer,r.byteOffset,r.byteLength/t.LaneType.BYTES_PER_ELEMENT);return r}materializeAll(){for(let e=0;e<this.chunks.length;e++)!this.chunks[e]&&!this._spilled?.has(e)&&this._materialize(e);return this}get chunkCount(){return this.chunks.length}get single(){return this.chunks.length===1?this.chunks[0]:null}get byteLength(){let e=0;for(let t of this.chunks)t&&(e+=t.byteLength);return e}chunkFor(e){let t=e/this.recordsPerChunk|0,n=this.chunks[t];if(n)return n;if(this._spilled?.has(t))throw Error(`ChunkedRecords: chunk ${t} is on disk — await ensureResident() before touching record ${e}`);return this._materialize(t)}async spill(e,{keep:t=()=>!1}={}){if(this._owner)throw Error(`ChunkedRecords: spill the storage, not a view of it`);this._store=e,this._spilled??=new Set;let n=0;for(let r=0;r<this.chunks.length;r++){let i=this.chunks[r];if(!(!i||t(r))){await e.write(r,i),this.chunks[r]=null;for(let e of this._liveViews())e.chunks[r]=null;this._spilled.add(r),n+=i.byteLength}}return n}async spillChunk(e,t){let n=this.chunks[e];if(!n)return 0;this._store=t,this._spilled??=new Set,await t.write(e,n),this.chunks[e]=null;for(let t of this._liveViews())t.chunks[e]=null;return this._spilled.add(e),n.byteLength}async ensureResident(e=0,t=this.recordCount){if(!this._spilled?.size||t<=0)return;let n=e/this.recordsPerChunk|0,r=(e+t-1)/this.recordsPerChunk|0;for(let e=n;e<=r;e++){if(!this._spilled.has(e))continue;let t=Math.min(this.recordsPerChunk,this.recordCount-e*this.recordsPerChunk)*this.lanesPerRecord,n=R(this.LaneType,t,this.shared),r=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);this._store.readInto?await this._store.readInto(e,r):r.set(new Uint8Array(await this._store.read(e,r.byteLength))),this.chunks[e]=n;for(let t of this._liveViews())t.chunks[e]=new t.LaneType(n.buffer,n.byteOffset,n.byteLength/t.LaneType.BYTES_PER_ELEMENT);this._spilled.delete(e)}}_liveViews(){return this._weakViews&&=this._weakViews.filter(e=>e.deref()),[...this._views??[],...(this._weakViews??[]).map(e=>e.deref())]}isResident(e=0,t=this.recordCount){if(!this._spilled?.size||t<=0)return!0;let n=e/this.recordsPerChunk|0,r=(e+t-1)/this.recordsPerChunk|0;for(let e=n;e<=r;e++)if(this._spilled.has(e))return!1;return!0}get spilledChunks(){return this._spilled?.size??0}baseOf(e){return e%this.recordsPerChunk*this.lanesPerRecord}isContiguous(e,t){return t<=0?!0:(e/this.recordsPerChunk|0)==((e+t-1)/this.recordsPerChunk|0)}slice(e,t){let n=this.baseOf(e),r=t*this.lanesPerRecord;if(this.isContiguous(e,t))return this.chunkFor(e).subarray(n,n+r);let i=new this.LaneType(r);return this.readRecords(e,t,i),i}readRecords(e,t,n){let r=0;for(;r<t;){let i=e+r,a=this.chunkFor(i),o=this.baseOf(i),s=this.recordsPerChunk-i%this.recordsPerChunk,c=Math.min(s,t-r);n.set(a.subarray(o,o+c*this.lanesPerRecord),r*this.lanesPerRecord),r+=c}return n}setRecords(e,t){let n=t.length/this.lanesPerRecord,r=0;for(;r<n;){let i=e+r,a=this.chunkFor(i),o=this.baseOf(i),s=this.recordsPerChunk-i%this.recordsPerChunk,c=Math.min(s,n-r);a.set(t.subarray(r*this.lanesPerRecord,(r+c)*this.lanesPerRecord),o),r+=c}}copyOf(e,t){return this.readRecords(e,t,new this.LaneType(t*this.lanesPerRecord))}trimTo(t){let n=Math.max(1,Math.ceil(t/this.recordsPerChunk)),r=this.chunks.slice(0,n),i=(t-(n-1)*this.recordsPerChunk)*this.lanesPerRecord,a=r[n-1];return a.length>i&&(r[n-1]=a.subarray(0,Math.max(0,i))),e.adopt(r,t,this.lanesPerRecord,this.recordsPerChunk)}grow(e){if(e<=this.recordCount)return;let t=this.chunks.length-1,n=(e,t)=>Math.min(this.recordsPerChunk,t-e*this.recordsPerChunk)*this.lanesPerRecord,r=this.chunks[t];this.recordCount=e;for(let t of this._liveViews())t.recordCount=e;if(this.chunks.length*this.recordsPerChunk<e){this.chunks.length=Math.ceil(e/this.recordsPerChunk);for(let e of this._liveViews())e.chunks.length=this.chunks.length}if(r&&r.length<n(t,e)){let i=R(this.LaneType,n(t,e),this.shared);i.set(r),this.chunks[t]=i;for(let e of this._liveViews())e.chunks[t]=new e.LaneType(i.buffer,i.byteOffset,i.byteLength/e.LaneType.BYTES_PER_ELEMENT)}else if(!r&&this._spilled?.has(t))throw Error(`ChunkedRecords: cannot grow past chunk ${t}, which is on disk`)}release(e,t){let n=this.recordsPerChunk,r=Math.ceil(e/n),i=Math.floor((e+t)/n),a=0;for(let e=r;e<i;e++){let t=this.chunks[e];if(t){a+=t.byteLength,this.chunks[e]=void 0;for(let t of this._liveViews())t.chunks[e]=void 0}}return a}trimInPlace(e){let t=Math.max(1,Math.ceil(e/this.recordsPerChunk)),n=Math.max(0,(e-(t-1)*this.recordsPerChunk)*this.lanesPerRecord),r=[this,...this._liveViews()];for(let i of r){i.chunks.length=t;let r=i.chunks[t-1];r&&r.length>n&&(i.chunks[t-1]=r.subarray(0,n)),i.recordCount=e}if(this._spilled)for(let e of this._spilled)e>=t&&this._spilled.delete(e);return this}viewAs(t){let n=e=>new t(e.buffer,e.byteOffset,e.byteLength/t.BYTES_PER_ELEMENT),r=e.adopt(this.chunks.map(e=>e?n(e):void 0),this.recordCount,this.lanesPerRecord,this.recordsPerChunk);return r.LaneType=t,r._owner=this,this._views?this._views.push(r):(this._weakViews??=[]).push(new WeakRef(r)),r._spilled=this._spilled??=new Set,r}};const B=new I;let V=null,H=null,U=0;self.onmessage=function(e){let{type:t}=e.data;if(t===`init`){V=z.adopt(e.data.sharedBvhBufs.map(e=>new Float32Array(e)),e.data.bvhRecordCount,16,e.data.bvhRecordsPerChunk),H=z.adopt(e.data.sharedTriBufs.map(e=>new Uint32Array(e)),e.data.triRecordCount,e.data.triLanesPerRecord,e.data.triRecordsPerChunk),U=V.recordCount;return}if(t===`refit`)try{let t=performance.now(),{blasRanges:n,tlasNodeCount:r,groupRange:i,treeNodeCount:a,recordNodeStart:o=-1}=e.data;n?B.refitPartial(V,H,n,r,i,o):B.refit(V,H,a??U,o),self.postMessage({type:`refitComplete`,refitTimeMs:performance.now()-t})}catch(e){console.error(`[BVHRefitWorker] Refit error:`,e),self.postMessage({type:`error`,error:e.message})}};",kc=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Oc],{type:`text/javascript;charset=utf-8`});function Ac(e){let t;try{if(t=kc&&(self.URL||self.webkitURL).createObjectURL(kc),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Oc),{type:`module`,name:e?.name})}}var jc="const e={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826,CLUSTER_LEAF:1073741827};new Uint32Array(new Float32Array(1).buffer);function t(e){return new Uint32Array(e.buffer,e.byteOffset,e.length)}function n(e,t){if(e>=1073741824)throw RangeError(`${t} is ${e.toLocaleString()}, at or past the BVH index limit of ${1073741824 .toLocaleString()}. Node indices are stored as u32 bit patterns and the leaf tags occupy everything above that.`);return e}const r=Float64Array.from([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);Object.freeze([]);function i(e,t){return e[t]*(e[t+5]*e[t+10]-e[t+6]*e[t+9])-e[t+4]*(e[t+1]*e[t+10]-e[t+2]*e[t+9])+e[t+8]*(e[t+1]*e[t+6]-e[t+2]*e[t+5])}function a(e,t,n){let a=i(e,t);if(!Number.isFinite(a)||Math.abs(a)<1e-20)return n.set(r),n;let o=1/a;return n[0]=(e[t+5]*e[t+10]-e[t+6]*e[t+9])*o,n[1]=(e[t+2]*e[t+9]-e[t+1]*e[t+10])*o,n[2]=(e[t+1]*e[t+6]-e[t+2]*e[t+5])*o,n[3]=0,n[4]=(e[t+6]*e[t+8]-e[t+4]*e[t+10])*o,n[5]=(e[t]*e[t+10]-e[t+2]*e[t+8])*o,n[6]=(e[t+2]*e[t+4]-e[t]*e[t+6])*o,n[7]=0,n[8]=(e[t+4]*e[t+9]-e[t+5]*e[t+8])*o,n[9]=(e[t+1]*e[t+8]-e[t]*e[t+9])*o,n[10]=(e[t]*e[t+5]-e[t+1]*e[t+4])*o,n[11]=0,n[12]=-(n[0]*e[t+12]+n[4]*e[t+13]+n[8]*e[t+14]),n[13]=-(n[1]*e[t+12]+n[5]*e[t+13]+n[9]*e[t+14]),n[14]=-(n[2]*e[t+12]+n[6]*e[t+13]+n[10]*e[t+14]),n[15]=1,n}function o(e,t){for(let n=0;n<16;n++)if(e[t+n]!==r[n])return!1;return!0}const s=e=>e<32?e:32,c=new Float64Array(16);var l=class r{constructor(){this._flatBuffer=null,this._flatBufferCapacity=0,this._binCounts=new Int32Array(96),this._binBounds=new Float64Array(576),this._binSuffix=new Float64Array(32),this._binSuffixCount=new Int32Array(32),this._order=null,this._stackI=null,this._stackB=null,this._stackFrames=0,this._sortScratch=[],this._suffix=null,this._bounds=new Float64Array(12),this._extent=new Float64Array(3),this._cMin=new Float64Array(3)}static nodeCountFor(e){return e>0?e*2-1:0}releaseFlattenBuffer(){this._flatBuffer=null,this._flatBufferCapacity=0}build(e){let t=e.clusterCount>0,n=t?e.clusterBounds:new Float64Array(e.entryCount*6);t||e.writeEntryWorldAABBs(n);let i=this.buildStructure(n,t?e.clusterCount:e.entryCount);return r.fillLeaves(i.data,i.nodeCount,e),i}buildStructure(i,a){let o=r.nodeCountFor(a);if(a===0)return{data:new Float32Array,nodeCount:0};n(o,`TLAS node count`);let s=o*16;s>this._flatBufferCapacity&&(this._flatBuffer=new Float32Array(s),this._flatBufferCapacity=s);let c=this._flatBuffer,l=t(c);(!this._order||this._order.length<a)&&(this._order=new Int32Array(a));let u=this._order;for(let e=0;e<a;e++)u[e]=e;this._ensureStack(64);let d=0,f=0,p=0,m=a,h=this._bounds;this._rangeBounds(i,u,p,m,h,0);let g=h[0],_=h[1],v=h[2],y=h[3],b=h[4],x=h[5];for(;;){if(m-p===1){let t=f*16;l[t]=0,l[t+1]=u[p],c[t+2]=0,l[t+3]=e.BLAS_POINTER_LEAF}else{let e=this._partition(i,u,p,m,g,_,v,y,b,x),t=e-p,n=f+1,r=n+(t*2-1),a=f*16;c[a]=h[0],c[a+1]=h[1],c[a+2]=h[2],l[a+3]=n,c[a+4]=h[3],c[a+5]=h[4],c[a+6]=h[5],l[a+7]=r,c[a+8]=h[6],c[a+9]=h[7],c[a+10]=h[8],c[a+11]=0,c[a+12]=h[9],c[a+13]=h[10],c[a+14]=h[11],c[a+15]=0;let o=t<=m-e,s=o?0:6,S=o?6:0;d=this._push(d,o?r:n,o?e:p,o?m:e,h,S),f=o?n:r,o?m=e:p=e,g=h[s],_=h[s+1],v=h[s+2],y=h[s+3],b=h[s+4],x=h[s+5];continue}if(d===0)break;d--;let t=d*3,n=d*6;f=this._stackI[t],p=this._stackI[t+1],m=this._stackI[t+2],g=this._stackB[n],_=this._stackB[n+1],v=this._stackB[n+2],y=this._stackB[n+3],b=this._stackB[n+4],x=this._stackB[n+5]}return{data:c.subarray(0,s),nodeCount:o}}_push(e,t,n,r,i,a){e>=this._stackFrames&&this._ensureStack(this._stackFrames*2);let o=e*3,s=e*6;this._stackI[o]=t,this._stackI[o+1]=n,this._stackI[o+2]=r;for(let e=0;e<6;e++)this._stackB[s+e]=i[a+e];return e+1}_ensureStack(e){if(this._stackFrames>=e)return;let t=new Int32Array(e*3),n=new Float64Array(e*6);this._stackI&&(t.set(this._stackI),n.set(this._stackB)),this._stackI=t,this._stackB=n,this._stackFrames=e}static fillLeaves(n,i,a){let o=t(n);if(a.clusterCount>0){for(let t=0;t<i;t++){let r=t*16;o[r+3]===e.BLAS_POINTER_LEAF&&a.writeClusterLeaf(n,o,r,o[r+1],a.clusterWorld,t)}return}for(let t=0;t<i;t++){let i=t*16;if(o[i+3]!==e.BLAS_POINTER_LEAF)continue;let s=o[i+1]&1073741823;o[i]=a.entryRoot(s),n[i+2]=+!!a.entryVisible(s),r.writeLeafMatrix(n,o,i,a,a.repOf(s),s),a.setLeafOf(s,t)}}static writeLeafMatrix(e,t,n,r,i,s=i){let l=c,u=r.matrixRow(i),d=r.rowArray;a(d,u,l),e[n+4]=l[0],e[n+5]=l[4],e[n+6]=l[8],e[n+7]=l[12],e[n+8]=l[1],e[n+9]=l[5],e[n+10]=l[9],e[n+11]=l[13],e[n+12]=l[2],e[n+13]=l[6],e[n+14]=l[10],e[n+15]=l[14],t[n+1]=(s|(o(d,u)?1073741824:0))>>>0}_partition(e,t,n,r,i,a,o,s,c,l){let u=r-n,d=0;if(u===2)d=n+1;else if(u<=8)d=n+(u>>1),this._insertionSortRange(e,t,n,r,this._widestCentroidAxis(e,t,n,r));else{if(d=this._binnedSplit(e,t,n,r,i,a,o,s,c,l),d>n&&d<r)return d;if(d=this._sweepSplit(e,t,n,r,i,a,o,s,c,l),!(d>n&&d<r)){let f=s-i,p=c-a,m=l-o,h=p>f&&p>m?1:m>f?2:0;this._sortRange(e,t,n,r,h),d=n+(u>>1)}}let f=this._bounds;return this._rangeBounds(e,t,n,d,f,0),this._rangeBounds(e,t,d,r,f,6),d}_binnedSplit(e,t,n,r,i,a,o,c,l,u){let d=this._surfaceArea(i,a,o,c,l,u);if(!(d>0)||!isFinite(d))return n;let f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,_=-1/0;for(let i=n;i<r;i++){let n=t[i]*6,r=(e[n]+e[n+3])*.5,a=(e[n+1]+e[n+4])*.5,o=(e[n+2]+e[n+5])*.5;r<f&&(f=r),r>h&&(h=r),a<p&&(p=a),a>g&&(g=a),o<m&&(m=o),o>_&&(_=o)}let v=this._extent,y=this._cMin;v[0]=h-f,v[1]=g-p,v[2]=_-m,y[0]=f,y[1]=p,y[2]=m;let b=1/0,x=-1,S=-1,C=this._binCounts,w=this._binBounds,T=v[0]>1e-12,E=v[1]>1e-12,D=v[2]>1e-12;if(!T&&!E&&!D)return n;let O=s(r-n),k=T?O/v[0]:0,A=E?O/v[1]:0,j=D?O/v[2]:0;C.fill(0,0,O*3);for(let e=0;e<O*3;e++){let t=e*6;w[t]=w[t+1]=w[t+2]=1/0,w[t+3]=w[t+4]=w[t+5]=-1/0}for(let i=n;i<r;i++){let n=t[i]*6,r=e[n],a=e[n+1],o=e[n+2],s=e[n+3],c=e[n+4],l=e[n+5];for(let e=0;e<3;e++){let t=e===0?k:e===1?A:j;if(t===0)continue;let n=((e===0?(r+s)*.5:e===1?(a+c)*.5:(o+l)*.5)-y[e])*t|0;n<0?n=0:n>=O&&(n=O-1),n+=e*O,C[n]++;let i=n*6;r<w[i]&&(w[i]=r),a<w[i+1]&&(w[i+1]=a),o<w[i+2]&&(w[i+2]=o),s>w[i+3]&&(w[i+3]=s),c>w[i+4]&&(w[i+4]=c),l>w[i+5]&&(w[i+5]=l)}}for(let e=0;e<3;e++){if(!(v[e]>1e-12))continue;let t=e*O,n=this._binSuffix,r=this._binSuffixCount,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0,u=0;for(let e=O-1;e>=1;e--){let d=(t+e)*6;w[d]<i&&(i=w[d]),w[d+1]<a&&(a=w[d+1]),w[d+2]<o&&(o=w[d+2]),w[d+3]>s&&(s=w[d+3]),w[d+4]>c&&(c=w[d+4]),w[d+5]>l&&(l=w[d+5]),u+=C[t+e],n[e]=u?this._surfaceArea(i,a,o,s,c,l):0,r[e]=u}let f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,_=-1/0,y=0;for(let i=1;i<O;i++){let a=(t+i-1)*6;if(w[a]<f&&(f=w[a]),w[a+1]<p&&(p=w[a+1]),w[a+2]<m&&(m=w[a+2]),w[a+3]>h&&(h=w[a+3]),w[a+4]>g&&(g=w[a+4]),w[a+5]>_&&(_=w[a+5]),y+=C[t+i-1],y===0||r[i]===0)continue;let o=1+(this._surfaceArea(f,p,m,h,g,_)*y+n[i]*r[i])/d;o<b&&(b=o,x=e,S=i)}}if(x<0)return n;let M=O/v[x],N=y[x],P=this._bounds;P[0]=P[1]=P[2]=P[6]=P[7]=P[8]=1/0,P[3]=P[4]=P[5]=P[9]=P[10]=P[11]=-1/0;let F=n,I=r-1;for(;F<=I;){let n=t[F]*6,r=((e[n+x]+e[n+3+x])*.5-N)*M|0;r<0?r=0:r>=O&&(r=O-1);let i=r<S?0:6;if(e[n]<P[i]&&(P[i]=e[n]),e[n+1]<P[i+1]&&(P[i+1]=e[n+1]),e[n+2]<P[i+2]&&(P[i+2]=e[n+2]),e[n+3]>P[i+3]&&(P[i+3]=e[n+3]),e[n+4]>P[i+4]&&(P[i+4]=e[n+4]),e[n+5]>P[i+5]&&(P[i+5]=e[n+5]),i===0)F++;else{let e=t[F];t[F]=t[I],t[I]=e,I--}}return F}_sweepSplit(e,t,n,r,i,a,o,s,c,l){let u=r-n,d=this._surfaceArea(i,a,o,s,c,l);if(!(d>0)||!isFinite(d))return n;let f=this._suffixBuffer(u),p=1/0,m=-1,h=-1;for(let i=0;i<3;i++){this._sortRange(e,t,n,r,i);let a=1/0,o=1/0,s=1/0,c=-1/0,l=-1/0,g=-1/0;for(let r=u-1;r>=1;r--){let i=t[n+r]*6;e[i]<a&&(a=e[i]),e[i+1]<o&&(o=e[i+1]),e[i+2]<s&&(s=e[i+2]),e[i+3]>c&&(c=e[i+3]),e[i+4]>l&&(l=e[i+4]),e[i+5]>g&&(g=e[i+5]);let u=r*6;f[u]=a,f[u+1]=o,f[u+2]=s,f[u+3]=c,f[u+4]=l,f[u+5]=g}let _=1/0,v=1/0,y=1/0,b=-1/0,x=-1/0,S=-1/0;for(let r=1;r<u;r++){let a=t[n+r-1]*6;e[a]<_&&(_=e[a]),e[a+1]<v&&(v=e[a+1]),e[a+2]<y&&(y=e[a+2]),e[a+3]>b&&(b=e[a+3]),e[a+4]>x&&(x=e[a+4]),e[a+5]>S&&(S=e[a+5]);let o=r*6,s=this._surfaceArea(_,v,y,b,x,S),c=this._surfaceArea(f[o],f[o+1],f[o+2],f[o+3],f[o+4],f[o+5]),l=1+(s*r+c*(u-r))/d;l<p&&(p=l,m=i,h=r)}}return m<0||h<=0?n:(m!==2&&this._sortRange(e,t,n,r,m),n+h)}_widestCentroidAxis(e,t,n,r){let i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let u=n;u<r;u++){let n=t[u]*6,r=(e[n]+e[n+3])*.5,d=(e[n+1]+e[n+4])*.5,f=(e[n+2]+e[n+5])*.5;r<i&&(i=r),r>s&&(s=r),d<a&&(a=d),d>c&&(c=d),f<o&&(o=f),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o;return d>u&&d>f?1:f>u?2:0}_insertionSortRange(e,t,n,r,i){let a=i,o=3+i;for(let i=n+1;i<r;i++){let r=t[i],s=e[r*6+a]+e[r*6+o],c=i-1;for(;c>=n&&e[t[c]*6+a]+e[t[c]*6+o]>s;)t[c+1]=t[c],c--;t[c+1]=r}}_sortRange(e,t,n,r,i){let a=r-n,o=this._sortScratch;o.length=a;for(let e=0;e<a;e++)o[e]=t[n+e];let s=i,c=3+i;o.sort((t,n)=>e[t*6+s]+e[t*6+c]-(e[n*6+s]+e[n*6+c]));for(let e=0;e<a;e++)t[n+e]=o[e]}_suffixBuffer(e){let t=e*6;return(!this._suffix||this._suffix.length<t)&&(this._suffix=new Float64Array(t)),this._suffix}_rangeBounds(e,t,n,r,i,a){let o=1/0,s=1/0,c=1/0,l=-1/0,u=-1/0,d=-1/0;for(let i=n;i<r;i++){let n=t[i]*6;e[n]<o&&(o=e[n]),e[n+1]<s&&(s=e[n+1]),e[n+2]<c&&(c=e[n+2]),e[n+3]>l&&(l=e[n+3]),e[n+4]>u&&(u=e[n+4]),e[n+5]>d&&(d=e[n+5])}i[a]=o,i[a+1]=s,i[a+2]=c,i[a+3]=l,i[a+4]=u,i[a+5]=d}_surfaceArea(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}};const u={silent:0,error:1,warn:2,info:3,debug:4},d=`info`,f=`rayzeeLogLevel`,p=`rayzeeLogNamespaces`,m=`color:#7c8494`,h=`color:inherit`;let g=null,_=null;function v(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function y(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function b(){if(g!==null)return g;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in u?(g=u[e],g):(g=u[v(f)]??u[d],g)}function x(){if(_!==null)return _;let e=globalThis.__RAYZEE_LOG_NS__??v(p);return _=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],_}function S(e,t){if(t<u.debug)return!0;let n=x();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function C(e,t,n){if(e>b()||!S(t,e))return;let r=e===u.error?console.error:e===u.warn?console.warn:console.log,i=`[${t}]`;typeof n[0]==`string`?r(`%c${i}%c ${n[0]}`,m,h,...n.slice(1)):r(`%c${i}`,m,...n)}const w={n:e=>Number(e).toLocaleString(`en-US`),ms:e=>e<10?`${Number(e).toFixed(1)} ms`:`${Math.round(e)} ms`,mb:e=>{let t=e/(1024*1024);return t<10?`${t.toFixed(1)} MB`:`${Math.round(t)} MB`},px:(e,t)=>`${e}×${t}`,count:(e,t,n=`${t}s`)=>`${w.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},T={levels:u,setLevel(e){return e in u?(globalThis.__RAYZEE_LOG_LEVEL__=e,g=u[e],y(f,e===d?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(u).join(`, `)}`),this.getLevel())},getLevel(){let e=b();return Object.keys(u).find(t=>u[t]===e)},isEnabled(e){return(u[e]??u.debug)<=b()},only(...e){let t=e.flat().filter(Boolean);return _=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),y(p,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return g=null,_=null,this.getLevel()}};function E(e){return{namespace:e,error:(...t)=>C(u.error,e,t),warn:(...t)=>C(u.warn,e,t),info:(...t)=>C(u.info,e,t),debug:(...t)=>C(u.debug,e,t),isEnabled:e=>T.isEnabled(e),summary(t,n=[]){let r=n.filter(Boolean);if(r.length===0||!console.groupCollapsed){C(u.info,e,[t]),r.forEach(t=>C(u.debug,e,[t]));return}u.info>b()||((b()>=u.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,m,h),r.forEach(e=>console.log(e)),console.groupEnd())}}}function D(e){e&&e in u&&(globalThis.__RAYZEE_LOG_LEVEL__=e,g=u[e])}const O=E(`bvh`);self.onmessage=function(e){let{aabbs:t,count:n,logLevel:r}=e.data;D(r);try{let e=performance.now(),{data:r,nodeCount:i}=new l().buildStructure(new Float64Array(t),n);O.debug(`TLAS ${w.n(i)} nodes in ${w.ms(performance.now()-e)}`),self.postMessage({tlasData:r,nodeCount:i},[r.buffer])}catch(e){O.error(`TLAS build failed:`,e),self.postMessage({error:e.message})}};",Mc=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,jc],{type:`text/javascript;charset=utf-8`});function Nc(e){let t;try{if(t=Mc&&(self.URL||self.webkitURL).createObjectURL(Mc),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(jc),{type:`module`,name:e?.name})}}pn(),Jn(),ke(),It(),tn(),on(),ri(),bn(),kn(),li(),Pr();var Pc=5e4,Fc=2e5,Ic=2e6,Lc=1<<19,Rc=4e7,zc=1e6,Bc=1024**3,Vc=1024**3,Hc=32*1024*1024,Uc=64*1024*1024,Wc=256*1024*1024,Gc=ve(`scene`),Kc=Object.freeze([`maps`,`normalMaps`,`bumpMaps`,`roughnessMaps`,`metalnessMaps`,`emissiveMaps`,`displacementMaps`,`anisotropyMaps`,`transmissionMaps`,`clearcoatMaps`,`clearcoatRoughnessMaps`,`sheenColorMaps`,`sheenRoughnessMaps`,`iridescenceMaps`,`iridescenceThicknessMaps`,`specularIntensityMaps`,`specularColorMaps`,`diffuseTransmissionMaps`,`diffuseTransmissionColorMaps`]),qc=e=>Array.isArray(e)?e:[e],Jc=e=>qc(e).reduce((e,t)=>e+t.byteLength,0),Yc=64*1024*1024;async function Xc(e,t,n){for(let r of qc(n))await e.writeAt(t,r),t+=r.byteLength}function Zc(e){let t=0;return e.traverse(e=>{let n=e.isMesh?e.geometry:null;n&&(t=Math.max(t,Math.ceil((n.index?n.index.count:n.attributes.position?.count??0)/3)))}),t}var Qc=1024,$c=64;function el(e){let t=Int32Array.from(e).sort(),n=[],r=t[0],i=r;for(let e=1;e<=t.length;e++){if(e<t.length&&t[e]-i<=Qc){i=t[e];continue}n.push({offset:r*16,count:(i-r+1)*16}),r=i=t[e]}return n.length>$c?[{offset:t[0]*16,count:(t.at(-1)-t[0]+1)*16}]:n}var tl=class{constructor(e={}){this.config={useWorkers:!0,bvhDepth:30,maxLeafSize:4,verbose:!1,useFloat32Array:!0,textureQuality:`adaptive`,maxTextureSize:$t.DEFAULT_MAX_TEXTURE_SIZE,enableTextureCache:!0,maxConcurrentTextureTasks:Math.min(Dr(),6),maxSceneBytes:yo,sceneCache:!0,sceneCacheMinBuildMs:Tc,...e},this.triangleData=null,this.triangleFloats=null,this.triangleCount=0,this.materials=[],this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.roughnessMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.displacementMaps=[],this.anisotropyMaps=[],this.transmissionMaps=[],this.clearcoatMaps=[],this.clearcoatRoughnessMaps=[],this.sheenColorMaps=[],this.sheenRoughnessMaps=[],this.iridescenceMaps=[],this.iridescenceThicknessMaps=[],this.specularIntensityMaps=[],this.specularColorMaps=[],this.diffuseTransmissionMaps=[],this.diffuseTransmissionColorMaps=[],this.directionalLights=[],this.cameras=[],this.spheres=[],this.bvhRoot=null,this.bvh=null,this.bvhData=null,this.bvhIndexChunks=null,this.bvhIndex=null,this.materialData=null,this.instanceTable=null,this._refitWorker=null,this._refitSharedBuffers=null,this._rebuildGeneration=0,this._pendingRebuilds=new Map,this.srgbBucketTextures=null,this.linearBucketTextures=null,this.emissiveTriangleData=null,this.emissiveTriangleCount=0,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this._initProcessors(),this.isProcessing=!1,this.processingStage=null,this.memory=new To,this.memoryPreflight=null,this.performanceMetrics={textureCreationTime:0,geometryExtractionTime:0,bvhBuildTime:0,blasBuildTime:0,blasWorkerTime:0,tlasBuildTime:0,bvhAssembleTime:0,totalProcessingTime:0}}setMaxTextureSize(e){return this.config.maxTextureSize=e,this.textureCreator?.setMaxTextureSize(e)}_initProcessors(){this.geometryExtractor=new qn({issues:this.config.issues}),this.bvhBuilder=new Zi,this.bvhBuilder.maxLeafSize=this.config.maxLeafSize,this.textureCreator=new Ws({maxTextureSize:this.config.maxTextureSize,issues:this.config.issues}),this.emissiveTriangleBuilder=new $s,this.tlasBuilder=new oo,this._tlasWorker=null,this._tlasWorkerFailed=!1}_log(e,t){t===void 0?Gc.debug(e):Gc.debug(e,t)}needsSpill(e){return co(this.geometryExtractor.surveyScene(e)).total>vo}get spilling(){return!!this._progressive&&(this.triangles?.chunks?.length??0)>1}_preflightMemory(e){let t=this.config.maxSceneBytes??9663676416,n=this.geometryExtractor.surveyScene(e),r=co(n);if(this._streaming){let t=Bc+Zc(e)*(G.FLOATS_PER_TRIANGLE*4+44);r.total=lo(r,n.placements,Math.min(r.triangles,t))}else this._progressive&&(r.total-=r.bvh);let i={...n,estimate:r,safeBytes:vo,maxBytes:t,fits:r.total<=vo};if(this.memoryPreflight=i,r.total<1610612736)return i;if(Gc.debug(H.list([`memory preflight: ${H.mb(r.total)} estimated`,`triangles ${H.mb(r.triangles)} · bvh ${H.mb(r.bvh)} · geometry ${H.mb(r.geometry)}`,`${H.n(n.triangles)} tris · ${H.n(n.placements)} placements`])),r.total>t){let e=`Scene needs about ${H.mb(r.total)} of CPU memory, past the ${H.mb(t)} a browser tab can hold — loading it would crash the tab rather than fail. Reduce the scene (it has ${H.n(n.triangles)} triangles), or raise maxSceneBytes to try anyway.`;throw this.config.issues?.record(Y.SCENE_MEMORY_BUDGET,e,{...n,estimate:r,maxBytes:t}),Error(e)}return i.fits||this.config.issues?.warn(Y.SCENE_MEMORY_BUDGET,`Scene needs about ${H.mb(r.total)} of CPU memory, above the ${H.mb(vo)} a fresh browser session can usually place. It may still load, but a long-running session will probably fail during BVH assembly; restarting the browser recovers the address space.`,{...n,estimate:r,safeBytes:vo}),i}_checkAssemblyHeadroom(e){let t=e*64;if(t<1610612736)return!0;let n=uo(Math.ceil(t*Co),{shared:un});return this.memoryPreflight&&(this.memoryPreflight.assemblyProbed=n.placed),n.exhausted&&this.config.issues?.warn(Y.SCENE_MEMORY_BUDGET,`BVH assembly needs ${H.mb(t)} but only ${H.mb(n.placed)} could be allocated. Restarting the browser usually recovers the address space.`,{totalNodes:e,need:t,placeable:n.placed}),!n.exhausted}_liveMemoryParts(){let e=this.instanceTable,t={triangles:this.triangles?.byteLength??0,bvh:this.bvh?.byteLength??0,geometry:this._geometryBytes??this.memoryPreflight?.geometryBytes??0,placements:e?.matrixBytes??0,blasScratch:0,orderMaps:0};if(e){for(let n of e.blasData.values())t.blasScratch+=n?Jc(n):0;for(let n of e.bvhToOriginal.values())t.orderMaps+=n?.byteLength??0;for(let n of e.originalToBvhMap.values())t.orderMaps+=n?.byteLength??0}return t}sceneBounds(){if(!this.bvh||this.bvh.recordCount===0)return null;if(!this.bvh.isResident(0,1))return this._spilledRootBounds??null;let e=this.bvh.chunkFor(0),t=this.bvh.baseOf(0),n=[],r=[];for(let i=0;i<3;i++)n.push(Math.min(e[t+i],e[t+8+i])),r.push(Math.max(e[t+4+i],e[t+12+i]));return{min:n,max:r}}_sampleMemory(e){this.memory.sample(e,this._liveMemoryParts())}_logMemoryReport(){let{allocatedBytes:e,peakLiveBytes:t,byPhase:n}=this.memory;if(e===0)return;let r=Object.keys(n).filter(e=>n[e].allocated>0).map(e=>`${e} ${H.mb(n[e].allocated)}`),i=this.memoryPreflight?.estimate?.total;Gc.debug(H.list([`memory: peak live ${H.mb(t)}`,`allocated ${H.mb(e)}`,i?`predicted ${H.mb(i)}`:null,r.join(` · `)]))}async buildBVH(e,{sceneKey:t=null,progressive:n=null}={}){if(this.isProcessing)throw Error(`Already processing a scene. Call dispose() first.`);this.isProcessing=!0,this.processingStage=`init`,this.memory.reset(),this._geometryBytes=0,sn(e=>this.memory.alloc(e));let r=new ec(e.name??``,{namespace:`scene`});try{this._geometryOwner===e&&await Promise.all([this._restoreGeometry(e),this.ensureMovable()]),this._reset(),this._sceneKey=t,this._blasKey=null,this._blasRestored=!1,this._progressive=n?.storage&&n.uploader?n:null;let i=this.geometryExtractor._countStoredTriangles(e);this._streaming=!!this._progressive&&i>Math.floor(67108864/(G.FLOATS_PER_TRIANGLE*4)),this._foldLeaves=i>Rc,this.textureCoordinates=zn(e),this.bvhBuilder.foldLeaves=this._foldLeaves,this._log(`Starting scene processing`),this.memory.mark(`preflight`),this._preflightMemory(e),this.processingStage=`extraction`,this.memory.mark(`extraction`),r.start(`Geometry extraction`),this._streaming?await this._extractStreaming(e):await this._extractGeometry(e),r.end(`Geometry extraction`),this.performanceMetrics.geometryExtractionTime=r.getDuration(`Geometry extraction`),this._geometryBytes=Nn(e),this._sampleMemory(`after extraction`),this.processingStage=`bvh`,r.start(`BVH construction (worker)`),r.start(`Material textures (parallel)`);let a=!1,o=this._buildBVH().then(()=>r.end(`BVH construction (worker)`)),s=this._createMaterialTextures().then(()=>{r.end(`Material textures (parallel)`),a=!0});return await o,z({status:`Building light data...`,progress:77}),r.start(`Emissive extraction + Light BVH`),this._buildEmissiveData(),r.end(`Emissive extraction + Light BVH`),a||z({status:`Processing material textures...`,progress:80}),await s,this.performanceMetrics.bvhBuildTime=r.getDuration(`BVH construction (worker)`),this.performanceMetrics.textureCreationTime=r.getDuration(`Material textures (parallel)`),this.processingStage=`finalize`,r.start(`BVH data packing`),this.bvhRoot&&!this.bvh&&this._setBVHData(this.textureCreator.createBVHRawData(this.bvhRoot)),r.end(`BVH data packing`),this.spheres=this._createSpheres(),this.performanceMetrics.totalProcessingTime=performance.now()-r.totalStart,r.print(),this.processingStage=`complete`,this._streaming&&this._geometrySpill?.bytes>=Vc?this._geometryOwner=e:await this._restoreGeometry(e),z({status:`Scene data ready`,progress:85}),this._blasKey&&!this._blasRestored&&this.performanceMetrics.totalProcessingTime>=this.config.sceneCacheMinBuildMs&&(this._blasStoring=this._storeBLASes(e.name??``).catch(e=>Gc.debug(`storing BLASes failed:`,e))),this}catch(e){throw this.processingStage=`error`,Gc.error(`processing failed:`,e),z({status:`Error: ${e.message}`,failed:!0,progress:100}),e}finally{this._geometryOwner||this._disposeGeometrySpill(),sn(null),this._sampleMemory(`at ${this.processingStage}`),this._logMemoryReport(),this.isProcessing=!1}}async _extractGeometry(e){z({isLoading:!0,title:`Processing`,status:`Extracting geometry...`,progress:15}),await new Promise(e=>setTimeout(e,0)),this._log(`Extracting geometry`);let t=performance.now();try{this._adoptExtraction(this.geometryExtractor.extract(e));let n=performance.now()-t;this._log(`Geometry extraction complete (${n.toFixed(2)}ms)`,{triangleCount:this.triangleCount,materials:this.materials.length}),z({status:`Extracted ${this.triangleCount.toLocaleString()} triangles`,progress:25})}catch(e){throw Gc.error(`geometry extraction failed:`,e),z({status:`Extraction error: ${e.message}`,failed:!0,progress:25}),e}}async _extractStreaming(e){z({isLoading:!0,title:`Processing`,status:`Large scene: building through disk to save memory...`,progress:15}),await new Promise(e=>setTimeout(e,0));let t=performance.now(),n=this.geometryExtractor,{storage:r,uploader:i}=this._progressive,a=`spill:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`,o=n._countStoredTriangles(e),s=fn.lazy(o,G.FLOATS_PER_TRIANGLE,Uint32Array),c=s.recordsPerChunk*s.lanesPerRecord*4,l=await yn.create(r,`${a}:tri`,c,{label:`Triangle records`,expectedBytes:o*c/s.recordsPerChunk}),u=l&&await yn.create(r,`${a}:blas`,0,{label:`BLAS nodes (while building)`});if(!u)return await l?.dispose(),this._streaming=!1,this._extractGeometry(e);let d=await On.create(r,`${a}:geo`,this.memoryPreflight?.geometryBytes??0);this._geometrySpill=d;let f={key:a,triStore:l,blasStore:u,bvhStore:null,blasBytes:0,blasAt:new Map,pending:[],extractedChunks:0,emitterChunks:new Set,isEmitter:e=>n._emissiveMaterial(e),uploadTriangles:null,chain:Promise.resolve(),error:null};this._spillStores=[l],this._blasKey=null;let p=new Map,m=this._blasWorkerOpts(),h=[],g=()=>new Promise(e=>h.push(e)),_=()=>{let e=h;h=[];for(let t of e)t()},v=null,y=(e,t,n)=>{let r=n.bvhData,i=new Float32Array(6);Ga.rootAABB(qc(r)[0],v,t.start,t.count,i,0),p.set(e,{result:n,aabb:i});let a=f.blasBytes;f.blasBytes+=Jc(r),f.blasAt.set(e,a),n.nodeCount=Jc(r)/64,n.bvhData=null,this._queueSpill(f,()=>Xc(u,a,r)),this._forEachChunk(v,t.start,t.count,e=>{--f.pending[e]===0&&e<f.extractedChunks&&this._finishTriangleChunk(f,e)}),_()},b=0,x=this._blasPool(m,()=>b++,(e,t,n)=>y(e,t,n)),S=Promise.resolve(),C=0,w=e=>{let t=e>=v.recordCount?v.chunks.length:Math.floor(e/v.recordsPerChunk);for(let e=f.extractedChunks;e<t;e++)f.pending[e]||this._finishTriangleChunk(f,e);f.extractedChunks=Math.max(f.extractedChunks,t)},T;try{if(T=await n.extractStreaming(e,{onStore:e=>{v=e,this._setTriangleData(e),f.uploadTriangles=i(e,`triangles`,{textureCoordinates:this.textureCoordinates})},onRange:(e,t)=>{this._forEachChunk(v,t.start,t.count,e=>f.pending[e]=(f.pending[e]??0)+1),this._isLargeMesh(t)?(C++,S=S.then(async()=>{y(e,t,await this._buildLargeBLAS(t,m)),C--}),S.catch(e=>{f.error??=e,_()})):x.submit({m:e,range:t})},releaseGeometry:d?e=>d.add(e):null,pause:async e=>{for(w(e),d?.queuedBytes>Wc&&await d.written(),z({status:`Extracted ${e.toLocaleString()} triangles, ${b.toLocaleString()} BVHs built...`,progress:15+Math.floor(20*e/Math.max(1,o))}),await new Promise(e=>setTimeout(e,0));v.byteLength>Bc&&(x.pending>0||C>0)&&!f.error&&!x.error;)await Promise.race([g(),new Promise(e=>setTimeout(e,50))]);if(f.error||x.error)throw f.error??x.error}}),w(1/0),await Promise.all([x.close(),S]),await f.chain,f.error)throw f.error}catch(e){throw x.abort(e),Gc.error(`streamed extraction failed:`,e),z({status:`Extraction error: ${e.message}`,failed:!0,progress:25}),e}this._adoptExtraction(T),this._streamed={state:f,templates:p},this._log(`Geometry extracted and ${p.size} BLASes built together (${(performance.now()-t).toFixed(0)}ms)`)}_adoptExtraction(e){if(this._setTriangleData(e.triangleData),this.geometryExtractor.releaseTriangles(),this.triangleCount=bt(e.triangleCount,`triangle count`),this._foldLeaves&&this.triangleCount>134217728)throw RangeError(`${this.triangleCount.toLocaleString()} triangles is past the ${Pt.toLocaleString()} a folded BVH leaf can address`);this.expandedTriangleCount=e.expandedTriangleCount??e.triangleCount,this.instanceSource=e.instanceSource||null,this.matrixRuns=e.matrixRuns||null,this.instanceCount=e.instanceCount||0,this.instanceGroups=e.instanceGroups??[],this.bakeInverse=e.bakeInverse||null,this._log(`Using Float32Array format: ${this.triangleCount} triangles, ${(this.triangles.byteLength/(1024*1024)).toFixed(2)}MB`),this.materials=e.materials,this.materialTriangleCounts=e.materialTriangleCounts,this.meshes=e.meshes,this.meshTriangleRanges=e.meshTriangleRanges,this._adoptTextureLists(e),this.directionalLights=e.directionalLights,this.cameras=e.cameras}async _buildBVH(){if(z({status:`Building BVH...`,progress:25}),this.triangleCount===0)throw Error(`No triangles to build BVH from`);this._log(`Building two-level BVH (TLAS/BLAS)`),this.memory.mark(`blas`);let e=performance.now();try{let t=this.meshTriangleRanges;if(!t||t.length===0)throw Error(`No mesh triangle ranges available for TLAS/BLAS build`);let n=this.instanceCount>0,r=n?this.instanceCount:t.length,i=this.instanceSource,a=n?this.matrixRuns:null,o=e=>n?i[e]:e;this.instanceTable=new Ga,this.instanceTable.allocate(r,t.length,a,n?i:null),this.instanceTable.tplBakeInverse=this.bakeInverse,this.instanceTable.setGroups(n?this.instanceGroups:null);let s=this._clusterCopies(this.instanceTable);s&&this.instanceTable.planClusters();let c=s?this.instanceTable.clusterCount:this.instanceTable.entryCount,l=oo.nodeCountFor(c)+this.instanceTable.groupNodeCount,u=this._streamed;this._streamed=null;let d=[],f=[],p=[],m=new Int32Array(r).fill(-1),h=new Map;for(let e=0;e<r;e++){let n=t[o(e)];if(!n||n.count===0)continue;let r=h.get(n.start);if(r!==void 0){m[e]=r;continue}h.set(n.start,e),u?p.push({m:e,range:n}):this._isLargeMesh(n)?f.push({m:e,range:n}):d.push({m:e,range:n})}let g=this._blasWorkerOpts(),_=d.length+f.length,v=0,y=()=>{v++,z({status:`Building BLAS ${v}/${_}...`,progress:25+Math.floor(v/_*45)})},b=[...d,...f].map(({m:e,range:t})=>({m:e,range:t,t:o(e),triOffset:t.start,triCount:t.count})).sort((e,t)=>e.t-t.t),x=u?null:await this._restoreBLASes(b,l,g),S=u?u.state:!x&&this._progressive&&this.triangles.chunks.length>1?await this._beginProgressiveSpill(b):null,C=S&&!u?(e,t,n)=>this._onBLASBuilt(S,o(e),t,n):null;if(u)for(let[e,t]of u.templates)this.instanceTable.tplObjectAABB.set(t.aabb,e*6);x&&(d.length=0,f.length=0,z({status:`Restored stored BVHs`,progress:68}));let w=x?Promise.resolve(x.results):u?Promise.resolve(p.map(({m:e,range:t})=>({m:e,range:t,result:u.templates.get(o(e)).result}))):this._buildBLASesWithPool(d,g,y,C),T=[],E=(async()=>{for(let{m:e,range:t}of f){let n=await this._buildLargeBLAS(t,g);C?.(e,t,n),T.push({m:e,range:t,result:n}),y()}})(),[D]=await Promise.all([w,E]);if(S&&(await S.chain,S.error))throw S.error;let O={sah:0,objMed:0,spatMed:0,failed:0};for(let{m:e,range:t,result:r}of[...D,...T]){let i=r.splitStats;i&&(O.sah+=i.sahSplits??0,O.objMed+=i.objectMedianSplits??0,O.spatMed+=i.spatialMedianSplits??0,O.failed+=i.failedSplits??0,this.performanceMetrics.blasWorkerTime+=i.totalBuildTime??0),this.instanceTable.setEntry({meshIndex:e,blasNodeCount:r.nodeCount??Jc(r.bvhData)/64,triOffset:t.start,triCount:t.count,originalToBvhMap:r.originalToBvh||null,bvhData:r.bvhData,matrixWorld:n?Ra:this.meshes?.[e]?.matrixWorld?.elements??null,expandedStart:t.expandedStart,sourceMesh:o(e)})}for(let e=0;e<r;e++){let r=m[e];r<0||this.instanceTable.setAlias(e,r,n?Ra:this.meshes?.[e]?.matrixWorld?.elements??null,t[o(e)].expandedStart,o(e))}z({status:`Built all BLASes`,progress:70}),this.performanceMetrics.blasBuildTime=performance.now()-e,z({status:`Building TLAS...`,progress:72}),this._sampleMemory(`BLASes built`),this.memory.mark(`tlas`);let k=performance.now(),A=this.instanceTable;this.instanceTable.computeAABBs(this.triangles,{owners:!S}),this.instanceTable.computeGroupAABBs(),s&&(A.clusterWorld=new Float32Array(A.entryCount*6),A.writeEntryWorldAABBs(A.clusterWorld),A.clusterBounds=A.formClusters(A.clusterWorld)),this.instanceTable.assignOffsets(oo.nodeCountFor(c));let j=this.instanceTable.totalNodeCount,M=await this._buildTLAS(A);if(this._streaming&&s){let e=A.clusterWorld;this._spillMeshBounds=this._instancedMeshBounds((t,n)=>{for(let r=0;r<6;r++)n[r]=e[t*6+r]})}A.clusterWorld=null,A.clusterBounds=null,this.performanceMetrics.tlasBuildTime=performance.now()-k,this.memory.mark(`assemble`);let N=performance.now();S||this._checkAssemblyHeadroom(j),this._setBVHData(fn.lazy(j,16,Float32Array,void 0,un));let P=S?await this._beginBVHSpill(S,A.blasBase):null;this.bvh.setRecords(0,M),A.groupNodeCount&&this.bvh.setRecords(A.groupNodeStart,A.groupNodeBlock()),M=null,this.tlasBuilder.releaseFlattenBuffer();let F=Math.max(1,Math.ceil(A.templateCount/32));if(x){try{let e=performance.now();await lc(x.nodes,this.bvh,A.blasBase,A.totalBLASNodes),this.performanceMetrics.blasRestore.readMs=performance.now()-e}finally{x.release()}A.blasData.clear()}else{for(let e=0;e<A.templateCount;e++){let t=S?await this._readSpilledBLAS(S,e):A.blasData.get(e);if(!t)continue;let n=A.tplBlasOffset[e],r=n;for(let e of qc(t))this.bvh.setRecords(r,e),r+=e.length/16;this._offsetBLASInPlace(n,r-n,n,A.tplTriOffset[e]),A.blasData.delete(e),await P?.(r),e%F===0&&this._sampleMemory(`assembling ${e}/${A.templateCount}`)}s&&await this._writeCopyRecords(P),await P?.(j,!0),S&&await S.blasStore.dispose()}if(s&&x&&await this._writeCopyRecords(null),this._setBVHData(this.bvh.materializeAll()),x)for(let[e,t]of x.orders)A.bvhToOriginal.set(e,t);else this._buildBvhToOriginalMaps();this.performanceMetrics.bvhAssembleTime=performance.now()-N,A.originalToBvhMap.clear(),A.blasData.clear(),this.bvhRoot=!0,this._disposeRefitWorker();let I=performance.now()-e;Gc.debug(H.list([`${H.n(A.setCount)} BLASes + TLAS`,`${H.n(this.bvh.recordCount)} nodes`,`SAH ${H.n(O.sah)} · objMed ${O.objMed} · spatMed ${O.spatMed} · failed ${O.failed}`,H.ms(I)])),z({status:`BVH construction complete`,progress:75})}catch(e){throw Gc.error(`BVH build failed:`,e),z({status:`BVH error: ${e.message}`,failed:!0,progress:75}),e}}_blasWorkerOpts(){return{depth:this.config.bvhDepth,reinsertionOptimization:{enabled:this.bvhBuilder.enableReinsertionOptimization,batchSizeRatio:this.bvhBuilder.reinsertionBatchSizeRatio,maxIterations:this.bvhBuilder.reinsertionMaxIterations},maxLeafSize:this.bvhBuilder.maxLeafSize,foldLeaves:this._foldLeaves===!0,numBins:this.bvhBuilder.numBins,maxBins:this.bvhBuilder.maxBins,minBins:this.bvhBuilder.minBins,logLevel:B()}}_isLargeMesh(e){return e.count>=Fc&&Ia(e.count)}async _buildLargeBLAS(e,t){if(e.count>Ic)return this._buildSplitBLAS(e,t);let n=new Uint32Array(new SharedArrayBuffer(e.count*this.triangles.lanesPerRecord*4));this.triangles.readRecords(e.start,e.count,n),this.triangles.release(e.start,e.count);let r=await Na(n,this.config.bvhDepth,null,t);return r.reorderedTriangles?(this.triangles.setRecords(e.start,r.reorderedTriangles),delete r.reorderedTriangles):r.order&&(this._writeInOrder(e.start,r.triangles,r.order),delete r.order,delete r.triangles),r}async _buildSplitBLAS(e,t){let n=this.triangles,{order:r,pieces:i,tree:a}=await hc(n,e.start,e.count,Lc,{pause:()=>new Promise(e=>setTimeout(e,0))}),o=this._blasPool(t,null,null,Math.min(Dr(),8));i.forEach((t,n)=>o.submit({m:n,range:{start:e.start+t.start,count:t.count}}));let s=[],c={};for(let{m:e,range:t,result:r}of await o.close()){r.aabb=new Float32Array(6),Ga.rootAABB(r.bvhData,n,t.start,t.count,r.aabb,0),s[e]=r;for(let[e,t]of Object.entries(r.splitStats??{}))typeof t==`number`&&(c[e]=(c[e]??0)+t)}return{...yc(a,i,s,r),splitStats:c}}_blasCacheKey(e){let t={...e};delete t.logLevel;let n=typeof navigator<`u`?navigator.hardwareConcurrency:0;return`blas:2:${Sc}:${JSON.stringify(t)}:${n}:${this._sceneKey}`}async _restoreBLASes(e,t,n){if(!this._sceneKey||this.config.sceneCache===!1)return null;let r=ti(oi().cacheNamespace);if(!r)return null;this._blasKey=this._blasCacheKey(n);let i=await sc(r,this._blasKey);if(!i)return null;let a=e=>(Gc.debug(`stored BLASes not used: ${e}`),i.release(),null),{index:o}=i;if(o.tlasNodeCount!==t||o.templates.length!==e.length)return a(`layout changed`);let s=t;for(let t=0;t<e.length;t++){let[n,r,i,c,l]=o.templates[t],u=e[t];if(u.t!==n||u.triOffset!==r||u.triCount!==i||l!==s)return a(`layout changed`);s+=c}if(s!==o.totalNodes)return a(`layout changed`);let c=performance.now(),l=await oc(this.triangles,e);for(let t=0;t<e.length;t++)if(l[t]!==o.templates[t][6])return a(`triangles changed`);let u=performance.now();try{let t=new Map,n=[];for(let r=0;r<e.length;r++){let[a,s,c,l,,u,,d]=o.templates[r],f=await uc(i.order,u,c);this._permuteRange(s,c,f),t.set(a,f),n.push({m:e[r].m,range:e[r].range,result:{bvhData:new Float32Array(Uint32Array.from(d).buffer),originalToBvh:null,nodeCount:l}})}return this._blasRestored=!0,this.performanceMetrics.blasRestore={checksumMs:u-c,permuteMs:performance.now()-u},Gc.debug(`restored ${H.n(e.length)} stored BLASes`),{results:n,orders:t,nodes:i.nodes,release:i.release}}catch(e){throw i.release(),e}}_writeInOrder(e,t,n){let r=this.triangles,i=r.lanesPerRecord;for(let a=0,o=n.length;a<o;){let s=r.chunkFor(e+a),c=Math.min(o,(((e+a)/r.recordsPerChunk|0)+1)*r.recordsPerChunk-e);for(let o=r.baseOf(e+a);a<c;a++,o+=i){let e=n[a]*i;for(let n=0;n<i;n++)s[o+n]=t[e+n]}}}_permuteRange(e,t,n){let r=!0;for(let e=0;e<t&&r;e++)r=n[e]===e;if(r)return;let i=this.triangles.lanesPerRecord,a=this.triangles.slice(e,t),o=new a.constructor(a.length);if(i===20)for(let e=0,r=0;e<t;e++,r+=20){let t=n[e]*20;o[r]=a[t],o[r+1]=a[t+1],o[r+2]=a[t+2],o[r+3]=a[t+3],o[r+4]=a[t+4],o[r+5]=a[t+5],o[r+6]=a[t+6],o[r+7]=a[t+7],o[r+8]=a[t+8],o[r+9]=a[t+9],o[r+10]=a[t+10],o[r+11]=a[t+11],o[r+12]=a[t+12],o[r+13]=a[t+13],o[r+14]=a[t+14],o[r+15]=a[t+15],o[r+16]=a[t+16],o[r+17]=a[t+17],o[r+18]=a[t+18],o[r+19]=a[t+19]}else for(let e=0;e<t;e++){let t=n[e]*i,r=e*i;for(let e=0;e<i;e++)o[r+e]=a[t+e]}this.triangles.setRecords(e,o)}async _storeBLASes(e){let t=ti(oi().cacheNamespace),n=this.instanceTable;if(!t||!n||!this.bvh)return!1;let r=this._blasKey,i=this._geometryVersion,a=()=>this._geometryVersion!==i||this._blasKey!==r,o=[];for(let e=0;e<n.templateCount;e++){let t=n.tplOwner[e];t<0||n.sourceMesh[t]!==e||o.push({t:e,triOffset:n.tplTriOffset[e],triCount:n.tplTriCount[e],nodeCount:n.tplNodeCount[e],blasOffset:n.tplBlasOffset[e]})}let s=await oc(this.triangles,o);if(a())return!1;let c=e=>{let t=this.bvhIndexChunks.chunkFor(e),n=this.bvhIndexChunks.baseOf(e);return Array.from(t.subarray(n,n+16))},l=0,u=[],d=o.map((e,t)=>{u.push(n.bvhToOriginal.get(e.t)??Uint32Array.from({length:e.triCount},(e,t)=>t));let r=[e.t,e.triOffset,e.triCount,e.nodeCount,e.blasOffset,l,s[t],c(e.blasOffset)];return l+=e.triCount,r}),f=await cc(t,r,{index:{v:2,tlasNodeCount:n.blasBase,totalNodes:n.treeNodeCount,templates:d},bvh:this.bvh,orders:u,isStale:a,label:e});return f&&Gc.debug(`stored ${H.n(o.length)} BLASes for the next load`),f}async _beginProgressiveSpill(e){let{storage:t,uploader:n}=this._progressive,r=this.triangles,i=`spill:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`,a=r.recordsPerChunk*r.lanesPerRecord*r.LaneType.BYTES_PER_ELEMENT,o=await yn.create(t,`${i}:tri`,a,{label:`Triangle records`,expectedBytes:r.byteLength}),s=o&&await yn.create(t,`${i}:blas`,0,{label:`BLAS nodes (while building)`});if(!s)return await o?.dispose(),null;let c={key:i,triStore:o,blasStore:s,bvhStore:null,blasBytes:0,blasAt:new Map,pending:new Int32Array(r.chunks.length),emitterChunks:new Set,isEmitter:e=>{let t=this.materials[e];return(t?.emissiveIntensity??0)>0&&!!t.emissive&&(t.emissive.r>0||t.emissive.g>0||t.emissive.b>0)},uploadTriangles:n(r,`triangles`,{textureCoordinates:this.textureCoordinates}),chain:Promise.resolve(),error:null};this._spillStores=[o],this._blasKey=null;for(let{triOffset:t,triCount:n}of e)this._forEachChunk(r,t,n,e=>c.pending[e]++);for(let e=0;e<r.chunks.length;e++)c.pending[e]===0&&this._finishTriangleChunk(c,e);return c}_forEachChunk(e,t,n,r){if(n<=0)return;let i=(t+n-1)/e.recordsPerChunk|0;for(let n=t/e.recordsPerChunk|0;n<=i;n++)r(n)}_onBLASBuilt(e,t,n,r){let i=this.instanceTable,a=r.bvhData;i.tplTriOffset[t]=n.start,i.tplTriCount[t]=n.count,i._readRootAABB(qc(a)[0],t,this.triangles,i.tplObjectAABB,t*6);let o=e.blasBytes;e.blasBytes+=Jc(a),e.blasAt.set(t,o),r.nodeCount=Jc(a)/64,r.bvhData=null,this._queueSpill(e,()=>Xc(e.blasStore,o,a)),this._forEachChunk(this.triangles,n.start,n.count,t=>{--e.pending[t]===0&&this._finishTriangleChunk(e,t)})}_queueSpill(e,t){e.chain=e.chain.then(t).catch(t=>{e.error??=t})}_finishTriangleChunk(e,t){this._queueSpill(e,async()=>{let n=this.triangles,r=n.chunks[t];if(!r)return;await e.uploadTriangles(t);let i=n.lanesPerRecord;for(let n=G.MATERIAL_FLAGS_OFFSET;n<r.length;n+=i)if(e.isEmitter(r[n]&16777215)){e.emitterChunks.add(t);return}await n.spillChunk(t,e.triStore)})}async _readSpilledBLAS(e,t){let n=e.blasAt.get(t);if(n===void 0)return null;let r=this.instanceTable.tplNodeCount[t]*64,i=[];for(let t=0;t<r;t+=Yc)i.push(new Float32Array(await e.blasStore.readAt(n+t,Math.min(Yc,r-t))));return i}async _beginBVHSpill(e,t){let{storage:n,uploader:r}=this._progressive,i=this.bvh,a=i.recordsPerChunk*i.lanesPerRecord*i.LaneType.BYTES_PER_ELEMENT,o=await yn.create(n,`${e.key}:bvh`,a,{label:`BLAS nodes`,expectedBytes:i.recordCount*64}),s=r(i),c=Math.ceil(t/i.recordsPerChunk);o&&this._spillStores.push(o),this._bvhSpillStore=o;let l=c;return async(e,t=!1)=>{for(;l<i.chunks.length&&(t||(l+1)*i.recordsPerChunk<=e);)i.chunks[l]||i._materialize(l),await s(l),o&&await i.spillChunk(l,o),l++;if(t)for(let e=0;e<Math.min(c,i.chunks.length);e++)i.chunks[e]||i._materialize(e),await s(e)}}_offsetBLASInPlace(e,t,n,r){let i=this.bvhIndexChunks;for(let a=e,o=e+t;a<o;){let e=i.chunkFor(a),t=Math.min(o,((a/i.recordsPerChunk|0)+1)*i.recordsPerChunk),s=i.baseOf(a);Hi(e,n,r,s,s+(t-a)*16),a=t}}_buildBLASesWithPool(e,t,n,r=null){let i=this._blasPool(t,n,r);for(let t of e)i.submit(t);return i.close()}_blasPool(e,t,n=null,r=this.config.maxConcurrentTextureTasks||4){let i=[],a=[],o=[],s=[],c=!1,l=0,u=0,d=null,f,p=new Promise((e,t)=>f={resolve:e,reject:t});p.catch(()=>{});let m=e=>{d||(d=e,o.forEach(e=>e.terminate()),f.reject(e))},h=()=>{d||!c||i.length>0||l>0||(o.forEach(e=>e.terminate()),f.resolve(a))},g=t=>{let n=i.shift();if(!n){s.push(t),h();return}let{m:r,range:a}=n;l++;try{let n=this.triangles.copyOf(a.start,a.count),i=a.count;t._currentTask={m:r,range:a},t.postMessage({triangleData:n.buffer,triangleByteOffset:n.byteOffset,triangleByteLength:n.byteLength,triangleCount:i,depth:e.depth,reportProgress:!1,sharedReorderBuffer:null,reinsertionOptimization:e.reinsertionOptimization,maxLeafSize:e.maxLeafSize,foldLeaves:e.foldLeaves,numBins:e.numBins,maxBins:e.maxBins,minBins:e.minBins,logLevel:e.logLevel},[n.buffer])}catch(e){m(e)}},_=(e,r)=>{let i=r.data;if(i.error){m(Error(i.error));return}if(i.progress!==void 0)return;let{m:o,range:s}=e._currentTask;l--;try{i.triangles&&this.triangles.setRecords(s.start,i.triangles);let e={bvhData:i.bvhData,originalToBvh:i.originalToBvh||null,splitStats:i.splitStats||null};n?.(o,s,e),a.push({m:o,range:s,result:e})}catch(e){m(e);return}u++,t?.(u),g(e)},v=()=>{let e=jr(Ta);return e.onmessage=t=>_(e,t),e.onerror=e=>m(e),o.push(e),e};return{submit(e){if(!d){i.push(e);try{let e=s.pop()??(o.length<r?v():null);e&&g(e)}catch(e){m(e)}}},close(){return c=!0,h(),p},abort(e){m(e??Error(`BLAS pool aborted`))},get pending(){return i.length+l},get error(){return d}}}_buildBvhToOriginalMaps(){let e=this.instanceTable;for(let t=0;t<e.count;t++){if(!e.isSet[t]||!e.isOwner(t))continue;let n=e.sourceMesh[t],r=e.tplTriCount[n],i=e.originalToBvhMap.get(n),a=new Uint32Array(r);if(i)for(let e=0;e<r;e++)a[i[e]]=e;else for(let e=0;e<r;e++)a[e]=e;e.bvhToOriginal.set(n,a),e.originalToBvhMap.delete(n)}}async _createMaterialTextures(){this._log(`Creating material textures (parallel with BVH)`);try{let{srgbLists:e,linearLists:t,remap:n}=this._bucketTextures();this._remapMaterialTextureIndices(n),this.materials?.length&&(this.materialData=this.textureCreator.createMaterialRawData(this.materials));let i=(e,t)=>e.length===0?Promise.resolve(null):this.textureCreator.createTexturesToDataTexture(e,{srgbPool:t}).then(e=>(e&&t&&(e.colorSpace=r.SRGBColorSpace),e)),[a,o]=await Promise.all([Promise.all(e.map(e=>i(e,!0))),Promise.all(t.map(e=>i(e,!1)))]);this.srgbBucketTextures=a,this.linearBucketTextures=o,this._log(`Material textures complete`,{materialData:!!this.materialData,srgbBuckets:a.map(e=>e?`${e.image.width}x${e.image.height}x${e.image.depth}`:`-`).join(`,`),linearBuckets:o.map(e=>e?`${e.image.width}x${e.image.height}x${e.image.depth}`:`-`).join(`,`)})}catch(e){throw Gc.error(`texture creation failed:`,e),e}}_bucketTextures(){let e=this.config.maxTextureSize,t=$t.MATERIAL_BUCKET_COUNT,n=$t.BUCKET_LAYER_STRIDE,r=e=>{let t=new Set,n=[];for(let r of e)for(let e of r||[]){if(!e?.image)continue;let r=e.source?.uuid??e.uuid;t.has(r)||(t.add(r),n.push({width:e.image.width,height:e.image.height}))}return n},i=[this.maps,this.emissiveMaps,this.sheenColorMaps,this.specularColorMaps,this.diffuseTransmissionColorMaps],a=[this.normalMaps,this.bumpMaps,this.roughnessMaps,this.metalnessMaps,this.displacementMaps,this.anisotropyMaps,this.transmissionMaps,this.clearcoatMaps,this.clearcoatRoughnessMaps,this.sheenRoughnessMaps,this.iridescenceMaps,this.iridescenceThicknessMaps,this.specularIntensityMaps,this.diffuseTransmissionMaps],o=Xt(r(i),e,t),s=Xt(r(a),e,t);this._srgbBucketShapes=o,this._linearBucketShapes=s;let c=Array.from({length:t},()=>[]),l=Array.from({length:t},()=>[]),u=Array.from({length:t},()=>new Map),d=Array.from({length:t},()=>new Map);this._srgbTexPacked=new Map,this._linearTexPacked=new Map;let f=!1,p=!1,m=(e,t,r,i,a)=>{if(!e)return-1;if(!e.image)return p||this.config.issues?.record(Y.TEXTURE_BUILD_FAILED,`a material map had not finished decoding when the scene was packed; it renders untextured`,{texture:e.name||e.source?.uuid||e.uuid}),p=!0,-1;let o=Zt(e.image.width,e.image.height,a),s=e.source?.uuid??e.uuid,c=r[o].get(s);if(c!==void 0)return Qt(o,c);if(t[o].length>=n)return Gc.warn(`texture bucket ${o} full (${n}); dropping a map`),f||this.config.issues?.record(Y.TEXTURE_LIMIT_EXCEEDED,`texture bucket ${o} full (${n} layers); the rest render untextured`,{bucket:o,limit:n}),f=!0,-1;t[o].push(e);let l=t[o].length-1;r[o].set(s,l);let u=Qt(o,l);return i.set(s,u),u},h=(e,t,n,r,i)=>(e||[]).map(e=>m(e,t,n,r,i));return{srgbLists:c,linearLists:l,remap:{albedo:h(this.maps,c,u,this._srgbTexPacked,o),emissive:h(this.emissiveMaps,c,u,this._srgbTexPacked,o),normal:h(this.normalMaps,l,d,this._linearTexPacked,s),bump:h(this.bumpMaps,l,d,this._linearTexPacked,s),roughness:h(this.roughnessMaps,l,d,this._linearTexPacked,s),metalness:h(this.metalnessMaps,l,d,this._linearTexPacked,s),displacement:h(this.displacementMaps,l,d,this._linearTexPacked,s),anisotropy:h(this.anisotropyMaps,l,d,this._linearTexPacked,s),transmission:h(this.transmissionMaps,l,d,this._linearTexPacked,s),clearcoat:h(this.clearcoatMaps,l,d,this._linearTexPacked,s),clearcoatRoughness:h(this.clearcoatRoughnessMaps,l,d,this._linearTexPacked,s),sheenColor:h(this.sheenColorMaps,c,u,this._srgbTexPacked,o),sheenRoughness:h(this.sheenRoughnessMaps,l,d,this._linearTexPacked,s),iridescence:h(this.iridescenceMaps,l,d,this._linearTexPacked,s),iridescenceThickness:h(this.iridescenceThicknessMaps,l,d,this._linearTexPacked,s),specularIntensity:h(this.specularIntensityMaps,l,d,this._linearTexPacked,s),specularColor:h(this.specularColorMaps,c,u,this._srgbTexPacked,o),diffuseTransmission:h(this.diffuseTransmissionMaps,l,d,this._linearTexPacked,s),diffuseTransmissionColor:h(this.diffuseTransmissionColorMaps,c,u,this._srgbTexPacked,o)}}}_remapMaterialTextureIndices(e){let t=(e,t)=>e>=0&&e<t.length?t[e]:-1;for(let n of this.materials)n.map=t(n.map,e.albedo),n.emissiveMap=t(n.emissiveMap,e.emissive),n.normalMap=t(n.normalMap,e.normal),n.bumpMap=t(n.bumpMap,e.bump),n.roughnessMap=t(n.roughnessMap,e.roughness),n.metalnessMap=t(n.metalnessMap,e.metalness),n.displacementMap=t(n.displacementMap,e.displacement),n.anisotropyMap=t(n.anisotropyMap,e.anisotropy),n.transmissionMap=t(n.transmissionMap,e.transmission),n.clearcoatMap=t(n.clearcoatMap,e.clearcoat),n.clearcoatRoughnessMap=t(n.clearcoatRoughnessMap,e.clearcoatRoughness),n.sheenColorMap=t(n.sheenColorMap,e.sheenColor),n.sheenRoughnessMap=t(n.sheenRoughnessMap,e.sheenRoughness),n.iridescenceMap=t(n.iridescenceMap,e.iridescence),n.iridescenceThicknessMap=t(n.iridescenceThicknessMap,e.iridescenceThickness),n.specularIntensityMap=t(n.specularIntensityMap,e.specularIntensity),n.specularColorMap=t(n.specularColorMap,e.specularColor),n.diffuseTransmissionMap=t(n.diffuseTransmissionMap,e.diffuseTransmission),n.diffuseTransmissionColorMap=t(n.diffuseTransmissionColorMap,e.diffuseTransmissionColor)}_buildEmissiveData(){this.emissiveTriangleCount=this.emissiveTriangleBuilder.extractEmissiveTriangles(this.triangles,this.materials,this.triangleCount,this.instanceTable??null),this.emissiveTriangleData=this.emissiveTriangleBuilder.createEmissiveRawData(),this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower,this._log(`Emissive triangle extraction complete`,this.emissiveTriangleBuilder.getStats()),this.emissiveTriangleBuilder.buildLightBVH(),this.lightBVHNodeData=this.emissiveTriangleBuilder.lightBVHNodeData,this.lightBVHNodeCount=this.emissiveTriangleBuilder.lightBVHNodeCount,this.emissiveTriangleData=this.emissiveTriangleBuilder.emissiveTriangleData||this.emissiveTriangleData,this.emissiveBitTrailMap=this.emissiveTriangleBuilder.emissiveBitTrailMap,this.emissiveTriangleCount=this.emissiveTriangleBuilder.emissiveCount,this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower}_createSpheres(){return[]}_reset(){this._geometryVersion=(this._geometryVersion??0)+1,this._disposeSpill(),this._disposeGeometrySpill(),this._disposeMatrixSpill(),this._orderSpill?.store.dispose().catch(()=>{}),this._orderSpill=null,this._spilledAfterLoad=!1,this._disposeTextures(),this.triangles=[],this._setTriangleData(null),this.triangleCount=0,this.materials=[],this.meshTriangleRanges=null,this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.roughnessMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.displacementMaps=[],this.anisotropyMaps=[],this.transmissionMaps=[],this.clearcoatMaps=[],this.clearcoatRoughnessMaps=[],this.sheenColorMaps=[],this.sheenRoughnessMaps=[],this.iridescenceMaps=[],this.iridescenceThicknessMaps=[],this.specularIntensityMaps=[],this.specularColorMaps=[],this.diffuseTransmissionMaps=[],this.diffuseTransmissionColorMaps=[],this.directionalLights=[],this.cameras=[],this.spheres=[],this.bvhRoot=null,this.bvh=null,this.bvhData=null,this.bvhIndexChunks=null,this.bvhIndex=null,this.instanceTable=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this.performanceMetrics={textureCreationTime:0,geometryExtractionTime:0,bvhBuildTime:0,blasBuildTime:0,blasWorkerTime:0,tlasBuildTime:0,bvhAssembleTime:0,totalProcessingTime:0}}_disposeTextures(){this._disposeBucketTextures()}_disposeBucketTextures(){for(let e of[`srgbBucketTextures`,`linearBucketTextures`]){let t=this[e];if(t){for(let n of t)if(n&&typeof n.dispose==`function`)try{n.dispose()}catch(t){Gc.warn(`error disposing ${e}:`,t)}this[e]=null}}}async rebuildMaterials(e){if(this.isProcessing)throw Error(`Already processing. Cannot rebuild materials during processing.`);this._log(`Rebuilding materials and textures`);let t=performance.now();try{this.isProcessing=!0;let n=this.geometryExtractor.extractMaterialsOnly(e);this._disposeMaterialTextures(),this.materials=n.materials,this.meshes=n.meshes,this._adoptTextureLists(n),await this._createMaterialTextures();let r=performance.now()-t;return this._log(`Material rebuild complete (${r.toFixed(2)}ms)`,{materials:this.materials.length,textures:this.maps.length}),this}catch(e){throw Gc.error(`material rebuild failed:`,e),e}finally{this.isProcessing=!1}}_adoptTextureLists(e){for(let t of Kc)this[t]=e[t]??[]}_disposeMaterialTextures(){this._disposeBucketTextures(),this.textureCreator&&this.textureCreator.textureCache&&(this.textureCreator.textureCache.dispose(),this.textureCreator.textureCache=new this.textureCreator.textureCache.constructor)}getStatistics(){let e={triangleCount:this.triangleCount,materialCount:this.materials.length,textureCount:this.maps.length,lightCount:this.directionalLights.length,cameraCount:this.cameras.length,processingComplete:this.processingStage===`complete`,hasBVH:!!this.bvhRoot,hasTextures:!!this.materialData&&!!this.bvh,useFloat32Array:this.config.useFloat32Array,triangleDataSize:this.triangles?(this.triangles.byteLength/(1024*1024)).toFixed(2)+`MB`:`0MB`};return this.performanceMetrics.totalProcessingTime>0&&(e.performance={totalTime:this.performanceMetrics.totalProcessingTime,textureTime:this.performanceMetrics.textureCreationTime,bvhTime:this.performanceMetrics.bvhBuildTime,extractionTime:this.performanceMetrics.geometryExtractionTime,texturePercentage:(this.performanceMetrics.textureCreationTime/this.performanceMetrics.totalProcessingTime*100).toFixed(1)+`%`}),this.textureCreator&&this.textureCreator.capabilities&&(e.textureCapabilities=this.textureCreator.capabilities),e}updateConfig(e){Object.assign(this.config,e),this.bvhBuilder&&(this.bvhBuilder.maxLeafSize=this.config.maxLeafSize),this._log(`Configuration updated`,this.config)}_adoptSharedChunks(e,t){let n=this[e];if(n.shared)return;let r=n.chunks.map(e=>{let n=new t(new SharedArrayBuffer(e.byteLength));return n.set(e),n}),i=fn.adopt(r,n.recordCount,n.lanesPerRecord,n.recordsPerChunk);e===`bvh`?this._setBVHData(i):this._setTriangleData(i)}_meshSource(e,t){if(e==null)return null;let n=this.instanceTable;if(typeof e==`function`)return r=>{let i=n.sourceMesh[r],a=e(i,n.triCountOf(r)),o=n.triCountOf(r)*9;if(a&&a.length!==o)throw Error(`SceneProcessor: ${t}s for mesh ${i} must be ${o} floats (${n.triCountOf(r)} triangles × 9), got ${a.length}.`);return a??null};let r=(this.expandedTriangleCount??this.triangleCount)*9;if(e.length!==r)throw Error(`SceneProcessor: expected ${r} ${t} floats (${r/9} triangles × 9, full scene), got ${e.length}. Pass a per-mesh callback instead to avoid building one array for the whole scene.`);return t=>{let r=n.expandedStartOf(t)*9;return e.subarray(r,r+n.triCountOf(t)*9)}}async refitBVH(e,t){if(this._geometryVersion=(this._geometryVersion??0)+1,!this.bvh||!this.triangles||!this.instanceTable)throw Error(`No BVH data available for refit. Run buildBVH() first.`);let n=this._meshSource(e,`position`),r=this._meshSource(t,`normal`);if(!n)throw Error(`SceneProcessor.refitBVH: positions are required.`);if(this._refitWorker||=jr(Ac),!this._refitSharedBuffers){this._adoptSharedChunks(`bvh`,Float32Array),this._adoptSharedChunks(`triangles`,Uint32Array);let e=this.bvh.chunks.map(e=>e.buffer),t=this.triangles.chunks.map(e=>e.buffer);this._refitSharedBuffers={bvhBufs:e,triBufs:t},this._refitWorker.postMessage({type:`init`,sharedBvhBufs:e,bvhRecordCount:this.bvh.recordCount,bvhRecordsPerChunk:this.bvh.recordsPerChunk,sharedTriBufs:t,triRecordCount:this.triangles.recordCount,triLanesPerRecord:this.triangles.lanesPerRecord,triRecordsPerChunk:this.triangles.recordsPerChunk})}let i=this.instanceTable,a=G.FLOATS_PER_TRIANGLE,o=[],s=[],c=[],l=0;for(let e=0;e<i.count;e++){if(!i.isSet[e]||!i.isOwner(e))continue;l++;let t=n(e);if(!t)continue;if(this._updateMeshTrianglePositions(e,t),s.push(i.blasOffsetOf(e),i.blasNodeCountOf(e)),c.push(e),r){let t=r(e);t&&this._patchMeshSmoothNormals(e,t)}let u=i.triOffsetOf(e)*a,d=i.triCountOf(e)*a,f=o.at(-1);f&&f.offset+f.count===u?f.count+=d:o.push({offset:u,count:d})}let u=i.tlasNodeCount,d=u>0&&s.length/2<l,f=d?[this.computeTLASDirtyRange()]:null;for(let e=0;d&&e<s.length;e+=2)f.push({offset:s[e]*16,count:s[e+1]*16});return new Promise((e,t)=>{this._refitWorker.onmessage=n=>{let r=n.data;if(r.type===`refitComplete`){for(let e of c)i.recomputeAABB(e,this.bvh,this.triangles);i.computeGroupAABBs();let t=this._hiddenGroupLeaves();t.length&&this._refitTLAS(t),e({refitTimeMs:r.refitTimeMs,triRanges:o,bvhRanges:f})}else r.type===`error`&&t(Error(r.error))},this._refitWorker.postMessage({type:`refit`,blasRanges:d?s:null,tlasNodeCount:u,groupRange:i.groupNodeCount?[i.groupNodeStart,i.groupNodeCount]:null,treeNodeCount:i.treeNodeCount,recordNodeStart:i.clusterCount?i.recordNodeStart:-1})})}_patchSmoothNormals(e){let t=this.instanceTable;if(t)for(let n=0;n<t.count;n++){if(!t.isSet[n]||!t.isOwner(n))continue;let r=e(n);r&&this._patchMeshSmoothNormals(n,r)}}_placementOf(e){return this.instanceTable?.placementRunOf(e)?.start??-1}refitBLASes(e,t,n){if(this._geometryVersion=(this._geometryVersion??0)+1,!this.instanceTable||!this.bvh||!this.triangles)throw Error(`No TLAS/BLAS data available. Run buildBVH() first.`);let r=this._meshSource(t,`position`),i=this._meshSource(n,`normal`);if(!r)throw Error(`SceneProcessor.refitBLASes: positions are required.`);let a=performance.now();this._blasRefitter||=new Sa;let o=this.instanceTable;for(let t of e){let e=this._placementOf(t);if(e<0||!o.isSet[e])continue;if(!o.isOwner(e)){let n=o.tplOwner[o.sourceMesh[e]];this.config.issues?.record(Y.REFIT_SHARED_GEOMETRY,`mesh ${t} shares its triangles with another placement; deforming it would move every copy, so it was skipped`,{meshIndex:t,owner:o.sourceMesh[n]??n});continue}let n=r(e);if(n){if(this._updateMeshTrianglePositions(e,n),i){let t=i(e);t&&this._patchMeshSmoothNormals(e,t)}this._blasRefitter.refitRange(this.bvh,this.triangles,o.blasOffsetOf(e),o.blasNodeCountOf(e)),this.instanceTable.recomputeAABB(e,this.bvh,this.triangles)}}return this._writeGroupNodes(),this._refitTLAS(),{refitTimeMs:performance.now()-a}}updateMeshTransforms(e){if(!this.instanceTable||!this.bvh)throw Error(`No TLAS/BLAS data available. Run buildBVH() first.`);let t=performance.now(),n=this.instanceTable,r=this._transformScratch??=new Float32Array(16),i=[];for(let t of this._withGroupSiblings(e)){let e=this.meshes?.[t],a=n.placementRunOf(t);if(!e||!a)continue;e.updateMatrixWorld(!0);let o=e.matrixWorld.elements,s=e.isInstancedMesh?e.instanceMatrix?.array??null:null,c=n.tplBakeInverse?.get(n.sourceMesh[a.start])??null;for(let e=0;e<a.count;e++){let t=a.start+e;if(!n.isSet[t])continue;s?(Va(o,s,e*16,r),n.setPlacementMatrix(t,r)):c?(Va(o,c,0,r),n.setPlacementMatrix(t,r)):n.setPlacementMatrix(t,o),this._writeLeafMatrix(t);let l=n.leafOfPlacement(t);l>=0&&i.push(l)}}return this._refitTLAS(i),{refitTimeMs:performance.now()-t,placements:i.length}}_hiddenGroupLeaves(){let e=this.instanceTable,t=[];for(let n of e.groups)if(!n.members.every((t,r)=>e.visible[n.starts[r]]))for(let r=0;r<n.count;r++)t.push(e.leafOfPlacement(n.starts[0]+r));return t}_withGroupSiblings(e){let t=this.instanceTable;if(!t.groups.length)return e;let n=new Set(e),i=new Set,a=this._parentInverse??=new r.Matrix4;for(let r of e){let e=t.groupOfTemplate[r]??-1;if(e<0||i.has(e))continue;i.add(e);let o=this.meshes?.[r];if(o){o.updateMatrixWorld(!0);for(let r of t.groups[e].members){n.add(r);let e=this.meshes[r];!e||e===o||(e.parent&&e.parent.updateMatrixWorld(!0),e.matrix.copy(o.matrixWorld),e.parent&&e.matrix.premultiply(a.copy(e.parent.matrixWorld).invert()),e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0))}}}return n}_writeLeafMatrix(e){let t=this.instanceTable,n=t.tlasLeafIndex[e];if(!(n<0)){if(t.clusterCount){this._writeCopyRecord(n,t.repOf(t.entryOf(e)));return}oo.writeLeafMatrix(this.bvh.chunkFor(n),this.bvhIndexChunks.chunkFor(n),this.bvh.baseOf(n),t,e,t.entryOf(e))}}_writeCopyRecord(e,t){let n=this.instanceTable,r=this._recordScratch??=new Float32Array(12);n.writeRecord(r,0,t);let i=n.recordNodeStart*16+e*3*4;for(let e=0;e<12;e++){let t=i+e>>4;this.bvh.chunkFor(t)[this.bvh.baseOf(t)+(i+e&15)]=r[e]}let a=n.clusterLeaf[n.clusterOf(e)],o=this.bvhIndexChunks.chunkFor(a),s=this.bvh.baseOf(a)+n.copyWordSlot(e),c=Ha(n.matrixWorldOf(t));o[s]=(o[s]&~wt|(c?wt:0))>>>0;let l=this._movedRecords??=new Map,u=this.bvh.recordsPerChunk*16;for(let e=i,t=i+12;e<t;){let n=Math.floor(e/u),r=Math.min(t,(n+1)*u),i=l.get(n);i?(i.lo=Math.min(i.lo,e),i.hi=Math.max(i.hi,r)):l.set(n,{lo:e,hi:r}),e=r}}takeMoveRanges(){let e=this._tlasRanges??[this.computeTLASDirtyRange()];return this._tlasRanges=null,[...e,...this.takeMovedRecordRanges()]}takeMovedRecordRanges(){let e=this._movedRecords;return this._movedRecords=null,e?[...e.values()].map(e=>({offset:e.lo,count:e.hi-e.lo})):[]}_writeGroupNodes(){let e=this.instanceTable;!e?.groupNodeCount||!this.bvh||(e.computeGroupAABBs(),this.bvh.setRecords(e.groupNodeStart,e.groupNodeBlock()))}computeTLASDirtyRange(){return{offset:0,count:this.instanceTable.blasBase*16}}computeBLASDirtyRanges(e){let t=G.FLOATS_PER_TRIANGLE,n=[],r=[];for(let i of e){let e=this.instanceTable,a=this._placementOf(i);a<0||!e.isSet[a]||(n.push({offset:e.triOffsetOf(a)*t,count:e.triCountOf(a)*t}),r.push({offset:e.blasOffsetOf(a)*16,count:e.blasNodeCountOf(a)*16}))}return r.push({offset:0,count:this.instanceTable.blasBase*16}),{triRanges:n,bvhRanges:r}}async uploadChunks(e){for(let[t,n]of[[this.triangles,`triangles`],[this.bvh,`bvh`]]){if(!t?.chunks||t.chunks.length<2||t._gpuUpload)continue;let r=e(t,n,{textureCoordinates:this.textureCoordinates});for(let e=0;e<t.chunks.length;e++)t.chunks[e]&&await r(e)}}uploadToPathTracer(e,t,n,r,{keepUserLights:i=!1}={}){return this.triangles?(e.setTriangleData(this.triangles,this.triangleCount,{textureCoordinates:this.textureCoordinates}),this.bvh?(e.setBVHData(this.bvh),e.setInstanceTable(this.instanceTable),this.materialData?e.materialData.setMaterialData(this.materialData,this.materials.map(e=>e.sources)):Gc.warn(`no material data, using defaults`),r&&e.environment.setEnvironmentTexture(r),e.materialData.setMaterialTextures({srgbBuckets:this.srgbBucketTextures,linearBuckets:this.linearBucketTextures}),e.materialData.setTexturePackMaps?.(this._srgbTexPacked,this._linearTexPacked),this.emissiveTriangleData&&(e.setEmissiveTriangleData(this.emissiveTriangleData,this.emissiveTriangleCount,this.emissiveTotalPower,this.emissiveBitTrailMap),this._releaseBitTrailMap()),this.lightBVHNodeData&&e.setLightBVHData(this.lightBVHNodeData,this.lightBVHNodeCount),t.transferSceneLights(n,{keepUserLights:i}),!0):(Gc.error(`failed to get BVH data`),!1)):(Gc.error(`failed to get triangle data`),!1)}updateMaterialEmissive(e,t,n){if(!this.emissiveTriangleBuilder)return null;let r=this.materials[e];return!r||(t===`emissive`?r.emissive=n:t===`emissiveIntensity`&&(r.emissiveIntensity=n),!this.emissiveTriangleBuilder.updateMaterialEmissive(e,r,this.triangles,this.materials,this.triangleCount))?null:this._collectEmissivePayload()}rebuildEmissiveColors(){return!this.emissiveTriangleBuilder||!this.triangleCount?null:(this.emissiveTriangleBuilder.extractEmissiveTriangles(this.triangles,this.materials,this.triangleCount,this.instanceTable??null),this.emissiveTriangleBuilder.createEmissiveRawData(),this._collectEmissivePayload())}rebuildEmissiveForVisibility(e,t=!1){return!this.emissiveTriangleBuilder||!this.emissiveTriangleBuilder.setHiddenMeshes(e)&&!t?null:this._collectEmissivePayload()}movesEmitters(e){let t=this.emissiveTriangleBuilder?.emissiveMeshes;return!!t?.size&&e.some(e=>t.has(e))}refreshEmissiveTransforms(){let e=this.emissiveTriangleBuilder;return!e?.emissiveTriangles.length||!this.instanceTable||!this.triangles?null:(e.refreshTransforms(this.triangles,this.instanceTable),this._collectEmissivePayload())}_collectEmissivePayload(){this.emissiveTriangleBuilder.buildLightBVH(),this.lightBVHNodeData=this.emissiveTriangleBuilder.lightBVHNodeData,this.lightBVHNodeCount=this.emissiveTriangleBuilder.lightBVHNodeCount,this.emissiveTriangleData=this.emissiveTriangleBuilder.emissiveTriangleData,this.emissiveBitTrailMap=this.emissiveTriangleBuilder.emissiveBitTrailMap,this.emissiveTriangleCount=this.emissiveTriangleBuilder.emissiveCount,this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower;let e=this.emissiveBitTrailMap;return this._releaseBitTrailMap(),{rawData:this.emissiveTriangleData,emissiveCount:this.emissiveTriangleCount,totalPower:this.emissiveTotalPower,bitTrailMap:e,lightBVHNodeData:this.lightBVHNodeData,lightBVHNodeCount:this.lightBVHNodeCount}}get spilled(){return!!(this.triangles?.spilledChunks||this.bvh?.spilledChunks||this._orderSpill)}async spillToDisk(e){let t=this.triangles,n=this.bvh;if(!e||this.spilled||this._spillStores||!t?.chunks||t.chunks.length<2||!n?.chunks)return null;await this._blasStoring;let r=this._geometryVersion,i=performance.now(),a=`spill:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`,o=e=>e.recordsPerChunk*e.lanesPerRecord*e.LaneType.BYTES_PER_ELEMENT,s=await yn.create(e,`${a}:tri`,o(t),{label:`Triangle records`,expectedBytes:t.byteLength}),c=s&&await yn.create(e,`${a}:bvh`,o(n),{label:`BLAS nodes`,expectedBytes:n.byteLength});if(!s||!c)return await s?.dispose(),null;this._spillStores=[s,c];let l=Math.ceil((this.instanceTable?.blasBase??1)/n.recordsPerChunk),u=await t.spill(s);if(u+=await n.spill(c,{keep:e=>e<l}),await s.flush(),await c.flush(),r!==this._geometryVersion)return null;let d=performance.now()-i;return Gc.info(`spilled ${(u/1048576).toFixed(0)} MB of triangles and BLAS nodes to disk in ${d.toFixed(0)} ms`),{bytes:u,ms:d}}ensureResident(){return this._paging??=(async()=>{await this.triangles?.ensureResident?.(),await this.bvh?.ensureResident?.(),await this._restoreOrderMaps(),this.spilled||this._disposeSpill()})().finally(()=>{this._paging=null}),this._paging}get geometryOnDisk(){return!!this._geometryOwner}ensureGeometryResident(){let e=this._geometryOwner?this._geometryReading??=this._restoreGeometry(this._geometryOwner).finally(()=>{this._geometryReading=null}):null;return Promise.all([e,this.ensureMovable()])}get matricesOnDisk(){return!!this._matrixSpill}async ensureMovable(e=[]){this._movePageIns=(this._movePageIns??0)+1;try{await this._afterLoadSpill;let t=this._matrixSpill;t&&await(this._matrixReading??=t.restore().then(()=>this._disposeMatrixSpill()).finally(()=>{this._matrixReading=null}));let n=this.instanceTable,r=this.bvh;if(!e.length||!n||!r?.spilledChunks)return;await r.ensureResident(0,n.blasBase);for(let t of this._recordChunksOf(e))await r.ensureResident(t*r.recordsPerChunk,1)}finally{this._movePageIns--}}async _spillMatrices(e=!1){let t=this.instanceTable,n=t?.adoptedMatrices()??[],i=this._spillMeshBounds;if(this._spillMeshBounds=null,!n.length||!this._progressive?.storage)return;let a=await On.create(this._progressive.storage,`spill:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}:mat`);if(!a)return;for(let[n,a]of i??this._instancedMeshBounds((e,n)=>t.writeEntryWorldAABB(e,n,0),e))n.boundingBox=new r.Box3(new r.Vector3(a[0],a[1],a[2]),new r.Vector3(a[3],a[4],a[5])),n.boundingSphere=n.boundingBox.getBoundingSphere(new r.Sphere);let o=n.reduce((e,t)=>e+t.array.byteLength,0);a.addAttributes(n),this._matrixSpill=a,Gc.info(`${H.mb(o)} of instance matrices left for disk`)}async _spillTLAS(){let e=this.instanceTable,t=this.bvh,n=this._bvhSpillStore;if(!n||!e?.clusterCount)return;let r=t.recordsPerChunk,i=e.groupNodeStart/r|0,a=(e.groupNodeStart+Math.max(1,e.groupNodeCount)-1)/r|0;this._spilledRootBounds=this.sceneBounds();let o=await t.spill(n,{keep:t=>e.groupNodeCount>0&&t>=i&&t<=a});Gc.info(`spilled ${H.mb(o)} of TLAS to disk`)}async _spillOrderMaps(){let e=this.instanceTable,t=this._progressive?.storage;if(!e?.bvhToOriginal.size||!t)return;let n=0;for(let t of e.bvhToOriginal.values())n+=t.byteLength;let r=await yn.create(t,`spill:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}:order`,0,{label:`Triangle order maps`,expectedBytes:n});if(!r)return;let i=[],a=new Uint8Array(Hc),o=0,s=0,c=async()=>{s&&await r.writeAt(o-s,a.subarray(0,s)),s=0};for(let[t,n]of e.bvhToOriginal){let e=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);i.push(t,o,n.length),s+e.length>a.length&&await c(),e.length>a.length?await r.writeAt(o,e):(a.set(e,s),s+=e.length),o+=e.length}await c(),await r.flush(),e.bvhToOriginal.clear(),this._orderSpill={store:r,index:i,bytes:n}}async _restoreOrderMaps(){let e=this._orderSpill;if(!e)return;this._orderSpill=null;let{store:t,index:n,bytes:r}=e,i=this.instanceTable.bvhToOriginal,a=0,o=null;for(let e=0;e<n.length;e+=3){let s=n[e],c=n[e+1],l=n[e+2]*4;if(l>Uc){i.set(s,new Uint32Array(await t.readAt(c,l)));continue}(!o||c+l>a+o.byteLength)&&(a=c,o=await t.readAt(c,Math.min(Uc,r-c))),i.set(s,new Uint32Array(o.slice(c-a,c-a+l)))}await t.dispose()}spillAfterLoad(){return!this._geometryOwner||this._spilledAfterLoad?this._afterLoadSpill??Promise.resolve():(this._spilledAfterLoad=!0,this._spillUnused(!1))}respill(){return!this._geometryOwner||!this._spilledAfterLoad||this._afterLoadSpill?this._afterLoadSpill??Promise.resolve():this._matrixReading||this._tlasReading||this._movePageIns?Promise.resolve():this._spillUnused(!0)}_spillUnused(e){return this._afterLoadSpill=(async()=>{await this._spillMatrices(e),await this._spillTLAS(),await this._spillOrderMaps()})().finally(()=>{this._afterLoadSpill=null}),this._afterLoadSpill}whenTLASEditable(){if(this._afterLoadSpill)return this._afterLoadSpill.then(()=>this.whenTLASEditable());let e=this.bvh,t=this.instanceTable;return!e||!t||e.isResident(0,t.blasBase)?null:this._tlasReading??=e.ensureResident(0,t.blasBase).finally(()=>{this._tlasReading=null})}needsPageInForMove(e){if(this._matrixSpill||this._afterLoadSpill)return!0;let t=this.instanceTable,n=this.bvh;if(!t||!n?.spilledChunks)return!1;if(!n.isResident(0,t.blasBase))return!0;for(let t of this._recordChunksOf(e))if(!n.isResident(t*n.recordsPerChunk,1))return!0;return!1}_recordChunksOf(e){let t=this.instanceTable,n=this.bvh.recordsPerChunk,r=new Set;if(!t.clusterCount)return r;let i=new Set(e);for(let n of e){let e=t.groupOfTemplate?.[n]??-1;if(e>=0)for(let n of t.groups[e].members)i.add(n)}for(let e of i){let i=t.placementRunOf(e);if(i)for(let e=i.start;e<i.start+i.count;e++){let i=t.tlasLeafIndex[e];if(i<0)continue;let a=t.recordNodeStart*16+i*3*4;r.add(Math.floor(a/16/n)),r.add(Math.floor((a+11)/16/n))}}return r}_instancedMeshBounds(e,t=!1){let n=this.instanceTable,r=new Set(n.adoptedMatrices()),i=new Map,a=new Float64Array(6);return(this.meshes??[]).forEach((o,s)=>{if(!o?.isInstancedMesh||!r.has(o.instanceMatrix)||t&&o.boundingBox)return;let c=n.placementRunOf(s);if(!c)return;let l=[1/0,1/0,1/0,-1/0,-1/0,-1/0];for(let t=c.start;t<c.start+c.count;t++){e(n.entryOf(t),a);for(let e=0;e<3;e++)a[e]<l[e]&&(l[e]=a[e]),a[3+e]>l[3+e]&&(l[3+e]=a[3+e])}i.set(o,l)}),i}_disposeMatrixSpill(){let e=this._matrixSpill;this._matrixSpill=null,e?.dispose().catch(()=>{})}async _restoreGeometry(e){let t=this._geometrySpill;if(!t?.bytes){this._geometryOwner=null;return}this._geometryOwner||z({status:`Reading scene geometry back...`,progress:84});let n=performance.now(),r=t.bytes;await t.restore(),this._disposeGeometrySpill(),this._geometryBytes=Nn(e),Gc.info(`read ${H.mb(r)} of scene geometry back from disk in ${H.ms(performance.now()-n)}`),t.error&&Gc.warn(`some scene geometry stayed in memory, its spill write failed:`,t.error)}_disposeGeometrySpill(){let e=this._geometrySpill;this._geometrySpill=null,this._geometryOwner=null,e?.dispose().catch(()=>{})}_disposeSpill(){let e=this._spillStores;this._spillStores=null;for(let t of e??[])t.dispose().catch(()=>{})}_releaseBitTrailMap(){this.emissiveBitTrailMap=null,this.emissiveTriangleBuilder&&(this.emissiveTriangleBuilder.emissiveBitTrailMap=null)}_clusterCopies(e){let t=this.config.clusterCopies??`auto`;return t===`auto`?e.entryCount>=zc:t===!0}async _writeCopyRecords(e){let t=this.instanceTable,n=t.entryCount,r=4096,i=r*3/4,a=new Float32Array(i*16);for(let o=0;o<n;o+=r){let s=Math.min(r,n-o);a.fill(0);for(let e=0;e<s;e++)t.writeRecord(a,e*3*4,t.repOf(t.recordEntry[o+e]));let c=t.recordNodeStart+o*3/4,l=Math.ceil(s*3/4);this.bvh.setRecords(c,l===i?a:a.subarray(0,l*16)),await e?.(c+l)}}async _buildTLAS(e){let t=e.clusterCount>0,n=t?e.clusterCount:e.entryCount;if(n>=Pc&&!this._tlasWorkerFailed)try{let r=t?e.clusterBounds:new Float64Array(n*6);t||e.writeEntryWorldAABBs(r);let{tlasData:i,nodeCount:a}=await this._runTLASWorker(r,n);return oo.fillLeaves(i,a,e),i}catch(e){this._tlasWorkerFailed=!0,Gc.warn(`TLAS worker unavailable (${e.message}); building on the main thread`)}return this.tlasBuilder.build(e).data}_runTLASWorker(e,t){this._tlasWorker||=jr(Nc);let n=this._tlasWorker;return new Promise((r,i)=>{let a=e=>{n.removeEventListener(`message`,a),n.removeEventListener(`error`,o),e.data?.error?i(Error(e.data.error)):r(e.data)},o=e=>{n.removeEventListener(`message`,a),n.removeEventListener(`error`,o),i(Error(e.message||`worker error`))};n.addEventListener(`message`,a),n.addEventListener(`error`,o),n.postMessage({aabbs:e.buffer,count:t,logLevel:B()},[e.buffer])})}_setBVHData(e){let t=e?e instanceof fn?e:fn.adopt([e],e.length/16,16,e.length/16):null;this.bvh=t,t&&this._foldLeaves&&(t.foldedLeaves=!0),t&&this.instanceTable?.clusterCount&&(t.copyRecordBase=this.instanceTable.recordNodeStart*4),this.bvhIndexChunks=t?t.viewAs(Uint32Array):null,this.bvhData=t?t.single:null,this.bvhIndex=this.bvhIndexChunks?this.bvhIndexChunks.single:null}_setTriangleData(e){let t=G.FLOATS_PER_TRIANGLE,n=e?e instanceof fn?e:fn.adopt([e],e.length/t,t,e.length/t):null;this.triangles=n,this.triangleFloatChunks=n?n.viewAs(Float32Array):null,this.triangleData=n?n.single:null,this.triangleFloats=this.triangleFloatChunks?this.triangleFloatChunks.single:null}_updateMeshTrianglePositions(e,t){let n=G.POSITION_A_OFFSET,r=G.POSITION_B_OFFSET,i=G.POSITION_C_OFFSET,a=G.NORMAL_A_PACKED_OFFSET,o=G.NORMAL_B_PACKED_OFFSET,s=G.NORMAL_C_PACKED_OFFSET,c=this.triangles,l=this.triangleFloatChunks,u=this.instanceTable,d=u.bvhToOriginalOf(e),f=u.triOffsetOf(e),p=u.triCountOf(e),m=u.matrixInverseOf(e),h=Ha(m);for(let e=0;e<p;e++){let u=d?d[e]:e,p=f+e,g=l.chunkFor(p),_=c.chunkFor(p),v=c.baseOf(p),y=u*9,b=t[y],x=t[y+1],S=t[y+2],C=t[y+3],w=t[y+4],T=t[y+5],E=t[y+6],D=t[y+7],O=t[y+8];if(!h){let e=(e,t,n)=>m[0]*e+m[4]*t+m[8]*n+m[12],t=(e,t,n)=>m[1]*e+m[5]*t+m[9]*n+m[13],n=(e,t,n)=>m[2]*e+m[6]*t+m[10]*n+m[14],r=[e(b,x,S),t(b,x,S),n(b,x,S)],i=[e(C,w,T),t(C,w,T),n(C,w,T)],a=[e(E,D,O),t(E,D,O),n(E,D,O)];b=r[0],x=r[1],S=r[2],C=i[0],w=i[1],T=i[2],E=a[0],D=a[1],O=a[2]}g[v+n]=b,g[v+n+1]=x,g[v+n+2]=S,g[v+r]=C,g[v+r+1]=w,g[v+r+2]=T,g[v+i]=E,g[v+i+1]=D,g[v+i+2]=O;let k=C-b,A=w-x,j=T-S,M=E-b,N=D-x,P=O-S,F=ht(A*P-j*N,j*M-k*P,k*N-A*M);_[v+a]=F,_[v+o]=F,_[v+s]=F}}_patchMeshSmoothNormals(e,t){let n=this.instanceTable;this._patchNormalsRange(t,n.triOffsetOf(e),n.triCountOf(e),n.matrixWorldOf(e),n.bvhToOriginalOf(e))}_patchNormalsRange(e,t,n,r,i){let a=G.NORMAL_A_PACKED_OFFSET,o=G.NORMAL_B_PACKED_OFFSET,s=G.NORMAL_C_PACKED_OFFSET,c=r,l=!c||Ha(c),u=[a,o,s];for(let r=0;r<n;r++){let n=t+r,a=this.triangles.chunkFor(n),o=this.triangles.baseOf(n),s=(i?i[r]:r)*9;for(let t=0;t<3;t++){let n=s+t*3,r=e[n],i=e[n+1],d=e[n+2],f=r,p=i,m=d;if(!l){f=c[0]*r+c[1]*i+c[2]*d,p=c[4]*r+c[5]*i+c[6]*d,m=c[8]*r+c[9]*i+c[10]*d;let e=Math.hypot(f,p,m)||1;f/=e,p/=e,m/=e}a[o+u[t]]=ht(f,p,m)}}}_refitTLAS(e=null){let t=this.instanceTable,n=t.tlasNodeCount,r=e?Int32Array.from(e).sort():null;if(this._tlasRanges=r?[]:null,!n||r?.length===0)return;let i=r?Array.from(r):null,a=this._refitStack??=new Int32Array(256),o=0,s=0,c=this._refitBox??=new Float32Array(6),l=(e,t,n,r)=>{if(o+4>a.length){let e=new Int32Array(a.length*2);e.set(a),a=this._refitStack=e}a[o++]=e,a[o++]=t,a[o++]=n,a[o++]=r};for(l(0,n,-1,0);o;){let e=a[--o],n=a[--o],u=a[--o],d=a[--o],f=this.bvh.chunkFor(d),p=this.bvh.baseOf(d);if(e)c[0]=Math.min(f[p],f[p+8]),c[1]=Math.min(f[p+1],f[p+9]),c[2]=Math.min(f[p+2],f[p+10]),c[3]=Math.max(f[p+4],f[p+12]),c[4]=Math.max(f[p+5],f[p+13]),c[5]=Math.max(f[p+6],f[p+14]);else{if(r){for(;s<r.length&&r[s]<d;)s++;if(s===r.length||r[s]>=u)continue}let e=this.bvhIndexChunks.chunkFor(d),i=e[p+3];if(i===Et.BLAS_POINTER_LEAF){let n=e[p+1]&Tt;if(n>=t.entryCount)continue;t.writeEntryWorldAABB(n,c,0)}else if(i===Et.CLUSTER_LEAF)t.encodeClusterBoxes(f,e,p,t.clusterOf(e[p]&Dt),null,c,0);else if(i<Et.TRIANGLE_LEAF){let t=e[p+7];l(d,u,n,1),l(t,u,d*2+1,0),l(i,t,d*2,0);continue}else continue}if(n<0)continue;let m=n>>1,h=this.bvh.chunkFor(m),g=this.bvh.baseOf(m)+(n&1)*8;h[g]=c[0],h[g+1]=c[1],h[g+2]=c[2],h[g+4]=c[3],h[g+5]=c[4],h[g+6]=c[5],i?.push(m)}i&&(this._tlasRanges=el(i))}scheduleBackgroundRebuild(e,t){if(!this.instanceTable||!this.triangles)return;this._rebuildGeneration++;let n=this._rebuildGeneration,r=(e,r,i)=>{let a=this.triangles.copyOf(r.triOffset,r.triCount);this._pendingRebuilds.set(e,i),i.onmessage=a=>{let o=a.data;if(i.terminate(),this._pendingRebuilds.delete(e),o.error){Gc.error(`background BLAS rebuild failed (mesh ${e}):`,o.error);return}n===this._rebuildGeneration&&this._swapBLAS(e,r,o,t)},i.onerror=t=>{Gc.error(`background BLAS rebuild worker failed (mesh ${e}):`,t),i.terminate(),this._pendingRebuilds.delete(e)},i.postMessage({triangleData:a.buffer,triangleByteOffset:a.byteOffset,triangleByteLength:a.byteLength,triangleCount:r.triCount,depth:this.config.bvhDepth,maxLeafSize:this.bvhBuilder.maxLeafSize,foldLeaves:this._foldLeaves===!0,numBins:this.bvhBuilder.numBins,maxBins:this.bvhBuilder.maxBins,minBins:this.bvhBuilder.minBins,reportProgress:!1,sharedReorderBuffer:null,reinsertionOptimization:{enabled:this.bvhBuilder.enableReinsertionOptimization,batchSizeRatio:this.bvhBuilder.reinsertionBatchSizeRatio,maxIterations:this.bvhBuilder.reinsertionMaxIterations}},[a.buffer])};for(let t of e){let e=this._placementOf(t);if(e<0)continue;let n=this.instanceTable.entryAt(e);if(!n||!this.instanceTable.isOwner(e))continue;let i=this._pendingRebuilds.get(e);i&&i.terminate(),r(e,n,jr(Ta))}}_swapBLAS(e,t,n,r){this._geometryVersion=(this._geometryVersion??0)+1;let i=n.bvhData,a=i.length/16;if(a>t.blasNodeCount){Gc.warn(`background rebuild does not fit for mesh ${e} (${a} nodes vs ${t.blasNodeCount} reserved), skipping swap`);return}this.bvh.setRecords(t.blasOffset,i),this._offsetBLASInPlace(t.blasOffset,a,t.blasOffset,t.triOffset);let o=n.triangles;o&&this.triangles.setRecords(t.triOffset,o),this.instanceTable.setBlasNodeCount(e,a);let s=n.originalToBvh;if(s){let n=this.instanceTable.bvhToOriginalOf(e),r=new Uint32Array(t.triCount);for(let e=0;e<t.triCount;e++)r[s[e]]=n?n[e]:e;this.instanceTable.setBvhToOriginal(e,r)}this.instanceTable.recomputeAABB(e,this.bvh,this.triangles),this._refitTLAS(),this._log(`Background BLAS rebuild complete for mesh ${e}`),r?.(this.instanceTable.sourceMesh[e]??e)}cancelBackgroundRebuilds(){for(let e of this._pendingRebuilds.values())e.terminate();this._pendingRebuilds.clear()}_disposeRefitWorker(){this._refitWorker&&=(this._refitWorker.terminate(),null),this._refitSharedBuffers=null,this.cancelBackgroundRebuilds()}_disposeTLASWorker(){this._tlasWorker&&=(this._tlasWorker.terminate(),null)}dispose(){this._geometryVersion=(this._geometryVersion??0)+1,this._log(`Disposing resources`),this._disposeRefitWorker(),this._disposeTLASWorker(),this._disposeTextures(),this._reset(),this.textureCreator&&=(this.textureCreator.dispose(),null),this.geometryExtractor=null,this.bvhBuilder=null,this.tlasBuilder=null,this._blasRefitter=null}},nl=[[1619.19106,-.00205010916,5.02995757],[2488.45471,-.00111330907,3.22621544],[3341.43193,-.000486551192,1.76486769],[4094.61742,-.000127446582,.725731635],[4670.28036,291258199e-13,.126703442],[4595.09185,287495649e-13,.15034502],[3787.1745,935907826e-14,.399075871]],rl=[[-488.999748,.000604330754,-.0755807526],[-755.994277,.000316730098,.478306139],[-1023.63977,.00012022347,.936662319],[-1265.71316,487340896e-14,1.27054498],[-1425.29332,-401150431e-13,1.43972784],[-1175.54822,-216378048e-13,1.30408023],[-500.799571,-459832026e-14,1.09098763]],il=[[596945309e-19,-4.85742887e-8,-970622247e-13,-.00407936148],[240430366e-19,5.55021075e-8,-.000198503712,.0289312858],[-140949732e-19,1.89878968e-7,-.000356632824,.0910767778],[-361460868e-19,2.84822009e-7,-.000493211319,.15672344],[-197075738e-19,1.75359352e-7,-.000250542825,-.0222783266],[-161997957e-21,-1.64216008e-8,.000386216271,-.738077418],[672650283e-21,-2.73078809e-8,.000424098264,-.752335691]];function al(e){let t,n,r;if(e>=12e3)t=.8262954810464208,n=.9945080501520986,r=1.566307710274283;else if(e<800)t=5.413294490189271,n=-.20319390035873933,r=-.0822535242887164;else{let i=e>=6365?6:e>=3315?5:e>=1902?4:e>=1449?3:e>=1167?2:+(e>=965),a=nl[i],o=rl[i],s=il[i],c=1/e;t=a[0]*c+a[1]*e+a[2],n=o[0]*c+o[1]*e+o[2],r=((s[0]*e+s[1])*e+s[2])*e+s[3]}return[Math.max(0,t),Math.max(0,n),Math.max(0,r)]}nr();var ol=1/(4*Math.PI);function sl(e){let t=e.userData||{},n=Number.isFinite(t.exposure)?t.exposure:0,r=e.intensity*2**n,i=[e.color.r,e.color.g,e.color.b];if(t.useTemperature){let[e,n,r]=al(t.temperature??6500);i[0]*=e,i[1]*=n,i[2]*=r}return Qn(i),{r:i[0],g:i[1],b:i[2],intensity:r}}var cl=e=>Math.max(0,Number(e.userData?.radius)||0),ll=class{constructor(){this.lightData={directional:[],rectArea:[],point:[],spot:[]},this.directionalLightCache=[],this.areaLightCache=[],this.pointLightCache=[],this.spotLightCache=[]}clear(){this.lightData.directional=[],this.lightData.rectArea=[],this.lightData.point=[],this.lightData.spot=[],this.directionalLightCache=[],this.areaLightCache=[],this.pointLightCache=[],this.spotLightCache=[]}calculateLightImportance(e,t=`directional`){let n=.2126*e.color.r+.7152*e.color.g+.0722*e.color.b,r=e.intensity*n;if(t===`area`){let t=e.width*e.height;r*=Math.sqrt(t)}else if(t===`point`)r*=Math.sqrt(e.distance||100);else if(t===`spot`){let t=Math.sin(e.angle||Math.PI/4);r*=Math.sqrt(e.distance||100)*t}return r}addDirectionalLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n;if(e.target){e.target.updateMatrixWorld();let i=e.target.getWorldPosition(new r.Vector3);n=t.sub(i).normalize()}else n=t.normalize();let i=this.calculateLightImportance(e,`directional`),a=e.userData.angle||e.angle||0,o=sl(e),s=e.userData?.gobo,c=s&&Number.isInteger(s.index)?s.index:-1,l=s&&typeof s.intensity==`number`?s.intensity:1,u=s&&s.inverted?-Math.abs(l):Math.abs(l),d=s&&typeof s.scale==`number`?s.scale:5;this.directionalLightCache.push({data:[n.x,n.y,n.z,o.r,o.g,o.b,o.intensity,a,c,u,d,0],importance:i,light:e})}addRectAreaLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n=e.getWorldQuaternion(new r.Quaternion),i=e.getWorldScale(new r.Vector3),a=e.width*i.x*.5,o=e.height*i.y*.5,s=new r.Vector3(a,0,0).applyQuaternion(n),c=new r.Vector3(0,-o,0).applyQuaternion(n),l=this.calculateLightImportance(e,`area`),u=e.userData?.normalize??!0?1:0,d=Number.isFinite(e.userData?.spread)?e.userData.spread:Math.PI,f=+(e.userData?.shape===`ellipse`||e.userData?.shape===`disk`||e.userData?.shape===1),p=sl(e);this.areaLightCache.push({data:[t.x,t.y,t.z,s.x,s.y,s.z,c.x,c.y,c.z,p.r,p.g,p.b,p.intensity,u,d,f],importance:l,light:e})}addPointLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n=this.calculateLightImportance(e,`point`),i=sl(e);this.pointLightCache.push({data:[t.x,t.y,t.z,i.r,i.g,i.b,i.intensity*ol,e.distance||0,e.decay===void 0?2:e.decay,cl(e)],importance:n,light:e})}addSpotLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n=(e.target?e.target.getWorldPosition(new r.Vector3):new r.Vector3(0,0,-1)).sub(t).normalize(),i=this.calculateLightImportance(e,`spot`),a=e.userData?.gobo,o=a&&Number.isInteger(a.index)?a.index:-1,s=a&&typeof a.intensity==`number`?a.intensity:1,c=a&&a.inverted?-Math.abs(s):Math.abs(s),l=e.userData?.ies,u=l&&Number.isInteger(l.index)?l.index:-1,d=l&&typeof l.intensity==`number`?l.intensity:1,f=sl(e);this.spotLightCache.push({data:[t.x,t.y,t.z,n.x,n.y,n.z,f.r,f.g,f.b,f.intensity*ol,e.angle||Math.PI/4,e.penumbra||0,e.distance||0,e.decay===void 0?2:e.decay,o,c,u,d,cl(e),0],importance:i,light:e})}preprocessLights(){this.directionalLightCache.sort((e,t)=>t.importance-e.importance),this.areaLightCache.sort((e,t)=>t.importance-e.importance),this.pointLightCache.sort((e,t)=>t.importance-e.importance),this.spotLightCache.sort((e,t)=>t.importance-e.importance),this.lightData.directional=[],this.lightData.rectArea=[],this.lightData.point=[],this.lightData.spot=[],this.directionalLightCache.forEach(e=>{this.lightData.directional.push(...e.data)}),this.areaLightCache.forEach(e=>{this.lightData.rectArea.push(...e.data)}),this.pointLightCache.forEach(e=>{this.lightData.point.push(...e.data)}),this.spotLightCache.forEach(e=>{this.lightData.spot.push(...e.data)}),this.areaLightCache.length>0&&console.log(`Preprocessed ${this.areaLightCache.length} area lights by importance`),this.pointLightCache.length>0&&console.log(`Preprocessed ${this.pointLightCache.length} point lights by importance`),this.spotLightCache.length>0&&console.log(`Preprocessed ${this.spotLightCache.length} spot lights by importance`)}updateShaderUniforms(e){let t=Math.floor(this.lightData.directional.length/12),n=Math.floor(this.lightData.rectArea.length/16),r=Math.floor(this.lightData.point.length/9),i=Math.floor(this.lightData.spot.length/20);e.defines.MAX_DIRECTIONAL_LIGHTS=t,e.defines.MAX_AREA_LIGHTS=n,e.defines.MAX_POINT_LIGHTS=r,e.defines.MAX_SPOT_LIGHTS=i,e.uniforms.directionalLights.value=new Float32Array(this.lightData.directional),e.uniforms.areaLights.value=new Float32Array(this.lightData.rectArea),e.uniforms.pointLights.value=new Float32Array(this.lightData.point),e.uniforms.spotLights.value=new Float32Array(this.lightData.spot),e.needsUpdate=!0}processSceneLights(e,t){this.clear(),e.traverse(e=>{e.isDirectionalLight?this.addDirectionalLight(e):e.isRectAreaLight?this.addRectAreaLight(e):e.isPointLight?this.addPointLight(e):e.isSpotLight&&this.addSpotLight(e)}),this.preprocessLights(),this.updateShaderUniforms(t)}getLightStatistics(){return{directionalLights:this.directionalLightCache.map(e=>({intensity:e.light.intensity,importance:e.importance,color:e.light.color})),areaLights:this.areaLightCache.map(e=>({intensity:e.light.intensity,importance:e.importance,color:e.light.color,size:e.light.width*e.light.height}))}}},ul,dl,fl,pl,ml,hl,gl,_l,vl,yl,bl,xl,Sl,Cl,wl,Tl,El=g((()=>{ul=x({origin:`vec3`,direction:`vec3`}),dl=x({color:`vec4`,emissive:`vec3`,emissiveIntensity:`float`,roughness:`float`,metalness:`float`,ior:`float`,transmission:`float`,thickness:`float`,clearcoat:`float`,clearcoatRoughness:`float`,opacity:`float`,transparent:`bool`,attenuationColor:`vec3`,attenuationDistance:`float`,dispersion:`float`,sheen:`float`,sheenRoughness:`float`,sheenColor:`vec3`,specularIntensity:`float`,specularColor:`vec3`,alphaTest:`float`,alphaMode:`int`,side:`int`,depthWrite:`int`,albedoMapIndex:`int`,emissiveMapIndex:`int`,normalMapIndex:`int`,bumpMapIndex:`int`,bumpScale:`float`,displacementScale:`float`,displacementBias:`float`,metalnessMapIndex:`int`,roughnessMapIndex:`int`,displacementMapIndex:`int`,normalScale:`vec2`,albedoTransform:`mat3`,emissiveTransform:`mat3`,normalTransform:`mat3`,bumpTransform:`mat3`,metalnessTransform:`mat3`,roughnessTransform:`mat3`,displacementTransform:`mat3`,iridescence:`float`,iridescenceIOR:`float`,iridescenceThicknessRange:`vec2`,subsurface:`float`,subsurfaceColor:`vec3`,subsurfaceRadius:`vec3`,subsurfaceRadiusScale:`float`,subsurfaceAnisotropy:`float`,anisotropy:`float`,anisotropyRotation:`float`,anisotropyMapIndex:`int`,transmissionMapIndex:`int`,clearcoatMapIndex:`int`,clearcoatRoughnessMapIndex:`int`,sheenColorMapIndex:`int`,sheenRoughnessMapIndex:`int`,iridescenceMapIndex:`int`,iridescenceThicknessMapIndex:`int`,specularIntensityMapIndex:`int`,specularColorMapIndex:`int`,diffuseTransmission:`float`,diffuseTransmissionColor:`vec3`,diffuseTransmissionMapIndex:`int`,diffuseTransmissionColorMapIndex:`int`}),fl=x({transmission:`float`,clearcoat:`float`,clearcoatRoughness:`float`,sheenColor:`vec3`,sheenRoughness:`float`,iridescence:`float`,iridescenceThickness:`float`,specularIntensity:`float`,specularColor:`vec3`,diffuseTransmission:`float`,diffuseTransmissionColor:`vec3`}),pl=x({color:`vec4`,ior:`float`,transmission:`float`,attenuationColor:`vec3`,attenuationDistance:`float`,albedoMapIndex:`int`,opacity:`float`,transparent:`bool`,alphaTest:`float`,alphaMode:`int`,albedoTransform:`mat3`}),ml=x({shadowed:`vec3`,unoccluded:`vec3`}),x({position:`vec3`,radius:`float`,material:dl}),hl=x({didHit:`bool`,dst:`float`,hitPoint:`vec3`,normal:`vec3`,uv:`vec2`,materialIndex:`int`,meshIndex:`int`,instanceLeaf:`int`,triangleIndex:`int`,boxTests:`int`,triTests:`int`}),x({posA:`vec3`,posB:`vec3`,posC:`vec3`,uvA:`vec2`,uvB:`vec2`,uvC:`vec2`,normalA:`vec3`,normalB:`vec3`,normalC:`vec3`,material:dl,materialIndex:`int`,meshIndex:`int`}),x({color:`vec4`,samples:`int`}),gl=x({direction:`vec3`,value:`vec3`,pdf:`float`,isTransmission:`bool`,colorWeight:`vec3`,isDiffuseTransmission:`bool`}),_l=x({specular:`float`,diffuse:`float`,sheen:`float`,clearcoat:`float`,transmission:`float`,iridescence:`float`,diffuseTransmission:`float`}),vl=x({Ta:`vec3`,Ba:`vec3`}),yl=x({NoL:`float`,NoV:`float`,NoH:`float`,VoH:`float`,LoH:`float`,ToH:`float`,BoH:`float`,ToV:`float`,BoV:`float`,ToL:`float`,BoL:`float`}),bl=x({compensation:`vec3`,E_total:`vec3`}),xl=x({f0:`vec3`,f90:`float`,eta:`float`,F0m:`vec3`,F0:`vec3`}),Sl=x({albedo:`vec4`,emissive:`vec3`,metalness:`float`,roughness:`float`,normal:`vec3`,hasTextures:`bool`}),Cl=x({isMetallic:`bool`,isRough:`bool`,isSmooth:`bool`,isTransmissive:`bool`,hasClearcoat:`bool`,isEmissive:`bool`,complexityScore:`float`}),wl=x({albedoUV:`vec2`,normalUV:`vec2`,metalnessUV:`vec2`,emissiveUV:`vec2`,bumpUV:`vec2`,roughnessUV:`vec2`,normalBumpSameUV:`bool`,metalRoughSameUV:`bool`,albedoEmissiveSameUV:`bool`,allSameUV:`bool`}),Tl=x({invRoughness:`float`,metalFactor:`float`,iorFactor:`float`,maxSheenColor:`float`}),x({traversals:`int`,transmissiveTraversals:`int`,rayType:`int`,isPrimaryRay:`bool`,actualBounceDepth:`int`})}));function Dl(e,t,n){return e.length===1?e[0]:{isSplitStorage:!0,parts:e,perPart:t,type:n,value:e[0].value}}function Ol(e,t,r){let{parts:i,perPart:a}=e,o=(0,n.int)(t).toVar(),s=r.map(()=>({uvec4:n.uvec4,uvec2:n.uvec2}[e.type]??n.vec4)(0).toVar()),c=e=>()=>{let t=e===0?o:o.sub((0,n.int)(a*e));r.forEach((r,a)=>s[a].assign(i[e].element(r===0?t:t.add((0,n.int)(r)))))},l=(0,n.If)(o.lessThan((0,n.int)(a)),c(0));for(let e=1;e<i.length-1;e++)l=l.ElseIf(o.lessThan((0,n.int)(a*(e+1))),c(e));return l.Else(c(i.length-1)),s}function kl(e,t){return e.isSplitStorage?Ol(e,t,[0])[0]:e.element(t)}var Al,jl,Ml,Nl,Pl,Fl,Il,Ll,Rl,zl,Bl,Vl,Hl,Ul,Wl,Gl,Kl,ql,Jl,Yl,Xl,Zl,Ql,$l,eu,tu,nu,ru,iu,X,au,ou,su,cu,lu,uu,du,fu,pu,mu,hu,gu,_u,vu=g((()=>{El(),It(),Al=(0,n.wgslFn)(`
|
|
247
|
+
`,bindings:n}}function ss(){us.length=0,us.push(...qo),ds.clear();for(let e of us)ds.set(e.id,e);Yo()}var cs,ls,us,ds,fs,ps,ms,hs,gs,_s=g((()=>{Jo(),cs=200,ls=12,us=[...qo],ds=new Map(us.map(e=>[e.id,e])),fs=1,ps=new Set,ms=ds,hs=r.NoToneMapping,gs=r.AgXToneMapping}));_s();var vs=e=>(t,n,r,i,a)=>e(t>0?t:0,n>0?n:0,r>0?r:0,i,a),ys=new Map;function bs(){ys.clear();for(let e of ms.values())ys.set(e.id,vs(e.cpu))}bs(),Zo(bs);function xs(e){return Qo(e)?.outputEncoded===!0}function Ss(e){return e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055}function Cs(e,t){let n=Qo(t);return n?n.appliesExposure?e:1:t===r.NoToneMapping?1:e}function ws(e,t,n){return Cs(e,n)/Cs(t,n)}function Ts(e,t,n){return e+(t-e)*(1-Math.min(Math.max(n,0),1))}var Es=.2126,Ds=.7152,Os=.0722;function ks(e,t){if(t===1)return;let n=e[0]*Es+e[1]*Ds+e[2]*Os;e[0]=n+(e[0]-n)*t,e[1]=n+(e[1]-n)*t,e[2]=n+(e[2]-n)*t}function As(e,{exposure:t,toneMapping:n,saturation:i=1,preserveAlpha:a=!1,pixelGain:o=null}){let s=ys.get(n)??ys.get(r.NoToneMapping),c=Cs(t,n),l=xs(n),u=new Uint8ClampedArray(e.length),d=[0,0,0],f=Math.log2(t);for(let t=0;t<e.length;t+=4){let n=c;if(o){let r=1;if(o.fn){let n=t>>2,i=n%o.width,a=(n-i)/o.width,s=e[t]*.2126+e[t+1]*.7152+e[t+2]*.0722;r=o.fn((i+.5)/o.width,(a+.5)/o.height,s,f)}o.backdrop>0&&(r=Ts(r,o.backdrop,e[t+3])),n*=r}d[0]=e[t]*n,d[1]=e[t+1]*n,d[2]=e[t+2]*n,ks(d,i),s(d[0],d[1],d[2],1,d),l?(u[t]=d[0]*255+.5,u[t+1]=d[1]*255+.5,u[t+2]=d[2]*255+.5):(u[t]=Ss(d[0])*255+.5,u[t+1]=Ss(d[1])*255+.5,u[t+2]=Ss(d[2])*255+.5),u[t+3]=a?e[t+3]*255+.5:255}return u}It(),tn(),on(),ke(),Pr();var js=ve(`textures`),Ms={MAX_BUFFER_MEMORY:1024*1024*1024,MAX_TEXTURE_MEMORY:2048*1024*1024,CLEANUP_THRESHOLD:.8,STREAM_BATCH_SIZE:4},Ns=8*2**20,Ps=16,Fs=4,Is=8192*8192,Ls={busy:0,waiting:[]};async function Rs(){return Ls.busy<Math.max(1,Dr()-1)?Ls.busy++:await new Promise(e=>Ls.waiting.push(e)),()=>{let e=Ls.waiting.shift();e?e():Ls.busy--}}var zs={toSRGB:null,toLinear:null};function Bs(e){if(!zs[e]){let t=new Uint8Array(256);for(let n=0;n<256;n++){let r=n/255,i=e===`toSRGB`?Ss(r):r<=.04045?r/12.92:((r+.055)/1.055)**2.4;t[n]=Math.max(0,Math.min(255,Math.round(i*255)))}zs[e]=t}return zs[e]}var Vs=class{constructor(){this.canvasContextPairs=[],this.maxPoolSize=$t.CANVAS_POOL_SIZE}getCanvasWithContext(e,t,n=!1,r={}){let i={willReadFrequently:!0,alpha:!0,desynchronized:!0,...r},a=this.canvasContextPairs.pop();if(!a){let r;r=n&&typeof OffscreenCanvas<`u`?new OffscreenCanvas(e,t):document.createElement(`canvas`);let o=r.getContext(`2d`,i);a={canvas:r,context:o}}return a.canvas.width=e,a.canvas.height=t,a}releaseCanvasWithContext(e){this.canvasContextPairs.length<this.maxPoolSize&&(e.context.globalAlpha=1,e.context.globalCompositeOperation=`source-over`,e.context.imageSmoothingEnabled=!0,e.context.clearRect(0,0,e.canvas.width,e.canvas.height),e.canvas.width=1,e.canvas.height=1,this.canvasContextPairs.push(e))}getCanvas(e,t,n=!1){return this.getCanvasWithContext(e,t,n).canvas}getContext(e,t={}){let n=this.canvasContextPairs.find(t=>t.canvas===e);return n?n.context:e.getContext(`2d`,{willReadFrequently:!0,alpha:!0,desynchronized:!0,...t})}dispose(){this.canvasContextPairs=[]}},Hs=class{constructor(e={}){this.pools=new Map,this.memoryUsage=0,this.maxMemoryUsage=e.maxMemory||Ms.MAX_BUFFER_MEMORY,this.allocatedBuffers=new WeakMap,this.sizeStrategy=e.sizeStrategy||`adaptive`}getOptimalSize(e){switch(this.sizeStrategy){case`exact`:return e;case`power2`:return 2**Math.ceil(Math.log2(e));default:return e<1024?e:e<1024*1024?Math.ceil(e/1024)*1024:2**Math.ceil(Math.log2(e))}}getBuffer(e,t=Float32Array){let n=this.getOptimalSize(e),r=`${t.name}-${n}`,i=(this.pools.get(r)||[]).pop();if(!i)try{i=new t(n),this.memoryUsage+=i.byteLength,this.allocatedBuffers.set(i,!0)}catch{this.cleanup();try{i=new t(n),this.memoryUsage+=i.byteLength,this.allocatedBuffers.set(i,!0)}catch(e){let r=n*t.BYTES_PER_ELEMENT/(1024*1024),i=this.memoryUsage/(1024*1024);throw Error(`Buffer allocation failed: requested ${r.toFixed(1)}MB, current usage: ${i.toFixed(1)}MB, max: ${(this.maxMemoryUsage/(1024*1024)).toFixed(1)}MB. Original error: ${e.message}`)}}return this.memoryUsage>this.maxMemoryUsage*Ms.CLEANUP_THRESHOLD&&this.cleanup(),this.checkMemoryHealth(),i.byteOffset+e*t.BYTES_PER_ELEMENT>i.buffer.byteLength&&(i=new t(e),this.memoryUsage+=i.byteLength),new t(i.buffer,i.byteOffset,e)}forget(e){this.memoryUsage=Math.max(0,this.memoryUsage-e.buffer.byteLength)}releaseBuffer(e,t=Float32Array){let n=(e.buffer.byteLength-e.byteOffset)/t.BYTES_PER_ELEMENT,r=this.getOptimalSize(n),i=`${t.name}-${r}`,a=this.pools.get(i)||[];a.length<$t.BUFFER_POOL_SIZE?(a.push(new t(e.buffer,e.byteOffset,n)),this.pools.set(i,a)):this.allocatedBuffers.has(e)&&(this.memoryUsage-=e.byteLength,this.allocatedBuffers.delete(e))}cleanup(){let e=Array.from(this.pools.entries());e.slice(0,Math.floor(e.length/2)).forEach(([e,t])=>{t.forEach(e=>{this.allocatedBuffers.has(e)&&(this.memoryUsage-=e.byteLength,this.allocatedBuffers.delete(e))}),this.pools.delete(e)})}dispose(){this.pools.forEach(e=>{e.forEach(e=>{this.allocatedBuffers.has(e)&&this.allocatedBuffers.delete(e)})}),this.pools.clear(),this.memoryUsage=0}getMemoryStats(){return{currentUsage:this.memoryUsage,maxUsage:this.maxMemoryUsage,utilizationPercentage:this.memoryUsage/this.maxMemoryUsage*100,poolCount:this.pools.size,allocatedBufferCount:this.allocatedBuffers&&this.allocatedBuffers.size||0}}checkMemoryHealth(){let e=this.getMemoryStats();return e.utilizationPercentage>90?(console.warn(`Memory pool critical: ${e.utilizationPercentage.toFixed(1)}% used (${(e.currentUsage/(1024*1024)).toFixed(1)}MB / ${(e.maxUsage/(1024*1024)).toFixed(1)}MB)`),`critical`):e.utilizationPercentage>70?(console.warn(`Memory pool high: ${e.utilizationPercentage.toFixed(1)}% used (${(e.currentUsage/(1024*1024)).toFixed(1)}MB / ${(e.maxUsage/(1024*1024)).toFixed(1)}MB)`),`high`):`normal`}},Us=class{constructor(e=$t.CACHE_SIZE_LIMIT){this.cache=new Map,this.accessOrder=[],this.maxSize=e}generateHash(e){let t=``;for(let n of e)if(n?.image){let e=n.image.width||0,r=n.image.height||0,i=n.image.src||n.uuid||``,a=n.flipY===!1?`n`:`f`,o=`${n.colorSpace??``}|${n.userData?.ocioColorSpace??``}`;t+=`${e}x${r}_${i.slice(-8)}_${a}_${o}_`}return t+e.length}get(e){if(this.cache.has(e)){let t=this.cache.get(e);if(t?.userData&&t.userData.buffer===null){this.cache.delete(e);let t=this.accessOrder.indexOf(e);return t>-1&&this.accessOrder.splice(t,1),null}let n=this.accessOrder.indexOf(e);return n>-1&&this.accessOrder.splice(n,1),this.accessOrder.push(e),t}return null}set(e,t){if(this.cache.has(e)){let t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1)}else this.cache.size>=this.maxSize&&this.evictLRU();this.cache.set(e,t),this.accessOrder.push(e)}evictLRU(){if(this.accessOrder.length>0){let e=this.accessOrder.shift(),t=this.cache.get(e);t&&t.dispose&&t.dispose(),this.cache.delete(e)}}dispose(){this.cache.forEach(e=>{e&&e.dispose&&e.dispose()}),this.cache.clear(),this.accessOrder=[]}},Ws=class{constructor(e={}){this.useWorkers=typeof Worker<`u`,this.maxConcurrentWorkers=$t.MAX_CONCURRENT_WORKERS,this.activeWorkers=0,this._issues=e.issues??null,this.maxTextureSize=this._clampTextureSize(e.maxTextureSize??$t.DEFAULT_MAX_TEXTURE_SIZE),this.canvasPool=new Vs,this.bufferPool=new Hs({maxMemory:e.maxBufferMemory||Ms.MAX_BUFFER_MEMORY,sizeStrategy:e.bufferSizeStrategy||`adaptive`}),this.textureCache=new Us,this.capabilities=this.detectCapabilities(),this.optimalMethod=this.selectOptimalMethod()}_reportTextureFailure(e,t){if(t instanceof rn)throw t;this._issues?.record(Y.TEXTURE_BUILD_FAILED,`${e} texture array failed to build — those surfaces render untextured`,{map:e,cause:String(t?.message??t)})}_reportTextureLayer(e,t){this._issues?.record(Y.TEXTURE_BUILD_FAILED,`texture ${e} could not be read — its surfaces show a white placeholder`,{layer:e,cause:String(t?.message??t)})}_clampTextureSize(e){let t=Math.floor(Number(e)||$t.DEFAULT_MAX_TEXTURE_SIZE);return Math.max($t.MIN_TEXTURE_WIDTH,Math.min(t,$t.MAX_TEXTURE_SIZE))}setMaxTextureSize(e){let t=this._clampTextureSize(e);return t===this.maxTextureSize?t:(this.maxTextureSize=t,this.textureCache?.dispose(),this.textureCache=new Us,this.maxTextureSize)}detectCapabilities(){return{offscreenCanvas:typeof OffscreenCanvas<`u`,imageBitmap:typeof createImageBitmap<`u`,workers:typeof Worker<`u`,hardwareConcurrency:Dr()}}selectOptimalMethod(){return this.capabilities.workers&&this.capabilities.offscreenCanvas?`worker-offscreen`:this.capabilities.imageBitmap?`imageBitmap`:`canvas`}_applyColorManagement(e,t,n,i=new Set){let a=Qr();if(!a?.hasConfig)return;let o=e?.image?.data;if(!o||!n)return;let s=t.filter(e=>e?.image),c=e.image.width*e.image.height*4,l=0,u=0,d=[];for(let e=0;e<s.length;e++){let t=e*c,n=Math.min(t+c,o.length);if(t>=o.length)break;let f=s[e],p=o.subarray(t,n),m=null;try{m=a.resolveTexture(f)}catch(t){js.warn(`could not resolve the colour space of layer ${e}: ${t.message}`)}let h=m&&m.via!==`three`?m.colorSpace:null,g=f.type===r.FloatType||f.type===r.HalfFloatType;h&&(i.has(e)||g)&&(d.push(`${f.name||`layer ${e}`} (${h})`),h=null);try{a.convertTextureBytes(p,{space:h,encoding:`srgb`})&&(h?l++:u++)}catch(t){this._issues?.warn(Y.TEXTURE_PROCESSING_FALLBACK,`colour conversion failed for layer ${e} — left in its original space`,{cause:String(t?.message??t),space:h})}}d.length&&this._issues?.warn(Y.TEXTURE_PROCESSING_FALLBACK,`${d.length} colour map(s) name a colour space their stored bytes are no longer in (re-encoded or quantized on the way in); converted by primaries only`,{textures:d.slice(0,8)}),l+u!==0&&(e.needsUpdate=!0,js.info(`colour maps into ${a.workingSpace}: ${l} by named space, ${u} by primaries, of ${s.length}`))}_harmonizeTransfer(e,t,n){let i=new Set,a=e?.image?.data;if(!a)return i;let o=t.filter(e=>e?.image),s=n?r.SRGBColorSpace:r.LinearSRGBColorSpace,c=e.image.width*e.image.height*4,l=[];for(let e=0;e<o.length;e++){let t=o[e].colorSpace;if(t!==r.SRGBColorSpace&&t!==r.LinearSRGBColorSpace||t===s)continue;let u=Bs(n?`toSRGB`:`toLinear`),d=e*c,f=Math.min(d+c,a.length);for(let e=d;e<f;e+=4)a[e]=u[a[e]],a[e+1]=u[a[e+1]],a[e+2]=u[a[e+2]];l.push(o[e].name||o[e].source?.uuid?.slice(0,8)||`layer ${e}`),i.add(e)}if(l.length===0)return i;e.needsUpdate=!0;let u=l.slice(0,4).join(`, `)+(l.length>4?`, +${l.length-4} more`:``);return n?js.info(`re-encoded ${l.length}/${o.length} linear-declared colour map(s) to sRGB so the GPU decode round-trips: ${u}`):js.warn(`decoded ${l.length}/${o.length} sRGB-declared data map(s) to linear — precision is lost in the darks, check the asset: ${u}`),i}async createTexturesToDataTexture(e,{srgbPool:t=!1}={}){if(!e||e.length===0)return null;let n=Qr()?.inputKey??`-`,r=`${t?`s`:`l`}:${n}:${this.textureCache.generateHash(e)}`,i=this.textureCache.get(r);if(i)return i;if(typeof createImageBitmap>`u`){let n=await this.processOnCPU(e),i=this._harmonizeTransfer(n,e,t);return this._applyColorManagement(n,e,t,i),this.textureCache.set(r,n),n}let{normalized:a,bitmapsToClose:o}=await this._normalizeTexturesForProcessing(e),s=this.selectProcessingStrategy(a),c;try{switch(s.method){case`worker-direct`:c=await this.processWithWorkerDirect(a);break;case`worker-streaming`:c=await this.processInWorkerStreaming(a);break;case`main-batch`:c=await this.processOnMainThreadBatch(a,s.batchSize);break;case`main-streaming`:c=await this.processOnMainThreadStreaming(a);break;default:c=await this.processOnMainThreadSync(a)}if(c){let n=this._harmonizeTransfer(c,e,t);this._applyColorManagement(c,e,t,n),this.textureCache.set(r,c)}return c}catch(n){if(n instanceof rn)throw n;this._issues?.warn(Y.TEXTURE_PROCESSING_FALLBACK,`worker texture processing failed — retrying on the main thread`,{cause:String(n?.message??n)});let r=await this.processOnMainThreadSync(a),i=this._harmonizeTransfer(r,e,t);return this._applyColorManagement(r,e,t,i),r}finally{for(let e of o)e.close()}}selectProcessingStrategy(e){let t=e.reduce((e,t)=>e+(t.image?.width||0)*(t.image?.height||0),0),n=t*4;return this.capabilities.workers&&n>Ms.MAX_TEXTURE_MEMORY?{method:`worker-streaming`}:this.capabilities.workers&&t>2097152?{method:`worker-direct`}:t>524288?{method:`main-batch`,batchSize:Math.min(4,e.length)}:e.length>8?{method:`main-streaming`}:{method:`main-sync`}}async processWithWorkerDirect(e){for(;this.activeWorkers>=this.maxConcurrentWorkers;)await new Promise(e=>setTimeout(e,10));this.activeWorkers++;let t=1,n=null;try{let r=await this.prepareTexturesForWorkerDirect(e),i=this._sharedPackSlots(r);if(i>0)return t+=i,this.activeWorkers+=i,this.createDataArrayTextureFromResult(await this._packAcrossWorkers(r,t));n=new ko;let a=await new Promise((e,t)=>{n.onmessage=n=>{n.data.error?t(Error(n.data.error)):e(n.data)},n.onerror=t;let i=[];r.forEach(e=>{e.data instanceof ArrayBuffer?i.push(e.data):e.bitmap&&i.push(e.bitmap)}),n.postMessage({textures:r,maxTextureSize:this.maxTextureSize,method:`direct-transfer`},i)});return this.createDataArrayTextureFromResult(a)}finally{n?.terminate(),this.activeWorkers-=t}}_sharedPackSlots(e){if(typeof SharedArrayBuffer>`u`||!globalThis.crossOriginIsolated||e.reduce((e,t)=>e+t.width*t.height,0)<Is)return 0;let t=this.maxConcurrentWorkers-this.activeWorkers;return Math.max(0,Math.min(e.length,Fs,t+1)-1)}async _packAcrossWorkers(e,t){let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(e.map(e=>({image:e}))),i=e.length,a=new SharedArrayBuffer(n*r*i*4),o=Array.from({length:t},()=>({cost:0,layers:[],transfer:[]})),s=e.map((e,t)=>t),c=t=>e[t].width*e[t].height;s.sort((e,t)=>c(t)-c(e));for(let t of s){let n=o.reduce((e,t)=>t.cost<e.cost?t:e),r=e[t];n.layers.push({index:t,texture:r}),n.cost+=c(t),r.data instanceof ArrayBuffer?n.transfer.push(r.data):r.bitmap&&n.transfer.push(r.bitmap)}let l=[];try{await Promise.all(o.filter(e=>e.layers.length).map(e=>new Promise((t,i)=>{let o=jr(ko);l.push(o),o.onmessage=({data:e})=>e.error?i(Error(e.error)):t(),o.onerror=e=>i(Error(e.message||`texture worker failed`)),o.postMessage({shared:a,width:n,height:r,layers:e.layers,maxTextureSize:this.maxTextureSize},e.transfer)})))}finally{for(let e of l)e.terminate()}return{data:a,width:n,height:r,depth:i}}async processInWorkerStreaming(e){let t=e.filter(e=>e?.image);if(t.length===0)return this.createFallbackTexture();let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t),i=t.length;for(;this.activeWorkers>=this.maxConcurrentWorkers;)await new Promise(e=>setTimeout(e,10));this.activeWorkers++;let a=jr(ko);try{let e=0,o=null,s,c=new Promise((e,t)=>s={resolve:e,reject:t});c.catch(()=>{}),a.onmessage=({data:t})=>{t.error?s.reject(Error(t.error)):t.stream===`ack`?e++:s.resolve(t),o?.()},a.onerror=e=>{s.reject(Error(e.message||`texture worker failed`)),o?.()},a.postMessage({stream:`begin`,width:n,height:r,depth:i});let l=performance.now();for(let s=0;s<i;s++){for(;s-e>=Ms.STREAM_BATCH_SIZE;)await Promise.race([new Promise(e=>o=e),c]),l=performance.now();let i=t[s],u=await createImageBitmap(i.image,{resizeWidth:n,resizeHeight:r,resizeQuality:`high`,imageOrientation:i.flipY===!1?`none`:`flipY`});a.postMessage({stream:`layer`,index:s,bitmap:u},[u]),performance.now()-l>Ps&&(await new Promise(e=>setTimeout(e,0)),l=performance.now())}return a.postMessage({stream:`end`}),this.createDataArrayTextureFromResult(await c)}finally{a.terminate(),this.activeWorkers--}}async prepareTexturesForWorkerDirect(e){let t=[],n=()=>({data:new Uint8ClampedArray([255,255,255,255]).buffer,width:1,height:1,isImageData:!0});for(let r=0;r<e.length;r++){let i=e[r];if(!i?.image){this._reportTextureLayer(r,`no image`),t.push(n());continue}let a=i.flipY!==!1;try{let e=i.image;if(typeof createImageBitmap<`u`&&(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&e instanceof OffscreenCanvas)){let e=await createImageBitmap(i.image,{imageOrientation:a?`flipY`:`none`});t.push({bitmap:e,width:i.image.width,height:i.image.height,isDirect:!0})}else{let e=i.image.width,n=i.image.height,r=await createImageBitmap(i.image,{imageOrientation:a?`flipY`:`none`}),o=this.canvasPool.getCanvasWithContext(e,n);o.context.drawImage(r,0,0),r.close();let s=o.context.getImageData(0,0,e,n);t.push({data:s.data.buffer,width:e,height:n,isImageData:!0}),this.canvasPool.releaseCanvasWithContext(o)}}catch(e){this._reportTextureLayer(r,e),t.push(n())}}return t}async processOnCPU(e){let t=e.map((e,t)=>{let n=e?.image,r=e?.isCompressedTexture?e.mipmaps?.[0]:n,i=e?.isCompressedTexture?r?.data:Ks(e);return i&&r.width>0&&r.height>0&&i.byteLength>=r.width*r.height*4?{data:new Uint8Array(i.buffer,i.byteOffset,r.width*r.height*4),width:r.width,height:r.height,flipY:e.flipY!==!1}:(this._reportTextureLayer(t,n?`not decoded to pixels, and there is no browser to decode it`:`no image`),{data:new Uint8Array([255,255,255,255]),width:1,height:1,flipY:!1})}),{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t.map(e=>({image:e}))),i=n*r*4,a=kr()&&i*t.length>=Ns?await this._packInWorker(t,n,r):null;if(a)return this.createDataArrayTextureFromBuffer(a,n,r,t.length);let o=this.bufferPool.getBuffer(i*t.length,Uint8Array);return t.forEach((e,t)=>No(e,o,t*i,n,r)),this.createDataArrayTextureFromBuffer(o,n,r,t.length)}async _packInWorker(e,t,n){let r=await Rs(),i=null;try{let r=[],a=e.map(e=>{if(typeof SharedArrayBuffer<`u`&&e.data.buffer instanceof SharedArrayBuffer)return e;let t=e.data.slice();return r.push(t.buffer),{...e,data:t}});return i=jr(Mo),await new Promise((e,o)=>{i.onmessage=t=>t.data.error?o(Error(t.data.error)):e(t.data.data),i.onerror=e=>o(e.error??Error(e.message??`texture pack worker failed`)),i.postMessage({layers:a,width:t,height:n},r)})}catch(e){return this._issues?.warn(Y.TEXTURE_PROCESSING_FALLBACK,`worker texture packing failed — packing on the main thread`,{cause:String(e?.message??e)}),null}finally{i?.terminate(),r()}}async processOnMainThreadBatch(e,t){let n=e.filter(e=>e?.image);if(n.length===0)return this.createFallbackTexture();let{maxWidth:r,maxHeight:i}=this.calculateOptimalDimensions(n),a=n.length,o=this.bufferPool.getBuffer(r*i*a*4,Uint8Array);for(let e=0;e<n.length;e+=t){let a=Math.min(e+t,n.length),s=[];for(let t=e;t<a;t++){let e=n[t],a=e.flipY!==!1,o=createImageBitmap(e.image,{resizeWidth:r,resizeHeight:i,resizeQuality:`high`,imageOrientation:a?`flipY`:`none`});s.push(o.then(e=>({bitmap:e,index:t})))}let c=await Promise.all(s),l=this.canvasPool.getCanvasWithContext(r,i);l.context.imageSmoothingEnabled=!1;for(let{bitmap:e,index:t}of c){l.context.clearRect(0,0,r,i),l.context.drawImage(e,0,0);let n=l.context.getImageData(0,0,r,i),a=r*i*4*t;o.set(n.data,a),e.close()}this.canvasPool.releaseCanvasWithContext(l)}return this.createDataArrayTextureFromBuffer(o,r,i,a)}async processOnMainThreadStreaming(e){let t=e.filter(e=>e?.image);if(t.length===0)return this.createFallbackTexture();let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t),i=t.length,a=this.bufferPool.getBuffer(n*r*i*4,Uint8Array),o=this.canvasPool.getCanvasWithContext(n,r);o.context.imageSmoothingEnabled=!0,o.context.imageSmoothingQuality=`high`;for(let e=0;e<t.length;e++){let i=t[e],s=await createImageBitmap(i.image,{resizeWidth:n,resizeHeight:r,resizeQuality:`high`,imageOrientation:i.flipY===!1?`none`:`flipY`});o.context.clearRect(0,0,n,r),o.context.drawImage(s,0,0),s.close();let c=o.context.getImageData(0,0,n,r),l=n*r*4*e;a.set(c.data,l),e%Ms.STREAM_BATCH_SIZE===0&&await new Promise(e=>setTimeout(e,0))}return this.canvasPool.releaseCanvasWithContext(o),this.createDataArrayTextureFromBuffer(a,n,r,i)}async processOnMainThreadSync(e){let t=e.filter(e=>e?.image);if(t.length===0)return this.createFallbackTexture();let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t),i=t.length,a=this.bufferPool.getBuffer(n*r*i*4,Uint8Array),o=this.canvasPool.getCanvasWithContext(n,r);o.context.imageSmoothingEnabled=!0,o.context.imageSmoothingQuality=`high`;for(let e=0;e<t.length;e++){let i=t[e],s=await createImageBitmap(i.image,{resizeWidth:n,resizeHeight:r,resizeQuality:`high`,imageOrientation:i.flipY===!1?`none`:`flipY`});o.context.clearRect(0,0,n,r),o.context.drawImage(s,0,0),s.close();let c=o.context.getImageData(0,0,n,r),l=n*r*4*e;a.set(c.data,l)}return this.canvasPool.releaseCanvasWithContext(o),this.createDataArrayTextureFromBuffer(a,n,r,i)}createMaterialRawData(e){let t=K.FLOATS_PER_MATERIAL,n=new Float32Array(e.length*t);for(let r=0;r<e.length;r++)Ut(n,r*t,e[r]);return n}createBVHRawData(e){let t=[],n=e=>{let r=t.length;if(t.push(e),e.leftChild){let t=n(e.leftChild),r=n(e.rightChild);e.leftChild=t,e.rightChild=r}return r};n(e);let r=$t.VEC4_PER_BVH_NODE*$t.FLOATS_PER_VEC4;bt(t.length,`BVH node count`);let i=t.length*r,a=new Float32Array(i),o=yt(a);for(let e=0;e<t.length;e++){let n=e*r,i=t[e];if(i.leftChild!==null){let e=i.leftChild,r=i.rightChild,s=t[e],c=t[r];a[n]=s.boundsMin.x,a[n+1]=s.boundsMin.y,a[n+2]=s.boundsMin.z,o[n+3]=e,a[n+4]=s.boundsMax.x,a[n+5]=s.boundsMax.y,a[n+6]=s.boundsMax.z,o[n+7]=r,a[n+8]=c.boundsMin.x,a[n+9]=c.boundsMin.y,a[n+10]=c.boundsMin.z,a[n+12]=c.boundsMax.x,a[n+13]=c.boundsMax.y,a[n+14]=c.boundsMax.z}else o[n]=i.triangleOffset,o[n+1]=i.triangleCount,o[n+3]=Et.TRIANGLE_LEAF}return a}async createMaterialTextures(e){let{materials:t,maps:n,normalMaps:i,bumpMaps:a,roughnessMaps:o,metalnessMaps:s,emissiveMaps:c,displacementMaps:l}=e;console.log(`[TextureCreator] Creating material textures only`);let u=performance.now();try{if(!t||t.length===0)throw Error(`No materials provided for texture creation`);this.textureCache.dispose(),this.textureCache=new Us;let e=[];for(let[t,r]of[[`albedo`,n],[`normal`,i],[`bump`,a],[`roughness`,o],[`metalness`,s],[`emissive`,c],[`displacement`,l]])!r||r.length===0||e.push(this.createTexturesToDataTexture(r).then(e=>({type:t,texture:e})).catch(e=>(this._reportTextureFailure(t,e),{type:t,texture:null})));let d=await Promise.allSettled(e),f=d.find(e=>e.status===`rejected`);if(f)throw f.reason;let p={};d.forEach(e=>{if(e.status===`fulfilled`&&e.value){let{type:t,texture:n}=e.value;if(n)switch(t){case`albedo`:n.colorSpace=r.SRGBColorSpace,p.albedoTexture=n;break;case`normal`:p.normalTexture=n;break;case`bump`:p.bumpTexture=n;break;case`roughness`:p.roughnessTexture=n;break;case`metalness`:p.metalnessTexture=n;break;case`emissive`:n.colorSpace=r.SRGBColorSpace,p.emissiveTexture=n;break;case`displacement`:p.displacementTexture=n;break}}});let m=performance.now()-u;return console.log(`[TextureCreator] Material texture creation complete (${m.toFixed(2)}ms)`),p}catch(e){throw console.error(`[TextureCreator] Material texture creation error:`,e),Error(`Material texture creation failed: ${e.message}`)}}calculateOptimalDimensions(e){let t=0,n=0;for(let r of e)t=Math.max(t,r.image.width),n=Math.max(n,r.image.height);let r=Math.max(t,n);if(r>this.maxTextureSize){let e=this.maxTextureSize/r;t=Math.round(t*e),n=Math.round(n*e)}return{maxWidth:Wt(t,this.maxTextureSize),maxHeight:Math.max(1,n)}}createDataArrayTextureFromResult(e){let t=(e.data instanceof ArrayBuffer,new Uint8Array(e.data));return this.createDataArrayTextureFromBuffer(t,e.width,e.height,e.depth)}createDataArrayTextureFromBuffer(e,t,n,i){let a=new r.DataArrayTexture(e,t,n,i);a.minFilter=r.LinearFilter,a.magFilter=r.LinearFilter,a.wrapS=r.RepeatWrapping,a.wrapT=r.RepeatWrapping,a.format=r.RGBAFormat,a.type=r.UnsignedByteType,a.needsUpdate=!0,a.generateMipmaps=!1,a.userData={buffer:e,bufferType:Uint8Array},a.onUpdate=()=>{let e=a.userData.buffer;e&&(this.bufferPool.forget(e),a.userData.buffer=null,a.image.data=null)};let o=a.dispose.bind(a);return a.dispose=()=>{a.userData.buffer&&(this.bufferPool.releaseBuffer(a.userData.buffer,a.userData.bufferType),a.userData.buffer=null),o()},a}async _normalizeTexturesForProcessing(e){let t=[],n=[],i=[];for(let n of e){if(!n?.image){this._reportTextureLayer(t.length,`no image`),t.push(null);continue}if(n.isCompressedTexture&&n.format===r.RGBAFormat&&n.mipmaps?.[0]?.data){let e=n.mipmaps[0],r=t.length;t.push(null),i.push({index:r,flipY:n.flipY,promise:Gs(e.data,e.width,e.height)});continue}if(n.isCompressedTexture){console.warn(`[TextureCreator] GPU-compressed texture in mixed group — using placeholder`),t.push(null);continue}if(n.image.data&&!(typeof HTMLImageElement<`u`&&n.image instanceof HTMLImageElement)&&!(typeof HTMLCanvasElement<`u`&&n.image instanceof HTMLCanvasElement)&&!(typeof ImageBitmap<`u`&&n.image instanceof ImageBitmap)){let e=t.length;t.push(null);let r=Ks(n);i.push({index:e,flipY:n.flipY,promise:r?Gs(r,n.image.width,n.image.height):Promise.reject(Error(`pixels in a layout the texture arrays cannot take`))});continue}t.push(n)}if(i.length>0){let e=await Promise.allSettled(i.map(e=>e.promise));for(let r=0;r<i.length;r++){let{index:a,flipY:o}=i[r],s=e[r];if(s.status===`fulfilled`){let e=s.value;n.push(e),t[a]={image:e,flipY:o}}else this._reportTextureLayer(a,s.reason)}}for(let e=0;e<t.length;e++)if(t[e]===null){let r=new Uint8ClampedArray([255,255,255,255]),i=await createImageBitmap(new ImageData(r,1,1));n.push(i),t[e]={image:i,flipY:!1}}return{normalized:t,bitmapsToClose:n}}createFallbackTexture(){let e=new r.DataArrayTexture(new Uint8Array([255,255,255,255]),1,1,1);return e.minFilter=r.LinearFilter,e.magFilter=r.LinearFilter,e.format=r.RGBAFormat,e.type=r.UnsignedByteType,e.needsUpdate=!0,e.generateMipmaps=!1,e}dispose(){this.canvasPool.dispose(),this.bufferPool.dispose(),this.textureCache.dispose()}};async function Gs(e,t,n){let r=new Uint8ClampedArray(e.buffer,e.byteOffset,e.byteLength);return createImageBitmap(new ImageData(r,t,n))}function Ks(e){let t=e?.image,n=t?.data;if(!n||!(t.width>0)||!(t.height>0))return null;let i=t.width*t.height;if(n instanceof Uint8Array||n instanceof Uint8ClampedArray)return n.byteLength>=i*4?new Uint8Array(n.buffer,n.byteOffset,i*4):null;let a={[r.RGBAFormat]:4,[r.RGFormat]:2,[r.RedFormat]:1}[e.format]??Math.round(n.length/i);if(!(a>=1&&a<=4)||n.length<i*a)return null;let o=e.type===r.HalfFloatType,s=e.type===r.UnsignedShortType?1/65535:1,c=new Uint8Array(i*4);for(let e=0;e<i;e++)for(let t=0;t<4;t++){let i=t<a?n[e*a+t]:null,l=i===null?t===3?1:c[e*4]/255:o?r.DataUtils.fromHalfFloat(i):i*s;c[e*4+t]=Math.max(0,Math.min(255,Math.round(l*255)))}return c}var qs=class{constructor(){this.maxLeafSize=8}build(e){let t=e.length;if(t===0){let e=new Float32Array(16);return e[7]=1,e[14]=1,e[15]=-1,{nodeData:e,nodeCount:1,sortedPerm:new Int32Array,bitTrails:new Float32Array}}let n=new Int32Array(t);for(let e=0;e<t;e++)n[e]=e;let r=2*t+4,i=new Float32Array(r*16),a=0,o=new Float32Array(t),s=(t,r,c,l)=>{let u=a++,d=u*16,f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,_=-1/0,v=0,y=1/0,b=1/0,x=1/0,S=-1/0,C=-1/0,w=-1/0;for(let i=t;i<r;i++){let t=e[n[i]];f=Math.min(f,t.bMinX),p=Math.min(p,t.bMinY),m=Math.min(m,t.bMinZ),h=Math.max(h,t.bMaxX),g=Math.max(g,t.bMaxY),_=Math.max(_,t.bMaxZ),v+=t.power,y=Math.min(y,t.cx),b=Math.min(b,t.cy),x=Math.min(x,t.cz),S=Math.max(S,t.cx),C=Math.max(C,t.cy),w=Math.max(w,t.cz)}i[d+0]=f,i[d+1]=p,i[d+2]=m,i[d+3]=v,i[d+4]=h,i[d+5]=g,i[d+6]=_;let T=r-t,E;if(T<=this.maxLeafSize){i[d+7]=1,i[d+8]=t,i[d+9]=T,i[d+10]=0,i[d+11]=0,E=null;for(let i=t;i<r;i++){let t=e[n[i]];E=Ys(E,Js(t)),o[i]=c}E||={ax:0,ay:0,az:1,cosO:-1}}else{let a=S-y,o=C-b,u=w-x,f;f=a>=o&&a>=u?0:o>=u?1:2;let p=[`cx`,`cy`,`cz`][f],m=t+r>>1;this._nthElement(n,e,t,r,m,p),i[d+7]=0;let h=s(t,m,c,l+1),g=s(m,r,c+2**l,l+1);i[d+8]=h.nodeIndex,i[d+9]=g.nodeIndex,i[d+10]=0,i[d+11]=0,E=Ys(h.cone,g.cone)}return i[d+12]=E.ax,i[d+13]=E.ay,i[d+14]=E.az,i[d+15]=E.cosO,{nodeIndex:u,cone:E}};s(0,t,0,0);let c=new Int32Array(t);for(let e=0;e<t;e++)c[e]=n[e];let l=new Float32Array(a*16);return l.set(i.subarray(0,a*16)),console.log(`[LightBVHBuilder] Built BVH: ${a} nodes for ${t} emissive triangles`),{nodeData:l,nodeCount:a,sortedPerm:c,bitTrails:o}}_nthElement(e,t,n,r,i,a){for(;n<r-1;){let o=n+r>>1,s=t[e[o]][a],c=e[o];e[o]=e[r-1],e[r-1]=c;let l=n;for(let i=n;i<r-1;i++)t[e[i]][a]<s&&(c=e[i],e[i]=e[l],e[l]=c,l++);if(c=e[l],e[l]=e[r-1],e[r-1]=c,l===i)return;l<i?n=l+1:r=l}}};function Js(e){return e.twoSided?{ax:e.nx,ay:e.ny,az:e.nz,cosO:-1}:{ax:e.nx,ay:e.ny,az:e.nz,cosO:1}}function Ys(e,t){if(!e)return t;if(!t||e.cosO<=-1)return e;if(t.cosO<=-1)return t;let n=Math.min(Math.max(e.cosO,-1),1),r=Math.min(Math.max(t.cosO,-1),1),i=Math.acos(n),a=Math.acos(r),o=Math.min(Math.max(e.ax*t.ax+e.ay*t.ay+e.az*t.az,-1),1),s=Math.acos(o);if(Math.min(s+a,Math.PI)<=i)return e;if(Math.min(s+i,Math.PI)<=a)return t;let c=(i+a+s)*.5;if(c>=Math.PI)return{ax:e.ax,ay:e.ay,az:e.az,cosO:-1};let l=c-i,u=e.ay*t.az-e.az*t.ay,d=e.az*t.ax-e.ax*t.az,f=e.ax*t.ay-e.ay*t.ax,p=Math.sqrt(u*u+d*d+f*f);if(p<1e-8)return{ax:e.ax,ay:e.ay,az:e.az,cosO:-1};u/=p,d/=p,f/=p;let m=Math.cos(l),h=Math.sin(l),g=u*e.ax+d*e.ay+f*e.az,_=d*e.az-f*e.ay,v=f*e.ax-u*e.az,y=u*e.ay-d*e.ax,b=e.ax*m+_*h+u*g*(1-m),x=e.ay*m+v*h+d*g*(1-m),S=e.az*m+y*h+f*g*(1-m),C=Math.sqrt(b*b+x*x+S*S)||1;return{ax:b/C,ay:x/C,az:S/C,cosO:Math.cos(c)}}It(),ke(),nr();var Xs=Object.freeze({r:0,g:0,b:0});function Zs(e){if(!e)return Xs;if(!Xn())return e;let t=[e.r,e.g,e.b];return Qn(t),{r:t[0],g:t[1],b:t[2]}}var Qs=ve(`emissive`),$s=class{constructor(){this.emissiveTriangles=[],this.emissiveCount=0,this.totalEmissivePower=0,this.emissiveIndicesArray=null,this.emissivePowerArray=null,this.cdfArray=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this._totalTriangleCount=0,this._hiddenMeshes=new Set}extractEmissiveTriangles(e,t,n,r=null){this.emissiveTriangles=[],this._emissiveMeshes=null,this.totalEmissivePower=0,this._totalTriangleCount=n;let i=G.FLOATS_PER_TRIANGLE,a=G.MATERIAL_FLAGS_OFFSET,o=G.MESH_INDEX_OFFSET,s=e&&e.chunks?e:null,c=s?s.viewAs(Float32Array):null,l=s?null:e,u=s?null:new Float32Array(e.buffer,e.byteOffset,e.length),d=new Map;for(let e=0;e<n;e++){if(s?.spilledChunks&&!s.isResident(e,1)){e=((e/s.recordsPerChunk|0)+1)*s.recordsPerChunk-1;continue}let n=s?s.chunkFor(e):l,f=s?c.chunkFor(e):u,p=s?s.baseOf(e):e*i,m=n[p+a]&xt,h=n[p+o],g=t[m];if(!g)continue;let _=d.get(g);_===void 0&&(_=Zs(g.emissive),d.set(g,_));let v=g.emissiveIntensity||0;if(v>0&&(_.r>0||_.g>0||_.b>0)){let t=r?.placementRunOf?.(h)?.start??-1,n=t>=0&&r.isSet[t],i=n?r.matrixRow(t):0,a=n?r.rowArray:null,o=(e,t,n)=>a?a[i]*e+a[i+4]*t+a[i+8]*n+a[i+12]:e,s=(e,t,n)=>a?a[i+1]*e+a[i+5]*t+a[i+9]*n+a[i+13]:t,c=(e,t,n)=>a?a[i+2]*e+a[i+6]*t+a[i+10]*n+a[i+14]:n,l=f[p+0],u=f[p+1],d=f[p+2],y=f[p+4],b=f[p+5],x=f[p+6],S=f[p+8],C=f[p+9],w=f[p+10],T=o(l,u,d),E=s(l,u,d),D=c(l,u,d),O=o(y,b,x),k=s(y,b,x),A=c(y,b,x),j=o(S,C,w),M=s(S,C,w),N=c(S,C,w),P=this._calculateTriangleArea(T,E,D,O,k,A,j,M,N),F=(.2126*_.r+.7152*_.g+.0722*_.b)*v*P,I=(k-E)*(N-D)-(A-D)*(M-E),L=(A-D)*(j-T)-(O-T)*(N-D),ee=(O-T)*(M-E)-(k-E)*(j-T),te=Math.sqrt(I*I+L*L+ee*ee)||1,R=g.side===1?-1:1;I=I/te*R,L=L/te*R,ee=ee/te*R;let ne=g.side===2,re=(T+O+j)/3,ie=(E+k+M)/3,ae=(D+A+N)/3,oe=Math.min(T,O,j),se=Math.min(E,k,M),ce=Math.min(D,A,N),le=Math.max(T,O,j),z=Math.max(E,k,M),ue=Math.max(D,A,N);this.emissiveTriangles.push({triangleIndex:e,materialIndex:m,meshIndex:h,sideSign:R,instanceLeaf:n?r.tlasLeafIndex[t]:-1,power:F,area:P,emissive:{r:_.r,g:_.g,b:_.b},emissiveIntensity:v,cx:re,cy:ie,cz:ae,bMinX:oe,bMinY:se,bMinZ:ce,bMaxX:le,bMaxY:z,bMaxZ:ue,nx:I,ny:L,nz:ee,twoSided:ne}),this.totalEmissivePower+=F}}return this.emissiveCount=this.emissiveTriangles.length,this.emissiveCount>0&&Qs.debug(`${H.n(this.emissiveCount)} emissive tris (${(this.emissiveCount/n*100).toFixed(2)}%) · total power ${this.totalEmissivePower.toFixed(2)}`),this._buildDataArrays(),this.emissiveCount}get emissiveMeshes(){return this._emissiveMeshes??=new Set(this.emissiveTriangles.map(e=>e.meshIndex))}refreshTransforms(e,t){let n=e&&e.chunks?e:null,r=n?n.viewAs(Float32Array):null,i=n?null:new Float32Array(e.buffer,e.byteOffset,e.length),a=G.FLOATS_PER_TRIANGLE;this.totalEmissivePower=0;for(let e of this.emissiveTriangles){let o=n?r.chunkFor(e.triangleIndex):i,s=n?n.baseOf(e.triangleIndex):e.triangleIndex*a,c=[o[s],o[s+1],o[s+2],o[s+4],o[s+5],o[s+6],o[s+8],o[s+9],o[s+10]],l=t.placementRunOf?.(e.meshIndex)?.start??-1;if(l>=0&&t.isSet[l]){let e=t.matrixRow(l),n=t.rowArray;for(let t=0;t<9;t+=3){let r=c[t],i=c[t+1],a=c[t+2];c[t]=n[e]*r+n[e+4]*i+n[e+8]*a+n[e+12],c[t+1]=n[e+1]*r+n[e+5]*i+n[e+9]*a+n[e+13],c[t+2]=n[e+2]*r+n[e+6]*i+n[e+10]*a+n[e+14]}}let[u,d,f,p,m,h,g,_,v]=c,y=this._calculateTriangleArea(u,d,f,p,m,h,g,_,v),b=e.emissive;e.power=(.2126*b.r+.7152*b.g+.0722*b.b)*e.emissiveIntensity*y,e.area=y;let x=(m-d)*(v-f)-(h-f)*(_-d),S=(h-f)*(g-u)-(p-u)*(v-f),C=(p-u)*(_-d)-(m-d)*(g-u),w=(Math.sqrt(x*x+S*S+C*C)||1)/e.sideSign;e.nx=x/w,e.ny=S/w,e.nz=C/w,e.cx=(u+p+g)/3,e.cy=(d+m+_)/3,e.cz=(f+h+v)/3,e.bMinX=Math.min(u,p,g),e.bMinY=Math.min(d,m,_),e.bMinZ=Math.min(f,h,v),e.bMaxX=Math.max(u,p,g),e.bMaxY=Math.max(d,m,_),e.bMaxZ=Math.max(f,h,v),this.totalEmissivePower+=e.power}this._buildDataArrays()}_calculateTriangleArea(e,t,n,r,i,a,o,s,c){let l=r-e,u=i-t,d=a-n,f=o-e,p=s-t,m=c-n,h=u*m-d*p,g=d*f-l*m,_=l*p-u*f;return Math.sqrt(h*h+g*g+_*_)*.5}_buildDataArrays(){this.emissiveIndicesArray=new Int32Array(this.emissiveCount),this.emissivePowerArray=new Float32Array(this.emissiveCount);for(let e=0;e<this.emissiveCount;e++)this.emissiveIndicesArray[e]=this.emissiveTriangles[e].triangleIndex,this.emissivePowerArray[e]=this.emissiveTriangles[e].power;this._buildCDF()}_buildCDF(){if(this.emissiveCount===0){this.cdfArray=new Float32Array(1),this.cdfArray[0]=0;return}this.cdfArray=new Float32Array(this.emissiveCount);let e=0;for(let t=0;t<this.emissiveCount;t++)e+=this.emissivePowerArray[t],this.cdfArray[t]=e;if(e>0)for(let t=0;t<this.emissiveCount;t++)this.cdfArray[t]/=e}sampleCDF(e){if(this.emissiveCount===0)return-1;if(this.emissiveCount===1)return 0;let t=0,n=this.emissiveCount-1;for(;t<n;){let r=Math.floor((t+n)/2);this.cdfArray[r]<e?t=r+1:n=r}return t}getGPUData(){return{emissiveIndices:this.emissiveIndicesArray,emissivePower:this.emissivePowerArray,emissiveCDF:this.cdfArray,emissiveCount:this.emissiveCount,totalPower:this.totalEmissivePower}}createEmissiveTexture(){if(this.emissiveCount===0)return new r.DataTexture(new Float32Array(4),1,1,r.RGBAFormat,r.FloatType);let e=new Float32Array(this.emissiveCount*4);for(let t=0;t<this.emissiveCount;t++){let n=t*4;e[n+0]=this.emissiveIndicesArray[t],e[n+1]=this.emissivePowerArray[t],e[n+2]=this.cdfArray[t],e[n+3]=0}let t=Math.ceil(Math.sqrt(this.emissiveCount)),n=Math.ceil(this.emissiveCount/t),i=t*n*4,a=new Float32Array(i);a.set(e);let o=new r.DataTexture(a,t,n,r.RGBAFormat,r.FloatType);return o.needsUpdate=!0,o.generateMipmaps=!1,o.minFilter=r.NearestFilter,o.magFilter=r.NearestFilter,Qs.debug(`emissive texture ${H.px(t,n)} · ${H.n(this.emissiveCount)} entries`),o}createEmissiveRawData(){if(this.emissiveCount===0)return new Float32Array(8);let e=new Float32Array(this.emissiveCount*8);for(let t=0;t<this.emissiveCount;t++){let n=this.emissiveTriangles[t],r=t*8;e[r+0]=n.triangleIndex,e[r+1]=n.power,e[r+2]=this.cdfArray[t],e[r+3]=n.instanceLeaf,e[r+4]=n.emissive.r*n.emissiveIntensity,e[r+5]=n.emissive.g*n.emissiveIntensity,e[r+6]=n.emissive.b*n.emissiveIntensity,e[r+7]=n.area}return Qs.debug(`emissive raw data ${H.n(this.emissiveCount)} entries (${H.mb(e.byteLength)})`),e}getStats(){if(this.emissiveCount===0)return{count:0,totalPower:0,averagePower:0,minPower:0,maxPower:0};let e=1/0,t=-1/0;for(let n=0;n<this.emissiveCount;n++){let r=this.emissivePowerArray[n];e=Math.min(e,r),t=Math.max(t,r)}return{count:this.emissiveCount,totalPower:this.totalEmissivePower,averagePower:this.totalEmissivePower/this.emissiveCount,minPower:e,maxPower:t}}updateMaterialEmissive(e,t,n,r,i){let a=Zs(t.emissive),o=t.emissiveIntensity||0,s=o>0&&(a.r>0||a.g>0||a.b>0);if(s!==this.emissiveTriangles.some(t=>t.materialIndex===e))return this.extractEmissiveTriangles(n,r,i),!0;if(!s)return!1;let c=.2126*a.r+.7152*a.g+.0722*a.b;for(let t of this.emissiveTriangles)t.materialIndex===e&&(t.power=c*o*t.area,t.emissive={r:a.r,g:a.g,b:a.b},t.emissiveIntensity=o);return!0}setHiddenMeshes(e){let t=new Set;for(let e of this.emissiveTriangles)t.add(e.meshIndex);let n=new Set;for(let r of e)t.has(r)&&n.add(r);let r=this._hiddenMeshes,i=n.size!==r.size;if(!i){for(let e of n)if(!r.has(e)){i=!0;break}}return this._hiddenMeshes=n,i}buildLightBVH(){let e=this._hiddenMeshes.size===0?this.emissiveTriangles:this.emissiveTriangles.filter(e=>!this._hiddenMeshes.has(e.meshIndex));this.emissiveCount=e.length,this.totalEmissivePower=0;for(let t of e)this.totalEmissivePower+=t.power;if(e.length===0)return this.lightBVHNodeData=new Float32Array(16),this.lightBVHNodeData[7]=1,this.lightBVHNodeData[14]=1,this.lightBVHNodeData[15]=-1,this.lightBVHNodeCount=1,this.emissiveBitTrailMap=new Float32Array(4).fill(-1),this.emissiveIndicesArray=new Int32Array,this.emissivePowerArray=new Float32Array,this._buildCDF(),this.emissiveTriangleData=new Float32Array(8),1;let{nodeData:t,nodeCount:n,sortedPerm:r,bitTrails:i}=new qs().build(e);this.lightBVHNodeData=t,this.lightBVHNodeCount=n,this._rebuildSortedEmissiveData(r,e),this.emissiveBitTrailMap=new Float32Array(Math.max(this._totalTriangleCount,1)).fill(-1);for(let t=0;t<r.length;t++){let n=e[r[t]].triangleIndex;this.emissiveBitTrailMap[n]=i[t]}return n}_rebuildSortedEmissiveData(e,t){let n=e.length;this.emissiveIndicesArray=new Int32Array(n),this.emissivePowerArray=new Float32Array(n);for(let r=0;r<n;r++){let n=e[r];this.emissiveIndicesArray[r]=t[n].triangleIndex,this.emissivePowerArray[r]=t[n].power}this._buildCDF();let r=new Float32Array(n*8);for(let i=0;i<n;i++){let n=t[e[i]],a=i*8;r[a+0]=n.triangleIndex,r[a+1]=n.power,r[a+2]=this.cdfArray[i],r[a+3]=n.instanceLeaf,r[a+4]=n.emissive.r*n.emissiveIntensity,r[a+5]=n.emissive.g*n.emissiveIntensity,r[a+6]=n.emissive.b*n.emissiveIntensity,r[a+7]=n.area}this.emissiveTriangleData=r,Qs.debug(`rebuilt sorted emissive data · ${H.n(n)} entries`)}clear(){this.emissiveTriangles=[],this.emissiveCount=0,this.totalEmissivePower=0,this.emissiveIndicesArray=null,this.emissivePowerArray=null,this.cdfArray=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this._totalTriangleCount=0,this._hiddenMeshes=new Set}};ke();var ec=class{constructor(e=`Build`,{namespace:t=`build`,level:n=`debug`}={}){this.label=e,this.level=n,this.logger=ve(t),this.entries=new Map,this.order=[],this.totalStart=performance.now()}start(e){return this.entries.set(e,{start:performance.now(),end:null}),this.order.includes(e)||this.order.push(e),this}end(e){let t=this.entries.get(e);return t&&(t.end=performance.now(),t.duration=t.end-t.start),this}getDuration(e){return this.entries.get(e)?.duration??0}print(e=[]){let t=performance.now()-this.totalStart,n=this.order.map(e=>{let t=this.entries.get(e)?.duration??0;return t>=1?`${e} ${Math.round(t)}ms`:null}).filter(Boolean),r=H.list([this.label,...e,H.ms(t)]);return this.level===`info`?this.logger.summary(r,n):this.logger.debug(H.list([r,n.join(` · `)])),{steps:Object.fromEntries(this.order.map(e=>[e,Math.round(this.entries.get(e)?.duration??0)])),total:Math.round(t)}}};gn();var tc=1<<20,nc=1<<21,rc=()=>new Promise(e=>setTimeout(e,0)),ic=[0,1,2,4,5,6,8,9,10];function ac(e,t,n,r=ic){let i=e.lanesPerRecord,a=r.length,o=0,s=0,c=0;for(;c<n;){let l=t+c,u=e.chunkFor(l),d=Math.min(e.recordsPerChunk-l%e.recordsPerChunk,n-c),f=e.baseOf(l);for(let e=0;e<d;e++,f+=i){let e=2166136261,t=2654435769;for(let n=0;n<a;n++){let i=u[f+r[n]];e=Math.imul(e^i,16777619),t=Math.imul(t+i|0,2246822507)^t>>>13}o=o+e>>>0,s=s+t>>>0}c+=d}return`${o.toString(16)}.${s.toString(16)}`}async function oc(e,t){let n=[],r=0;for(let{triOffset:i,triCount:a}of t)n.push(ac(e,i,a)),r+=a,r>=nc&&(r=0,await rc());return n}async function sc(e,t){let n=await e?.area(hn.SCENES).open(t);if(!n)return null;try{let e=await n.json(`index.json`),t=await n.file(`nodes.f32`),r=await n.file(`order.u32`);return e?.v!==2||!t||!r?(n.release(),null):{index:e,nodes:t,order:r,release:()=>n.release()}}catch{return n.release(),null}}async function cc(e,t,{index:n,bvh:r,orders:i,isStale:a,label:o=``}){let s=e?.area(hn.SCENES);if(!s)return!1;let c=n.totalNodes-n.tlasNodeCount,l=i.reduce((e,t)=>e+(t?.byteLength??0),0),u=await s.create(t,{label:`${o} (BVH)`,expectedBytes:c*64+l});if(!u)return!1;try{for(let e=n.tlasNodeCount;e<n.totalNodes;){if(a())throw Error(`scene changed while it was being stored`);let t=r.chunkFor(e),i=r.recordsPerChunk-e%r.recordsPerChunk,o=Math.min(i,n.totalNodes-e,tc),s=r.baseOf(e);await u.write(`nodes.f32`,t.subarray(s,s+o*16)),e+=o}for(let e of i)if(e)for(let t=0;t<e.length;t+=tc*4)await u.write(`order.u32`,e.subarray(t,Math.min(e.length,t+tc*4)));if(l===0&&await u.write(`order.u32`,new Uint8Array),a())throw Error(`scene changed while it was being stored`);return await u.writeJSON(`index.json`,n),await u.commit(),!0}catch{return await u.abort(),!1}}async function lc(e,t,n,r){for(let i=0;i<r;i+=tc){let a=Math.min(tc,r-i),o=await e.slice(i*64,(i+a)*64).arrayBuffer();t.setRecords(n+i,new Float32Array(o))}}async function uc(e,t,n){return new Uint32Array(await e.slice(t*4,(t+n)*4).arrayBuffer())}It();var dc=16,fc=G.POSITION_A_OFFSET,pc=G.POSITION_B_OFFSET,mc=G.POSITION_C_OFFSET;async function hc(e,t,n,r,{pause:i=null}={}){let a=e.lanesPerRecord,o=[new Float32Array(n),new Float32Array(n),new Float32Array(n)],[s,c,l]=o;for(let r=0;r<n;){let i=e.chunkFor(t+r),o=new Float32Array(i.buffer,i.byteOffset,i.length),u=Math.min(n,(((t+r)/e.recordsPerChunk|0)+1)*e.recordsPerChunk-t);for(let n=e.baseOf(t+r);r<u;r++,n+=a)s[r]=o[n+fc]+o[n+pc]+o[n+mc],c[r]=o[n+fc+1]+o[n+pc+1]+o[n+mc+1],l[r]=o[n+fc+2]+o[n+pc+2]+o[n+mc+2]}let u=new Uint32Array(n);for(let e=0;e<n;e++)u[e]=e;let d=[],f=(e,t)=>{if(t-e<=r)return d.push({start:e,count:t-e}),{piece:d.length-1};let n=e+(t-e>>1);return _c(u,o,gc(o,e,t),e,t,n),{left:f(e,n),right:f(n,t)}},p=f(0,n);return await i?.(),await vc(e,t,n,u,i),{order:u,pieces:d,tree:p}}function gc(e,t,n){let r=0,i=-1;for(let a=0;a<3;a++){let o=e[a],s=1/0,c=-1/0;for(let e=t;e<n;e++){let t=o[e];t<s&&(s=t),t>c&&(c=t)}c-s>i&&(i=c-s,r=a)}return r}function _c(e,t,n,r,i,a){let o=t[n],[s,c,l]=t,u=(t,n)=>{let r=e[t];e[t]=e[n],e[n]=r,r=s[t],s[t]=s[n],s[n]=r,r=c[t],c[t]=c[n],c[n]=r,r=l[t],l[t]=l[n],l[n]=r},d=2654435769,f=()=>(d^=d<<13,d^=d>>>17,d^=d<<5,o[r+(d>>>0)%(i-r)]);for(;i-r>1;){let e=f(),t=f(),n=f(),s=e<t?t<n?t:e<n?n:e:e<n?e:t<n?n:t,c=r,l=r,d=i;for(;l<d;){let e=o[l];e<s?u(c++,l++):e>s?u(l,--d):l++}if(a<c)i=c;else if(a>=d)r=d;else return}}async function vc(e,t,n,r,i){let a=e.lanesPerRecord,o=new Uint32Array(a),s=new Uint8Array(n),c=0;for(let l=0;l<n;l++){if(s[l]||(s[l]=1,r[l]===l))continue;let n=e.chunkFor(t+l),u=e.baseOf(t+l);for(let e=0;e<a;e++)o[e]=n[u+e];for(let d=l;;){let f=r[d],p=n,m=u;if(f===l){for(let e=0;e<a;e++)p[m+e]=o[e];break}n=e.chunkFor(t+f),u=e.baseOf(t+f);for(let e=0;e<a;e++)p[m+e]=n[u+e];s[f]=1,d=f,i&&!(++c&1048575)&&await i()}}}function yc(e,t,n,r){let i=t.length-1,a=[],o=i;for(let{bvhData:e}of n)a.push(o),o+=e.length/dc;let s=new Float32Array(i*dc),c=new Uint32Array(s.buffer),l=[s],u=new Uint32Array(r.length);for(let e=0;e<t.length;e++){let{bvhData:i,originalToBvh:o}=n[e];n[e].bvhData=n[e].originalToBvh=null;let s=a[e],{start:c,count:d}=t[e];Hi(new Uint32Array(i.buffer,i.byteOffset,i.length),s,c),l.push(i);for(let e=0;e<d;e++)u[r[c+e]]=c+(o?o[e]:e)}let d=0,f=e=>{if(e.piece!==void 0)return{index:a[e.piece],box:n[e.piece].aabb};let t=d++,r=f(e.left),i=f(e.right),o=t*dc;return s[o]=r.box[0],s[o+1]=r.box[1],s[o+2]=r.box[2],c[o+3]=r.index,s[o+4]=r.box[3],s[o+5]=r.box[4],s[o+6]=r.box[5],c[o+7]=i.index,s[o+8]=i.box[0],s[o+9]=i.box[1],s[o+10]=i.box[2],s[o+12]=i.box[3],s[o+13]=i.box[4],s[o+14]=i.box[5],{index:t,box:[0,1,2].map(e=>Math.min(r.box[e],i.box[e])).concat([3,4,5].map(e=>Math.max(r.box[e],i.box[e])))}};return f(e),{bvhData:l,nodeCount:o,originalToBvh:u}}var bc,xc=g((()=>{bc=`11.10.0`})),Sc,Cc=g((()=>{xc(),Sc=bc}));function wc(e,t,n=Tc){return e>=n&&t/Ec<e/3}var Tc,Ec,Dc=g((()=>{Tc=1e4,Ec=15e5}));Cc(),Dc();var Oc="const e={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_PACKED_OFFSET:3,NORMAL_B_PACKED_OFFSET:7,NORMAL_C_PACKED_OFFSET:11,UV_AB_OFFSET:12,UV_C_OFFSET:16,MATERIAL_FLAGS_OFFSET:18,MESH_INDEX_OFFSET:19};function t(e,t,n){let r=Math.sqrt(e*e+t*t+n*n);r>0?(e/=r,t/=r,n/=r):(e=0,t=0,n=1);let i=Math.abs(e)+Math.abs(t)+Math.abs(n),a=e/i,o=t/i;if(n<0){let e=a,t=o;a=(1-Math.abs(t))*(e>=0?1:-1),o=(1-Math.abs(e))*(t>=0?1:-1)}let s=Math.round(Math.min(1,Math.max(-1,a))*32767)&65535;return((Math.round(Math.min(1,Math.max(-1,o))*32767)&65535)<<16|s)>>>0}const n={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826,CLUSTER_LEAF:1073741827},r=new Float32Array(1),i=new Uint32Array(r.buffer);function a(e){let t=Math.fround(e);return t<=e?t:(r[0]=t,i[0]+=t>0?-1:1,r[0])}function o(e,t){return Math.max(Math.abs(e),Math.abs(t),1e-30)*2**-21}const s=[2,4,5];function c(e,t,n,r,i,c,u){let d=0;for(let f=0;f<3;f++){let p=1/0,m=-1/0;for(let e=0;e<i;e++)p=Math.min(p,r[e*6+f]),m=Math.max(m,r[e*6+3+f]);if(c&&(c[u+f]=p,c[u+3+f]=m),!(p<=m)){e[n+s[f]]=l,t[n+6+f]=0,t[n+9+f]=0;continue}let h=o(p,m),g=a(p-h),_=Math.max(-126,Math.ceil(Math.log2((m+h-g)/255)));for(;Math.fround(g+255*2**_)<m+h;)_++;let v=2**_;e[n+s[f]]=g,d|=_+127<<f*8;let y=0,b=0;for(let e=0;e<i;e++){let t=r[e*6+f],n=r[e*6+3+f],i=o(t,n);y|=Math.max(0,Math.min(255,Math.floor((t-i-g)/v)))<<e*8,b|=Math.max(0,Math.min(255,Math.ceil((n+i-g)/v)))<<e*8}t[n+6+f]=y>>>0,t[n+9+f]=b>>>0}t[n+1]=d>>>0}const l=1e30;n.TRIANGLE_LEAF;const u=e=>e>=2147483648,d=e=>~e>>>0>>>4,f=e=>~e&15,p=e.FLOATS_PER_TRIANGLE,m=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),h=e=>e instanceof Uint32Array?e:new Uint32Array(e.buffer,e.byteOffset,e.length),g=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:e,idx:t?e.viewAs(Uint32Array):h(e)}},_=(e,t)=>e.chunked?e.f.chunkFor(t):e.f,v=(e,t)=>e.chunked?e.idx.chunkFor(t):e.idx,y=(e,t)=>e.chunked?e.chunked.baseOf(t):t*x,b=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:t?t.viewAs(Float32Array):m(e),u:t?e:h(e)}},x=16,S=n.TRIANGLE_LEAF,C=n.BLAS_POINTER_LEAF,w=n.CLUSTER_LEAF;function T(e,t,n,r,i,a){if(n[r]>n[r+3]){for(let e=0;e<6;e++)i[a+e]=n[r+e];return}let o=e[t+4],s=e[t+5],c=e[t+6],l=e[t+7],u=e[t+8],d=e[t+9],f=e[t+10],p=e[t+11],m=e[t+12],h=e[t+13],g=e[t+14],_=e[t+15],v=d*g-f*h,y=f*m-u*g,b=u*h-d*m,x=o*v+s*y+c*b,S=o===1&&d===1&&g===1&&s===0&&c===0&&u===0&&f===0&&m===0&&h===0&&l===0&&p===0&&_===0,C=(Math.abs(o)+Math.abs(s)+Math.abs(c))*(Math.abs(u)+Math.abs(d)+Math.abs(f))*(Math.abs(m)+Math.abs(h)+Math.abs(g));if(S||!Number.isFinite(x)||Math.abs(x)<=1e-12*C){for(let e=0;e<6;e++)i[a+e]=n[r+e];return}let w=1/x,T=v*w,E=y*w,D=b*w,O=(c*h-s*g)*w,k=(o*g-c*m)*w,A=(s*m-o*h)*w,j=(s*f-c*d)*w,M=(c*u-o*f)*w,N=(o*d-s*u)*w,P=1/0,F=1/0,I=1/0,L=-1/0,R=-1/0,z=-1/0;for(let e=0;e<8;e++){let t=(e&1?n[r+3]:n[r])-l,i=(e&2?n[r+4]:n[r+1])-p,a=(e&4?n[r+5]:n[r+2])-_,o=T*t+O*i+j*a,s=E*t+k*i+M*a,c=D*t+A*i+N*a;o<P&&(P=o),o>L&&(L=o),s<F&&(F=s),s>R&&(R=s),c<I&&(I=c),c>z&&(z=c)}i[a]=P,i[a+1]=F,i[a+2]=I,i[a+3]=L,i[a+4]=R,i[a+5]=z}function E(t,n,r,i,a){let o=e.POSITION_A_OFFSET,s=e.POSITION_B_OFFSET,c=e.POSITION_C_OFFSET,l=1/0,u=1/0,d=1/0,f=-1/0,m=-1/0,h=-1/0;for(let e=0;e<r;e++){let r=n+e,i=t.chunked?t.f.chunkFor(r):t.f,a=t.chunked?t.chunked.baseOf(r):r*p;l=Math.min(l,i[a+o],i[a+s],i[a+c]),u=Math.min(u,i[a+o+1],i[a+s+1],i[a+c+1]),d=Math.min(d,i[a+o+2],i[a+s+2],i[a+c+2]),f=Math.max(f,i[a+o],i[a+s],i[a+c]),m=Math.max(m,i[a+o+1],i[a+s+1],i[a+c+1]),h=Math.max(h,i[a+o+2],i[a+s+2],i[a+c+2])}i[a]=l,i[a+1]=u,i[a+2]=d,i[a+3]=f,i[a+4]=m,i[a+5]=h}const D=new Float32Array(12),O=(e,t)=>e[t]>=l*.5;function k(e,t,n,r){let i=n[r]>n[r+3];e[t]=i?l:n[r],e[t+1]=i?l:n[r+1],e[t+2]=i?l:n[r+2],e[t+4]=i?l:n[r+3],e[t+5]=i?l:n[r+4],e[t+6]=i?l:n[r+5]}function A(e,t,n,r){let i=_(e,t),a=v(e,t),o=y(e,t);if(a[o+3]===S){E(n,a[o],a[o+1],r,0);return}let s=!O(i,o),c=!O(i,o+8);for(let e=0;e<3;e++)r[e]=Math.min(s?i[o+e]:1/0,c?i[o+8+e]:1/0),r[3+e]=Math.max(s?i[o+4+e]:-1/0,c?i[o+12+e]:-1/0)}const j=new Float32Array(16),M=new Float32Array(6),N=new Float32Array(24);function P(e,t,n,r,i,a){let o=_(e,t),s=v(e,t),l=y(e,t),u=s[l]&268435455,d=(s[l]>>>28&3)+1;for(let t=0;t<d;t++){let i=s[l+12+t];if(A(e,i&1073741823,n,M),i&1073741824){for(let e=0;e<6;e++)N[t*6+e]=M[e];continue}let a=r*16+(u+t)*3*4;for(let t=0;t<12;t++){let n=a+t>>4;j[4+t]=_(e,n)[y(e,n)+(a+t&15)]}T(j,0,M,0,N,t*6)}c(o,s,l,N,d,i,a)}function F(e,t,n,r,i,a=-1){let o=_(e,t),s=v(e,t),c=y(e,t),l=(t-i)*6,p=s[c+3];if(p===S){E(n,s[c],s[c+1],r,l);return}if(p===w){P(e,t,n,a,r,l);return}if(p===C){T(o,c,r,(s[c]-i)*6,r,l);return}let m=s[c+7],h=r,g=(p-i)*6;u(p)&&(E(n,d(p),f(p),D,0),h=D,g=0);let b=r,x=(m-i)*6;u(m)&&(E(n,d(m),f(m),D,6),b=D,x=6),k(o,c,h,g),k(o,c+8,b,x);for(let e=0;e<3;e++)r[l+e]=Math.min(h[g+e],b[x+e]),r[l+3+e]=Math.max(h[g+3+e],b[x+3+e])}var I=class{constructor(){this._bounds=null,this._boundsNodeCount=0,this._tlasBounds=null,this._rootBox=null}updateTrianglePositions(n,r,i){let a=i.length,o=b(n);for(let n=0;n<a;n++){let a=i[n],s=o.chunked?o.f.chunkFor(n):o.f,c=o.chunked?o.u.chunkFor(n):o.u,l=o.chunked?o.chunked.baseOf(n):n*p,u=a*9,d=r[u],f=r[u+1],m=r[u+2],h=r[u+3],g=r[u+4],_=r[u+5],v=r[u+6],y=r[u+7],b=r[u+8];s[l+e.POSITION_A_OFFSET]=d,s[l+e.POSITION_A_OFFSET+1]=f,s[l+e.POSITION_A_OFFSET+2]=m,s[l+e.POSITION_B_OFFSET]=h,s[l+e.POSITION_B_OFFSET+1]=g,s[l+e.POSITION_B_OFFSET+2]=_,s[l+e.POSITION_C_OFFSET]=v,s[l+e.POSITION_C_OFFSET+1]=y,s[l+e.POSITION_C_OFFSET+2]=b;let x=h-d,S=g-f,C=_-m,w=v-d,T=y-f,E=b-m,D=t(S*E-C*T,C*w-x*E,x*T-S*w);c[l+e.NORMAL_A_PACKED_OFFSET]=D,c[l+e.NORMAL_B_PACKED_OFFSET]=D,c[l+e.NORMAL_C_PACKED_OFFSET]=D}}refitRange(e,t,n,r){let i=b(t);r>this._boundsNodeCount&&(this._bounds=new Float32Array(r*6),this._boundsNodeCount=r);let a=g(e);for(let e=n+r-1;e>=n;e--)F(a,e,i,this._bounds,n)}refitPartial(e,t,n,r,i=null,a=-1){for(let r=0;r<n.length;r+=2)this.refitRange(e,t,n[r],n[r+1]);let o=b(t),s=g(e);i&&this.refitGroups(s,o,i[0],i[1]),(!this._tlasBounds||this._tlasBounds.length<r*6)&&(this._tlasBounds=new Float32Array(r*6));let c=this._tlasBounds;for(let e=r-1;e>=0;e--){let t=v(s,e),n=y(s,e);t[n+3]===C?(A(s,t[n],o,M),T(_(s,e),n,M,0,c,e*6)):F(s,e,o,c,0,a)}}refitGroups(e,t,n,r){let i=this._groupBox||=new Float32Array(6);for(let a=n+r-1;a>=n;a--){let n=_(e,a),r=v(e,a),o=y(e,a);r[o+3]!==S&&(A(e,r[o+3],t,i),k(n,o,i,0),A(e,r[o+7],t,i),k(n,o+8,i,0))}}refit(e,t,n,r=-1){let i=b(t);n!==this._boundsNodeCount&&(this._bounds=new Float32Array(n*6),this._boundsNodeCount=n);let a=g(e);for(let e=n-1;e>=0;e--)F(a,e,i,this._bounds,0,r)}};const L=64*1024*1024;function R(e,t,n){return n?new e(new SharedArrayBuffer(t*e.BYTES_PER_ELEMENT)):new e(t)}var z=class e{constructor(e,t,n,r=L,i=!1){let a=t*n.BYTES_PER_ELEMENT,o=Math.max(1,Math.floor(r/a));this.recordCount=e,this.lanesPerRecord=t,this.LaneType=n,this.recordsPerChunk=e<=o?Math.max(e,1):o,this.shared=i,this.chunks=[];let s=e;for(;s>0;){let e=Math.min(s,this.recordsPerChunk);this.chunks.push(R(n,e*t,i)),s-=e}this.chunks.length===0&&this.chunks.push(R(n,0,i))}static adopt(t,n,r,i){let a=Object.create(e.prototype);return a.recordCount=n,a.lanesPerRecord=r,a.LaneType=t[0]?.constructor??null,a.recordsPerChunk=i,a.chunks=t,a.shared=typeof SharedArrayBuffer<`u`&&t[0]?.buffer instanceof SharedArrayBuffer,a}static lazy(t,n,r,i=L,a=!1){let o=Math.max(1,Math.floor(i/(n*r.BYTES_PER_ELEMENT))),s=Object.create(e.prototype);return s.recordCount=t,s.lanesPerRecord=n,s.LaneType=r,s.recordsPerChunk=t<=o?Math.max(t,1):o,s.shared=a,s.chunks=Array(Math.max(1,Math.ceil(t/s.recordsPerChunk))),s._views=[],s}_materialize(e){if(this._owner)return this._owner._materialize(e),this.chunks[e];let t=e*this.recordsPerChunk,n=Math.min(this.recordsPerChunk,this.recordCount-t)*this.lanesPerRecord,r=this.chunks[e]=R(this.LaneType,n,this.shared);for(let t of this._liveViews())t.chunks[e]=new t.LaneType(r.buffer,r.byteOffset,r.byteLength/t.LaneType.BYTES_PER_ELEMENT);return r}materializeAll(){for(let e=0;e<this.chunks.length;e++)!this.chunks[e]&&!this._spilled?.has(e)&&this._materialize(e);return this}get chunkCount(){return this.chunks.length}get single(){return this.chunks.length===1?this.chunks[0]:null}get byteLength(){let e=0;for(let t of this.chunks)t&&(e+=t.byteLength);return e}chunkFor(e){let t=e/this.recordsPerChunk|0,n=this.chunks[t];if(n)return n;if(this._spilled?.has(t))throw Error(`ChunkedRecords: chunk ${t} is on disk — await ensureResident() before touching record ${e}`);return this._materialize(t)}async spill(e,{keep:t=()=>!1}={}){if(this._owner)throw Error(`ChunkedRecords: spill the storage, not a view of it`);this._store=e,this._spilled??=new Set;let n=0;for(let r=0;r<this.chunks.length;r++){let i=this.chunks[r];if(!(!i||t(r))){await e.write(r,i),this.chunks[r]=null;for(let e of this._liveViews())e.chunks[r]=null;this._spilled.add(r),n+=i.byteLength}}return n}async spillChunk(e,t){let n=this.chunks[e];if(!n)return 0;this._store=t,this._spilled??=new Set,await t.write(e,n),this.chunks[e]=null;for(let t of this._liveViews())t.chunks[e]=null;return this._spilled.add(e),n.byteLength}async ensureResident(e=0,t=this.recordCount){if(!this._spilled?.size||t<=0)return;let n=e/this.recordsPerChunk|0,r=(e+t-1)/this.recordsPerChunk|0;for(let e=n;e<=r;e++){if(!this._spilled.has(e))continue;let t=Math.min(this.recordsPerChunk,this.recordCount-e*this.recordsPerChunk)*this.lanesPerRecord,n=R(this.LaneType,t,this.shared),r=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);this._store.readInto?await this._store.readInto(e,r):r.set(new Uint8Array(await this._store.read(e,r.byteLength))),this.chunks[e]=n;for(let t of this._liveViews())t.chunks[e]=new t.LaneType(n.buffer,n.byteOffset,n.byteLength/t.LaneType.BYTES_PER_ELEMENT);this._spilled.delete(e)}}_liveViews(){return this._weakViews&&=this._weakViews.filter(e=>e.deref()),[...this._views??[],...(this._weakViews??[]).map(e=>e.deref())]}isResident(e=0,t=this.recordCount){if(!this._spilled?.size||t<=0)return!0;let n=e/this.recordsPerChunk|0,r=(e+t-1)/this.recordsPerChunk|0;for(let e=n;e<=r;e++)if(this._spilled.has(e))return!1;return!0}get spilledChunks(){return this._spilled?.size??0}baseOf(e){return e%this.recordsPerChunk*this.lanesPerRecord}isContiguous(e,t){return t<=0?!0:(e/this.recordsPerChunk|0)==((e+t-1)/this.recordsPerChunk|0)}slice(e,t){let n=this.baseOf(e),r=t*this.lanesPerRecord;if(this.isContiguous(e,t))return this.chunkFor(e).subarray(n,n+r);let i=new this.LaneType(r);return this.readRecords(e,t,i),i}readRecords(e,t,n){let r=0;for(;r<t;){let i=e+r,a=this.chunkFor(i),o=this.baseOf(i),s=this.recordsPerChunk-i%this.recordsPerChunk,c=Math.min(s,t-r);n.set(a.subarray(o,o+c*this.lanesPerRecord),r*this.lanesPerRecord),r+=c}return n}setRecords(e,t){let n=t.length/this.lanesPerRecord,r=0;for(;r<n;){let i=e+r,a=this.chunkFor(i),o=this.baseOf(i),s=this.recordsPerChunk-i%this.recordsPerChunk,c=Math.min(s,n-r);a.set(t.subarray(r*this.lanesPerRecord,(r+c)*this.lanesPerRecord),o),r+=c}}copyOf(e,t){return this.readRecords(e,t,new this.LaneType(t*this.lanesPerRecord))}trimTo(t){let n=Math.max(1,Math.ceil(t/this.recordsPerChunk)),r=this.chunks.slice(0,n),i=(t-(n-1)*this.recordsPerChunk)*this.lanesPerRecord,a=r[n-1];return a.length>i&&(r[n-1]=a.subarray(0,Math.max(0,i))),e.adopt(r,t,this.lanesPerRecord,this.recordsPerChunk)}grow(e){if(e<=this.recordCount)return;let t=this.chunks.length-1,n=(e,t)=>Math.min(this.recordsPerChunk,t-e*this.recordsPerChunk)*this.lanesPerRecord,r=this.chunks[t];this.recordCount=e;for(let t of this._liveViews())t.recordCount=e;if(this.chunks.length*this.recordsPerChunk<e){this.chunks.length=Math.ceil(e/this.recordsPerChunk);for(let e of this._liveViews())e.chunks.length=this.chunks.length}if(r&&r.length<n(t,e)){let i=R(this.LaneType,n(t,e),this.shared);i.set(r),this.chunks[t]=i;for(let e of this._liveViews())e.chunks[t]=new e.LaneType(i.buffer,i.byteOffset,i.byteLength/e.LaneType.BYTES_PER_ELEMENT)}else if(!r&&this._spilled?.has(t))throw Error(`ChunkedRecords: cannot grow past chunk ${t}, which is on disk`)}release(e,t){let n=this.recordsPerChunk,r=Math.ceil(e/n),i=Math.floor((e+t)/n),a=0;for(let e=r;e<i;e++){let t=this.chunks[e];if(t){a+=t.byteLength,this.chunks[e]=void 0;for(let t of this._liveViews())t.chunks[e]=void 0}}return a}trimInPlace(e){let t=Math.max(1,Math.ceil(e/this.recordsPerChunk)),n=Math.max(0,(e-(t-1)*this.recordsPerChunk)*this.lanesPerRecord),r=[this,...this._liveViews()];for(let i of r){i.chunks.length=t;let r=i.chunks[t-1];r&&r.length>n&&(i.chunks[t-1]=r.subarray(0,n)),i.recordCount=e}if(this._spilled)for(let e of this._spilled)e>=t&&this._spilled.delete(e);return this}viewAs(t){let n=e=>new t(e.buffer,e.byteOffset,e.byteLength/t.BYTES_PER_ELEMENT),r=e.adopt(this.chunks.map(e=>e?n(e):void 0),this.recordCount,this.lanesPerRecord,this.recordsPerChunk);return r.LaneType=t,r._owner=this,this._views?this._views.push(r):(this._weakViews??=[]).push(new WeakRef(r)),r._spilled=this._spilled??=new Set,r}};const B=new I;let V=null,H=null,U=0;self.onmessage=function(e){let{type:t}=e.data;if(t===`init`){V=z.adopt(e.data.sharedBvhBufs.map(e=>new Float32Array(e)),e.data.bvhRecordCount,16,e.data.bvhRecordsPerChunk),H=z.adopt(e.data.sharedTriBufs.map(e=>new Uint32Array(e)),e.data.triRecordCount,e.data.triLanesPerRecord,e.data.triRecordsPerChunk),U=V.recordCount;return}if(t===`refit`)try{let t=performance.now(),{blasRanges:n,tlasNodeCount:r,groupRange:i,treeNodeCount:a,recordNodeStart:o=-1}=e.data;n?B.refitPartial(V,H,n,r,i,o):B.refit(V,H,a??U,o),self.postMessage({type:`refitComplete`,refitTimeMs:performance.now()-t})}catch(e){console.error(`[BVHRefitWorker] Refit error:`,e),self.postMessage({type:`error`,error:e.message})}};",kc=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Oc],{type:`text/javascript;charset=utf-8`});function Ac(e){let t;try{if(t=kc&&(self.URL||self.webkitURL).createObjectURL(kc),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Oc),{type:`module`,name:e?.name})}}var jc="const e={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826,CLUSTER_LEAF:1073741827};new Uint32Array(new Float32Array(1).buffer);function t(e){return new Uint32Array(e.buffer,e.byteOffset,e.length)}function n(e,t){if(e>=1073741824)throw RangeError(`${t} is ${e.toLocaleString()}, at or past the BVH index limit of ${1073741824 .toLocaleString()}. Node indices are stored as u32 bit patterns and the leaf tags occupy everything above that.`);return e}const r=Float64Array.from([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);Object.freeze([]);function i(e,t){return e[t]*(e[t+5]*e[t+10]-e[t+6]*e[t+9])-e[t+4]*(e[t+1]*e[t+10]-e[t+2]*e[t+9])+e[t+8]*(e[t+1]*e[t+6]-e[t+2]*e[t+5])}function a(e,t,n){let a=i(e,t);if(!Number.isFinite(a)||Math.abs(a)<1e-20)return n.set(r),n;let o=1/a;return n[0]=(e[t+5]*e[t+10]-e[t+6]*e[t+9])*o,n[1]=(e[t+2]*e[t+9]-e[t+1]*e[t+10])*o,n[2]=(e[t+1]*e[t+6]-e[t+2]*e[t+5])*o,n[3]=0,n[4]=(e[t+6]*e[t+8]-e[t+4]*e[t+10])*o,n[5]=(e[t]*e[t+10]-e[t+2]*e[t+8])*o,n[6]=(e[t+2]*e[t+4]-e[t]*e[t+6])*o,n[7]=0,n[8]=(e[t+4]*e[t+9]-e[t+5]*e[t+8])*o,n[9]=(e[t+1]*e[t+8]-e[t]*e[t+9])*o,n[10]=(e[t]*e[t+5]-e[t+1]*e[t+4])*o,n[11]=0,n[12]=-(n[0]*e[t+12]+n[4]*e[t+13]+n[8]*e[t+14]),n[13]=-(n[1]*e[t+12]+n[5]*e[t+13]+n[9]*e[t+14]),n[14]=-(n[2]*e[t+12]+n[6]*e[t+13]+n[10]*e[t+14]),n[15]=1,n}function o(e,t){for(let n=0;n<16;n++)if(e[t+n]!==r[n])return!1;return!0}const s=e=>e<32?e:32,c=new Float64Array(16);var l=class r{constructor(){this._flatBuffer=null,this._flatBufferCapacity=0,this._binCounts=new Int32Array(96),this._binBounds=new Float64Array(576),this._binSuffix=new Float64Array(32),this._binSuffixCount=new Int32Array(32),this._order=null,this._stackI=null,this._stackB=null,this._stackFrames=0,this._sortScratch=[],this._suffix=null,this._bounds=new Float64Array(12),this._extent=new Float64Array(3),this._cMin=new Float64Array(3)}static nodeCountFor(e){return e>0?e*2-1:0}releaseFlattenBuffer(){this._flatBuffer=null,this._flatBufferCapacity=0}build(e){let t=e.clusterCount>0,n=t?e.clusterBounds:new Float64Array(e.entryCount*6);t||e.writeEntryWorldAABBs(n);let i=this.buildStructure(n,t?e.clusterCount:e.entryCount);return r.fillLeaves(i.data,i.nodeCount,e),i}buildStructure(i,a){let o=r.nodeCountFor(a);if(a===0)return{data:new Float32Array,nodeCount:0};n(o,`TLAS node count`);let s=o*16;s>this._flatBufferCapacity&&(this._flatBuffer=new Float32Array(s),this._flatBufferCapacity=s);let c=this._flatBuffer,l=t(c);(!this._order||this._order.length<a)&&(this._order=new Int32Array(a));let u=this._order;for(let e=0;e<a;e++)u[e]=e;this._ensureStack(64);let d=0,f=0,p=0,m=a,h=this._bounds;this._rangeBounds(i,u,p,m,h,0);let g=h[0],_=h[1],v=h[2],y=h[3],b=h[4],x=h[5];for(;;){if(m-p===1){let t=f*16;l[t]=0,l[t+1]=u[p],c[t+2]=0,l[t+3]=e.BLAS_POINTER_LEAF}else{let e=this._partition(i,u,p,m,g,_,v,y,b,x),t=e-p,n=f+1,r=n+(t*2-1),a=f*16;c[a]=h[0],c[a+1]=h[1],c[a+2]=h[2],l[a+3]=n,c[a+4]=h[3],c[a+5]=h[4],c[a+6]=h[5],l[a+7]=r,c[a+8]=h[6],c[a+9]=h[7],c[a+10]=h[8],c[a+11]=0,c[a+12]=h[9],c[a+13]=h[10],c[a+14]=h[11],c[a+15]=0;let o=t<=m-e,s=o?0:6,S=o?6:0;d=this._push(d,o?r:n,o?e:p,o?m:e,h,S),f=o?n:r,o?m=e:p=e,g=h[s],_=h[s+1],v=h[s+2],y=h[s+3],b=h[s+4],x=h[s+5];continue}if(d===0)break;d--;let t=d*3,n=d*6;f=this._stackI[t],p=this._stackI[t+1],m=this._stackI[t+2],g=this._stackB[n],_=this._stackB[n+1],v=this._stackB[n+2],y=this._stackB[n+3],b=this._stackB[n+4],x=this._stackB[n+5]}return{data:c.subarray(0,s),nodeCount:o}}_push(e,t,n,r,i,a){e>=this._stackFrames&&this._ensureStack(this._stackFrames*2);let o=e*3,s=e*6;this._stackI[o]=t,this._stackI[o+1]=n,this._stackI[o+2]=r;for(let e=0;e<6;e++)this._stackB[s+e]=i[a+e];return e+1}_ensureStack(e){if(this._stackFrames>=e)return;let t=new Int32Array(e*3),n=new Float64Array(e*6);this._stackI&&(t.set(this._stackI),n.set(this._stackB)),this._stackI=t,this._stackB=n,this._stackFrames=e}static fillLeaves(n,i,a){let o=t(n);if(a.clusterCount>0){for(let t=0;t<i;t++){let r=t*16;o[r+3]===e.BLAS_POINTER_LEAF&&a.writeClusterLeaf(n,o,r,o[r+1],a.clusterWorld,t)}return}for(let t=0;t<i;t++){let i=t*16;if(o[i+3]!==e.BLAS_POINTER_LEAF)continue;let s=o[i+1]&1073741823;o[i]=a.entryRoot(s),n[i+2]=+!!a.entryVisible(s),r.writeLeafMatrix(n,o,i,a,a.repOf(s),s),a.setLeafOf(s,t)}}static writeLeafMatrix(e,t,n,r,i,s=i){let l=c,u=r.matrixRow(i),d=r.rowArray;a(d,u,l),e[n+4]=l[0],e[n+5]=l[4],e[n+6]=l[8],e[n+7]=l[12],e[n+8]=l[1],e[n+9]=l[5],e[n+10]=l[9],e[n+11]=l[13],e[n+12]=l[2],e[n+13]=l[6],e[n+14]=l[10],e[n+15]=l[14],t[n+1]=(s|(o(d,u)?1073741824:0))>>>0}_partition(e,t,n,r,i,a,o,s,c,l){let u=r-n,d=0;if(u===2)d=n+1;else if(u<=8)d=n+(u>>1),this._insertionSortRange(e,t,n,r,this._widestCentroidAxis(e,t,n,r));else{if(d=this._binnedSplit(e,t,n,r,i,a,o,s,c,l),d>n&&d<r)return d;if(d=this._sweepSplit(e,t,n,r,i,a,o,s,c,l),!(d>n&&d<r)){let f=s-i,p=c-a,m=l-o,h=p>f&&p>m?1:m>f?2:0;this._sortRange(e,t,n,r,h),d=n+(u>>1)}}let f=this._bounds;return this._rangeBounds(e,t,n,d,f,0),this._rangeBounds(e,t,d,r,f,6),d}_binnedSplit(e,t,n,r,i,a,o,c,l,u){let d=this._surfaceArea(i,a,o,c,l,u);if(!(d>0)||!isFinite(d))return n;let f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,_=-1/0;for(let i=n;i<r;i++){let n=t[i]*6,r=(e[n]+e[n+3])*.5,a=(e[n+1]+e[n+4])*.5,o=(e[n+2]+e[n+5])*.5;r<f&&(f=r),r>h&&(h=r),a<p&&(p=a),a>g&&(g=a),o<m&&(m=o),o>_&&(_=o)}let v=this._extent,y=this._cMin;v[0]=h-f,v[1]=g-p,v[2]=_-m,y[0]=f,y[1]=p,y[2]=m;let b=1/0,x=-1,S=-1,C=this._binCounts,w=this._binBounds,T=v[0]>1e-12,E=v[1]>1e-12,D=v[2]>1e-12;if(!T&&!E&&!D)return n;let O=s(r-n),k=T?O/v[0]:0,A=E?O/v[1]:0,j=D?O/v[2]:0;C.fill(0,0,O*3);for(let e=0;e<O*3;e++){let t=e*6;w[t]=w[t+1]=w[t+2]=1/0,w[t+3]=w[t+4]=w[t+5]=-1/0}for(let i=n;i<r;i++){let n=t[i]*6,r=e[n],a=e[n+1],o=e[n+2],s=e[n+3],c=e[n+4],l=e[n+5];for(let e=0;e<3;e++){let t=e===0?k:e===1?A:j;if(t===0)continue;let n=((e===0?(r+s)*.5:e===1?(a+c)*.5:(o+l)*.5)-y[e])*t|0;n<0?n=0:n>=O&&(n=O-1),n+=e*O,C[n]++;let i=n*6;r<w[i]&&(w[i]=r),a<w[i+1]&&(w[i+1]=a),o<w[i+2]&&(w[i+2]=o),s>w[i+3]&&(w[i+3]=s),c>w[i+4]&&(w[i+4]=c),l>w[i+5]&&(w[i+5]=l)}}for(let e=0;e<3;e++){if(!(v[e]>1e-12))continue;let t=e*O,n=this._binSuffix,r=this._binSuffixCount,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0,u=0;for(let e=O-1;e>=1;e--){let d=(t+e)*6;w[d]<i&&(i=w[d]),w[d+1]<a&&(a=w[d+1]),w[d+2]<o&&(o=w[d+2]),w[d+3]>s&&(s=w[d+3]),w[d+4]>c&&(c=w[d+4]),w[d+5]>l&&(l=w[d+5]),u+=C[t+e],n[e]=u?this._surfaceArea(i,a,o,s,c,l):0,r[e]=u}let f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,_=-1/0,y=0;for(let i=1;i<O;i++){let a=(t+i-1)*6;if(w[a]<f&&(f=w[a]),w[a+1]<p&&(p=w[a+1]),w[a+2]<m&&(m=w[a+2]),w[a+3]>h&&(h=w[a+3]),w[a+4]>g&&(g=w[a+4]),w[a+5]>_&&(_=w[a+5]),y+=C[t+i-1],y===0||r[i]===0)continue;let o=1+(this._surfaceArea(f,p,m,h,g,_)*y+n[i]*r[i])/d;o<b&&(b=o,x=e,S=i)}}if(x<0)return n;let M=O/v[x],N=y[x],P=this._bounds;P[0]=P[1]=P[2]=P[6]=P[7]=P[8]=1/0,P[3]=P[4]=P[5]=P[9]=P[10]=P[11]=-1/0;let F=n,I=r-1;for(;F<=I;){let n=t[F]*6,r=((e[n+x]+e[n+3+x])*.5-N)*M|0;r<0?r=0:r>=O&&(r=O-1);let i=r<S?0:6;if(e[n]<P[i]&&(P[i]=e[n]),e[n+1]<P[i+1]&&(P[i+1]=e[n+1]),e[n+2]<P[i+2]&&(P[i+2]=e[n+2]),e[n+3]>P[i+3]&&(P[i+3]=e[n+3]),e[n+4]>P[i+4]&&(P[i+4]=e[n+4]),e[n+5]>P[i+5]&&(P[i+5]=e[n+5]),i===0)F++;else{let e=t[F];t[F]=t[I],t[I]=e,I--}}return F}_sweepSplit(e,t,n,r,i,a,o,s,c,l){let u=r-n,d=this._surfaceArea(i,a,o,s,c,l);if(!(d>0)||!isFinite(d))return n;let f=this._suffixBuffer(u),p=1/0,m=-1,h=-1;for(let i=0;i<3;i++){this._sortRange(e,t,n,r,i);let a=1/0,o=1/0,s=1/0,c=-1/0,l=-1/0,g=-1/0;for(let r=u-1;r>=1;r--){let i=t[n+r]*6;e[i]<a&&(a=e[i]),e[i+1]<o&&(o=e[i+1]),e[i+2]<s&&(s=e[i+2]),e[i+3]>c&&(c=e[i+3]),e[i+4]>l&&(l=e[i+4]),e[i+5]>g&&(g=e[i+5]);let u=r*6;f[u]=a,f[u+1]=o,f[u+2]=s,f[u+3]=c,f[u+4]=l,f[u+5]=g}let _=1/0,v=1/0,y=1/0,b=-1/0,x=-1/0,S=-1/0;for(let r=1;r<u;r++){let a=t[n+r-1]*6;e[a]<_&&(_=e[a]),e[a+1]<v&&(v=e[a+1]),e[a+2]<y&&(y=e[a+2]),e[a+3]>b&&(b=e[a+3]),e[a+4]>x&&(x=e[a+4]),e[a+5]>S&&(S=e[a+5]);let o=r*6,s=this._surfaceArea(_,v,y,b,x,S),c=this._surfaceArea(f[o],f[o+1],f[o+2],f[o+3],f[o+4],f[o+5]),l=1+(s*r+c*(u-r))/d;l<p&&(p=l,m=i,h=r)}}return m<0||h<=0?n:(m!==2&&this._sortRange(e,t,n,r,m),n+h)}_widestCentroidAxis(e,t,n,r){let i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let u=n;u<r;u++){let n=t[u]*6,r=(e[n]+e[n+3])*.5,d=(e[n+1]+e[n+4])*.5,f=(e[n+2]+e[n+5])*.5;r<i&&(i=r),r>s&&(s=r),d<a&&(a=d),d>c&&(c=d),f<o&&(o=f),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o;return d>u&&d>f?1:f>u?2:0}_insertionSortRange(e,t,n,r,i){let a=i,o=3+i;for(let i=n+1;i<r;i++){let r=t[i],s=e[r*6+a]+e[r*6+o],c=i-1;for(;c>=n&&e[t[c]*6+a]+e[t[c]*6+o]>s;)t[c+1]=t[c],c--;t[c+1]=r}}_sortRange(e,t,n,r,i){let a=r-n,o=this._sortScratch;o.length=a;for(let e=0;e<a;e++)o[e]=t[n+e];let s=i,c=3+i;o.sort((t,n)=>e[t*6+s]+e[t*6+c]-(e[n*6+s]+e[n*6+c]));for(let e=0;e<a;e++)t[n+e]=o[e]}_suffixBuffer(e){let t=e*6;return(!this._suffix||this._suffix.length<t)&&(this._suffix=new Float64Array(t)),this._suffix}_rangeBounds(e,t,n,r,i,a){let o=1/0,s=1/0,c=1/0,l=-1/0,u=-1/0,d=-1/0;for(let i=n;i<r;i++){let n=t[i]*6;e[n]<o&&(o=e[n]),e[n+1]<s&&(s=e[n+1]),e[n+2]<c&&(c=e[n+2]),e[n+3]>l&&(l=e[n+3]),e[n+4]>u&&(u=e[n+4]),e[n+5]>d&&(d=e[n+5])}i[a]=o,i[a+1]=s,i[a+2]=c,i[a+3]=l,i[a+4]=u,i[a+5]=d}_surfaceArea(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}};const u={silent:0,error:1,warn:2,info:3,debug:4},d=`info`,f=`rayzeeLogLevel`,p=`rayzeeLogNamespaces`,m=`color:#7c8494`,h=`color:inherit`;let g=null,_=null;function v(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function y(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function b(){if(g!==null)return g;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in u?(g=u[e],g):(g=u[v(f)]??u[d],g)}function x(){if(_!==null)return _;let e=globalThis.__RAYZEE_LOG_NS__??v(p);return _=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],_}function S(e,t){if(t<u.debug)return!0;let n=x();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function C(e,t,n){if(e>b()||!S(t,e))return;let r=e===u.error?console.error:e===u.warn?console.warn:console.log,i=`[${t}]`;typeof n[0]==`string`?r(`%c${i}%c ${n[0]}`,m,h,...n.slice(1)):r(`%c${i}`,m,...n)}const w={n:e=>Number(e).toLocaleString(`en-US`),ms:e=>e<10?`${Number(e).toFixed(1)} ms`:`${Math.round(e)} ms`,mb:e=>{let t=e/(1024*1024);return t<10?`${t.toFixed(1)} MB`:`${Math.round(t)} MB`},px:(e,t)=>`${e}×${t}`,count:(e,t,n=`${t}s`)=>`${w.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},T={levels:u,setLevel(e){return e in u?(globalThis.__RAYZEE_LOG_LEVEL__=e,g=u[e],y(f,e===d?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(u).join(`, `)}`),this.getLevel())},getLevel(){let e=b();return Object.keys(u).find(t=>u[t]===e)},isEnabled(e){return(u[e]??u.debug)<=b()},only(...e){let t=e.flat().filter(Boolean);return _=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),y(p,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return g=null,_=null,this.getLevel()}};function E(e){return{namespace:e,error:(...t)=>C(u.error,e,t),warn:(...t)=>C(u.warn,e,t),info:(...t)=>C(u.info,e,t),debug:(...t)=>C(u.debug,e,t),isEnabled:e=>T.isEnabled(e),summary(t,n=[]){let r=n.filter(Boolean);if(r.length===0||!console.groupCollapsed){C(u.info,e,[t]),r.forEach(t=>C(u.debug,e,[t]));return}u.info>b()||((b()>=u.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,m,h),r.forEach(e=>console.log(e)),console.groupEnd())}}}function D(e){e&&e in u&&(globalThis.__RAYZEE_LOG_LEVEL__=e,g=u[e])}const O=E(`bvh`);self.onmessage=function(e){let{aabbs:t,count:n,logLevel:r}=e.data;D(r);try{let e=performance.now(),{data:r,nodeCount:i}=new l().buildStructure(new Float64Array(t),n);O.debug(`TLAS ${w.n(i)} nodes in ${w.ms(performance.now()-e)}`),self.postMessage({tlasData:r,nodeCount:i},[r.buffer])}catch(e){O.error(`TLAS build failed:`,e),self.postMessage({error:e.message})}};",Mc=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,jc],{type:`text/javascript;charset=utf-8`});function Nc(e){let t;try{if(t=Mc&&(self.URL||self.webkitURL).createObjectURL(Mc),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(jc),{type:`module`,name:e?.name})}}pn(),Jn(),ke(),It(),tn(),on(),ri(),bn(),kn(),li(),Pr();var Pc=5e4,Fc=2e5,Ic=2e6,Lc=1<<19,Rc=4e7,zc=1e6,Bc=1024**3,Vc=1024**3,Hc=32*1024*1024,Uc=64*1024*1024,Wc=256*1024*1024,Gc=ve(`scene`),Kc=Object.freeze([`maps`,`normalMaps`,`bumpMaps`,`roughnessMaps`,`metalnessMaps`,`emissiveMaps`,`displacementMaps`,`anisotropyMaps`,`transmissionMaps`,`clearcoatMaps`,`clearcoatRoughnessMaps`,`sheenColorMaps`,`sheenRoughnessMaps`,`iridescenceMaps`,`iridescenceThicknessMaps`,`specularIntensityMaps`,`specularColorMaps`,`diffuseTransmissionMaps`,`diffuseTransmissionColorMaps`]),qc=e=>Array.isArray(e)?e:[e],Jc=e=>qc(e).reduce((e,t)=>e+t.byteLength,0),Yc=64*1024*1024;async function Xc(e,t,n){for(let r of qc(n))await e.writeAt(t,r),t+=r.byteLength}function Zc(e){let t=0;return e.traverse(e=>{let n=e.isMesh?e.geometry:null;n&&(t=Math.max(t,Math.ceil((n.index?n.index.count:n.attributes.position?.count??0)/3)))}),t}var Qc=1024,$c=64;function el(e){let t=Int32Array.from(e).sort(),n=[],r=t[0],i=r;for(let e=1;e<=t.length;e++){if(e<t.length&&t[e]-i<=Qc){i=t[e];continue}n.push({offset:r*16,count:(i-r+1)*16}),r=i=t[e]}return n.length>$c?[{offset:t[0]*16,count:(t.at(-1)-t[0]+1)*16}]:n}var tl=class{constructor(e={}){this.config={useWorkers:!0,bvhDepth:30,maxLeafSize:4,verbose:!1,useFloat32Array:!0,textureQuality:`adaptive`,maxTextureSize:$t.DEFAULT_MAX_TEXTURE_SIZE,enableTextureCache:!0,maxConcurrentTextureTasks:Math.min(Dr(),6),maxSceneBytes:yo,sceneCache:!0,sceneCacheMinBuildMs:Tc,...e},this.triangleData=null,this.triangleFloats=null,this.triangleCount=0,this.materials=[],this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.roughnessMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.displacementMaps=[],this.anisotropyMaps=[],this.transmissionMaps=[],this.clearcoatMaps=[],this.clearcoatRoughnessMaps=[],this.sheenColorMaps=[],this.sheenRoughnessMaps=[],this.iridescenceMaps=[],this.iridescenceThicknessMaps=[],this.specularIntensityMaps=[],this.specularColorMaps=[],this.diffuseTransmissionMaps=[],this.diffuseTransmissionColorMaps=[],this.directionalLights=[],this.cameras=[],this.spheres=[],this.bvhRoot=null,this.bvh=null,this.bvhData=null,this.bvhIndexChunks=null,this.bvhIndex=null,this.materialData=null,this.instanceTable=null,this._refitWorker=null,this._refitSharedBuffers=null,this._rebuildGeneration=0,this._pendingRebuilds=new Map,this.srgbBucketTextures=null,this.linearBucketTextures=null,this.emissiveTriangleData=null,this.emissiveTriangleCount=0,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this._initProcessors(),this.isProcessing=!1,this.processingStage=null,this.memory=new To,this.memoryPreflight=null,this.performanceMetrics={textureCreationTime:0,geometryExtractionTime:0,bvhBuildTime:0,blasBuildTime:0,blasWorkerTime:0,tlasBuildTime:0,bvhAssembleTime:0,totalProcessingTime:0}}setMaxTextureSize(e){return this.config.maxTextureSize=e,this.textureCreator?.setMaxTextureSize(e)}_initProcessors(){this.geometryExtractor=new qn({issues:this.config.issues}),this.bvhBuilder=new Zi,this.bvhBuilder.maxLeafSize=this.config.maxLeafSize,this.textureCreator=new Ws({maxTextureSize:this.config.maxTextureSize,issues:this.config.issues}),this.emissiveTriangleBuilder=new $s,this.tlasBuilder=new oo,this._tlasWorker=null,this._tlasWorkerFailed=!1}_log(e,t){t===void 0?Gc.debug(e):Gc.debug(e,t)}needsSpill(e){return co(this.geometryExtractor.surveyScene(e)).total>vo}get spilling(){return!!this._progressive&&(this.triangles?.chunks?.length??0)>1}_preflightMemory(e){let t=this.config.maxSceneBytes??9663676416,n=this.geometryExtractor.surveyScene(e),r=co(n);if(this._streaming){let t=Bc+Zc(e)*(G.FLOATS_PER_TRIANGLE*4+44);r.total=lo(r,n.placements,Math.min(r.triangles,t))}else this._progressive&&(r.total-=r.bvh);let i={...n,estimate:r,safeBytes:vo,maxBytes:t,fits:r.total<=vo};if(this.memoryPreflight=i,r.total<1610612736)return i;if(Gc.debug(H.list([`memory preflight: ${H.mb(r.total)} estimated`,`triangles ${H.mb(r.triangles)} · bvh ${H.mb(r.bvh)} · geometry ${H.mb(r.geometry)}`,`${H.n(n.triangles)} tris · ${H.n(n.placements)} placements`])),r.total>t){let e=`Scene needs about ${H.mb(r.total)} of CPU memory, past the ${H.mb(t)} a browser tab can hold — loading it would crash the tab rather than fail. Reduce the scene (it has ${H.n(n.triangles)} triangles), or raise maxSceneBytes to try anyway.`;throw this.config.issues?.record(Y.SCENE_MEMORY_BUDGET,e,{...n,estimate:r,maxBytes:t}),Error(e)}return i.fits||this.config.issues?.warn(Y.SCENE_MEMORY_BUDGET,`Scene needs about ${H.mb(r.total)} of CPU memory, above the ${H.mb(vo)} a fresh browser session can usually place. It may still load, but a long-running session will probably fail during BVH assembly; restarting the browser recovers the address space.`,{...n,estimate:r,safeBytes:vo}),i}_checkAssemblyHeadroom(e){let t=e*64;if(t<1610612736)return!0;let n=uo(Math.ceil(t*Co),{shared:un});return this.memoryPreflight&&(this.memoryPreflight.assemblyProbed=n.placed),n.exhausted&&this.config.issues?.warn(Y.SCENE_MEMORY_BUDGET,`BVH assembly needs ${H.mb(t)} but only ${H.mb(n.placed)} could be allocated. Restarting the browser usually recovers the address space.`,{totalNodes:e,need:t,placeable:n.placed}),!n.exhausted}_liveMemoryParts(){let e=this.instanceTable,t={triangles:this.triangles?.byteLength??0,bvh:this.bvh?.byteLength??0,geometry:this._geometryBytes??this.memoryPreflight?.geometryBytes??0,placements:e?.matrixBytes??0,blasScratch:0,orderMaps:0};if(e){for(let n of e.blasData.values())t.blasScratch+=n?Jc(n):0;for(let n of e.bvhToOriginal.values())t.orderMaps+=n?.byteLength??0;for(let n of e.originalToBvhMap.values())t.orderMaps+=n?.byteLength??0}return t}sceneBounds(){if(!this.bvh||this.bvh.recordCount===0)return null;if(!this.bvh.isResident(0,1))return this._spilledRootBounds??null;let e=this.bvh.chunkFor(0),t=this.bvh.baseOf(0),n=[],r=[];for(let i=0;i<3;i++)n.push(Math.min(e[t+i],e[t+8+i])),r.push(Math.max(e[t+4+i],e[t+12+i]));return{min:n,max:r}}_sampleMemory(e){this.memory.sample(e,this._liveMemoryParts())}_logMemoryReport(){let{allocatedBytes:e,peakLiveBytes:t,byPhase:n}=this.memory;if(e===0)return;let r=Object.keys(n).filter(e=>n[e].allocated>0).map(e=>`${e} ${H.mb(n[e].allocated)}`),i=this.memoryPreflight?.estimate?.total;Gc.debug(H.list([`memory: peak live ${H.mb(t)}`,`allocated ${H.mb(e)}`,i?`predicted ${H.mb(i)}`:null,r.join(` · `)]))}async buildBVH(e,{sceneKey:t=null,progressive:n=null}={}){if(this.isProcessing)throw Error(`Already processing a scene. Call dispose() first.`);this.isProcessing=!0,this.processingStage=`init`,this.memory.reset(),this._geometryBytes=0,sn(e=>this.memory.alloc(e));let r=new ec(e.name??``,{namespace:`scene`});try{this._geometryOwner===e&&await Promise.all([this._restoreGeometry(e),this.ensureMovable()]),this._reset(),this._sceneKey=t,this._blasKey=null,this._blasRestored=!1,this._progressive=n?.storage&&n.uploader?n:null;let i=this.geometryExtractor._countStoredTriangles(e);this._streaming=!!this._progressive&&i>Math.floor(67108864/(G.FLOATS_PER_TRIANGLE*4)),this._foldLeaves=i>Rc,this.textureCoordinates=zn(e),this.bvhBuilder.foldLeaves=this._foldLeaves,this._log(`Starting scene processing`),this.memory.mark(`preflight`),this._preflightMemory(e),this.processingStage=`extraction`,this.memory.mark(`extraction`),r.start(`Geometry extraction`),this._streaming?await this._extractStreaming(e):await this._extractGeometry(e),r.end(`Geometry extraction`),this.performanceMetrics.geometryExtractionTime=r.getDuration(`Geometry extraction`),this._geometryBytes=Nn(e),this._sampleMemory(`after extraction`),this.processingStage=`bvh`,r.start(`BVH construction (worker)`),r.start(`Material textures (parallel)`);let a=!1,o=this._buildBVH().then(()=>r.end(`BVH construction (worker)`)),s=this._createMaterialTextures().then(()=>{r.end(`Material textures (parallel)`),a=!0});return await o,z({status:`Building light data...`,progress:77}),r.start(`Emissive extraction + Light BVH`),this._buildEmissiveData(),r.end(`Emissive extraction + Light BVH`),a||z({status:`Processing material textures...`,progress:80}),await s,this.performanceMetrics.bvhBuildTime=r.getDuration(`BVH construction (worker)`),this.performanceMetrics.textureCreationTime=r.getDuration(`Material textures (parallel)`),this.processingStage=`finalize`,r.start(`BVH data packing`),this.bvhRoot&&!this.bvh&&this._setBVHData(this.textureCreator.createBVHRawData(this.bvhRoot)),r.end(`BVH data packing`),this.spheres=this._createSpheres(),this.performanceMetrics.totalProcessingTime=performance.now()-r.totalStart,r.print(),this.processingStage=`complete`,this._streaming&&this._geometrySpill?.bytes>=Vc?this._geometryOwner=e:await this._restoreGeometry(e),z({status:`Scene data ready`,progress:85}),this._blasKey&&!this._blasRestored&&this.performanceMetrics.totalProcessingTime>=this.config.sceneCacheMinBuildMs&&(this._blasStoring=this._storeBLASes(e.name??``).catch(e=>Gc.debug(`storing BLASes failed:`,e))),this}catch(e){throw this.processingStage=`error`,Gc.error(`processing failed:`,e),z({status:`Error: ${e.message}`,failed:!0,progress:100}),e}finally{this._geometryOwner||this._disposeGeometrySpill(),sn(null),this._sampleMemory(`at ${this.processingStage}`),this._logMemoryReport(),this.isProcessing=!1}}async _extractGeometry(e){z({isLoading:!0,title:`Processing`,status:`Extracting geometry...`,progress:15}),await new Promise(e=>setTimeout(e,0)),this._log(`Extracting geometry`);let t=performance.now();try{this._adoptExtraction(this.geometryExtractor.extract(e));let n=performance.now()-t;this._log(`Geometry extraction complete (${n.toFixed(2)}ms)`,{triangleCount:this.triangleCount,materials:this.materials.length}),z({status:`Extracted ${this.triangleCount.toLocaleString()} triangles`,progress:25})}catch(e){throw Gc.error(`geometry extraction failed:`,e),z({status:`Extraction error: ${e.message}`,failed:!0,progress:25}),e}}async _extractStreaming(e){z({isLoading:!0,title:`Processing`,status:`Large scene: building through disk to save memory...`,progress:15}),await new Promise(e=>setTimeout(e,0));let t=performance.now(),n=this.geometryExtractor,{storage:r,uploader:i}=this._progressive,a=`spill:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`,o=n._countStoredTriangles(e),s=fn.lazy(o,G.FLOATS_PER_TRIANGLE,Uint32Array),c=s.recordsPerChunk*s.lanesPerRecord*4,l=await yn.create(r,`${a}:tri`,c,{label:`Triangle records`,expectedBytes:o*c/s.recordsPerChunk}),u=l&&await yn.create(r,`${a}:blas`,0,{label:`BLAS nodes (while building)`});if(!u)return await l?.dispose(),this._streaming=!1,this._extractGeometry(e);let d=await On.create(r,`${a}:geo`,this.memoryPreflight?.geometryBytes??0);this._geometrySpill=d;let f={key:a,triStore:l,blasStore:u,bvhStore:null,blasBytes:0,blasAt:new Map,pending:[],extractedChunks:0,emitterChunks:new Set,isEmitter:e=>n._emissiveMaterial(e),uploadTriangles:null,chain:Promise.resolve(),error:null};this._spillStores=[l],this._blasKey=null;let p=new Map,m=this._blasWorkerOpts(),h=[],g=()=>new Promise(e=>h.push(e)),_=()=>{let e=h;h=[];for(let t of e)t()},v=null,y=(e,t,n)=>{let r=n.bvhData,i=new Float32Array(6);Ga.rootAABB(qc(r)[0],v,t.start,t.count,i,0),p.set(e,{result:n,aabb:i});let a=f.blasBytes;f.blasBytes+=Jc(r),f.blasAt.set(e,a),n.nodeCount=Jc(r)/64,n.bvhData=null,this._queueSpill(f,()=>Xc(u,a,r)),this._forEachChunk(v,t.start,t.count,e=>{--f.pending[e]===0&&e<f.extractedChunks&&this._finishTriangleChunk(f,e)}),_()},b=0,x=this._blasPool(m,()=>b++,(e,t,n)=>y(e,t,n)),S=Promise.resolve(),C=0,w=e=>{let t=e>=v.recordCount?v.chunks.length:Math.floor(e/v.recordsPerChunk);for(let e=f.extractedChunks;e<t;e++)f.pending[e]||this._finishTriangleChunk(f,e);f.extractedChunks=Math.max(f.extractedChunks,t)},T;try{if(T=await n.extractStreaming(e,{onStore:e=>{v=e,this._setTriangleData(e),f.uploadTriangles=i(e,`triangles`,{textureCoordinates:this.textureCoordinates})},onRange:(e,t)=>{this._forEachChunk(v,t.start,t.count,e=>f.pending[e]=(f.pending[e]??0)+1),this._isLargeMesh(t)?(C++,S=S.then(async()=>{y(e,t,await this._buildLargeBLAS(t,m)),C--}),S.catch(e=>{f.error??=e,_()})):x.submit({m:e,range:t})},releaseGeometry:d?e=>d.add(e):null,pause:async e=>{for(w(e),d?.queuedBytes>Wc&&await d.written(),z({status:`Extracted ${e.toLocaleString()} triangles, ${b.toLocaleString()} BVHs built...`,progress:15+Math.floor(20*e/Math.max(1,o))}),await new Promise(e=>setTimeout(e,0));v.byteLength>Bc&&(x.pending>0||C>0)&&!f.error&&!x.error;)await Promise.race([g(),new Promise(e=>setTimeout(e,50))]);if(f.error||x.error)throw f.error??x.error}}),w(1/0),await Promise.all([x.close(),S]),await f.chain,f.error)throw f.error}catch(e){throw x.abort(e),Gc.error(`streamed extraction failed:`,e),z({status:`Extraction error: ${e.message}`,failed:!0,progress:25}),e}this._adoptExtraction(T),this._streamed={state:f,templates:p},this._log(`Geometry extracted and ${p.size} BLASes built together (${(performance.now()-t).toFixed(0)}ms)`)}_adoptExtraction(e){if(this._setTriangleData(e.triangleData),this.geometryExtractor.releaseTriangles(),this.triangleCount=bt(e.triangleCount,`triangle count`),this._foldLeaves&&this.triangleCount>134217728)throw RangeError(`${this.triangleCount.toLocaleString()} triangles is past the ${Pt.toLocaleString()} a folded BVH leaf can address`);this.expandedTriangleCount=e.expandedTriangleCount??e.triangleCount,this.instanceSource=e.instanceSource||null,this.matrixRuns=e.matrixRuns||null,this.instanceCount=e.instanceCount||0,this.instanceGroups=e.instanceGroups??[],this.bakeInverse=e.bakeInverse||null,this._log(`Using Float32Array format: ${this.triangleCount} triangles, ${(this.triangles.byteLength/(1024*1024)).toFixed(2)}MB`),this.materials=e.materials,this.materialTriangleCounts=e.materialTriangleCounts,this.meshes=e.meshes,this.meshTriangleRanges=e.meshTriangleRanges,this._adoptTextureLists(e),this.directionalLights=e.directionalLights,this.cameras=e.cameras}async _buildBVH(){if(z({status:`Building BVH...`,progress:25}),this.triangleCount===0)throw Error(`No triangles to build BVH from`);this._log(`Building two-level BVH (TLAS/BLAS)`),this.memory.mark(`blas`);let e=performance.now();try{let t=this.meshTriangleRanges;if(!t||t.length===0)throw Error(`No mesh triangle ranges available for TLAS/BLAS build`);let n=this.instanceCount>0,r=n?this.instanceCount:t.length,i=this.instanceSource,a=n?this.matrixRuns:null,o=e=>n?i[e]:e;this.instanceTable=new Ga,this.instanceTable.allocate(r,t.length,a,n?i:null),this.instanceTable.tplBakeInverse=this.bakeInverse,this.instanceTable.setGroups(n?this.instanceGroups:null);let s=this._clusterCopies(this.instanceTable);s&&this.instanceTable.planClusters();let c=s?this.instanceTable.clusterCount:this.instanceTable.entryCount,l=oo.nodeCountFor(c)+this.instanceTable.groupNodeCount,u=this._streamed;this._streamed=null;let d=[],f=[],p=[],m=new Int32Array(r).fill(-1),h=new Map;for(let e=0;e<r;e++){let n=t[o(e)];if(!n||n.count===0)continue;let r=h.get(n.start);if(r!==void 0){m[e]=r;continue}h.set(n.start,e),u?p.push({m:e,range:n}):this._isLargeMesh(n)?f.push({m:e,range:n}):d.push({m:e,range:n})}let g=this._blasWorkerOpts(),_=d.length+f.length,v=0,y=()=>{v++,z({status:`Building BLAS ${v}/${_}...`,progress:25+Math.floor(v/_*45)})},b=[...d,...f].map(({m:e,range:t})=>({m:e,range:t,t:o(e),triOffset:t.start,triCount:t.count})).sort((e,t)=>e.t-t.t),x=u?null:await this._restoreBLASes(b,l,g),S=u?u.state:!x&&this._progressive&&this.triangles.chunks.length>1?await this._beginProgressiveSpill(b):null,C=S&&!u?(e,t,n)=>this._onBLASBuilt(S,o(e),t,n):null;if(u)for(let[e,t]of u.templates)this.instanceTable.tplObjectAABB.set(t.aabb,e*6);x&&(d.length=0,f.length=0,z({status:`Restored stored BVHs`,progress:68}));let w=x?Promise.resolve(x.results):u?Promise.resolve(p.map(({m:e,range:t})=>({m:e,range:t,result:u.templates.get(o(e)).result}))):this._buildBLASesWithPool(d,g,y,C),T=[],E=(async()=>{for(let{m:e,range:t}of f){let n=await this._buildLargeBLAS(t,g);C?.(e,t,n),T.push({m:e,range:t,result:n}),y()}})(),[D]=await Promise.all([w,E]);if(S&&(await S.chain,S.error))throw S.error;let O={sah:0,objMed:0,spatMed:0,failed:0};for(let{m:e,range:t,result:r}of[...D,...T]){let i=r.splitStats;i&&(O.sah+=i.sahSplits??0,O.objMed+=i.objectMedianSplits??0,O.spatMed+=i.spatialMedianSplits??0,O.failed+=i.failedSplits??0,this.performanceMetrics.blasWorkerTime+=i.totalBuildTime??0),this.instanceTable.setEntry({meshIndex:e,blasNodeCount:r.nodeCount??Jc(r.bvhData)/64,triOffset:t.start,triCount:t.count,originalToBvhMap:r.originalToBvh||null,bvhData:r.bvhData,matrixWorld:n?Ra:this.meshes?.[e]?.matrixWorld?.elements??null,expandedStart:t.expandedStart,sourceMesh:o(e)})}for(let e=0;e<r;e++){let r=m[e];r<0||this.instanceTable.setAlias(e,r,n?Ra:this.meshes?.[e]?.matrixWorld?.elements??null,t[o(e)].expandedStart,o(e))}z({status:`Built all BLASes`,progress:70}),this.performanceMetrics.blasBuildTime=performance.now()-e,z({status:`Building TLAS...`,progress:72}),this._sampleMemory(`BLASes built`),this.memory.mark(`tlas`);let k=performance.now(),A=this.instanceTable;this.instanceTable.computeAABBs(this.triangles,{owners:!S}),this.instanceTable.computeGroupAABBs(),s&&(A.clusterWorld=new Float32Array(A.entryCount*6),A.writeEntryWorldAABBs(A.clusterWorld),A.clusterBounds=A.formClusters(A.clusterWorld)),this.instanceTable.assignOffsets(oo.nodeCountFor(c));let j=this.instanceTable.totalNodeCount,M=await this._buildTLAS(A);if(this._streaming&&s){let e=A.clusterWorld;this._spillMeshBounds=this._instancedMeshBounds((t,n)=>{for(let r=0;r<6;r++)n[r]=e[t*6+r]})}A.clusterWorld=null,A.clusterBounds=null,this.performanceMetrics.tlasBuildTime=performance.now()-k,this.memory.mark(`assemble`);let N=performance.now();S||this._checkAssemblyHeadroom(j),this._setBVHData(fn.lazy(j,16,Float32Array,void 0,un));let P=S?await this._beginBVHSpill(S,A.blasBase):null;this.bvh.setRecords(0,M),A.groupNodeCount&&this.bvh.setRecords(A.groupNodeStart,A.groupNodeBlock()),M=null,this.tlasBuilder.releaseFlattenBuffer();let F=Math.max(1,Math.ceil(A.templateCount/32));if(x){try{let e=performance.now();await lc(x.nodes,this.bvh,A.blasBase,A.totalBLASNodes),this.performanceMetrics.blasRestore.readMs=performance.now()-e}finally{x.release()}A.blasData.clear()}else{for(let e=0;e<A.templateCount;e++){let t=S?await this._readSpilledBLAS(S,e):A.blasData.get(e);if(!t)continue;let n=A.tplBlasOffset[e],r=n;for(let e of qc(t))this.bvh.setRecords(r,e),r+=e.length/16;this._offsetBLASInPlace(n,r-n,n,A.tplTriOffset[e]),A.blasData.delete(e),await P?.(r),e%F===0&&this._sampleMemory(`assembling ${e}/${A.templateCount}`)}s&&await this._writeCopyRecords(P),await P?.(j,!0),S&&await S.blasStore.dispose()}if(s&&x&&await this._writeCopyRecords(null),this._setBVHData(this.bvh.materializeAll()),x)for(let[e,t]of x.orders)A.bvhToOriginal.set(e,t);else this._buildBvhToOriginalMaps();this.performanceMetrics.bvhAssembleTime=performance.now()-N,A.originalToBvhMap.clear(),A.blasData.clear(),this.bvhRoot=!0,this._disposeRefitWorker();let I=performance.now()-e;Gc.debug(H.list([`${H.n(A.setCount)} BLASes + TLAS`,`${H.n(this.bvh.recordCount)} nodes`,`SAH ${H.n(O.sah)} · objMed ${O.objMed} · spatMed ${O.spatMed} · failed ${O.failed}`,H.ms(I)])),z({status:`BVH construction complete`,progress:75})}catch(e){throw Gc.error(`BVH build failed:`,e),z({status:`BVH error: ${e.message}`,failed:!0,progress:75}),e}}_blasWorkerOpts(){return{depth:this.config.bvhDepth,reinsertionOptimization:{enabled:this.bvhBuilder.enableReinsertionOptimization,batchSizeRatio:this.bvhBuilder.reinsertionBatchSizeRatio,maxIterations:this.bvhBuilder.reinsertionMaxIterations},maxLeafSize:this.bvhBuilder.maxLeafSize,foldLeaves:this._foldLeaves===!0,numBins:this.bvhBuilder.numBins,maxBins:this.bvhBuilder.maxBins,minBins:this.bvhBuilder.minBins,logLevel:B()}}_isLargeMesh(e){return e.count>=Fc&&Ia(e.count)}async _buildLargeBLAS(e,t){if(e.count>Ic)return this._buildSplitBLAS(e,t);let n=new Uint32Array(new SharedArrayBuffer(e.count*this.triangles.lanesPerRecord*4));this.triangles.readRecords(e.start,e.count,n),this.triangles.release(e.start,e.count);let r=await Na(n,this.config.bvhDepth,null,t);return r.reorderedTriangles?(this.triangles.setRecords(e.start,r.reorderedTriangles),delete r.reorderedTriangles):r.order&&(this._writeInOrder(e.start,r.triangles,r.order),delete r.order,delete r.triangles),r}async _buildSplitBLAS(e,t){let n=this.triangles,{order:r,pieces:i,tree:a}=await hc(n,e.start,e.count,Lc,{pause:()=>new Promise(e=>setTimeout(e,0))}),o=this._blasPool(t,null,null,Math.min(Dr(),8));i.forEach((t,n)=>o.submit({m:n,range:{start:e.start+t.start,count:t.count}}));let s=[],c={};for(let{m:e,range:t,result:r}of await o.close()){r.aabb=new Float32Array(6),Ga.rootAABB(r.bvhData,n,t.start,t.count,r.aabb,0),s[e]=r;for(let[e,t]of Object.entries(r.splitStats??{}))typeof t==`number`&&(c[e]=(c[e]??0)+t)}return{...yc(a,i,s,r),splitStats:c}}_blasCacheKey(e){let t={...e};delete t.logLevel;let n=typeof navigator<`u`?navigator.hardwareConcurrency:0;return`blas:2:${Sc}:${JSON.stringify(t)}:${n}:${this._sceneKey}`}async _restoreBLASes(e,t,n){if(!this._sceneKey||this.config.sceneCache===!1)return null;let r=ti(oi().cacheNamespace);if(!r)return null;this._blasKey=this._blasCacheKey(n);let i=await sc(r,this._blasKey);if(!i)return null;let a=e=>(Gc.debug(`stored BLASes not used: ${e}`),i.release(),null),{index:o}=i;if(o.tlasNodeCount!==t||o.templates.length!==e.length)return a(`layout changed`);let s=t;for(let t=0;t<e.length;t++){let[n,r,i,c,l]=o.templates[t],u=e[t];if(u.t!==n||u.triOffset!==r||u.triCount!==i||l!==s)return a(`layout changed`);s+=c}if(s!==o.totalNodes)return a(`layout changed`);let c=performance.now(),l=await oc(this.triangles,e);for(let t=0;t<e.length;t++)if(l[t]!==o.templates[t][6])return a(`triangles changed`);let u=performance.now();try{let t=new Map,n=[];for(let r=0;r<e.length;r++){let[a,s,c,l,,u,,d]=o.templates[r],f=await uc(i.order,u,c);this._permuteRange(s,c,f),t.set(a,f),n.push({m:e[r].m,range:e[r].range,result:{bvhData:new Float32Array(Uint32Array.from(d).buffer),originalToBvh:null,nodeCount:l}})}return this._blasRestored=!0,this.performanceMetrics.blasRestore={checksumMs:u-c,permuteMs:performance.now()-u},Gc.debug(`restored ${H.n(e.length)} stored BLASes`),{results:n,orders:t,nodes:i.nodes,release:i.release}}catch(e){throw i.release(),e}}_writeInOrder(e,t,n){let r=this.triangles,i=r.lanesPerRecord;for(let a=0,o=n.length;a<o;){let s=r.chunkFor(e+a),c=Math.min(o,(((e+a)/r.recordsPerChunk|0)+1)*r.recordsPerChunk-e);for(let o=r.baseOf(e+a);a<c;a++,o+=i){let e=n[a]*i;for(let n=0;n<i;n++)s[o+n]=t[e+n]}}}_permuteRange(e,t,n){let r=!0;for(let e=0;e<t&&r;e++)r=n[e]===e;if(r)return;let i=this.triangles.lanesPerRecord,a=this.triangles.slice(e,t),o=new a.constructor(a.length);if(i===20)for(let e=0,r=0;e<t;e++,r+=20){let t=n[e]*20;o[r]=a[t],o[r+1]=a[t+1],o[r+2]=a[t+2],o[r+3]=a[t+3],o[r+4]=a[t+4],o[r+5]=a[t+5],o[r+6]=a[t+6],o[r+7]=a[t+7],o[r+8]=a[t+8],o[r+9]=a[t+9],o[r+10]=a[t+10],o[r+11]=a[t+11],o[r+12]=a[t+12],o[r+13]=a[t+13],o[r+14]=a[t+14],o[r+15]=a[t+15],o[r+16]=a[t+16],o[r+17]=a[t+17],o[r+18]=a[t+18],o[r+19]=a[t+19]}else for(let e=0;e<t;e++){let t=n[e]*i,r=e*i;for(let e=0;e<i;e++)o[r+e]=a[t+e]}this.triangles.setRecords(e,o)}async _storeBLASes(e){let t=ti(oi().cacheNamespace),n=this.instanceTable;if(!t||!n||!this.bvh)return!1;let r=this._blasKey,i=this._geometryVersion,a=()=>this._geometryVersion!==i||this._blasKey!==r,o=[];for(let e=0;e<n.templateCount;e++){let t=n.tplOwner[e];t<0||n.sourceMesh[t]!==e||o.push({t:e,triOffset:n.tplTriOffset[e],triCount:n.tplTriCount[e],nodeCount:n.tplNodeCount[e],blasOffset:n.tplBlasOffset[e]})}let s=await oc(this.triangles,o);if(a())return!1;let c=e=>{let t=this.bvhIndexChunks.chunkFor(e),n=this.bvhIndexChunks.baseOf(e);return Array.from(t.subarray(n,n+16))},l=0,u=[],d=o.map((e,t)=>{u.push(n.bvhToOriginal.get(e.t)??Uint32Array.from({length:e.triCount},(e,t)=>t));let r=[e.t,e.triOffset,e.triCount,e.nodeCount,e.blasOffset,l,s[t],c(e.blasOffset)];return l+=e.triCount,r}),f=await cc(t,r,{index:{v:2,tlasNodeCount:n.blasBase,totalNodes:n.treeNodeCount,templates:d},bvh:this.bvh,orders:u,isStale:a,label:e});return f&&Gc.debug(`stored ${H.n(o.length)} BLASes for the next load`),f}async _beginProgressiveSpill(e){let{storage:t,uploader:n}=this._progressive,r=this.triangles,i=`spill:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`,a=r.recordsPerChunk*r.lanesPerRecord*r.LaneType.BYTES_PER_ELEMENT,o=await yn.create(t,`${i}:tri`,a,{label:`Triangle records`,expectedBytes:r.byteLength}),s=o&&await yn.create(t,`${i}:blas`,0,{label:`BLAS nodes (while building)`});if(!s)return await o?.dispose(),null;let c={key:i,triStore:o,blasStore:s,bvhStore:null,blasBytes:0,blasAt:new Map,pending:new Int32Array(r.chunks.length),emitterChunks:new Set,isEmitter:e=>{let t=this.materials[e];return(t?.emissiveIntensity??0)>0&&!!t.emissive&&(t.emissive.r>0||t.emissive.g>0||t.emissive.b>0)},uploadTriangles:n(r,`triangles`,{textureCoordinates:this.textureCoordinates}),chain:Promise.resolve(),error:null};this._spillStores=[o],this._blasKey=null;for(let{triOffset:t,triCount:n}of e)this._forEachChunk(r,t,n,e=>c.pending[e]++);for(let e=0;e<r.chunks.length;e++)c.pending[e]===0&&this._finishTriangleChunk(c,e);return c}_forEachChunk(e,t,n,r){if(n<=0)return;let i=(t+n-1)/e.recordsPerChunk|0;for(let n=t/e.recordsPerChunk|0;n<=i;n++)r(n)}_onBLASBuilt(e,t,n,r){let i=this.instanceTable,a=r.bvhData;i.tplTriOffset[t]=n.start,i.tplTriCount[t]=n.count,i._readRootAABB(qc(a)[0],t,this.triangles,i.tplObjectAABB,t*6);let o=e.blasBytes;e.blasBytes+=Jc(a),e.blasAt.set(t,o),r.nodeCount=Jc(a)/64,r.bvhData=null,this._queueSpill(e,()=>Xc(e.blasStore,o,a)),this._forEachChunk(this.triangles,n.start,n.count,t=>{--e.pending[t]===0&&this._finishTriangleChunk(e,t)})}_queueSpill(e,t){e.chain=e.chain.then(t).catch(t=>{e.error??=t})}_finishTriangleChunk(e,t){this._queueSpill(e,async()=>{let n=this.triangles,r=n.chunks[t];if(!r)return;await e.uploadTriangles(t);let i=n.lanesPerRecord;for(let n=G.MATERIAL_FLAGS_OFFSET;n<r.length;n+=i)if(e.isEmitter(r[n]&16777215)){e.emitterChunks.add(t);return}await n.spillChunk(t,e.triStore)})}async _readSpilledBLAS(e,t){let n=e.blasAt.get(t);if(n===void 0)return null;let r=this.instanceTable.tplNodeCount[t]*64,i=[];for(let t=0;t<r;t+=Yc)i.push(new Float32Array(await e.blasStore.readAt(n+t,Math.min(Yc,r-t))));return i}async _beginBVHSpill(e,t){let{storage:n,uploader:r}=this._progressive,i=this.bvh,a=i.recordsPerChunk*i.lanesPerRecord*i.LaneType.BYTES_PER_ELEMENT,o=await yn.create(n,`${e.key}:bvh`,a,{label:`BLAS nodes`,expectedBytes:i.recordCount*64}),s=r(i),c=Math.ceil(t/i.recordsPerChunk);o&&this._spillStores.push(o),this._bvhSpillStore=o;let l=c;return async(e,t=!1)=>{for(;l<i.chunks.length&&(t||(l+1)*i.recordsPerChunk<=e);)i.chunks[l]||i._materialize(l),await s(l),o&&await i.spillChunk(l,o),l++;if(t)for(let e=0;e<Math.min(c,i.chunks.length);e++)i.chunks[e]||i._materialize(e),await s(e)}}_offsetBLASInPlace(e,t,n,r){let i=this.bvhIndexChunks;for(let a=e,o=e+t;a<o;){let e=i.chunkFor(a),t=Math.min(o,((a/i.recordsPerChunk|0)+1)*i.recordsPerChunk),s=i.baseOf(a);Hi(e,n,r,s,s+(t-a)*16),a=t}}_buildBLASesWithPool(e,t,n,r=null){let i=this._blasPool(t,n,r);for(let t of e)i.submit(t);return i.close()}_blasPool(e,t,n=null,r=this.config.maxConcurrentTextureTasks||4){let i=[],a=[],o=[],s=[],c=!1,l=0,u=0,d=null,f,p=new Promise((e,t)=>f={resolve:e,reject:t});p.catch(()=>{});let m=e=>{d||(d=e,o.forEach(e=>e.terminate()),f.reject(e))},h=()=>{d||!c||i.length>0||l>0||(o.forEach(e=>e.terminate()),f.resolve(a))},g=t=>{let n=i.shift();if(!n){s.push(t),h();return}let{m:r,range:a}=n;l++;try{let n=this.triangles.copyOf(a.start,a.count),i=a.count;t._currentTask={m:r,range:a},t.postMessage({triangleData:n.buffer,triangleByteOffset:n.byteOffset,triangleByteLength:n.byteLength,triangleCount:i,depth:e.depth,reportProgress:!1,sharedReorderBuffer:null,reinsertionOptimization:e.reinsertionOptimization,maxLeafSize:e.maxLeafSize,foldLeaves:e.foldLeaves,numBins:e.numBins,maxBins:e.maxBins,minBins:e.minBins,logLevel:e.logLevel},[n.buffer])}catch(e){m(e)}},_=(e,r)=>{let i=r.data;if(i.error){m(Error(i.error));return}if(i.progress!==void 0)return;let{m:o,range:s}=e._currentTask;l--;try{i.triangles&&this.triangles.setRecords(s.start,i.triangles);let e={bvhData:i.bvhData,originalToBvh:i.originalToBvh||null,splitStats:i.splitStats||null};n?.(o,s,e),a.push({m:o,range:s,result:e})}catch(e){m(e);return}u++,t?.(u),g(e)},v=()=>{let e=jr(Ta);return e.onmessage=t=>_(e,t),e.onerror=e=>m(e),o.push(e),e};return{submit(e){if(!d){i.push(e);try{let e=s.pop()??(o.length<r?v():null);e&&g(e)}catch(e){m(e)}}},close(){return c=!0,h(),p},abort(e){m(e??Error(`BLAS pool aborted`))},get pending(){return i.length+l},get error(){return d}}}_buildBvhToOriginalMaps(){let e=this.instanceTable;for(let t=0;t<e.count;t++){if(!e.isSet[t]||!e.isOwner(t))continue;let n=e.sourceMesh[t],r=e.tplTriCount[n],i=e.originalToBvhMap.get(n),a=new Uint32Array(r);if(i)for(let e=0;e<r;e++)a[i[e]]=e;else for(let e=0;e<r;e++)a[e]=e;e.bvhToOriginal.set(n,a),e.originalToBvhMap.delete(n)}}async _createMaterialTextures(){this._log(`Creating material textures (parallel with BVH)`);try{let{srgbLists:e,linearLists:t,remap:n}=this._bucketTextures();this._remapMaterialTextureIndices(n),this.materials?.length&&(this.materialData=this.textureCreator.createMaterialRawData(this.materials));let i=(e,t)=>e.length===0?Promise.resolve(null):this.textureCreator.createTexturesToDataTexture(e,{srgbPool:t}).then(e=>(e&&t&&(e.colorSpace=r.SRGBColorSpace),e)),[a,o]=await Promise.all([Promise.all(e.map(e=>i(e,!0))),Promise.all(t.map(e=>i(e,!1)))]);this.srgbBucketTextures=a,this.linearBucketTextures=o,this._log(`Material textures complete`,{materialData:!!this.materialData,srgbBuckets:a.map(e=>e?`${e.image.width}x${e.image.height}x${e.image.depth}`:`-`).join(`,`),linearBuckets:o.map(e=>e?`${e.image.width}x${e.image.height}x${e.image.depth}`:`-`).join(`,`)})}catch(e){throw Gc.error(`texture creation failed:`,e),e}}_bucketTextures(){let e=this.config.maxTextureSize,t=$t.MATERIAL_BUCKET_COUNT,n=$t.BUCKET_LAYER_STRIDE,r=e=>{let t=new Set,n=[];for(let r of e)for(let e of r||[]){if(!e?.image)continue;let r=e.source?.uuid??e.uuid;t.has(r)||(t.add(r),n.push({width:e.image.width,height:e.image.height}))}return n},i=[this.maps,this.emissiveMaps,this.sheenColorMaps,this.specularColorMaps,this.diffuseTransmissionColorMaps],a=[this.normalMaps,this.bumpMaps,this.roughnessMaps,this.metalnessMaps,this.displacementMaps,this.anisotropyMaps,this.transmissionMaps,this.clearcoatMaps,this.clearcoatRoughnessMaps,this.sheenRoughnessMaps,this.iridescenceMaps,this.iridescenceThicknessMaps,this.specularIntensityMaps,this.diffuseTransmissionMaps],o=Xt(r(i),e,t),s=Xt(r(a),e,t);this._srgbBucketShapes=o,this._linearBucketShapes=s;let c=Array.from({length:t},()=>[]),l=Array.from({length:t},()=>[]),u=Array.from({length:t},()=>new Map),d=Array.from({length:t},()=>new Map);this._srgbTexPacked=new Map,this._linearTexPacked=new Map;let f=!1,p=!1,m=(e,t,r,i,a)=>{if(!e)return-1;if(!e.image)return p||this.config.issues?.record(Y.TEXTURE_BUILD_FAILED,`a material map had not finished decoding when the scene was packed; it renders untextured`,{texture:e.name||e.source?.uuid||e.uuid}),p=!0,-1;let o=Zt(e.image.width,e.image.height,a),s=e.source?.uuid??e.uuid,c=r[o].get(s);if(c!==void 0)return Qt(o,c);if(t[o].length>=n)return Gc.warn(`texture bucket ${o} full (${n}); dropping a map`),f||this.config.issues?.record(Y.TEXTURE_LIMIT_EXCEEDED,`texture bucket ${o} full (${n} layers); the rest render untextured`,{bucket:o,limit:n}),f=!0,-1;t[o].push(e);let l=t[o].length-1;r[o].set(s,l);let u=Qt(o,l);return i.set(s,u),u},h=(e,t,n,r,i)=>(e||[]).map(e=>m(e,t,n,r,i));return{srgbLists:c,linearLists:l,remap:{albedo:h(this.maps,c,u,this._srgbTexPacked,o),emissive:h(this.emissiveMaps,c,u,this._srgbTexPacked,o),normal:h(this.normalMaps,l,d,this._linearTexPacked,s),bump:h(this.bumpMaps,l,d,this._linearTexPacked,s),roughness:h(this.roughnessMaps,l,d,this._linearTexPacked,s),metalness:h(this.metalnessMaps,l,d,this._linearTexPacked,s),displacement:h(this.displacementMaps,l,d,this._linearTexPacked,s),anisotropy:h(this.anisotropyMaps,l,d,this._linearTexPacked,s),transmission:h(this.transmissionMaps,l,d,this._linearTexPacked,s),clearcoat:h(this.clearcoatMaps,l,d,this._linearTexPacked,s),clearcoatRoughness:h(this.clearcoatRoughnessMaps,l,d,this._linearTexPacked,s),sheenColor:h(this.sheenColorMaps,c,u,this._srgbTexPacked,o),sheenRoughness:h(this.sheenRoughnessMaps,l,d,this._linearTexPacked,s),iridescence:h(this.iridescenceMaps,l,d,this._linearTexPacked,s),iridescenceThickness:h(this.iridescenceThicknessMaps,l,d,this._linearTexPacked,s),specularIntensity:h(this.specularIntensityMaps,l,d,this._linearTexPacked,s),specularColor:h(this.specularColorMaps,c,u,this._srgbTexPacked,o),diffuseTransmission:h(this.diffuseTransmissionMaps,l,d,this._linearTexPacked,s),diffuseTransmissionColor:h(this.diffuseTransmissionColorMaps,c,u,this._srgbTexPacked,o)}}}_remapMaterialTextureIndices(e){let t=(e,t)=>e>=0&&e<t.length?t[e]:-1;for(let n of this.materials)n.map=t(n.map,e.albedo),n.emissiveMap=t(n.emissiveMap,e.emissive),n.normalMap=t(n.normalMap,e.normal),n.bumpMap=t(n.bumpMap,e.bump),n.roughnessMap=t(n.roughnessMap,e.roughness),n.metalnessMap=t(n.metalnessMap,e.metalness),n.displacementMap=t(n.displacementMap,e.displacement),n.anisotropyMap=t(n.anisotropyMap,e.anisotropy),n.transmissionMap=t(n.transmissionMap,e.transmission),n.clearcoatMap=t(n.clearcoatMap,e.clearcoat),n.clearcoatRoughnessMap=t(n.clearcoatRoughnessMap,e.clearcoatRoughness),n.sheenColorMap=t(n.sheenColorMap,e.sheenColor),n.sheenRoughnessMap=t(n.sheenRoughnessMap,e.sheenRoughness),n.iridescenceMap=t(n.iridescenceMap,e.iridescence),n.iridescenceThicknessMap=t(n.iridescenceThicknessMap,e.iridescenceThickness),n.specularIntensityMap=t(n.specularIntensityMap,e.specularIntensity),n.specularColorMap=t(n.specularColorMap,e.specularColor),n.diffuseTransmissionMap=t(n.diffuseTransmissionMap,e.diffuseTransmission),n.diffuseTransmissionColorMap=t(n.diffuseTransmissionColorMap,e.diffuseTransmissionColor)}_buildEmissiveData(){this.emissiveTriangleCount=this.emissiveTriangleBuilder.extractEmissiveTriangles(this.triangles,this.materials,this.triangleCount,this.instanceTable??null),this.emissiveTriangleData=this.emissiveTriangleBuilder.createEmissiveRawData(),this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower,this._log(`Emissive triangle extraction complete`,this.emissiveTriangleBuilder.getStats()),this.emissiveTriangleBuilder.buildLightBVH(),this.lightBVHNodeData=this.emissiveTriangleBuilder.lightBVHNodeData,this.lightBVHNodeCount=this.emissiveTriangleBuilder.lightBVHNodeCount,this.emissiveTriangleData=this.emissiveTriangleBuilder.emissiveTriangleData||this.emissiveTriangleData,this.emissiveBitTrailMap=this.emissiveTriangleBuilder.emissiveBitTrailMap,this.emissiveTriangleCount=this.emissiveTriangleBuilder.emissiveCount,this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower}_createSpheres(){return[]}_reset(){this._geometryVersion=(this._geometryVersion??0)+1,this._disposeSpill(),this._disposeGeometrySpill(),this._disposeMatrixSpill(),this._orderSpill?.store.dispose().catch(()=>{}),this._orderSpill=null,this._spilledAfterLoad=!1,this._disposeTextures(),this.triangles=[],this._setTriangleData(null),this.triangleCount=0,this.materials=[],this.meshTriangleRanges=null,this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.roughnessMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.displacementMaps=[],this.anisotropyMaps=[],this.transmissionMaps=[],this.clearcoatMaps=[],this.clearcoatRoughnessMaps=[],this.sheenColorMaps=[],this.sheenRoughnessMaps=[],this.iridescenceMaps=[],this.iridescenceThicknessMaps=[],this.specularIntensityMaps=[],this.specularColorMaps=[],this.diffuseTransmissionMaps=[],this.diffuseTransmissionColorMaps=[],this.directionalLights=[],this.cameras=[],this.spheres=[],this.bvhRoot=null,this.bvh=null,this.bvhData=null,this.bvhIndexChunks=null,this.bvhIndex=null,this.instanceTable=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this.performanceMetrics={textureCreationTime:0,geometryExtractionTime:0,bvhBuildTime:0,blasBuildTime:0,blasWorkerTime:0,tlasBuildTime:0,bvhAssembleTime:0,totalProcessingTime:0}}_disposeTextures(){this._disposeBucketTextures()}_disposeBucketTextures(){for(let e of[`srgbBucketTextures`,`linearBucketTextures`]){let t=this[e];if(t){for(let n of t)if(n&&typeof n.dispose==`function`)try{n.dispose()}catch(t){Gc.warn(`error disposing ${e}:`,t)}this[e]=null}}}async rebuildMaterials(e){if(this.isProcessing)throw Error(`Already processing. Cannot rebuild materials during processing.`);this._log(`Rebuilding materials and textures`);let t=performance.now();try{this.isProcessing=!0;let n=this.geometryExtractor.extractMaterialsOnly(e);this._disposeMaterialTextures(),this.materials=n.materials,this.meshes=n.meshes,this._adoptTextureLists(n),await this._createMaterialTextures();let r=performance.now()-t;return this._log(`Material rebuild complete (${r.toFixed(2)}ms)`,{materials:this.materials.length,textures:this.maps.length}),this}catch(e){throw Gc.error(`material rebuild failed:`,e),e}finally{this.isProcessing=!1}}_adoptTextureLists(e){for(let t of Kc)this[t]=e[t]??[]}_disposeMaterialTextures(){this._disposeBucketTextures(),this.textureCreator&&this.textureCreator.textureCache&&(this.textureCreator.textureCache.dispose(),this.textureCreator.textureCache=new this.textureCreator.textureCache.constructor)}getStatistics(){let e={triangleCount:this.triangleCount,materialCount:this.materials.length,textureCount:this.maps.length,lightCount:this.directionalLights.length,cameraCount:this.cameras.length,processingComplete:this.processingStage===`complete`,hasBVH:!!this.bvhRoot,hasTextures:!!this.materialData&&!!this.bvh,useFloat32Array:this.config.useFloat32Array,triangleDataSize:this.triangles?(this.triangles.byteLength/(1024*1024)).toFixed(2)+`MB`:`0MB`};return this.performanceMetrics.totalProcessingTime>0&&(e.performance={totalTime:this.performanceMetrics.totalProcessingTime,textureTime:this.performanceMetrics.textureCreationTime,bvhTime:this.performanceMetrics.bvhBuildTime,extractionTime:this.performanceMetrics.geometryExtractionTime,texturePercentage:(this.performanceMetrics.textureCreationTime/this.performanceMetrics.totalProcessingTime*100).toFixed(1)+`%`}),this.textureCreator&&this.textureCreator.capabilities&&(e.textureCapabilities=this.textureCreator.capabilities),e}updateConfig(e){Object.assign(this.config,e),this.bvhBuilder&&(this.bvhBuilder.maxLeafSize=this.config.maxLeafSize),this._log(`Configuration updated`,this.config)}_adoptSharedChunks(e,t){let n=this[e];if(n.shared)return;let r=n.chunks.map(e=>{let n=new t(new SharedArrayBuffer(e.byteLength));return n.set(e),n}),i=fn.adopt(r,n.recordCount,n.lanesPerRecord,n.recordsPerChunk);e===`bvh`?this._setBVHData(i):this._setTriangleData(i)}_meshSource(e,t){if(e==null)return null;let n=this.instanceTable;if(typeof e==`function`)return r=>{let i=n.sourceMesh[r],a=e(i,n.triCountOf(r)),o=n.triCountOf(r)*9;if(a&&a.length!==o)throw Error(`SceneProcessor: ${t}s for mesh ${i} must be ${o} floats (${n.triCountOf(r)} triangles × 9), got ${a.length}.`);return a??null};let r=(this.expandedTriangleCount??this.triangleCount)*9;if(e.length!==r)throw Error(`SceneProcessor: expected ${r} ${t} floats (${r/9} triangles × 9, full scene), got ${e.length}. Pass a per-mesh callback instead to avoid building one array for the whole scene.`);return t=>{let r=n.expandedStartOf(t)*9;return e.subarray(r,r+n.triCountOf(t)*9)}}async refitBVH(e,t){if(this._geometryVersion=(this._geometryVersion??0)+1,!this.bvh||!this.triangles||!this.instanceTable)throw Error(`No BVH data available for refit. Run buildBVH() first.`);let n=this._meshSource(e,`position`),r=this._meshSource(t,`normal`);if(!n)throw Error(`SceneProcessor.refitBVH: positions are required.`);if(this._refitWorker||=jr(Ac),!this._refitSharedBuffers){this._adoptSharedChunks(`bvh`,Float32Array),this._adoptSharedChunks(`triangles`,Uint32Array);let e=this.bvh.chunks.map(e=>e.buffer),t=this.triangles.chunks.map(e=>e.buffer);this._refitSharedBuffers={bvhBufs:e,triBufs:t},this._refitWorker.postMessage({type:`init`,sharedBvhBufs:e,bvhRecordCount:this.bvh.recordCount,bvhRecordsPerChunk:this.bvh.recordsPerChunk,sharedTriBufs:t,triRecordCount:this.triangles.recordCount,triLanesPerRecord:this.triangles.lanesPerRecord,triRecordsPerChunk:this.triangles.recordsPerChunk})}let i=this.instanceTable,a=G.FLOATS_PER_TRIANGLE,o=[],s=[],c=[],l=0;for(let e=0;e<i.count;e++){if(!i.isSet[e]||!i.isOwner(e))continue;l++;let t=n(e);if(!t)continue;if(this._updateMeshTrianglePositions(e,t),s.push(i.blasOffsetOf(e),i.blasNodeCountOf(e)),c.push(e),r){let t=r(e);t&&this._patchMeshSmoothNormals(e,t)}let u=i.triOffsetOf(e)*a,d=i.triCountOf(e)*a,f=o.at(-1);f&&f.offset+f.count===u?f.count+=d:o.push({offset:u,count:d})}let u=i.tlasNodeCount,d=u>0&&s.length/2<l,f=d?[this.computeTLASDirtyRange()]:null;for(let e=0;d&&e<s.length;e+=2)f.push({offset:s[e]*16,count:s[e+1]*16});return new Promise((e,t)=>{this._refitWorker.onmessage=n=>{let r=n.data;if(r.type===`refitComplete`){for(let e of c)i.recomputeAABB(e,this.bvh,this.triangles);i.computeGroupAABBs();let t=this._hiddenGroupLeaves();t.length&&this._refitTLAS(t),e({refitTimeMs:r.refitTimeMs,triRanges:o,bvhRanges:f})}else r.type===`error`&&t(Error(r.error))},this._refitWorker.postMessage({type:`refit`,blasRanges:d?s:null,tlasNodeCount:u,groupRange:i.groupNodeCount?[i.groupNodeStart,i.groupNodeCount]:null,treeNodeCount:i.treeNodeCount,recordNodeStart:i.clusterCount?i.recordNodeStart:-1})})}_patchSmoothNormals(e){let t=this.instanceTable;if(t)for(let n=0;n<t.count;n++){if(!t.isSet[n]||!t.isOwner(n))continue;let r=e(n);r&&this._patchMeshSmoothNormals(n,r)}}_placementOf(e){return this.instanceTable?.placementRunOf(e)?.start??-1}refitBLASes(e,t,n){if(this._geometryVersion=(this._geometryVersion??0)+1,!this.instanceTable||!this.bvh||!this.triangles)throw Error(`No TLAS/BLAS data available. Run buildBVH() first.`);let r=this._meshSource(t,`position`),i=this._meshSource(n,`normal`);if(!r)throw Error(`SceneProcessor.refitBLASes: positions are required.`);let a=performance.now();this._blasRefitter||=new Sa;let o=this.instanceTable;for(let t of e){let e=this._placementOf(t);if(e<0||!o.isSet[e])continue;if(!o.isOwner(e)){let n=o.tplOwner[o.sourceMesh[e]];this.config.issues?.record(Y.REFIT_SHARED_GEOMETRY,`mesh ${t} shares its triangles with another placement; deforming it would move every copy, so it was skipped`,{meshIndex:t,owner:o.sourceMesh[n]??n});continue}let n=r(e);if(n){if(this._updateMeshTrianglePositions(e,n),i){let t=i(e);t&&this._patchMeshSmoothNormals(e,t)}this._blasRefitter.refitRange(this.bvh,this.triangles,o.blasOffsetOf(e),o.blasNodeCountOf(e)),this.instanceTable.recomputeAABB(e,this.bvh,this.triangles)}}return this._writeGroupNodes(),this._refitTLAS(),{refitTimeMs:performance.now()-a}}updateMeshTransforms(e){if(!this.instanceTable||!this.bvh)throw Error(`No TLAS/BLAS data available. Run buildBVH() first.`);let t=performance.now(),n=this.instanceTable,r=this._transformScratch??=new Float32Array(16),i=[];for(let t of this._withGroupSiblings(e)){let e=this.meshes?.[t],a=n.placementRunOf(t);if(!e||!a)continue;e.updateMatrixWorld(!0);let o=e.matrixWorld.elements,s=e.isInstancedMesh?e.instanceMatrix?.array??null:null,c=n.tplBakeInverse?.get(n.sourceMesh[a.start])??null;for(let e=0;e<a.count;e++){let t=a.start+e;if(!n.isSet[t])continue;s?(Va(o,s,e*16,r),n.setPlacementMatrix(t,r)):c?(Va(o,c,0,r),n.setPlacementMatrix(t,r)):n.setPlacementMatrix(t,o),this._writeLeafMatrix(t);let l=n.leafOfPlacement(t);l>=0&&i.push(l)}}return this._refitTLAS(i),{refitTimeMs:performance.now()-t,placements:i.length}}_hiddenGroupLeaves(){let e=this.instanceTable,t=[];for(let n of e.groups)if(!n.members.every((t,r)=>e.visible[n.starts[r]]))for(let r=0;r<n.count;r++)t.push(e.leafOfPlacement(n.starts[0]+r));return t}_withGroupSiblings(e){let t=this.instanceTable;if(!t.groups.length)return e;let n=new Set(e),i=new Set,a=this._parentInverse??=new r.Matrix4;for(let r of e){let e=t.groupOfTemplate[r]??-1;if(e<0||i.has(e))continue;i.add(e);let o=this.meshes?.[r];if(o){o.updateMatrixWorld(!0);for(let r of t.groups[e].members){n.add(r);let e=this.meshes[r];!e||e===o||(e.parent&&e.parent.updateMatrixWorld(!0),e.matrix.copy(o.matrixWorld),e.parent&&e.matrix.premultiply(a.copy(e.parent.matrixWorld).invert()),e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0))}}}return n}_writeLeafMatrix(e){let t=this.instanceTable,n=t.tlasLeafIndex[e];if(!(n<0)){if(t.clusterCount){this._writeCopyRecord(n,t.repOf(t.entryOf(e)));return}oo.writeLeafMatrix(this.bvh.chunkFor(n),this.bvhIndexChunks.chunkFor(n),this.bvh.baseOf(n),t,e,t.entryOf(e))}}_writeCopyRecord(e,t){let n=this.instanceTable,r=this._recordScratch??=new Float32Array(12);n.writeRecord(r,0,t);let i=n.recordNodeStart*16+e*3*4;for(let e=0;e<12;e++){let t=i+e>>4;this.bvh.chunkFor(t)[this.bvh.baseOf(t)+(i+e&15)]=r[e]}let a=n.clusterLeaf[n.clusterOf(e)],o=this.bvhIndexChunks.chunkFor(a),s=this.bvh.baseOf(a)+n.copyWordSlot(e),c=Ha(n.matrixWorldOf(t));o[s]=(o[s]&~wt|(c?wt:0))>>>0;let l=this._movedRecords??=new Map,u=this.bvh.recordsPerChunk*16;for(let e=i,t=i+12;e<t;){let n=Math.floor(e/u),r=Math.min(t,(n+1)*u),i=l.get(n);i?(i.lo=Math.min(i.lo,e),i.hi=Math.max(i.hi,r)):l.set(n,{lo:e,hi:r}),e=r}}takeMoveRanges(){let e=this._tlasRanges??[this.computeTLASDirtyRange()];return this._tlasRanges=null,[...e,...this.takeMovedRecordRanges()]}takeMovedRecordRanges(){let e=this._movedRecords;return this._movedRecords=null,e?[...e.values()].map(e=>({offset:e.lo,count:e.hi-e.lo})):[]}_writeGroupNodes(){let e=this.instanceTable;!e?.groupNodeCount||!this.bvh||(e.computeGroupAABBs(),this.bvh.setRecords(e.groupNodeStart,e.groupNodeBlock()))}computeTLASDirtyRange(){return{offset:0,count:this.instanceTable.blasBase*16}}computeBLASDirtyRanges(e){let t=G.FLOATS_PER_TRIANGLE,n=[],r=[];for(let i of e){let e=this.instanceTable,a=this._placementOf(i);a<0||!e.isSet[a]||(n.push({offset:e.triOffsetOf(a)*t,count:e.triCountOf(a)*t}),r.push({offset:e.blasOffsetOf(a)*16,count:e.blasNodeCountOf(a)*16}))}return r.push({offset:0,count:this.instanceTable.blasBase*16}),{triRanges:n,bvhRanges:r}}async uploadChunks(e){for(let[t,n]of[[this.triangles,`triangles`],[this.bvh,`bvh`]]){if(!t?.chunks||t.chunks.length<2||t._gpuUpload)continue;let r=e(t,n,{textureCoordinates:this.textureCoordinates});for(let e=0;e<t.chunks.length;e++)t.chunks[e]&&await r(e)}}uploadToPathTracer(e,t,n,r,{keepUserLights:i=!1}={}){return this.triangles?(e.setTriangleData(this.triangles,this.triangleCount,{textureCoordinates:this.textureCoordinates}),this.bvh?(e.setBVHData(this.bvh),e.setInstanceTable(this.instanceTable),this.materialData?e.materialData.setMaterialData(this.materialData,this.materials.map(e=>e.sources)):Gc.warn(`no material data, using defaults`),r&&e.environment.setEnvironmentTexture(r),e.materialData.setMaterialTextures({srgbBuckets:this.srgbBucketTextures,linearBuckets:this.linearBucketTextures}),e.materialData.setTexturePackMaps?.(this._srgbTexPacked,this._linearTexPacked),this.emissiveTriangleData&&(e.setEmissiveTriangleData(this.emissiveTriangleData,this.emissiveTriangleCount,this.emissiveTotalPower,this.emissiveBitTrailMap),this._releaseBitTrailMap()),this.lightBVHNodeData&&e.setLightBVHData(this.lightBVHNodeData,this.lightBVHNodeCount),t.transferSceneLights(n,{keepUserLights:i}),!0):(Gc.error(`failed to get BVH data`),!1)):(Gc.error(`failed to get triangle data`),!1)}updateMaterialEmissive(e,t,n){if(!this.emissiveTriangleBuilder)return null;let r=this.materials[e];return!r||(t===`emissive`?r.emissive=n:t===`emissiveIntensity`&&(r.emissiveIntensity=n),!this.emissiveTriangleBuilder.updateMaterialEmissive(e,r,this.triangles,this.materials,this.triangleCount))?null:this._collectEmissivePayload()}rebuildEmissiveColors(){return!this.emissiveTriangleBuilder||!this.triangleCount?null:(this.emissiveTriangleBuilder.extractEmissiveTriangles(this.triangles,this.materials,this.triangleCount,this.instanceTable??null),this.emissiveTriangleBuilder.createEmissiveRawData(),this._collectEmissivePayload())}rebuildEmissiveForVisibility(e,t=!1){return!this.emissiveTriangleBuilder||!this.emissiveTriangleBuilder.setHiddenMeshes(e)&&!t?null:this._collectEmissivePayload()}movesEmitters(e){let t=this.emissiveTriangleBuilder?.emissiveMeshes;return!!t?.size&&e.some(e=>t.has(e))}refreshEmissiveTransforms(){let e=this.emissiveTriangleBuilder;return!e?.emissiveTriangles.length||!this.instanceTable||!this.triangles?null:(e.refreshTransforms(this.triangles,this.instanceTable),this._collectEmissivePayload())}_collectEmissivePayload(){this.emissiveTriangleBuilder.buildLightBVH(),this.lightBVHNodeData=this.emissiveTriangleBuilder.lightBVHNodeData,this.lightBVHNodeCount=this.emissiveTriangleBuilder.lightBVHNodeCount,this.emissiveTriangleData=this.emissiveTriangleBuilder.emissiveTriangleData,this.emissiveBitTrailMap=this.emissiveTriangleBuilder.emissiveBitTrailMap,this.emissiveTriangleCount=this.emissiveTriangleBuilder.emissiveCount,this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower;let e=this.emissiveBitTrailMap;return this._releaseBitTrailMap(),{rawData:this.emissiveTriangleData,emissiveCount:this.emissiveTriangleCount,totalPower:this.emissiveTotalPower,bitTrailMap:e,lightBVHNodeData:this.lightBVHNodeData,lightBVHNodeCount:this.lightBVHNodeCount}}get spilled(){return!!(this.triangles?.spilledChunks||this.bvh?.spilledChunks||this._orderSpill)}async spillToDisk(e){let t=this.triangles,n=this.bvh;if(!e||this.spilled||this._spillStores||!t?.chunks||t.chunks.length<2||!n?.chunks)return null;await this._blasStoring;let r=this._geometryVersion,i=performance.now(),a=`spill:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`,o=e=>e.recordsPerChunk*e.lanesPerRecord*e.LaneType.BYTES_PER_ELEMENT,s=await yn.create(e,`${a}:tri`,o(t),{label:`Triangle records`,expectedBytes:t.byteLength}),c=s&&await yn.create(e,`${a}:bvh`,o(n),{label:`BLAS nodes`,expectedBytes:n.byteLength});if(!s||!c)return await s?.dispose(),null;this._spillStores=[s,c];let l=Math.ceil((this.instanceTable?.blasBase??1)/n.recordsPerChunk),u=await t.spill(s);if(u+=await n.spill(c,{keep:e=>e<l}),await s.flush(),await c.flush(),r!==this._geometryVersion)return null;let d=performance.now()-i;return Gc.info(`spilled ${(u/1048576).toFixed(0)} MB of triangles and BLAS nodes to disk in ${d.toFixed(0)} ms`),{bytes:u,ms:d}}ensureResident(){return this._paging??=(async()=>{await this.triangles?.ensureResident?.(),await this.bvh?.ensureResident?.(),await this._restoreOrderMaps(),this.spilled||this._disposeSpill()})().finally(()=>{this._paging=null}),this._paging}get geometryOnDisk(){return!!this._geometryOwner}ensureGeometryResident(){let e=this._geometryOwner?this._geometryReading??=this._restoreGeometry(this._geometryOwner).finally(()=>{this._geometryReading=null}):null;return Promise.all([e,this.ensureMovable()])}get matricesOnDisk(){return!!this._matrixSpill}async ensureMovable(e=[]){this._movePageIns=(this._movePageIns??0)+1;try{await this._afterLoadSpill;let t=this._matrixSpill;t&&await(this._matrixReading??=t.restore().then(()=>this._disposeMatrixSpill()).finally(()=>{this._matrixReading=null}));let n=this.instanceTable,r=this.bvh;if(!e.length||!n||!r?.spilledChunks)return;await r.ensureResident(0,n.blasBase);for(let t of this._recordChunksOf(e))await r.ensureResident(t*r.recordsPerChunk,1)}finally{this._movePageIns--}}async _spillMatrices(e=!1){let t=this.instanceTable,n=t?.adoptedMatrices()??[],i=this._spillMeshBounds;if(this._spillMeshBounds=null,!n.length||!this._progressive?.storage)return;let a=await On.create(this._progressive.storage,`spill:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}:mat`);if(!a)return;for(let[n,a]of i??this._instancedMeshBounds((e,n)=>t.writeEntryWorldAABB(e,n,0),e))n.boundingBox=new r.Box3(new r.Vector3(a[0],a[1],a[2]),new r.Vector3(a[3],a[4],a[5])),n.boundingSphere=n.boundingBox.getBoundingSphere(new r.Sphere);let o=n.reduce((e,t)=>e+t.array.byteLength,0);a.addAttributes(n),this._matrixSpill=a,Gc.info(`${H.mb(o)} of instance matrices left for disk`)}async _spillTLAS(){let e=this.instanceTable,t=this.bvh,n=this._bvhSpillStore;if(!n||!e?.clusterCount)return;let r=t.recordsPerChunk,i=e.groupNodeStart/r|0,a=(e.groupNodeStart+Math.max(1,e.groupNodeCount)-1)/r|0;this._spilledRootBounds=this.sceneBounds();let o=await t.spill(n,{keep:t=>e.groupNodeCount>0&&t>=i&&t<=a});Gc.info(`spilled ${H.mb(o)} of TLAS to disk`)}async _spillOrderMaps(){let e=this.instanceTable,t=this._progressive?.storage;if(!e?.bvhToOriginal.size||!t)return;let n=0;for(let t of e.bvhToOriginal.values())n+=t.byteLength;let r=await yn.create(t,`spill:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}:order`,0,{label:`Triangle order maps`,expectedBytes:n});if(!r)return;let i=[],a=new Uint8Array(Hc),o=0,s=0,c=async()=>{s&&await r.writeAt(o-s,a.subarray(0,s)),s=0};for(let[t,n]of e.bvhToOriginal){let e=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);i.push(t,o,n.length),s+e.length>a.length&&await c(),e.length>a.length?await r.writeAt(o,e):(a.set(e,s),s+=e.length),o+=e.length}await c(),await r.flush(),e.bvhToOriginal.clear(),this._orderSpill={store:r,index:i,bytes:n}}async _restoreOrderMaps(){let e=this._orderSpill;if(!e)return;this._orderSpill=null;let{store:t,index:n,bytes:r}=e,i=this.instanceTable.bvhToOriginal,a=0,o=null;for(let e=0;e<n.length;e+=3){let s=n[e],c=n[e+1],l=n[e+2]*4;if(l>Uc){i.set(s,new Uint32Array(await t.readAt(c,l)));continue}(!o||c+l>a+o.byteLength)&&(a=c,o=await t.readAt(c,Math.min(Uc,r-c))),i.set(s,new Uint32Array(o.slice(c-a,c-a+l)))}await t.dispose()}spillAfterLoad(){return!this._geometryOwner||this._spilledAfterLoad?this._afterLoadSpill??Promise.resolve():(this._spilledAfterLoad=!0,this._spillUnused(!1))}respill(){return!this._geometryOwner||!this._spilledAfterLoad||this._afterLoadSpill?this._afterLoadSpill??Promise.resolve():this._matrixReading||this._tlasReading||this._movePageIns?Promise.resolve():this._spillUnused(!0)}_spillUnused(e){return this._afterLoadSpill=(async()=>{await this._spillMatrices(e),await this._spillTLAS(),await this._spillOrderMaps()})().finally(()=>{this._afterLoadSpill=null}),this._afterLoadSpill}whenTLASEditable(){if(this._afterLoadSpill)return this._afterLoadSpill.then(()=>this.whenTLASEditable());let e=this.bvh,t=this.instanceTable;return!e||!t||e.isResident(0,t.blasBase)?null:this._tlasReading??=e.ensureResident(0,t.blasBase).finally(()=>{this._tlasReading=null})}needsPageInForMove(e){if(this._matrixSpill||this._afterLoadSpill)return!0;let t=this.instanceTable,n=this.bvh;if(!t||!n?.spilledChunks)return!1;if(!n.isResident(0,t.blasBase))return!0;for(let t of this._recordChunksOf(e))if(!n.isResident(t*n.recordsPerChunk,1))return!0;return!1}_recordChunksOf(e){let t=this.instanceTable,n=this.bvh.recordsPerChunk,r=new Set;if(!t.clusterCount)return r;let i=new Set(e);for(let n of e){let e=t.groupOfTemplate?.[n]??-1;if(e>=0)for(let n of t.groups[e].members)i.add(n)}for(let e of i){let i=t.placementRunOf(e);if(i)for(let e=i.start;e<i.start+i.count;e++){let i=t.tlasLeafIndex[e];if(i<0)continue;let a=t.recordNodeStart*16+i*3*4;r.add(Math.floor(a/16/n)),r.add(Math.floor((a+11)/16/n))}}return r}_instancedMeshBounds(e,t=!1){let n=this.instanceTable,r=new Set(n.adoptedMatrices()),i=new Map,a=new Float64Array(6);return(this.meshes??[]).forEach((o,s)=>{if(!o?.isInstancedMesh||!r.has(o.instanceMatrix)||t&&o.boundingBox)return;let c=n.placementRunOf(s);if(!c)return;let l=[1/0,1/0,1/0,-1/0,-1/0,-1/0];for(let t=c.start;t<c.start+c.count;t++){e(n.entryOf(t),a);for(let e=0;e<3;e++)a[e]<l[e]&&(l[e]=a[e]),a[3+e]>l[3+e]&&(l[3+e]=a[3+e])}i.set(o,l)}),i}_disposeMatrixSpill(){let e=this._matrixSpill;this._matrixSpill=null,e?.dispose().catch(()=>{})}async _restoreGeometry(e){let t=this._geometrySpill;if(!t?.bytes){this._geometryOwner=null;return}this._geometryOwner||z({status:`Reading scene geometry back...`,progress:84});let n=performance.now(),r=t.bytes;await t.restore(),this._disposeGeometrySpill(),this._geometryBytes=Nn(e),Gc.info(`read ${H.mb(r)} of scene geometry back from disk in ${H.ms(performance.now()-n)}`),t.error&&Gc.warn(`some scene geometry stayed in memory, its spill write failed:`,t.error)}_disposeGeometrySpill(){let e=this._geometrySpill;this._geometrySpill=null,this._geometryOwner=null,e?.dispose().catch(()=>{})}_disposeSpill(){let e=this._spillStores;this._spillStores=null;for(let t of e??[])t.dispose().catch(()=>{})}_releaseBitTrailMap(){this.emissiveBitTrailMap=null,this.emissiveTriangleBuilder&&(this.emissiveTriangleBuilder.emissiveBitTrailMap=null)}_clusterCopies(e){let t=this.config.clusterCopies??`auto`;return t===`auto`?e.entryCount>=zc:t===!0}async _writeCopyRecords(e){let t=this.instanceTable,n=t.entryCount,r=4096,i=r*3/4,a=new Float32Array(i*16);for(let o=0;o<n;o+=r){let s=Math.min(r,n-o);a.fill(0);for(let e=0;e<s;e++)t.writeRecord(a,e*3*4,t.repOf(t.recordEntry[o+e]));let c=t.recordNodeStart+o*3/4,l=Math.ceil(s*3/4);this.bvh.setRecords(c,l===i?a:a.subarray(0,l*16)),await e?.(c+l)}}async _buildTLAS(e){let t=e.clusterCount>0,n=t?e.clusterCount:e.entryCount;if(n>=Pc&&!this._tlasWorkerFailed)try{let r=t?e.clusterBounds:new Float64Array(n*6);t||e.writeEntryWorldAABBs(r);let{tlasData:i,nodeCount:a}=await this._runTLASWorker(r,n);return oo.fillLeaves(i,a,e),i}catch(e){this._tlasWorkerFailed=!0,Gc.warn(`TLAS worker unavailable (${e.message}); building on the main thread`)}return this.tlasBuilder.build(e).data}_runTLASWorker(e,t){this._tlasWorker||=jr(Nc);let n=this._tlasWorker;return new Promise((r,i)=>{let a=e=>{n.removeEventListener(`message`,a),n.removeEventListener(`error`,o),e.data?.error?i(Error(e.data.error)):r(e.data)},o=e=>{n.removeEventListener(`message`,a),n.removeEventListener(`error`,o),i(Error(e.message||`worker error`))};n.addEventListener(`message`,a),n.addEventListener(`error`,o),n.postMessage({aabbs:e.buffer,count:t,logLevel:B()},[e.buffer])})}_setBVHData(e){let t=e?e instanceof fn?e:fn.adopt([e],e.length/16,16,e.length/16):null;this.bvh=t,t&&this._foldLeaves&&(t.foldedLeaves=!0),t&&this.instanceTable?.clusterCount&&(t.copyRecordBase=this.instanceTable.recordNodeStart*4),this.bvhIndexChunks=t?t.viewAs(Uint32Array):null,this.bvhData=t?t.single:null,this.bvhIndex=this.bvhIndexChunks?this.bvhIndexChunks.single:null}_setTriangleData(e){let t=G.FLOATS_PER_TRIANGLE,n=e?e instanceof fn?e:fn.adopt([e],e.length/t,t,e.length/t):null;this.triangles=n,this.triangleFloatChunks=n?n.viewAs(Float32Array):null,this.triangleData=n?n.single:null,this.triangleFloats=this.triangleFloatChunks?this.triangleFloatChunks.single:null}_updateMeshTrianglePositions(e,t){let n=G.POSITION_A_OFFSET,r=G.POSITION_B_OFFSET,i=G.POSITION_C_OFFSET,a=G.NORMAL_A_PACKED_OFFSET,o=G.NORMAL_B_PACKED_OFFSET,s=G.NORMAL_C_PACKED_OFFSET,c=this.triangles,l=this.triangleFloatChunks,u=this.instanceTable,d=u.bvhToOriginalOf(e),f=u.triOffsetOf(e),p=u.triCountOf(e),m=u.matrixInverseOf(e),h=Ha(m);for(let e=0;e<p;e++){let u=d?d[e]:e,p=f+e,g=l.chunkFor(p),_=c.chunkFor(p),v=c.baseOf(p),y=u*9,b=t[y],x=t[y+1],S=t[y+2],C=t[y+3],w=t[y+4],T=t[y+5],E=t[y+6],D=t[y+7],O=t[y+8];if(!h){let e=(e,t,n)=>m[0]*e+m[4]*t+m[8]*n+m[12],t=(e,t,n)=>m[1]*e+m[5]*t+m[9]*n+m[13],n=(e,t,n)=>m[2]*e+m[6]*t+m[10]*n+m[14],r=[e(b,x,S),t(b,x,S),n(b,x,S)],i=[e(C,w,T),t(C,w,T),n(C,w,T)],a=[e(E,D,O),t(E,D,O),n(E,D,O)];b=r[0],x=r[1],S=r[2],C=i[0],w=i[1],T=i[2],E=a[0],D=a[1],O=a[2]}g[v+n]=b,g[v+n+1]=x,g[v+n+2]=S,g[v+r]=C,g[v+r+1]=w,g[v+r+2]=T,g[v+i]=E,g[v+i+1]=D,g[v+i+2]=O;let k=C-b,A=w-x,j=T-S,M=E-b,N=D-x,P=O-S,F=ht(A*P-j*N,j*M-k*P,k*N-A*M);_[v+a]=F,_[v+o]=F,_[v+s]=F}}_patchMeshSmoothNormals(e,t){let n=this.instanceTable;this._patchNormalsRange(t,n.triOffsetOf(e),n.triCountOf(e),n.matrixWorldOf(e),n.bvhToOriginalOf(e))}_patchNormalsRange(e,t,n,r,i){let a=G.NORMAL_A_PACKED_OFFSET,o=G.NORMAL_B_PACKED_OFFSET,s=G.NORMAL_C_PACKED_OFFSET,c=r,l=!c||Ha(c),u=[a,o,s];for(let r=0;r<n;r++){let n=t+r,a=this.triangles.chunkFor(n),o=this.triangles.baseOf(n),s=(i?i[r]:r)*9;for(let t=0;t<3;t++){let n=s+t*3,r=e[n],i=e[n+1],d=e[n+2],f=r,p=i,m=d;if(!l){f=c[0]*r+c[1]*i+c[2]*d,p=c[4]*r+c[5]*i+c[6]*d,m=c[8]*r+c[9]*i+c[10]*d;let e=Math.hypot(f,p,m)||1;f/=e,p/=e,m/=e}a[o+u[t]]=ht(f,p,m)}}}_refitTLAS(e=null){let t=this.instanceTable,n=t.tlasNodeCount,r=e?Int32Array.from(e).sort():null;if(this._tlasRanges=r?[]:null,!n||r?.length===0)return;let i=r?Array.from(r):null,a=this._refitStack??=new Int32Array(256),o=0,s=0,c=this._refitBox??=new Float32Array(6),l=(e,t,n,r)=>{if(o+4>a.length){let e=new Int32Array(a.length*2);e.set(a),a=this._refitStack=e}a[o++]=e,a[o++]=t,a[o++]=n,a[o++]=r};for(l(0,n,-1,0);o;){let e=a[--o],n=a[--o],u=a[--o],d=a[--o],f=this.bvh.chunkFor(d),p=this.bvh.baseOf(d);if(e)c[0]=Math.min(f[p],f[p+8]),c[1]=Math.min(f[p+1],f[p+9]),c[2]=Math.min(f[p+2],f[p+10]),c[3]=Math.max(f[p+4],f[p+12]),c[4]=Math.max(f[p+5],f[p+13]),c[5]=Math.max(f[p+6],f[p+14]);else{if(r){for(;s<r.length&&r[s]<d;)s++;if(s===r.length||r[s]>=u)continue}let e=this.bvhIndexChunks.chunkFor(d),i=e[p+3];if(i===Et.BLAS_POINTER_LEAF){let n=e[p+1]&Tt;if(n>=t.entryCount)continue;t.writeEntryWorldAABB(n,c,0)}else if(i===Et.CLUSTER_LEAF)t.encodeClusterBoxes(f,e,p,t.clusterOf(e[p]&Dt),null,c,0);else if(i<Et.TRIANGLE_LEAF){let t=e[p+7];l(d,u,n,1),l(t,u,d*2+1,0),l(i,t,d*2,0);continue}else continue}if(n<0)continue;let m=n>>1,h=this.bvh.chunkFor(m),g=this.bvh.baseOf(m)+(n&1)*8;h[g]=c[0],h[g+1]=c[1],h[g+2]=c[2],h[g+4]=c[3],h[g+5]=c[4],h[g+6]=c[5],i?.push(m)}i&&(this._tlasRanges=el(i))}scheduleBackgroundRebuild(e,t){if(!this.instanceTable||!this.triangles)return;this._rebuildGeneration++;let n=this._rebuildGeneration,r=(e,r,i)=>{let a=this.triangles.copyOf(r.triOffset,r.triCount);this._pendingRebuilds.set(e,i),i.onmessage=a=>{let o=a.data;if(i.terminate(),this._pendingRebuilds.delete(e),o.error){Gc.error(`background BLAS rebuild failed (mesh ${e}):`,o.error);return}n===this._rebuildGeneration&&this._swapBLAS(e,r,o,t)},i.onerror=t=>{Gc.error(`background BLAS rebuild worker failed (mesh ${e}):`,t),i.terminate(),this._pendingRebuilds.delete(e)},i.postMessage({triangleData:a.buffer,triangleByteOffset:a.byteOffset,triangleByteLength:a.byteLength,triangleCount:r.triCount,depth:this.config.bvhDepth,maxLeafSize:this.bvhBuilder.maxLeafSize,foldLeaves:this._foldLeaves===!0,numBins:this.bvhBuilder.numBins,maxBins:this.bvhBuilder.maxBins,minBins:this.bvhBuilder.minBins,reportProgress:!1,sharedReorderBuffer:null,reinsertionOptimization:{enabled:this.bvhBuilder.enableReinsertionOptimization,batchSizeRatio:this.bvhBuilder.reinsertionBatchSizeRatio,maxIterations:this.bvhBuilder.reinsertionMaxIterations}},[a.buffer])};for(let t of e){let e=this._placementOf(t);if(e<0)continue;let n=this.instanceTable.entryAt(e);if(!n||!this.instanceTable.isOwner(e))continue;let i=this._pendingRebuilds.get(e);i&&i.terminate(),r(e,n,jr(Ta))}}_swapBLAS(e,t,n,r){this._geometryVersion=(this._geometryVersion??0)+1;let i=n.bvhData,a=i.length/16;if(a>t.blasNodeCount){Gc.warn(`background rebuild does not fit for mesh ${e} (${a} nodes vs ${t.blasNodeCount} reserved), skipping swap`);return}this.bvh.setRecords(t.blasOffset,i),this._offsetBLASInPlace(t.blasOffset,a,t.blasOffset,t.triOffset);let o=n.triangles;o&&this.triangles.setRecords(t.triOffset,o),this.instanceTable.setBlasNodeCount(e,a);let s=n.originalToBvh;if(s){let n=this.instanceTable.bvhToOriginalOf(e),r=new Uint32Array(t.triCount);for(let e=0;e<t.triCount;e++)r[s[e]]=n?n[e]:e;this.instanceTable.setBvhToOriginal(e,r)}this.instanceTable.recomputeAABB(e,this.bvh,this.triangles),this._refitTLAS(),this._log(`Background BLAS rebuild complete for mesh ${e}`),r?.(this.instanceTable.sourceMesh[e]??e)}cancelBackgroundRebuilds(){for(let e of this._pendingRebuilds.values())e.terminate();this._pendingRebuilds.clear()}_disposeRefitWorker(){this._refitWorker&&=(this._refitWorker.terminate(),null),this._refitSharedBuffers=null,this.cancelBackgroundRebuilds()}_disposeTLASWorker(){this._tlasWorker&&=(this._tlasWorker.terminate(),null)}dispose(){this._geometryVersion=(this._geometryVersion??0)+1,this._log(`Disposing resources`),this._disposeRefitWorker(),this._disposeTLASWorker(),this._disposeTextures(),this._reset(),this.textureCreator&&=(this.textureCreator.dispose(),null),this.geometryExtractor=null,this.bvhBuilder=null,this.tlasBuilder=null,this._blasRefitter=null}},nl=[[1619.19106,-.00205010916,5.02995757],[2488.45471,-.00111330907,3.22621544],[3341.43193,-.000486551192,1.76486769],[4094.61742,-.000127446582,.725731635],[4670.28036,291258199e-13,.126703442],[4595.09185,287495649e-13,.15034502],[3787.1745,935907826e-14,.399075871]],rl=[[-488.999748,.000604330754,-.0755807526],[-755.994277,.000316730098,.478306139],[-1023.63977,.00012022347,.936662319],[-1265.71316,487340896e-14,1.27054498],[-1425.29332,-401150431e-13,1.43972784],[-1175.54822,-216378048e-13,1.30408023],[-500.799571,-459832026e-14,1.09098763]],il=[[596945309e-19,-4.85742887e-8,-970622247e-13,-.00407936148],[240430366e-19,5.55021075e-8,-.000198503712,.0289312858],[-140949732e-19,1.89878968e-7,-.000356632824,.0910767778],[-361460868e-19,2.84822009e-7,-.000493211319,.15672344],[-197075738e-19,1.75359352e-7,-.000250542825,-.0222783266],[-161997957e-21,-1.64216008e-8,.000386216271,-.738077418],[672650283e-21,-2.73078809e-8,.000424098264,-.752335691]];function al(e){let t,n,r;if(e>=12e3)t=.8262954810464208,n=.9945080501520986,r=1.566307710274283;else if(e<800)t=5.413294490189271,n=-.20319390035873933,r=-.0822535242887164;else{let i=e>=6365?6:e>=3315?5:e>=1902?4:e>=1449?3:e>=1167?2:+(e>=965),a=nl[i],o=rl[i],s=il[i],c=1/e;t=a[0]*c+a[1]*e+a[2],n=o[0]*c+o[1]*e+o[2],r=((s[0]*e+s[1])*e+s[2])*e+s[3]}return[Math.max(0,t),Math.max(0,n),Math.max(0,r)]}nr();var ol=1/(4*Math.PI);function sl(e){let t=e.userData||{},n=Number.isFinite(t.exposure)?t.exposure:0,r=e.intensity*2**n,i=[e.color.r,e.color.g,e.color.b];if(t.useTemperature){let[e,n,r]=al(t.temperature??6500);i[0]*=e,i[1]*=n,i[2]*=r}return Qn(i),{r:i[0],g:i[1],b:i[2],intensity:r}}var cl=e=>Math.max(0,Number(e.userData?.radius)||0),ll=class{constructor(){this.lightData={directional:[],rectArea:[],point:[],spot:[]},this.directionalLightCache=[],this.areaLightCache=[],this.pointLightCache=[],this.spotLightCache=[]}clear(){this.lightData.directional=[],this.lightData.rectArea=[],this.lightData.point=[],this.lightData.spot=[],this.directionalLightCache=[],this.areaLightCache=[],this.pointLightCache=[],this.spotLightCache=[]}calculateLightImportance(e,t=`directional`){let n=.2126*e.color.r+.7152*e.color.g+.0722*e.color.b,r=e.intensity*n;if(t===`area`){let t=e.width*e.height;r*=Math.sqrt(t)}else if(t===`point`)r*=Math.sqrt(e.distance||100);else if(t===`spot`){let t=Math.sin(e.angle||Math.PI/4);r*=Math.sqrt(e.distance||100)*t}return r}addDirectionalLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n;if(e.target){e.target.updateMatrixWorld();let i=e.target.getWorldPosition(new r.Vector3);n=t.sub(i).normalize()}else n=t.normalize();let i=this.calculateLightImportance(e,`directional`),a=e.userData.angle||e.angle||0,o=sl(e),s=e.userData?.gobo,c=s&&Number.isInteger(s.index)?s.index:-1,l=s&&typeof s.intensity==`number`?s.intensity:1,u=s&&s.inverted?-Math.abs(l):Math.abs(l),d=s&&typeof s.scale==`number`?s.scale:5;this.directionalLightCache.push({data:[n.x,n.y,n.z,o.r,o.g,o.b,o.intensity,a,c,u,d,0],importance:i,light:e})}addRectAreaLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n=e.getWorldQuaternion(new r.Quaternion),i=e.getWorldScale(new r.Vector3),a=e.width*i.x*.5,o=e.height*i.y*.5,s=new r.Vector3(a,0,0).applyQuaternion(n),c=new r.Vector3(0,-o,0).applyQuaternion(n),l=this.calculateLightImportance(e,`area`),u=e.userData?.normalize??!0?1:0,d=Number.isFinite(e.userData?.spread)?e.userData.spread:Math.PI,f=+(e.userData?.shape===`ellipse`||e.userData?.shape===`disk`||e.userData?.shape===1),p=sl(e);this.areaLightCache.push({data:[t.x,t.y,t.z,s.x,s.y,s.z,c.x,c.y,c.z,p.r,p.g,p.b,p.intensity,u,d,f],importance:l,light:e})}addPointLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n=this.calculateLightImportance(e,`point`),i=sl(e);this.pointLightCache.push({data:[t.x,t.y,t.z,i.r,i.g,i.b,i.intensity*ol,e.distance||0,e.decay===void 0?2:e.decay,cl(e)],importance:n,light:e})}addSpotLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n=(e.target?e.target.getWorldPosition(new r.Vector3):new r.Vector3(0,0,-1)).sub(t).normalize(),i=this.calculateLightImportance(e,`spot`),a=e.userData?.gobo,o=a&&Number.isInteger(a.index)?a.index:-1,s=a&&typeof a.intensity==`number`?a.intensity:1,c=a&&a.inverted?-Math.abs(s):Math.abs(s),l=e.userData?.ies,u=l&&Number.isInteger(l.index)?l.index:-1,d=l&&typeof l.intensity==`number`?l.intensity:1,f=sl(e);this.spotLightCache.push({data:[t.x,t.y,t.z,n.x,n.y,n.z,f.r,f.g,f.b,f.intensity*ol,e.angle||Math.PI/4,e.penumbra||0,e.distance||0,e.decay===void 0?2:e.decay,o,c,u,d,cl(e),0],importance:i,light:e})}preprocessLights(){this.directionalLightCache.sort((e,t)=>t.importance-e.importance),this.areaLightCache.sort((e,t)=>t.importance-e.importance),this.pointLightCache.sort((e,t)=>t.importance-e.importance),this.spotLightCache.sort((e,t)=>t.importance-e.importance),this.lightData.directional=[],this.lightData.rectArea=[],this.lightData.point=[],this.lightData.spot=[],this.directionalLightCache.forEach(e=>{this.lightData.directional.push(...e.data)}),this.areaLightCache.forEach(e=>{this.lightData.rectArea.push(...e.data)}),this.pointLightCache.forEach(e=>{this.lightData.point.push(...e.data)}),this.spotLightCache.forEach(e=>{this.lightData.spot.push(...e.data)}),this.areaLightCache.length>0&&console.log(`Preprocessed ${this.areaLightCache.length} area lights by importance`),this.pointLightCache.length>0&&console.log(`Preprocessed ${this.pointLightCache.length} point lights by importance`),this.spotLightCache.length>0&&console.log(`Preprocessed ${this.spotLightCache.length} spot lights by importance`)}updateShaderUniforms(e){let t=Math.floor(this.lightData.directional.length/12),n=Math.floor(this.lightData.rectArea.length/16),r=Math.floor(this.lightData.point.length/9),i=Math.floor(this.lightData.spot.length/20);e.defines.MAX_DIRECTIONAL_LIGHTS=t,e.defines.MAX_AREA_LIGHTS=n,e.defines.MAX_POINT_LIGHTS=r,e.defines.MAX_SPOT_LIGHTS=i,e.uniforms.directionalLights.value=new Float32Array(this.lightData.directional),e.uniforms.areaLights.value=new Float32Array(this.lightData.rectArea),e.uniforms.pointLights.value=new Float32Array(this.lightData.point),e.uniforms.spotLights.value=new Float32Array(this.lightData.spot),e.needsUpdate=!0}processSceneLights(e,t){this.clear(),e.traverse(e=>{e.isDirectionalLight?this.addDirectionalLight(e):e.isRectAreaLight?this.addRectAreaLight(e):e.isPointLight?this.addPointLight(e):e.isSpotLight&&this.addSpotLight(e)}),this.preprocessLights(),this.updateShaderUniforms(t)}getLightStatistics(){return{directionalLights:this.directionalLightCache.map(e=>({intensity:e.light.intensity,importance:e.importance,color:e.light.color})),areaLights:this.areaLightCache.map(e=>({intensity:e.light.intensity,importance:e.importance,color:e.light.color,size:e.light.width*e.light.height}))}}},ul,dl,fl,pl,ml,hl,gl,_l,vl,yl,bl,xl,Sl,Cl,wl,Tl,El=g((()=>{ul=x({origin:`vec3`,direction:`vec3`}),dl=x({color:`vec4`,emissive:`vec3`,emissiveIntensity:`float`,roughness:`float`,metalness:`float`,ior:`float`,transmission:`float`,thickness:`float`,clearcoat:`float`,clearcoatRoughness:`float`,opacity:`float`,transparent:`bool`,attenuationColor:`vec3`,attenuationDistance:`float`,dispersion:`float`,sheen:`float`,sheenRoughness:`float`,sheenColor:`vec3`,specularIntensity:`float`,specularColor:`vec3`,alphaTest:`float`,alphaMode:`int`,side:`int`,depthWrite:`int`,albedoMapIndex:`int`,emissiveMapIndex:`int`,normalMapIndex:`int`,bumpMapIndex:`int`,bumpScale:`float`,displacementScale:`float`,displacementBias:`float`,metalnessMapIndex:`int`,roughnessMapIndex:`int`,displacementMapIndex:`int`,normalScale:`vec2`,albedoTransform:`mat3`,emissiveTransform:`mat3`,normalTransform:`mat3`,bumpTransform:`mat3`,metalnessTransform:`mat3`,roughnessTransform:`mat3`,displacementTransform:`mat3`,iridescence:`float`,iridescenceIOR:`float`,iridescenceThicknessRange:`vec2`,subsurface:`float`,subsurfaceColor:`vec3`,subsurfaceRadius:`vec3`,subsurfaceRadiusScale:`float`,subsurfaceAnisotropy:`float`,anisotropy:`float`,anisotropyRotation:`float`,anisotropyMapIndex:`int`,transmissionMapIndex:`int`,clearcoatMapIndex:`int`,clearcoatRoughnessMapIndex:`int`,sheenColorMapIndex:`int`,sheenRoughnessMapIndex:`int`,iridescenceMapIndex:`int`,iridescenceThicknessMapIndex:`int`,specularIntensityMapIndex:`int`,specularColorMapIndex:`int`,diffuseTransmission:`float`,diffuseTransmissionColor:`vec3`,diffuseTransmissionMapIndex:`int`,diffuseTransmissionColorMapIndex:`int`}),fl=x({transmission:`float`,clearcoat:`float`,clearcoatRoughness:`float`,sheenColor:`vec3`,sheenRoughness:`float`,iridescence:`float`,iridescenceThickness:`float`,specularIntensity:`float`,specularColor:`vec3`,diffuseTransmission:`float`,diffuseTransmissionColor:`vec3`}),pl=x({color:`vec4`,ior:`float`,transmission:`float`,attenuationColor:`vec3`,attenuationDistance:`float`,albedoMapIndex:`int`,opacity:`float`,transparent:`bool`,alphaTest:`float`,alphaMode:`int`,albedoTransform:`mat3`}),ml=x({shadowed:`vec3`,unoccluded:`vec3`}),x({position:`vec3`,radius:`float`,material:dl}),hl=x({didHit:`bool`,dst:`float`,hitPoint:`vec3`,normal:`vec3`,uv:`vec2`,materialIndex:`int`,meshIndex:`int`,instanceLeaf:`int`,triangleIndex:`int`,boxTests:`int`,triTests:`int`}),x({posA:`vec3`,posB:`vec3`,posC:`vec3`,uvA:`vec2`,uvB:`vec2`,uvC:`vec2`,normalA:`vec3`,normalB:`vec3`,normalC:`vec3`,material:dl,materialIndex:`int`,meshIndex:`int`}),x({color:`vec4`,samples:`int`}),gl=x({direction:`vec3`,value:`vec3`,pdf:`float`,isTransmission:`bool`,colorWeight:`vec3`,isDiffuseTransmission:`bool`}),_l=x({specular:`float`,diffuse:`float`,sheen:`float`,clearcoat:`float`,transmission:`float`,iridescence:`float`,diffuseTransmission:`float`}),vl=x({Ta:`vec3`,Ba:`vec3`}),yl=x({NoL:`float`,NoV:`float`,NoH:`float`,VoH:`float`,LoH:`float`,ToH:`float`,BoH:`float`,ToV:`float`,BoV:`float`,ToL:`float`,BoL:`float`}),bl=x({compensation:`vec3`,E_total:`vec3`}),xl=x({f0:`vec3`,f90:`float`,eta:`float`,F0m:`vec3`,F0:`vec3`}),Sl=x({albedo:`vec4`,emissive:`vec3`,metalness:`float`,roughness:`float`,normal:`vec3`,hasTextures:`bool`}),Cl=x({isMetallic:`bool`,isRough:`bool`,isSmooth:`bool`,isTransmissive:`bool`,hasClearcoat:`bool`,isEmissive:`bool`,complexityScore:`float`}),wl=x({albedoUV:`vec2`,normalUV:`vec2`,metalnessUV:`vec2`,emissiveUV:`vec2`,bumpUV:`vec2`,roughnessUV:`vec2`,normalBumpSameUV:`bool`,metalRoughSameUV:`bool`,albedoEmissiveSameUV:`bool`,allSameUV:`bool`}),Tl=x({invRoughness:`float`,metalFactor:`float`,iorFactor:`float`,maxSheenColor:`float`}),x({traversals:`int`,transmissiveTraversals:`int`,rayType:`int`,isPrimaryRay:`bool`,actualBounceDepth:`int`})}));function Dl(e,t,n){return e.length===1?e[0]:{isSplitStorage:!0,parts:e,perPart:t,type:n,value:e[0].value}}function Ol(e,t,r){let{parts:i,perPart:a}=e,o=(0,n.int)(t).toVar(),s=r.map(()=>({uvec4:n.uvec4,uvec2:n.uvec2}[e.type]??n.vec4)(0).toVar()),c=e=>()=>{let t=e===0?o:o.sub((0,n.int)(a*e));r.forEach((r,a)=>s[a].assign(i[e].element(r===0?t:t.add((0,n.int)(r)))))},l=(0,n.If)(o.lessThan((0,n.int)(a)),c(0));for(let e=1;e<i.length-1;e++)l=l.ElseIf(o.lessThan((0,n.int)(a*(e+1))),c(e));return l.Else(c(i.length-1)),s}function kl(e,t){return e.isSplitStorage?Ol(e,t,[0])[0]:e.element(t)}var Al,jl,Ml,Nl,Pl,Fl,Il,Ll,Rl,zl,Bl,Vl,Hl,Ul,Wl,Gl,Kl,ql,Jl,Yl,Xl,Zl,Ql,$l,eu,tu,nu,ru,iu,X,au,ou,su,cu,lu,uu,du,fu,pu,mu,hu,gu,_u,vu=g((()=>{El(),It(),Al=(0,n.wgslFn)(`
|
|
248
248
|
fn offsetRayOrigin( p: vec3f, n: vec3f ) -> vec3f {
|
|
249
249
|
let step = select( vec3<i32>( 32 ), vec3<i32>( -32 ), ( p < vec3f( 0.0 ) ) != ( n < vec3f( 0.0 ) ) );
|
|
250
250
|
let far = bitcast<vec3f>( bitcast<vec3<i32>>( p ) + step );
|