rayzee 11.2.0 → 11.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/dist/{ArchiveImporter-eNlu0_6F.js → ArchiveImporter-D_x863yu.js} +2 -2
- package/dist/{BidirectionalIntegrator-D1-6UySB.js → BidirectionalIntegrator-DmkxxEOR.js} +1 -1
- package/dist/{NeuralRetouch-DFGbnmLb.js → NeuralRetouch-Cr-otSW8.js} +1 -1
- package/dist/{NeuralSuperRes-BtXvyJQl.js → NeuralSuperRes-B7E3_M0t.js} +1 -1
- package/dist/{PathTracer-BHXGJtPN.js → PathTracer-D6nbknj5.js} +2 -2
- package/dist/{PhysicalSky-DN6u8UX4.js → PhysicalSky-Dq5VSiCQ.js} +1 -1
- package/dist/{RayzeeRenderer-Dw1x8mVL.js → RayzeeRenderer-DbjqO6v-.js} +3 -3
- 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 +3 -3
- package/dist/rayzee.es.js +10 -10
- package/dist/rayzee.umd.js +3 -3
- package/dist/{sceneCachePolicy-DA7iGoL4.js → sceneCachePolicy-C4-4qwt6.js} +1 -1
- package/package.json +1 -1
- package/src/EngineDefaults.js +1 -1
- package/src/RayzeeRenderer.js +1 -1
package/dist/rayzee.umd.js
CHANGED
|
@@ -112,7 +112,7 @@
|
|
|
112
112
|
return seed;
|
|
113
113
|
|
|
114
114
|
}
|
|
115
|
-
`,[Be,ze]),G=rt({maxBounces:3,transmissiveBounces:5,maxSubsurfaceSteps:8,maxTransparentBounces:32,integrator:`path`,shadowRays:`two`,samplingTechnique:2,enableEmissiveTriangleSampling:!1,emissiveBoost:1,enableAlphaShadows:!1,fireflyThreshold:3,shadowTerminatorOffset:.1,globalIlluminationIntensity:1,wavefrontSortMaterials:!0,maxSamples:60,renderLimitMode:`frames`,renderTimeLimit:30,renderMode:0,useAdaptiveSampling:!0,noiseThreshold:.1,adaptiveMinSamples:8,adaptiveStopFraction:.9,usePixelFreeze:!0,pixelFreezeThreshold:.02,pixelFreezeStability:8,convergenceOverlay:!1,interactionModeEnabled:!0,exposure:1,saturation:1,transparentBackground:!1,backgroundColor:`#000000`,enableEnvironment:!0,environmentIntensity:1,environmentRotation:0,showBackground:!0,backgroundIntensity:1,backgroundBlurriness:0,backgroundBlurSamples:8,groundProjectionEnabled:!1,groundProjectionRadius:100,groundProjectionHeight:15,groundProjectionLevel:0,enableGroundCatcher:!1,groundCatcherHeight:0,cameraProjection:`perspective`,panoramaLonRange:[-180,180],panoramaLatRange:[-90,90],panoramaLevelHorizon:!0,enableDOF:!1,dofMode:`look`,dofBlur:.05,focusDistance:.8,aperture:5.6,focalLength:50,apertureScale:1,anamorphicRatio:1,unitsPerMetre:1,maxTextureSize:4096,areaLightIntensityScale:1,visMode:0,debugVisScale:100}),tt=Object.freeze({perspective:0,equirectangular:1,orthographic:2}),nt=rt({color:[1,1,1],emissive:[0,0,0],emissiveIntensity:1,roughness:1,metalness:0,ior:1.5,opacity:1,transmission:0,thickness:0,attenuationColor:[1,1,1],attenuationDistance:1/0,dispersion:0,sheen:0,sheenRoughness:1,sheenColor:[0,0,0],specularIntensity:1,specularColor:[1,1,1],clearcoat:0,clearcoatRoughness:0,iridescence:0,iridescenceIOR:1.3,iridescenceThicknessRange:[100,400],normalScale:[1,1],bumpScale:1,displacementScale:1,transparent:0,alphaTest:0,alphaMode:0,side:0,depthWrite:1,subsurface:0,subsurfaceColor:[1,1,1],subsurfaceRadius:[1,.2,.1],subsurfaceRadiusScale:1,subsurfaceAnisotropy:0,anisotropy:0,anisotropyRotation:0,diffuseTransmission:0,diffuseTransmissionColor:[1,1,1]});function rt(e){for(let t of Object.values(e))typeof t==`object`&&Object.freeze(t);return Object.freeze(e)}var it={maxSamples:30,bounces:20,transmissiveBounces:24,maxSubsurfaceSteps:64,renderMode:1,enableAlphaShadows:!0,enableOIDN:!0,oidnQuality:`high`,interactionModeEnabled:!1,useAdaptiveSampling:!0,noiseThreshold:.02,adaptiveStopFraction:.94,usePixelFreeze:!0},at={maxSamples:G.maxSamples,bounces:G.maxBounces,renderMode:G.renderMode,enableAlphaShadows:G.enableAlphaShadows,transmissiveBounces:12,maxSubsurfaceSteps:G.maxSubsurfaceSteps,enableOIDN:!0,oidnQuality:`fast`,interactionModeEnabled:!0,useAdaptiveSampling:!0,noiseThreshold:.1,usePixelFreeze:!0};function ot(e){return{maxSamples:e.maxSamples,maxBounces:e.bounces,transmissiveBounces:e.transmissiveBounces,maxSubsurfaceSteps:e.maxSubsurfaceSteps,enableAlphaShadows:e.enableAlphaShadows??!1,useAdaptiveSampling:e.useAdaptiveSampling??!1,noiseThreshold:e.noiseThreshold??G.noiseThreshold,adaptiveStopFraction:e.adaptiveStopFraction??G.adaptiveStopFraction,adaptiveMinSamples:e.adaptiveMinSamples??G.adaptiveMinSamples,usePixelFreeze:e.usePixelFreeze??!1,pixelFreezeThreshold:e.pixelFreezeThreshold??G.pixelFreezeThreshold,pixelFreezeStability:e.pixelFreezeStability??G.pixelFreezeStability,interactionModeEnabled:e.interactionModeEnabled??G.interactionModeEnabled}}var st={cameraViewMatrix:`ptCameraViewMatrix`,cameraProjectionMatrix:`ptCameraProjectionMatrix`},ct=Object.freeze({directional:12,area:16,point:9,spot:20}),lt=65536/16;function ut(e,t){let n=Math.ceil(t/16)*16;return Math.max(t,Math.min(n,Math.floor(lt/ct[e])))}var dt=class{constructor(e=1920,t=1080){this._uniforms=new Map,this._booleans=new Set,this._arrayWarned=new Set,this._lightBuffers={},this._initUniforms(e,t),this._nameAll()}get(e){return this._uniforms.get(e)}set(e,t){let n=this._uniforms.get(e);if(!n){console.warn(`UniformManager: Unknown uniform "${e}"`);return}Array.isArray(t)&&t.length===1&&(this._booleans.has(e)||typeof n.value==`number`)&&(this._arrayWarned.has(e)||(this._arrayWarned.add(e),console.warn(`UniformManager: "${e}" was set to [${t[0]}] but expects a scalar — unwrapping. Fix the caller; a slider handler is probably forwarding its array value unchanged.`)),t=t[0]),this._booleans.has(e)?n.value=+!!t:typeof t==`object`&&t&&typeof n.value?.copy==`function`?n.value.copy(t):n.value=t}has(e){return this._uniforms.has(e)}keys(){return this._uniforms.keys()}getLightBufferNodes(){return this._lightBuffers}updateMany(e){let t=!1;for(let[n,r]of Object.entries(e)){let e=this._uniforms.get(n);e&&e.value!==r&&(e.value=r,t=!0)}return t}_initUniforms(e,t){let i=(e,t,r)=>{let i=(0,n.uniform)(t,r);return this._uniforms.set(e,i),i},a=(e,t)=>(this._booleans.add(e),i(e,+!!t,`int`));i(`frame`,0,`uint`),i(`seedFrame`,0,`uint`),i(`maxBounces`,G.maxBounces,`int`),i(`maxSamples`,G.maxSamples,`int`),i(`transmissiveBounces`,G.transmissiveBounces,`int`),i(`maxSubsurfaceSteps`,G.maxSubsurfaceSteps,`int`),i(`maxTransparentBounces`,G.maxTransparentBounces,`int`),i(`visMode`,G.visMode,`int`),i(`debugVisScale`,G.debugVisScale,`float`),a(`useAdaptiveSampling`,G.useAdaptiveSampling),i(`noiseThreshold`,G.noiseThreshold,`float`),i(`adaptiveMinSamples`,G.adaptiveMinSamples,`int`),i(`adaptiveStopFraction`,G.adaptiveStopFraction,`float`),a(`usePixelFreeze`,G.usePixelFreeze),i(`pixelFreezeThreshold`,G.pixelFreezeThreshold,`float`),i(`pixelFreezeStability`,G.pixelFreezeStability,`int`),a(`convergenceOverlay`,G.convergenceOverlay),a(`enableAccumulation`,!0),i(`accumulationAlpha`,0,`float`),a(`cameraIsMoving`,!1),a(`hasPreviousAccumulated`,!1),i(`auxAccumulationAlpha`,1,`float`),a(`hasPreviousAux`,!1),i(`environmentIntensity`,G.environmentIntensity,`float`),i(`backgroundIntensity`,G.backgroundIntensity,`float`),i(`backgroundColor`,new r.Color(0,0,0),`color`),i(`backgroundBlurriness`,G.backgroundBlurriness,`float`),i(`backgroundBlurSamples`,G.backgroundBlurSamples,`int`),a(`showBackground`,G.showBackground),a(`transparentBackground`,G.transparentBackground),a(`enableEnvironment`,G.enableEnvironment),i(`environmentMatrix`,new r.Matrix4,`mat4`),i(`envTotalSum`,0,`float`),i(`envResolution`,new r.Vector2(1,1),`vec2`),a(`groundProjectionEnabled`,G.groundProjectionEnabled),i(`groundProjectionRadius`,G.groundProjectionRadius,`float`),i(`groundProjectionHeight`,G.groundProjectionHeight,`float`),i(`groundProjectionLevel`,G.groundProjectionLevel,`float`),a(`enableGroundCatcher`,G.enableGroundCatcher),i(`groundCatcherHeight`,G.groundCatcherHeight,`float`),i(`sunDirection`,new r.Vector3(0,1,0),`vec3`),i(`sunRadiance`,new r.Vector3,`vec3`),i(`sunParams`,new r.Vector4(1,0,0,0),`vec4`),a(`hasSun`,!1),i(`globalIlluminationIntensity`,G.globalIlluminationIntensity,`float`),i(`exposure`,G.exposure,`float`),i(`numDirectionalLights`,0,`int`),i(`numAreaLights`,0,`int`),i(`numPointLights`,0,`int`),i(`numSpotLights`,0,`int`),this._lightBuffers=Object.fromEntries(Object.entries(ct).map(([e,t])=>[e,(0,n.uniformArray)(new Float32Array(t*16),`float`)])),i(`cameraWorldMatrix`,new r.Matrix4,`mat4`),i(`cameraProjectionMatrixInverse`,new r.Matrix4,`mat4`),i(`cameraViewMatrix`,new r.Matrix4,`mat4`),i(`cameraProjectionMatrix`,new r.Matrix4,`mat4`);let o=([e,t])=>new r.Vector2(e,t).multiplyScalar(r.MathUtils.DEG2RAD);i(`cameraProjection`,tt[G.cameraProjection],`int`),i(`panoLonRange`,o(G.panoramaLonRange),`vec2`),i(`panoLatRange`,o(G.panoramaLatRange),`vec2`),a(`panoLevelHorizon`,G.panoramaLevelHorizon),a(`enableDOF`,G.enableDOF),i(`focusDistance`,G.focusDistance,`float`),i(`focalLength`,G.focalLength,`float`),i(`aperture`,G.aperture,`float`),i(`apertureScale`,1,`float`),i(`anamorphicRatio`,G.anamorphicRatio??1,`float`),i(`unitsPerMetre`,G.unitsPerMetre,`float`),i(`dofMode`,+(G.dofMode===`look`),`int`),i(`dofBlur`,G.dofBlur,`float`),this._uniforms.set(`samplingTechnique`,Le),Le.value=G.samplingTechnique,i(`fireflyThreshold`,G.fireflyThreshold,`float`),i(`shadowTerminatorOffset`,G.shadowTerminatorOffset,`float`),a(`enableEmissiveTriangleSampling`,G.enableEmissiveTriangleSampling),i(`emissiveBoost`,G.emissiveBoost,`float`),i(`emissiveTriangleCount`,0,`int`),i(`emissiveTotalPower`,0,`float`),i(`lightBVHNodeCount`,0,`int`),i(`emissiveVec4Offset`,0,`int`),i(`reverseMapVec4Offset`,0,`int`),i(`renderMode`,G.renderMode,`int`),a(`enableAlphaShadows`,G.enableAlphaShadows),i(`resolution`,new r.Vector2(e,t),`vec2`)}_nameAll(){for(let[e,t]of this._uniforms)t.name=st[e]||e}dispose(){this._disposed||(this._disposed=!0,this._uniforms.clear(),this._booleans.clear(),this._arrayWarned.clear(),this._lightBuffers={})}};function ft(e){return!e||!((e.transmission||0)===0&&(!(e.transparent|0)||(e.opacity??1)>=1))?0:e.alphaMode|0?2:1}function pt(e,t){return(e&_t|(t?.side??0)<<24|ft(t)<<26)>>>0}function mt(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}function ht(e){return new Uint32Array(e.buffer,e.byteOffset,e.length)}function gt(e,t){if(e>=1073741824)throw RangeError(`${t} is ${e.toLocaleString()}, at or past the BVH index limit of ${yt.toLocaleString()}. Node indices are stored as u32 bit patterns and the leaf tags occupy everything above that.`);return e}var K,_t,q,vt,yt,bt,xt,St,Ct,wt=g((()=>{K={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},_t=16777215,q={SLOTS_PER_MATERIAL:34,FLOATS_PER_MATERIAL:136,IOR:0,TRANSMISSION:1,THICKNESS:2,EMISSIVE_INTENSITY:3,ATTENUATION_COLOR:4,ATTENUATION_DISTANCE:7,OPACITY:8,SIDE:9,TRANSPARENT:10,ALPHA_TEST:11,ALPHA_MODE:12,DEPTH_WRITE:13,NORMAL_SCALE:14,COLOR:16,METALNESS:19,EMISSIVE:20,ROUGHNESS:23,ALBEDO_MAP_INDEX:24,NORMAL_MAP_INDEX:25,ROUGHNESS_MAP_INDEX:26,METALNESS_MAP_INDEX:27,EMISSIVE_MAP_INDEX:28,BUMP_MAP_INDEX:29,CLEARCOAT:30,CLEARCOAT_ROUGHNESS:31,DISPERSION:32,VISIBLE:33,SHEEN:34,SHEEN_ROUGHNESS:35,SHEEN_COLOR:36,DIFFUSE_TRANSMISSION:39,SPECULAR_INTENSITY:40,SPECULAR_COLOR:41,IRIDESCENCE:44,IRIDESCENCE_IOR:45,IRIDESCENCE_THICKNESS_RANGE:46,BUMP_SCALE:48,DISPLACEMENT_SCALE:49,DISPLACEMENT_MAP_INDEX:50,ALBEDO_TRANSFORM:52,NORMAL_TRANSFORM:60,ROUGHNESS_TRANSFORM:68,METALNESS_TRANSFORM:76,EMISSIVE_TRANSFORM:84,BUMP_TRANSFORM:92,DISPLACEMENT_TRANSFORM:100,SUBSURFACE_COLOR:108,SUBSURFACE:111,SUBSURFACE_RADIUS:112,SUBSURFACE_RADIUS_SCALE:115,SUBSURFACE_ANISOTROPY:116,ANISOTROPY:117,ANISOTROPY_ROTATION:118,ANISOTROPY_MAP_INDEX:119,TRANSMISSION_MAP_INDEX:120,CLEARCOAT_MAP_INDEX:121,CLEARCOAT_ROUGHNESS_MAP_INDEX:122,SHEEN_COLOR_MAP_INDEX:123,SHEEN_ROUGHNESS_MAP_INDEX:124,IRIDESCENCE_MAP_INDEX:125,IRIDESCENCE_THICKNESS_MAP_INDEX:126,SPECULAR_INTENSITY_MAP_INDEX:127,SPECULAR_COLOR_MAP_INDEX:128,DIFFUSE_TRANSMISSION_COLOR:129,DIFFUSE_TRANSMISSION_MAP_INDEX:132,DIFFUSE_TRANSMISSION_COLOR_MAP_INDEX:133,SLOT:{IOR_TRANSMISSION:0,ATTENUATION:1,OPACITY_ALPHA:2,ALPHA_MODE:3,COLOR_METALNESS:4,EMISSIVE_ROUGHNESS:5,MAP_INDICES_A:6,MAP_INDICES_B:7,DISPERSION_SHEEN:8,SHEEN_COLOR:9,SPECULAR:10,IRIDESCENCE:11,BUMP_DISPLACEMENT:12,ALBEDO_TRANSFORM_A:13,ALBEDO_TRANSFORM_B:14,NORMAL_TRANSFORM_A:15,NORMAL_TRANSFORM_B:16,ROUGHNESS_TRANSFORM_A:17,ROUGHNESS_TRANSFORM_B:18,METALNESS_TRANSFORM_A:19,METALNESS_TRANSFORM_B:20,EMISSIVE_TRANSFORM_A:21,EMISSIVE_TRANSFORM_B:22,BUMP_TRANSFORM_A:23,BUMP_TRANSFORM_B:24,DISPLACEMENT_TRANSFORM_A:25,DISPLACEMENT_TRANSFORM_B:26,SUBSURFACE_A:27,SUBSURFACE_B:28,SUBSURFACE_C:29,EXT_MAP_INDICES_A:30,EXT_MAP_INDICES_B:31,EXT_MAP_INDICES_C:32,EXT_MAP_INDICES_D:33}},vt=e=>Number.isFinite(e)&&e>0?e:0,yt=1073741824,bt=1073741824,xt=1073741823,St={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826},Ct=1<<27}));wt();var Tt=[1,0,0,0,1,0,0,0],Et=[[`mapMatrix`,q.ALBEDO_TRANSFORM],[`normalMapMatrices`,q.NORMAL_TRANSFORM],[`roughnessMapMatrices`,q.ROUGHNESS_TRANSFORM],[`metalnessMapMatrices`,q.METALNESS_TRANSFORM],[`emissiveMapMatrices`,q.EMISSIVE_TRANSFORM],[`bumpMapMatrices`,q.BUMP_TRANSFORM],[`displacementMapMatrices`,q.DISPLACEMENT_TRANSFORM]];Object.freeze([q.VISIBLE,q.DISPLACEMENT_MAP_INDEX+1,q.DIFFUSE_TRANSMISSION_COLOR_MAP_INDEX+1,q.DIFFUSE_TRANSMISSION_COLOR_MAP_INDEX+2]);var Dt=Object.freeze(new Set([`metalness`,`roughness`,`transmission`,`opacity`,`clearcoat`,`clearcoatRoughness`,`sheen`,`sheenRoughness`,`specularIntensity`,`iridescence`,`subsurface`,`anisotropy`,`diffuseTransmission`])),Ot=e=>Math.min(Math.max(e,0),1);function kt(e,t){let n=typeof e==`boolean`?+e:e;return Number.isFinite(n)?n:t}function At(e){return Number.isInteger(e)?e:-1}function jt(e,t,n,r){let i=n?.r??n?.[0]??n?.x,a=n?.g??n?.[1]??n?.y,o=n?.b??n?.[2]??n?.z;e[t]=kt(i,r[0]),e[t+1]=kt(a,r[1]),e[t+2]=kt(o,r[2])}function Mt(e,t,n){let r=(n,r,i)=>{e[t+n]=kt(r,i)},i=(n,r,i)=>{e[t+n]=Ot(kt(r,i))};r(q.IOR,n.ior,nt.ior),i(q.TRANSMISSION,n.transmission,nt.transmission),r(q.THICKNESS,n.thickness,nt.thickness),r(q.EMISSIVE_INTENSITY,n.emissiveIntensity,nt.emissiveIntensity),jt(e,t+q.ATTENUATION_COLOR,n.attenuationColor,nt.attenuationColor),e[t+q.ATTENUATION_DISTANCE]=vt(n.attenuationDistance??nt.attenuationDistance),i(q.OPACITY,n.opacity,nt.opacity),r(q.SIDE,n.side,nt.side),r(q.TRANSPARENT,n.transparent,nt.transparent),r(q.ALPHA_TEST,n.alphaTest,nt.alphaTest),r(q.ALPHA_MODE,n.alphaMode,nt.alphaMode),r(q.DEPTH_WRITE,n.depthWrite,nt.depthWrite);let a=n.normalScale,o=typeof a==`number`?a:void 0;r(q.NORMAL_SCALE,o??a?.x??a?.[0],nt.normalScale[0]),r(q.NORMAL_SCALE+1,o??a?.y??a?.[1],nt.normalScale[1]),jt(e,t+q.COLOR,n.color,nt.color),i(q.METALNESS,n.metalness,nt.metalness),jt(e,t+q.EMISSIVE,n.emissive,nt.emissive),i(q.ROUGHNESS,n.roughness,nt.roughness),e[t+q.ALBEDO_MAP_INDEX]=At(n.map),e[t+q.NORMAL_MAP_INDEX]=At(n.normalMap),e[t+q.ROUGHNESS_MAP_INDEX]=At(n.roughnessMap),e[t+q.METALNESS_MAP_INDEX]=At(n.metalnessMap),e[t+q.EMISSIVE_MAP_INDEX]=At(n.emissiveMap),e[t+q.BUMP_MAP_INDEX]=At(n.bumpMap),i(q.CLEARCOAT,n.clearcoat,nt.clearcoat),i(q.CLEARCOAT_ROUGHNESS,n.clearcoatRoughness,nt.clearcoatRoughness),r(q.DISPERSION,n.dispersion,nt.dispersion),i(q.SHEEN,n.sheen,nt.sheen),i(q.SHEEN_ROUGHNESS,n.sheenRoughness,nt.sheenRoughness),jt(e,t+q.SHEEN_COLOR,n.sheenColor,nt.sheenColor),i(q.DIFFUSE_TRANSMISSION,n.diffuseTransmission,nt.diffuseTransmission),i(q.SPECULAR_INTENSITY,n.specularIntensity,nt.specularIntensity),jt(e,t+q.SPECULAR_COLOR,n.specularColor,nt.specularColor),i(q.IRIDESCENCE,n.iridescence,nt.iridescence),r(q.IRIDESCENCE_IOR,n.iridescenceIOR,nt.iridescenceIOR),r(q.IRIDESCENCE_THICKNESS_RANGE,n.iridescenceThicknessRange?.[0],nt.iridescenceThicknessRange[0]),r(q.IRIDESCENCE_THICKNESS_RANGE+1,n.iridescenceThicknessRange?.[1],nt.iridescenceThicknessRange[1]),r(q.BUMP_SCALE,n.bumpScale,nt.bumpScale),r(q.DISPLACEMENT_SCALE,n.displacementScale,nt.displacementScale),e[t+q.DISPLACEMENT_MAP_INDEX]=At(n.displacementMap);for(let[r,i]of Et){let a=n[r];for(let n=0;n<8;n++)e[t+i+n]=kt(a?.[n],Tt[n])}jt(e,t+q.SUBSURFACE_COLOR,n.subsurfaceColor,nt.subsurfaceColor),i(q.SUBSURFACE,n.subsurface,nt.subsurface),jt(e,t+q.SUBSURFACE_RADIUS,n.subsurfaceRadius,nt.subsurfaceRadius),r(q.SUBSURFACE_RADIUS_SCALE,n.subsurfaceRadiusScale,nt.subsurfaceRadiusScale),r(q.SUBSURFACE_ANISOTROPY,n.subsurfaceAnisotropy,nt.subsurfaceAnisotropy),i(q.ANISOTROPY,n.anisotropy,nt.anisotropy),r(q.ANISOTROPY_ROTATION,n.anisotropyRotation,nt.anisotropyRotation),e[t+q.ANISOTROPY_MAP_INDEX]=At(n.anisotropyMap),e[t+q.TRANSMISSION_MAP_INDEX]=At(n.transmissionMap),e[t+q.CLEARCOAT_MAP_INDEX]=At(n.clearcoatMap),e[t+q.CLEARCOAT_ROUGHNESS_MAP_INDEX]=At(n.clearcoatRoughnessMap),e[t+q.SHEEN_COLOR_MAP_INDEX]=At(n.sheenColorMap),e[t+q.SHEEN_ROUGHNESS_MAP_INDEX]=At(n.sheenRoughnessMap),e[t+q.IRIDESCENCE_MAP_INDEX]=At(n.iridescenceMap),e[t+q.IRIDESCENCE_THICKNESS_MAP_INDEX]=At(n.iridescenceThicknessMap),e[t+q.SPECULAR_INTENSITY_MAP_INDEX]=At(n.specularIntensityMap),e[t+q.SPECULAR_COLOR_MAP_INDEX]=At(n.specularColorMap),jt(e,t+q.DIFFUSE_TRANSMISSION_COLOR,n.diffuseTransmissionColor,nt.diffuseTransmissionColor),e[t+q.DIFFUSE_TRANSMISSION_MAP_INDEX]=At(n.diffuseTransmissionMap),e[t+q.DIFFUSE_TRANSMISSION_COLOR_MAP_INDEX]=At(n.diffuseTransmissionColorMap),e[t+q.VISIBLE]=1,e[t+q.DISPLACEMENT_MAP_INDEX+1]=0,e[t+q.DIFFUSE_TRANSMISSION_COLOR_MAP_INDEX+1]=0,e[t+q.DIFFUSE_TRANSMISSION_COLOR_MAP_INDEX+2]=0}var Nt={VEC4_PER_BVH_NODE:4,FLOATS_PER_VEC4:4,MIN_TEXTURE_WIDTH:4,MAX_CONCURRENT_WORKERS:Math.min(typeof navigator<`u`&&navigator.hardwareConcurrency||4,6),BUFFER_POOL_SIZE:20,CANVAS_POOL_SIZE:12,CACHE_SIZE_LIMIT:50,MAX_TEXTURE_SIZE:8192,DEFAULT_MAX_TEXTURE_SIZE:4096,MAX_TEXTURES_LIMIT:4*256,MATERIAL_BUCKET_COUNT:4,BUCKET_LAYER_STRIDE:256},Pt=64;function Ft(e,t){let n=Math.ceil(Math.max(1,e)/Pt)*Pt;return Math.min(t,Math.max(Nt.MIN_TEXTURE_WIDTH,n))}function It(e){let t=0,n=0,r=0;for(let i of e)t=Math.max(t,i.width),n=Math.max(n,i.height),r+=i.count;return{units:e,width:t,height:n,count:r}}function J(e,t){return Ft(e.width,t)*e.height*e.count*4}function Lt(e,t){return e.reduce((e,n)=>e+J(n,t),0)}function Rt(e,t,n){let r=e.slice();for(;r.length>t;){let e=null;for(let t=0;t<r.length;t++)for(let i=t+1;i<r.length;i++){let a=It(r[t].units.concat(r[i].units)),o=J(a,n)-J(r[t],n)-J(r[i],n);(!e||o<e.delta)&&(e={i:t,j:i,delta:o,fused:a})}r=r.filter((t,n)=>n!==e.i&&n!==e.j).concat([e.fused])}return r}function zt(e,t,n){let r=[];for(let e=t-1;e>=0;e--)r.push(Math.max(Nt.MIN_TEXTURE_WIDTH,Math.round(n/2**e)));let i=r.map(()=>[]);for(let t of e){let e=2**Math.ceil(Math.log2(Math.max(t.width,t.height))),n=r.findIndex(t=>e<=t);n<0&&(n=r.length-1),i[n].push(t)}return i.filter(e=>e.length).map(It)}function Bt(e,t){let n=e;for(let e=0;e<8;e++){let e=!1;for(let r of n.flatMap(e=>e.units)){let i=n.findIndex(e=>e.units.includes(r));if(!(i<0))for(let a=0;a<n.length;a++){if(a===i)continue;let o=[];for(let e=0;e<n.length;e++)if(e===i){let t=n[e].units.filter(e=>e!==r);t.length&&o.push(It(t))}else e===a?o.push(It(n[e].units.concat([r]))):o.push(n[e]);if(Lt(o,t)<Lt(n,t)){n=o,e=!0;break}}}if(!e)break}return n}function Vt(e,t,n=Nt.MATERIAL_BUCKET_COUNT){let r=new Map;for(let{width:n,height:i}of e){let e=Math.min(t,Math.max(1,n||1)),a=Math.min(t,Math.max(1,i||1)),o=`${e}x${a}`,s=r.get(o);s?s.count++:r.set(o,{width:e,height:a,count:1})}let i=[...r.values()],a=i.map(e=>It([e]));if(a.length>n){let e=zt(i,n,t),r=Rt(a,n,t);a=Lt(e,t)<Lt(r,t)?e:r,a=Bt(a,t)}return a.map(e=>({width:Ft(e.width,t),height:e.height})).sort((e,t)=>e.width*e.height-t.width*t.height)}function Ht(e,t,n){let r=Math.max(1,e||1),i=Math.max(1,t||1);for(let e=0;e<n.length;e++)if(n[e].width>=r&&n[e].height>=i)return e;return Math.max(0,n.length-1)}function Ut(e,t){return e*Nt.BUCKET_LAYER_STRIDE+t}var Y,Wt,Gt,Kt,X=g((()=>{Y=Object.freeze({ADAPTER_SOFTWARE:`adapter.software`,ASSET_UNREACHABLE:`asset.unreachable`,ASSET_AMBIGUOUS_ENTRY:`asset.ambiguous_entry`,ASSET_ARCHIVE_TOO_LARGE:`asset.archive_too_large`,ASSET_ENTRY_TOO_LARGE:`asset.entry_too_large`,TEXTURE_BUILD_FAILED:`texture.build_failed`,TEXTURE_PROCESSING_FALLBACK:`texture.processing_fallback`,TEXTURE_LIMIT_EXCEEDED:`texture.limit_exceeded`,ENVIRONMENT_LOAD_FAILED:`environment.load_failed`,SETTING_UNKNOWN_KEY:`setting.unknown_key`,RENDER_SIZE_DECLINED:`render.size_declined`,STAGE_RENDER_FAILED:`stage.render_failed`,RENDER_RESERVE_CAPPED:`render.reserve_capped`,SCENE_MEMORY_BUDGET:`scene.memory_budget`,EMISSIVE_INSTANCES_COLLAPSED:`emissive.instances_collapsed`,REFIT_SHARED_GEOMETRY:`refit.shared_geometry`,VIEW_TRANSFORM_DISPLAY_MISMATCH:`viewTransform.display_mismatch`,VIEW_TRANSFORM_BAKE_FAILED:`viewTransform.bake_failed`,COLOR_CONFIG_LOAD_FAILED:`color.config_load_failed`,STORAGE_UNAVAILABLE:`storage.unavailable`,STORAGE_QUOTA_EXCEEDED:`storage.quota_exceeded`,STORAGE_WRITE_FAILED:`storage.write_failed`,STORAGE_READ_FAILED:`storage.read_failed`,STORAGE_ENTRY_CORRUPT:`storage.entry_corrupt`,STORAGE_CACHE_MISMATCH:`storage.cache_mismatch`,DENOISER_UNAVAILABLE:`denoiser.unavailable`,OUTPUT_SOURCE_FALLBACK:`output.source_fallback`,OUTPUT_TONEMAP_FALLBACK:`output.tonemap_fallback`,LIGHT_PLACEHOLDER_SKIPPED:`light.placeholder_skipped`,CAPABILITY_MISSING:`capability.missing`}),Wt=Object.freeze({ERROR:`error`,WARNING:`warning`}),Gt=class extends Error{constructor(e){super(`[${e.code}] ${e.message}`),this.name=`EngineIssueError`,this.code=e.code,this.detail=e.detail}},Kt=class{constructor({strict:e=!1,onIssue:t=null}={}){this.strict=e===!0,this._onIssue=t,this._entries=[]}record(e,t,n={},r=Wt.ERROR){let i=Object.freeze({code:e,message:t,detail:n,severity:r,at:Date.now()});if(this._entries.push(i),this._onIssue?.(i),this.strict&&r===Wt.ERROR)throw new Gt(i);return i}warn(e,t,n){return this.record(e,t,n,Wt.WARNING)}get list(){return this._entries.slice()}get errors(){return this._entries.filter(e=>e.severity===Wt.ERROR)}clear(){this._entries.length=0}detach(){this._onIssue=null,this.strict=!1}}}));function qt(e){Zt=e}function Jt(e,t,n){let r=n?new e(new SharedArrayBuffer(t*e.BYTES_PER_ELEMENT)):new e(t);return Zt&&r.byteLength>0&&Zt(r.byteLength,n),r}var Yt,Xt,Zt,Qt,$t=g((()=>{Yt=64*1024*1024,Xt=typeof SharedArrayBuffer<`u`,Zt=null,Qt=class e{constructor(e,t,n,r=Yt,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(Jt(n,e*t,i)),s-=e}this.chunks.length===0&&this.chunks.push(Jt(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=Yt,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]=Jt(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=await this._store.read(e,t*this.LaneType.BYTES_PER_ELEMENT),r=Jt(this.LaneType,t,this.shared);new Uint8Array(r.buffer,r.byteOffset,r.byteLength).set(new Uint8Array(n)),this.chunks[e]=r;for(let t of this._liveViews())t.chunks[e]=new t.LaneType(r.buffer,r.byteOffset,r.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=Jt(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}}})),en,tn,nn=g((()=>{en=Object.freeze({CACHE:`cache`,USER:`user`,SCRATCH:`scratch`}),tn=Object.freeze({DOWNLOADS:`downloads`,ARCHIVES:`archives`,SCENES:`scenes`,CDF:`cdf`,SPILL:`spill`})}));X(),$t(),nn();var rn=32*1024*1024,an=`chunks.bin`,on=class e{static async create(t,n,r,{label:i=``,expectedBytes:a=0}={}){let o=t?.area(tn.SPILL),s=await o?.create(n,{label:i,expectedBytes:a,growable:[an]});return s?new e(o,n,r,s):null}constructor(e,t,n,r){this._area=e,this._key=t,this._chunkBytes=n,this._writer=r,this._entry=null,this._file=null}write(e,t){return this.writeAt(e*this._chunkBytes,t)}async writeAt(e,t){if(!this._writer&&(this._entry?.release(),this._entry=this._file=null,this._writer=await this._area.edit(this._key),!this._writer))throw Error(`spill: its storage entry is gone`);let n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),r=0;do await this._writer.write(an,n.subarray(r,Math.min(n.length,r+rn)),{at:e+r}),r+=rn;while(r<n.length)}async flush(){if(this._writer&&=(await this._writer.commit(),null),!this._entry&&(this._entry=await this._area.open(this._key,{wait:!0}),this._file=await this._entry?.file(an),!this._file))throw Error(`spill: its storage entry is gone`)}read(e,t){return this.readAt(e*this._chunkBytes,t)}async readAt(e,t){return await this.flush(),await this._file.slice(e,e+t).arrayBuffer()}async dispose(){this._writer&&await this._writer.abort(),this._writer=null,this._entry?.release(),this._entry=this._file=null,await this._area.remove(this._key)}},sn=32*1024*1024,cn=sn/4,ln=64*1024*1024,un=new Map;function dn(e){let t=un.get(e);return t||un.set(e,t=new e(0)),t}var fn=class e{static async create(t,n,r=0){let i=await on.create(t,n,0,{label:`Scene geometry (while building)`,expectedBytes:r});return i?new e(i):null}static canTake(e){if(Object.keys(e.morphAttributes??{}).length)return!1;for(let t in e.attributes)if(!e.attributes[t].isBufferAttribute)return!1;return!e.index||e.index.isBufferAttribute===!0}constructor(e){this._store=e,this._records=[],this._geometries=[],this._end=0,this._pack=null,this._packAt=0,this._packUsed=0,this._packRecords=[],this._chain=Promise.resolve(),this._queued=0,this.bytes=0,this.error=null}get queuedBytes(){return this._queued}add(e){let t=new Map,n=Object.values(e.attributes);e.index&&n.push(e.index);for(let e of n){let n=e.array;if(!n?.byteLength)continue;let r=t.get(n);r||t.set(n,r=this._write(n)),r.attributes.push(e),e.array=dn(n.constructor)}this._geometries.push({geometry:e,box:e.boundingBox!==null,sphere:e.boundingSphere!==null})}_write(e){let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n={at:0,byteLength:t.byteLength,Type:e.constructor,attributes:[],array:null,pack:null,offset:0};return this._records.push(n),this.bytes+=t.byteLength,t.byteLength>=cn?(n.at=this._end,n.array=e,this._end+=t.byteLength,this._queue(n.at,t,[n]),n):(this._pack&&this._packUsed+t.byteLength>sn&&this._flushPack(),this._pack||(this._pack=new Uint8Array(sn),this._packAt=this._end,this._packUsed=0,this._end+=sn),this._pack.set(t,this._packUsed),n.at=this._packAt+this._packUsed,n.pack=this._pack,n.offset=this._packUsed,this._packUsed+=t.byteLength,this._packRecords.push(n),n)}_flushPack(){this._pack&&(this._queue(this._packAt,this._pack.subarray(0,this._packUsed),this._packRecords),this._pack=null,this._packRecords=[])}_queue(e,t,n){this._queued+=t.byteLength,this._chain=this._chain.then(async()=>{if(!this.error){await this._store.writeAt(e,t);for(let e of n)e.array=e.pack=null}}).catch(e=>void(this.error??=e)).finally(()=>void(this._queued-=t.byteLength))}written(){return this._flushPack(),this._chain}async restore(){await this.written();let e=this._records.sort((e,t)=>e.at-t.at);e.some(e=>!e.array&&!e.pack)&&await this._store.flush();let t=null,n=0;for(let r of e){let e;if(r.array?e=r.array:r.pack?e=new r.Type(r.pack.slice(r.offset,r.offset+r.byteLength).buffer):r.byteLength>ln?e=new r.Type(await this._store.readAt(r.at,r.byteLength)):((!t||r.at+r.byteLength>n+t.byteLength)&&(n=r.at,t=await this._store.readAt(r.at,ln)),e=new r.Type(t.slice(r.at-n,r.at-n+r.byteLength))),e.byteLength!==r.byteLength)throw Error(`geometry spill: an array came back short`);for(let t of r.attributes)t.array=e}for(let{geometry:e,box:t,sphere:n}of this._geometries)t||(e.boundingBox=null),n||(e.boundingSphere=null);this._records=[],this._geometries=[],this.bytes=0}async dispose(){await this._chain,this._records=[],this._geometries=[],this._pack=null,this._packRecords=[],await this._store.dispose()}};wt(),Ae();var pn=ye(`geometry`),mn=Nt.MAX_TEXTURES_LIMIT,hn=new Set([`color`,`emissive`,`attenuationColor`,`sheenColor`,`specularColor`,`subsurfaceColor`,`diffuseTransmissionColor`]),gn=Object.freeze({MATERIAL:`material`,MAPPED:`mapped`,DEFAULT:`default`,HOST:`host`}),_n=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function vn(e){for(let t=0;t<16;t++)if(e[t]!==_n[t])return!1;return!0}function yn(e){return{map:e.map,normalMap:e.normalMap,bumpMap:e.bumpMap,roughnessMap:e.roughnessMap,metalnessMap:e.metalnessMap,emissiveMap:e.emissiveMap??(e.isMeshBasicMaterial?e.map:void 0),displacementMap:e.displacementMap,anisotropyMap:e.anisotropyMap,clearcoatMap:e.clearcoatMap,clearcoatRoughnessMap:e.clearcoatRoughnessMap,transmissionMap:e.transmissionMap,sheenColorMap:e.sheenColorMap,sheenRoughnessMap:e.sheenRoughnessMap,specularIntensityMap:e.specularIntensityMap,specularColorMap:e.specularColorMap,diffuseTransmissionMap:e.diffuseTransmissionMap,diffuseTransmissionColorMap:e.diffuseTransmissionColorMap,iridescenceMap:e.iridescenceMap,iridescenceThicknessMap:e.iridescenceThicknessMap}}function bn(e){if(e.userData?.gltfExtensions?.KHR_materials_unlit?.alphaMode){let t=e.userData.gltfExtensions.KHR_materials_unlit.alphaMode;return t===`BLEND`?2:+(t===`MASK`)}return e.alphaTest>0?1:e.transparent&&e.opacity<1||e.map&&e.map.format===r.RGBAFormat&&e.transparent?2:0}function xn(e){let t=0,n=new Set,r=e=>{let i=e.isMesh&&e.material?e.geometry:null;if(i&&!n.has(i.uuid)){n.add(i.uuid);for(let e in i.attributes)t+=i.attributes[e].array?.byteLength??0;t+=i.index?.array?.byteLength??0}if(e.children)for(let t of e.children)r(t)};return r(e),t}function Sn(e,t){let n=e.x,r=e.y,i=e.z;e.x=t[0]*n+t[4]*r+t[8]*i+t[12],e.y=t[1]*n+t[5]*r+t[9]*i+t[13],e.z=t[2]*n+t[6]*r+t[10]*i+t[14]}function Cn(e,t){let n=e.x,r=e.y,i=e.z;e.x=t[0]*n+t[3]*r+t[6]*i,e.y=t[1]*n+t[4]*r+t[7]*i,e.z=t[2]*n+t[5]*r+t[8]*i}var wn=1<<21;function Tn(e){return!!(e.isSkinnedMesh||Object.keys(e.geometry?.morphAttributes??{}).length)}function En(e){return e[0]*(e[5]*e[10]-e[9]*e[6])-e[4]*(e[1]*e[10]-e[9]*e[2])+e[8]*(e[1]*e[6]-e[5]*e[2])}var Dn=class{constructor({issues:e=null}={}){this._issues=e,this._droppedTextures=0,this._vectorPool={vec3:Array(9).fill().map(()=>new r.Vector3),vec2:[,,,,,,].fill().map(()=>new r.Vector2)},this._geometryRanges=new Map,this.expandedTriangleCount=0,this._allocatePlacements(0),this._matrixPool={mat3:new r.Matrix3,mat4:new r.Matrix4},this.resetArrays(),this.triangleCount=0,this.currentTriangleIndex=0}_getVec3(e=0){return this._vectorPool.vec3[e%this._vectorPool.vec3.length]}_getVec2(e=0){return this._vectorPool.vec2[e%this._vectorPool.vec2.length]}extract(e){this.resetArrays();let t=this._countTriangles(e);return this._triangleCapacity=Math.max(1024,t),this._allocateTriangles(this._triangleCapacity),this.currentTriangleIndex=0,this._allocatePlacements(this._countPlacements(e)),this._geometryUses=this._countGeometryUses(e),this.bakeInverse=new Map,this.traverseObject(e),this._shareInstanceMatrices(),this._compressAttributes(e),this.logStats(),this.getExtractedData()}async extractStreaming(e,{onStore:t,onRange:n,pause:r,yieldEvery:i=1<<20,releaseGeometry:a=null}){this.resetArrays(),this._triangleCapacity=Math.max(1,this._countStoredTriangles(e)),this._allocateTriangles(this._triangleCapacity,!0),t?.(this.triangles),this.currentTriangleIndex=0,this._allocatePlacements(this._countPlacements(e)),this._geometryUses=this._countGeometryUses(e),this.bakeInverse=new Map,this._onRange=n,this._releaseAfterRead=a?this._geometryReleaser(e,a):null;try{let t=[e],n=0;for(;t.length;){let e=t.pop();if(this._visit(e),e.children)for(let n=e.children.length-1;n>=0;n--)t.push(e.children[n]);this.currentTriangleIndex-n>=i&&(n=this.currentTriangleIndex,await r(this.currentTriangleIndex))}}finally{this._onRange=null,this._releaseAfterRead=null}return this._shareInstanceMatrices(),this._compressAttributes(e),this.triangles.trimInPlace(this.currentTriangleIndex),this._streamedStore=!0,this.logStats(),this.getExtractedData()}_countStoredTriangles(e){let t=new Set,n=0,r=e=>{if(e.isMesh&&e.geometry&&e.material){let r=e.geometry,i=Math.ceil((r.index?r.index.count:r.attributes.position?.count??0)/3),a=Array.isArray(e.material)?e.material[0]:e.material,o=a?.emissive,s=a?.emissiveIntensity>0&&!!o&&(o.r>0||o.g>0||o.b>0),c=e.isInstancedMesh?e.count??0:1;if(s&&e.isInstancedMesh&&!Tn(e)&&i*c<=wn)n+=i*c;else if(s||Tn(e))n+=i;else{let e=`${r.uuid}|${a?.uuid}`;t.has(e)||(t.add(e),n+=i)}}if(e.children)for(let t of e.children)r(t)};return r(e),n}_geometryReleaser(e,t){let n=new Map,r=new Map,i=new Set,a=(e,t)=>{t||=!!e.userData?.__rayzeeExternal;let o=e.isMesh&&e.material?e.geometry:null;if(o){if(!n.has(o)){fn.canTake(o)||i.add(o);for(let e of[...Object.values(o.attributes),o.index]){let t=e?.array;if(!t)continue;let n=r.get(t);n&&n!==o?i.add(o).add(n):r.set(t,o)}}n.set(o,(n.get(o)??0)+1),(t||Tn(e))&&i.add(o)}if(e.children)for(let n of e.children)a(n,t)};return a(e,!1),e=>{let r=e.material?e.geometry:null;if(!r||!n.has(r))return;let a=n.get(r)-1;if(a>0)return void n.set(r,a);n.delete(r),!i.has(r)&&(this._compressGeometry(r),t(r))}}surveyScene(e){let t=0,n=e=>{if(e.isMesh&&e.geometry&&e.material&&t++,e.children)for(let t of e.children)n(t)};return n(e),{triangles:this._countTriangles(e),placements:this._countPlacements(e),meshes:t,geometryBytes:xn(e)}}_countGeometryUses(e){let t=new Map;return e.traverse(e=>{if(!e.isMesh||!e.geometry||!e.material)return;let n=`${e.geometry.uuid}|${e.material.uuid}`;t.set(n,(t.get(n)??0)+1)}),t}_countPlacements(e){let t=0;if(e.isMesh&&e.geometry&&e.material&&(t+=e.isInstancedMesh&&e.instanceMatrix?e.count??e.instanceMatrix.array.length/16:1),e.children)for(let n of e.children)t+=this._countPlacements(n);return t}_allocatePlacements(e){this.instanceCount=0,this.instanceCapacity=e,this.instanceSource=new Int32Array(e),this.instanceMatrices=new Float32Array(e*16),this._shareable=[],this._compressed=new Set}_compressAttributes(e){let t=(e,n)=>{if(!e.userData?.__rayzeeExternal){n(e);for(let r of e.children)t(r,n)}};t(e,e=>{e.isMesh&&e.geometry&&this._compressGeometry(e.geometry)})}_compressGeometry(e){if(!this._compressed.has(e.uuid)){this._compressed.add(e.uuid);for(let t of[`normal`,`tangent`,`color`]){let n=e.getAttribute(t);if(!n||n.normalized||!(n.array instanceof Float32Array)||e.morphAttributes?.[t]?.length)continue;let i=n.array,a=!0;for(let e=0;e<i.length;e++){let t=i[e];if(!(t>=-1.0001&&t<=1.0001)){a=!1;break}}if(!a)continue;let o=new Int16Array(i.length);for(let e=0;e<i.length;e++)o[e]=Math.round(Math.max(-1,Math.min(1,i[e]))*32767);e.setAttribute(t,new r.BufferAttribute(o,n.itemSize,!0))}}}_shareInstanceMatrices(){for(let{mesh:e,start:t,count:n}of this._shareable){let r=e.instanceMatrix;!r||r.array.length!==n*16||(r.array=this.instanceMatrices.subarray(t*16,(t+n)*16))}this._shareable=[]}_countTriangles(e){let t=0;if(e.isMesh&&e.geometry&&e.material){let n=e.geometry.index,r=e.geometry.attributes.position;n?t+=Math.ceil(n.count/3):r&&(t+=Math.ceil(r.count/3))}if(e.children)for(let n of e.children)t+=this._countTriangles(n);return t}_ensureCapacity(e){if(e<=this._triangleCapacity)return;if(this._onRange){this.triangles.grow(e),this._triangleCapacity=e;return}let t=this.triangles,n=this.currentTriangleIndex;this._allocateTriangles(e);for(let e=0;e<n;e++)this.triangles.chunkFor(e).set(t.chunkFor(e).subarray(t.baseOf(e),t.baseOf(e)+t.lanesPerRecord),this.triangles.baseOf(e));this._triangleCapacity=e}_allocateTriangles(e,t=!1){this.triangles=(t?Qt.lazy:(...e)=>new Qt(...e))(e,K.FLOATS_PER_TRIANGLE,Uint32Array,void 0,Xt),this.triangleFloatChunks=this.triangles.viewAs(Float32Array),this.triangleData=this.triangles.single,this.triangleFloats=this.triangleFloatChunks.single}traverseObject(e){if(this._visit(e),e.children)for(let t of e.children)this.traverseObject(t)}_visit(e){e.isMesh?(this.processMesh(e),this._releaseAfterRead?.(e)):e.isDirectionalLight?this.directionalLights.push(e):e.isCamera&&this.cameras.push(e)}processMesh(e){if(!e.geometry||!e.material){console.warn(`Skipping mesh with missing geometry or material:`,e);return}let t=this.processMaterial(e.material);e.userData.materialIndex=t;let n=this.meshes.length;this.meshes.push(e),e.userData.meshIndex=n;let r=`${e.geometry.uuid}|${t}`,i=Tn(e),a=!this._emissiveMaterial(t)&&!i,o=a?this._geometryRanges.get(r):null;if(o){let t={start:o.start,count:o.count,expandedStart:this.expandedTriangleCount,sharedFrom:o.meshIndex};this.expandedTriangleCount+=o.count,this.meshTriangleRanges.push(t),this._recordPlacements(e,n);return}let s=this.currentTriangleIndex,c=e.isInstancedMesh&&!i&&this._emissiveMaterial(t)&&this._canExpand(e),l=c||!e.isInstancedMesh&&!i&&(this._geometryUses.get(`${e.geometry.uuid}|${e.material?.uuid}`)===1||this._emissiveMaterial(t));this.extractGeometry(e,t,n,l,c);let u={start:s,count:this.currentTriangleIndex-s,expandedStart:this.expandedTriangleCount};this.expandedTriangleCount+=u.count,this.meshTriangleRanges.push(u),u.count>0&&!l&&a&&this._geometryRanges.set(r,{...u,meshIndex:n}),this._recordPlacements(e,n,l,c),u.count>0&&this._onRange?.(n,u)}_recordPlacements(e,t,n=!1,r=!1){let i=e.matrixWorld.elements,a=this.instanceMatrices,o=this.instanceSource;if(!e.isInstancedMesh||!e.instanceMatrix||r){let r=this._nextPlacement();if(o[r]=t,n){for(let e=0;e<16;e++)a[r*16+e]=+(e%5==0);this.bakeInverse.set(t,Float32Array.from(this._matrixPool.mat4.copy(e.matrixWorld).invert().elements))}else for(let e=0;e<16;e++)a[r*16+e]=i[e];return}let s=e.instanceMatrix.array,c=e.count??s.length/16,l=vn(i);l&&s.length===c*16&&this._shareable.push({mesh:e,start:this.instanceCount,count:c});for(let e=0;e<c;e++){let n=e*16,r=this._nextPlacement(),c=r*16;if(o[r]=t,l){for(let e=0;e<16;e++)a[c+e]=s[n+e];continue}for(let e=0;e<4;e++)for(let t=0;t<4;t++)a[c+e*4+t]=i[t]*s[n+e*4]+i[4+t]*s[n+e*4+1]+i[8+t]*s[n+e*4+2]+i[12+t]*s[n+e*4+3]}}_nextPlacement(){if(this.instanceCount>=this.instanceCapacity){let e=Math.max(16,this.instanceCapacity*2),t=new Int32Array(e),n=new Float32Array(e*16);t.set(this.instanceSource),n.set(this.instanceMatrices),this.instanceSource=t,this.instanceMatrices=n,this.instanceCapacity=e}return this.instanceCount++}_canExpand(e){let t=e.geometry,n=(t.index?t.index.count:t.attributes.position.count)/3,r=e.count??(e.instanceMatrix?.array.length??0)/16;return n*r<=wn?!0:(this._issues?.record(Y.EMISSIVE_INSTANCES_COLLAPSED,`"${e.name||`instanced mesh`}" would need ${Math.round(n*r).toLocaleString()} triangles to light every instance; lighting the first one only`,{instances:r,trianglesPerInstance:n,limit:wn}),!1)}_emissiveMaterial(e){let t=this.materials[e];if(!t||!(t.emissiveIntensity>0))return!1;let n=t.emissive;return!!n&&(n.r>0||n.g>0||n.b>0)}processMaterial(e){let t=this._materialUuidMap.get(e.uuid)??-1;if(t===-1){e.depthWrite===!1&&(e.depthWrite=!0,B(pn,`depthWrite`,`material had depthWrite disabled — enabled for rastered rendering`));let n=this.createMaterialObject(e);this.materials.push(n),t=this.materials.length-1,this._materialUuidMap.set(e.uuid,t)}return t}getMaterialType(e){return e.isMeshPhysicalMaterial?`physical`:e.isMeshStandardMaterial?`standard`:e.isMeshPhongMaterial?`phong`:e.isMeshLambertMaterial?`lambert`:e.isMeshBasicMaterial?`basic`:e.isMeshToonMaterial?`toon`:`unknown`}getPhysicalDefaults(){let e={};for(let[t,n]of Object.entries(nt))e[t]=hn.has(t)?new r.Color().fromArray(n):Array.isArray(n)?[...n]:n;return e.normalScale={x:nt.normalScale[0],y:nt.normalScale[1]},e}mapLegacyMaterialToPhysical(e,t){let n={};switch(t){case`basic`:n.emissive=e.color.clone(),n.emissiveIntensity=1,n.color=new r.Color(0),n.roughness=1,n.metalness=0,n.specularIntensity=0;break;case`lambert`:n.roughness=1,n.metalness=0,n.specularIntensity=0;break;case`phong`:{let t=e.shininess||30;n.roughness=Math.sqrt(2/(t+2)),n.metalness=0}if(e.specular){let t=e.specular,i=t.r*.299+t.g*.587+t.b*.114,a=Math.max(t.r,t.g,t.b);n.specularIntensity=Math.min(i*2,1),n.specularColor=a>0?t.clone().multiplyScalar(1/a):new r.Color(1,1,1)}break;case`toon`:n.roughness=.9,n.metalness=0;break;case`standard`:case`physical`:break}return n}createMaterialObject(e){let t=this.getPhysicalDefaults(),n=this.getMaterialType(e),r=this.mapLegacyMaterialToPhysical(e,n),i=yn(e),a={},o=n=>r[n]===void 0?e[n]!==void 0&&e[n]!==null?(a[n]=gn.MATERIAL,e[n]):(a[n]=gn.DEFAULT,t[n]):(a[n]=gn.MAPPED,r[n]);for(let e of[`transparent`,`alphaMode`,`side`,`depthWrite`])a[e]=gn.MATERIAL;return{uuid:e.uuid,color:o(`color`),emissive:o(`emissive`),emissiveIntensity:o(`emissiveIntensity`),roughness:Math.max(.02,o(`roughness`)),metalness:o(`metalness`),ior:o(`ior`),opacity:o(`opacity`),transmission:o(`transmission`),thickness:o(`thickness`),attenuationColor:o(`attenuationColor`),attenuationDistance:o(`attenuationDistance`),dispersion:o(`dispersion`),sheen:o(`sheen`),sheenRoughness:o(`sheenRoughness`),sheenColor:o(`sheenColor`),clearcoat:o(`clearcoat`),clearcoatRoughness:o(`clearcoatRoughness`),iridescence:o(`iridescence`),iridescenceIOR:o(`iridescenceIOR`),iridescenceThicknessRange:o(`iridescenceThicknessRange`),subsurface:o(`subsurface`),subsurfaceColor:o(`subsurfaceColor`),subsurfaceRadius:o(`subsurfaceRadius`),subsurfaceRadiusScale:o(`subsurfaceRadiusScale`),subsurfaceAnisotropy:o(`subsurfaceAnisotropy`),anisotropy:o(`anisotropy`),anisotropyRotation:o(`anisotropyRotation`),specularIntensity:o(`specularIntensity`),specularColor:o(`specularColor`),diffuseTransmission:o(`diffuseTransmission`),diffuseTransmissionColor:o(`diffuseTransmissionColor`),normalScale:o(`normalScale`),bumpScale:o(`bumpScale`),displacementScale:o(`displacementScale`),transparent:+!!e.transparent,alphaTest:o(`alphaTest`),alphaMode:bn(e),side:this.getMaterialSide(e),depthWrite:e.depthWrite??!0?1:0,map:this.processTexture(i.map,this.maps),normalMap:this.processTexture(i.normalMap,this.normalMaps),bumpMap:this.processTexture(i.bumpMap,this.bumpMaps),roughnessMap:this.processTexture(i.roughnessMap,this.roughnessMaps),metalnessMap:this.processTexture(i.metalnessMap,this.metalnessMaps),emissiveMap:this.processTexture(i.emissiveMap,this.emissiveMaps),displacementMap:this.processTexture(i.displacementMap,this.displacementMaps),anisotropyMap:this.processTexture(i.anisotropyMap,this.anisotropyMaps),clearcoatMap:this.processTexture(i.clearcoatMap,this.clearcoatMaps),clearcoatRoughnessMap:this.processTexture(i.clearcoatRoughnessMap,this.clearcoatRoughnessMaps),transmissionMap:this.processTexture(i.transmissionMap,this.transmissionMaps),thicknessMap:this.processTexture(e.thicknessMap,[]),sheenColorMap:this.processTexture(i.sheenColorMap,this.sheenColorMaps),sheenRoughnessMap:this.processTexture(i.sheenRoughnessMap,this.sheenRoughnessMaps),specularIntensityMap:this.processTexture(i.specularIntensityMap,this.specularIntensityMaps),specularColorMap:this.processTexture(i.specularColorMap,this.specularColorMaps),diffuseTransmissionMap:this.processTexture(i.diffuseTransmissionMap,this.diffuseTransmissionMaps),diffuseTransmissionColorMap:this.processTexture(i.diffuseTransmissionColorMap,this.diffuseTransmissionColorMaps),iridescenceMap:this.processTexture(i.iridescenceMap,this.iridescenceMaps),iridescenceThicknessMap:this.processTexture(i.iridescenceThicknessMap,this.iridescenceThicknessMaps),mapMatrix:this.getTextureMatrix(i.map),normalMapMatrices:this.getTextureMatrix(i.normalMap),bumpMapMatrices:this.getTextureMatrix(i.bumpMap),roughnessMapMatrices:this.getTextureMatrix(i.roughnessMap),metalnessMapMatrices:this.getTextureMatrix(i.metalnessMap),emissiveMapMatrices:this.getTextureMatrix(i.emissiveMap),displacementMapMatrices:this.getTextureMatrix(i.displacementMap),sources:a,originalType:n}}getTextureMatrix(e){return e?(e.matrixAutoUpdate&&e.updateMatrix(),e.matrix.elements):new r.Matrix3().elements}getMaterialSide(e){if(e.transmission>0)return 2;switch(e.side){case r.FrontSide:return 0;case r.BackSide:return 1;case r.DoubleSide:return 2;default:return 0}}processTexture(e,t){if(!e)return-1;let n=this._textureIndexCache.get(t);n||(n=new Map,this._textureIndexCache.set(t,n));let r=e.source.uuid,i=n.get(r);if(i!==void 0)return i;if(t.length<mn){t.push(e);let i=t.length-1;return n.set(r,i),i}return this._droppedTextures++,this._droppedTextures===1&&this._issues?.record(Y.TEXTURE_LIMIT_EXCEEDED,`scene needs more than ${mn} distinct textures for one map type; the rest render untextured`,{limit:mn,firstDropped:e.name||e.source?.uuid}),-1}extractGeometry(e,t,n,i=!1,a=!1){e.updateMatrix(),e.updateMatrixWorld();let o=e.geometry;o.attributes.normal||o.computeVertexNormals();let s=o.attributes.position,c=o.attributes.normal,l=o.attributes.uv,u=o.index?o.index.array:null,d=u?u.length/3:s.count/3;if(a){let i=e.count??e.instanceMatrix.array.length/16,a=this._matrixPool.mat4,o=new r.Matrix4;for(let f=0;f<i;f++){a.fromArray(e.instanceMatrix.array,f*16),o.multiplyMatrices(e.matrixWorld,a);let i=new r.Matrix3().getNormalMatrix(o);this.extractTrianglesInBatch(s,c,l,u,d,t,n,o,i,En(o.elements)<0)}return}let f=i?this._matrixPool.mat4.copy(e.matrixWorld):null,p=i?this._matrixPool.mat3.getNormalMatrix(e.matrixWorld):null,m=i&&En(f.elements)<0;this.extractTrianglesInBatch(s,c,l,u,d,t,n,f,p,m)}extractTrianglesInBatch(e,t,n,r,i,a,o,s=null,c=null,l=!1){for(;this.materialTriangleCounts.length<=a;)this.materialTriangleCounts.push(0);this.materialTriangleCounts[a]+=i;let u=this._getVec3(0),d=this._getVec3(1),f=this._getVec3(2),p=this._getVec3(3),m=this._getVec3(4),h=this._getVec3(5),g=this._getVec2(0),_=this._getVec2(1),v=this._getVec2(2);this._ensureCapacity(this.currentTriangleIndex+i);let y=s?.elements,b=c?.elements;for(let c=0;c<i;c++){let i=c*3,x=r?r[i+0]:i+0,S=l?2:1,C=l?1:2,w=r?r[i+S]:i+S,T=r?r[i+C]:i+C;this.getVertex(e,x,u),this.getVertex(e,w,d),this.getVertex(e,T,f),this.getVertex(t,x,p),this.getVertex(t,w,m),this.getVertex(t,T,h),n?(this.getVertex(n,x,g),this.getVertex(n,w,_),this.getVertex(n,T,v)):(g.set(0,0),_.set(0,0),v.set(0,0)),s&&(Sn(u,y),Sn(d,y),Sn(f,y),Cn(p,b),Cn(m,b),Cn(h,b)),p.normalize(),m.normalize(),h.normalize(),this.packTriangleDataTextureFormat(this.currentTriangleIndex,u,d,f,p,m,h,g,_,v,a,o),this.currentTriangleIndex++}}packTriangleDataTextureFormat(e,t,n,r,i,a,o,s,c,l,u,d){let f=K,p=this.triangles.baseOf(e),m=this.triangleFloatChunks.chunkFor(e),h=this.triangles.chunkFor(e);m[p+f.POSITION_A_OFFSET+0]=t.x,m[p+f.POSITION_A_OFFSET+1]=t.y,m[p+f.POSITION_A_OFFSET+2]=t.z,h[p+f.NORMAL_A_PACKED_OFFSET]=mt(i.x,i.y,i.z),m[p+f.POSITION_B_OFFSET+0]=n.x,m[p+f.POSITION_B_OFFSET+1]=n.y,m[p+f.POSITION_B_OFFSET+2]=n.z,h[p+f.NORMAL_B_PACKED_OFFSET]=mt(a.x,a.y,a.z),m[p+f.POSITION_C_OFFSET+0]=r.x,m[p+f.POSITION_C_OFFSET+1]=r.y,m[p+f.POSITION_C_OFFSET+2]=r.z,h[p+f.NORMAL_C_PACKED_OFFSET]=mt(o.x,o.y,o.z),m[p+f.UV_AB_OFFSET+0]=s.x,m[p+f.UV_AB_OFFSET+1]=s.y,m[p+f.UV_AB_OFFSET+2]=c.x,m[p+f.UV_AB_OFFSET+3]=c.y,m[p+f.UV_C_OFFSET+0]=l.x,m[p+f.UV_C_OFFSET+1]=l.y,h[p+f.MATERIAL_FLAGS_OFFSET]=pt(u,this.materials[u]),h[p+f.MESH_INDEX_OFFSET]=d}releaseTriangles(){this.triangles=null,this.triangleData=null,this.triangleFloatChunks=null,this.triangleFloats=null}getTriangleData(){return this.triangles?this._streamedStore?this.triangles:this.triangles.trimTo(this.currentTriangleIndex):null}getTriangleCount(){return this.currentTriangleIndex}getVertex(e,t,n){return e.itemSize===2?(n.x=e.getX(t),n.y=e.getY(t)):e.itemSize>=3&&(n.x=e.getX(t),n.y=e.getY(t),n.z=e.getZ(t)),n}logStats(){let e=this.currentTriangleIndex*K.FLOATS_PER_TRIANGLE*4;pn.debug(H.list([`${H.count(this.currentTriangleIndex,`tri`)} (${H.mb(e)})`,H.count(this.materials.length,`material`),H.count(this.maps.length,`map`)]))}extractMaterialsOnly(e){return this.resetArrays(),this._traverseMaterialsOnly(e),this.getExtractedData()}_traverseMaterialsOnly(e){if(e.isMesh&&e.geometry&&e.material){let t=this.processMaterial(e.material);e.userData.materialIndex=t;let n=this.meshes.length;this.meshes.push(e),e.userData.meshIndex=n}else e.isDirectionalLight?this.directionalLights.push(e):e.isCamera&&this.cameras.push(e);if(e.children)for(let t of e.children)this._traverseMaterialsOnly(t)}resetArrays(){this._droppedTextures=0,this.triangles=null,this._streamedStore=!1,this.triangleData=null,this.triangleFloatChunks=null,this.triangleFloats=null,this.triangleCount=0,this.currentTriangleIndex=0,this.materials=[],this.materialTriangleCounts=[],this.meshes=[],this.meshTriangleRanges=[],this._geometryRanges=new Map,this.expandedTriangleCount=0,this._allocatePlacements(0),this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.roughnessMaps=[],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._materialUuidMap=new Map,this._textureIndexCache=new WeakMap}getExtractedData(){return{triangleData:this.getTriangleData(),triangleCount:this.getTriangleCount(),materials:this.materials,materialTriangleCounts:this.materialTriangleCounts,meshes:this.meshes,meshTriangleRanges:this.meshTriangleRanges,expandedTriangleCount:this.expandedTriangleCount,instanceSource:this.instanceSource.subarray(0,this.instanceCount),instanceMatrices:this.instanceMatrices.subarray(0,this.instanceCount*16),instanceCount:this.instanceCount,bakeInverse:this.bakeInverse,maps:this.maps,normalMaps:this.normalMaps,bumpMaps:this.bumpMaps,metalnessMaps:this.metalnessMaps,emissiveMaps:this.emissiveMaps,roughnessMaps:this.roughnessMaps,displacementMaps:this.displacementMaps,anisotropyMaps:this.anisotropyMaps,transmissionMaps:this.transmissionMaps,clearcoatMaps:this.clearcoatMaps,clearcoatRoughnessMaps:this.clearcoatRoughnessMaps,sheenColorMaps:this.sheenColorMaps,sheenRoughnessMaps:this.sheenRoughnessMaps,iridescenceMaps:this.iridescenceMaps,iridescenceThicknessMaps:this.iridescenceThicknessMaps,specularIntensityMaps:this.specularIntensityMaps,specularColorMaps:this.specularColorMaps,diffuseTransmissionMaps:this.diffuseTransmissionMaps,diffuseTransmissionColorMaps:this.diffuseTransmissionColorMaps,directionalLights:this.directionalLights,cameras:this.cameras}}};function On(e,t=null){Nn=e,Pn=e?t:null}function kn(){return Nn}function An(){return Pn}function jn(e){if(!Nn)return!1;let t=e[0],n=e[1],r=e[2];return e[0]=Nn[0]*t+Nn[1]*n+Nn[2]*r,e[1]=Nn[3]*t+Nn[4]*n+Nn[5]*r,e[2]=Nn[6]*t+Nn[7]*n+Nn[8]*r,!0}function Mn(e,t,n){if(!Nn||n.length===0)return 0;let r=0;for(let i=0;i+t<=e.length;i+=t)for(let t of n){let n=i+t,a=e[n],o=e[n+1],s=e[n+2];e[n]=Nn[0]*a+Nn[1]*o+Nn[2]*s,e[n+1]=Nn[3]*a+Nn[4]*o+Nn[5]*s,e[n+2]=Nn[6]*a+Nn[7]*o+Nn[8]*s,r++}return r}var Nn,Pn,Fn=g((()=>{Nn=null,Pn=null}));Fn();function In(e){if(e===null||typeof e==`boolean`||typeof e==`string`)return e;if(typeof e==`number`)return Number.isFinite(e)?e:{$num:String(e)};if(typeof e!=`object`)return;if(e.isColor)return{$color:[e.r,e.g,e.b]};if(e.isQuaternion)return{$quat:[e.x,e.y,e.z,e.w]};if(e.isVector2||e.isVector3||e.isVector4)return{$vec:e.toArray()};if(ArrayBuffer.isView(e))return Array.from(e);if(Array.isArray(e))return e.map(e=>In(e)??null);let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return;let n={};for(let[t,r]of Object.entries(e)){let e=In(r);e!==void 0&&(n[t]=e)}return n}function Ln(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(Ln);if(`$num`in e)return Number(e.$num);if(e.$color)return new r.Color(...e.$color);if(e.$quat)return new r.Quaternion(...e.$quat);if(e.$vec){let t=[null,null,r.Vector2,r.Vector3,r.Vector4][e.$vec.length];return new t(...e.$vec)}let t={};for(let[n,r]of Object.entries(e))t[n]=Ln(r);return t}var Rn=`rayzeeScene`,zn=(e,t)=>(0,n.context)(e,{[Rn]:t});function Bn(e){let t=e.context[Rn];if(!t)throw Error(`this kernel samples scene resources: build its root with withSceneResources()`);return t}var Vn=Object.freeze([`clearcoat`,`sheen`,`iridescence`,`anisotropy`,`subsurface`,`dispersion`,`diffuseTransmission`]),Hn=Object.freeze(Object.fromEntries(Vn.map(e=>[e,!0])));function Un(e){return e.context[Rn]?.materialLayers??Hn}wt(),Ae();var Wn=new WeakSet,Gn=ye(`material`),Kn=q.SLOTS_PER_MATERIAL,qn=K.MATERIAL_FLAGS_OFFSET,Jn=new Set([`transmission`,`transparent`,`opacity`,`alphaMode`]),Yn=new Set([`side`,...Jn,`emissive`,`emissiveIntensity`]),Xn=[[`map`,!0],[`emissiveMap`,!0],[`sheenColorMap`,!0],[`specularColorMap`,!0],[`normalMap`,!1],[`bumpMap`,!1],[`roughnessMap`,!1],[`metalnessMap`,!1],[`displacementMap`,!1],[`anisotropyMap`,!1],[`transmissionMap`,!1],[`clearcoatMap`,!1],[`clearcoatRoughnessMap`,!1],[`sheenRoughnessMap`,!1],[`iridescenceMap`,!1],[`iridescenceThicknessMap`,!1],[`specularIntensityMap`,!1],[`diffuseTransmissionColorMap`,!0],[`diffuseTransmissionMap`,!1]],Zn={ior:q.IOR,transmission:q.TRANSMISSION,thickness:q.THICKNESS,emissiveIntensity:q.EMISSIVE_INTENSITY,attenuationDistance:q.ATTENUATION_DISTANCE,opacity:q.OPACITY,alphaTest:q.ALPHA_TEST,metalness:q.METALNESS,roughness:q.ROUGHNESS,clearcoat:q.CLEARCOAT,clearcoatRoughness:q.CLEARCOAT_ROUGHNESS,dispersion:q.DISPERSION,sheen:q.SHEEN,sheenRoughness:q.SHEEN_ROUGHNESS,specularIntensity:q.SPECULAR_INTENSITY,iridescence:q.IRIDESCENCE,iridescenceIOR:q.IRIDESCENCE_IOR,subsurface:q.SUBSURFACE,subsurfaceRadiusScale:q.SUBSURFACE_RADIUS_SCALE,subsurfaceAnisotropy:q.SUBSURFACE_ANISOTROPY,anisotropy:q.ANISOTROPY,anisotropyRotation:q.ANISOTROPY_ROTATION,diffuseTransmission:q.DIFFUSE_TRANSMISSION},Qn=class e{constructor(e){this.sdfs=e,this.materialStorageAttr=null,this.materialStorageNode=null,this.materialCount=0,this.srgbBuckets=null,this.linearBuckets=null,this._srgbTexPacked=null,this._linearTexPacked=null,this.callbacks={},this._sources=[],this._hostSet=[]}static COLOR_OFFSETS=[q.COLOR,q.EMISSIVE,q.ATTENUATION_COLOR,q.SHEEN_COLOR,q.SPECULAR_COLOR,q.SUBSURFACE_COLOR,q.DIFFUSE_TRANSMISSION_COLOR].filter(e=>Number.isInteger(e));_convertColorsToWorkingSpace(t){if(Wn.has(t))return;Wn.add(t);let n=Mn(t,q.FLOATS_PER_MATERIAL,e.COLOR_OFFSETS);n&&Gn.debug(`converted ${n} material colour(s) into ${An()}`)}_writeColor(e,t,n,r,i){let a=[n,r,i];jn(a)&&([n,r,i]=a),e[t]=n,e[t+1]=r,e[t+2]=i}setMaterialData(e,r=[]){if(!e)return;this._convertColorsToWorkingSpace(e);let i=e.length/4;this.materialStorageNode?(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode.value=this.materialStorageAttr,this.materialStorageNode.bufferCount=i):(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode=(0,n.storage)(this.materialStorageAttr,`vec4`,i).toReadOnly()),this.materialCount=Math.floor(i/Kn),this._sources=[...r],this._hostSet=[],this.callbacks.onMaterialFeaturesChanged?.(),Gn.debug(`${H.n(this.materialCount)} materials (storage buffer)`)}getStorageAttr(){return this.materialStorageAttr}getStorageNode(){return this.materialStorageNode}setMaterialTextures(e){e.srgbBuckets&&(this.srgbBuckets=e.srgbBuckets),e.linearBuckets&&(this.linearBuckets=e.linearBuckets)}setTexturePackMaps(e,t){this._srgbTexPacked=e||null,this._linearTexPacked=t||null}getPackedTextureIndex(e,t){if(!e)return-1;let n=e.source?.uuid??e.uuid,r=(t?this._srgbTexPacked:this._linearTexPacked)?.get(n);return r===void 0?-1:r}loadTexturesFromSdfs(){this.srgbBuckets=this.sdfs.srgbBucketTextures,this.linearBuckets=this.sdfs.linearBucketTextures,this.setTexturePackMaps(this.sdfs._srgbTexPacked,this.sdfs._linearTexPacked)}getTextureArrays(){return{srgbBuckets:this.srgbBuckets,linearBuckets:this.linearBuckets}}getMaterialProperty(e,t){let n=this.materialStorageAttr?.array;if(!n)return;let r=Zn[t];if(r===void 0)return;let i=e*q.FLOATS_PER_MATERIAL+r;return i<n.length?n[i]:void 0}materialLayers(){let e=Object.fromEntries(Vn.map(e=>[e,!1])),t=this.materialStorageAttr?.array;if(!t)return e;for(let n=0;n<this.materialCount;n++){let r=n*q.FLOATS_PER_MATERIAL;for(let n of Vn)t[r+Zn[n]]>0&&(e[n]=!0)}return e}getMaterialPropertySource(e,t){return this._hostSet[e]?.has(t)?gn.HOST:this._sources[e]?.[t]}serializeHostEdits(){let e=[];return this._hostSet.forEach((t,n)=>{t?.size&&e.push({index:n,props:Object.fromEntries(t)})}),e}updateMaterialProperty(e,t,n){if(!this.materialStorageAttr){Gn.warn(`material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=e*q.FLOATS_PER_MATERIAL;switch(Dt.has(t)&&typeof n==`number`&&(n=Ot(n)),t){case`color`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.COLOR,n.r,n.g,n.b);break;case`metalness`:r[i+q.METALNESS]=n;break;case`emissive`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.EMISSIVE,n[0],n[1],n[2]):this._writeColor(r,i+q.EMISSIVE,n.r,n.g,n.b);break;case`roughness`:r[i+q.ROUGHNESS]=n;break;case`ior`:r[i+q.IOR]=n;break;case`transmission`:r[i+q.TRANSMISSION]=n;break;case`thickness`:r[i+q.THICKNESS]=n;break;case`emissiveIntensity`:r[i+q.EMISSIVE_INTENSITY]=n;break;case`attenuationColor`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.ATTENUATION_COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.ATTENUATION_COLOR,n.r,n.g,n.b);break;case`attenuationDistance`:r[i+q.ATTENUATION_DISTANCE]=vt(n);break;case`dispersion`:r[i+q.DISPERSION]=n;break;case`sheen`:r[i+q.SHEEN]=n;break;case`sheenRoughness`:r[i+q.SHEEN_ROUGHNESS]=n;break;case`sheenColor`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.SHEEN_COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.SHEEN_COLOR,n.r,n.g,n.b);break;case`specularIntensity`:r[i+q.SPECULAR_INTENSITY]=n;break;case`specularColor`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.SPECULAR_COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.SPECULAR_COLOR,n.r,n.g,n.b);break;case`iridescence`:r[i+q.IRIDESCENCE]=n;break;case`iridescenceIOR`:r[i+q.IRIDESCENCE_IOR]=n;break;case`iridescenceThicknessRange`:Array.isArray(n)&&(r[i+q.IRIDESCENCE_THICKNESS_RANGE]=n[0],r[i+q.IRIDESCENCE_THICKNESS_RANGE+1]=n[1]);break;case`clearcoat`:r[i+q.CLEARCOAT]=n;break;case`clearcoatRoughness`:r[i+q.CLEARCOAT_ROUGHNESS]=n;break;case`opacity`:r[i+q.OPACITY]=n;break;case`side`:r[i+q.SIDE]=n,this._patchTriangleSideForMaterial(e,n);break;case`transparent`:r[i+q.TRANSPARENT]=n;break;case`alphaTest`:r[i+q.ALPHA_TEST]=n;break;case`alphaMode`:r[i+q.ALPHA_MODE]=n;break;case`depthWrite`:r[i+q.DEPTH_WRITE]=n;break;case`normalScale`:n.x===void 0?typeof n==`number`&&(r[i+q.NORMAL_SCALE]=n,r[i+q.NORMAL_SCALE+1]=n):(r[i+q.NORMAL_SCALE]=n.x,r[i+q.NORMAL_SCALE+1]=n.y);break;case`bumpScale`:r[i+q.BUMP_SCALE]=n;break;case`displacementScale`:r[i+q.DISPLACEMENT_SCALE]=n;break;case`subsurface`:r[i+q.SUBSURFACE]=n;break;case`subsurfaceRadiusScale`:r[i+q.SUBSURFACE_RADIUS_SCALE]=n;break;case`subsurfaceAnisotropy`:r[i+q.SUBSURFACE_ANISOTROPY]=n;break;case`anisotropy`:r[i+q.ANISOTROPY]=n;break;case`anisotropyRotation`:r[i+q.ANISOTROPY_ROTATION]=n;break;case`diffuseTransmission`:r[i+q.DIFFUSE_TRANSMISSION]=n;break;case`diffuseTransmissionColor`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.DIFFUSE_TRANSMISSION_COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.DIFFUSE_TRANSMISSION_COLOR,n.r,n.g,n.b);break;case`subsurfaceColor`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.SUBSURFACE_COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.SUBSURFACE_COLOR,n.r,n.g,n.b);break;case`subsurfaceRadius`:Array.isArray(n)?(r[i+q.SUBSURFACE_RADIUS]=n[0],r[i+q.SUBSURFACE_RADIUS+1]=n[1],r[i+q.SUBSURFACE_RADIUS+2]=n[2]):n.x!==void 0&&(r[i+q.SUBSURFACE_RADIUS]=n.x,r[i+q.SUBSURFACE_RADIUS+1]=n.y,r[i+q.SUBSURFACE_RADIUS+2]=n.z);break;default:Gn.warn(`unknown material property: ${t}`);return}this.materialStorageAttr.needsUpdate=!0,(this._hostSet[e]??=new Map).set(t,In(n)),Jn.has(t)&&this._recomputeOpaqueBlockerForMaterial(e),Vn.includes(t)&&this.callbacks.onMaterialFeaturesChanged?.(),this._notifyReset()}updateMaterialDataFromObject(t,n){if(!this.materialStorageAttr){Gn.warn(`material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=t*q.FLOATS_PER_MATERIAL;Mt(r,i,n);for(let t of e.COLOR_OFFSETS)this._writeColor(r,i+t,r[i+t],r[i+t+1],r[i+t+2]);this._sources[t]=n.sources,this._hostSet[t]=void 0,this._patchTriangleSideForMaterial(t,r[i+q.SIDE]),this._recomputeOpaqueBlockerForMaterial(t),this.callbacks.onMaterialFeaturesChanged?.(),this.materialStorageAttr.needsUpdate=!0,this._notifyReset()}updateMaterial(e,t){let n=this.sdfs.geometryExtractor.createMaterialObject(t);if(this._srgbTexPacked||this._linearTexPacked){let e=yn(t);for(let[t,r]of Xn)n[t]=this.getPackedTextureIndex(e[t],r)}this.updateMaterialDataFromObject(e,n)}updateTextureTransform(e,t,n){if(!this.materialStorageAttr){Gn.warn(`material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=e*q.FLOATS_PER_MATERIAL,a={map:q.ALBEDO_TRANSFORM,normalMap:q.NORMAL_TRANSFORM,roughnessMap:q.ROUGHNESS_TRANSFORM,metalnessMap:q.METALNESS_TRANSFORM,emissiveMap:q.EMISSIVE_TRANSFORM,bumpMap:q.BUMP_TRANSFORM,displacementMap:q.DISPLACEMENT_TRANSFORM}[t];if(a===void 0){Gn.warn(`unknown texture name for transform update: ${t}`);return}for(let e=0;e<8;e++)i+a+e<r.length&&(r[i+a+e]=n[e]);this.materialStorageAttr.needsUpdate=!0,this._notifyReset()}_notifyReset(){this.callbacks.onReset&&this.callbacks.onReset()}_recomputeOpaqueBlockerForMaterial(e){let t=this.materialStorageAttr?.array;if(!t)return;let n=e*q.FLOATS_PER_MATERIAL,r=ft({alphaMode:t[n+q.ALPHA_MODE],transparent:t[n+q.TRANSPARENT],transmission:t[n+q.TRANSMISSION],opacity:t[n+q.OPACITY]});this._patchTriangleFlagForMaterial(e,26,2,r)}_patchTriangleFlagForMaterial(e,t,n,r){let i=this.callbacks.getTriangleData?.(),a=i?.records,o=a?null:i?.array,s=i?.count|0;if(!o&&!a||s===0)return;let c=K.FLOATS_PER_TRIANGLE,l=(1<<n)-1<<t>>>0,u=(r<<t&l)>>>0,d=0;for(let t=0;t<s;t++){let n=a?a.chunkFor(t):o,r=a?a.baseOf(t):t*c;(n[r+qn]&16777215)===e&&(n[r+qn]=(n[r+qn]&~l|u)>>>0,d++)}d>0&&this.callbacks.onTriangleDataChanged&&this.callbacks.onTriangleDataChanged()}_patchTriangleSideForMaterial(e,t){this._patchTriangleFlagForMaterial(e,24,2,t)}dispose(){this.materialStorageAttr=null,this.materialStorageNode=null,this.materialCount=0,this.srgbBuckets=null,this.linearBuckets=null,this._srgbTexPacked=null,this._linearTexPacked=null,this._sources=[],this._hostSet=[]}},$n=`function e(e,t){let n=Math.max(1,Math.ceil(e/1024));return{k:n,width:Math.ceil(e/n),height:Math.ceil(t/n)}}function t(e,t,n,r,i,a){let o=0;for(let s=0;s<a;s++){for(;o<n-1&&e[t+o]<=s/a;)o++;r[i+s]=o}}function n(n,r,i,{filtered:a=!0}={}){let{k:o,width:s,height:c}=e(r,i),l=new Float32Array(r*i),u=0;for(let e=0;e<i;e++){let t=Math.sin(Math.PI*(e+.5)/i);for(let i=0;i<r;i++){let a=4*(e*r+i),o=.2126*n[a]+.7152*n[a+1]+.0722*n[a+2];l[e*r+i]=Number.isFinite(o)&&o>0?o:0,u+=l[e*r+i]*t}}let d=[1/8,6/8,1/8],f=e=>{for(let t=0;t<i;t++){let n=Math.sin(Math.PI*(t+.5)/i),c=Math.floor(t/o)*s,u=[Math.max(t-1,0),t,Math.min(t+1,i-1)];for(let i=0;i<r;i++){let s=l[t*r+i];if(a){let e=[(i+r-1)%r,i,(i+1)%r];s=0;for(let t=0;t<3;t++)for(let n=0;n<3;n++)s+=d[t]*d[n]*l[u[t]*r+e[n]]}e(c+Math.floor(i/o),s*n)}}},p=0;f((e,t)=>void(p+=t));let m=p/(r*i),h=new Float64Array(s*c),g=0;f((e,t)=>{h[e]+=Math.max(t-m,0),g+=Math.max(t-m,0)}),g>0||(h.fill(0),f((e,t)=>void(h[e]+=t)));let _=p>0?1e-4*p/(s*c):0,v=new Float32Array(s*c),y=new Float32Array(c),b=new Float64Array(c),x=0;for(let e=0;e<c;e++){let t=0;for(let n=0;n<s;n++)t+=h[e*s+n]+_;let n=0;for(let r=0;r<s;r++)n+=h[e*s+r]+_,v[e*s+r]=t>0?r===s-1?1:n/t:0;b[e]=t,x+=t}let S=0;for(let e=0;e<c;e++)S+=b[e],y[e]=x>0?e===c-1?1:S/x:0;let C=new Float32Array(2*s*c),w=new Float32Array(2*c);for(let e=0;e<c;e++)t(v,e*s,s,C,2*e*s,2*s);return t(y,0,c,w,0,2*c),{exactWidth:s,exactHeight:c,exactConditional:v,exactMarginal:y,exactRowGuide:C,exactMarginalGuide:w,radianceIntegral:2*Math.PI*Math.PI*u/(r*i)}}self.onmessage=function(e){let{floatData:t,width:r,height:i}=e.data;try{let e=n(t,r,i);self.postMessage({width:r,height:i,...e},[e.exactConditional.buffer,e.exactMarginal.buffer,e.exactRowGuide.buffer,e.exactMarginalGuide.buffer])}catch(e){self.postMessage({error:e.message})}};`,er=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,$n],{type:`text/javascript;charset=utf-8`});function tr(e){let t;try{if(t=er&&(self.URL||self.webkitURL).createObjectURL(er),!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($n),{type:`module`,name:e?.name})}}function nr(e){e&&Object.assign(lr,e)}function rr(){return lr}function ir(){return typeof navigator<`u`&&navigator.hardwareConcurrency||4}function ar(){return!!lr.decodeImage||typeof self<`u`&&(typeof createImageBitmap<`u`||typeof document<`u`)}function or(){return!!lr.Worker||typeof Worker<`u`}async function sr(e){if(!lr.Worker||ur===0&&globalThis.Worker!==void 0)return e();ur++===0&&(globalThis.Worker=lr.Worker);try{return await e()}finally{--ur===0&&globalThis.Worker===lr.Worker&&delete globalThis.Worker}}function cr(e,t){let n=lr.Worker;if(!n)return new e(t);let r=Object.prototype.hasOwnProperty.call(globalThis,`Worker`),i=globalThis.Worker;globalThis.Worker=n;try{return new e(t)}finally{r?globalThis.Worker=i:delete globalThis.Worker}}var lr,ur,dr=g((()=>{lr={Worker:null,decodeImage:null},ur=0}));dr();var fr=1024,pr=1e-4;function mr(e,t){let n=Math.max(1,Math.ceil(e/fr));return{k:n,width:Math.ceil(e/n),height:Math.ceil(t/n)}}function hr(e,t,n,r,i,a){let o=0;for(let s=0;s<a;s++){for(;o<n-1&&e[t+o]<=s/a;)o++;r[i+s]=o}}function gr(e,t,n,{filtered:r=!0}={}){let{k:i,width:a,height:o}=mr(t,n),s=new Float32Array(t*n),c=0;for(let r=0;r<n;r++){let i=Math.sin(Math.PI*(r+.5)/n);for(let n=0;n<t;n++){let a=4*(r*t+n),o=.2126*e[a]+.7152*e[a+1]+.0722*e[a+2];s[r*t+n]=Number.isFinite(o)&&o>0?o:0,c+=s[r*t+n]*i}}let l=[1/8,6/8,1/8],u=e=>{for(let o=0;o<n;o++){let c=Math.sin(Math.PI*(o+.5)/n),u=Math.floor(o/i)*a,d=[Math.max(o-1,0),o,Math.min(o+1,n-1)];for(let n=0;n<t;n++){let a=s[o*t+n];if(r){let e=[(n+t-1)%t,n,(n+1)%t];a=0;for(let n=0;n<3;n++)for(let r=0;r<3;r++)a+=l[n]*l[r]*s[d[n]*t+e[r]]}e(u+Math.floor(n/i),a*c)}}},d=0;u((e,t)=>void(d+=t));let f=d/(t*n),p=new Float64Array(a*o),m=0;u((e,t)=>{p[e]+=Math.max(t-f,0),m+=Math.max(t-f,0)}),m>0||(p.fill(0),u((e,t)=>void(p[e]+=t)));let h=d>0?pr*d/(a*o):0,g=new Float32Array(a*o),_=new Float32Array(o),v=new Float64Array(o),y=0;for(let e=0;e<o;e++){let t=0;for(let n=0;n<a;n++)t+=p[e*a+n]+h;let n=0;for(let r=0;r<a;r++)n+=p[e*a+r]+h,g[e*a+r]=t>0?r===a-1?1:n/t:0;v[e]=t,y+=t}let b=0;for(let e=0;e<o;e++)b+=v[e],_[e]=y>0?e===o-1?1:b/y:0;let x=new Float32Array(2*a*o),S=new Float32Array(2*o);for(let e=0;e<o;e++)hr(g,e*a,a,x,2*e*a,2*a);return hr(_,0,o,S,0,2*o),{exactWidth:a,exactHeight:o,exactConditional:g,exactMarginal:_,exactRowGuide:x,exactMarginalGuide:S,radianceIntegral:2*Math.PI*Math.PI*c/(t*n)}}function _r({exactWidth:e,exactHeight:t,exactConditional:n,exactMarginal:r,exactRowGuide:i,exactMarginalGuide:a}){let o=e+1,s=new Float32Array(4*o*t);for(let c=0;c<t;c++){let t=4*c*o;for(let r=0,a=c*e;r<e;r++,a++,t+=4)s[t]=n[a],s[t+1]=r>0?n[a-1]:0,s[t+2]=i[2*a],s[t+3]=i[2*a+1];s[t]=r[c],s[t+1]=c>0?r[c-1]:0,s[t+2]=a[2*c],s[t+3]=a[2*c+1]}return{data:s,width:o,height:t}}function vr(e){return e<=.04045?e/12.92:((e+.055)/1.055)**2.4}function yr(e){let{width:t,height:n}=e.image,i=e.image.data,a=!1;if(!i){let r=new OffscreenCanvas(t,n).getContext(`2d`);r.drawImage(e.image,0,0,t,n),i=r.getImageData(0,0,t,n).data,a=!0}let o;if(e.type===r.FloatType&&i instanceof Float32Array)o=new Float32Array(i);else if(e.type===r.HalfFloatType){o=new Float32Array(i.length);for(let e=0,t=i.length;e<t;e++)o[e]=r.DataUtils.fromHalfFloat(i[e])}else{let e;e=i instanceof Int8Array||i instanceof Int16Array||i instanceof Int32Array?2**(8*i.BYTES_PER_ELEMENT-1)-1:2**(8*i.BYTES_PER_ELEMENT)-1,o=new Float32Array(i.length);for(let t=0,n=i.length;t<n;t++)o[t]=i[t]/e}if(!a&&e.colorSpace===r.SRGBColorSpace&&(a=!0),a)for(let e=0,t=o.length;e<t;e+=4)o[e]=vr(o[e]),o[e+1]=vr(o[e+1]),o[e+2]=vr(o[e+2]);if(e.flipY){let e=new Float32Array(o.length);for(let r=0;r<n;r++){let i=n-r-1,a=r*t*4,s=i*t*4;e.set(o.subarray(a,a+t*4),s)}o=e}return{floatData:o,width:t,height:n}}var br=class{constructor(){this.totalSum=0,this.width=0,this.height=0,this.exactConditional=null,this.exactMarginal=null,this.exactRowGuide=null,this.exactMarginalGuide=null,this.exactWidth=0,this.exactHeight=0,this.radianceIntegral=0,this._worker=null}dispose(){this.exactConditional=null,this.exactMarginal=null,this.exactRowGuide=null,this.exactMarginalGuide=null,this._worker&&=(this._worker.terminate(),null)}_adopt(e,t,n){Object.assign(this,e),this.width=t,this.height=n,this.totalSum=e.radianceIntegral}updateFrom(e){let{floatData:t,width:n,height:r}=yr(e);this._adopt(gr(t,n,r),n,r)}async updateFromAsync(e){let{floatData:t,width:n,height:r}=yr(e);this._worker=cr(tr);try{let{width:e,height:i,...a}=await new Promise((e,i)=>{this._worker.onmessage=t=>{t.data.error?i(Error(t.data.error)):e(t.data)},this._worker.onerror=i,this._worker.postMessage({floatData:t,width:n,height:r},[t.buffer])});this._adopt(a,e,i)}finally{this._worker&&=(this._worker.terminate(),null)}}},xr=class{constructor(e=512,t=256){this.width=e,this.height=t,this.lastRenderTime=0,this._pixels=new Float32Array(e*t*4),this._texture=new r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1}renderSolid(e){let t=performance.now(),{width:n,height:r}=this,i=this._pixels,a=e.color.r,o=e.color.g,s=e.color.b;for(let e=0;e<r;e++)for(let t=0;t<n;t++){let r=(e*n+t)*4;i[r]=a,i[r+1]=o,i[r+2]=s,i[r+3]=1}return this._texture.needsUpdate=!0,delete this._texture.userData?.__rayzeeColorSpace,this.lastRenderTime=performance.now()-t,this._texture}setResolution(e,t){this.width===e&&this.height===t||(this.width=e,this.height=t,this._pixels=new Float32Array(e*t*4),this._texture.dispose(),this._texture=new r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1)}getLastRenderTime(){return this.lastRenderTime}dispose(){this._texture.dispose()}},Sr=Math.PI/180;function Cr(e){let t=2*Math.PI*(e-1)/365;return .006918-.399912*Math.cos(t)+.070257*Math.sin(t)-.006758*Math.cos(2*t)+907e-6*Math.sin(2*t)-.002697*Math.cos(3*t)+.00148*Math.sin(3*t)}function wr({hours:e,dayOfYear:t,latitude:n}){let r=Cr(t),i=(e-12)*15*Sr,a=n*Sr,o=Math.sin(a)*Math.sin(r)+Math.cos(a)*Math.cos(r)*Math.cos(i),s=Math.asin(Math.min(1,Math.max(-1,o)))/Sr;return{azimuth:(Math.atan2(Math.sin(i),Math.cos(i)*Math.sin(a)-Math.tan(r)*Math.cos(a))/Sr+540)%360,elevation:s}}function Tr({elevation:e,dayOfYear:t,latitude:n,afternoon:r=!1}){let i=Cr(t),a=n*Sr,o=(Math.sin(e*Sr)-Math.sin(a)*Math.sin(i))/(Math.cos(a)*Math.cos(i)),s=Math.acos(Math.min(1,Math.max(-1,o)))/Sr/15;return r?12+s:12-s}var Er=e=>[0,31,59,90,120,151,181,212,243,273,304,334][e-1]+21,Dr=`Linear Rec.709 (sRGB)`,Or=null;function kr(){return Or}function Ar(e){Or=e,e?._publishWorkingMatrix?.()}function jr(e){Or===null&&(Or=e)}function Mr(e){return Nr.get(e)?.storage??null}var Nr,Pr=g((()=>{Nr=new Map}));function Fr(e){if(e){Object.assign(Rr,e);for(let t of Object.keys(e))zr.add(t)}}function Ir(e){return zr.has(e)}function Lr(){return{...Rr}}var Rr,zr,Br=g((()=>{Rr={ortRuntimeUrl:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/ort.webgpu.bundle.min.mjs`,ortWasmPaths:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/`,dracoDecoderPath:`https://www.gstatic.com/draco/v1/decoders/`,ktx2TranscoderPath:`https://cdn.jsdelivr.net/npm/three@0.183.2/examples/jsm/libs/basis/`,oidnWeightsBaseUrl:`https://assets.rayzee.atulmourya.com/oidn/denoiser-0.0.11/`,ocioRuntimeFactory:null,ocioRuntimeUrl:null,ocioWasmUrl:null,upscalerModelBaseUrl:`https://huggingface.co/notaneimu/onnx-image-models/resolve/main/`,neuralRuntimeUrl:`/neural/neural-runtime.js`,neuralAssetBaseUrl:null,cacheNamespace:`rayzee`,storage:`auto`},zr=new Set}));function Vr(e,t){e&&t&&(e.userData.__rayzeeSource=t)}function Hr(e){let t=e?.userData?.__rayzeeSource;if(!t)return null;let{width:n=0,height:r=0}=e.image??{};return`cdf:${Gr}:${t}|${n}x${r}|${e.userData.__rayzeeColorSpace??`native`}`}async function Ur(e){let t=Hr(e),n=t?await Kr()?.open(t):null;if(!n)return null;try{let e=await Promise.all(Jr.map(e=>n.file(e)));if(e.some(e=>!e))return null;let t=await Promise.all(e.map(async e=>new Float32Array(await e.arrayBuffer()))),{totalSum:r,width:i,height:a,exactWidth:o,exactHeight:s,radianceIntegral:c}=n.extra;return{...Object.fromEntries(qr.map((e,n)=>[e,t[n]])),totalSum:r,width:i,height:a,exactWidth:o,exactHeight:s,radianceIntegral:c}}finally{n.release()}}async function Wr(e,t){let{totalSum:n,width:r,height:i,exactWidth:a,exactHeight:o,radianceIntegral:s}=t,c=qr.map(e=>t[e]),l=Hr(e),u=l?Kr():null;if(!u||c.some(e=>!e))return!1;let d=await u.create(l,{label:e.name||`environment`,expectedBytes:c.reduce((e,t)=>e+t.byteLength,0)});if(!d)return!1;try{for(let e=0;e<Jr.length;e++)await d.write(Jr[e],c[e]);return await d.commit({totalSum:n,width:r,height:i,exactWidth:a,exactHeight:o,radianceIntegral:s}),!0}catch{return await d.abort(),!1}}var Gr,Kr,qr,Jr,Yr=g((()=>{nn(),Pr(),Br(),Gr=5,Kr=()=>Mr(Lr().cacheNamespace)?.area(tn.CDF)??null,qr=[`exactConditional`,`exactMarginal`,`exactRowGuide`,`exactMarginalGuide`],Jr=qr.map(e=>`${e}.f32`)}));Fn(),Ae(),Yr(),X();var Xr=ye(`env`),Zr=Object.freeze({time:10,month:3,latitude:40}),Qr=wr({hours:Zr.time,dayOfYear:Er(Zr.month),latitude:Zr.latitude}),$r=Object.freeze({solidSkyColor:`#87CEEB`,skySunAzimuth:180-Qr.azimuth,skySunElevation:Qr.elevation,skySunStrength:1,skySunSize:.53,skyTurbidity:2,skyOzone:300,skyAirDensity:1,skyGroundAlbedo:`#959595`,skyAltitude:50}),ei=1024,ti=512,ni=Math.PI/180,ri=new r.Matrix4,ii=4,ai=class{constructor(e,t,n=null){this.scene=e,this.uniforms=t,this.renderer=n,this.equirectHdrInfo=new br,this.ProceduralSky=null,this._loadProceduralSky=null,this._proceduralSkyLoading=null,this.issues=null,this.physicalSky=null,this.simpleSkyRenderer=null,this._sun=null,this._skyRequested=!1,this._skyScheduled=!1,this._skyInFlight=0,this._skyCaughtUp=null,this._resolveSky=null,this._skyBakes=0,this._skyStatsBake=0,this._envPlaceholder=new r.DataTexture(new Float32Array([0,0,0,1]),1,1,r.RGBAFormat,r.FloatType,void 0,void 0,void 0,r.LinearFilter,r.LinearFilter),this._envPlaceholder.needsUpdate=!0,this.environmentTexture=this._envPlaceholder,this.envTexSize=new r.Vector2,this.envCDFTexture=null,this._initCDFTexture(),this.environmentRotationMatrix=new r.Matrix4,this.cdfBuildTime=0,this.envParams={mode:`hdri`,solidSkyColor:new r.Color($r.solidSkyColor),skySunDirection:this._calculateInitialSunDirection(),skySunStrength:$r.skySunStrength,skySunSize:$r.skySunSize,skyTurbidity:$r.skyTurbidity,skyOzone:$r.skyOzone,skyAirDensity:$r.skyAirDensity,skyGroundAlbedo:new r.Color($r.skyGroundAlbedo),skyAltitude:$r.skyAltitude},this.callbacks={},this._previousHDRI=null}async setMode(e){let t=this.envParams.mode;this.envParams.mode=e,e!==`hdri`&&t===`hdri`&&(this._previousHDRI=this.environmentTexture),e===`color`?await this.generateSolidColorTexture():e===`procedural`?await this.generateProceduralSkyTexture():e===`hdri`&&this._previousHDRI&&(await this.setEnvironmentMap(this._previousHDRI),this._previousHDRI=null),e!==`procedural`&&t===`procedural`&&this._releaseSky(),this.markDirty(),this.callbacks.onLightingChanged?.(),this._notifyReset()}markDirty(){this.environmentTexture&&(this.environmentTexture.needsUpdate=!0)}get hdriSource(){return(this.envParams.mode===`hdri`?this.environmentTexture:this._previousHDRI)?.userData?.__rayzeeSource??null}serialize(){let e=this.envParams;return{mode:e.mode,hdri:this.hdriSource,solidSkyColor:e.solidSkyColor.toArray(),skyModel:`atmosphere`,skySunDirection:e.skySunDirection.toArray(),skySunStrength:e.skySunStrength,skySunSize:e.skySunSize,skyTurbidity:e.skyTurbidity,skyOzone:e.skyOzone,skyAirDensity:e.skyAirDensity,skyGroundAlbedo:e.skyGroundAlbedo.toArray(),skyAltitude:e.skyAltitude}}async restore(e){if(!e)return;let t=this.envParams,n=e.skyModel===`atmosphere`,r=[`solidSkyColor`,`skySunDirection`];for(let i of n?[...r,`skyGroundAlbedo`]:r)Array.isArray(e[i])&&t[i].fromArray(e[i]);if(n)for(let n of[`skySunStrength`,`skySunSize`,`skyTurbidity`,`skyOzone`,`skyAirDensity`,`skyAltitude`])typeof e[n]==`number`&&(t[n]=e[n]);[`hdri`,`color`,`procedural`].includes(e.mode)&&(e.mode!==`hdri`||t.mode!==`hdri`)&&await this.setMode(e.mode)}get params(){return this.envParams}get texture(){return this.environmentTexture}generateSolid(){return this.generateSolidColorTexture()}generateProcedural(){return this.generateProceduralSkyTexture()}_initCDFTexture(){this.envCDFTexture=new r.DataTexture(new Float32Array(4),1,1,r.RGBAFormat,r.FloatType),this.envCDFTexture.needsUpdate=!0,this._exactTable=null}_updateCDFTexture(){let e=this.equirectHdrInfo;if(!e.exactConditional||!(e.exactWidth>0))return;let{data:t,width:n,height:i}=_r(e);this.envCDFTexture?._isPhysicalSky||this.envCDFTexture?.dispose?.(),this.envCDFTexture=new r.DataTexture(t,n,i,r.RGBAFormat,r.FloatType),this.envCDFTexture.needsUpdate=!0,this._exactTable={radianceIntegral:e.radianceIntegral}}get exactTable(){return this.scene.environment?this._exactTable??null:null}setEnvironmentTexture(e){if(!e)return;let t=kr();if(t?.hasConfig)try{t.convertTexturePixels(e,{space:e.userData?.ocioColorSpace??null})}catch(e){Xr.warn(`environment colour conversion failed, left in its original space: ${e.message}`)}this.environmentTexture=e,this.envTexSize.set(e.image.width,e.image.height)}getEnvironmentTexture(){return this.environmentTexture}setEnvironmentRotation(e){let t=Math.PI/180*e;this.environmentRotationMatrix.makeRotationY(t),this.uniforms.get(`environmentMatrix`).value.copy(this.environmentRotationMatrix),this.refreshSun()}async buildEnvironmentCDF({useWorker:e=!0}={}){if(!this.scene.environment){this._cdfSignature=null,this._updateCDFTexture(),this.uniforms.set(`envTotalSum`,0);return}if(!this.scene.environment._isPhysicalSky)try{let t=performance.now(),n=this.scene.environment;if(!n.image){this._cdfSignature=null,this._updateCDFTexture(),this.uniforms.set(`envTotalSum`,0);return}let r=`${n.uuid}:${n.version}`;if(r===this._cdfSignature)return;let i=await Ur(n).catch(()=>null);i?Object.assign(this.equirectHdrInfo,i):e?await this.equirectHdrInfo.updateFromAsync(n):this.equirectHdrInfo.updateFrom(n),i||Wr(n,this.equirectHdrInfo).catch(()=>{}),this._cdfSignature=r,this.cdfBuildTime=performance.now()-t,this._updateCDFTexture(),this.uniforms.set(`envTotalSum`,this.equirectHdrInfo.totalSum);let{width:a,height:o}=this.equirectHdrInfo;a&&o&&this.uniforms.get(`envResolution`).value.set(a,o),Xr.info(H.list([H.px(this.envTexSize.x,this.envTexSize.y),`CDF ${H.ms(this.cdfBuildTime)}${i?` (stored)`:e?``:` (main thread)`}`]))}catch(e){this._cdfSignature=null,Xr.error(`CDF build failed:`,e),this.uniforms.set(`envTotalSum`,0)}}applyCDFResults(){let e=this.scene.environment,t=this.callbacks.getSceneTextureNodes?.();t&&e&&t.envTex&&(t.envTex.value=e),e&&!e._isGeneratedProcedural&&this.uniforms.set(`hasSun`,0)}async setEnvironmentMap(e,{buildCDF:t=!0}={}){let n=this.environmentTexture;e&&n&&n!==e&&n!==this._envPlaceholder&&n!==this._previousHDRI&&!n._isPhysicalSky&&n.dispose?.(),this.scene.environment=e,this.setEnvironmentTexture(e),e?t&&await this.buildEnvironmentCDF():(this._cdfSignature=null,this._updateCDFTexture(),this.uniforms.set(`envTotalSum`,0));let r=this.callbacks.getSceneTextureNodes?.();r&&e&&r.envTex&&(r.envTex.value=e),e&&!e._isGeneratedProcedural&&this.uniforms.set(`hasSun`,0),e&&n?._isPhysicalSky&&this.envParams.mode!==`procedural`&&this._releaseSky(),this._notifyReset()}beginHDRI(e=null){this._previousHDRI&&this._previousHDRI!==e&&this._previousHDRI.dispose?.(),this._previousHDRI=null,this.envParams.mode=`hdri`}async applyHDRI(e,{buildCDF:t=!0}={}){this.beginHDRI(e),await this.setEnvironmentMap(e,{buildCDF:t})}async generateSolidColorTexture(){this.simpleSkyRenderer||=new xr(512,256);let e={color:this.envParams.solidSkyColor};try{let t=this.simpleSkyRenderer.renderSolid(e);t._isGeneratedProcedural=!0,await this.setEnvironmentMap(t),this.uniforms.set(`hasSun`,0)}catch(e){Xr.error(`solid color sky generation failed:`,e)}}generateProceduralSkyTexture(){return!this.ProceduralSky&&this._loadProceduralSky?(this._proceduralSkyLoading??=this._loadProceduralSky().then(e=>{this._proceduralSkyLoading=null,this.ProceduralSky||=e}),this._proceduralSkyLoading.then(()=>this.generateProceduralSkyTexture())):this.ProceduralSky?(this._skyRequested=!0,this._skyCaughtUp??=new Promise(e=>void(this._resolveSky=e)),this._pumpSky(),this._skyCaughtUp):(this.issues?.record(Y.CAPABILITY_MISSING,`procedural mode needs the physical sky: environmentManager.setProceduralSky( PhysicalSky ), from rayzee/addons/physical-sky`,{capability:`physical-sky`}),Promise.resolve())}_pumpSky(){this._skyScheduled||!this._skyRequested||this._skyInFlight>=ii||(this._skyScheduled=!0,queueMicrotask(()=>{this._skyScheduled=!1,this._skyRequested&&this._skyInFlight<ii&&this._bakePhysicalSky()}))}_settleSky(){let e=this._resolveSky;this._skyCaughtUp=this._resolveSky=null,e?.()}async _bakePhysicalSky(){this._skyRequested=!1;let e=this.envParams;if(!this.renderer||e.mode!==`procedural`){this.renderer||Xr.warn(`physical sky needs a renderer`),this._skyInFlight===0&&this._settleSky();return}let t=this.physicalSky??=new this.ProceduralSky(ei,ti),n=e.skyGroundAlbedo,r=++this._skyBakes,i=()=>r===this._skyBakes&&!this._skyRequested;this._skyInFlight++;try{let{texture:a,cdfTexture:o,sun:s,stats:c}=t.bake(this.renderer,{sunDirection:e.skySunDirection.toArray(),turbidity:e.skyTurbidity,ozone:e.skyOzone,airDensity:e.skyAirDensity,groundAlbedo:[n.r,n.g,n.b],altitude:e.skyAltitude,sunAngularDiameter:e.skySunSize*ni,sunStrength:e.skySunStrength});this._sun=s,this._installSky(a,o);let{totalSum:l,radianceIntegral:u}=await c;e.mode===`procedural`&&t===this.physicalSky&&r>this._skyStatsBake&&(this._skyStatsBake=r,this.uniforms.set(`envTotalSum`,l),this._exactTable?.sky&&(this._exactTable.radianceIntegral=u),i()&&this._notifyReset()),i()&&Xr.debug(`physical sky ${H.ms(t.getLastRenderTime())} · sun ${s.radiance.map(e=>e.toPrecision(3)).join(`,`)}`)}catch(e){Xr.error(`physical sky generation failed:`,e)}finally{this._skyInFlight--,i()?this._settleSky():this._pumpSky()}}setProceduralSky(e){this._loadProceduralSky=null,e!==this.ProceduralSky&&(this._releaseSky(),this.ProceduralSky=e,e&&this.envParams.mode===`procedural`&&this.generateProceduralSkyTexture())}setProceduralSkyLoader(e){this._loadProceduralSky=e}_installSky(e,t){let n=this.environmentTexture;n&&n!==e&&n!==this._envPlaceholder&&n!==this._previousHDRI&&n.dispose?.(),this.envCDFTexture!==t&&(this.envCDFTexture?.dispose?.(),this.envCDFTexture=t),this._cdfSignature=null,this._exactTable?.sky||(this._exactTable={radianceIntegral:0,sky:!0}),e._isGeneratedProcedural=!0,this.scene.environment=e,this.environmentTexture=e,this.envTexSize.set(e.image.width,e.image.height),this.uniforms.get(`envResolution`).value.set(e.image.width,e.image.height);let r=this.callbacks.getSceneTextureNodes?.();r?.envTex&&(r.envTex.value=e),this.refreshSun(),this._notifyReset()}_releaseSky(){this.physicalSky&&(this.physicalSky.dispose(this.renderer),this.physicalSky=null,this._sun=null,this.refreshSun())}refreshSun(){let e=this.envParams.mode===`procedural`?this._sun:null,t=!!e&&e.radiance.some(e=>e>0);if(this.uniforms.set(`hasSun`,+!!t),!t)return;this.uniforms.get(`sunDirection`).value.fromArray(e.direction).transformDirection(ri.copy(this.environmentRotationMatrix).transpose());let n=[...e.radiance];jn(n),this.uniforms.get(`sunRadiance`).value.fromArray(n),this.uniforms.get(`sunParams`).value.set(e.cosHalfAngle,e.solidAngle,1/(e.sinHalfAngle*e.sinHalfAngle),e.horizonSin)}_calculateInitialSunDirection(){let e=$r.skySunAzimuth*(Math.PI/180),t=$r.skySunElevation*(Math.PI/180);return new r.Vector3(Math.cos(t)*Math.sin(e),Math.sin(t),Math.cos(t)*Math.cos(e)).normalize()}_notifyReset(){this.callbacks.onReset&&this.callbacks.onReset()}dispose(){this.callbacks={},this._settleSky(),this.physicalSky?.dispose(this.renderer),this.physicalSky=null,this.simpleSkyRenderer=null,this._sun=null,this.envCDFTexture?.dispose?.(),this.envCDFTexture=null,this.environmentTexture&&this.environmentTexture!==this._envPlaceholder&&this.environmentTexture.dispose?.(),this._envPlaceholder?.dispose(),this._envPlaceholder=null,this.environmentTexture=null,this._previousHDRI=null}};Ae();var oi=ye(`shader`),si=class{constructor(){this.prevColorTexNode=null,this.prevAlbedoTexNode=null,this.prevNormalDepthTexNode=null,this._sceneTextureNodes=null}updateSceneTextures(e){let t=this._sceneTextureNodes,n=e.environment;n.environmentTexture&&t.envTex&&(t.envTex.value=n.environmentTexture),e.goboMaps&&t.goboMapsTex&&(t.goboMapsTex.value=e.goboMaps),e.iesProfiles&&t.iesProfilesTex&&(t.iesProfilesTex.value=e.iesProfiles),oi.debug(`scene textures updated in-place`)}updateGoboMaps(e){let t=this._sceneTextureNodes;!t||!t.goboMapsTex||e&&(t.goboMapsTex.value=e)}updateIESProfiles(e){let t=this._sceneTextureNodes;!t||!t.iesProfilesTex||e&&(t.iesProfilesTex.value=e)}getSceneTextureNodes(){return this._sceneTextureNodes}createSceneTextureNodes(e,t){let i=e.triangleStorageNode,a=e.bvhStorageNode,o=e.materialData.materialStorageNode,s=e.lightStorageNode,c=(0,n.texture)(e.environment.environmentTexture),l=t.getReadTextures();this.prevColorTexNode=(0,n.texture)(l.color),this.prevAlbedoTexNode=(0,n.texture)(l.albedo),this.prevNormalDepthTexNode=(0,n.texture)(l.normalDepth);let u=()=>{let e=new r.DataArrayTexture(new Uint8Array([255,255,255,255]),1,1,1);return e.minFilter=r.LinearFilter,e.magFilter=r.LinearFilter,e.generateMipmaps=!1,e.needsUpdate=!0,(0,n.texture)(e)},d={triStorage:i,bvhStorage:a,matStorage:o,lightBufferStorage:s,envTex:c,goboMapsTex:e.goboMaps?(0,n.texture)(e.goboMaps):u(),iesProfilesTex:e.iesProfiles?(0,n.texture)(e.iesProfiles):u()};return this._sceneTextureNodes=d,d}dispose(){this.prevColorTexNode=null,this.prevAlbedoTexNode=null,this.prevNormalDepthTexNode=null,this._sceneTextureNodes=null}},ci=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.batchSizeRatio=.02,this.maxIterations=2,this.timeBudgetMs=15e3,this.stats={reinsertionsApplied:0,iterations:0,timeMs:0}}setBatchSizeRatio(e){this.batchSizeRatio=Math.max(.005,Math.min(.1,e))}setMaxIterations(e){this.maxIterations=Math.max(1,Math.min(5,e))}getStatistics(){return{...this.stats}}surfaceArea(e){let t=e.maxX-e.minX,n=e.maxY-e.minY,r=e.maxZ-e.minZ;return t*n+n*r+r*t}buildParentMap(e){let t=new Map;t.set(e,{parent:null,isLeft:!1});let n=[e];for(;n.length>0;){let e=n.pop();e.triangleCount>0||(e.leftChild&&(t.set(e.leftChild,{parent:e,isLeft:!0}),n.push(e.leftChild)),e.rightChild&&(t.set(e.rightChild,{parent:e,isLeft:!1}),n.push(e.rightChild)))}return t}findCandidates(e,t,n){let r=[],i=[e];for(;i.length>0;){let a=i.pop();if(a!==e&&n.get(a).parent!==e){let e=this.surfaceArea(a);r.length<t?(r.push({node:a,cost:e}),r.length===t&&this._heapify(r)):e>r[0].cost&&(r[0]={node:a,cost:e},this._siftDown(r,0))}a.triangleCount===0&&(a.leftChild&&i.push(a.leftChild),a.rightChild&&i.push(a.rightChild))}return r}_heapify(e){for(let t=(e.length>>1)-1;t>=0;t--)this._siftDown(e,t)}_siftDown(e,t){let n=e.length;for(;;){let r=t,i=2*t+1,a=2*t+2;if(i<n&&e[i].cost<e[r].cost&&(r=i),a<n&&e[a].cost<e[r].cost&&(r=a),r===t)break;let o=e[t];e[t]=e[r],e[r]=o,t=r}}findReinsertion(e,t,n){let r=n.get(e),i=r.parent;if(!i)return null;let a=r.isLeft?i.rightChild:i.leftChild,o=this.surfaceArea(e),s=this.surfaceArea(i),c=null,l=0,u=s,d=a.minX,f=a.minY,p=a.minZ,m=a.maxX,h=a.maxY,g=a.maxZ,_=a,v=i,y=[];do{for(y.length=0,y.push(u,_);y.length>0;){let t=y.pop(),n=y.pop();if(n-o<=l)continue;let r=Math.min(t.minX,e.minX),i=Math.min(t.minY,e.minY),a=Math.min(t.minZ,e.minZ),s=Math.max(t.maxX,e.maxX),u=Math.max(t.maxY,e.maxY),d=Math.max(t.maxZ,e.maxZ),f=s-r,p=u-i,m=d-a,h=n-(f*p+p*m+m*f);if(h>l&&(c=t,l=h),t.triangleCount===0&&t.leftChild&&t.rightChild){let e=h+this.surfaceArea(t);y.push(e,t.leftChild),y.push(e,t.rightChild)}}let t=n.get(v);if(!t||t.parent===null)break;if(v!==i){d=Math.min(d,_.minX),f=Math.min(f,_.minY),p=Math.min(p,_.minZ),m=Math.max(m,_.maxX),h=Math.max(h,_.maxY),g=Math.max(g,_.maxZ);let e=m-d,t=h-f,n=g-p,r=e*t+t*n+n*e;u+=this.surfaceArea(v)-r}let r=t.parent;_=t.isLeft?r.rightChild:r.leftChild,v=r}while(n.get(v).parent!==null);return c===a||c===i?null:c?{from:e,to:c,areaDiff:l}:null}getConflicts(e,t,n){let r=n.get(e);return[t,e,r.isLeft?r.parent.rightChild:r.parent.leftChild,n.get(t).parent,r.parent]}reinsertNode(e,t,n){let r=n.get(e),i=r.parent,a=r.isLeft?i.rightChild:i.leftChild,o=n.get(i),s=o.parent,c=n.get(t),l=c.parent;o.isLeft?s.leftChild=a:s.rightChild=a,i.leftChild=e,i.rightChild=t,i.triangleOffset=0,i.triangleCount=0,i.minX=Math.min(e.minX,t.minX),i.minY=Math.min(e.minY,t.minY),i.minZ=Math.min(e.minZ,t.minZ),i.maxX=Math.max(e.maxX,t.maxX),i.maxY=Math.max(e.maxY,t.maxY),i.maxZ=Math.max(e.maxZ,t.maxZ),c.isLeft?l.leftChild=i:l.rightChild=i,n.set(a,{parent:s,isLeft:o.isLeft}),n.set(i,{parent:l,isLeft:c.isLeft}),n.set(e,{parent:i,isLeft:!0}),n.set(t,{parent:i,isLeft:!1}),this.refitFrom(s,n),this.refitFrom(l,n)}refitFrom(e,t){let n=e;for(;n;){if(n.triangleCount===0&&n.leftChild&&n.rightChild){let e=n.leftChild,t=n.rightChild;n.minX=Math.min(e.minX,t.minX),n.minY=Math.min(e.minY,t.minY),n.minZ=Math.min(e.minZ,t.minZ),n.maxX=Math.max(e.maxX,t.maxX),n.maxY=Math.max(e.maxY,t.maxY),n.maxZ=Math.max(e.maxZ,t.maxZ)}let e=t.get(n);n=e?e.parent:null}}optimizeBVH(e,t){let n=performance.now();this.stats={reinsertionsApplied:0,iterations:0,timeMs:0};for(let r=0;r<this.maxIterations&&!(performance.now()-n>this.timeBudgetMs);r++){let i=this.buildParentMap(e),a=i.size,o=Math.max(1,Math.floor(a*this.batchSizeRatio));t&&t(`Reinsertion iter ${r+1}/${this.maxIterations}: selecting ${o} candidates`);let s=this.findCandidates(e,o,i),c=[];for(let t=0;t<s.length&&!(performance.now()-n>this.timeBudgetMs);t++){let n=this.findReinsertion(s[t].node,e,i);n&&n.areaDiff>0&&c.push(n)}c.sort((e,t)=>t.areaDiff-e.areaDiff);let l=new Set,u=0;for(let e of c){let t=this.getConflicts(e.from,e.to,i);if(!t.some(e=>l.has(e))){for(let e of t)l.add(e);this.reinsertNode(e.from,e.to,i),u++}}if(this.stats.reinsertionsApplied+=u,this.stats.iterations=r+1,t&&t(`Reinsertion iter ${r+1}: applied ${u} reinsertions`),u===0)break}return this.stats.timeMs=performance.now()-n,this.stats}};wt();var li=St.TRIANGLE_LEAF,ui=16,di=2147483648,fi=(e,t)=>~(e<<4|t)>>>0,pi=e=>e>=di,mi=e=>~e>>>0>>>4,hi=e=>~e&15;function gi(e){let t=new Uint32Array(e.buffer,e.byteOffset,e.length),n=e.length/ui,r=e=>{let n=e*ui;return t[n+3]===li&&t[n+1]>0&&t[n+1]<=15},i=new Uint32Array(n),a=new Uint32Array(n),o=0,s=[0];for(;s.length;){let e=s.pop();i[e]=o,a[o++]=e;let n=e*ui;t[n+3]>=1073741824||(r(t[n+7])||s.push(t[n+7]),r(t[n+3])||s.push(t[n+3]))}let c=new Float32Array(o*ui),l=new Uint32Array(c.buffer);for(let n=0;n<o;n++){let o=a[n]*ui,s=n*ui;c.set(e.subarray(o,o+ui),s),!(t[o+3]>=1073741824)&&(l[s+3]=_i(t,t[o+3],r,i),l[s+7]=_i(t,t[o+7],r,i))}return c}function _i(e,t,n,r){let i=t*ui;return n(t)?fi(e[i],e[i+1]):r[t]}var vi=(e,t,n)=>e>=di?fi(mi(e)+n,hi(e)):e+t;function yi(e,t,n,r=0,i=e.length){for(let a=r;a<i;a+=ui){if(e[a+3]===li){e[a]+=n;continue}e[a+3]=vi(e[a+3],t,n),e[a+7]=vi(e[a+7],t,n)}}Ae(),dr(),wt();var bi=ye(`bvh`),xi=St.TRIANGLE_LEAF,Si=St.FRONTIER,Ci=null;function wi(e){Ci=e}var Ti=K.FLOATS_PER_TRIANGLE,Ei=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),Di=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},Oi=class{constructor(){this.useWorker=!0,this.maxLeafSize=8,this.foldLeaves=!1,this.numBins=32,this.minBins=8,this.maxBins=64,this.totalNodes=0,this.processedTriangles=0,this.totalTriangles=0,this.lastProgressUpdate=0,this.progressUpdateInterval=100,this.traversalCost=1,this.intersectionCost=2.5,this.useMortonCodes=!0,this.mortonBits=10,this.mortonClusterThreshold=128,this.enableObjectMedianFallback=!0,this.enableSpatialMedianFallback=!0,this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0},this.enableReinsertionOptimization=!0,this.reinsertionBatchSizeRatio=.02,this.reinsertionMaxIterations=2,this.initializeBinArrays(),this._partResult={mid:0,lMinX:0,lMinY:0,lMinZ:0,lMaxX:0,lMaxY:0,lMaxZ:0,rMinX:0,rMinY:0,rMinZ:0,rMaxX:0,rMaxY:0,rMaxZ:0},this.centroids=null,this.bMin=null,this.bMax=null,this.indices=null,this.mortonCodes=null,this.triangles=null,this.reorderedTriangleData=null}initializeBinArrays(){let e=this.maxBins;this.binBoundsMin=new Float32Array(e*3),this.binBoundsMax=new Float32Array(e*3),this.binCounts=new Uint32Array(e),this.leftPrefixMin=new Float32Array(e*3),this.leftPrefixMax=new Float32Array(e*3),this.leftPrefixCount=new Uint32Array(e),this.rightPrefixMin=new Float32Array(e*3),this.rightPrefixMax=new Float32Array(e*3),this.rightPrefixCount=new Uint32Array(e)}getOptimalBinCount(e){return e<=16?this.minBins:e<=64?16:e<=256?32:e<=1024?48:this.maxBins}setAdaptiveBinConfig(e){e.minBins!==void 0&&(this.minBins=Math.max(4,e.minBins)),e.maxBins!==void 0&&(this.maxBins=Math.min(128,e.maxBins)),e.baseBins!==void 0&&(this.numBins=e.baseBins),e.maxBins!==void 0&&this.initializeBinArrays()}setMortonConfig(e){e.enabled!==void 0&&(this.useMortonCodes=e.enabled),e.bits!==void 0&&(this.mortonBits=Math.max(6,Math.min(10,e.bits))),e.threshold!==void 0&&(this.mortonClusterThreshold=Math.max(16,e.threshold))}setFallbackConfig(e){e.objectMedian!==void 0&&(this.enableObjectMedianFallback=e.objectMedian),e.spatialMedian!==void 0&&(this.enableSpatialMedianFallback=e.spatialMedian)}setReinsertionConfig(e){e.enabled!==void 0&&(this.enableReinsertionOptimization=e.enabled),e.batchSizeRatio!==void 0&&(this.reinsertionBatchSizeRatio=Math.max(.005,Math.min(.1,e.batchSizeRatio))),e.maxIterations!==void 0&&(this.reinsertionMaxIterations=Math.max(1,Math.min(5,e.maxIterations)))}initializeTriangleArrays(){let e=this.totalTriangles,t=Ei(this.triangles),n=K.POSITION_A_OFFSET,r=K.POSITION_B_OFFSET,i=K.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*Ti,o=t[e+n],s=t[e+n+1],c=t[e+n+2],l=t[e+r],u=t[e+r+1],d=t[e+r+2],f=t[e+i],p=t[e+i+1],m=t[e+i+2],h=a*3;this.centroids[h]=(o+l+f)/3,this.centroids[h+1]=(s+u+p)/3,this.centroids[h+2]=(c+d+m)/3,this.bMin[h]=o<l?o<f?o:f:l<f?l:f,this.bMin[h+1]=s<u?s<p?s:p:u<p?u:p,this.bMin[h+2]=c<d?c<m?c:m:d<m?d:m,this.bMax[h]=o>l?o>f?o:f:l>f?l:f,this.bMax[h+1]=s>u?s>p?s:p:u>p?u:p,this.bMax[h+2]=c>d?c>m?c:m:d>m?d:m,this.indices[a]=a}}expandBits(e){return e=e*65537&4278190335,e=e*257&251719695,e=e*17&3272356035,e=e*5&1227133513,e}morton3D(e,t,n){return(this.expandBits(n)<<2)+(this.expandBits(t)<<1)+this.expandBits(e)}computeMortonCodeForIndex(e,t,n,r,i,a,o){let s=this.centroids,c=e*3,l=(1<<this.mortonBits)-1,u=i>0?(s[c]-t)/i:0,d=a>0?(s[c+1]-n)/a:0,f=o>0?(s[c+2]-r)/o:0,p=Math.max(0,Math.min(l,Math.floor(u*l))),m=Math.max(0,Math.min(l,Math.floor(d*l))),h=Math.max(0,Math.min(l,Math.floor(f*l)));return this.morton3D(p,m,h)}sortTrianglesByMortonCode(){let e=this.totalTriangles;if(!this.useMortonCodes||e<this.mortonClusterThreshold)return;let t=performance.now(),n=this.centroids,r=this.indices,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let t=0;t<e;t++){let e=r[t]*3,u=n[e],d=n[e+1],f=n[e+2];u<i&&(i=u),d<a&&(a=d),f<o&&(o=f),u>s&&(s=u),d>c&&(c=d),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o,p=this.mortonCodes,m=(1<<this.mortonBits)-1,h=u>0?m/u:0,g=d>0?m/d:0,_=f>0?m/f:0;for(let t=0;t<e;t++){let e=r[t],s=e*3,c=(n[s]-i)*h,l=(n[s+1]-a)*g,u=(n[s+2]-o)*_;c=c<0?0:(c>m?m:c)|0,l=l<0?0:(l>m?m:l)|0,u=u<0?0:(u>m?m:u)|0,c=c*65537&4278190335,c=c*257&251719695,c=c*17&3272356035,c=c*5&1227133513,l=l*65537&4278190335,l=l*257&251719695,l=l*17&3272356035,l=l*5&1227133513,u=u*65537&4278190335,u=u*257&251719695,u=u*17&3272356035,u=u*5&1227133513,p[e]=(u<<2)+(l<<1)+c}let v=new Uint32Array(e),y=new Uint32Array(256);for(let t=0;t<32;t+=8){y.fill(0);for(let n=0;n<e;n++)y[p[r[n]]>>>t&255]++;let n=0;for(let e=0;e<256;e++){let t=y[e];y[e]=n,n+=t}for(let n=0;n<e;n++){let e=p[r[n]]>>>t&255;v[y[e]++]=r[n]}r.set(v)}this.splitStats.mortonSortTime+=performance.now()-t}build(e,t=30,n=null){return this.totalTriangles=e.byteLength/(Ti*4),this.processedTriangles=0,this.lastProgressUpdate=performance.now(),this.useWorker&&Ci&&or()?new Promise((r,i)=>{let a=a=>{let o=this.totalTriangles,s=typeof SharedArrayBuffer<`u`;bi.debug(`SharedArrayBuffer ${s?`enabled`:`unavailable (using transfer fallback)`}`);let c=s?new SharedArrayBuffer(o*Ti*4):null;a.onmessage=e=>{let{bvhData:t,triangles:o,originalToBvh:s,error:l,progress:u,splitStats:d}=e.data;if(l){a.terminate(),i(Error(l));return}if(u!==void 0&&n){n(u);return}d&&(this.splitStats=d),a.terminate(),r({bvhData:t,bvhRoot:!0,reorderedTriangles:c?new Float32Array(c):o,originalToBvh:s||null})},a.onerror=e=>{a.terminate(),i(e)};let l=e.buffer,u={triangleData:l,triangleByteOffset:e.byteOffset,triangleByteLength:e.byteLength,triangleCount:o,depth:t,reportProgress:!!n,sharedReorderBuffer:c,reinsertionOptimization:{enabled:this.enableReinsertionOptimization,batchSizeRatio:this.reinsertionBatchSizeRatio,maxIterations:this.reinsertionMaxIterations}};a.postMessage(u,[l])};try{a(Ci())}catch(i){bi.warn(`worker creation failed, falling back to synchronous build:`,i),r(this._buildSyncAndFlatten(e,t,n))}}):new Promise(r=>{r(this._buildSyncAndFlatten(e,t,n))})}_buildSyncAndFlatten(e,t,n){let r=this.buildSync(e,t,n),i=this.flattenBVH(r);return{bvhData:this.foldLeaves?gi(i):i,bvhRoot:!0,reorderedTriangles:this.reorderedTriangleData||null,originalToBvh:this.originalToBvhMap||null}}buildSync(e,t=30,n=null,r=null){let i=performance.now();this.totalNodes=0,this.processedTriangles=0,this.triangles=e,this.totalTriangles=e.byteLength/(Ti*4),this.lastProgressUpdate=performance.now(),this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0,saOrderTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let a=this.totalTriangles,o=performance.now();this.centroids=new Float32Array(a*3),this.bMin=new Float32Array(a*3),this.bMax=new Float32Array(a*3),this.indices=new Uint32Array(a),this.mortonCodes=new Uint32Array(a),this.initializeTriangleArrays(),this.splitStats.initTime=performance.now()-o,this.sortTrianglesByMortonCode();let s=performance.now(),c=this.buildNodeRecursive(0,a,t,n);if(this.splitStats.sahBuildTime=performance.now()-s,this.enableReinsertionOptimization&&this.totalTriangles>1e3){let e=new ci(this.traversalCost,this.intersectionCost);e.setBatchSizeRatio(this.reinsertionBatchSizeRatio),e.setMaxIterations(this.reinsertionMaxIterations);let t=n?e=>{n(e)}:null;try{e.optimizeBVH(c,t)}catch(e){bi.error(`reinsertion optimizer failed:`,e)}let r=e.getStatistics();this.splitStats.reinsertionOptimizationTime=r.timeMs,this.splitStats.reinsertionsApplied=r.reinsertionsApplied,this.splitStats.reinsertionIterations=r.iterations}let l=performance.now();this.applySAOrdering(c),this.splitStats.saOrderTime=performance.now()-l;let u=performance.now(),d=this.triangles,f=r||new d.constructor(a*Ti);for(let e=0;e<a;e++){let t=this.indices[e]*Ti,n=e*Ti;f.set(d.subarray(t,t+Ti),n)}this.reorderedTriangleData=f;let p=new Uint32Array(a);for(let e=0;e<a;e++)p[this.indices[e]]=e;this.originalToBvhMap=p,this.splitStats.reorderTime=performance.now()-u,this.splitStats.totalBuildTime=performance.now()-i;let m=this.splitStats.totalBuildTime,h=this.splitStats;return bi.debug(`${H.n(a)} tris → ${H.n(this.totalNodes)} nodes in ${H.ms(m)} | SAH ${h.sahSplits} objMed ${h.objectMedianSplits} spatMed ${h.spatialMedianSplits} failed ${h.failedSplits}`+(h.reinsertionsApplied?` | reinsertions ${h.reinsertionsApplied}`:``)),n&&n(100),this.centroids=null,this.bMin=null,this.bMax=null,this.mortonCodes=null,c}updateProgress(e,t){if(!t)return;this.processedTriangles+=e;let n=performance.now();n-this.lastProgressUpdate<this.progressUpdateInterval||(this.lastProgressUpdate=n,t(Math.min(Math.floor(this.processedTriangles/this.totalTriangles*100),99)))}buildNodeRecursiveToDepth(e,t,n,r,i,a,o,s,c,l,u){let d=new Di;this.totalNodes++;let f=t-e;if(a===void 0?this.updateNodeBounds(d,e,t):(d.minX=a,d.minY=o,d.minZ=s,d.maxX=c,d.maxY=l,d.maxZ=u),f<=this.maxLeafSize||n<=0)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;if(r<=0&&f>this.maxLeafSize*16){let r=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=r,this.frontierTasks.push({taskId:r,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}let p=this.findBestSplitPositionSAH(e,t,d);if(!p.success){if(this.splitStats.failedSplits++,r>0||f<=this.maxLeafSize*16)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;let a=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=a,this.frontierTasks.push({taskId:a,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}p.method===`SAH`?this.splitStats.sahSplits++:p.method===`object_median`?this.splitStats.objectMedianSplits++:p.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,p.axis,p.pos);let m=this._partResult,h=m.mid,g=m.lMinX,_=m.lMinY,v=m.lMinZ,y=m.lMaxX,b=m.lMaxY,x=m.lMaxZ,S=m.rMinX,C=m.rMinY,w=m.rMinZ,T=m.rMaxX,E=m.rMaxY,D=m.rMaxZ;return h===e||h===t?(d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d):(d.leftChild=this.buildNodeRecursiveToDepth(e,h,n-1,r-1,i,g,_,v,y,b,x),d.rightChild=this.buildNodeRecursiveToDepth(h,t,n-1,r-1,i,S,C,w,T,E,D),d)}buildNodeRecursive(e,t,n,r,i,a,o,s,c,l){let u=new Di;this.totalNodes++;let d=t-e;if(i===void 0?this.updateNodeBounds(u,e,t):(u.minX=i,u.minY=a,u.minZ=o,u.maxX=s,u.maxY=c,u.maxZ=l),d<=this.maxLeafSize||n<=0)return u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;let f=this.findBestSplitPositionSAH(e,t,u);if(!f.success)return this.splitStats.failedSplits++,u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;f.method===`SAH`?this.splitStats.sahSplits++:f.method===`object_median`?this.splitStats.objectMedianSplits++:f.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,f.axis,f.pos);let p=this._partResult,m=p.mid,h=p.lMinX,g=p.lMinY,_=p.lMinZ,v=p.lMaxX,y=p.lMaxY,b=p.lMaxZ,x=p.rMinX,S=p.rMinY,C=p.rMinZ,w=p.rMaxX,T=p.rMaxY,E=p.rMaxZ;return m===e||m===t?(u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u):(u.leftChild=this.buildNodeRecursive(e,m,n-1,r,h,g,_,v,y,b),u.rightChild=this.buildNodeRecursive(m,t,n-1,r,x,S,C,w,T,E),u)}partitionWithBounds(e,t,n,r){let i=this.indices,a=this.centroids,o=this.bMin,s=this.bMax,c=e,l=t-1,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(;c<=l;){let e=i[c],t=e*3;a[t+n]<=r?(o[t]<u&&(u=o[t]),o[t+1]<d&&(d=o[t+1]),o[t+2]<f&&(f=o[t+2]),s[t]>p&&(p=s[t]),s[t+1]>m&&(m=s[t+1]),s[t+2]>h&&(h=s[t+2]),c++):(o[t]<g&&(g=o[t]),o[t+1]<_&&(_=o[t+1]),o[t+2]<v&&(v=o[t+2]),s[t]>y&&(y=s[t]),s[t+1]>b&&(b=s[t+1]),s[t+2]>x&&(x=s[t+2]),i[c]=i[l],i[l]=e,l--)}let S=this._partResult;return S.mid=c,S.lMinX=u,S.lMinY=d,S.lMinZ=f,S.lMaxX=p,S.lMaxY=m,S.lMaxZ=h,S.rMinX=g,S.rMinY=_,S.rMinZ=v,S.rMaxX=y,S.rMaxY=b,S.rMaxZ=x,S}updateNodeBounds(e,t,n){let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0,l=this.indices,u=this.bMin,d=this.bMax;for(let e=t;e<n;e++){let t=l[e]*3;u[t]<r&&(r=u[t]),u[t+1]<i&&(i=u[t+1]),u[t+2]<a&&(a=u[t+2]),d[t]>o&&(o=d[t]),d[t+1]>s&&(s=d[t+1]),d[t+2]>c&&(c=d[t+2])}e.minX=r,e.minY=i,e.minZ=a,e.maxX=o,e.maxY=s,e.maxZ=c}findBestSplitPositionSAH(e,t,n){let r=1/0,i=-1,a=0,o=this.computeSurfaceAreaFlat(n.minX,n.minY,n.minZ,n.maxX,n.maxY,n.maxZ),s=t-e,c=this.intersectionCost*s,l=this.getOptimalBinCount(s);this.splitStats.totalSplitAttempts++,this.splitStats.avgBinsUsed=(this.splitStats.avgBinsUsed*(this.splitStats.totalSplitAttempts-1)+l)/this.splitStats.totalSplitAttempts;let u=this.indices,d=this.centroids,f=this.bMin,p=this.bMax,m=this.binBoundsMin,h=this.binBoundsMax,g=this.binCounts,_=this.leftPrefixMin,v=this.leftPrefixMax,y=this.leftPrefixCount,b=this.rightPrefixMin,x=this.rightPrefixMax,S=this.rightPrefixCount,C=1/0,w=-1/0,T=1/0,E=-1/0,D=1/0,O=-1/0;for(let n=e;n<t;n++){let e=u[n]*3,t=d[e],r=d[e+1],i=d[e+2];t<C&&(C=t),t>w&&(w=t),r<T&&(T=r),r>E&&(E=r),i<D&&(D=i),i>O&&(O=i)}let k=[C,T,D],A=[w,E,O];for(let n=0;n<3;n++){let s=k[n],C=A[n];if(C-s<1e-6)continue;for(let e=0;e<l;e++){g[e]=0;let t=e*3;m[t]=1/0,m[t+1]=1/0,m[t+2]=1/0,h[t]=-1/0,h[t+1]=-1/0,h[t+2]=-1/0}let w=l/(C-s);for(let r=e;r<t;r++){let e=u[r],t=d[e*3+n],i=Math.floor((t-s)*w);i>=l&&(i=l-1),g[i]++;let a=i*3,o=e*3;f[o]<m[a]&&(m[a]=f[o]),f[o+1]<m[a+1]&&(m[a+1]=f[o+1]),f[o+2]<m[a+2]&&(m[a+2]=f[o+2]),p[o]>h[a]&&(h[a]=p[o]),p[o+1]>h[a+1]&&(h[a+1]=p[o+1]),p[o+2]>h[a+2]&&(h[a+2]=p[o+2])}y[0]=g[0],_[0]=m[0],_[1]=m[1],_[2]=m[2],v[0]=h[0],v[1]=h[1],v[2]=h[2];for(let e=1;e<l;e++){let t=e*3,n=(e-1)*3;y[e]=y[e-1]+g[e];let r=_[n],i=m[t],a=_[n+1],o=m[t+1],s=_[n+2],c=m[t+2];_[t]=r<i?r:i,_[t+1]=a<o?a:o,_[t+2]=s<c?s:c;let l=v[n],u=h[t],d=v[n+1],f=h[t+1],p=v[n+2],b=h[t+2];v[t]=l>u?l:u,v[t+1]=d>f?d:f,v[t+2]=p>b?p:b}let T=l-1,E=T*3;S[T]=g[T],b[E]=m[E],b[E+1]=m[E+1],b[E+2]=m[E+2],x[E]=h[E],x[E+1]=h[E+1],x[E+2]=h[E+2];for(let e=T-1;e>=0;e--){let t=e*3,n=(e+1)*3;S[e]=S[e+1]+g[e];let r=b[n],i=m[t],a=b[n+1],o=m[t+1],s=b[n+2],c=m[t+2];b[t]=r<i?r:i,b[t+1]=a<o?a:o,b[t+2]=s<c?s:c;let l=x[n],u=h[t],d=x[n+1],f=h[t+1],p=x[n+2],_=h[t+2];x[t]=l>u?l:u,x[t+1]=d>f?d:f,x[t+2]=p>_?p:_}for(let e=1;e<l;e++){let t=(e-1)*3,u=e*3,d=y[e-1],f=S[e];if(d===0||f===0)continue;let p=v[t]-_[t],m=v[t+1]-_[t+1],h=v[t+2]-_[t+2],g=2*(p*m+m*h+h*p),w=x[u]-b[u],T=x[u+1]-b[u+1],E=x[u+2]-b[u+2],D=2*(w*T+T*E+E*w),O=this.traversalCost+g/o*d*this.intersectionCost+D/o*f*this.intersectionCost;O<r&&O<c&&(r=O,i=n,a=s+(C-s)*e/l)}}return i===-1?this.enableObjectMedianFallback?this.findObjectMedianSplit(e,t):this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`fallbacks_disabled`}:{success:!0,axis:i,pos:a,method:`SAH`,binsUsed:l}}findObjectMedianSplit(e,t){let n=this.indices,r=this.centroids,i=-1,a=-1;for(let o=0;o<3;o++){let s=1/0,c=-1/0;for(let i=e;i<t;i++){let e=r[n[i]*3+o];e<s&&(s=e),e>c&&(c=e)}let l=c-s;l>a&&(a=l,i=o)}if(i===-1||a<1e-10)return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_failed`};let o=t-e,s=e+Math.floor(o/2);this.quickselect(e,t,s,i);let c=r[n[s]*3+i],l=!0;for(let e=s+1;e<t;e++)if(r[n[e]*3+i]>c){l=!1;break}if(l){let a=-1/0;for(let t=e;t<s;t++){let e=r[n[t]*3+i];e>a&&(a=e)}if(a<c)c=(a+c)*.5;else return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_degenerate`}}return{success:!0,axis:i,pos:c,method:`object_median`}}findSpatialMedianSplit(e,t){let n=this.indices,r=this.centroids,i=this.bMin,a=this.bMax,o=-1,s=-1,c=0,l=0;for(let r=0;r<3;r++){let u=1/0,d=-1/0;for(let o=e;o<t;o++){let e=n[o]*3+r;i[e]<u&&(u=i[e]),a[e]>d&&(d=a[e])}let f=d-u;f>s&&(s=f,o=r,c=u,l=d)}if(o===-1||s<1e-12)return{success:!1,method:`spatial_median_failed`};let u=(c+l)*.5,d=t-e,f=0;for(let i=e;i<t;i++)r[n[i]*3+o]<=u&&f++;if(f===0||f===d){let i=e+Math.floor(d/2);this.quickselect(e,t,i,o);let a=r[n[i]*3+o],s=!0;for(let i=e;i<t;i++)if(r[n[i]*3+o]!==a){s=!1;break}if(s)return{success:!1,method:`spatial_median_degenerate`};let c=-1/0;for(let t=e;t<i;t++){let e=r[n[t]*3+o];e>c&&(c=e)}if(c<a)u=(c+a)*.5;else{let e=1/0;for(let a=i+1;a<t;a++){let t=r[n[a]*3+o];t<e&&(e=t)}u=(a+e)*.5}}return{success:!0,axis:o,pos:u,method:`spatial_median`}}quickselect(e,t,n,r){let i=this.indices,a=this.centroids,o=e,s=t-1;for(;o<s;){let e=o+s>>>1,t=a[i[o]*3+r],c=a[i[e]*3+r],l=a[i[s]*3+r];if(t>c){let t=i[o];i[o]=i[e],i[e]=t}if(t>l){let e=i[o];i[o]=i[s],i[s]=e}if(c>l){let t=i[e];i[e]=i[s],i[s]=t}let u=a[i[e]*3+r],d=o,f=s;for(;d<=f;){for(;a[i[d]*3+r]<u;)d++;for(;a[i[f]*3+r]>u;)f--;if(d<=f){let e=i[d];i[d]=i[f],i[f]=e,d++,f--}}f<n&&(o=d),d>n&&(s=f)}}applySAOrdering(e){if(!e||!e.leftChild)return;let t=[e],n=[];for(;t.length>0;){let e=t.pop();!e.leftChild||!e.rightChild||(n.push(e),t.push(e.leftChild),t.push(e.rightChild))}for(let e=n.length-1;e>=0;e--){let t=n[e],r=t.leftChild,i=t.rightChild,a=r.maxX-r.minX,o=r.maxY-r.minY,s=r.maxZ-r.minZ,c=i.maxX-i.minX,l=i.maxY-i.minY,u=i.maxZ-i.minZ;c*l+l*u+u*c>a*o+o*s+s*a&&(t.leftChild=i,t.rightChild=r)}}flattenBVH(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}gt(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=ht(r);for(let e=0;e<t.length;e++){let n=t[e],a=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[a]=e.minX,r[a+1]=e.minY,r[a+2]=e.minZ,i[a+3]=e._flatIndex,r[a+4]=e.maxX,r[a+5]=e.maxY,r[a+6]=e.maxZ,i[a+7]=t._flatIndex,r[a+8]=t.minX,r[a+9]=t.minY,r[a+10]=t.minZ,r[a+12]=t.maxX,r[a+13]=t.maxY,r[a+14]=t.maxZ}else i[a]=n.triangleOffset,i[a+1]=n.triangleCount,i[a+3]=xi}return r}flattenBVHWithFrontier(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}gt(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=[],a=ht(r);for(let e=0;e<t.length;e++){let n=t[e],o=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[o]=e.minX,r[o+1]=e.minY,r[o+2]=e.minZ,a[o+3]=e._flatIndex,r[o+4]=e.maxX,r[o+5]=e.maxY,r[o+6]=e.maxZ,a[o+7]=t._flatIndex,r[o+8]=t.minX,r[o+9]=t.minY,r[o+10]=t.minZ,r[o+12]=t.maxX,r[o+13]=t.maxY,r[o+14]=t.maxZ}else if(n.isFrontier){let t=n.frontierTaskId;a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+2]=t,a[o+3]=Si,i.push({taskId:t,flatIndex:e})}else a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+3]=xi}return{flatData:r,frontierMap:i,nodeCount:t.length}}assembleParallelBVH(e,t,n,r){let i=[...r].sort((e,t)=>e.taskId-t.taskId),a=t;for(let e=0;e<i.length;e++)a+=i[e].nodeCount;gt(a,`assembled BLAS node count`);let o=new Float32Array(a*16),s=ht(o);o.set(e);let c=new Map;for(let e of n)c.set(e.taskId,e.flatIndex);let l=t;for(let e=0;e<i.length;e++){let t=i[e],n=t.flatData,r=t.nodeCount,a=l*16;o.set(n,a);for(let e=0;e<r;e++){let t=a+e*16;s[t+3]<xi&&(s[t+3]+=l,s[t+7]+=l)}let u=c.get(t.taskId);if(u!==void 0){let e=u*16,t=a;for(let n=0;n<16;n++)o[e+n]=o[t+n]}l+=r}return o}computeSurfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}};wt();var ki=K.FLOATS_PER_TRIANGLE,Ai=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),ji=e=>e instanceof Uint32Array?e:new Uint32Array(e.buffer,e.byteOffset,e.length),Mi=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:e,idx:t?e.viewAs(Uint32Array):ji(e)}},Ni=(e,t)=>e.chunked?e.f.chunkFor(t):e.f,Pi=(e,t)=>e.chunked?e.idx.chunkFor(t):e.idx,Fi=(e,t)=>e.chunked?e.chunked.baseOf(t):t*Li,Ii=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:t?t.viewAs(Float32Array):Ai(e),u:t?e:ji(e)}},Li=16,Ri=St.TRIANGLE_LEAF,zi=St.BLAS_POINTER_LEAF,Bi=1e-12;function Vi(e,t,n,r,i,a){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)<=Bi*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,ee=-1/0,te=-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>ee&&(ee=s),c<I&&(I=c),c>te&&(te=c)}i[a]=P,i[a+1]=F,i[a+2]=I,i[a+3]=L,i[a+4]=ee,i[a+5]=te}function Hi(e,t,n,r,i){let a=K.POSITION_A_OFFSET,o=K.POSITION_B_OFFSET,s=K.POSITION_C_OFFSET,c=1/0,l=1/0,u=1/0,d=-1/0,f=-1/0,p=-1/0;for(let r=0;r<n;r++){let n=t+r,i=e.chunked?e.f.chunkFor(n):e.f,m=e.chunked?e.chunked.baseOf(n):n*ki;c=Math.min(c,i[m+a],i[m+o],i[m+s]),l=Math.min(l,i[m+a+1],i[m+o+1],i[m+s+1]),u=Math.min(u,i[m+a+2],i[m+o+2],i[m+s+2]),d=Math.max(d,i[m+a],i[m+o],i[m+s]),f=Math.max(f,i[m+a+1],i[m+o+1],i[m+s+1]),p=Math.max(p,i[m+a+2],i[m+o+2],i[m+s+2])}r[i]=c,r[i+1]=l,r[i+2]=u,r[i+3]=d,r[i+4]=f,r[i+5]=p}var Ui=new Float32Array(12);function Wi(e,t,n,r){let i=Ni(e,t),a=Pi(e,t),o=Fi(e,t);if(a[o+3]===Ri){Hi(n,a[o],a[o+1],r,0);return}for(let e=0;e<3;e++)r[e]=Math.min(i[o+e],i[o+8+e]),r[3+e]=Math.max(i[o+4+e],i[o+12+e])}function Gi(e,t,n,r,i){let a=Ni(e,t),o=Pi(e,t),s=Fi(e,t),c=(t-i)*6,l=o[s+3];if(l===Ri){Hi(n,o[s],o[s+1],r,c);return}if(l===zi){Vi(a,s,r,(o[s]-i)*6,r,c);return}let u=o[s+7],d=r,f=(l-i)*6;pi(l)&&(Hi(n,mi(l),hi(l),Ui,0),d=Ui,f=0);let p=r,m=(u-i)*6;pi(u)&&(Hi(n,mi(u),hi(u),Ui,6),p=Ui,m=6),a[s]=d[f],a[s+1]=d[f+1],a[s+2]=d[f+2],a[s+4]=d[f+3],a[s+5]=d[f+4],a[s+6]=d[f+5],a[s+8]=p[m],a[s+9]=p[m+1],a[s+10]=p[m+2],a[s+12]=p[m+3],a[s+13]=p[m+4],a[s+14]=p[m+5];for(let e=0;e<3;e++)r[c+e]=Math.min(d[f+e],p[m+e]),r[c+3+e]=Math.max(d[f+3+e],p[m+3+e])}var Ki=class{constructor(){this._bounds=null,this._boundsNodeCount=0,this._tlasBounds=null,this._rootBox=null}updateTrianglePositions(e,t,n){let r=n.length,i=Ii(e);for(let e=0;e<r;e++){let r=n[e],a=i.chunked?i.f.chunkFor(e):i.f,o=i.chunked?i.u.chunkFor(e):i.u,s=i.chunked?i.chunked.baseOf(e):e*ki,c=r*9,l=t[c],u=t[c+1],d=t[c+2],f=t[c+3],p=t[c+4],m=t[c+5],h=t[c+6],g=t[c+7],_=t[c+8];a[s+K.POSITION_A_OFFSET]=l,a[s+K.POSITION_A_OFFSET+1]=u,a[s+K.POSITION_A_OFFSET+2]=d,a[s+K.POSITION_B_OFFSET]=f,a[s+K.POSITION_B_OFFSET+1]=p,a[s+K.POSITION_B_OFFSET+2]=m,a[s+K.POSITION_C_OFFSET]=h,a[s+K.POSITION_C_OFFSET+1]=g,a[s+K.POSITION_C_OFFSET+2]=_;let v=f-l,y=p-u,b=m-d,x=h-l,S=g-u,C=_-d,w=mt(y*C-b*S,b*x-v*C,v*S-y*x);o[s+K.NORMAL_A_PACKED_OFFSET]=w,o[s+K.NORMAL_B_PACKED_OFFSET]=w,o[s+K.NORMAL_C_PACKED_OFFSET]=w}}refitRange(e,t,n,r){let i=Ii(t);r>this._boundsNodeCount&&(this._bounds=new Float32Array(r*6),this._boundsNodeCount=r);let a=Mi(e);for(let e=n+r-1;e>=n;e--)Gi(a,e,i,this._bounds,n)}refitPartial(e,t,n,r){for(let r=0;r<n.length;r+=2)this.refitRange(e,t,n[r],n[r+1]);let i=Ii(t),a=Mi(e);(!this._tlasBounds||this._tlasBounds.length<r*6)&&(this._tlasBounds=new Float32Array(r*6));let o=this._tlasBounds,s=this._rootBox||=new Float32Array(6);for(let e=r-1;e>=0;e--){let t=Pi(a,e),n=Fi(a,e);t[n+3]===zi?(Wi(a,t[n],i,s),Vi(Ni(a,e),n,s,0,o,e*6)):Gi(a,e,i,o,0)}}refit(e,t,n){let r=Ii(t);n!==this._boundsNodeCount&&(this._bounds=new Float32Array(n*6),this._boundsNodeCount=n);let i=Mi(e);for(let e=n-1;e>=0;e--)Gi(i,e,r,this._bounds,0)}},qi="var e=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.batchSizeRatio=.02,this.maxIterations=2,this.timeBudgetMs=15e3,this.stats={reinsertionsApplied:0,iterations:0,timeMs:0}}setBatchSizeRatio(e){this.batchSizeRatio=Math.max(.005,Math.min(.1,e))}setMaxIterations(e){this.maxIterations=Math.max(1,Math.min(5,e))}getStatistics(){return{...this.stats}}surfaceArea(e){let t=e.maxX-e.minX,n=e.maxY-e.minY,r=e.maxZ-e.minZ;return t*n+n*r+r*t}buildParentMap(e){let t=new Map;t.set(e,{parent:null,isLeft:!1});let n=[e];for(;n.length>0;){let e=n.pop();e.triangleCount>0||(e.leftChild&&(t.set(e.leftChild,{parent:e,isLeft:!0}),n.push(e.leftChild)),e.rightChild&&(t.set(e.rightChild,{parent:e,isLeft:!1}),n.push(e.rightChild)))}return t}findCandidates(e,t,n){let r=[],i=[e];for(;i.length>0;){let a=i.pop();if(a!==e&&n.get(a).parent!==e){let e=this.surfaceArea(a);r.length<t?(r.push({node:a,cost:e}),r.length===t&&this._heapify(r)):e>r[0].cost&&(r[0]={node:a,cost:e},this._siftDown(r,0))}a.triangleCount===0&&(a.leftChild&&i.push(a.leftChild),a.rightChild&&i.push(a.rightChild))}return r}_heapify(e){for(let t=(e.length>>1)-1;t>=0;t--)this._siftDown(e,t)}_siftDown(e,t){let n=e.length;for(;;){let r=t,i=2*t+1,a=2*t+2;if(i<n&&e[i].cost<e[r].cost&&(r=i),a<n&&e[a].cost<e[r].cost&&(r=a),r===t)break;let o=e[t];e[t]=e[r],e[r]=o,t=r}}findReinsertion(e,t,n){let r=n.get(e),i=r.parent;if(!i)return null;let a=r.isLeft?i.rightChild:i.leftChild,o=this.surfaceArea(e),s=this.surfaceArea(i),c=null,l=0,u=s,d=a.minX,f=a.minY,p=a.minZ,m=a.maxX,h=a.maxY,g=a.maxZ,_=a,v=i,y=[];do{for(y.length=0,y.push(u,_);y.length>0;){let t=y.pop(),n=y.pop();if(n-o<=l)continue;let r=Math.min(t.minX,e.minX),i=Math.min(t.minY,e.minY),a=Math.min(t.minZ,e.minZ),s=Math.max(t.maxX,e.maxX),u=Math.max(t.maxY,e.maxY),d=Math.max(t.maxZ,e.maxZ),f=s-r,p=u-i,m=d-a,h=n-(f*p+p*m+m*f);if(h>l&&(c=t,l=h),t.triangleCount===0&&t.leftChild&&t.rightChild){let e=h+this.surfaceArea(t);y.push(e,t.leftChild),y.push(e,t.rightChild)}}let t=n.get(v);if(!t||t.parent===null)break;if(v!==i){d=Math.min(d,_.minX),f=Math.min(f,_.minY),p=Math.min(p,_.minZ),m=Math.max(m,_.maxX),h=Math.max(h,_.maxY),g=Math.max(g,_.maxZ);let e=m-d,t=h-f,n=g-p,r=e*t+t*n+n*e;u+=this.surfaceArea(v)-r}let r=t.parent;_=t.isLeft?r.rightChild:r.leftChild,v=r}while(n.get(v).parent!==null);return c===a||c===i?null:c?{from:e,to:c,areaDiff:l}:null}getConflicts(e,t,n){let r=n.get(e);return[t,e,r.isLeft?r.parent.rightChild:r.parent.leftChild,n.get(t).parent,r.parent]}reinsertNode(e,t,n){let r=n.get(e),i=r.parent,a=r.isLeft?i.rightChild:i.leftChild,o=n.get(i),s=o.parent,c=n.get(t),l=c.parent;o.isLeft?s.leftChild=a:s.rightChild=a,i.leftChild=e,i.rightChild=t,i.triangleOffset=0,i.triangleCount=0,i.minX=Math.min(e.minX,t.minX),i.minY=Math.min(e.minY,t.minY),i.minZ=Math.min(e.minZ,t.minZ),i.maxX=Math.max(e.maxX,t.maxX),i.maxY=Math.max(e.maxY,t.maxY),i.maxZ=Math.max(e.maxZ,t.maxZ),c.isLeft?l.leftChild=i:l.rightChild=i,n.set(a,{parent:s,isLeft:o.isLeft}),n.set(i,{parent:l,isLeft:c.isLeft}),n.set(e,{parent:i,isLeft:!0}),n.set(t,{parent:i,isLeft:!1}),this.refitFrom(s,n),this.refitFrom(l,n)}refitFrom(e,t){let n=e;for(;n;){if(n.triangleCount===0&&n.leftChild&&n.rightChild){let e=n.leftChild,t=n.rightChild;n.minX=Math.min(e.minX,t.minX),n.minY=Math.min(e.minY,t.minY),n.minZ=Math.min(e.minZ,t.minZ),n.maxX=Math.max(e.maxX,t.maxX),n.maxY=Math.max(e.maxY,t.maxY),n.maxZ=Math.max(e.maxZ,t.maxZ)}let e=t.get(n);n=e?e.parent:null}}optimizeBVH(e,t){let n=performance.now();this.stats={reinsertionsApplied:0,iterations:0,timeMs:0};for(let r=0;r<this.maxIterations&&!(performance.now()-n>this.timeBudgetMs);r++){let i=this.buildParentMap(e),a=i.size,o=Math.max(1,Math.floor(a*this.batchSizeRatio));t&&t(`Reinsertion iter ${r+1}/${this.maxIterations}: selecting ${o} candidates`);let s=this.findCandidates(e,o,i),c=[];for(let t=0;t<s.length&&!(performance.now()-n>this.timeBudgetMs);t++){let n=this.findReinsertion(s[t].node,e,i);n&&n.areaDiff>0&&c.push(n)}c.sort((e,t)=>t.areaDiff-e.areaDiff);let l=new Set,u=0;for(let e of c){let t=this.getConflicts(e.from,e.to,i);if(!t.some(e=>l.has(e))){for(let e of t)l.add(e);this.reinsertNode(e.from,e.to,i),u++}}if(this.stats.reinsertionsApplied+=u,this.stats.iterations=r+1,t&&t(`Reinsertion iter ${r+1}: applied ${u} reinsertions`),u===0)break}return this.stats.timeMs=performance.now()-n,this.stats}};const t={silent:0,error:1,warn:2,info:3,debug:4},n=`info`,r=`rayzeeLogLevel`,i=`rayzeeLogNamespaces`,a=`color:#7c8494`,o=`color:inherit`;let s=null,c=null;function l(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function u(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function d(){if(s!==null)return s;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in t?(s=t[e],s):(s=t[l(r)]??t[n],s)}function f(){if(c!==null)return c;let e=globalThis.__RAYZEE_LOG_NS__??l(i);return c=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],c}function p(e,n){if(n<t.debug)return!0;let r=f();return r.length===0||r.some(t=>e===t||e.startsWith(`${t}:`))}function m(e,n,r){if(e>d()||!p(n,e))return;let i=e===t.error?console.error:e===t.warn?console.warn:console.log,s=`[${n}]`;typeof r[0]==`string`?i(`%c${s}%c ${r[0]}`,a,o,...r.slice(1)):i(`%c${s}`,a,...r)}const h={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`)=>`${h.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},g={levels:t,setLevel(e){return e in t?(globalThis.__RAYZEE_LOG_LEVEL__=e,s=t[e],u(r,e===n?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(t).join(`, `)}`),this.getLevel())},getLevel(){let e=d();return Object.keys(t).find(n=>t[n]===e)},isEnabled(e){return(t[e]??t.debug)<=d()},only(...e){let t=e.flat().filter(Boolean);return c=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),u(i,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return s=null,c=null,this.getLevel()}};function _(e){return{namespace:e,error:(...n)=>m(t.error,e,n),warn:(...n)=>m(t.warn,e,n),info:(...n)=>m(t.info,e,n),debug:(...n)=>m(t.debug,e,n),isEnabled:e=>g.isEnabled(e),summary(n,r=[]){let i=r.filter(Boolean);if(i.length===0||!console.groupCollapsed){m(t.info,e,[n]),i.forEach(n=>m(t.debug,e,[n]));return}t.info>d()||((d()>=t.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${n}`,a,o),i.forEach(e=>console.log(e)),console.groupEnd())}}}function v(e){e&&e in t&&(globalThis.__RAYZEE_LOG_LEVEL__=e,s=t[e])}const y={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},b={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826};function x(e){return new Uint32Array(e.buffer,e.byteOffset,e.length)}function S(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 C=b.TRIANGLE_LEAF,w=(e,t)=>~(e<<4|t)>>>0;function T(e){let t=new Uint32Array(e.buffer,e.byteOffset,e.length),n=e.length/16,r=e=>{let n=e*16;return t[n+3]===C&&t[n+1]>0&&t[n+1]<=15},i=new Uint32Array(n),a=new Uint32Array(n),o=0,s=[0];for(;s.length;){let e=s.pop();i[e]=o,a[o++]=e;let n=e*16;t[n+3]>=1073741824||(r(t[n+7])||s.push(t[n+7]),r(t[n+3])||s.push(t[n+3]))}let c=new Float32Array(o*16),l=new Uint32Array(c.buffer);for(let n=0;n<o;n++){let o=a[n]*16,s=n*16;c.set(e.subarray(o,o+16),s),!(t[o+3]>=1073741824)&&(l[s+3]=E(t,t[o+3],r,i),l[s+7]=E(t,t[o+7],r,i))}return c}function E(e,t,n,r){let i=t*16;return n(t)?w(e[i],e[i+1]):r[t]}const D=_(`bvh`),O=b.TRIANGLE_LEAF,k=b.FRONTIER,A=y.FLOATS_PER_TRIANGLE,j=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length);var M=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},N=class{constructor(){this.useWorker=!0,this.maxLeafSize=8,this.foldLeaves=!1,this.numBins=32,this.minBins=8,this.maxBins=64,this.totalNodes=0,this.processedTriangles=0,this.totalTriangles=0,this.lastProgressUpdate=0,this.progressUpdateInterval=100,this.traversalCost=1,this.intersectionCost=2.5,this.useMortonCodes=!0,this.mortonBits=10,this.mortonClusterThreshold=128,this.enableObjectMedianFallback=!0,this.enableSpatialMedianFallback=!0,this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0},this.enableReinsertionOptimization=!0,this.reinsertionBatchSizeRatio=.02,this.reinsertionMaxIterations=2,this.initializeBinArrays(),this._partResult={mid:0,lMinX:0,lMinY:0,lMinZ:0,lMaxX:0,lMaxY:0,lMaxZ:0,rMinX:0,rMinY:0,rMinZ:0,rMaxX:0,rMaxY:0,rMaxZ:0},this.centroids=null,this.bMin=null,this.bMax=null,this.indices=null,this.mortonCodes=null,this.triangles=null,this.reorderedTriangleData=null}initializeBinArrays(){let e=this.maxBins;this.binBoundsMin=new Float32Array(e*3),this.binBoundsMax=new Float32Array(e*3),this.binCounts=new Uint32Array(e),this.leftPrefixMin=new Float32Array(e*3),this.leftPrefixMax=new Float32Array(e*3),this.leftPrefixCount=new Uint32Array(e),this.rightPrefixMin=new Float32Array(e*3),this.rightPrefixMax=new Float32Array(e*3),this.rightPrefixCount=new Uint32Array(e)}getOptimalBinCount(e){return e<=16?this.minBins:e<=64?16:e<=256?32:e<=1024?48:this.maxBins}setAdaptiveBinConfig(e){e.minBins!==void 0&&(this.minBins=Math.max(4,e.minBins)),e.maxBins!==void 0&&(this.maxBins=Math.min(128,e.maxBins)),e.baseBins!==void 0&&(this.numBins=e.baseBins),e.maxBins!==void 0&&this.initializeBinArrays()}setMortonConfig(e){e.enabled!==void 0&&(this.useMortonCodes=e.enabled),e.bits!==void 0&&(this.mortonBits=Math.max(6,Math.min(10,e.bits))),e.threshold!==void 0&&(this.mortonClusterThreshold=Math.max(16,e.threshold))}setFallbackConfig(e){e.objectMedian!==void 0&&(this.enableObjectMedianFallback=e.objectMedian),e.spatialMedian!==void 0&&(this.enableSpatialMedianFallback=e.spatialMedian)}setReinsertionConfig(e){e.enabled!==void 0&&(this.enableReinsertionOptimization=e.enabled),e.batchSizeRatio!==void 0&&(this.reinsertionBatchSizeRatio=Math.max(.005,Math.min(.1,e.batchSizeRatio))),e.maxIterations!==void 0&&(this.reinsertionMaxIterations=Math.max(1,Math.min(5,e.maxIterations)))}initializeTriangleArrays(){let e=this.totalTriangles,t=j(this.triangles),n=y.POSITION_A_OFFSET,r=y.POSITION_B_OFFSET,i=y.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*A,o=t[e+n],s=t[e+n+1],c=t[e+n+2],l=t[e+r],u=t[e+r+1],d=t[e+r+2],f=t[e+i],p=t[e+i+1],m=t[e+i+2],h=a*3;this.centroids[h]=(o+l+f)/3,this.centroids[h+1]=(s+u+p)/3,this.centroids[h+2]=(c+d+m)/3,this.bMin[h]=o<l?o<f?o:f:l<f?l:f,this.bMin[h+1]=s<u?s<p?s:p:u<p?u:p,this.bMin[h+2]=c<d?c<m?c:m:d<m?d:m,this.bMax[h]=o>l?o>f?o:f:l>f?l:f,this.bMax[h+1]=s>u?s>p?s:p:u>p?u:p,this.bMax[h+2]=c>d?c>m?c:m:d>m?d:m,this.indices[a]=a}}expandBits(e){return e=e*65537&4278190335,e=e*257&251719695,e=e*17&3272356035,e=e*5&1227133513,e}morton3D(e,t,n){return(this.expandBits(n)<<2)+(this.expandBits(t)<<1)+this.expandBits(e)}computeMortonCodeForIndex(e,t,n,r,i,a,o){let s=this.centroids,c=e*3,l=(1<<this.mortonBits)-1,u=i>0?(s[c]-t)/i:0,d=a>0?(s[c+1]-n)/a:0,f=o>0?(s[c+2]-r)/o:0,p=Math.max(0,Math.min(l,Math.floor(u*l))),m=Math.max(0,Math.min(l,Math.floor(d*l))),h=Math.max(0,Math.min(l,Math.floor(f*l)));return this.morton3D(p,m,h)}sortTrianglesByMortonCode(){let e=this.totalTriangles;if(!this.useMortonCodes||e<this.mortonClusterThreshold)return;let t=performance.now(),n=this.centroids,r=this.indices,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let t=0;t<e;t++){let e=r[t]*3,u=n[e],d=n[e+1],f=n[e+2];u<i&&(i=u),d<a&&(a=d),f<o&&(o=f),u>s&&(s=u),d>c&&(c=d),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o,p=this.mortonCodes,m=(1<<this.mortonBits)-1,h=u>0?m/u:0,g=d>0?m/d:0,_=f>0?m/f:0;for(let t=0;t<e;t++){let e=r[t],s=e*3,c=(n[s]-i)*h,l=(n[s+1]-a)*g,u=(n[s+2]-o)*_;c=c<0?0:(c>m?m:c)|0,l=l<0?0:(l>m?m:l)|0,u=u<0?0:(u>m?m:u)|0,c=c*65537&4278190335,c=c*257&251719695,c=c*17&3272356035,c=c*5&1227133513,l=l*65537&4278190335,l=l*257&251719695,l=l*17&3272356035,l=l*5&1227133513,u=u*65537&4278190335,u=u*257&251719695,u=u*17&3272356035,u=u*5&1227133513,p[e]=(u<<2)+(l<<1)+c}let v=new Uint32Array(e),y=new Uint32Array(256);for(let t=0;t<32;t+=8){y.fill(0);for(let n=0;n<e;n++)y[p[r[n]]>>>t&255]++;let n=0;for(let e=0;e<256;e++){let t=y[e];y[e]=n,n+=t}for(let n=0;n<e;n++){let e=p[r[n]]>>>t&255;v[y[e]++]=r[n]}r.set(v)}this.splitStats.mortonSortTime+=performance.now()-t}build(e,t=30,n=null){if(this.totalTriangles=e.byteLength/(A*4),this.processedTriangles=0,this.lastProgressUpdate=performance.now(),!(this.useWorker&&null))return new Promise(r=>{r(this._buildSyncAndFlatten(e,t,n))})}_buildSyncAndFlatten(e,t,n){let r=this.buildSync(e,t,n),i=this.flattenBVH(r);return{bvhData:this.foldLeaves?T(i):i,bvhRoot:!0,reorderedTriangles:this.reorderedTriangleData||null,originalToBvh:this.originalToBvhMap||null}}buildSync(t,n=30,r=null,i=null){let a=performance.now();this.totalNodes=0,this.processedTriangles=0,this.triangles=t,this.totalTriangles=t.byteLength/(A*4),this.lastProgressUpdate=performance.now(),this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0,saOrderTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let o=this.totalTriangles,s=performance.now();this.centroids=new Float32Array(o*3),this.bMin=new Float32Array(o*3),this.bMax=new Float32Array(o*3),this.indices=new Uint32Array(o),this.mortonCodes=new Uint32Array(o),this.initializeTriangleArrays(),this.splitStats.initTime=performance.now()-s,this.sortTrianglesByMortonCode();let c=performance.now(),l=this.buildNodeRecursive(0,o,n,r);if(this.splitStats.sahBuildTime=performance.now()-c,this.enableReinsertionOptimization&&this.totalTriangles>1e3){let t=new e(this.traversalCost,this.intersectionCost);t.setBatchSizeRatio(this.reinsertionBatchSizeRatio),t.setMaxIterations(this.reinsertionMaxIterations);let n=r?e=>{r(e)}:null;try{t.optimizeBVH(l,n)}catch(e){D.error(`reinsertion optimizer failed:`,e)}let i=t.getStatistics();this.splitStats.reinsertionOptimizationTime=i.timeMs,this.splitStats.reinsertionsApplied=i.reinsertionsApplied,this.splitStats.reinsertionIterations=i.iterations}let u=performance.now();this.applySAOrdering(l),this.splitStats.saOrderTime=performance.now()-u;let d=performance.now(),f=this.triangles,p=i||new f.constructor(o*A);for(let e=0;e<o;e++){let t=this.indices[e]*A,n=e*A;p.set(f.subarray(t,t+A),n)}this.reorderedTriangleData=p;let m=new Uint32Array(o);for(let e=0;e<o;e++)m[this.indices[e]]=e;this.originalToBvhMap=m,this.splitStats.reorderTime=performance.now()-d,this.splitStats.totalBuildTime=performance.now()-a;let g=this.splitStats.totalBuildTime,_=this.splitStats;return D.debug(`${h.n(o)} tris → ${h.n(this.totalNodes)} nodes in ${h.ms(g)} | SAH ${_.sahSplits} objMed ${_.objectMedianSplits} spatMed ${_.spatialMedianSplits} failed ${_.failedSplits}`+(_.reinsertionsApplied?` | reinsertions ${_.reinsertionsApplied}`:``)),r&&r(100),this.centroids=null,this.bMin=null,this.bMax=null,this.mortonCodes=null,l}updateProgress(e,t){if(!t)return;this.processedTriangles+=e;let n=performance.now();n-this.lastProgressUpdate<this.progressUpdateInterval||(this.lastProgressUpdate=n,t(Math.min(Math.floor(this.processedTriangles/this.totalTriangles*100),99)))}buildNodeRecursiveToDepth(e,t,n,r,i,a,o,s,c,l,u){let d=new M;this.totalNodes++;let f=t-e;if(a===void 0?this.updateNodeBounds(d,e,t):(d.minX=a,d.minY=o,d.minZ=s,d.maxX=c,d.maxY=l,d.maxZ=u),f<=this.maxLeafSize||n<=0)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;if(r<=0&&f>this.maxLeafSize*16){let r=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=r,this.frontierTasks.push({taskId:r,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}let p=this.findBestSplitPositionSAH(e,t,d);if(!p.success){if(this.splitStats.failedSplits++,r>0||f<=this.maxLeafSize*16)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;let a=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=a,this.frontierTasks.push({taskId:a,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}p.method===`SAH`?this.splitStats.sahSplits++:p.method===`object_median`?this.splitStats.objectMedianSplits++:p.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,p.axis,p.pos);let m=this._partResult,h=m.mid,g=m.lMinX,_=m.lMinY,v=m.lMinZ,y=m.lMaxX,b=m.lMaxY,x=m.lMaxZ,S=m.rMinX,C=m.rMinY,w=m.rMinZ,T=m.rMaxX,E=m.rMaxY,D=m.rMaxZ;return h===e||h===t?(d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d):(d.leftChild=this.buildNodeRecursiveToDepth(e,h,n-1,r-1,i,g,_,v,y,b,x),d.rightChild=this.buildNodeRecursiveToDepth(h,t,n-1,r-1,i,S,C,w,T,E,D),d)}buildNodeRecursive(e,t,n,r,i,a,o,s,c,l){let u=new M;this.totalNodes++;let d=t-e;if(i===void 0?this.updateNodeBounds(u,e,t):(u.minX=i,u.minY=a,u.minZ=o,u.maxX=s,u.maxY=c,u.maxZ=l),d<=this.maxLeafSize||n<=0)return u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;let f=this.findBestSplitPositionSAH(e,t,u);if(!f.success)return this.splitStats.failedSplits++,u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;f.method===`SAH`?this.splitStats.sahSplits++:f.method===`object_median`?this.splitStats.objectMedianSplits++:f.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,f.axis,f.pos);let p=this._partResult,m=p.mid,h=p.lMinX,g=p.lMinY,_=p.lMinZ,v=p.lMaxX,y=p.lMaxY,b=p.lMaxZ,x=p.rMinX,S=p.rMinY,C=p.rMinZ,w=p.rMaxX,T=p.rMaxY,E=p.rMaxZ;return m===e||m===t?(u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u):(u.leftChild=this.buildNodeRecursive(e,m,n-1,r,h,g,_,v,y,b),u.rightChild=this.buildNodeRecursive(m,t,n-1,r,x,S,C,w,T,E),u)}partitionWithBounds(e,t,n,r){let i=this.indices,a=this.centroids,o=this.bMin,s=this.bMax,c=e,l=t-1,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(;c<=l;){let e=i[c],t=e*3;a[t+n]<=r?(o[t]<u&&(u=o[t]),o[t+1]<d&&(d=o[t+1]),o[t+2]<f&&(f=o[t+2]),s[t]>p&&(p=s[t]),s[t+1]>m&&(m=s[t+1]),s[t+2]>h&&(h=s[t+2]),c++):(o[t]<g&&(g=o[t]),o[t+1]<_&&(_=o[t+1]),o[t+2]<v&&(v=o[t+2]),s[t]>y&&(y=s[t]),s[t+1]>b&&(b=s[t+1]),s[t+2]>x&&(x=s[t+2]),i[c]=i[l],i[l]=e,l--)}let S=this._partResult;return S.mid=c,S.lMinX=u,S.lMinY=d,S.lMinZ=f,S.lMaxX=p,S.lMaxY=m,S.lMaxZ=h,S.rMinX=g,S.rMinY=_,S.rMinZ=v,S.rMaxX=y,S.rMaxY=b,S.rMaxZ=x,S}updateNodeBounds(e,t,n){let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0,l=this.indices,u=this.bMin,d=this.bMax;for(let e=t;e<n;e++){let t=l[e]*3;u[t]<r&&(r=u[t]),u[t+1]<i&&(i=u[t+1]),u[t+2]<a&&(a=u[t+2]),d[t]>o&&(o=d[t]),d[t+1]>s&&(s=d[t+1]),d[t+2]>c&&(c=d[t+2])}e.minX=r,e.minY=i,e.minZ=a,e.maxX=o,e.maxY=s,e.maxZ=c}findBestSplitPositionSAH(e,t,n){let r=1/0,i=-1,a=0,o=this.computeSurfaceAreaFlat(n.minX,n.minY,n.minZ,n.maxX,n.maxY,n.maxZ),s=t-e,c=this.intersectionCost*s,l=this.getOptimalBinCount(s);this.splitStats.totalSplitAttempts++,this.splitStats.avgBinsUsed=(this.splitStats.avgBinsUsed*(this.splitStats.totalSplitAttempts-1)+l)/this.splitStats.totalSplitAttempts;let u=this.indices,d=this.centroids,f=this.bMin,p=this.bMax,m=this.binBoundsMin,h=this.binBoundsMax,g=this.binCounts,_=this.leftPrefixMin,v=this.leftPrefixMax,y=this.leftPrefixCount,b=this.rightPrefixMin,x=this.rightPrefixMax,S=this.rightPrefixCount,C=1/0,w=-1/0,T=1/0,E=-1/0,D=1/0,O=-1/0;for(let n=e;n<t;n++){let e=u[n]*3,t=d[e],r=d[e+1],i=d[e+2];t<C&&(C=t),t>w&&(w=t),r<T&&(T=r),r>E&&(E=r),i<D&&(D=i),i>O&&(O=i)}let k=[C,T,D],A=[w,E,O];for(let n=0;n<3;n++){let s=k[n],C=A[n];if(C-s<1e-6)continue;for(let e=0;e<l;e++){g[e]=0;let t=e*3;m[t]=1/0,m[t+1]=1/0,m[t+2]=1/0,h[t]=-1/0,h[t+1]=-1/0,h[t+2]=-1/0}let w=l/(C-s);for(let r=e;r<t;r++){let e=u[r],t=d[e*3+n],i=Math.floor((t-s)*w);i>=l&&(i=l-1),g[i]++;let a=i*3,o=e*3;f[o]<m[a]&&(m[a]=f[o]),f[o+1]<m[a+1]&&(m[a+1]=f[o+1]),f[o+2]<m[a+2]&&(m[a+2]=f[o+2]),p[o]>h[a]&&(h[a]=p[o]),p[o+1]>h[a+1]&&(h[a+1]=p[o+1]),p[o+2]>h[a+2]&&(h[a+2]=p[o+2])}y[0]=g[0],_[0]=m[0],_[1]=m[1],_[2]=m[2],v[0]=h[0],v[1]=h[1],v[2]=h[2];for(let e=1;e<l;e++){let t=e*3,n=(e-1)*3;y[e]=y[e-1]+g[e];let r=_[n],i=m[t],a=_[n+1],o=m[t+1],s=_[n+2],c=m[t+2];_[t]=r<i?r:i,_[t+1]=a<o?a:o,_[t+2]=s<c?s:c;let l=v[n],u=h[t],d=v[n+1],f=h[t+1],p=v[n+2],b=h[t+2];v[t]=l>u?l:u,v[t+1]=d>f?d:f,v[t+2]=p>b?p:b}let T=l-1,E=T*3;S[T]=g[T],b[E]=m[E],b[E+1]=m[E+1],b[E+2]=m[E+2],x[E]=h[E],x[E+1]=h[E+1],x[E+2]=h[E+2];for(let e=T-1;e>=0;e--){let t=e*3,n=(e+1)*3;S[e]=S[e+1]+g[e];let r=b[n],i=m[t],a=b[n+1],o=m[t+1],s=b[n+2],c=m[t+2];b[t]=r<i?r:i,b[t+1]=a<o?a:o,b[t+2]=s<c?s:c;let l=x[n],u=h[t],d=x[n+1],f=h[t+1],p=x[n+2],_=h[t+2];x[t]=l>u?l:u,x[t+1]=d>f?d:f,x[t+2]=p>_?p:_}for(let e=1;e<l;e++){let t=(e-1)*3,u=e*3,d=y[e-1],f=S[e];if(d===0||f===0)continue;let p=v[t]-_[t],m=v[t+1]-_[t+1],h=v[t+2]-_[t+2],g=2*(p*m+m*h+h*p),w=x[u]-b[u],T=x[u+1]-b[u+1],E=x[u+2]-b[u+2],D=2*(w*T+T*E+E*w),O=this.traversalCost+g/o*d*this.intersectionCost+D/o*f*this.intersectionCost;O<r&&O<c&&(r=O,i=n,a=s+(C-s)*e/l)}}return i===-1?this.enableObjectMedianFallback?this.findObjectMedianSplit(e,t):this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`fallbacks_disabled`}:{success:!0,axis:i,pos:a,method:`SAH`,binsUsed:l}}findObjectMedianSplit(e,t){let n=this.indices,r=this.centroids,i=-1,a=-1;for(let o=0;o<3;o++){let s=1/0,c=-1/0;for(let i=e;i<t;i++){let e=r[n[i]*3+o];e<s&&(s=e),e>c&&(c=e)}let l=c-s;l>a&&(a=l,i=o)}if(i===-1||a<1e-10)return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_failed`};let o=t-e,s=e+Math.floor(o/2);this.quickselect(e,t,s,i);let c=r[n[s]*3+i],l=!0;for(let e=s+1;e<t;e++)if(r[n[e]*3+i]>c){l=!1;break}if(l){let a=-1/0;for(let t=e;t<s;t++){let e=r[n[t]*3+i];e>a&&(a=e)}if(a<c)c=(a+c)*.5;else return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_degenerate`}}return{success:!0,axis:i,pos:c,method:`object_median`}}findSpatialMedianSplit(e,t){let n=this.indices,r=this.centroids,i=this.bMin,a=this.bMax,o=-1,s=-1,c=0,l=0;for(let r=0;r<3;r++){let u=1/0,d=-1/0;for(let o=e;o<t;o++){let e=n[o]*3+r;i[e]<u&&(u=i[e]),a[e]>d&&(d=a[e])}let f=d-u;f>s&&(s=f,o=r,c=u,l=d)}if(o===-1||s<1e-12)return{success:!1,method:`spatial_median_failed`};let u=(c+l)*.5,d=t-e,f=0;for(let i=e;i<t;i++)r[n[i]*3+o]<=u&&f++;if(f===0||f===d){let i=e+Math.floor(d/2);this.quickselect(e,t,i,o);let a=r[n[i]*3+o],s=!0;for(let i=e;i<t;i++)if(r[n[i]*3+o]!==a){s=!1;break}if(s)return{success:!1,method:`spatial_median_degenerate`};let c=-1/0;for(let t=e;t<i;t++){let e=r[n[t]*3+o];e>c&&(c=e)}if(c<a)u=(c+a)*.5;else{let e=1/0;for(let a=i+1;a<t;a++){let t=r[n[a]*3+o];t<e&&(e=t)}u=(a+e)*.5}}return{success:!0,axis:o,pos:u,method:`spatial_median`}}quickselect(e,t,n,r){let i=this.indices,a=this.centroids,o=e,s=t-1;for(;o<s;){let e=o+s>>>1,t=a[i[o]*3+r],c=a[i[e]*3+r],l=a[i[s]*3+r];if(t>c){let t=i[o];i[o]=i[e],i[e]=t}if(t>l){let e=i[o];i[o]=i[s],i[s]=e}if(c>l){let t=i[e];i[e]=i[s],i[s]=t}let u=a[i[e]*3+r],d=o,f=s;for(;d<=f;){for(;a[i[d]*3+r]<u;)d++;for(;a[i[f]*3+r]>u;)f--;if(d<=f){let e=i[d];i[d]=i[f],i[f]=e,d++,f--}}f<n&&(o=d),d>n&&(s=f)}}applySAOrdering(e){if(!e||!e.leftChild)return;let t=[e],n=[];for(;t.length>0;){let e=t.pop();!e.leftChild||!e.rightChild||(n.push(e),t.push(e.leftChild),t.push(e.rightChild))}for(let e=n.length-1;e>=0;e--){let t=n[e],r=t.leftChild,i=t.rightChild,a=r.maxX-r.minX,o=r.maxY-r.minY,s=r.maxZ-r.minZ,c=i.maxX-i.minX,l=i.maxY-i.minY,u=i.maxZ-i.minZ;c*l+l*u+u*c>a*o+o*s+s*a&&(t.leftChild=i,t.rightChild=r)}}flattenBVH(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}S(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=x(r);for(let e=0;e<t.length;e++){let n=t[e],a=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[a]=e.minX,r[a+1]=e.minY,r[a+2]=e.minZ,i[a+3]=e._flatIndex,r[a+4]=e.maxX,r[a+5]=e.maxY,r[a+6]=e.maxZ,i[a+7]=t._flatIndex,r[a+8]=t.minX,r[a+9]=t.minY,r[a+10]=t.minZ,r[a+12]=t.maxX,r[a+13]=t.maxY,r[a+14]=t.maxZ}else i[a]=n.triangleOffset,i[a+1]=n.triangleCount,i[a+3]=O}return r}flattenBVHWithFrontier(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}S(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=[],a=x(r);for(let e=0;e<t.length;e++){let n=t[e],o=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[o]=e.minX,r[o+1]=e.minY,r[o+2]=e.minZ,a[o+3]=e._flatIndex,r[o+4]=e.maxX,r[o+5]=e.maxY,r[o+6]=e.maxZ,a[o+7]=t._flatIndex,r[o+8]=t.minX,r[o+9]=t.minY,r[o+10]=t.minZ,r[o+12]=t.maxX,r[o+13]=t.maxY,r[o+14]=t.maxZ}else if(n.isFrontier){let t=n.frontierTaskId;a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+2]=t,a[o+3]=k,i.push({taskId:t,flatIndex:e})}else a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+3]=O}return{flatData:r,frontierMap:i,nodeCount:t.length}}assembleParallelBVH(e,t,n,r){let i=[...r].sort((e,t)=>e.taskId-t.taskId),a=t;for(let e=0;e<i.length;e++)a+=i[e].nodeCount;S(a,`assembled BLAS node count`);let o=new Float32Array(a*16),s=x(o);o.set(e);let c=new Map;for(let e of n)c.set(e.taskId,e.flatIndex);let l=t;for(let e=0;e<i.length;e++){let t=i[e],n=t.flatData,r=t.nodeCount,a=l*16;o.set(n,a);for(let e=0;e<r;e++){let t=a+e*16;s[t+3]<O&&(s[t+3]+=l,s[t+7]+=l)}let u=c.get(t.taskId);if(u!==void 0){let e=u*16,t=a;for(let n=0;n<16;n++)o[e+n]=o[t+n]}l+=r}return o}computeSurfaceAreaFlat(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 P=_(`bvh`);self.onmessage=function(e){let t=e.data,n=t.type;v(t.logLevel),n===`buildPhase1`?F(t):n===`assemble`?I(t):L(t)};function F(e){let{sharedTriangleData:t,sharedCentroids:n,sharedBMin:r,sharedBMax:i,sharedIndices:a,sharedMortonCodes:o,triangleCount:s,depth:c,parallelDepth:l,reportProgress:u}=e;try{let e=new N,d=u?e=>{self.postMessage({type:`progress`,progress:e})}:null;e.triangles=new Uint32Array(t),e.centroids=new Float32Array(n),e.bMin=new Float32Array(r),e.bMax=new Float32Array(i),e.indices=new Uint32Array(a),e.mortonCodes=new Uint32Array(o),e.totalTriangles=s,e.totalNodes=0,e.processedTriangles=0,e.lastProgressUpdate=performance.now(),e.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let f=performance.now(),p=performance.now();e.initializeTriangleArrays(),e.splitStats.initTime=performance.now()-p,e.sortTrianglesByMortonCode(),e.frontierTasks=[];let m=performance.now(),g=e.buildNodeRecursiveToDepth(0,s,c,l,d);e.splitStats.sahBuildTime=performance.now()-m,e.applySAOrdering(g);let _=performance.now(),{flatData:v,frontierMap:y,nodeCount:b}=e.flattenBVHWithFrontier(g),x=performance.now()-_,S=performance.now()-f;P.debug(`phase 1 ${h.ms(S)} (init ${h.ms(e.splitStats.initTime)} · morton ${h.ms(e.splitStats.mortonSortTime)} · SAH ${h.ms(e.splitStats.sahBuildTime)} · flatten ${h.ms(x)}) · ${e.frontierTasks.length} frontier tasks`),self.postMessage({type:`phase1Result`,topFlatData:v,topNodeCount:b,frontierTasks:e.frontierTasks,frontierMap:y,splitStats:e.splitStats},[v.buffer])}catch(e){P.error(`phase 1 failed:`,e),self.postMessage({type:`error`,error:e.message})}}function I(e){let{topFlatData:t,topNodeCount:n,frontierMap:r,subtreeResults:i,sharedTriangleData:a,sharedIndices:o,sharedReorderBuffer:s,triangleCount:c,foldLeaves:l}=e;try{let e=performance.now(),u=new N().assembleParallelBVH(t,n,r,i),d=l?T(u):u,f=new Uint32Array(o);if(s){let e=new Uint32Array(a),t=new Uint32Array(s);for(let n=0;n<c;n++){let r=f[n]*20,i=n*20;t.set(e.subarray(r,r+20),i)}}let p=new Uint32Array(c);for(let e=0;e<c;e++)p[f[e]]=e;let m=performance.now()-e;P.debug(`phase 3 assemble + reorder ${h.ms(m)} (${h.mb(d.byteLength)} BVH)`),self.postMessage({type:`assembleResult`,bvhData:d,originalToBvh:p,triangleCount:c},[d.buffer,p.buffer])}catch(e){P.error(`assembly failed:`,e),self.postMessage({type:`error`,error:e.message})}}function L(e){let{triangleData:t,triangleByteOffset:n,triangleByteLength:r,depth:i,reportProgress:a,reinsertionOptimization:o,sharedReorderBuffer:s,maxLeafSize:c,numBins:l,maxBins:u,minBins:d,foldLeaves:f}=e,p=new N;c!==void 0&&(p.maxLeafSize=c),l!==void 0&&(p.numBins=l),u!==void 0&&(p.maxBins=u),d!==void 0&&(p.minBins=d);try{o&&p.setReinsertionConfig(o);let e=a?e=>{self.postMessage({progress:e})}:null,c=n===void 0?new Uint32Array(t):new Uint32Array(t,n,r/4),l=s?new Uint32Array(s):null,u=p.buildSync(c,i,e,l),d=performance.now(),m=p.flattenBVH(u),g=f?T(m):m,_=performance.now()-d;P.debug(`flatten ${h.ms(_)} (${h.mb(g.byteLength)})`);let v=p.originalToBvhMap||null;if(s){let e=[g.buffer];v&&e.push(v.buffer),self.postMessage({bvhData:g,originalToBvh:v,triangleCount:c.length/20,splitStats:p.splitStats},e)}else{let e=p.reorderedTriangleData,t=e.byteLength/80,n=[g.buffer,e.buffer];v&&n.push(v.buffer),self.postMessage({bvhData:g,triangles:e,originalToBvh:v,triangleCount:t,splitStats:p.splitStats},n)}}catch(e){P.error(`build failed:`,e),self.postMessage({error:e.message})}}",Ji=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,qi],{type:`text/javascript;charset=utf-8`});function Yi(e){let t;try{if(t=Ji&&(self.URL||self.webkitURL).createObjectURL(Ji),!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(qi),{type:`module`,name:e?.name})}}var Xi="var e=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.batchSizeRatio=.02,this.maxIterations=2,this.timeBudgetMs=15e3,this.stats={reinsertionsApplied:0,iterations:0,timeMs:0}}setBatchSizeRatio(e){this.batchSizeRatio=Math.max(.005,Math.min(.1,e))}setMaxIterations(e){this.maxIterations=Math.max(1,Math.min(5,e))}getStatistics(){return{...this.stats}}surfaceArea(e){let t=e.maxX-e.minX,n=e.maxY-e.minY,r=e.maxZ-e.minZ;return t*n+n*r+r*t}buildParentMap(e){let t=new Map;t.set(e,{parent:null,isLeft:!1});let n=[e];for(;n.length>0;){let e=n.pop();e.triangleCount>0||(e.leftChild&&(t.set(e.leftChild,{parent:e,isLeft:!0}),n.push(e.leftChild)),e.rightChild&&(t.set(e.rightChild,{parent:e,isLeft:!1}),n.push(e.rightChild)))}return t}findCandidates(e,t,n){let r=[],i=[e];for(;i.length>0;){let a=i.pop();if(a!==e&&n.get(a).parent!==e){let e=this.surfaceArea(a);r.length<t?(r.push({node:a,cost:e}),r.length===t&&this._heapify(r)):e>r[0].cost&&(r[0]={node:a,cost:e},this._siftDown(r,0))}a.triangleCount===0&&(a.leftChild&&i.push(a.leftChild),a.rightChild&&i.push(a.rightChild))}return r}_heapify(e){for(let t=(e.length>>1)-1;t>=0;t--)this._siftDown(e,t)}_siftDown(e,t){let n=e.length;for(;;){let r=t,i=2*t+1,a=2*t+2;if(i<n&&e[i].cost<e[r].cost&&(r=i),a<n&&e[a].cost<e[r].cost&&(r=a),r===t)break;let o=e[t];e[t]=e[r],e[r]=o,t=r}}findReinsertion(e,t,n){let r=n.get(e),i=r.parent;if(!i)return null;let a=r.isLeft?i.rightChild:i.leftChild,o=this.surfaceArea(e),s=this.surfaceArea(i),c=null,l=0,u=s,d=a.minX,f=a.minY,p=a.minZ,m=a.maxX,h=a.maxY,g=a.maxZ,_=a,v=i,y=[];do{for(y.length=0,y.push(u,_);y.length>0;){let t=y.pop(),n=y.pop();if(n-o<=l)continue;let r=Math.min(t.minX,e.minX),i=Math.min(t.minY,e.minY),a=Math.min(t.minZ,e.minZ),s=Math.max(t.maxX,e.maxX),u=Math.max(t.maxY,e.maxY),d=Math.max(t.maxZ,e.maxZ),f=s-r,p=u-i,m=d-a,h=n-(f*p+p*m+m*f);if(h>l&&(c=t,l=h),t.triangleCount===0&&t.leftChild&&t.rightChild){let e=h+this.surfaceArea(t);y.push(e,t.leftChild),y.push(e,t.rightChild)}}let t=n.get(v);if(!t||t.parent===null)break;if(v!==i){d=Math.min(d,_.minX),f=Math.min(f,_.minY),p=Math.min(p,_.minZ),m=Math.max(m,_.maxX),h=Math.max(h,_.maxY),g=Math.max(g,_.maxZ);let e=m-d,t=h-f,n=g-p,r=e*t+t*n+n*e;u+=this.surfaceArea(v)-r}let r=t.parent;_=t.isLeft?r.rightChild:r.leftChild,v=r}while(n.get(v).parent!==null);return c===a||c===i?null:c?{from:e,to:c,areaDiff:l}:null}getConflicts(e,t,n){let r=n.get(e);return[t,e,r.isLeft?r.parent.rightChild:r.parent.leftChild,n.get(t).parent,r.parent]}reinsertNode(e,t,n){let r=n.get(e),i=r.parent,a=r.isLeft?i.rightChild:i.leftChild,o=n.get(i),s=o.parent,c=n.get(t),l=c.parent;o.isLeft?s.leftChild=a:s.rightChild=a,i.leftChild=e,i.rightChild=t,i.triangleOffset=0,i.triangleCount=0,i.minX=Math.min(e.minX,t.minX),i.minY=Math.min(e.minY,t.minY),i.minZ=Math.min(e.minZ,t.minZ),i.maxX=Math.max(e.maxX,t.maxX),i.maxY=Math.max(e.maxY,t.maxY),i.maxZ=Math.max(e.maxZ,t.maxZ),c.isLeft?l.leftChild=i:l.rightChild=i,n.set(a,{parent:s,isLeft:o.isLeft}),n.set(i,{parent:l,isLeft:c.isLeft}),n.set(e,{parent:i,isLeft:!0}),n.set(t,{parent:i,isLeft:!1}),this.refitFrom(s,n),this.refitFrom(l,n)}refitFrom(e,t){let n=e;for(;n;){if(n.triangleCount===0&&n.leftChild&&n.rightChild){let e=n.leftChild,t=n.rightChild;n.minX=Math.min(e.minX,t.minX),n.minY=Math.min(e.minY,t.minY),n.minZ=Math.min(e.minZ,t.minZ),n.maxX=Math.max(e.maxX,t.maxX),n.maxY=Math.max(e.maxY,t.maxY),n.maxZ=Math.max(e.maxZ,t.maxZ)}let e=t.get(n);n=e?e.parent:null}}optimizeBVH(e,t){let n=performance.now();this.stats={reinsertionsApplied:0,iterations:0,timeMs:0};for(let r=0;r<this.maxIterations&&!(performance.now()-n>this.timeBudgetMs);r++){let i=this.buildParentMap(e),a=i.size,o=Math.max(1,Math.floor(a*this.batchSizeRatio));t&&t(`Reinsertion iter ${r+1}/${this.maxIterations}: selecting ${o} candidates`);let s=this.findCandidates(e,o,i),c=[];for(let t=0;t<s.length&&!(performance.now()-n>this.timeBudgetMs);t++){let n=this.findReinsertion(s[t].node,e,i);n&&n.areaDiff>0&&c.push(n)}c.sort((e,t)=>t.areaDiff-e.areaDiff);let l=new Set,u=0;for(let e of c){let t=this.getConflicts(e.from,e.to,i);if(!t.some(e=>l.has(e))){for(let e of t)l.add(e);this.reinsertNode(e.from,e.to,i),u++}}if(this.stats.reinsertionsApplied+=u,this.stats.iterations=r+1,t&&t(`Reinsertion iter ${r+1}: applied ${u} reinsertions`),u===0)break}return this.stats.timeMs=performance.now()-n,this.stats}};const t={silent:0,error:1,warn:2,info:3,debug:4},n=`info`,r=`rayzeeLogLevel`,i=`rayzeeLogNamespaces`,a=`color:#7c8494`,o=`color:inherit`;let s=null,c=null;function l(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function u(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function d(){if(s!==null)return s;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in t?(s=t[e],s):(s=t[l(r)]??t[n],s)}function f(){if(c!==null)return c;let e=globalThis.__RAYZEE_LOG_NS__??l(i);return c=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],c}function p(e,n){if(n<t.debug)return!0;let r=f();return r.length===0||r.some(t=>e===t||e.startsWith(`${t}:`))}function m(e,n,r){if(e>d()||!p(n,e))return;let i=e===t.error?console.error:e===t.warn?console.warn:console.log,s=`[${n}]`;typeof r[0]==`string`?i(`%c${s}%c ${r[0]}`,a,o,...r.slice(1)):i(`%c${s}`,a,...r)}const h={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`)=>`${h.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},g={levels:t,setLevel(e){return e in t?(globalThis.__RAYZEE_LOG_LEVEL__=e,s=t[e],u(r,e===n?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(t).join(`, `)}`),this.getLevel())},getLevel(){let e=d();return Object.keys(t).find(n=>t[n]===e)},isEnabled(e){return(t[e]??t.debug)<=d()},only(...e){let t=e.flat().filter(Boolean);return c=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),u(i,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return s=null,c=null,this.getLevel()}};function _(e){return{namespace:e,error:(...n)=>m(t.error,e,n),warn:(...n)=>m(t.warn,e,n),info:(...n)=>m(t.info,e,n),debug:(...n)=>m(t.debug,e,n),isEnabled:e=>g.isEnabled(e),summary(n,r=[]){let i=r.filter(Boolean);if(i.length===0||!console.groupCollapsed){m(t.info,e,[n]),i.forEach(n=>m(t.debug,e,[n]));return}t.info>d()||((d()>=t.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${n}`,a,o),i.forEach(e=>console.log(e)),console.groupEnd())}}}const v={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},y={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826};function b(e){return new Uint32Array(e.buffer,e.byteOffset,e.length)}function x(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 S=y.TRIANGLE_LEAF,C=(e,t)=>~(e<<4|t)>>>0;function w(e){let t=new Uint32Array(e.buffer,e.byteOffset,e.length),n=e.length/16,r=e=>{let n=e*16;return t[n+3]===S&&t[n+1]>0&&t[n+1]<=15},i=new Uint32Array(n),a=new Uint32Array(n),o=0,s=[0];for(;s.length;){let e=s.pop();i[e]=o,a[o++]=e;let n=e*16;t[n+3]>=1073741824||(r(t[n+7])||s.push(t[n+7]),r(t[n+3])||s.push(t[n+3]))}let c=new Float32Array(o*16),l=new Uint32Array(c.buffer);for(let n=0;n<o;n++){let o=a[n]*16,s=n*16;c.set(e.subarray(o,o+16),s),!(t[o+3]>=1073741824)&&(l[s+3]=T(t,t[o+3],r,i),l[s+7]=T(t,t[o+7],r,i))}return c}function T(e,t,n,r){let i=t*16;return n(t)?C(e[i],e[i+1]):r[t]}const E=_(`bvh`),D=y.TRIANGLE_LEAF,O=y.FRONTIER,k=v.FLOATS_PER_TRIANGLE,A=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length);var j=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},M=class{constructor(){this.useWorker=!0,this.maxLeafSize=8,this.foldLeaves=!1,this.numBins=32,this.minBins=8,this.maxBins=64,this.totalNodes=0,this.processedTriangles=0,this.totalTriangles=0,this.lastProgressUpdate=0,this.progressUpdateInterval=100,this.traversalCost=1,this.intersectionCost=2.5,this.useMortonCodes=!0,this.mortonBits=10,this.mortonClusterThreshold=128,this.enableObjectMedianFallback=!0,this.enableSpatialMedianFallback=!0,this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0},this.enableReinsertionOptimization=!0,this.reinsertionBatchSizeRatio=.02,this.reinsertionMaxIterations=2,this.initializeBinArrays(),this._partResult={mid:0,lMinX:0,lMinY:0,lMinZ:0,lMaxX:0,lMaxY:0,lMaxZ:0,rMinX:0,rMinY:0,rMinZ:0,rMaxX:0,rMaxY:0,rMaxZ:0},this.centroids=null,this.bMin=null,this.bMax=null,this.indices=null,this.mortonCodes=null,this.triangles=null,this.reorderedTriangleData=null}initializeBinArrays(){let e=this.maxBins;this.binBoundsMin=new Float32Array(e*3),this.binBoundsMax=new Float32Array(e*3),this.binCounts=new Uint32Array(e),this.leftPrefixMin=new Float32Array(e*3),this.leftPrefixMax=new Float32Array(e*3),this.leftPrefixCount=new Uint32Array(e),this.rightPrefixMin=new Float32Array(e*3),this.rightPrefixMax=new Float32Array(e*3),this.rightPrefixCount=new Uint32Array(e)}getOptimalBinCount(e){return e<=16?this.minBins:e<=64?16:e<=256?32:e<=1024?48:this.maxBins}setAdaptiveBinConfig(e){e.minBins!==void 0&&(this.minBins=Math.max(4,e.minBins)),e.maxBins!==void 0&&(this.maxBins=Math.min(128,e.maxBins)),e.baseBins!==void 0&&(this.numBins=e.baseBins),e.maxBins!==void 0&&this.initializeBinArrays()}setMortonConfig(e){e.enabled!==void 0&&(this.useMortonCodes=e.enabled),e.bits!==void 0&&(this.mortonBits=Math.max(6,Math.min(10,e.bits))),e.threshold!==void 0&&(this.mortonClusterThreshold=Math.max(16,e.threshold))}setFallbackConfig(e){e.objectMedian!==void 0&&(this.enableObjectMedianFallback=e.objectMedian),e.spatialMedian!==void 0&&(this.enableSpatialMedianFallback=e.spatialMedian)}setReinsertionConfig(e){e.enabled!==void 0&&(this.enableReinsertionOptimization=e.enabled),e.batchSizeRatio!==void 0&&(this.reinsertionBatchSizeRatio=Math.max(.005,Math.min(.1,e.batchSizeRatio))),e.maxIterations!==void 0&&(this.reinsertionMaxIterations=Math.max(1,Math.min(5,e.maxIterations)))}initializeTriangleArrays(){let e=this.totalTriangles,t=A(this.triangles),n=v.POSITION_A_OFFSET,r=v.POSITION_B_OFFSET,i=v.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*k,o=t[e+n],s=t[e+n+1],c=t[e+n+2],l=t[e+r],u=t[e+r+1],d=t[e+r+2],f=t[e+i],p=t[e+i+1],m=t[e+i+2],h=a*3;this.centroids[h]=(o+l+f)/3,this.centroids[h+1]=(s+u+p)/3,this.centroids[h+2]=(c+d+m)/3,this.bMin[h]=o<l?o<f?o:f:l<f?l:f,this.bMin[h+1]=s<u?s<p?s:p:u<p?u:p,this.bMin[h+2]=c<d?c<m?c:m:d<m?d:m,this.bMax[h]=o>l?o>f?o:f:l>f?l:f,this.bMax[h+1]=s>u?s>p?s:p:u>p?u:p,this.bMax[h+2]=c>d?c>m?c:m:d>m?d:m,this.indices[a]=a}}expandBits(e){return e=e*65537&4278190335,e=e*257&251719695,e=e*17&3272356035,e=e*5&1227133513,e}morton3D(e,t,n){return(this.expandBits(n)<<2)+(this.expandBits(t)<<1)+this.expandBits(e)}computeMortonCodeForIndex(e,t,n,r,i,a,o){let s=this.centroids,c=e*3,l=(1<<this.mortonBits)-1,u=i>0?(s[c]-t)/i:0,d=a>0?(s[c+1]-n)/a:0,f=o>0?(s[c+2]-r)/o:0,p=Math.max(0,Math.min(l,Math.floor(u*l))),m=Math.max(0,Math.min(l,Math.floor(d*l))),h=Math.max(0,Math.min(l,Math.floor(f*l)));return this.morton3D(p,m,h)}sortTrianglesByMortonCode(){let e=this.totalTriangles;if(!this.useMortonCodes||e<this.mortonClusterThreshold)return;let t=performance.now(),n=this.centroids,r=this.indices,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let t=0;t<e;t++){let e=r[t]*3,u=n[e],d=n[e+1],f=n[e+2];u<i&&(i=u),d<a&&(a=d),f<o&&(o=f),u>s&&(s=u),d>c&&(c=d),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o,p=this.mortonCodes,m=(1<<this.mortonBits)-1,h=u>0?m/u:0,g=d>0?m/d:0,_=f>0?m/f:0;for(let t=0;t<e;t++){let e=r[t],s=e*3,c=(n[s]-i)*h,l=(n[s+1]-a)*g,u=(n[s+2]-o)*_;c=c<0?0:(c>m?m:c)|0,l=l<0?0:(l>m?m:l)|0,u=u<0?0:(u>m?m:u)|0,c=c*65537&4278190335,c=c*257&251719695,c=c*17&3272356035,c=c*5&1227133513,l=l*65537&4278190335,l=l*257&251719695,l=l*17&3272356035,l=l*5&1227133513,u=u*65537&4278190335,u=u*257&251719695,u=u*17&3272356035,u=u*5&1227133513,p[e]=(u<<2)+(l<<1)+c}let v=new Uint32Array(e),y=new Uint32Array(256);for(let t=0;t<32;t+=8){y.fill(0);for(let n=0;n<e;n++)y[p[r[n]]>>>t&255]++;let n=0;for(let e=0;e<256;e++){let t=y[e];y[e]=n,n+=t}for(let n=0;n<e;n++){let e=p[r[n]]>>>t&255;v[y[e]++]=r[n]}r.set(v)}this.splitStats.mortonSortTime+=performance.now()-t}build(e,t=30,n=null){if(this.totalTriangles=e.byteLength/(k*4),this.processedTriangles=0,this.lastProgressUpdate=performance.now(),!(this.useWorker&&null))return new Promise(r=>{r(this._buildSyncAndFlatten(e,t,n))})}_buildSyncAndFlatten(e,t,n){let r=this.buildSync(e,t,n),i=this.flattenBVH(r);return{bvhData:this.foldLeaves?w(i):i,bvhRoot:!0,reorderedTriangles:this.reorderedTriangleData||null,originalToBvh:this.originalToBvhMap||null}}buildSync(t,n=30,r=null,i=null){let a=performance.now();this.totalNodes=0,this.processedTriangles=0,this.triangles=t,this.totalTriangles=t.byteLength/(k*4),this.lastProgressUpdate=performance.now(),this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0,saOrderTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let o=this.totalTriangles,s=performance.now();this.centroids=new Float32Array(o*3),this.bMin=new Float32Array(o*3),this.bMax=new Float32Array(o*3),this.indices=new Uint32Array(o),this.mortonCodes=new Uint32Array(o),this.initializeTriangleArrays(),this.splitStats.initTime=performance.now()-s,this.sortTrianglesByMortonCode();let c=performance.now(),l=this.buildNodeRecursive(0,o,n,r);if(this.splitStats.sahBuildTime=performance.now()-c,this.enableReinsertionOptimization&&this.totalTriangles>1e3){let t=new e(this.traversalCost,this.intersectionCost);t.setBatchSizeRatio(this.reinsertionBatchSizeRatio),t.setMaxIterations(this.reinsertionMaxIterations);let n=r?e=>{r(e)}:null;try{t.optimizeBVH(l,n)}catch(e){E.error(`reinsertion optimizer failed:`,e)}let i=t.getStatistics();this.splitStats.reinsertionOptimizationTime=i.timeMs,this.splitStats.reinsertionsApplied=i.reinsertionsApplied,this.splitStats.reinsertionIterations=i.iterations}let u=performance.now();this.applySAOrdering(l),this.splitStats.saOrderTime=performance.now()-u;let d=performance.now(),f=this.triangles,p=i||new f.constructor(o*k);for(let e=0;e<o;e++){let t=this.indices[e]*k,n=e*k;p.set(f.subarray(t,t+k),n)}this.reorderedTriangleData=p;let m=new Uint32Array(o);for(let e=0;e<o;e++)m[this.indices[e]]=e;this.originalToBvhMap=m,this.splitStats.reorderTime=performance.now()-d,this.splitStats.totalBuildTime=performance.now()-a;let g=this.splitStats.totalBuildTime,_=this.splitStats;return E.debug(`${h.n(o)} tris → ${h.n(this.totalNodes)} nodes in ${h.ms(g)} | SAH ${_.sahSplits} objMed ${_.objectMedianSplits} spatMed ${_.spatialMedianSplits} failed ${_.failedSplits}`+(_.reinsertionsApplied?` | reinsertions ${_.reinsertionsApplied}`:``)),r&&r(100),this.centroids=null,this.bMin=null,this.bMax=null,this.mortonCodes=null,l}updateProgress(e,t){if(!t)return;this.processedTriangles+=e;let n=performance.now();n-this.lastProgressUpdate<this.progressUpdateInterval||(this.lastProgressUpdate=n,t(Math.min(Math.floor(this.processedTriangles/this.totalTriangles*100),99)))}buildNodeRecursiveToDepth(e,t,n,r,i,a,o,s,c,l,u){let d=new j;this.totalNodes++;let f=t-e;if(a===void 0?this.updateNodeBounds(d,e,t):(d.minX=a,d.minY=o,d.minZ=s,d.maxX=c,d.maxY=l,d.maxZ=u),f<=this.maxLeafSize||n<=0)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;if(r<=0&&f>this.maxLeafSize*16){let r=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=r,this.frontierTasks.push({taskId:r,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}let p=this.findBestSplitPositionSAH(e,t,d);if(!p.success){if(this.splitStats.failedSplits++,r>0||f<=this.maxLeafSize*16)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;let a=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=a,this.frontierTasks.push({taskId:a,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}p.method===`SAH`?this.splitStats.sahSplits++:p.method===`object_median`?this.splitStats.objectMedianSplits++:p.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,p.axis,p.pos);let m=this._partResult,h=m.mid,g=m.lMinX,_=m.lMinY,v=m.lMinZ,y=m.lMaxX,b=m.lMaxY,x=m.lMaxZ,S=m.rMinX,C=m.rMinY,w=m.rMinZ,T=m.rMaxX,E=m.rMaxY,D=m.rMaxZ;return h===e||h===t?(d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d):(d.leftChild=this.buildNodeRecursiveToDepth(e,h,n-1,r-1,i,g,_,v,y,b,x),d.rightChild=this.buildNodeRecursiveToDepth(h,t,n-1,r-1,i,S,C,w,T,E,D),d)}buildNodeRecursive(e,t,n,r,i,a,o,s,c,l){let u=new j;this.totalNodes++;let d=t-e;if(i===void 0?this.updateNodeBounds(u,e,t):(u.minX=i,u.minY=a,u.minZ=o,u.maxX=s,u.maxY=c,u.maxZ=l),d<=this.maxLeafSize||n<=0)return u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;let f=this.findBestSplitPositionSAH(e,t,u);if(!f.success)return this.splitStats.failedSplits++,u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;f.method===`SAH`?this.splitStats.sahSplits++:f.method===`object_median`?this.splitStats.objectMedianSplits++:f.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,f.axis,f.pos);let p=this._partResult,m=p.mid,h=p.lMinX,g=p.lMinY,_=p.lMinZ,v=p.lMaxX,y=p.lMaxY,b=p.lMaxZ,x=p.rMinX,S=p.rMinY,C=p.rMinZ,w=p.rMaxX,T=p.rMaxY,E=p.rMaxZ;return m===e||m===t?(u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u):(u.leftChild=this.buildNodeRecursive(e,m,n-1,r,h,g,_,v,y,b),u.rightChild=this.buildNodeRecursive(m,t,n-1,r,x,S,C,w,T,E),u)}partitionWithBounds(e,t,n,r){let i=this.indices,a=this.centroids,o=this.bMin,s=this.bMax,c=e,l=t-1,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(;c<=l;){let e=i[c],t=e*3;a[t+n]<=r?(o[t]<u&&(u=o[t]),o[t+1]<d&&(d=o[t+1]),o[t+2]<f&&(f=o[t+2]),s[t]>p&&(p=s[t]),s[t+1]>m&&(m=s[t+1]),s[t+2]>h&&(h=s[t+2]),c++):(o[t]<g&&(g=o[t]),o[t+1]<_&&(_=o[t+1]),o[t+2]<v&&(v=o[t+2]),s[t]>y&&(y=s[t]),s[t+1]>b&&(b=s[t+1]),s[t+2]>x&&(x=s[t+2]),i[c]=i[l],i[l]=e,l--)}let S=this._partResult;return S.mid=c,S.lMinX=u,S.lMinY=d,S.lMinZ=f,S.lMaxX=p,S.lMaxY=m,S.lMaxZ=h,S.rMinX=g,S.rMinY=_,S.rMinZ=v,S.rMaxX=y,S.rMaxY=b,S.rMaxZ=x,S}updateNodeBounds(e,t,n){let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0,l=this.indices,u=this.bMin,d=this.bMax;for(let e=t;e<n;e++){let t=l[e]*3;u[t]<r&&(r=u[t]),u[t+1]<i&&(i=u[t+1]),u[t+2]<a&&(a=u[t+2]),d[t]>o&&(o=d[t]),d[t+1]>s&&(s=d[t+1]),d[t+2]>c&&(c=d[t+2])}e.minX=r,e.minY=i,e.minZ=a,e.maxX=o,e.maxY=s,e.maxZ=c}findBestSplitPositionSAH(e,t,n){let r=1/0,i=-1,a=0,o=this.computeSurfaceAreaFlat(n.minX,n.minY,n.minZ,n.maxX,n.maxY,n.maxZ),s=t-e,c=this.intersectionCost*s,l=this.getOptimalBinCount(s);this.splitStats.totalSplitAttempts++,this.splitStats.avgBinsUsed=(this.splitStats.avgBinsUsed*(this.splitStats.totalSplitAttempts-1)+l)/this.splitStats.totalSplitAttempts;let u=this.indices,d=this.centroids,f=this.bMin,p=this.bMax,m=this.binBoundsMin,h=this.binBoundsMax,g=this.binCounts,_=this.leftPrefixMin,v=this.leftPrefixMax,y=this.leftPrefixCount,b=this.rightPrefixMin,x=this.rightPrefixMax,S=this.rightPrefixCount,C=1/0,w=-1/0,T=1/0,E=-1/0,D=1/0,O=-1/0;for(let n=e;n<t;n++){let e=u[n]*3,t=d[e],r=d[e+1],i=d[e+2];t<C&&(C=t),t>w&&(w=t),r<T&&(T=r),r>E&&(E=r),i<D&&(D=i),i>O&&(O=i)}let k=[C,T,D],A=[w,E,O];for(let n=0;n<3;n++){let s=k[n],C=A[n];if(C-s<1e-6)continue;for(let e=0;e<l;e++){g[e]=0;let t=e*3;m[t]=1/0,m[t+1]=1/0,m[t+2]=1/0,h[t]=-1/0,h[t+1]=-1/0,h[t+2]=-1/0}let w=l/(C-s);for(let r=e;r<t;r++){let e=u[r],t=d[e*3+n],i=Math.floor((t-s)*w);i>=l&&(i=l-1),g[i]++;let a=i*3,o=e*3;f[o]<m[a]&&(m[a]=f[o]),f[o+1]<m[a+1]&&(m[a+1]=f[o+1]),f[o+2]<m[a+2]&&(m[a+2]=f[o+2]),p[o]>h[a]&&(h[a]=p[o]),p[o+1]>h[a+1]&&(h[a+1]=p[o+1]),p[o+2]>h[a+2]&&(h[a+2]=p[o+2])}y[0]=g[0],_[0]=m[0],_[1]=m[1],_[2]=m[2],v[0]=h[0],v[1]=h[1],v[2]=h[2];for(let e=1;e<l;e++){let t=e*3,n=(e-1)*3;y[e]=y[e-1]+g[e];let r=_[n],i=m[t],a=_[n+1],o=m[t+1],s=_[n+2],c=m[t+2];_[t]=r<i?r:i,_[t+1]=a<o?a:o,_[t+2]=s<c?s:c;let l=v[n],u=h[t],d=v[n+1],f=h[t+1],p=v[n+2],b=h[t+2];v[t]=l>u?l:u,v[t+1]=d>f?d:f,v[t+2]=p>b?p:b}let T=l-1,E=T*3;S[T]=g[T],b[E]=m[E],b[E+1]=m[E+1],b[E+2]=m[E+2],x[E]=h[E],x[E+1]=h[E+1],x[E+2]=h[E+2];for(let e=T-1;e>=0;e--){let t=e*3,n=(e+1)*3;S[e]=S[e+1]+g[e];let r=b[n],i=m[t],a=b[n+1],o=m[t+1],s=b[n+2],c=m[t+2];b[t]=r<i?r:i,b[t+1]=a<o?a:o,b[t+2]=s<c?s:c;let l=x[n],u=h[t],d=x[n+1],f=h[t+1],p=x[n+2],_=h[t+2];x[t]=l>u?l:u,x[t+1]=d>f?d:f,x[t+2]=p>_?p:_}for(let e=1;e<l;e++){let t=(e-1)*3,u=e*3,d=y[e-1],f=S[e];if(d===0||f===0)continue;let p=v[t]-_[t],m=v[t+1]-_[t+1],h=v[t+2]-_[t+2],g=2*(p*m+m*h+h*p),w=x[u]-b[u],T=x[u+1]-b[u+1],E=x[u+2]-b[u+2],D=2*(w*T+T*E+E*w),O=this.traversalCost+g/o*d*this.intersectionCost+D/o*f*this.intersectionCost;O<r&&O<c&&(r=O,i=n,a=s+(C-s)*e/l)}}return i===-1?this.enableObjectMedianFallback?this.findObjectMedianSplit(e,t):this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`fallbacks_disabled`}:{success:!0,axis:i,pos:a,method:`SAH`,binsUsed:l}}findObjectMedianSplit(e,t){let n=this.indices,r=this.centroids,i=-1,a=-1;for(let o=0;o<3;o++){let s=1/0,c=-1/0;for(let i=e;i<t;i++){let e=r[n[i]*3+o];e<s&&(s=e),e>c&&(c=e)}let l=c-s;l>a&&(a=l,i=o)}if(i===-1||a<1e-10)return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_failed`};let o=t-e,s=e+Math.floor(o/2);this.quickselect(e,t,s,i);let c=r[n[s]*3+i],l=!0;for(let e=s+1;e<t;e++)if(r[n[e]*3+i]>c){l=!1;break}if(l){let a=-1/0;for(let t=e;t<s;t++){let e=r[n[t]*3+i];e>a&&(a=e)}if(a<c)c=(a+c)*.5;else return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_degenerate`}}return{success:!0,axis:i,pos:c,method:`object_median`}}findSpatialMedianSplit(e,t){let n=this.indices,r=this.centroids,i=this.bMin,a=this.bMax,o=-1,s=-1,c=0,l=0;for(let r=0;r<3;r++){let u=1/0,d=-1/0;for(let o=e;o<t;o++){let e=n[o]*3+r;i[e]<u&&(u=i[e]),a[e]>d&&(d=a[e])}let f=d-u;f>s&&(s=f,o=r,c=u,l=d)}if(o===-1||s<1e-12)return{success:!1,method:`spatial_median_failed`};let u=(c+l)*.5,d=t-e,f=0;for(let i=e;i<t;i++)r[n[i]*3+o]<=u&&f++;if(f===0||f===d){let i=e+Math.floor(d/2);this.quickselect(e,t,i,o);let a=r[n[i]*3+o],s=!0;for(let i=e;i<t;i++)if(r[n[i]*3+o]!==a){s=!1;break}if(s)return{success:!1,method:`spatial_median_degenerate`};let c=-1/0;for(let t=e;t<i;t++){let e=r[n[t]*3+o];e>c&&(c=e)}if(c<a)u=(c+a)*.5;else{let e=1/0;for(let a=i+1;a<t;a++){let t=r[n[a]*3+o];t<e&&(e=t)}u=(a+e)*.5}}return{success:!0,axis:o,pos:u,method:`spatial_median`}}quickselect(e,t,n,r){let i=this.indices,a=this.centroids,o=e,s=t-1;for(;o<s;){let e=o+s>>>1,t=a[i[o]*3+r],c=a[i[e]*3+r],l=a[i[s]*3+r];if(t>c){let t=i[o];i[o]=i[e],i[e]=t}if(t>l){let e=i[o];i[o]=i[s],i[s]=e}if(c>l){let t=i[e];i[e]=i[s],i[s]=t}let u=a[i[e]*3+r],d=o,f=s;for(;d<=f;){for(;a[i[d]*3+r]<u;)d++;for(;a[i[f]*3+r]>u;)f--;if(d<=f){let e=i[d];i[d]=i[f],i[f]=e,d++,f--}}f<n&&(o=d),d>n&&(s=f)}}applySAOrdering(e){if(!e||!e.leftChild)return;let t=[e],n=[];for(;t.length>0;){let e=t.pop();!e.leftChild||!e.rightChild||(n.push(e),t.push(e.leftChild),t.push(e.rightChild))}for(let e=n.length-1;e>=0;e--){let t=n[e],r=t.leftChild,i=t.rightChild,a=r.maxX-r.minX,o=r.maxY-r.minY,s=r.maxZ-r.minZ,c=i.maxX-i.minX,l=i.maxY-i.minY,u=i.maxZ-i.minZ;c*l+l*u+u*c>a*o+o*s+s*a&&(t.leftChild=i,t.rightChild=r)}}flattenBVH(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}x(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=b(r);for(let e=0;e<t.length;e++){let n=t[e],a=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[a]=e.minX,r[a+1]=e.minY,r[a+2]=e.minZ,i[a+3]=e._flatIndex,r[a+4]=e.maxX,r[a+5]=e.maxY,r[a+6]=e.maxZ,i[a+7]=t._flatIndex,r[a+8]=t.minX,r[a+9]=t.minY,r[a+10]=t.minZ,r[a+12]=t.maxX,r[a+13]=t.maxY,r[a+14]=t.maxZ}else i[a]=n.triangleOffset,i[a+1]=n.triangleCount,i[a+3]=D}return r}flattenBVHWithFrontier(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}x(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=[],a=b(r);for(let e=0;e<t.length;e++){let n=t[e],o=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[o]=e.minX,r[o+1]=e.minY,r[o+2]=e.minZ,a[o+3]=e._flatIndex,r[o+4]=e.maxX,r[o+5]=e.maxY,r[o+6]=e.maxZ,a[o+7]=t._flatIndex,r[o+8]=t.minX,r[o+9]=t.minY,r[o+10]=t.minZ,r[o+12]=t.maxX,r[o+13]=t.maxY,r[o+14]=t.maxZ}else if(n.isFrontier){let t=n.frontierTaskId;a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+2]=t,a[o+3]=O,i.push({taskId:t,flatIndex:e})}else a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+3]=D}return{flatData:r,frontierMap:i,nodeCount:t.length}}assembleParallelBVH(e,t,n,r){let i=[...r].sort((e,t)=>e.taskId-t.taskId),a=t;for(let e=0;e<i.length;e++)a+=i[e].nodeCount;x(a,`assembled BLAS node count`);let o=new Float32Array(a*16),s=b(o);o.set(e);let c=new Map;for(let e of n)c.set(e.taskId,e.flatIndex);let l=t;for(let e=0;e<i.length;e++){let t=i[e],n=t.flatData,r=t.nodeCount,a=l*16;o.set(n,a);for(let e=0;e<r;e++){let t=a+e*16;s[t+3]<D&&(s[t+3]+=l,s[t+7]+=l)}let u=c.get(t.taskId);if(u!==void 0){let e=u*16,t=a;for(let n=0;n<16;n++)o[e+n]=o[t+n]}l+=r}return o}computeSurfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}};self.onmessage=function(t){let{tasks:n,sharedTriangleData:r,sharedCentroids:i,sharedBMin:a,sharedBMax:o,sharedIndices:s,triangleCount:c,maxLeafSize:l,numBins:u,maxBins:d,minBins:f,reinsertionConfig:p,reportProgress:m}=t.data;for(let t=0;t<n.length;t++){let h=n[t];try{let t=new M;t.maxLeafSize=l,t.numBins=u,t.maxBins=d,t.minBins=f,t.triangles=new Float32Array(r),t.centroids=new Float32Array(i),t.bMin=new Float32Array(a),t.bMax=new Float32Array(o),t.indices=new Uint32Array(s),t.totalTriangles=c,t.totalNodes=0,t.processedTriangles=0,t.lastProgressUpdate=performance.now(),t.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let n=m?e=>{self.postMessage({type:`progress`,taskId:h.taskId,progress:e})}:null,g=performance.now(),_=t.buildNodeRecursive(h.start,h.end,h.depth,n,h.preMinX,h.preMinY,h.preMinZ,h.preMaxX,h.preMaxY,h.preMaxZ);if(p&&p.enabled&&h.end-h.start>1e3){let n=new e(t.traversalCost,t.intersectionCost);p.batchSizeRatio&&n.setBatchSizeRatio(p.batchSizeRatio),p.maxIterations&&n.setMaxIterations(p.maxIterations);try{n.optimizeBVH(_,null)}catch(e){console.error(`[BVHSubtreeWorker] Reinsertion error:`,e)}}t.applySAOrdering(_);let v=t.flattenBVH(_),y=v.length/16,b=performance.now()-g;console.log(`[BVHSubtreeWorker] Task ${h.taskId}: ${(h.end-h.start).toLocaleString()} triangles, ${y} nodes, ${Math.round(b)}ms`),self.postMessage({type:`subtreeResult`,taskId:h.taskId,flatData:v,nodeCount:y},[v.buffer])}catch(e){console.error(`[BVHSubtreeWorker] Task ${h.taskId} error:`,e),self.postMessage({type:`error`,taskId:h.taskId,error:e.message})}}};",Zi=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Xi],{type:`text/javascript;charset=utf-8`});function Qi(e){let t;try{if(t=Zi&&(self.URL||self.webkitURL).createObjectURL(Zi),!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(Xi),{type:`module`,name:e?.name})}}Ae(),dr(),wi(()=>cr(Yi));var $i=ye(`bvh`),ea=20,ta=5e4,na=8;function ra(e,t,n,r){let i=e.byteLength/(ea*4),a=Math.min(ir(),na),o=Math.ceil(Math.log2(a*2.5+1));return $i.debug(`parallel build ${H.n(i)} triangles · ${a} workers · parallelDepth ${o}`),new Promise((s,c)=>{(async()=>{let l=e.buffer instanceof SharedArrayBuffer&&e.byteOffset===0&&e.byteLength===e.buffer.byteLength,u=l?e.buffer:new SharedArrayBuffer(e.byteLength);l||new Uint32Array(u).set(e),e=null;let d=new SharedArrayBuffer(i*3*4),f=new SharedArrayBuffer(i*3*4),p=new SharedArrayBuffer(i*3*4),m=new SharedArrayBuffer(i*4),h=new SharedArrayBuffer(i*4),g=cr(Yi),_=null,v=[g],y={id:null},b=!1,x=()=>{y.id&&=(clearTimeout(y.id),null);for(let e of v)try{e.terminate()}catch{}},S=e=>{if(!b){b=!0,$i.warn(`parallel build failed (${e}), falling back to single worker`),x();try{let e=new ArrayBuffer(u.byteLength);new Uint32Array(e).set(new Uint32Array(u)),s(aa(new Uint32Array(e),t,n,r))}catch(e){c(e)}}};g.onerror=e=>{S(`coordinator error: ${e.message}`)},g.onmessage=e=>{let t=e.data;if(t.error||t.type===`error`){S(t.error);return}if(t.type===`progress`&&n){n(Math.floor(t.progress*.3));return}if(t.type===`phase1Result`){_=t.splitStats,ia(t,a,u,d,f,p,m,null,i,n,g,v,x,S,s,y,r).catch(e=>S(e.message));return}if(t.type===`assembleResult`){b=!0,x(),s({bvhData:t.bvhData,bvhRoot:!0,order:new Uint32Array(m),triangles:new Uint32Array(u),originalToBvh:t.originalToBvh||null,splitStats:_||{}});return}},n&&n(0),g.postMessage({type:`buildPhase1`,sharedTriangleData:u,sharedCentroids:d,sharedBMin:f,sharedBMax:p,sharedIndices:m,sharedMortonCodes:h,triangleCount:i,depth:t,parallelDepth:o,reportProgress:!!n})})().catch(e=>{$i.warn(`parallel build setup failed:`,e),c(e)})})}async function ia(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g){let{topFlatData:_,topNodeCount:v,frontierTasks:y,frontierMap:b}=e;if(!y||y.length===0){$i.debug(`no frontier tasks, assembling with top-level tree only`),u.postMessage({type:`assemble`,topFlatData:_,topNodeCount:v,frontierMap:[],subtreeResults:[],sharedTriangleData:n,sharedIndices:o,sharedReorderBuffer:s,triangleCount:c,foldLeaves:g.foldLeaves},[_.buffer]);return}$i.debug(`phase 2 distributing ${y.length} tasks across ${t} workers`);let x=[...y].sort((e,t)=>t.end-t.start-(e.end-e.start)),S=Array.from({length:Math.min(t,x.length)},()=>[]),C=Array(S.length).fill(0);for(let e of x){let t=0;for(let e=1;e<C.length;e++)C[e]<C[t]&&(t=e);S[t].push(e),C[t]+=e.end-e.start}let w=[],T=0,E=y.length,D=y.reduce((e,t)=>e+(t.end-t.start),0),O=0;h.id=setTimeout(()=>{p(`Phase 2 timeout (30s)`)},3e4);let k=()=>{clearTimeout(h.id),h.id=null,l&&l(85);let t=[];e.topFlatData&&e.topFlatData.buffer&&t.push(e.topFlatData.buffer);for(let e of w)e.flatData&&e.flatData.buffer&&t.push(e.flatData.buffer);u.postMessage({type:`assemble`,topFlatData:e.topFlatData,topNodeCount:v,frontierMap:b,subtreeResults:w,sharedTriangleData:n,sharedIndices:o,sharedReorderBuffer:s,triangleCount:c,foldLeaves:g.foldLeaves},t)},A=S.length;for(let e=0;e<A;e++){let t=S[e];if(t.length===0)continue;let s=cr(Qi);d.push(s),s.onerror=e=>{p(`subtree worker error: ${e.message}`)},s.onmessage=e=>{let t=e.data;if(t.type===`error`){p(`subtree task ${t.taskId} error: ${t.error}`);return}if(t.type===`progress`&&l){let e=30+Math.floor(O/D*55);l(Math.min(e,85));return}if(t.type===`subtreeResult`){w.push({taskId:t.taskId,flatData:t.flatData,nodeCount:t.nodeCount});let e=y.find(e=>e.taskId===t.taskId);if(e&&(O+=e.end-e.start),T++,l){let e=30+Math.floor(O/D*55);l(Math.min(e,85))}if(T===E){for(let e of d)if(e!==u)try{e.terminate()}catch{}k()}}},s.postMessage({tasks:t,sharedTriangleData:n,sharedCentroids:r,sharedBMin:i,sharedBMax:a,sharedIndices:o,triangleCount:c,maxLeafSize:g.maxLeafSize,numBins:g.numBins,maxBins:g.maxBins,minBins:g.minBins,reinsertionConfig:g.reinsertionOptimization,reportProgress:!!l})}}function aa(e,t,n,r){return new Promise((i,a)=>{(async()=>{let o=cr(Yi),s=e.byteLength/(ea*4),c=typeof SharedArrayBuffer<`u`?new SharedArrayBuffer(s*ea*4):null;o.onmessage=e=>{let{bvhData:t,triangles:r,originalToBvh:s,error:l,progress:u,splitStats:d}=e.data;if(l){o.terminate(),a(Error(l));return}if(u!==void 0&&n){n(u);return}o.terminate(),i({bvhData:t,bvhRoot:!0,reorderedTriangles:c?new Uint32Array(c):r,originalToBvh:s||null,splitStats:d||{}})},o.onerror=e=>{o.terminate(),a(e)};let l=e.buffer;o.postMessage({triangleData:l,triangleByteOffset:e.byteOffset,triangleByteLength:e.byteLength,triangleCount:s,depth:t,reportProgress:!!n,sharedReorderBuffer:c,reinsertionOptimization:r.reinsertionOptimization,foldLeaves:r.foldLeaves},[l])})().catch(e=>{$i.warn(`single worker fallback failed:`,e),a(e)})})}function oa(e){return or()&&typeof SharedArrayBuffer<`u`&&e>=ta}wt();var sa=Float64Array.from([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ca(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 la(e,t,n){let r=ca(e,t);if(!Number.isFinite(r)||Math.abs(r)<1e-20)return n.set(sa),n;let i=1/r;return n[0]=(e[t+5]*e[t+10]-e[t+6]*e[t+9])*i,n[1]=(e[t+2]*e[t+9]-e[t+1]*e[t+10])*i,n[2]=(e[t+1]*e[t+6]-e[t+2]*e[t+5])*i,n[3]=0,n[4]=(e[t+6]*e[t+8]-e[t+4]*e[t+10])*i,n[5]=(e[t]*e[t+10]-e[t+2]*e[t+8])*i,n[6]=(e[t+2]*e[t+4]-e[t]*e[t+6])*i,n[7]=0,n[8]=(e[t+4]*e[t+9]-e[t+5]*e[t+8])*i,n[9]=(e[t+1]*e[t+8]-e[t]*e[t+9])*i,n[10]=(e[t]*e[t+5]-e[t+1]*e[t+4])*i,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 ua(e,t,n,r){for(let i=0;i<4;i++){let a=n+i*4,o=t[a],s=t[a+1],c=t[a+2],l=t[a+3];for(let t=0;t<4;t++)r[i*4+t]=e[t]*o+e[4+t]*s+e[8+t]*c+e[12+t]*l}return r}function da(e){for(let t=0;t<16;t++)if(e[t]!==sa[t])return!1;return!0}function fa(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=0;i<8;i++){let a=e[t+(i&1?3:0)],f=e[t+(i&2?4:1)],p=e[t+(i&4?5:2)],m=n[r]*a+n[r+4]*f+n[r+8]*p+n[r+12],h=n[r+1]*a+n[r+5]*f+n[r+9]*p+n[r+13],g=n[r+2]*a+n[r+6]*f+n[r+10]*p+n[r+14];m<o&&(o=m),m>l&&(l=m),h<s&&(s=h),h>u&&(u=h),g<c&&(c=g),g>d&&(d=g)}i[a]=o,i[a+1]=s,i[a+2]=c,i[a+3]=l,i[a+4]=u,i[a+5]=d}function pa(e,t){for(let n=0;n<16;n++)if(e[t+n]!==sa[n])return!1;return!0}var ma=class e{constructor(){this.count=0,this.templateCount=0,this.totalBLASNodes=0,this.tlasNodeCount=0,this.allocate(0)}allocate(e,t=e,n=null,r=null){this.count=e,this.templateCount=t,this.isSet=new Uint8Array(e),this.sourceMesh=r&&r.length>=e?r:new Int32Array(e),this.tlasLeafIndex=new Int32Array(e).fill(-1),this.visible=new Uint8Array(e).fill(1),this.flipWinding=new Uint8Array(e),this.tplBakeInverse=null,n&&n.length>=e*16?(this.world=n,this.worldPooled=!0):(this.world=new Float32Array(e*16),this.worldPooled=!1),this.tplTriOffset=new Int32Array(t),this.tplTriCount=new Int32Array(t),this.tplExpandedStart=new Int32Array(t),this.tplNodeCount=new Int32Array(t),this.tplBlasOffset=new Int32Array(t),this.tplOwner=new Int32Array(t).fill(-1),this.tplObjectAABB=new Float32Array(t*6),this._placementRuns=null,this.originalToBvhMap=new Map,this.bvhToOriginal=new Map,this.blasData=new Map}_place(e,t,n,r){this.isSet[e]=1,this.sourceMesh[e]=t;let i=e*16;if(!n){this.world.set(sa,i),this.flipWinding[e]=0;return}if(n!==this.world)for(let e=0;e<16;e++)this.world[i+e]=n[r+e];this.flipWinding[e]=+(ca(this.world,i)<0)}setEntry({meshIndex:e,blasNodeCount:t,triOffset:n,triCount:r,originalToBvhMap:i,bvhData:a,matrixWorld:o=null,matrixOffset:s=0,expandedStart:c=null,sourceMesh:l=null}){let u=l??e;this._place(e,u,o,s),this.tplTriOffset[u]=n,this.tplTriCount[u]=r,this.tplExpandedStart[u]=c??n,this.tplNodeCount[u]=t,this.tplOwner[u]=e,i&&this.originalToBvhMap.set(u,i),a&&this.blasData.set(u,a)}setAlias(e,t,n=null,r=null,i=null,a=0){if(!this.isSet[t])throw Error(`InstanceTable.setAlias: owner ${t} not built`);let o=i??e,s=this.sourceMesh[t];this._place(e,o,n,a),o!==s&&(this.tplTriOffset[o]=this.tplTriOffset[s],this.tplTriCount[o]=this.tplTriCount[s],this.tplNodeCount[o]=this.tplNodeCount[s],this.tplExpandedStart[o]=r??this.tplExpandedStart[s],this.tplOwner[o]=this.tplOwner[s])}get setCount(){let e=0;for(let t=0;t<this.count;t++)e+=this.isSet[t];return e}setPlacementMatrix(e,t,n=0){this._place(e,this.sourceMesh[e],t,n)}placementRunOf(e){if(!this._placementRuns){let e=this._placementRuns=new Map;for(let t=0;t<this.count;t++){let n=this.sourceMesh[t],r=e.get(n);r?r.count++:e.set(n,{start:t,count:1})}}return this._placementRuns.get(e)??null}isOwner(e){return this.tplOwner[this.sourceMesh[e]]===e}triOffsetOf(e){return this.tplTriOffset[this.sourceMesh[e]]}triCountOf(e){return this.tplTriCount[this.sourceMesh[e]]}expandedStartOf(e){return this.tplExpandedStart[this.sourceMesh[e]]}blasOffsetOf(e){return this.tplBlasOffset[this.sourceMesh[e]]}blasNodeCountOf(e){return this.tplNodeCount[this.sourceMesh[e]]}setBlasNodeCount(e,t){this.tplNodeCount[this.sourceMesh[e]]=t}setBvhToOriginal(e,t){this.bvhToOriginal.set(this.sourceMesh[e],t)}bvhToOriginalOf(e){let t=this.sourceMesh[e],n=this.bvhToOriginal.get(t);if(n)return n;let r=this.tplOwner[t];return(r>=0?this.bvhToOriginal.get(this.sourceMesh[r]):null)||null}matrixWorldOf(e){return this.world.subarray(e*16,e*16+16)}matrixInverseOf(e){return la(this.world,e*16,new Float64Array(16))}writeWorldAABB(e,t,n){if(!this.isSet[e]){for(let e=0;e<6;e++)t[n+e]=0;return}fa(this.tplObjectAABB,this.sourceMesh[e]*6,this.world,e*16,t,n)}writeWorldAABBs(e){let t=this.tplObjectAABB,n=this.world,r=this.sourceMesh,i=this.isSet;for(let a=0;a<this.count;a++){let o=a*6;if(!i[a]){e[o]=0,e[o+1]=0,e[o+2]=0,e[o+3]=0,e[o+4]=0,e[o+5]=0;continue}fa(t,r[a]*6,n,a*16,e,o)}}entryAt(e){if(!this.isSet[e])return null;let t=this.sourceMesh[e],n=this.tplOwner[t];return{meshIndex:e,blasOffset:this.tplBlasOffset[t],blasNodeCount:this.tplNodeCount[t],triOffset:this.tplTriOffset[t],triCount:this.tplTriCount[t],expandedStart:this.tplExpandedStart[t],sourceMesh:t,sharedFrom:n===e?null:n,matrixWorld:this.matrixWorldOf(e),matrixInverse:this.matrixInverseOf(e),flipWinding:!!this.flipWinding[e],bvhToOriginal:this.bvhToOriginal.get(t)||null,visible:!!this.visible[e],tlasLeafIndex:this.tlasLeafIndex[e]}}setVisibility(e,t){this.isSet[e]&&(this.visible[e]=+!!t)}computeAABBs(e,{owners:t=!0}={}){for(let n=0;t&&n<this.templateCount;n++){if(this.tplOwner[n]<0)continue;let t=this.blasData.get(n);t&&this._readRootAABB(Array.isArray(t)?t[0]:t,n,e,this.tplObjectAABB,n*6)}for(let e=0;e<this.templateCount;e++){let t=this.tplOwner[e];if(t<0||this.blasData.has(e))continue;let n=this.sourceMesh[t];n!==e&&this.tplObjectAABB.copyWithin(e*6,n*6,n*6+6)}}recomputeAABB(e,t,n){let r=this.sourceMesh[e],i=this.tplBlasOffset[r],a=t.chunks?t.chunkFor(i).subarray(t.baseOf(i),t.baseOf(i)+16):t.subarray(i*16,i*16+16);this._readRootAABB(a,r,n,this.tplObjectAABB,r*6)}_readRootAABB(t,n,r,i,a){e.rootAABB(t,r,this.tplTriOffset[n],this.tplTriCount[n],i,a)}static rootAABB(e,t,n,r,i,a){if(!e||ht(e)[3]===St.TRIANGLE_LEAF){ha(t,n,r,i,a);return}i[a]=Math.min(e[0],e[8]),i[a+1]=Math.min(e[1],e[9]),i[a+2]=Math.min(e[2],e[10]),i[a+3]=Math.max(e[4],e[12]),i[a+4]=Math.max(e[5],e[13]),i[a+5]=Math.max(e[6],e[14])}_computeAABBFromTriangles(e,t,n,r){ha(t,this.tplTriOffset[e],this.tplTriCount[e],n,r)}assignOffsets(e){this.tlasNodeCount=e;let t=e;for(let e=0;e<this.templateCount;e++){let n=this.tplOwner[e];n<0||this.sourceMesh[n]!==e||(this.tplBlasOffset[e]=t,t+=this.tplNodeCount[e])}for(let e=0;e<this.templateCount;e++){let t=this.tplOwner[e];if(t<0)continue;let n=this.sourceMesh[t];n!==e&&(this.tplBlasOffset[e]=this.tplBlasOffset[n])}this.totalBLASNodes=t-e,gt(t,`combined TLAS + BLAS node count`)}get totalNodeCount(){return this.tlasNodeCount+this.totalBLASNodes}clear(){this.allocate(0),this.totalBLASNodes=0,this.tlasNodeCount=0}};function ha(e,t,n,r,i){let a=K.FLOATS_PER_TRIANGLE,o=e&&e.chunks?e.viewAs(Float32Array):null,s=o?null:e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),c=1/0,l=1/0,u=1/0,d=-1/0,f=-1/0,p=-1/0;for(let e=0;e<n;e++){let n=t+e,r=o?o.chunkFor(n):s,i=o?o.baseOf(n):n*a;for(let e=0;e<=8;e+=4){let t=r[i+e],n=r[i+e+1],a=r[i+e+2];t<c&&(c=t),n<l&&(l=n),a<u&&(u=a),t>d&&(d=t),n>f&&(f=n),a>p&&(p=a)}}r[i]=c,r[i+1]=l,r[i+2]=u,r[i+3]=d,r[i+4]=f,r[i+5]=p}wt();var ga=16,_a=32,va=e=>e<_a?e:_a,ya=8,ba=64,xa=new Float64Array(16),Sa=class e{constructor(){this._flatBuffer=null,this._flatBufferCapacity=0,this._binCounts=new Int32Array(_a*3),this._binBounds=new Float64Array(_a*6*3),this._binSuffix=new Float64Array(_a),this._binSuffixCount=new Int32Array(_a),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(t){let n=new Float64Array(t.count*6);t.writeWorldAABBs(n);let r=this.buildStructure(n,t.count);return e.fillLeaves(r.data,r.nodeCount,t),r}buildStructure(t,n){let r=e.nodeCountFor(n);if(n===0)return{data:new Float32Array,nodeCount:0};gt(r,`TLAS node count`);let i=r*ga;i>this._flatBufferCapacity&&(this._flatBuffer=new Float32Array(i),this._flatBufferCapacity=i);let a=this._flatBuffer,o=ht(a);(!this._order||this._order.length<n)&&(this._order=new Int32Array(n));let s=this._order;for(let e=0;e<n;e++)s[e]=e;this._ensureStack(ba);let c=0,l=0,u=0,d=n,f=this._bounds;this._rangeBounds(t,s,u,d,f,0);let p=f[0],m=f[1],h=f[2],g=f[3],_=f[4],v=f[5];for(;;){if(d-u===1){let e=l*ga;o[e]=0,o[e+1]=s[u],a[e+2]=0,o[e+3]=St.BLAS_POINTER_LEAF}else{let e=this._partition(t,s,u,d,p,m,h,g,_,v),n=e-u,r=l+1,i=r+(n*2-1),y=l*ga;a[y]=f[0],a[y+1]=f[1],a[y+2]=f[2],o[y+3]=r,a[y+4]=f[3],a[y+5]=f[4],a[y+6]=f[5],o[y+7]=i,a[y+8]=f[6],a[y+9]=f[7],a[y+10]=f[8],a[y+11]=0,a[y+12]=f[9],a[y+13]=f[10],a[y+14]=f[11],a[y+15]=0;let b=n<=d-e,x=b?0:6,S=b?6:0;c=this._push(c,b?i:r,b?e:u,b?d:e,f,S),l=b?r:i,b?d=e:u=e,p=f[x],m=f[x+1],h=f[x+2],g=f[x+3],_=f[x+4],v=f[x+5];continue}if(c===0)break;c--;let e=c*3,n=c*6;l=this._stackI[e],u=this._stackI[e+1],d=this._stackI[e+2],p=this._stackB[n],m=this._stackB[n+1],h=this._stackB[n+2],g=this._stackB[n+3],_=this._stackB[n+4],v=this._stackB[n+5]}return{data:a.subarray(0,i),nodeCount:r}}_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(t,n,r){let i=r.world,a=r.sourceMesh,o=r.tplBlasOffset,s=r.visible,c=r.tlasLeafIndex,l=ht(t);for(let r=0;r<n;r++){let n=r*ga;if(l[n+3]!==St.BLAS_POINTER_LEAF)continue;let u=l[n+1]&xt;l[n]=o[a[u]],t[n+2]=+!!s[u],e.writeLeafMatrix(t,l,n,i,u),c[u]=r}}static writeLeafMatrix(e,t,n,r,i){let a=xa;la(r,i*16,a),e[n+4]=a[0],e[n+5]=a[4],e[n+6]=a[8],e[n+7]=a[12],e[n+8]=a[1],e[n+9]=a[5],e[n+10]=a[9],e[n+11]=a[13],e[n+12]=a[2],e[n+13]=a[6],e[n+14]=a[10],e[n+15]=a[14],t[n+1]=(i|(pa(r,i*16)?bt: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<=ya)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,s,c,l){let u=this._surfaceArea(i,a,o,s,c,l);if(!(u>0)||!isFinite(u))return n;let d=1/0,f=1/0,p=1/0,m=-1/0,h=-1/0,g=-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<d&&(d=r),r>m&&(m=r),a<f&&(f=a),a>h&&(h=a),o<p&&(p=o),o>g&&(g=o)}let _=this._extent,v=this._cMin;_[0]=m-d,_[1]=h-f,_[2]=g-p,v[0]=d,v[1]=f,v[2]=p;let y=1/0,b=-1,x=-1,S=this._binCounts,C=this._binBounds,w=_[0]>1e-12,T=_[1]>1e-12,E=_[2]>1e-12;if(!w&&!T&&!E)return n;let D=va(r-n),O=w?D/_[0]:0,k=T?D/_[1]:0,A=E?D/_[2]:0;S.fill(0,0,D*3);for(let e=0;e<D*3;e++){let t=e*6;C[t]=C[t+1]=C[t+2]=1/0,C[t+3]=C[t+4]=C[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?O:e===1?k:A;if(t===0)continue;let n=((e===0?(r+s)*.5:e===1?(a+c)*.5:(o+l)*.5)-v[e])*t|0;n<0?n=0:n>=D&&(n=D-1),n+=e*D,S[n]++;let i=n*6;r<C[i]&&(C[i]=r),a<C[i+1]&&(C[i+1]=a),o<C[i+2]&&(C[i+2]=o),s>C[i+3]&&(C[i+3]=s),c>C[i+4]&&(C[i+4]=c),l>C[i+5]&&(C[i+5]=l)}}for(let e=0;e<3;e++){if(!(_[e]>1e-12))continue;let t=e*D,n=this._binSuffix,r=this._binSuffixCount,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0,d=0;for(let e=D-1;e>=1;e--){let u=(t+e)*6;C[u]<i&&(i=C[u]),C[u+1]<a&&(a=C[u+1]),C[u+2]<o&&(o=C[u+2]),C[u+3]>s&&(s=C[u+3]),C[u+4]>c&&(c=C[u+4]),C[u+5]>l&&(l=C[u+5]),d+=S[t+e],n[e]=d?this._surfaceArea(i,a,o,s,c,l):0,r[e]=d}let f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,v=-1/0,w=0;for(let i=1;i<D;i++){let a=(t+i-1)*6;if(C[a]<f&&(f=C[a]),C[a+1]<p&&(p=C[a+1]),C[a+2]<m&&(m=C[a+2]),C[a+3]>h&&(h=C[a+3]),C[a+4]>g&&(g=C[a+4]),C[a+5]>v&&(v=C[a+5]),w+=S[t+i-1],w===0||r[i]===0)continue;let o=1+(this._surfaceArea(f,p,m,h,g,v)*w+n[i]*r[i])/u;o<y&&(y=o,b=e,x=i)}}if(b<0)return n;let j=D/_[b],M=v[b],N=this._bounds;N[0]=N[1]=N[2]=N[6]=N[7]=N[8]=1/0,N[3]=N[4]=N[5]=N[9]=N[10]=N[11]=-1/0;let P=n,F=r-1;for(;P<=F;){let n=t[P]*6,r=((e[n+b]+e[n+3+b])*.5-M)*j|0;r<0?r=0:r>=D&&(r=D-1);let i=r<x?0:6;if(e[n]<N[i]&&(N[i]=e[n]),e[n+1]<N[i+1]&&(N[i+1]=e[n+1]),e[n+2]<N[i+2]&&(N[i+2]=e[n+2]),e[n+3]>N[i+3]&&(N[i+3]=e[n+3]),e[n+4]>N[i+4]&&(N[i+4]=e[n+4]),e[n+5]>N[i+5]&&(N[i+5]=e[n+5]),i===0)P++;else{let e=t[P];t[P]=t[F],t[F]=e,F--}}return P}_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)}};function Ca(e){if(e>0)return{gb:e,assumed:!1};let t=typeof navigator<`u`?navigator.deviceMemory:void 0;return t>0?{gb:t,assumed:!1}:{gb:4,assumed:!0}}function wa({triangles:e,placements:t,geometryBytes:n=0}){let r={triangles:e*Ea,bvh:Math.ceil(e*Oa)*Da,geometry:n,placements:t*ka,orderMaps:e*Aa};return r.total=r.triangles+r.bvh+r.geometry+r.placements+r.orderMaps,r}function Ta(e,{chunkBytes:t=Yt,shared:n=!1,allocate:r=null}={}){let i=Math.min(e,Ia),a=r??(n?e=>new SharedArrayBuffer(e):e=>new ArrayBuffer(e)),o=[],s=0;try{for(;s<i;){let e=Math.min(t,i-s);o.push(a(e)),s+=e}}catch{}for(let e=o.length-1;e>=0;e--)o[e]=null;return o.length=0,{placed:s,want:i,exhausted:s<i,capped:e>i}}var Ea,Da,Oa,ka,Aa,ja,Ma,Na,Pa,Fa,Ia,La,Ra=g((()=>{wt(),$t(),Ea=K.FLOATS_PER_TRIANGLE*4,Da=64,Oa=.9,ka=64,Aa=4,ja=7040*1024*1024,Ma=9216*1024*1024,Na=6e7,Pa=8e6,Fa=1.15,Ia=12*1024*1024*1024,La=class{constructor(){this.reset()}reset(){this.phase=`idle`,this.events=[],this.samples=[],this.allocatedBytes=0,this.peakLiveBytes=0,this.byPhase=Object.create(null)}mark(e){return this.phase=e,this.byPhase[e]??={allocated:0,chunks:0},this}alloc(e,t=`chunk`){if(!(e>0))return;let n=this.byPhase[this.phase]??={allocated:0,chunks:0};n.allocated+=e,n.chunks++,this.allocatedBytes+=e,this.events.push({phase:this.phase,bytes:e,what:t,at:performance.now()})}sample(e,t){let n=0;for(let e in t)n+=t[e]||0;return n>this.peakLiveBytes&&(this.peakLiveBytes=n),this.samples.push({label:e,phase:this.phase,total:n,parts:t,at:performance.now()}),n}get report(){return{allocatedBytes:this.allocatedBytes,peakLiveBytes:this.peakLiveBytes,byPhase:{...this.byPhase},samples:this.samples.slice()}}}}));Ra();var za="const e={VEC4_PER_BVH_NODE:4,FLOATS_PER_VEC4:4,MIN_TEXTURE_WIDTH:4,MAX_CONCURRENT_WORKERS:Math.min(typeof navigator<`u`&&navigator.hardwareConcurrency||4,6),BUFFER_POOL_SIZE:20,CANVAS_POOL_SIZE:12,CACHE_SIZE_LIMIT:50,MAX_TEXTURE_SIZE:8192,DEFAULT_MAX_TEXTURE_SIZE:4096,MAX_TEXTURES_LIMIT:4*256,MATERIAL_BUCKET_COUNT:4,BUCKET_LAYER_STRIDE:256};function t(t,n){let r=Math.ceil(Math.max(1,t)/64)*64;return Math.min(n,Math.max(e.MIN_TEXTURE_WIDTH,r))}let n,r;const i={CHUNK_SIZE:8,ADAPTIVE_CHUNK_SIZE:!0,MEMORY_SAFETY_FACTOR:.8};let a=null;function o(e){if(e.stream===`begin`){let{width:t,height:n,depth:r}=e;a={width:t,height:n,depth:r,context:new OffscreenCanvas(t,n).getContext(`2d`,{willReadFrequently:!0,alpha:!0,desynchronized:!0}),data:new Uint8Array(t*n*r*4)};return}let{width:t,height:n,depth:r,context:i,data:o}=a;if(e.stream===`layer`){i.clearRect(0,0,t,n),i.drawImage(e.bitmap,0,0),e.bitmap.close(),o.set(i.getImageData(0,0,t,n).data,t*n*4*e.index),self.postMessage({stream:`ack`,index:e.index});return}a=null,self.postMessage({data:o.buffer,width:t,height:n,depth:r},[o.buffer])}async function s({shared:e,width:t,height:i,layers:a}){(n.width!==t||n.height!==i)&&(n.width=t,n.height=i),r.imageSmoothingEnabled=!0,r.imageSmoothingQuality=`high`;let o=new Uint8Array(e),s=t*i*4;for(let{index:e,texture:n}of a)try{await p(n,o,e*s,t,i)}catch(t){console.warn(`Failed to process texture ${e}:`,t),o.fill(0,e*s,(e+1)*s)}}self.onmessage=async function(e){if(e.data.shared){try{n||c(e.data.maxTextureSize),await s(e.data),self.postMessage({done:!0})}catch(e){self.postMessage({error:e.message})}return}if(e.data.stream){try{o(e.data)}catch(e){self.postMessage({error:e.message})}return}let{textures:t,maxTextureSize:r,method:i=`direct-transfer`}=e.data;try{n||c(r);let e=await l(t,r,i);self.postMessage(e,[e.data])}catch(e){console.error(`Worker processing failed:`,e),self.postMessage({error:e.message})}};function c(t){let i=Math.min(t,e.MAX_TEXTURE_SIZE);n=new OffscreenCanvas(i,i),r=n.getContext(`2d`,{willReadFrequently:!0,alpha:!0,desynchronized:!0})}async function l(e,t,n){switch(n){case`direct-transfer`:return await g(e,t);case`offscreen-optimized`:return await v(e,t);case`imageBitmap-batch`:return await y(e,t);default:return await g(e,t)}}async function u(e,t,n){let{maxWidth:r,maxHeight:i}=b(e,t),a=e.length,o=d(r,i,a),s=Math.ceil(a/o);console.log(`Processing ${a} textures in ${s} chunks of up to ${o} textures each`),console.log(`Texture dimensions: ${r}x${i}, Est. memory per chunk: ${(r*i*o*4/1024/1024).toFixed(2)}MB`);let c;try{c=new Uint8Array(r*i*a*4)}catch{return console.warn(`Failed to allocate full texture array, reducing dimensions`),await _(e,x(e,t),n)}let l=r*i*o*4,u;try{u=new Uint8Array(l)}catch{return console.warn(`Failed to allocate chunk buffer, reducing dimensions`),await _(e,x(e,t),n)}for(let t=0;t<s;t++){let n=t*o,s=Math.min(n+o,a),l=s-n,d=await f(e.slice(n,s),r,i,u.subarray(0,r*i*l*4)),p=n*r*i*4,m=l*r*i*4;c.set(new Uint8Array(d.data.slice(0,m)),p),t%2==1&&await new Promise(e=>setTimeout(e,0))}return{data:c.buffer,width:r,height:i,depth:a}}function d(e,t,n){if(!i.ADAPTIVE_CHUNK_SIZE)return Math.min(i.CHUNK_SIZE,n);let r=e*t*4/(1024*1024),a;return a=r<=1?16:r<=4?8:r<=16?4:2,Math.min(a,n,i.CHUNK_SIZE*2)}async function f(e,t,i,a){(n.width!==t||n.height!==i)&&(n.width=t,n.height=i);let o=t*i*4;r.imageSmoothingEnabled=!0,r.imageSmoothingQuality=`high`;for(let n=0;n<e.length;n++){let r=e[n];try{await p(r,a,n*o,t,i)}catch(e){console.warn(`Failed to process texture ${n}:`,e);let t=n*o;a.fill(0,t,t+o)}}return{data:a.buffer,width:t,height:i,depth:e.length}}async function p(e,t,n,i,a){let o;if(e.isDirect&&e.bitmap)o=e.bitmap;else if(e.isImageData&&e.data){let t=new ImageData(new Uint8ClampedArray(e.data),e.width,e.height);o=await createImageBitmap(t,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}else if(e.isBlob){let t=new Blob([e.data]);o=await createImageBitmap(t,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}else throw Error(`Unknown texture data format`);r.clearRect(0,0,i,a),r.drawImage(o,0,0,i,a);let s=r.getImageData(0,0,i,a);t.set(s.data,n),(e.isImageData||e.isBlob)&&o.close()}async function m(e,t,n){let r;try{r=new Uint8Array(t*n*e.length*4)}catch(r){console.warn(`Failed to allocate texture array in processTextureChunk, reducing dimensions`);let i=Math.max(1,Math.floor(t/2)),a=Math.max(1,Math.floor(n/2));if(i===t&&a===n)throw r;return await m(e,i,a)}return await f(e,t,n,r)}async function h(e,t,n,r,i){await p(e,n,r*i*4*t,r,i)}async function g(e,t){let{maxWidth:i,maxHeight:a}=b(e,t);(n.width!==i||n.height!==a)&&(n.width=i,n.height=a);let o=e.length,s;try{s=new Uint8Array(i*a*o*4)}catch(n){return console.error(`Failed to allocate texture array:`,n),await u(e,t,`direct-transfer`)}r.imageSmoothingEnabled=!0,r.imageSmoothingQuality=`high`;for(let t=0;t<e.length;t++){let n=e[t];try{await h(n,t,s,i,a)}catch(e){console.warn(`Failed to process texture ${t}:`,e);let n=i*a*4*t;s.fill(0,n,n+i*a*4)}}return{data:s.buffer,width:i,height:a,depth:o}}async function _(e,t,n){let{maxWidth:r,maxHeight:i}=t;return console.log(`Using reduced dimensions: ${r}x${i}`),await m(e,r,i,n)}async function v(e,t){let{maxWidth:i,maxHeight:a}=b(e,t);(n.width!==i||n.height!==a)&&(n.width=i,n.height=a);let o=e.length,s;try{s=new Uint8Array(i*a*o*4)}catch(n){return console.error(`Failed to allocate texture array:`,n),await u(e,t,`offscreen-optimized`)}r.imageSmoothingEnabled=!0,r.imageSmoothingQuality=`high`;for(let t=0;t<e.length;t++){let n=e[t];try{let e;if(n.isBlob){let t=new Blob([n.data]);e=await createImageBitmap(t,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}else{let t=new ImageData(new Uint8ClampedArray(n.data),n.width,n.height);e=await createImageBitmap(t,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}r.clearRect(0,0,i,a),r.drawImage(e,0,0);let o=r.getImageData(0,0,i,a),c=i*a*4*t;s.set(o.data,c),e.close()}catch(e){console.warn(`Failed to process texture ${t}:`,e);let n=i*a*4*t;s.fill(0,n,n+i*a*4)}}return{data:s.buffer,width:i,height:a,depth:o}}async function y(e,t){let{maxWidth:i,maxHeight:a}=b(e,t),o=e.length,s;try{s=new Uint8Array(i*a*o*4)}catch(n){return console.error(`Failed to allocate texture array:`,n),await u(e,t,`imageBitmap-batch`)}let c=Math.min(d(i,a,e.length),e.length);for(let t=0;t<e.length;t+=c){let o=Math.min(t+c,e.length),l=[];for(let n=t;n<o;n++){let t=e[n],r;if(t.isBlob){let e=new Blob([t.data]);r=createImageBitmap(e,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}else{let e=new ImageData(new Uint8ClampedArray(t.data),t.width,t.height);r=createImageBitmap(e,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}l.push(r.then(e=>({bitmap:e,index:n})))}let u=await Promise.all(l);n.width=i,n.height=a,r.imageSmoothingEnabled=!1;for(let{bitmap:e,index:t}of u){r.clearRect(0,0,i,a),r.drawImage(e,0,0);let n=r.getImageData(0,0,i,a),o=i*a*4*t;s.set(n.data,o),e.close()}}return{data:s.buffer,width:i,height:a,depth:o}}function b(n,r){let i=0,a=0;for(let e of n)i=Math.max(i,e.width||0),a=Math.max(a,e.height||0);let o=Math.min(r,e.MAX_TEXTURE_SIZE),s=Math.max(i,a);if(s>o){let e=o/s;i=Math.round(i*e),a=Math.round(a*e)}return i=t(i,o),{maxWidth:i,maxHeight:Math.max(1,a)}}function x(e,t){let n=b(e,t);return{maxWidth:Math.max(64,Math.ceil(n.maxWidth/128)*64),maxHeight:Math.max(1,Math.floor(n.maxHeight/2))}}",Ba=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,za],{type:`text/javascript;charset=utf-8`});function Va(e){let t;try{if(t=Ba&&(self.URL||self.webkitURL).createObjectURL(Ba),!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(za),{type:`module`,name:e?.name})}}var Ha=`function e({data:e,width:t,height:n,flipY:r},i,a,o,s){let c=o*4;if(t===o&&n===s){if(!r){i.set(e.subarray(0,s*c),a);return}for(let t=0;t<s;t++)i.set(e.subarray(t*c,(t+1)*c),a+(s-1-t)*c);return}let l=new Int32Array(o),u=new Int32Array(o),d=new Float64Array(o);for(let e=0;e<o;e++){let n=Math.min(Math.max((e+.5)*t/o-.5,0),t-1),r=Math.floor(n);l[e]=r*4,u[e]=Math.min(r+1,t-1)*4,d[e]=n-r}if(s<=n){for(let f=0;f<s;f++){let p=Math.min(Math.max((f+.5)*n/s-.5,0),n-1),m=Math.floor(p),h=Math.min(m+1,n-1),g=p-m,_=m*t*4,v=h*t*4,y=a+(r?s-1-f:f)*c;for(let t=0;t<o;t++,y+=4){let n=_+l[t],r=_+u[t],a=v+l[t],o=v+u[t],s=d[t];for(let t=0;t<4;t++){let c=e[n+t]+(e[r+t]-e[n+t])*s,l=e[a+t]+(e[o+t]-e[a+t])*s;i[y+t]=Math.round(c+(l-c)*g)}}}return}let f=[{row:-1,data:new Float64Array(c)},{row:-1,data:new Float64Array(c)}],p=(n,r)=>{for(let e of f)if(e.row===n)return e.data;let i=f[0].row===r?f[1]:f[0],a=n*t*4,s=i.data;for(let t=0,n=0;t<o;t++,n+=4){let r=a+l[t],i=a+u[t],o=d[t];s[n]=e[r]+(e[i]-e[r])*o,s[n+1]=e[r+1]+(e[i+1]-e[r+1])*o,s[n+2]=e[r+2]+(e[i+2]-e[r+2])*o,s[n+3]=e[r+3]+(e[i+3]-e[r+3])*o}return i.row=n,s};for(let e=0;e<s;e++){let t=Math.min(Math.max((e+.5)*n/s-.5,0),n-1),o=Math.floor(t),l=Math.min(o+1,n-1),u=t-o,d=p(o,l),f=l===o?d:p(l,o),m=a+(r?s-1-e:e)*c;for(let e=0;e<c;e++)i[m+e]=Math.round(d[e]+(f[e]-d[e])*u)}}self.onmessage=function(t){let{layers:n,width:r,height:i}=t.data;try{let t=r*i*4,a=new Uint8Array(t*n.length);n.forEach((n,o)=>e(n,a,o*t,r,i)),self.postMessage({data:a},[a.buffer])}catch(e){self.postMessage({error:e.message})}};`,Ua=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Ha],{type:`text/javascript;charset=utf-8`});function Wa(e){let t;try{if(t=Ua&&(self.URL||self.webkitURL).createObjectURL(Ua),!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(Ha),{type:`module`,name:e?.name})}}function Ga({data:e,width:t,height:n,flipY:r},i,a,o,s){let c=o*4;if(t===o&&n===s){if(!r){i.set(e.subarray(0,s*c),a);return}for(let t=0;t<s;t++)i.set(e.subarray(t*c,(t+1)*c),a+(s-1-t)*c);return}let l=new Int32Array(o),u=new Int32Array(o),d=new Float64Array(o);for(let e=0;e<o;e++){let n=Math.min(Math.max((e+.5)*t/o-.5,0),t-1),r=Math.floor(n);l[e]=r*4,u[e]=Math.min(r+1,t-1)*4,d[e]=n-r}if(s<=n){for(let f=0;f<s;f++){let p=Math.min(Math.max((f+.5)*n/s-.5,0),n-1),m=Math.floor(p),h=Math.min(m+1,n-1),g=p-m,_=m*t*4,v=h*t*4,y=a+(r?s-1-f:f)*c;for(let t=0;t<o;t++,y+=4){let n=_+l[t],r=_+u[t],a=v+l[t],o=v+u[t],s=d[t];for(let t=0;t<4;t++){let c=e[n+t]+(e[r+t]-e[n+t])*s,l=e[a+t]+(e[o+t]-e[a+t])*s;i[y+t]=Math.round(c+(l-c)*g)}}}return}let f=[{row:-1,data:new Float64Array(c)},{row:-1,data:new Float64Array(c)}],p=(n,r)=>{for(let e of f)if(e.row===n)return e.data;let i=f[0].row===r?f[1]:f[0],a=n*t*4,s=i.data;for(let t=0,n=0;t<o;t++,n+=4){let r=a+l[t],i=a+u[t],o=d[t];s[n]=e[r]+(e[i]-e[r])*o,s[n+1]=e[r+1]+(e[i+1]-e[r+1])*o,s[n+2]=e[r+2]+(e[i+2]-e[r+2])*o,s[n+3]=e[r+3]+(e[i+3]-e[r+3])*o}return i.row=n,s};for(let e=0;e<s;e++){let t=Math.min(Math.max((e+.5)*n/s-.5,0),n-1),o=Math.floor(t),l=Math.min(o+1,n-1),u=t-o,d=p(o,l),f=l===o?d:p(l,o),m=a+(r?s-1-e:e)*c;for(let e=0;e<c;e++)i[m+e]=Math.round(d[e]+(f[e]-d[e])*u)}}function Ka(e,t,n,r,i){i[0]=$a(e),i[1]=$a(t),i[2]=$a(n)}function qa(e,t,n,r,i){i[0]=$a(e*r),i[1]=$a(t*r),i[2]=$a(n*r)}function Ja(e,t,n,r,i){e*=r,t*=r,n*=r,i[0]=$a(e/(e+1)),i[1]=$a(t/(t+1)),i[2]=$a(n/(n+1))}function Ya(e,t,n,r,i){e=Math.max(e*r-.004,0),t=Math.max(t*r-.004,0),n=Math.max(n*r-.004,0);let a=e=>(e*(6.2*e+.5)/(e*(6.2*e+1.7)+.06))**2.2;i[0]=a(e),i[1]=a(t),i[2]=a(n)}function Xa(e,t,n,r,i){e=e*r/.6,t=t*r/.6,n=n*r/.6;let a=.59719*e+.35458*t+.04823*n,o=.076*e+.90834*t+.01566*n,s=.0284*e+.13383*t+.83777*n,c=e=>(e*(e+.0245786)-90537e-9)/(e*(.983729*e+.432951)+.238081);a=c(a),o=c(o),s=c(s),i[0]=$a(1.60475*a-.53108*o-.07367*s),i[1]=$a(-.10208*a+1.10813*o-.00605*s),i[2]=$a(-.00327*a-.07276*o+1.07602*s)}function Za(e,t,n,r,i){e*=r,t*=r,n*=r;let a=.6274*e+.3293*t+.0433*n,o=.0691*e+.9195*t+.0113*n,s=.0164*e+.088*t+.8956*n,c=.856627153315983*a+.0951212405381588*o+.0482516061458583*s,l=.137318972929847*a+.761241990602591*o+.101439036467562*s,u=.11189821299995*a+.0767994186031903*o+.811302368396859*s,d=-12.47393,f=4.026069-d;c=$a((Math.log2(Math.max(c,1e-10))-d)/f),l=$a((Math.log2(Math.max(l,1e-10))-d)/f),u=$a((Math.log2(Math.max(u,1e-10))-d)/f);let p=e=>{let t=e*e,n=t*t;return 15.5*n*t-40.14*n*e+31.96*n-6.868*t*e+.4298*t+.1191*e-.00232};c=p(c),l=p(l),u=p(u);let m=1.1271005818144368*c-.11060664309660323*l-.016493938717834573*u,h=-.1413297634984383*c+1.157823702216272*l-.016493938717834257*u,g=-.14132976349843826*c-.11060664309660294*l+1.2519364065950405*u;m=Math.max(0,m)**2.2,h=Math.max(0,h)**2.2,g=Math.max(0,g)**2.2,i[0]=$a(1.6605*m-.5876*h-.0728*g),i[1]=$a(-.1246*m+1.1329*h-.0083*g),i[2]=$a(-.0182*m-.1006*h+1.1187*g)}function Qa(e,t,n,r,i){let a=.76;e*=r,t*=r,n*=r;let o=Math.min(e,Math.min(t,n)),s=o<.08?o-6.25*o*o:.04;e-=s,t-=s,n-=s;let c=Math.max(e,Math.max(t,n));if(c<a){i[0]=e,i[1]=t,i[2]=n;return}let l=1-a,u=1-l*l/(c+l-a),d=u/c;e*=d,t*=d,n*=d;let f=1-1/(.15*(c-u)+1);i[0]=e+(u-e)*f,i[1]=t+(u-t)*f,i[2]=n+(u-n)*f}var $a,eo,to,no,ro,io,ao,oo=g((()=>{$a=e=>Math.min(Math.max(e,0),1),eo=`
|
|
115
|
+
`,[Be,ze]),G=rt({maxBounces:3,transmissiveBounces:5,maxSubsurfaceSteps:8,maxTransparentBounces:32,integrator:`path`,shadowRays:`two`,samplingTechnique:2,enableEmissiveTriangleSampling:!1,emissiveBoost:1,enableAlphaShadows:!1,fireflyThreshold:3,shadowTerminatorOffset:.1,globalIlluminationIntensity:1,wavefrontSortMaterials:!0,maxSamples:60,renderLimitMode:`frames`,renderTimeLimit:30,renderMode:0,useAdaptiveSampling:!0,noiseThreshold:.1,adaptiveMinSamples:8,adaptiveStopFraction:.9,usePixelFreeze:!0,pixelFreezeThreshold:.02,pixelFreezeStability:8,convergenceOverlay:!1,interactionModeEnabled:!0,exposure:1,saturation:1,transparentBackground:!1,backgroundColor:`#000000`,enableEnvironment:!0,environmentIntensity:1,environmentRotation:0,showBackground:!0,backgroundIntensity:1,backgroundBlurriness:0,backgroundBlurSamples:8,groundProjectionEnabled:!1,groundProjectionRadius:100,groundProjectionHeight:15,groundProjectionLevel:0,enableGroundCatcher:!1,groundCatcherHeight:0,cameraProjection:`perspective`,panoramaLonRange:[-180,180],panoramaLatRange:[-90,90],panoramaLevelHorizon:!0,enableDOF:!1,dofMode:`look`,dofBlur:.05,focusDistance:.8,aperture:5.6,focalLength:50,apertureScale:1,anamorphicRatio:1,unitsPerMetre:1,maxTextureSize:4096,areaLightIntensityScale:.1,visMode:0,debugVisScale:100}),tt=Object.freeze({perspective:0,equirectangular:1,orthographic:2}),nt=rt({color:[1,1,1],emissive:[0,0,0],emissiveIntensity:1,roughness:1,metalness:0,ior:1.5,opacity:1,transmission:0,thickness:0,attenuationColor:[1,1,1],attenuationDistance:1/0,dispersion:0,sheen:0,sheenRoughness:1,sheenColor:[0,0,0],specularIntensity:1,specularColor:[1,1,1],clearcoat:0,clearcoatRoughness:0,iridescence:0,iridescenceIOR:1.3,iridescenceThicknessRange:[100,400],normalScale:[1,1],bumpScale:1,displacementScale:1,transparent:0,alphaTest:0,alphaMode:0,side:0,depthWrite:1,subsurface:0,subsurfaceColor:[1,1,1],subsurfaceRadius:[1,.2,.1],subsurfaceRadiusScale:1,subsurfaceAnisotropy:0,anisotropy:0,anisotropyRotation:0,diffuseTransmission:0,diffuseTransmissionColor:[1,1,1]});function rt(e){for(let t of Object.values(e))typeof t==`object`&&Object.freeze(t);return Object.freeze(e)}var it={maxSamples:30,bounces:20,transmissiveBounces:24,maxSubsurfaceSteps:64,renderMode:1,enableAlphaShadows:!0,enableOIDN:!0,oidnQuality:`high`,interactionModeEnabled:!1,useAdaptiveSampling:!0,noiseThreshold:.02,adaptiveStopFraction:.94,usePixelFreeze:!0},at={maxSamples:G.maxSamples,bounces:G.maxBounces,renderMode:G.renderMode,enableAlphaShadows:G.enableAlphaShadows,transmissiveBounces:12,maxSubsurfaceSteps:G.maxSubsurfaceSteps,enableOIDN:!0,oidnQuality:`fast`,interactionModeEnabled:!0,useAdaptiveSampling:!0,noiseThreshold:.1,usePixelFreeze:!0};function ot(e){return{maxSamples:e.maxSamples,maxBounces:e.bounces,transmissiveBounces:e.transmissiveBounces,maxSubsurfaceSteps:e.maxSubsurfaceSteps,enableAlphaShadows:e.enableAlphaShadows??!1,useAdaptiveSampling:e.useAdaptiveSampling??!1,noiseThreshold:e.noiseThreshold??G.noiseThreshold,adaptiveStopFraction:e.adaptiveStopFraction??G.adaptiveStopFraction,adaptiveMinSamples:e.adaptiveMinSamples??G.adaptiveMinSamples,usePixelFreeze:e.usePixelFreeze??!1,pixelFreezeThreshold:e.pixelFreezeThreshold??G.pixelFreezeThreshold,pixelFreezeStability:e.pixelFreezeStability??G.pixelFreezeStability,interactionModeEnabled:e.interactionModeEnabled??G.interactionModeEnabled}}var st={cameraViewMatrix:`ptCameraViewMatrix`,cameraProjectionMatrix:`ptCameraProjectionMatrix`},ct=Object.freeze({directional:12,area:16,point:9,spot:20}),lt=65536/16;function ut(e,t){let n=Math.ceil(t/16)*16;return Math.max(t,Math.min(n,Math.floor(lt/ct[e])))}var dt=class{constructor(e=1920,t=1080){this._uniforms=new Map,this._booleans=new Set,this._arrayWarned=new Set,this._lightBuffers={},this._initUniforms(e,t),this._nameAll()}get(e){return this._uniforms.get(e)}set(e,t){let n=this._uniforms.get(e);if(!n){console.warn(`UniformManager: Unknown uniform "${e}"`);return}Array.isArray(t)&&t.length===1&&(this._booleans.has(e)||typeof n.value==`number`)&&(this._arrayWarned.has(e)||(this._arrayWarned.add(e),console.warn(`UniformManager: "${e}" was set to [${t[0]}] but expects a scalar — unwrapping. Fix the caller; a slider handler is probably forwarding its array value unchanged.`)),t=t[0]),this._booleans.has(e)?n.value=+!!t:typeof t==`object`&&t&&typeof n.value?.copy==`function`?n.value.copy(t):n.value=t}has(e){return this._uniforms.has(e)}keys(){return this._uniforms.keys()}getLightBufferNodes(){return this._lightBuffers}updateMany(e){let t=!1;for(let[n,r]of Object.entries(e)){let e=this._uniforms.get(n);e&&e.value!==r&&(e.value=r,t=!0)}return t}_initUniforms(e,t){let i=(e,t,r)=>{let i=(0,n.uniform)(t,r);return this._uniforms.set(e,i),i},a=(e,t)=>(this._booleans.add(e),i(e,+!!t,`int`));i(`frame`,0,`uint`),i(`seedFrame`,0,`uint`),i(`maxBounces`,G.maxBounces,`int`),i(`maxSamples`,G.maxSamples,`int`),i(`transmissiveBounces`,G.transmissiveBounces,`int`),i(`maxSubsurfaceSteps`,G.maxSubsurfaceSteps,`int`),i(`maxTransparentBounces`,G.maxTransparentBounces,`int`),i(`visMode`,G.visMode,`int`),i(`debugVisScale`,G.debugVisScale,`float`),a(`useAdaptiveSampling`,G.useAdaptiveSampling),i(`noiseThreshold`,G.noiseThreshold,`float`),i(`adaptiveMinSamples`,G.adaptiveMinSamples,`int`),i(`adaptiveStopFraction`,G.adaptiveStopFraction,`float`),a(`usePixelFreeze`,G.usePixelFreeze),i(`pixelFreezeThreshold`,G.pixelFreezeThreshold,`float`),i(`pixelFreezeStability`,G.pixelFreezeStability,`int`),a(`convergenceOverlay`,G.convergenceOverlay),a(`enableAccumulation`,!0),i(`accumulationAlpha`,0,`float`),a(`cameraIsMoving`,!1),a(`hasPreviousAccumulated`,!1),i(`auxAccumulationAlpha`,1,`float`),a(`hasPreviousAux`,!1),i(`environmentIntensity`,G.environmentIntensity,`float`),i(`backgroundIntensity`,G.backgroundIntensity,`float`),i(`backgroundColor`,new r.Color(0,0,0),`color`),i(`backgroundBlurriness`,G.backgroundBlurriness,`float`),i(`backgroundBlurSamples`,G.backgroundBlurSamples,`int`),a(`showBackground`,G.showBackground),a(`transparentBackground`,G.transparentBackground),a(`enableEnvironment`,G.enableEnvironment),i(`environmentMatrix`,new r.Matrix4,`mat4`),i(`envTotalSum`,0,`float`),i(`envResolution`,new r.Vector2(1,1),`vec2`),a(`groundProjectionEnabled`,G.groundProjectionEnabled),i(`groundProjectionRadius`,G.groundProjectionRadius,`float`),i(`groundProjectionHeight`,G.groundProjectionHeight,`float`),i(`groundProjectionLevel`,G.groundProjectionLevel,`float`),a(`enableGroundCatcher`,G.enableGroundCatcher),i(`groundCatcherHeight`,G.groundCatcherHeight,`float`),i(`sunDirection`,new r.Vector3(0,1,0),`vec3`),i(`sunRadiance`,new r.Vector3,`vec3`),i(`sunParams`,new r.Vector4(1,0,0,0),`vec4`),a(`hasSun`,!1),i(`globalIlluminationIntensity`,G.globalIlluminationIntensity,`float`),i(`exposure`,G.exposure,`float`),i(`numDirectionalLights`,0,`int`),i(`numAreaLights`,0,`int`),i(`numPointLights`,0,`int`),i(`numSpotLights`,0,`int`),this._lightBuffers=Object.fromEntries(Object.entries(ct).map(([e,t])=>[e,(0,n.uniformArray)(new Float32Array(t*16),`float`)])),i(`cameraWorldMatrix`,new r.Matrix4,`mat4`),i(`cameraProjectionMatrixInverse`,new r.Matrix4,`mat4`),i(`cameraViewMatrix`,new r.Matrix4,`mat4`),i(`cameraProjectionMatrix`,new r.Matrix4,`mat4`);let o=([e,t])=>new r.Vector2(e,t).multiplyScalar(r.MathUtils.DEG2RAD);i(`cameraProjection`,tt[G.cameraProjection],`int`),i(`panoLonRange`,o(G.panoramaLonRange),`vec2`),i(`panoLatRange`,o(G.panoramaLatRange),`vec2`),a(`panoLevelHorizon`,G.panoramaLevelHorizon),a(`enableDOF`,G.enableDOF),i(`focusDistance`,G.focusDistance,`float`),i(`focalLength`,G.focalLength,`float`),i(`aperture`,G.aperture,`float`),i(`apertureScale`,1,`float`),i(`anamorphicRatio`,G.anamorphicRatio??1,`float`),i(`unitsPerMetre`,G.unitsPerMetre,`float`),i(`dofMode`,+(G.dofMode===`look`),`int`),i(`dofBlur`,G.dofBlur,`float`),this._uniforms.set(`samplingTechnique`,Le),Le.value=G.samplingTechnique,i(`fireflyThreshold`,G.fireflyThreshold,`float`),i(`shadowTerminatorOffset`,G.shadowTerminatorOffset,`float`),a(`enableEmissiveTriangleSampling`,G.enableEmissiveTriangleSampling),i(`emissiveBoost`,G.emissiveBoost,`float`),i(`emissiveTriangleCount`,0,`int`),i(`emissiveTotalPower`,0,`float`),i(`lightBVHNodeCount`,0,`int`),i(`emissiveVec4Offset`,0,`int`),i(`reverseMapVec4Offset`,0,`int`),i(`renderMode`,G.renderMode,`int`),a(`enableAlphaShadows`,G.enableAlphaShadows),i(`resolution`,new r.Vector2(e,t),`vec2`)}_nameAll(){for(let[e,t]of this._uniforms)t.name=st[e]||e}dispose(){this._disposed||(this._disposed=!0,this._uniforms.clear(),this._booleans.clear(),this._arrayWarned.clear(),this._lightBuffers={})}};function ft(e){return!e||!((e.transmission||0)===0&&(!(e.transparent|0)||(e.opacity??1)>=1))?0:e.alphaMode|0?2:1}function pt(e,t){return(e&_t|(t?.side??0)<<24|ft(t)<<26)>>>0}function mt(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}function ht(e){return new Uint32Array(e.buffer,e.byteOffset,e.length)}function gt(e,t){if(e>=1073741824)throw RangeError(`${t} is ${e.toLocaleString()}, at or past the BVH index limit of ${yt.toLocaleString()}. Node indices are stored as u32 bit patterns and the leaf tags occupy everything above that.`);return e}var K,_t,q,vt,yt,bt,xt,St,Ct,wt=g((()=>{K={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},_t=16777215,q={SLOTS_PER_MATERIAL:34,FLOATS_PER_MATERIAL:136,IOR:0,TRANSMISSION:1,THICKNESS:2,EMISSIVE_INTENSITY:3,ATTENUATION_COLOR:4,ATTENUATION_DISTANCE:7,OPACITY:8,SIDE:9,TRANSPARENT:10,ALPHA_TEST:11,ALPHA_MODE:12,DEPTH_WRITE:13,NORMAL_SCALE:14,COLOR:16,METALNESS:19,EMISSIVE:20,ROUGHNESS:23,ALBEDO_MAP_INDEX:24,NORMAL_MAP_INDEX:25,ROUGHNESS_MAP_INDEX:26,METALNESS_MAP_INDEX:27,EMISSIVE_MAP_INDEX:28,BUMP_MAP_INDEX:29,CLEARCOAT:30,CLEARCOAT_ROUGHNESS:31,DISPERSION:32,VISIBLE:33,SHEEN:34,SHEEN_ROUGHNESS:35,SHEEN_COLOR:36,DIFFUSE_TRANSMISSION:39,SPECULAR_INTENSITY:40,SPECULAR_COLOR:41,IRIDESCENCE:44,IRIDESCENCE_IOR:45,IRIDESCENCE_THICKNESS_RANGE:46,BUMP_SCALE:48,DISPLACEMENT_SCALE:49,DISPLACEMENT_MAP_INDEX:50,ALBEDO_TRANSFORM:52,NORMAL_TRANSFORM:60,ROUGHNESS_TRANSFORM:68,METALNESS_TRANSFORM:76,EMISSIVE_TRANSFORM:84,BUMP_TRANSFORM:92,DISPLACEMENT_TRANSFORM:100,SUBSURFACE_COLOR:108,SUBSURFACE:111,SUBSURFACE_RADIUS:112,SUBSURFACE_RADIUS_SCALE:115,SUBSURFACE_ANISOTROPY:116,ANISOTROPY:117,ANISOTROPY_ROTATION:118,ANISOTROPY_MAP_INDEX:119,TRANSMISSION_MAP_INDEX:120,CLEARCOAT_MAP_INDEX:121,CLEARCOAT_ROUGHNESS_MAP_INDEX:122,SHEEN_COLOR_MAP_INDEX:123,SHEEN_ROUGHNESS_MAP_INDEX:124,IRIDESCENCE_MAP_INDEX:125,IRIDESCENCE_THICKNESS_MAP_INDEX:126,SPECULAR_INTENSITY_MAP_INDEX:127,SPECULAR_COLOR_MAP_INDEX:128,DIFFUSE_TRANSMISSION_COLOR:129,DIFFUSE_TRANSMISSION_MAP_INDEX:132,DIFFUSE_TRANSMISSION_COLOR_MAP_INDEX:133,SLOT:{IOR_TRANSMISSION:0,ATTENUATION:1,OPACITY_ALPHA:2,ALPHA_MODE:3,COLOR_METALNESS:4,EMISSIVE_ROUGHNESS:5,MAP_INDICES_A:6,MAP_INDICES_B:7,DISPERSION_SHEEN:8,SHEEN_COLOR:9,SPECULAR:10,IRIDESCENCE:11,BUMP_DISPLACEMENT:12,ALBEDO_TRANSFORM_A:13,ALBEDO_TRANSFORM_B:14,NORMAL_TRANSFORM_A:15,NORMAL_TRANSFORM_B:16,ROUGHNESS_TRANSFORM_A:17,ROUGHNESS_TRANSFORM_B:18,METALNESS_TRANSFORM_A:19,METALNESS_TRANSFORM_B:20,EMISSIVE_TRANSFORM_A:21,EMISSIVE_TRANSFORM_B:22,BUMP_TRANSFORM_A:23,BUMP_TRANSFORM_B:24,DISPLACEMENT_TRANSFORM_A:25,DISPLACEMENT_TRANSFORM_B:26,SUBSURFACE_A:27,SUBSURFACE_B:28,SUBSURFACE_C:29,EXT_MAP_INDICES_A:30,EXT_MAP_INDICES_B:31,EXT_MAP_INDICES_C:32,EXT_MAP_INDICES_D:33}},vt=e=>Number.isFinite(e)&&e>0?e:0,yt=1073741824,bt=1073741824,xt=1073741823,St={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826},Ct=1<<27}));wt();var Tt=[1,0,0,0,1,0,0,0],Et=[[`mapMatrix`,q.ALBEDO_TRANSFORM],[`normalMapMatrices`,q.NORMAL_TRANSFORM],[`roughnessMapMatrices`,q.ROUGHNESS_TRANSFORM],[`metalnessMapMatrices`,q.METALNESS_TRANSFORM],[`emissiveMapMatrices`,q.EMISSIVE_TRANSFORM],[`bumpMapMatrices`,q.BUMP_TRANSFORM],[`displacementMapMatrices`,q.DISPLACEMENT_TRANSFORM]];Object.freeze([q.VISIBLE,q.DISPLACEMENT_MAP_INDEX+1,q.DIFFUSE_TRANSMISSION_COLOR_MAP_INDEX+1,q.DIFFUSE_TRANSMISSION_COLOR_MAP_INDEX+2]);var Dt=Object.freeze(new Set([`metalness`,`roughness`,`transmission`,`opacity`,`clearcoat`,`clearcoatRoughness`,`sheen`,`sheenRoughness`,`specularIntensity`,`iridescence`,`subsurface`,`anisotropy`,`diffuseTransmission`])),Ot=e=>Math.min(Math.max(e,0),1);function kt(e,t){let n=typeof e==`boolean`?+e:e;return Number.isFinite(n)?n:t}function At(e){return Number.isInteger(e)?e:-1}function jt(e,t,n,r){let i=n?.r??n?.[0]??n?.x,a=n?.g??n?.[1]??n?.y,o=n?.b??n?.[2]??n?.z;e[t]=kt(i,r[0]),e[t+1]=kt(a,r[1]),e[t+2]=kt(o,r[2])}function Mt(e,t,n){let r=(n,r,i)=>{e[t+n]=kt(r,i)},i=(n,r,i)=>{e[t+n]=Ot(kt(r,i))};r(q.IOR,n.ior,nt.ior),i(q.TRANSMISSION,n.transmission,nt.transmission),r(q.THICKNESS,n.thickness,nt.thickness),r(q.EMISSIVE_INTENSITY,n.emissiveIntensity,nt.emissiveIntensity),jt(e,t+q.ATTENUATION_COLOR,n.attenuationColor,nt.attenuationColor),e[t+q.ATTENUATION_DISTANCE]=vt(n.attenuationDistance??nt.attenuationDistance),i(q.OPACITY,n.opacity,nt.opacity),r(q.SIDE,n.side,nt.side),r(q.TRANSPARENT,n.transparent,nt.transparent),r(q.ALPHA_TEST,n.alphaTest,nt.alphaTest),r(q.ALPHA_MODE,n.alphaMode,nt.alphaMode),r(q.DEPTH_WRITE,n.depthWrite,nt.depthWrite);let a=n.normalScale,o=typeof a==`number`?a:void 0;r(q.NORMAL_SCALE,o??a?.x??a?.[0],nt.normalScale[0]),r(q.NORMAL_SCALE+1,o??a?.y??a?.[1],nt.normalScale[1]),jt(e,t+q.COLOR,n.color,nt.color),i(q.METALNESS,n.metalness,nt.metalness),jt(e,t+q.EMISSIVE,n.emissive,nt.emissive),i(q.ROUGHNESS,n.roughness,nt.roughness),e[t+q.ALBEDO_MAP_INDEX]=At(n.map),e[t+q.NORMAL_MAP_INDEX]=At(n.normalMap),e[t+q.ROUGHNESS_MAP_INDEX]=At(n.roughnessMap),e[t+q.METALNESS_MAP_INDEX]=At(n.metalnessMap),e[t+q.EMISSIVE_MAP_INDEX]=At(n.emissiveMap),e[t+q.BUMP_MAP_INDEX]=At(n.bumpMap),i(q.CLEARCOAT,n.clearcoat,nt.clearcoat),i(q.CLEARCOAT_ROUGHNESS,n.clearcoatRoughness,nt.clearcoatRoughness),r(q.DISPERSION,n.dispersion,nt.dispersion),i(q.SHEEN,n.sheen,nt.sheen),i(q.SHEEN_ROUGHNESS,n.sheenRoughness,nt.sheenRoughness),jt(e,t+q.SHEEN_COLOR,n.sheenColor,nt.sheenColor),i(q.DIFFUSE_TRANSMISSION,n.diffuseTransmission,nt.diffuseTransmission),i(q.SPECULAR_INTENSITY,n.specularIntensity,nt.specularIntensity),jt(e,t+q.SPECULAR_COLOR,n.specularColor,nt.specularColor),i(q.IRIDESCENCE,n.iridescence,nt.iridescence),r(q.IRIDESCENCE_IOR,n.iridescenceIOR,nt.iridescenceIOR),r(q.IRIDESCENCE_THICKNESS_RANGE,n.iridescenceThicknessRange?.[0],nt.iridescenceThicknessRange[0]),r(q.IRIDESCENCE_THICKNESS_RANGE+1,n.iridescenceThicknessRange?.[1],nt.iridescenceThicknessRange[1]),r(q.BUMP_SCALE,n.bumpScale,nt.bumpScale),r(q.DISPLACEMENT_SCALE,n.displacementScale,nt.displacementScale),e[t+q.DISPLACEMENT_MAP_INDEX]=At(n.displacementMap);for(let[r,i]of Et){let a=n[r];for(let n=0;n<8;n++)e[t+i+n]=kt(a?.[n],Tt[n])}jt(e,t+q.SUBSURFACE_COLOR,n.subsurfaceColor,nt.subsurfaceColor),i(q.SUBSURFACE,n.subsurface,nt.subsurface),jt(e,t+q.SUBSURFACE_RADIUS,n.subsurfaceRadius,nt.subsurfaceRadius),r(q.SUBSURFACE_RADIUS_SCALE,n.subsurfaceRadiusScale,nt.subsurfaceRadiusScale),r(q.SUBSURFACE_ANISOTROPY,n.subsurfaceAnisotropy,nt.subsurfaceAnisotropy),i(q.ANISOTROPY,n.anisotropy,nt.anisotropy),r(q.ANISOTROPY_ROTATION,n.anisotropyRotation,nt.anisotropyRotation),e[t+q.ANISOTROPY_MAP_INDEX]=At(n.anisotropyMap),e[t+q.TRANSMISSION_MAP_INDEX]=At(n.transmissionMap),e[t+q.CLEARCOAT_MAP_INDEX]=At(n.clearcoatMap),e[t+q.CLEARCOAT_ROUGHNESS_MAP_INDEX]=At(n.clearcoatRoughnessMap),e[t+q.SHEEN_COLOR_MAP_INDEX]=At(n.sheenColorMap),e[t+q.SHEEN_ROUGHNESS_MAP_INDEX]=At(n.sheenRoughnessMap),e[t+q.IRIDESCENCE_MAP_INDEX]=At(n.iridescenceMap),e[t+q.IRIDESCENCE_THICKNESS_MAP_INDEX]=At(n.iridescenceThicknessMap),e[t+q.SPECULAR_INTENSITY_MAP_INDEX]=At(n.specularIntensityMap),e[t+q.SPECULAR_COLOR_MAP_INDEX]=At(n.specularColorMap),jt(e,t+q.DIFFUSE_TRANSMISSION_COLOR,n.diffuseTransmissionColor,nt.diffuseTransmissionColor),e[t+q.DIFFUSE_TRANSMISSION_MAP_INDEX]=At(n.diffuseTransmissionMap),e[t+q.DIFFUSE_TRANSMISSION_COLOR_MAP_INDEX]=At(n.diffuseTransmissionColorMap),e[t+q.VISIBLE]=1,e[t+q.DISPLACEMENT_MAP_INDEX+1]=0,e[t+q.DIFFUSE_TRANSMISSION_COLOR_MAP_INDEX+1]=0,e[t+q.DIFFUSE_TRANSMISSION_COLOR_MAP_INDEX+2]=0}var Nt={VEC4_PER_BVH_NODE:4,FLOATS_PER_VEC4:4,MIN_TEXTURE_WIDTH:4,MAX_CONCURRENT_WORKERS:Math.min(typeof navigator<`u`&&navigator.hardwareConcurrency||4,6),BUFFER_POOL_SIZE:20,CANVAS_POOL_SIZE:12,CACHE_SIZE_LIMIT:50,MAX_TEXTURE_SIZE:8192,DEFAULT_MAX_TEXTURE_SIZE:4096,MAX_TEXTURES_LIMIT:4*256,MATERIAL_BUCKET_COUNT:4,BUCKET_LAYER_STRIDE:256},Pt=64;function Ft(e,t){let n=Math.ceil(Math.max(1,e)/Pt)*Pt;return Math.min(t,Math.max(Nt.MIN_TEXTURE_WIDTH,n))}function It(e){let t=0,n=0,r=0;for(let i of e)t=Math.max(t,i.width),n=Math.max(n,i.height),r+=i.count;return{units:e,width:t,height:n,count:r}}function J(e,t){return Ft(e.width,t)*e.height*e.count*4}function Lt(e,t){return e.reduce((e,n)=>e+J(n,t),0)}function Rt(e,t,n){let r=e.slice();for(;r.length>t;){let e=null;for(let t=0;t<r.length;t++)for(let i=t+1;i<r.length;i++){let a=It(r[t].units.concat(r[i].units)),o=J(a,n)-J(r[t],n)-J(r[i],n);(!e||o<e.delta)&&(e={i:t,j:i,delta:o,fused:a})}r=r.filter((t,n)=>n!==e.i&&n!==e.j).concat([e.fused])}return r}function zt(e,t,n){let r=[];for(let e=t-1;e>=0;e--)r.push(Math.max(Nt.MIN_TEXTURE_WIDTH,Math.round(n/2**e)));let i=r.map(()=>[]);for(let t of e){let e=2**Math.ceil(Math.log2(Math.max(t.width,t.height))),n=r.findIndex(t=>e<=t);n<0&&(n=r.length-1),i[n].push(t)}return i.filter(e=>e.length).map(It)}function Bt(e,t){let n=e;for(let e=0;e<8;e++){let e=!1;for(let r of n.flatMap(e=>e.units)){let i=n.findIndex(e=>e.units.includes(r));if(!(i<0))for(let a=0;a<n.length;a++){if(a===i)continue;let o=[];for(let e=0;e<n.length;e++)if(e===i){let t=n[e].units.filter(e=>e!==r);t.length&&o.push(It(t))}else e===a?o.push(It(n[e].units.concat([r]))):o.push(n[e]);if(Lt(o,t)<Lt(n,t)){n=o,e=!0;break}}}if(!e)break}return n}function Vt(e,t,n=Nt.MATERIAL_BUCKET_COUNT){let r=new Map;for(let{width:n,height:i}of e){let e=Math.min(t,Math.max(1,n||1)),a=Math.min(t,Math.max(1,i||1)),o=`${e}x${a}`,s=r.get(o);s?s.count++:r.set(o,{width:e,height:a,count:1})}let i=[...r.values()],a=i.map(e=>It([e]));if(a.length>n){let e=zt(i,n,t),r=Rt(a,n,t);a=Lt(e,t)<Lt(r,t)?e:r,a=Bt(a,t)}return a.map(e=>({width:Ft(e.width,t),height:e.height})).sort((e,t)=>e.width*e.height-t.width*t.height)}function Ht(e,t,n){let r=Math.max(1,e||1),i=Math.max(1,t||1);for(let e=0;e<n.length;e++)if(n[e].width>=r&&n[e].height>=i)return e;return Math.max(0,n.length-1)}function Ut(e,t){return e*Nt.BUCKET_LAYER_STRIDE+t}var Y,Wt,Gt,Kt,X=g((()=>{Y=Object.freeze({ADAPTER_SOFTWARE:`adapter.software`,ASSET_UNREACHABLE:`asset.unreachable`,ASSET_AMBIGUOUS_ENTRY:`asset.ambiguous_entry`,ASSET_ARCHIVE_TOO_LARGE:`asset.archive_too_large`,ASSET_ENTRY_TOO_LARGE:`asset.entry_too_large`,TEXTURE_BUILD_FAILED:`texture.build_failed`,TEXTURE_PROCESSING_FALLBACK:`texture.processing_fallback`,TEXTURE_LIMIT_EXCEEDED:`texture.limit_exceeded`,ENVIRONMENT_LOAD_FAILED:`environment.load_failed`,SETTING_UNKNOWN_KEY:`setting.unknown_key`,RENDER_SIZE_DECLINED:`render.size_declined`,STAGE_RENDER_FAILED:`stage.render_failed`,RENDER_RESERVE_CAPPED:`render.reserve_capped`,SCENE_MEMORY_BUDGET:`scene.memory_budget`,EMISSIVE_INSTANCES_COLLAPSED:`emissive.instances_collapsed`,REFIT_SHARED_GEOMETRY:`refit.shared_geometry`,VIEW_TRANSFORM_DISPLAY_MISMATCH:`viewTransform.display_mismatch`,VIEW_TRANSFORM_BAKE_FAILED:`viewTransform.bake_failed`,COLOR_CONFIG_LOAD_FAILED:`color.config_load_failed`,STORAGE_UNAVAILABLE:`storage.unavailable`,STORAGE_QUOTA_EXCEEDED:`storage.quota_exceeded`,STORAGE_WRITE_FAILED:`storage.write_failed`,STORAGE_READ_FAILED:`storage.read_failed`,STORAGE_ENTRY_CORRUPT:`storage.entry_corrupt`,STORAGE_CACHE_MISMATCH:`storage.cache_mismatch`,DENOISER_UNAVAILABLE:`denoiser.unavailable`,OUTPUT_SOURCE_FALLBACK:`output.source_fallback`,OUTPUT_TONEMAP_FALLBACK:`output.tonemap_fallback`,LIGHT_PLACEHOLDER_SKIPPED:`light.placeholder_skipped`,CAPABILITY_MISSING:`capability.missing`}),Wt=Object.freeze({ERROR:`error`,WARNING:`warning`}),Gt=class extends Error{constructor(e){super(`[${e.code}] ${e.message}`),this.name=`EngineIssueError`,this.code=e.code,this.detail=e.detail}},Kt=class{constructor({strict:e=!1,onIssue:t=null}={}){this.strict=e===!0,this._onIssue=t,this._entries=[]}record(e,t,n={},r=Wt.ERROR){let i=Object.freeze({code:e,message:t,detail:n,severity:r,at:Date.now()});if(this._entries.push(i),this._onIssue?.(i),this.strict&&r===Wt.ERROR)throw new Gt(i);return i}warn(e,t,n){return this.record(e,t,n,Wt.WARNING)}get list(){return this._entries.slice()}get errors(){return this._entries.filter(e=>e.severity===Wt.ERROR)}clear(){this._entries.length=0}detach(){this._onIssue=null,this.strict=!1}}}));function qt(e){Zt=e}function Jt(e,t,n){let r=n?new e(new SharedArrayBuffer(t*e.BYTES_PER_ELEMENT)):new e(t);return Zt&&r.byteLength>0&&Zt(r.byteLength,n),r}var Yt,Xt,Zt,Qt,$t=g((()=>{Yt=64*1024*1024,Xt=typeof SharedArrayBuffer<`u`,Zt=null,Qt=class e{constructor(e,t,n,r=Yt,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(Jt(n,e*t,i)),s-=e}this.chunks.length===0&&this.chunks.push(Jt(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=Yt,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]=Jt(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=await this._store.read(e,t*this.LaneType.BYTES_PER_ELEMENT),r=Jt(this.LaneType,t,this.shared);new Uint8Array(r.buffer,r.byteOffset,r.byteLength).set(new Uint8Array(n)),this.chunks[e]=r;for(let t of this._liveViews())t.chunks[e]=new t.LaneType(r.buffer,r.byteOffset,r.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=Jt(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}}})),en,tn,nn=g((()=>{en=Object.freeze({CACHE:`cache`,USER:`user`,SCRATCH:`scratch`}),tn=Object.freeze({DOWNLOADS:`downloads`,ARCHIVES:`archives`,SCENES:`scenes`,CDF:`cdf`,SPILL:`spill`})}));X(),$t(),nn();var rn=32*1024*1024,an=`chunks.bin`,on=class e{static async create(t,n,r,{label:i=``,expectedBytes:a=0}={}){let o=t?.area(tn.SPILL),s=await o?.create(n,{label:i,expectedBytes:a,growable:[an]});return s?new e(o,n,r,s):null}constructor(e,t,n,r){this._area=e,this._key=t,this._chunkBytes=n,this._writer=r,this._entry=null,this._file=null}write(e,t){return this.writeAt(e*this._chunkBytes,t)}async writeAt(e,t){if(!this._writer&&(this._entry?.release(),this._entry=this._file=null,this._writer=await this._area.edit(this._key),!this._writer))throw Error(`spill: its storage entry is gone`);let n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),r=0;do await this._writer.write(an,n.subarray(r,Math.min(n.length,r+rn)),{at:e+r}),r+=rn;while(r<n.length)}async flush(){if(this._writer&&=(await this._writer.commit(),null),!this._entry&&(this._entry=await this._area.open(this._key,{wait:!0}),this._file=await this._entry?.file(an),!this._file))throw Error(`spill: its storage entry is gone`)}read(e,t){return this.readAt(e*this._chunkBytes,t)}async readAt(e,t){return await this.flush(),await this._file.slice(e,e+t).arrayBuffer()}async dispose(){this._writer&&await this._writer.abort(),this._writer=null,this._entry?.release(),this._entry=this._file=null,await this._area.remove(this._key)}},sn=32*1024*1024,cn=sn/4,ln=64*1024*1024,un=new Map;function dn(e){let t=un.get(e);return t||un.set(e,t=new e(0)),t}var fn=class e{static async create(t,n,r=0){let i=await on.create(t,n,0,{label:`Scene geometry (while building)`,expectedBytes:r});return i?new e(i):null}static canTake(e){if(Object.keys(e.morphAttributes??{}).length)return!1;for(let t in e.attributes)if(!e.attributes[t].isBufferAttribute)return!1;return!e.index||e.index.isBufferAttribute===!0}constructor(e){this._store=e,this._records=[],this._geometries=[],this._end=0,this._pack=null,this._packAt=0,this._packUsed=0,this._packRecords=[],this._chain=Promise.resolve(),this._queued=0,this.bytes=0,this.error=null}get queuedBytes(){return this._queued}add(e){let t=new Map,n=Object.values(e.attributes);e.index&&n.push(e.index);for(let e of n){let n=e.array;if(!n?.byteLength)continue;let r=t.get(n);r||t.set(n,r=this._write(n)),r.attributes.push(e),e.array=dn(n.constructor)}this._geometries.push({geometry:e,box:e.boundingBox!==null,sphere:e.boundingSphere!==null})}_write(e){let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n={at:0,byteLength:t.byteLength,Type:e.constructor,attributes:[],array:null,pack:null,offset:0};return this._records.push(n),this.bytes+=t.byteLength,t.byteLength>=cn?(n.at=this._end,n.array=e,this._end+=t.byteLength,this._queue(n.at,t,[n]),n):(this._pack&&this._packUsed+t.byteLength>sn&&this._flushPack(),this._pack||(this._pack=new Uint8Array(sn),this._packAt=this._end,this._packUsed=0,this._end+=sn),this._pack.set(t,this._packUsed),n.at=this._packAt+this._packUsed,n.pack=this._pack,n.offset=this._packUsed,this._packUsed+=t.byteLength,this._packRecords.push(n),n)}_flushPack(){this._pack&&(this._queue(this._packAt,this._pack.subarray(0,this._packUsed),this._packRecords),this._pack=null,this._packRecords=[])}_queue(e,t,n){this._queued+=t.byteLength,this._chain=this._chain.then(async()=>{if(!this.error){await this._store.writeAt(e,t);for(let e of n)e.array=e.pack=null}}).catch(e=>void(this.error??=e)).finally(()=>void(this._queued-=t.byteLength))}written(){return this._flushPack(),this._chain}async restore(){await this.written();let e=this._records.sort((e,t)=>e.at-t.at);e.some(e=>!e.array&&!e.pack)&&await this._store.flush();let t=null,n=0;for(let r of e){let e;if(r.array?e=r.array:r.pack?e=new r.Type(r.pack.slice(r.offset,r.offset+r.byteLength).buffer):r.byteLength>ln?e=new r.Type(await this._store.readAt(r.at,r.byteLength)):((!t||r.at+r.byteLength>n+t.byteLength)&&(n=r.at,t=await this._store.readAt(r.at,ln)),e=new r.Type(t.slice(r.at-n,r.at-n+r.byteLength))),e.byteLength!==r.byteLength)throw Error(`geometry spill: an array came back short`);for(let t of r.attributes)t.array=e}for(let{geometry:e,box:t,sphere:n}of this._geometries)t||(e.boundingBox=null),n||(e.boundingSphere=null);this._records=[],this._geometries=[],this.bytes=0}async dispose(){await this._chain,this._records=[],this._geometries=[],this._pack=null,this._packRecords=[],await this._store.dispose()}};wt(),Ae();var pn=ye(`geometry`),mn=Nt.MAX_TEXTURES_LIMIT,hn=new Set([`color`,`emissive`,`attenuationColor`,`sheenColor`,`specularColor`,`subsurfaceColor`,`diffuseTransmissionColor`]),gn=Object.freeze({MATERIAL:`material`,MAPPED:`mapped`,DEFAULT:`default`,HOST:`host`}),_n=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function vn(e){for(let t=0;t<16;t++)if(e[t]!==_n[t])return!1;return!0}function yn(e){return{map:e.map,normalMap:e.normalMap,bumpMap:e.bumpMap,roughnessMap:e.roughnessMap,metalnessMap:e.metalnessMap,emissiveMap:e.emissiveMap??(e.isMeshBasicMaterial?e.map:void 0),displacementMap:e.displacementMap,anisotropyMap:e.anisotropyMap,clearcoatMap:e.clearcoatMap,clearcoatRoughnessMap:e.clearcoatRoughnessMap,transmissionMap:e.transmissionMap,sheenColorMap:e.sheenColorMap,sheenRoughnessMap:e.sheenRoughnessMap,specularIntensityMap:e.specularIntensityMap,specularColorMap:e.specularColorMap,diffuseTransmissionMap:e.diffuseTransmissionMap,diffuseTransmissionColorMap:e.diffuseTransmissionColorMap,iridescenceMap:e.iridescenceMap,iridescenceThicknessMap:e.iridescenceThicknessMap}}function bn(e){if(e.userData?.gltfExtensions?.KHR_materials_unlit?.alphaMode){let t=e.userData.gltfExtensions.KHR_materials_unlit.alphaMode;return t===`BLEND`?2:+(t===`MASK`)}return e.alphaTest>0?1:e.transparent&&e.opacity<1||e.map&&e.map.format===r.RGBAFormat&&e.transparent?2:0}function xn(e){let t=0,n=new Set,r=e=>{let i=e.isMesh&&e.material?e.geometry:null;if(i&&!n.has(i.uuid)){n.add(i.uuid);for(let e in i.attributes)t+=i.attributes[e].array?.byteLength??0;t+=i.index?.array?.byteLength??0}if(e.children)for(let t of e.children)r(t)};return r(e),t}function Sn(e,t){let n=e.x,r=e.y,i=e.z;e.x=t[0]*n+t[4]*r+t[8]*i+t[12],e.y=t[1]*n+t[5]*r+t[9]*i+t[13],e.z=t[2]*n+t[6]*r+t[10]*i+t[14]}function Cn(e,t){let n=e.x,r=e.y,i=e.z;e.x=t[0]*n+t[3]*r+t[6]*i,e.y=t[1]*n+t[4]*r+t[7]*i,e.z=t[2]*n+t[5]*r+t[8]*i}var wn=1<<21;function Tn(e){return!!(e.isSkinnedMesh||Object.keys(e.geometry?.morphAttributes??{}).length)}function En(e){return e[0]*(e[5]*e[10]-e[9]*e[6])-e[4]*(e[1]*e[10]-e[9]*e[2])+e[8]*(e[1]*e[6]-e[5]*e[2])}var Dn=class{constructor({issues:e=null}={}){this._issues=e,this._droppedTextures=0,this._vectorPool={vec3:Array(9).fill().map(()=>new r.Vector3),vec2:[,,,,,,].fill().map(()=>new r.Vector2)},this._geometryRanges=new Map,this.expandedTriangleCount=0,this._allocatePlacements(0),this._matrixPool={mat3:new r.Matrix3,mat4:new r.Matrix4},this.resetArrays(),this.triangleCount=0,this.currentTriangleIndex=0}_getVec3(e=0){return this._vectorPool.vec3[e%this._vectorPool.vec3.length]}_getVec2(e=0){return this._vectorPool.vec2[e%this._vectorPool.vec2.length]}extract(e){this.resetArrays();let t=this._countTriangles(e);return this._triangleCapacity=Math.max(1024,t),this._allocateTriangles(this._triangleCapacity),this.currentTriangleIndex=0,this._allocatePlacements(this._countPlacements(e)),this._geometryUses=this._countGeometryUses(e),this.bakeInverse=new Map,this.traverseObject(e),this._shareInstanceMatrices(),this._compressAttributes(e),this.logStats(),this.getExtractedData()}async extractStreaming(e,{onStore:t,onRange:n,pause:r,yieldEvery:i=1<<20,releaseGeometry:a=null}){this.resetArrays(),this._triangleCapacity=Math.max(1,this._countStoredTriangles(e)),this._allocateTriangles(this._triangleCapacity,!0),t?.(this.triangles),this.currentTriangleIndex=0,this._allocatePlacements(this._countPlacements(e)),this._geometryUses=this._countGeometryUses(e),this.bakeInverse=new Map,this._onRange=n,this._releaseAfterRead=a?this._geometryReleaser(e,a):null;try{let t=[e],n=0;for(;t.length;){let e=t.pop();if(this._visit(e),e.children)for(let n=e.children.length-1;n>=0;n--)t.push(e.children[n]);this.currentTriangleIndex-n>=i&&(n=this.currentTriangleIndex,await r(this.currentTriangleIndex))}}finally{this._onRange=null,this._releaseAfterRead=null}return this._shareInstanceMatrices(),this._compressAttributes(e),this.triangles.trimInPlace(this.currentTriangleIndex),this._streamedStore=!0,this.logStats(),this.getExtractedData()}_countStoredTriangles(e){let t=new Set,n=0,r=e=>{if(e.isMesh&&e.geometry&&e.material){let r=e.geometry,i=Math.ceil((r.index?r.index.count:r.attributes.position?.count??0)/3),a=Array.isArray(e.material)?e.material[0]:e.material,o=a?.emissive,s=a?.emissiveIntensity>0&&!!o&&(o.r>0||o.g>0||o.b>0),c=e.isInstancedMesh?e.count??0:1;if(s&&e.isInstancedMesh&&!Tn(e)&&i*c<=wn)n+=i*c;else if(s||Tn(e))n+=i;else{let e=`${r.uuid}|${a?.uuid}`;t.has(e)||(t.add(e),n+=i)}}if(e.children)for(let t of e.children)r(t)};return r(e),n}_geometryReleaser(e,t){let n=new Map,r=new Map,i=new Set,a=(e,t)=>{t||=!!e.userData?.__rayzeeExternal;let o=e.isMesh&&e.material?e.geometry:null;if(o){if(!n.has(o)){fn.canTake(o)||i.add(o);for(let e of[...Object.values(o.attributes),o.index]){let t=e?.array;if(!t)continue;let n=r.get(t);n&&n!==o?i.add(o).add(n):r.set(t,o)}}n.set(o,(n.get(o)??0)+1),(t||Tn(e))&&i.add(o)}if(e.children)for(let n of e.children)a(n,t)};return a(e,!1),e=>{let r=e.material?e.geometry:null;if(!r||!n.has(r))return;let a=n.get(r)-1;if(a>0)return void n.set(r,a);n.delete(r),!i.has(r)&&(this._compressGeometry(r),t(r))}}surveyScene(e){let t=0,n=e=>{if(e.isMesh&&e.geometry&&e.material&&t++,e.children)for(let t of e.children)n(t)};return n(e),{triangles:this._countTriangles(e),placements:this._countPlacements(e),meshes:t,geometryBytes:xn(e)}}_countGeometryUses(e){let t=new Map;return e.traverse(e=>{if(!e.isMesh||!e.geometry||!e.material)return;let n=`${e.geometry.uuid}|${e.material.uuid}`;t.set(n,(t.get(n)??0)+1)}),t}_countPlacements(e){let t=0;if(e.isMesh&&e.geometry&&e.material&&(t+=e.isInstancedMesh&&e.instanceMatrix?e.count??e.instanceMatrix.array.length/16:1),e.children)for(let n of e.children)t+=this._countPlacements(n);return t}_allocatePlacements(e){this.instanceCount=0,this.instanceCapacity=e,this.instanceSource=new Int32Array(e),this.instanceMatrices=new Float32Array(e*16),this._shareable=[],this._compressed=new Set}_compressAttributes(e){let t=(e,n)=>{if(!e.userData?.__rayzeeExternal){n(e);for(let r of e.children)t(r,n)}};t(e,e=>{e.isMesh&&e.geometry&&this._compressGeometry(e.geometry)})}_compressGeometry(e){if(!this._compressed.has(e.uuid)){this._compressed.add(e.uuid);for(let t of[`normal`,`tangent`,`color`]){let n=e.getAttribute(t);if(!n||n.normalized||!(n.array instanceof Float32Array)||e.morphAttributes?.[t]?.length)continue;let i=n.array,a=!0;for(let e=0;e<i.length;e++){let t=i[e];if(!(t>=-1.0001&&t<=1.0001)){a=!1;break}}if(!a)continue;let o=new Int16Array(i.length);for(let e=0;e<i.length;e++)o[e]=Math.round(Math.max(-1,Math.min(1,i[e]))*32767);e.setAttribute(t,new r.BufferAttribute(o,n.itemSize,!0))}}}_shareInstanceMatrices(){for(let{mesh:e,start:t,count:n}of this._shareable){let r=e.instanceMatrix;!r||r.array.length!==n*16||(r.array=this.instanceMatrices.subarray(t*16,(t+n)*16))}this._shareable=[]}_countTriangles(e){let t=0;if(e.isMesh&&e.geometry&&e.material){let n=e.geometry.index,r=e.geometry.attributes.position;n?t+=Math.ceil(n.count/3):r&&(t+=Math.ceil(r.count/3))}if(e.children)for(let n of e.children)t+=this._countTriangles(n);return t}_ensureCapacity(e){if(e<=this._triangleCapacity)return;if(this._onRange){this.triangles.grow(e),this._triangleCapacity=e;return}let t=this.triangles,n=this.currentTriangleIndex;this._allocateTriangles(e);for(let e=0;e<n;e++)this.triangles.chunkFor(e).set(t.chunkFor(e).subarray(t.baseOf(e),t.baseOf(e)+t.lanesPerRecord),this.triangles.baseOf(e));this._triangleCapacity=e}_allocateTriangles(e,t=!1){this.triangles=(t?Qt.lazy:(...e)=>new Qt(...e))(e,K.FLOATS_PER_TRIANGLE,Uint32Array,void 0,Xt),this.triangleFloatChunks=this.triangles.viewAs(Float32Array),this.triangleData=this.triangles.single,this.triangleFloats=this.triangleFloatChunks.single}traverseObject(e){if(this._visit(e),e.children)for(let t of e.children)this.traverseObject(t)}_visit(e){e.isMesh?(this.processMesh(e),this._releaseAfterRead?.(e)):e.isDirectionalLight?this.directionalLights.push(e):e.isCamera&&this.cameras.push(e)}processMesh(e){if(!e.geometry||!e.material){console.warn(`Skipping mesh with missing geometry or material:`,e);return}let t=this.processMaterial(e.material);e.userData.materialIndex=t;let n=this.meshes.length;this.meshes.push(e),e.userData.meshIndex=n;let r=`${e.geometry.uuid}|${t}`,i=Tn(e),a=!this._emissiveMaterial(t)&&!i,o=a?this._geometryRanges.get(r):null;if(o){let t={start:o.start,count:o.count,expandedStart:this.expandedTriangleCount,sharedFrom:o.meshIndex};this.expandedTriangleCount+=o.count,this.meshTriangleRanges.push(t),this._recordPlacements(e,n);return}let s=this.currentTriangleIndex,c=e.isInstancedMesh&&!i&&this._emissiveMaterial(t)&&this._canExpand(e),l=c||!e.isInstancedMesh&&!i&&(this._geometryUses.get(`${e.geometry.uuid}|${e.material?.uuid}`)===1||this._emissiveMaterial(t));this.extractGeometry(e,t,n,l,c);let u={start:s,count:this.currentTriangleIndex-s,expandedStart:this.expandedTriangleCount};this.expandedTriangleCount+=u.count,this.meshTriangleRanges.push(u),u.count>0&&!l&&a&&this._geometryRanges.set(r,{...u,meshIndex:n}),this._recordPlacements(e,n,l,c),u.count>0&&this._onRange?.(n,u)}_recordPlacements(e,t,n=!1,r=!1){let i=e.matrixWorld.elements,a=this.instanceMatrices,o=this.instanceSource;if(!e.isInstancedMesh||!e.instanceMatrix||r){let r=this._nextPlacement();if(o[r]=t,n){for(let e=0;e<16;e++)a[r*16+e]=+(e%5==0);this.bakeInverse.set(t,Float32Array.from(this._matrixPool.mat4.copy(e.matrixWorld).invert().elements))}else for(let e=0;e<16;e++)a[r*16+e]=i[e];return}let s=e.instanceMatrix.array,c=e.count??s.length/16,l=vn(i);l&&s.length===c*16&&this._shareable.push({mesh:e,start:this.instanceCount,count:c});for(let e=0;e<c;e++){let n=e*16,r=this._nextPlacement(),c=r*16;if(o[r]=t,l){for(let e=0;e<16;e++)a[c+e]=s[n+e];continue}for(let e=0;e<4;e++)for(let t=0;t<4;t++)a[c+e*4+t]=i[t]*s[n+e*4]+i[4+t]*s[n+e*4+1]+i[8+t]*s[n+e*4+2]+i[12+t]*s[n+e*4+3]}}_nextPlacement(){if(this.instanceCount>=this.instanceCapacity){let e=Math.max(16,this.instanceCapacity*2),t=new Int32Array(e),n=new Float32Array(e*16);t.set(this.instanceSource),n.set(this.instanceMatrices),this.instanceSource=t,this.instanceMatrices=n,this.instanceCapacity=e}return this.instanceCount++}_canExpand(e){let t=e.geometry,n=(t.index?t.index.count:t.attributes.position.count)/3,r=e.count??(e.instanceMatrix?.array.length??0)/16;return n*r<=wn?!0:(this._issues?.record(Y.EMISSIVE_INSTANCES_COLLAPSED,`"${e.name||`instanced mesh`}" would need ${Math.round(n*r).toLocaleString()} triangles to light every instance; lighting the first one only`,{instances:r,trianglesPerInstance:n,limit:wn}),!1)}_emissiveMaterial(e){let t=this.materials[e];if(!t||!(t.emissiveIntensity>0))return!1;let n=t.emissive;return!!n&&(n.r>0||n.g>0||n.b>0)}processMaterial(e){let t=this._materialUuidMap.get(e.uuid)??-1;if(t===-1){e.depthWrite===!1&&(e.depthWrite=!0,B(pn,`depthWrite`,`material had depthWrite disabled — enabled for rastered rendering`));let n=this.createMaterialObject(e);this.materials.push(n),t=this.materials.length-1,this._materialUuidMap.set(e.uuid,t)}return t}getMaterialType(e){return e.isMeshPhysicalMaterial?`physical`:e.isMeshStandardMaterial?`standard`:e.isMeshPhongMaterial?`phong`:e.isMeshLambertMaterial?`lambert`:e.isMeshBasicMaterial?`basic`:e.isMeshToonMaterial?`toon`:`unknown`}getPhysicalDefaults(){let e={};for(let[t,n]of Object.entries(nt))e[t]=hn.has(t)?new r.Color().fromArray(n):Array.isArray(n)?[...n]:n;return e.normalScale={x:nt.normalScale[0],y:nt.normalScale[1]},e}mapLegacyMaterialToPhysical(e,t){let n={};switch(t){case`basic`:n.emissive=e.color.clone(),n.emissiveIntensity=1,n.color=new r.Color(0),n.roughness=1,n.metalness=0,n.specularIntensity=0;break;case`lambert`:n.roughness=1,n.metalness=0,n.specularIntensity=0;break;case`phong`:{let t=e.shininess||30;n.roughness=Math.sqrt(2/(t+2)),n.metalness=0}if(e.specular){let t=e.specular,i=t.r*.299+t.g*.587+t.b*.114,a=Math.max(t.r,t.g,t.b);n.specularIntensity=Math.min(i*2,1),n.specularColor=a>0?t.clone().multiplyScalar(1/a):new r.Color(1,1,1)}break;case`toon`:n.roughness=.9,n.metalness=0;break;case`standard`:case`physical`:break}return n}createMaterialObject(e){let t=this.getPhysicalDefaults(),n=this.getMaterialType(e),r=this.mapLegacyMaterialToPhysical(e,n),i=yn(e),a={},o=n=>r[n]===void 0?e[n]!==void 0&&e[n]!==null?(a[n]=gn.MATERIAL,e[n]):(a[n]=gn.DEFAULT,t[n]):(a[n]=gn.MAPPED,r[n]);for(let e of[`transparent`,`alphaMode`,`side`,`depthWrite`])a[e]=gn.MATERIAL;return{uuid:e.uuid,color:o(`color`),emissive:o(`emissive`),emissiveIntensity:o(`emissiveIntensity`),roughness:Math.max(.02,o(`roughness`)),metalness:o(`metalness`),ior:o(`ior`),opacity:o(`opacity`),transmission:o(`transmission`),thickness:o(`thickness`),attenuationColor:o(`attenuationColor`),attenuationDistance:o(`attenuationDistance`),dispersion:o(`dispersion`),sheen:o(`sheen`),sheenRoughness:o(`sheenRoughness`),sheenColor:o(`sheenColor`),clearcoat:o(`clearcoat`),clearcoatRoughness:o(`clearcoatRoughness`),iridescence:o(`iridescence`),iridescenceIOR:o(`iridescenceIOR`),iridescenceThicknessRange:o(`iridescenceThicknessRange`),subsurface:o(`subsurface`),subsurfaceColor:o(`subsurfaceColor`),subsurfaceRadius:o(`subsurfaceRadius`),subsurfaceRadiusScale:o(`subsurfaceRadiusScale`),subsurfaceAnisotropy:o(`subsurfaceAnisotropy`),anisotropy:o(`anisotropy`),anisotropyRotation:o(`anisotropyRotation`),specularIntensity:o(`specularIntensity`),specularColor:o(`specularColor`),diffuseTransmission:o(`diffuseTransmission`),diffuseTransmissionColor:o(`diffuseTransmissionColor`),normalScale:o(`normalScale`),bumpScale:o(`bumpScale`),displacementScale:o(`displacementScale`),transparent:+!!e.transparent,alphaTest:o(`alphaTest`),alphaMode:bn(e),side:this.getMaterialSide(e),depthWrite:e.depthWrite??!0?1:0,map:this.processTexture(i.map,this.maps),normalMap:this.processTexture(i.normalMap,this.normalMaps),bumpMap:this.processTexture(i.bumpMap,this.bumpMaps),roughnessMap:this.processTexture(i.roughnessMap,this.roughnessMaps),metalnessMap:this.processTexture(i.metalnessMap,this.metalnessMaps),emissiveMap:this.processTexture(i.emissiveMap,this.emissiveMaps),displacementMap:this.processTexture(i.displacementMap,this.displacementMaps),anisotropyMap:this.processTexture(i.anisotropyMap,this.anisotropyMaps),clearcoatMap:this.processTexture(i.clearcoatMap,this.clearcoatMaps),clearcoatRoughnessMap:this.processTexture(i.clearcoatRoughnessMap,this.clearcoatRoughnessMaps),transmissionMap:this.processTexture(i.transmissionMap,this.transmissionMaps),thicknessMap:this.processTexture(e.thicknessMap,[]),sheenColorMap:this.processTexture(i.sheenColorMap,this.sheenColorMaps),sheenRoughnessMap:this.processTexture(i.sheenRoughnessMap,this.sheenRoughnessMaps),specularIntensityMap:this.processTexture(i.specularIntensityMap,this.specularIntensityMaps),specularColorMap:this.processTexture(i.specularColorMap,this.specularColorMaps),diffuseTransmissionMap:this.processTexture(i.diffuseTransmissionMap,this.diffuseTransmissionMaps),diffuseTransmissionColorMap:this.processTexture(i.diffuseTransmissionColorMap,this.diffuseTransmissionColorMaps),iridescenceMap:this.processTexture(i.iridescenceMap,this.iridescenceMaps),iridescenceThicknessMap:this.processTexture(i.iridescenceThicknessMap,this.iridescenceThicknessMaps),mapMatrix:this.getTextureMatrix(i.map),normalMapMatrices:this.getTextureMatrix(i.normalMap),bumpMapMatrices:this.getTextureMatrix(i.bumpMap),roughnessMapMatrices:this.getTextureMatrix(i.roughnessMap),metalnessMapMatrices:this.getTextureMatrix(i.metalnessMap),emissiveMapMatrices:this.getTextureMatrix(i.emissiveMap),displacementMapMatrices:this.getTextureMatrix(i.displacementMap),sources:a,originalType:n}}getTextureMatrix(e){return e?(e.matrixAutoUpdate&&e.updateMatrix(),e.matrix.elements):new r.Matrix3().elements}getMaterialSide(e){if(e.transmission>0)return 2;switch(e.side){case r.FrontSide:return 0;case r.BackSide:return 1;case r.DoubleSide:return 2;default:return 0}}processTexture(e,t){if(!e)return-1;let n=this._textureIndexCache.get(t);n||(n=new Map,this._textureIndexCache.set(t,n));let r=e.source.uuid,i=n.get(r);if(i!==void 0)return i;if(t.length<mn){t.push(e);let i=t.length-1;return n.set(r,i),i}return this._droppedTextures++,this._droppedTextures===1&&this._issues?.record(Y.TEXTURE_LIMIT_EXCEEDED,`scene needs more than ${mn} distinct textures for one map type; the rest render untextured`,{limit:mn,firstDropped:e.name||e.source?.uuid}),-1}extractGeometry(e,t,n,i=!1,a=!1){e.updateMatrix(),e.updateMatrixWorld();let o=e.geometry;o.attributes.normal||o.computeVertexNormals();let s=o.attributes.position,c=o.attributes.normal,l=o.attributes.uv,u=o.index?o.index.array:null,d=u?u.length/3:s.count/3;if(a){let i=e.count??e.instanceMatrix.array.length/16,a=this._matrixPool.mat4,o=new r.Matrix4;for(let f=0;f<i;f++){a.fromArray(e.instanceMatrix.array,f*16),o.multiplyMatrices(e.matrixWorld,a);let i=new r.Matrix3().getNormalMatrix(o);this.extractTrianglesInBatch(s,c,l,u,d,t,n,o,i,En(o.elements)<0)}return}let f=i?this._matrixPool.mat4.copy(e.matrixWorld):null,p=i?this._matrixPool.mat3.getNormalMatrix(e.matrixWorld):null,m=i&&En(f.elements)<0;this.extractTrianglesInBatch(s,c,l,u,d,t,n,f,p,m)}extractTrianglesInBatch(e,t,n,r,i,a,o,s=null,c=null,l=!1){for(;this.materialTriangleCounts.length<=a;)this.materialTriangleCounts.push(0);this.materialTriangleCounts[a]+=i;let u=this._getVec3(0),d=this._getVec3(1),f=this._getVec3(2),p=this._getVec3(3),m=this._getVec3(4),h=this._getVec3(5),g=this._getVec2(0),_=this._getVec2(1),v=this._getVec2(2);this._ensureCapacity(this.currentTriangleIndex+i);let y=s?.elements,b=c?.elements;for(let c=0;c<i;c++){let i=c*3,x=r?r[i+0]:i+0,S=l?2:1,C=l?1:2,w=r?r[i+S]:i+S,T=r?r[i+C]:i+C;this.getVertex(e,x,u),this.getVertex(e,w,d),this.getVertex(e,T,f),this.getVertex(t,x,p),this.getVertex(t,w,m),this.getVertex(t,T,h),n?(this.getVertex(n,x,g),this.getVertex(n,w,_),this.getVertex(n,T,v)):(g.set(0,0),_.set(0,0),v.set(0,0)),s&&(Sn(u,y),Sn(d,y),Sn(f,y),Cn(p,b),Cn(m,b),Cn(h,b)),p.normalize(),m.normalize(),h.normalize(),this.packTriangleDataTextureFormat(this.currentTriangleIndex,u,d,f,p,m,h,g,_,v,a,o),this.currentTriangleIndex++}}packTriangleDataTextureFormat(e,t,n,r,i,a,o,s,c,l,u,d){let f=K,p=this.triangles.baseOf(e),m=this.triangleFloatChunks.chunkFor(e),h=this.triangles.chunkFor(e);m[p+f.POSITION_A_OFFSET+0]=t.x,m[p+f.POSITION_A_OFFSET+1]=t.y,m[p+f.POSITION_A_OFFSET+2]=t.z,h[p+f.NORMAL_A_PACKED_OFFSET]=mt(i.x,i.y,i.z),m[p+f.POSITION_B_OFFSET+0]=n.x,m[p+f.POSITION_B_OFFSET+1]=n.y,m[p+f.POSITION_B_OFFSET+2]=n.z,h[p+f.NORMAL_B_PACKED_OFFSET]=mt(a.x,a.y,a.z),m[p+f.POSITION_C_OFFSET+0]=r.x,m[p+f.POSITION_C_OFFSET+1]=r.y,m[p+f.POSITION_C_OFFSET+2]=r.z,h[p+f.NORMAL_C_PACKED_OFFSET]=mt(o.x,o.y,o.z),m[p+f.UV_AB_OFFSET+0]=s.x,m[p+f.UV_AB_OFFSET+1]=s.y,m[p+f.UV_AB_OFFSET+2]=c.x,m[p+f.UV_AB_OFFSET+3]=c.y,m[p+f.UV_C_OFFSET+0]=l.x,m[p+f.UV_C_OFFSET+1]=l.y,h[p+f.MATERIAL_FLAGS_OFFSET]=pt(u,this.materials[u]),h[p+f.MESH_INDEX_OFFSET]=d}releaseTriangles(){this.triangles=null,this.triangleData=null,this.triangleFloatChunks=null,this.triangleFloats=null}getTriangleData(){return this.triangles?this._streamedStore?this.triangles:this.triangles.trimTo(this.currentTriangleIndex):null}getTriangleCount(){return this.currentTriangleIndex}getVertex(e,t,n){return e.itemSize===2?(n.x=e.getX(t),n.y=e.getY(t)):e.itemSize>=3&&(n.x=e.getX(t),n.y=e.getY(t),n.z=e.getZ(t)),n}logStats(){let e=this.currentTriangleIndex*K.FLOATS_PER_TRIANGLE*4;pn.debug(H.list([`${H.count(this.currentTriangleIndex,`tri`)} (${H.mb(e)})`,H.count(this.materials.length,`material`),H.count(this.maps.length,`map`)]))}extractMaterialsOnly(e){return this.resetArrays(),this._traverseMaterialsOnly(e),this.getExtractedData()}_traverseMaterialsOnly(e){if(e.isMesh&&e.geometry&&e.material){let t=this.processMaterial(e.material);e.userData.materialIndex=t;let n=this.meshes.length;this.meshes.push(e),e.userData.meshIndex=n}else e.isDirectionalLight?this.directionalLights.push(e):e.isCamera&&this.cameras.push(e);if(e.children)for(let t of e.children)this._traverseMaterialsOnly(t)}resetArrays(){this._droppedTextures=0,this.triangles=null,this._streamedStore=!1,this.triangleData=null,this.triangleFloatChunks=null,this.triangleFloats=null,this.triangleCount=0,this.currentTriangleIndex=0,this.materials=[],this.materialTriangleCounts=[],this.meshes=[],this.meshTriangleRanges=[],this._geometryRanges=new Map,this.expandedTriangleCount=0,this._allocatePlacements(0),this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.roughnessMaps=[],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._materialUuidMap=new Map,this._textureIndexCache=new WeakMap}getExtractedData(){return{triangleData:this.getTriangleData(),triangleCount:this.getTriangleCount(),materials:this.materials,materialTriangleCounts:this.materialTriangleCounts,meshes:this.meshes,meshTriangleRanges:this.meshTriangleRanges,expandedTriangleCount:this.expandedTriangleCount,instanceSource:this.instanceSource.subarray(0,this.instanceCount),instanceMatrices:this.instanceMatrices.subarray(0,this.instanceCount*16),instanceCount:this.instanceCount,bakeInverse:this.bakeInverse,maps:this.maps,normalMaps:this.normalMaps,bumpMaps:this.bumpMaps,metalnessMaps:this.metalnessMaps,emissiveMaps:this.emissiveMaps,roughnessMaps:this.roughnessMaps,displacementMaps:this.displacementMaps,anisotropyMaps:this.anisotropyMaps,transmissionMaps:this.transmissionMaps,clearcoatMaps:this.clearcoatMaps,clearcoatRoughnessMaps:this.clearcoatRoughnessMaps,sheenColorMaps:this.sheenColorMaps,sheenRoughnessMaps:this.sheenRoughnessMaps,iridescenceMaps:this.iridescenceMaps,iridescenceThicknessMaps:this.iridescenceThicknessMaps,specularIntensityMaps:this.specularIntensityMaps,specularColorMaps:this.specularColorMaps,diffuseTransmissionMaps:this.diffuseTransmissionMaps,diffuseTransmissionColorMaps:this.diffuseTransmissionColorMaps,directionalLights:this.directionalLights,cameras:this.cameras}}};function On(e,t=null){Nn=e,Pn=e?t:null}function kn(){return Nn}function An(){return Pn}function jn(e){if(!Nn)return!1;let t=e[0],n=e[1],r=e[2];return e[0]=Nn[0]*t+Nn[1]*n+Nn[2]*r,e[1]=Nn[3]*t+Nn[4]*n+Nn[5]*r,e[2]=Nn[6]*t+Nn[7]*n+Nn[8]*r,!0}function Mn(e,t,n){if(!Nn||n.length===0)return 0;let r=0;for(let i=0;i+t<=e.length;i+=t)for(let t of n){let n=i+t,a=e[n],o=e[n+1],s=e[n+2];e[n]=Nn[0]*a+Nn[1]*o+Nn[2]*s,e[n+1]=Nn[3]*a+Nn[4]*o+Nn[5]*s,e[n+2]=Nn[6]*a+Nn[7]*o+Nn[8]*s,r++}return r}var Nn,Pn,Fn=g((()=>{Nn=null,Pn=null}));Fn();function In(e){if(e===null||typeof e==`boolean`||typeof e==`string`)return e;if(typeof e==`number`)return Number.isFinite(e)?e:{$num:String(e)};if(typeof e!=`object`)return;if(e.isColor)return{$color:[e.r,e.g,e.b]};if(e.isQuaternion)return{$quat:[e.x,e.y,e.z,e.w]};if(e.isVector2||e.isVector3||e.isVector4)return{$vec:e.toArray()};if(ArrayBuffer.isView(e))return Array.from(e);if(Array.isArray(e))return e.map(e=>In(e)??null);let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return;let n={};for(let[t,r]of Object.entries(e)){let e=In(r);e!==void 0&&(n[t]=e)}return n}function Ln(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(Ln);if(`$num`in e)return Number(e.$num);if(e.$color)return new r.Color(...e.$color);if(e.$quat)return new r.Quaternion(...e.$quat);if(e.$vec){let t=[null,null,r.Vector2,r.Vector3,r.Vector4][e.$vec.length];return new t(...e.$vec)}let t={};for(let[n,r]of Object.entries(e))t[n]=Ln(r);return t}var Rn=`rayzeeScene`,zn=(e,t)=>(0,n.context)(e,{[Rn]:t});function Bn(e){let t=e.context[Rn];if(!t)throw Error(`this kernel samples scene resources: build its root with withSceneResources()`);return t}var Vn=Object.freeze([`clearcoat`,`sheen`,`iridescence`,`anisotropy`,`subsurface`,`dispersion`,`diffuseTransmission`]),Hn=Object.freeze(Object.fromEntries(Vn.map(e=>[e,!0])));function Un(e){return e.context[Rn]?.materialLayers??Hn}wt(),Ae();var Wn=new WeakSet,Gn=ye(`material`),Kn=q.SLOTS_PER_MATERIAL,qn=K.MATERIAL_FLAGS_OFFSET,Jn=new Set([`transmission`,`transparent`,`opacity`,`alphaMode`]),Yn=new Set([`side`,...Jn,`emissive`,`emissiveIntensity`]),Xn=[[`map`,!0],[`emissiveMap`,!0],[`sheenColorMap`,!0],[`specularColorMap`,!0],[`normalMap`,!1],[`bumpMap`,!1],[`roughnessMap`,!1],[`metalnessMap`,!1],[`displacementMap`,!1],[`anisotropyMap`,!1],[`transmissionMap`,!1],[`clearcoatMap`,!1],[`clearcoatRoughnessMap`,!1],[`sheenRoughnessMap`,!1],[`iridescenceMap`,!1],[`iridescenceThicknessMap`,!1],[`specularIntensityMap`,!1],[`diffuseTransmissionColorMap`,!0],[`diffuseTransmissionMap`,!1]],Zn={ior:q.IOR,transmission:q.TRANSMISSION,thickness:q.THICKNESS,emissiveIntensity:q.EMISSIVE_INTENSITY,attenuationDistance:q.ATTENUATION_DISTANCE,opacity:q.OPACITY,alphaTest:q.ALPHA_TEST,metalness:q.METALNESS,roughness:q.ROUGHNESS,clearcoat:q.CLEARCOAT,clearcoatRoughness:q.CLEARCOAT_ROUGHNESS,dispersion:q.DISPERSION,sheen:q.SHEEN,sheenRoughness:q.SHEEN_ROUGHNESS,specularIntensity:q.SPECULAR_INTENSITY,iridescence:q.IRIDESCENCE,iridescenceIOR:q.IRIDESCENCE_IOR,subsurface:q.SUBSURFACE,subsurfaceRadiusScale:q.SUBSURFACE_RADIUS_SCALE,subsurfaceAnisotropy:q.SUBSURFACE_ANISOTROPY,anisotropy:q.ANISOTROPY,anisotropyRotation:q.ANISOTROPY_ROTATION,diffuseTransmission:q.DIFFUSE_TRANSMISSION},Qn=class e{constructor(e){this.sdfs=e,this.materialStorageAttr=null,this.materialStorageNode=null,this.materialCount=0,this.srgbBuckets=null,this.linearBuckets=null,this._srgbTexPacked=null,this._linearTexPacked=null,this.callbacks={},this._sources=[],this._hostSet=[]}static COLOR_OFFSETS=[q.COLOR,q.EMISSIVE,q.ATTENUATION_COLOR,q.SHEEN_COLOR,q.SPECULAR_COLOR,q.SUBSURFACE_COLOR,q.DIFFUSE_TRANSMISSION_COLOR].filter(e=>Number.isInteger(e));_convertColorsToWorkingSpace(t){if(Wn.has(t))return;Wn.add(t);let n=Mn(t,q.FLOATS_PER_MATERIAL,e.COLOR_OFFSETS);n&&Gn.debug(`converted ${n} material colour(s) into ${An()}`)}_writeColor(e,t,n,r,i){let a=[n,r,i];jn(a)&&([n,r,i]=a),e[t]=n,e[t+1]=r,e[t+2]=i}setMaterialData(e,r=[]){if(!e)return;this._convertColorsToWorkingSpace(e);let i=e.length/4;this.materialStorageNode?(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode.value=this.materialStorageAttr,this.materialStorageNode.bufferCount=i):(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode=(0,n.storage)(this.materialStorageAttr,`vec4`,i).toReadOnly()),this.materialCount=Math.floor(i/Kn),this._sources=[...r],this._hostSet=[],this.callbacks.onMaterialFeaturesChanged?.(),Gn.debug(`${H.n(this.materialCount)} materials (storage buffer)`)}getStorageAttr(){return this.materialStorageAttr}getStorageNode(){return this.materialStorageNode}setMaterialTextures(e){e.srgbBuckets&&(this.srgbBuckets=e.srgbBuckets),e.linearBuckets&&(this.linearBuckets=e.linearBuckets)}setTexturePackMaps(e,t){this._srgbTexPacked=e||null,this._linearTexPacked=t||null}getPackedTextureIndex(e,t){if(!e)return-1;let n=e.source?.uuid??e.uuid,r=(t?this._srgbTexPacked:this._linearTexPacked)?.get(n);return r===void 0?-1:r}loadTexturesFromSdfs(){this.srgbBuckets=this.sdfs.srgbBucketTextures,this.linearBuckets=this.sdfs.linearBucketTextures,this.setTexturePackMaps(this.sdfs._srgbTexPacked,this.sdfs._linearTexPacked)}getTextureArrays(){return{srgbBuckets:this.srgbBuckets,linearBuckets:this.linearBuckets}}getMaterialProperty(e,t){let n=this.materialStorageAttr?.array;if(!n)return;let r=Zn[t];if(r===void 0)return;let i=e*q.FLOATS_PER_MATERIAL+r;return i<n.length?n[i]:void 0}materialLayers(){let e=Object.fromEntries(Vn.map(e=>[e,!1])),t=this.materialStorageAttr?.array;if(!t)return e;for(let n=0;n<this.materialCount;n++){let r=n*q.FLOATS_PER_MATERIAL;for(let n of Vn)t[r+Zn[n]]>0&&(e[n]=!0)}return e}getMaterialPropertySource(e,t){return this._hostSet[e]?.has(t)?gn.HOST:this._sources[e]?.[t]}serializeHostEdits(){let e=[];return this._hostSet.forEach((t,n)=>{t?.size&&e.push({index:n,props:Object.fromEntries(t)})}),e}updateMaterialProperty(e,t,n){if(!this.materialStorageAttr){Gn.warn(`material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=e*q.FLOATS_PER_MATERIAL;switch(Dt.has(t)&&typeof n==`number`&&(n=Ot(n)),t){case`color`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.COLOR,n.r,n.g,n.b);break;case`metalness`:r[i+q.METALNESS]=n;break;case`emissive`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.EMISSIVE,n[0],n[1],n[2]):this._writeColor(r,i+q.EMISSIVE,n.r,n.g,n.b);break;case`roughness`:r[i+q.ROUGHNESS]=n;break;case`ior`:r[i+q.IOR]=n;break;case`transmission`:r[i+q.TRANSMISSION]=n;break;case`thickness`:r[i+q.THICKNESS]=n;break;case`emissiveIntensity`:r[i+q.EMISSIVE_INTENSITY]=n;break;case`attenuationColor`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.ATTENUATION_COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.ATTENUATION_COLOR,n.r,n.g,n.b);break;case`attenuationDistance`:r[i+q.ATTENUATION_DISTANCE]=vt(n);break;case`dispersion`:r[i+q.DISPERSION]=n;break;case`sheen`:r[i+q.SHEEN]=n;break;case`sheenRoughness`:r[i+q.SHEEN_ROUGHNESS]=n;break;case`sheenColor`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.SHEEN_COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.SHEEN_COLOR,n.r,n.g,n.b);break;case`specularIntensity`:r[i+q.SPECULAR_INTENSITY]=n;break;case`specularColor`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.SPECULAR_COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.SPECULAR_COLOR,n.r,n.g,n.b);break;case`iridescence`:r[i+q.IRIDESCENCE]=n;break;case`iridescenceIOR`:r[i+q.IRIDESCENCE_IOR]=n;break;case`iridescenceThicknessRange`:Array.isArray(n)&&(r[i+q.IRIDESCENCE_THICKNESS_RANGE]=n[0],r[i+q.IRIDESCENCE_THICKNESS_RANGE+1]=n[1]);break;case`clearcoat`:r[i+q.CLEARCOAT]=n;break;case`clearcoatRoughness`:r[i+q.CLEARCOAT_ROUGHNESS]=n;break;case`opacity`:r[i+q.OPACITY]=n;break;case`side`:r[i+q.SIDE]=n,this._patchTriangleSideForMaterial(e,n);break;case`transparent`:r[i+q.TRANSPARENT]=n;break;case`alphaTest`:r[i+q.ALPHA_TEST]=n;break;case`alphaMode`:r[i+q.ALPHA_MODE]=n;break;case`depthWrite`:r[i+q.DEPTH_WRITE]=n;break;case`normalScale`:n.x===void 0?typeof n==`number`&&(r[i+q.NORMAL_SCALE]=n,r[i+q.NORMAL_SCALE+1]=n):(r[i+q.NORMAL_SCALE]=n.x,r[i+q.NORMAL_SCALE+1]=n.y);break;case`bumpScale`:r[i+q.BUMP_SCALE]=n;break;case`displacementScale`:r[i+q.DISPLACEMENT_SCALE]=n;break;case`subsurface`:r[i+q.SUBSURFACE]=n;break;case`subsurfaceRadiusScale`:r[i+q.SUBSURFACE_RADIUS_SCALE]=n;break;case`subsurfaceAnisotropy`:r[i+q.SUBSURFACE_ANISOTROPY]=n;break;case`anisotropy`:r[i+q.ANISOTROPY]=n;break;case`anisotropyRotation`:r[i+q.ANISOTROPY_ROTATION]=n;break;case`diffuseTransmission`:r[i+q.DIFFUSE_TRANSMISSION]=n;break;case`diffuseTransmissionColor`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.DIFFUSE_TRANSMISSION_COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.DIFFUSE_TRANSMISSION_COLOR,n.r,n.g,n.b);break;case`subsurfaceColor`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.SUBSURFACE_COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.SUBSURFACE_COLOR,n.r,n.g,n.b);break;case`subsurfaceRadius`:Array.isArray(n)?(r[i+q.SUBSURFACE_RADIUS]=n[0],r[i+q.SUBSURFACE_RADIUS+1]=n[1],r[i+q.SUBSURFACE_RADIUS+2]=n[2]):n.x!==void 0&&(r[i+q.SUBSURFACE_RADIUS]=n.x,r[i+q.SUBSURFACE_RADIUS+1]=n.y,r[i+q.SUBSURFACE_RADIUS+2]=n.z);break;default:Gn.warn(`unknown material property: ${t}`);return}this.materialStorageAttr.needsUpdate=!0,(this._hostSet[e]??=new Map).set(t,In(n)),Jn.has(t)&&this._recomputeOpaqueBlockerForMaterial(e),Vn.includes(t)&&this.callbacks.onMaterialFeaturesChanged?.(),this._notifyReset()}updateMaterialDataFromObject(t,n){if(!this.materialStorageAttr){Gn.warn(`material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=t*q.FLOATS_PER_MATERIAL;Mt(r,i,n);for(let t of e.COLOR_OFFSETS)this._writeColor(r,i+t,r[i+t],r[i+t+1],r[i+t+2]);this._sources[t]=n.sources,this._hostSet[t]=void 0,this._patchTriangleSideForMaterial(t,r[i+q.SIDE]),this._recomputeOpaqueBlockerForMaterial(t),this.callbacks.onMaterialFeaturesChanged?.(),this.materialStorageAttr.needsUpdate=!0,this._notifyReset()}updateMaterial(e,t){let n=this.sdfs.geometryExtractor.createMaterialObject(t);if(this._srgbTexPacked||this._linearTexPacked){let e=yn(t);for(let[t,r]of Xn)n[t]=this.getPackedTextureIndex(e[t],r)}this.updateMaterialDataFromObject(e,n)}updateTextureTransform(e,t,n){if(!this.materialStorageAttr){Gn.warn(`material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=e*q.FLOATS_PER_MATERIAL,a={map:q.ALBEDO_TRANSFORM,normalMap:q.NORMAL_TRANSFORM,roughnessMap:q.ROUGHNESS_TRANSFORM,metalnessMap:q.METALNESS_TRANSFORM,emissiveMap:q.EMISSIVE_TRANSFORM,bumpMap:q.BUMP_TRANSFORM,displacementMap:q.DISPLACEMENT_TRANSFORM}[t];if(a===void 0){Gn.warn(`unknown texture name for transform update: ${t}`);return}for(let e=0;e<8;e++)i+a+e<r.length&&(r[i+a+e]=n[e]);this.materialStorageAttr.needsUpdate=!0,this._notifyReset()}_notifyReset(){this.callbacks.onReset&&this.callbacks.onReset()}_recomputeOpaqueBlockerForMaterial(e){let t=this.materialStorageAttr?.array;if(!t)return;let n=e*q.FLOATS_PER_MATERIAL,r=ft({alphaMode:t[n+q.ALPHA_MODE],transparent:t[n+q.TRANSPARENT],transmission:t[n+q.TRANSMISSION],opacity:t[n+q.OPACITY]});this._patchTriangleFlagForMaterial(e,26,2,r)}_patchTriangleFlagForMaterial(e,t,n,r){let i=this.callbacks.getTriangleData?.(),a=i?.records,o=a?null:i?.array,s=i?.count|0;if(!o&&!a||s===0)return;let c=K.FLOATS_PER_TRIANGLE,l=(1<<n)-1<<t>>>0,u=(r<<t&l)>>>0,d=0;for(let t=0;t<s;t++){let n=a?a.chunkFor(t):o,r=a?a.baseOf(t):t*c;(n[r+qn]&16777215)===e&&(n[r+qn]=(n[r+qn]&~l|u)>>>0,d++)}d>0&&this.callbacks.onTriangleDataChanged&&this.callbacks.onTriangleDataChanged()}_patchTriangleSideForMaterial(e,t){this._patchTriangleFlagForMaterial(e,24,2,t)}dispose(){this.materialStorageAttr=null,this.materialStorageNode=null,this.materialCount=0,this.srgbBuckets=null,this.linearBuckets=null,this._srgbTexPacked=null,this._linearTexPacked=null,this._sources=[],this._hostSet=[]}},$n=`function e(e,t){let n=Math.max(1,Math.ceil(e/1024));return{k:n,width:Math.ceil(e/n),height:Math.ceil(t/n)}}function t(e,t,n,r,i,a){let o=0;for(let s=0;s<a;s++){for(;o<n-1&&e[t+o]<=s/a;)o++;r[i+s]=o}}function n(n,r,i,{filtered:a=!0}={}){let{k:o,width:s,height:c}=e(r,i),l=new Float32Array(r*i),u=0;for(let e=0;e<i;e++){let t=Math.sin(Math.PI*(e+.5)/i);for(let i=0;i<r;i++){let a=4*(e*r+i),o=.2126*n[a]+.7152*n[a+1]+.0722*n[a+2];l[e*r+i]=Number.isFinite(o)&&o>0?o:0,u+=l[e*r+i]*t}}let d=[1/8,6/8,1/8],f=e=>{for(let t=0;t<i;t++){let n=Math.sin(Math.PI*(t+.5)/i),c=Math.floor(t/o)*s,u=[Math.max(t-1,0),t,Math.min(t+1,i-1)];for(let i=0;i<r;i++){let s=l[t*r+i];if(a){let e=[(i+r-1)%r,i,(i+1)%r];s=0;for(let t=0;t<3;t++)for(let n=0;n<3;n++)s+=d[t]*d[n]*l[u[t]*r+e[n]]}e(c+Math.floor(i/o),s*n)}}},p=0;f((e,t)=>void(p+=t));let m=p/(r*i),h=new Float64Array(s*c),g=0;f((e,t)=>{h[e]+=Math.max(t-m,0),g+=Math.max(t-m,0)}),g>0||(h.fill(0),f((e,t)=>void(h[e]+=t)));let _=p>0?1e-4*p/(s*c):0,v=new Float32Array(s*c),y=new Float32Array(c),b=new Float64Array(c),x=0;for(let e=0;e<c;e++){let t=0;for(let n=0;n<s;n++)t+=h[e*s+n]+_;let n=0;for(let r=0;r<s;r++)n+=h[e*s+r]+_,v[e*s+r]=t>0?r===s-1?1:n/t:0;b[e]=t,x+=t}let S=0;for(let e=0;e<c;e++)S+=b[e],y[e]=x>0?e===c-1?1:S/x:0;let C=new Float32Array(2*s*c),w=new Float32Array(2*c);for(let e=0;e<c;e++)t(v,e*s,s,C,2*e*s,2*s);return t(y,0,c,w,0,2*c),{exactWidth:s,exactHeight:c,exactConditional:v,exactMarginal:y,exactRowGuide:C,exactMarginalGuide:w,radianceIntegral:2*Math.PI*Math.PI*u/(r*i)}}self.onmessage=function(e){let{floatData:t,width:r,height:i}=e.data;try{let e=n(t,r,i);self.postMessage({width:r,height:i,...e},[e.exactConditional.buffer,e.exactMarginal.buffer,e.exactRowGuide.buffer,e.exactMarginalGuide.buffer])}catch(e){self.postMessage({error:e.message})}};`,er=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,$n],{type:`text/javascript;charset=utf-8`});function tr(e){let t;try{if(t=er&&(self.URL||self.webkitURL).createObjectURL(er),!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($n),{type:`module`,name:e?.name})}}function nr(e){e&&Object.assign(lr,e)}function rr(){return lr}function ir(){return typeof navigator<`u`&&navigator.hardwareConcurrency||4}function ar(){return!!lr.decodeImage||typeof self<`u`&&(typeof createImageBitmap<`u`||typeof document<`u`)}function or(){return!!lr.Worker||typeof Worker<`u`}async function sr(e){if(!lr.Worker||ur===0&&globalThis.Worker!==void 0)return e();ur++===0&&(globalThis.Worker=lr.Worker);try{return await e()}finally{--ur===0&&globalThis.Worker===lr.Worker&&delete globalThis.Worker}}function cr(e,t){let n=lr.Worker;if(!n)return new e(t);let r=Object.prototype.hasOwnProperty.call(globalThis,`Worker`),i=globalThis.Worker;globalThis.Worker=n;try{return new e(t)}finally{r?globalThis.Worker=i:delete globalThis.Worker}}var lr,ur,dr=g((()=>{lr={Worker:null,decodeImage:null},ur=0}));dr();var fr=1024,pr=1e-4;function mr(e,t){let n=Math.max(1,Math.ceil(e/fr));return{k:n,width:Math.ceil(e/n),height:Math.ceil(t/n)}}function hr(e,t,n,r,i,a){let o=0;for(let s=0;s<a;s++){for(;o<n-1&&e[t+o]<=s/a;)o++;r[i+s]=o}}function gr(e,t,n,{filtered:r=!0}={}){let{k:i,width:a,height:o}=mr(t,n),s=new Float32Array(t*n),c=0;for(let r=0;r<n;r++){let i=Math.sin(Math.PI*(r+.5)/n);for(let n=0;n<t;n++){let a=4*(r*t+n),o=.2126*e[a]+.7152*e[a+1]+.0722*e[a+2];s[r*t+n]=Number.isFinite(o)&&o>0?o:0,c+=s[r*t+n]*i}}let l=[1/8,6/8,1/8],u=e=>{for(let o=0;o<n;o++){let c=Math.sin(Math.PI*(o+.5)/n),u=Math.floor(o/i)*a,d=[Math.max(o-1,0),o,Math.min(o+1,n-1)];for(let n=0;n<t;n++){let a=s[o*t+n];if(r){let e=[(n+t-1)%t,n,(n+1)%t];a=0;for(let n=0;n<3;n++)for(let r=0;r<3;r++)a+=l[n]*l[r]*s[d[n]*t+e[r]]}e(u+Math.floor(n/i),a*c)}}},d=0;u((e,t)=>void(d+=t));let f=d/(t*n),p=new Float64Array(a*o),m=0;u((e,t)=>{p[e]+=Math.max(t-f,0),m+=Math.max(t-f,0)}),m>0||(p.fill(0),u((e,t)=>void(p[e]+=t)));let h=d>0?pr*d/(a*o):0,g=new Float32Array(a*o),_=new Float32Array(o),v=new Float64Array(o),y=0;for(let e=0;e<o;e++){let t=0;for(let n=0;n<a;n++)t+=p[e*a+n]+h;let n=0;for(let r=0;r<a;r++)n+=p[e*a+r]+h,g[e*a+r]=t>0?r===a-1?1:n/t:0;v[e]=t,y+=t}let b=0;for(let e=0;e<o;e++)b+=v[e],_[e]=y>0?e===o-1?1:b/y:0;let x=new Float32Array(2*a*o),S=new Float32Array(2*o);for(let e=0;e<o;e++)hr(g,e*a,a,x,2*e*a,2*a);return hr(_,0,o,S,0,2*o),{exactWidth:a,exactHeight:o,exactConditional:g,exactMarginal:_,exactRowGuide:x,exactMarginalGuide:S,radianceIntegral:2*Math.PI*Math.PI*c/(t*n)}}function _r({exactWidth:e,exactHeight:t,exactConditional:n,exactMarginal:r,exactRowGuide:i,exactMarginalGuide:a}){let o=e+1,s=new Float32Array(4*o*t);for(let c=0;c<t;c++){let t=4*c*o;for(let r=0,a=c*e;r<e;r++,a++,t+=4)s[t]=n[a],s[t+1]=r>0?n[a-1]:0,s[t+2]=i[2*a],s[t+3]=i[2*a+1];s[t]=r[c],s[t+1]=c>0?r[c-1]:0,s[t+2]=a[2*c],s[t+3]=a[2*c+1]}return{data:s,width:o,height:t}}function vr(e){return e<=.04045?e/12.92:((e+.055)/1.055)**2.4}function yr(e){let{width:t,height:n}=e.image,i=e.image.data,a=!1;if(!i){let r=new OffscreenCanvas(t,n).getContext(`2d`);r.drawImage(e.image,0,0,t,n),i=r.getImageData(0,0,t,n).data,a=!0}let o;if(e.type===r.FloatType&&i instanceof Float32Array)o=new Float32Array(i);else if(e.type===r.HalfFloatType){o=new Float32Array(i.length);for(let e=0,t=i.length;e<t;e++)o[e]=r.DataUtils.fromHalfFloat(i[e])}else{let e;e=i instanceof Int8Array||i instanceof Int16Array||i instanceof Int32Array?2**(8*i.BYTES_PER_ELEMENT-1)-1:2**(8*i.BYTES_PER_ELEMENT)-1,o=new Float32Array(i.length);for(let t=0,n=i.length;t<n;t++)o[t]=i[t]/e}if(!a&&e.colorSpace===r.SRGBColorSpace&&(a=!0),a)for(let e=0,t=o.length;e<t;e+=4)o[e]=vr(o[e]),o[e+1]=vr(o[e+1]),o[e+2]=vr(o[e+2]);if(e.flipY){let e=new Float32Array(o.length);for(let r=0;r<n;r++){let i=n-r-1,a=r*t*4,s=i*t*4;e.set(o.subarray(a,a+t*4),s)}o=e}return{floatData:o,width:t,height:n}}var br=class{constructor(){this.totalSum=0,this.width=0,this.height=0,this.exactConditional=null,this.exactMarginal=null,this.exactRowGuide=null,this.exactMarginalGuide=null,this.exactWidth=0,this.exactHeight=0,this.radianceIntegral=0,this._worker=null}dispose(){this.exactConditional=null,this.exactMarginal=null,this.exactRowGuide=null,this.exactMarginalGuide=null,this._worker&&=(this._worker.terminate(),null)}_adopt(e,t,n){Object.assign(this,e),this.width=t,this.height=n,this.totalSum=e.radianceIntegral}updateFrom(e){let{floatData:t,width:n,height:r}=yr(e);this._adopt(gr(t,n,r),n,r)}async updateFromAsync(e){let{floatData:t,width:n,height:r}=yr(e);this._worker=cr(tr);try{let{width:e,height:i,...a}=await new Promise((e,i)=>{this._worker.onmessage=t=>{t.data.error?i(Error(t.data.error)):e(t.data)},this._worker.onerror=i,this._worker.postMessage({floatData:t,width:n,height:r},[t.buffer])});this._adopt(a,e,i)}finally{this._worker&&=(this._worker.terminate(),null)}}},xr=class{constructor(e=512,t=256){this.width=e,this.height=t,this.lastRenderTime=0,this._pixels=new Float32Array(e*t*4),this._texture=new r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1}renderSolid(e){let t=performance.now(),{width:n,height:r}=this,i=this._pixels,a=e.color.r,o=e.color.g,s=e.color.b;for(let e=0;e<r;e++)for(let t=0;t<n;t++){let r=(e*n+t)*4;i[r]=a,i[r+1]=o,i[r+2]=s,i[r+3]=1}return this._texture.needsUpdate=!0,delete this._texture.userData?.__rayzeeColorSpace,this.lastRenderTime=performance.now()-t,this._texture}setResolution(e,t){this.width===e&&this.height===t||(this.width=e,this.height=t,this._pixels=new Float32Array(e*t*4),this._texture.dispose(),this._texture=new r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1)}getLastRenderTime(){return this.lastRenderTime}dispose(){this._texture.dispose()}},Sr=Math.PI/180;function Cr(e){let t=2*Math.PI*(e-1)/365;return .006918-.399912*Math.cos(t)+.070257*Math.sin(t)-.006758*Math.cos(2*t)+907e-6*Math.sin(2*t)-.002697*Math.cos(3*t)+.00148*Math.sin(3*t)}function wr({hours:e,dayOfYear:t,latitude:n}){let r=Cr(t),i=(e-12)*15*Sr,a=n*Sr,o=Math.sin(a)*Math.sin(r)+Math.cos(a)*Math.cos(r)*Math.cos(i),s=Math.asin(Math.min(1,Math.max(-1,o)))/Sr;return{azimuth:(Math.atan2(Math.sin(i),Math.cos(i)*Math.sin(a)-Math.tan(r)*Math.cos(a))/Sr+540)%360,elevation:s}}function Tr({elevation:e,dayOfYear:t,latitude:n,afternoon:r=!1}){let i=Cr(t),a=n*Sr,o=(Math.sin(e*Sr)-Math.sin(a)*Math.sin(i))/(Math.cos(a)*Math.cos(i)),s=Math.acos(Math.min(1,Math.max(-1,o)))/Sr/15;return r?12+s:12-s}var Er=e=>[0,31,59,90,120,151,181,212,243,273,304,334][e-1]+21,Dr=`Linear Rec.709 (sRGB)`,Or=null;function kr(){return Or}function Ar(e){Or=e,e?._publishWorkingMatrix?.()}function jr(e){Or===null&&(Or=e)}function Mr(e){return Nr.get(e)?.storage??null}var Nr,Pr=g((()=>{Nr=new Map}));function Fr(e){if(e){Object.assign(Rr,e);for(let t of Object.keys(e))zr.add(t)}}function Ir(e){return zr.has(e)}function Lr(){return{...Rr}}var Rr,zr,Br=g((()=>{Rr={ortRuntimeUrl:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/ort.webgpu.bundle.min.mjs`,ortWasmPaths:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/`,dracoDecoderPath:`https://www.gstatic.com/draco/v1/decoders/`,ktx2TranscoderPath:`https://cdn.jsdelivr.net/npm/three@0.183.2/examples/jsm/libs/basis/`,oidnWeightsBaseUrl:`https://assets.rayzee.atulmourya.com/oidn/denoiser-0.0.11/`,ocioRuntimeFactory:null,ocioRuntimeUrl:null,ocioWasmUrl:null,upscalerModelBaseUrl:`https://huggingface.co/notaneimu/onnx-image-models/resolve/main/`,neuralRuntimeUrl:`/neural/neural-runtime.js`,neuralAssetBaseUrl:null,cacheNamespace:`rayzee`,storage:`auto`},zr=new Set}));function Vr(e,t){e&&t&&(e.userData.__rayzeeSource=t)}function Hr(e){let t=e?.userData?.__rayzeeSource;if(!t)return null;let{width:n=0,height:r=0}=e.image??{};return`cdf:${Gr}:${t}|${n}x${r}|${e.userData.__rayzeeColorSpace??`native`}`}async function Ur(e){let t=Hr(e),n=t?await Kr()?.open(t):null;if(!n)return null;try{let e=await Promise.all(Jr.map(e=>n.file(e)));if(e.some(e=>!e))return null;let t=await Promise.all(e.map(async e=>new Float32Array(await e.arrayBuffer()))),{totalSum:r,width:i,height:a,exactWidth:o,exactHeight:s,radianceIntegral:c}=n.extra;return{...Object.fromEntries(qr.map((e,n)=>[e,t[n]])),totalSum:r,width:i,height:a,exactWidth:o,exactHeight:s,radianceIntegral:c}}finally{n.release()}}async function Wr(e,t){let{totalSum:n,width:r,height:i,exactWidth:a,exactHeight:o,radianceIntegral:s}=t,c=qr.map(e=>t[e]),l=Hr(e),u=l?Kr():null;if(!u||c.some(e=>!e))return!1;let d=await u.create(l,{label:e.name||`environment`,expectedBytes:c.reduce((e,t)=>e+t.byteLength,0)});if(!d)return!1;try{for(let e=0;e<Jr.length;e++)await d.write(Jr[e],c[e]);return await d.commit({totalSum:n,width:r,height:i,exactWidth:a,exactHeight:o,radianceIntegral:s}),!0}catch{return await d.abort(),!1}}var Gr,Kr,qr,Jr,Yr=g((()=>{nn(),Pr(),Br(),Gr=5,Kr=()=>Mr(Lr().cacheNamespace)?.area(tn.CDF)??null,qr=[`exactConditional`,`exactMarginal`,`exactRowGuide`,`exactMarginalGuide`],Jr=qr.map(e=>`${e}.f32`)}));Fn(),Ae(),Yr(),X();var Xr=ye(`env`),Zr=Object.freeze({time:10,month:3,latitude:40}),Qr=wr({hours:Zr.time,dayOfYear:Er(Zr.month),latitude:Zr.latitude}),$r=Object.freeze({solidSkyColor:`#87CEEB`,skySunAzimuth:180-Qr.azimuth,skySunElevation:Qr.elevation,skySunStrength:1,skySunSize:.53,skyTurbidity:2,skyOzone:300,skyAirDensity:1,skyGroundAlbedo:`#959595`,skyAltitude:50}),ei=1024,ti=512,ni=Math.PI/180,ri=new r.Matrix4,ii=4,ai=class{constructor(e,t,n=null){this.scene=e,this.uniforms=t,this.renderer=n,this.equirectHdrInfo=new br,this.ProceduralSky=null,this._loadProceduralSky=null,this._proceduralSkyLoading=null,this.issues=null,this.physicalSky=null,this.simpleSkyRenderer=null,this._sun=null,this._skyRequested=!1,this._skyScheduled=!1,this._skyInFlight=0,this._skyCaughtUp=null,this._resolveSky=null,this._skyBakes=0,this._skyStatsBake=0,this._envPlaceholder=new r.DataTexture(new Float32Array([0,0,0,1]),1,1,r.RGBAFormat,r.FloatType,void 0,void 0,void 0,r.LinearFilter,r.LinearFilter),this._envPlaceholder.needsUpdate=!0,this.environmentTexture=this._envPlaceholder,this.envTexSize=new r.Vector2,this.envCDFTexture=null,this._initCDFTexture(),this.environmentRotationMatrix=new r.Matrix4,this.cdfBuildTime=0,this.envParams={mode:`hdri`,solidSkyColor:new r.Color($r.solidSkyColor),skySunDirection:this._calculateInitialSunDirection(),skySunStrength:$r.skySunStrength,skySunSize:$r.skySunSize,skyTurbidity:$r.skyTurbidity,skyOzone:$r.skyOzone,skyAirDensity:$r.skyAirDensity,skyGroundAlbedo:new r.Color($r.skyGroundAlbedo),skyAltitude:$r.skyAltitude},this.callbacks={},this._previousHDRI=null}async setMode(e){let t=this.envParams.mode;this.envParams.mode=e,e!==`hdri`&&t===`hdri`&&(this._previousHDRI=this.environmentTexture),e===`color`?await this.generateSolidColorTexture():e===`procedural`?await this.generateProceduralSkyTexture():e===`hdri`&&this._previousHDRI&&(await this.setEnvironmentMap(this._previousHDRI),this._previousHDRI=null),e!==`procedural`&&t===`procedural`&&this._releaseSky(),this.markDirty(),this.callbacks.onLightingChanged?.(),this._notifyReset()}markDirty(){this.environmentTexture&&(this.environmentTexture.needsUpdate=!0)}get hdriSource(){return(this.envParams.mode===`hdri`?this.environmentTexture:this._previousHDRI)?.userData?.__rayzeeSource??null}serialize(){let e=this.envParams;return{mode:e.mode,hdri:this.hdriSource,solidSkyColor:e.solidSkyColor.toArray(),skyModel:`atmosphere`,skySunDirection:e.skySunDirection.toArray(),skySunStrength:e.skySunStrength,skySunSize:e.skySunSize,skyTurbidity:e.skyTurbidity,skyOzone:e.skyOzone,skyAirDensity:e.skyAirDensity,skyGroundAlbedo:e.skyGroundAlbedo.toArray(),skyAltitude:e.skyAltitude}}async restore(e){if(!e)return;let t=this.envParams,n=e.skyModel===`atmosphere`,r=[`solidSkyColor`,`skySunDirection`];for(let i of n?[...r,`skyGroundAlbedo`]:r)Array.isArray(e[i])&&t[i].fromArray(e[i]);if(n)for(let n of[`skySunStrength`,`skySunSize`,`skyTurbidity`,`skyOzone`,`skyAirDensity`,`skyAltitude`])typeof e[n]==`number`&&(t[n]=e[n]);[`hdri`,`color`,`procedural`].includes(e.mode)&&(e.mode!==`hdri`||t.mode!==`hdri`)&&await this.setMode(e.mode)}get params(){return this.envParams}get texture(){return this.environmentTexture}generateSolid(){return this.generateSolidColorTexture()}generateProcedural(){return this.generateProceduralSkyTexture()}_initCDFTexture(){this.envCDFTexture=new r.DataTexture(new Float32Array(4),1,1,r.RGBAFormat,r.FloatType),this.envCDFTexture.needsUpdate=!0,this._exactTable=null}_updateCDFTexture(){let e=this.equirectHdrInfo;if(!e.exactConditional||!(e.exactWidth>0))return;let{data:t,width:n,height:i}=_r(e);this.envCDFTexture?._isPhysicalSky||this.envCDFTexture?.dispose?.(),this.envCDFTexture=new r.DataTexture(t,n,i,r.RGBAFormat,r.FloatType),this.envCDFTexture.needsUpdate=!0,this._exactTable={radianceIntegral:e.radianceIntegral}}get exactTable(){return this.scene.environment?this._exactTable??null:null}setEnvironmentTexture(e){if(!e)return;let t=kr();if(t?.hasConfig)try{t.convertTexturePixels(e,{space:e.userData?.ocioColorSpace??null})}catch(e){Xr.warn(`environment colour conversion failed, left in its original space: ${e.message}`)}this.environmentTexture=e,this.envTexSize.set(e.image.width,e.image.height)}getEnvironmentTexture(){return this.environmentTexture}setEnvironmentRotation(e){let t=Math.PI/180*e;this.environmentRotationMatrix.makeRotationY(t),this.uniforms.get(`environmentMatrix`).value.copy(this.environmentRotationMatrix),this.refreshSun()}async buildEnvironmentCDF({useWorker:e=!0}={}){if(!this.scene.environment){this._cdfSignature=null,this._updateCDFTexture(),this.uniforms.set(`envTotalSum`,0);return}if(!this.scene.environment._isPhysicalSky)try{let t=performance.now(),n=this.scene.environment;if(!n.image){this._cdfSignature=null,this._updateCDFTexture(),this.uniforms.set(`envTotalSum`,0);return}let r=`${n.uuid}:${n.version}`;if(r===this._cdfSignature)return;let i=await Ur(n).catch(()=>null);i?Object.assign(this.equirectHdrInfo,i):e?await this.equirectHdrInfo.updateFromAsync(n):this.equirectHdrInfo.updateFrom(n),i||Wr(n,this.equirectHdrInfo).catch(()=>{}),this._cdfSignature=r,this.cdfBuildTime=performance.now()-t,this._updateCDFTexture(),this.uniforms.set(`envTotalSum`,this.equirectHdrInfo.totalSum);let{width:a,height:o}=this.equirectHdrInfo;a&&o&&this.uniforms.get(`envResolution`).value.set(a,o),Xr.info(H.list([H.px(this.envTexSize.x,this.envTexSize.y),`CDF ${H.ms(this.cdfBuildTime)}${i?` (stored)`:e?``:` (main thread)`}`]))}catch(e){this._cdfSignature=null,Xr.error(`CDF build failed:`,e),this.uniforms.set(`envTotalSum`,0)}}applyCDFResults(){let e=this.scene.environment,t=this.callbacks.getSceneTextureNodes?.();t&&e&&t.envTex&&(t.envTex.value=e),e&&!e._isGeneratedProcedural&&this.uniforms.set(`hasSun`,0)}async setEnvironmentMap(e,{buildCDF:t=!0}={}){let n=this.environmentTexture;e&&n&&n!==e&&n!==this._envPlaceholder&&n!==this._previousHDRI&&!n._isPhysicalSky&&n.dispose?.(),this.scene.environment=e,this.setEnvironmentTexture(e),e?t&&await this.buildEnvironmentCDF():(this._cdfSignature=null,this._updateCDFTexture(),this.uniforms.set(`envTotalSum`,0));let r=this.callbacks.getSceneTextureNodes?.();r&&e&&r.envTex&&(r.envTex.value=e),e&&!e._isGeneratedProcedural&&this.uniforms.set(`hasSun`,0),e&&n?._isPhysicalSky&&this.envParams.mode!==`procedural`&&this._releaseSky(),this._notifyReset()}beginHDRI(e=null){this._previousHDRI&&this._previousHDRI!==e&&this._previousHDRI.dispose?.(),this._previousHDRI=null,this.envParams.mode=`hdri`}async applyHDRI(e,{buildCDF:t=!0}={}){this.beginHDRI(e),await this.setEnvironmentMap(e,{buildCDF:t})}async generateSolidColorTexture(){this.simpleSkyRenderer||=new xr(512,256);let e={color:this.envParams.solidSkyColor};try{let t=this.simpleSkyRenderer.renderSolid(e);t._isGeneratedProcedural=!0,await this.setEnvironmentMap(t),this.uniforms.set(`hasSun`,0)}catch(e){Xr.error(`solid color sky generation failed:`,e)}}generateProceduralSkyTexture(){return!this.ProceduralSky&&this._loadProceduralSky?(this._proceduralSkyLoading??=this._loadProceduralSky().then(e=>{this._proceduralSkyLoading=null,this.ProceduralSky||=e}),this._proceduralSkyLoading.then(()=>this.generateProceduralSkyTexture())):this.ProceduralSky?(this._skyRequested=!0,this._skyCaughtUp??=new Promise(e=>void(this._resolveSky=e)),this._pumpSky(),this._skyCaughtUp):(this.issues?.record(Y.CAPABILITY_MISSING,`procedural mode needs the physical sky: environmentManager.setProceduralSky( PhysicalSky ), from rayzee/addons/physical-sky`,{capability:`physical-sky`}),Promise.resolve())}_pumpSky(){this._skyScheduled||!this._skyRequested||this._skyInFlight>=ii||(this._skyScheduled=!0,queueMicrotask(()=>{this._skyScheduled=!1,this._skyRequested&&this._skyInFlight<ii&&this._bakePhysicalSky()}))}_settleSky(){let e=this._resolveSky;this._skyCaughtUp=this._resolveSky=null,e?.()}async _bakePhysicalSky(){this._skyRequested=!1;let e=this.envParams;if(!this.renderer||e.mode!==`procedural`){this.renderer||Xr.warn(`physical sky needs a renderer`),this._skyInFlight===0&&this._settleSky();return}let t=this.physicalSky??=new this.ProceduralSky(ei,ti),n=e.skyGroundAlbedo,r=++this._skyBakes,i=()=>r===this._skyBakes&&!this._skyRequested;this._skyInFlight++;try{let{texture:a,cdfTexture:o,sun:s,stats:c}=t.bake(this.renderer,{sunDirection:e.skySunDirection.toArray(),turbidity:e.skyTurbidity,ozone:e.skyOzone,airDensity:e.skyAirDensity,groundAlbedo:[n.r,n.g,n.b],altitude:e.skyAltitude,sunAngularDiameter:e.skySunSize*ni,sunStrength:e.skySunStrength});this._sun=s,this._installSky(a,o);let{totalSum:l,radianceIntegral:u}=await c;e.mode===`procedural`&&t===this.physicalSky&&r>this._skyStatsBake&&(this._skyStatsBake=r,this.uniforms.set(`envTotalSum`,l),this._exactTable?.sky&&(this._exactTable.radianceIntegral=u),i()&&this._notifyReset()),i()&&Xr.debug(`physical sky ${H.ms(t.getLastRenderTime())} · sun ${s.radiance.map(e=>e.toPrecision(3)).join(`,`)}`)}catch(e){Xr.error(`physical sky generation failed:`,e)}finally{this._skyInFlight--,i()?this._settleSky():this._pumpSky()}}setProceduralSky(e){this._loadProceduralSky=null,e!==this.ProceduralSky&&(this._releaseSky(),this.ProceduralSky=e,e&&this.envParams.mode===`procedural`&&this.generateProceduralSkyTexture())}setProceduralSkyLoader(e){this._loadProceduralSky=e}_installSky(e,t){let n=this.environmentTexture;n&&n!==e&&n!==this._envPlaceholder&&n!==this._previousHDRI&&n.dispose?.(),this.envCDFTexture!==t&&(this.envCDFTexture?.dispose?.(),this.envCDFTexture=t),this._cdfSignature=null,this._exactTable?.sky||(this._exactTable={radianceIntegral:0,sky:!0}),e._isGeneratedProcedural=!0,this.scene.environment=e,this.environmentTexture=e,this.envTexSize.set(e.image.width,e.image.height),this.uniforms.get(`envResolution`).value.set(e.image.width,e.image.height);let r=this.callbacks.getSceneTextureNodes?.();r?.envTex&&(r.envTex.value=e),this.refreshSun(),this._notifyReset()}_releaseSky(){this.physicalSky&&(this.physicalSky.dispose(this.renderer),this.physicalSky=null,this._sun=null,this.refreshSun())}refreshSun(){let e=this.envParams.mode===`procedural`?this._sun:null,t=!!e&&e.radiance.some(e=>e>0);if(this.uniforms.set(`hasSun`,+!!t),!t)return;this.uniforms.get(`sunDirection`).value.fromArray(e.direction).transformDirection(ri.copy(this.environmentRotationMatrix).transpose());let n=[...e.radiance];jn(n),this.uniforms.get(`sunRadiance`).value.fromArray(n),this.uniforms.get(`sunParams`).value.set(e.cosHalfAngle,e.solidAngle,1/(e.sinHalfAngle*e.sinHalfAngle),e.horizonSin)}_calculateInitialSunDirection(){let e=$r.skySunAzimuth*(Math.PI/180),t=$r.skySunElevation*(Math.PI/180);return new r.Vector3(Math.cos(t)*Math.sin(e),Math.sin(t),Math.cos(t)*Math.cos(e)).normalize()}_notifyReset(){this.callbacks.onReset&&this.callbacks.onReset()}dispose(){this.callbacks={},this._settleSky(),this.physicalSky?.dispose(this.renderer),this.physicalSky=null,this.simpleSkyRenderer=null,this._sun=null,this.envCDFTexture?.dispose?.(),this.envCDFTexture=null,this.environmentTexture&&this.environmentTexture!==this._envPlaceholder&&this.environmentTexture.dispose?.(),this._envPlaceholder?.dispose(),this._envPlaceholder=null,this.environmentTexture=null,this._previousHDRI=null}};Ae();var oi=ye(`shader`),si=class{constructor(){this.prevColorTexNode=null,this.prevAlbedoTexNode=null,this.prevNormalDepthTexNode=null,this._sceneTextureNodes=null}updateSceneTextures(e){let t=this._sceneTextureNodes,n=e.environment;n.environmentTexture&&t.envTex&&(t.envTex.value=n.environmentTexture),e.goboMaps&&t.goboMapsTex&&(t.goboMapsTex.value=e.goboMaps),e.iesProfiles&&t.iesProfilesTex&&(t.iesProfilesTex.value=e.iesProfiles),oi.debug(`scene textures updated in-place`)}updateGoboMaps(e){let t=this._sceneTextureNodes;!t||!t.goboMapsTex||e&&(t.goboMapsTex.value=e)}updateIESProfiles(e){let t=this._sceneTextureNodes;!t||!t.iesProfilesTex||e&&(t.iesProfilesTex.value=e)}getSceneTextureNodes(){return this._sceneTextureNodes}createSceneTextureNodes(e,t){let i=e.triangleStorageNode,a=e.bvhStorageNode,o=e.materialData.materialStorageNode,s=e.lightStorageNode,c=(0,n.texture)(e.environment.environmentTexture),l=t.getReadTextures();this.prevColorTexNode=(0,n.texture)(l.color),this.prevAlbedoTexNode=(0,n.texture)(l.albedo),this.prevNormalDepthTexNode=(0,n.texture)(l.normalDepth);let u=()=>{let e=new r.DataArrayTexture(new Uint8Array([255,255,255,255]),1,1,1);return e.minFilter=r.LinearFilter,e.magFilter=r.LinearFilter,e.generateMipmaps=!1,e.needsUpdate=!0,(0,n.texture)(e)},d={triStorage:i,bvhStorage:a,matStorage:o,lightBufferStorage:s,envTex:c,goboMapsTex:e.goboMaps?(0,n.texture)(e.goboMaps):u(),iesProfilesTex:e.iesProfiles?(0,n.texture)(e.iesProfiles):u()};return this._sceneTextureNodes=d,d}dispose(){this.prevColorTexNode=null,this.prevAlbedoTexNode=null,this.prevNormalDepthTexNode=null,this._sceneTextureNodes=null}},ci=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.batchSizeRatio=.02,this.maxIterations=2,this.timeBudgetMs=15e3,this.stats={reinsertionsApplied:0,iterations:0,timeMs:0}}setBatchSizeRatio(e){this.batchSizeRatio=Math.max(.005,Math.min(.1,e))}setMaxIterations(e){this.maxIterations=Math.max(1,Math.min(5,e))}getStatistics(){return{...this.stats}}surfaceArea(e){let t=e.maxX-e.minX,n=e.maxY-e.minY,r=e.maxZ-e.minZ;return t*n+n*r+r*t}buildParentMap(e){let t=new Map;t.set(e,{parent:null,isLeft:!1});let n=[e];for(;n.length>0;){let e=n.pop();e.triangleCount>0||(e.leftChild&&(t.set(e.leftChild,{parent:e,isLeft:!0}),n.push(e.leftChild)),e.rightChild&&(t.set(e.rightChild,{parent:e,isLeft:!1}),n.push(e.rightChild)))}return t}findCandidates(e,t,n){let r=[],i=[e];for(;i.length>0;){let a=i.pop();if(a!==e&&n.get(a).parent!==e){let e=this.surfaceArea(a);r.length<t?(r.push({node:a,cost:e}),r.length===t&&this._heapify(r)):e>r[0].cost&&(r[0]={node:a,cost:e},this._siftDown(r,0))}a.triangleCount===0&&(a.leftChild&&i.push(a.leftChild),a.rightChild&&i.push(a.rightChild))}return r}_heapify(e){for(let t=(e.length>>1)-1;t>=0;t--)this._siftDown(e,t)}_siftDown(e,t){let n=e.length;for(;;){let r=t,i=2*t+1,a=2*t+2;if(i<n&&e[i].cost<e[r].cost&&(r=i),a<n&&e[a].cost<e[r].cost&&(r=a),r===t)break;let o=e[t];e[t]=e[r],e[r]=o,t=r}}findReinsertion(e,t,n){let r=n.get(e),i=r.parent;if(!i)return null;let a=r.isLeft?i.rightChild:i.leftChild,o=this.surfaceArea(e),s=this.surfaceArea(i),c=null,l=0,u=s,d=a.minX,f=a.minY,p=a.minZ,m=a.maxX,h=a.maxY,g=a.maxZ,_=a,v=i,y=[];do{for(y.length=0,y.push(u,_);y.length>0;){let t=y.pop(),n=y.pop();if(n-o<=l)continue;let r=Math.min(t.minX,e.minX),i=Math.min(t.minY,e.minY),a=Math.min(t.minZ,e.minZ),s=Math.max(t.maxX,e.maxX),u=Math.max(t.maxY,e.maxY),d=Math.max(t.maxZ,e.maxZ),f=s-r,p=u-i,m=d-a,h=n-(f*p+p*m+m*f);if(h>l&&(c=t,l=h),t.triangleCount===0&&t.leftChild&&t.rightChild){let e=h+this.surfaceArea(t);y.push(e,t.leftChild),y.push(e,t.rightChild)}}let t=n.get(v);if(!t||t.parent===null)break;if(v!==i){d=Math.min(d,_.minX),f=Math.min(f,_.minY),p=Math.min(p,_.minZ),m=Math.max(m,_.maxX),h=Math.max(h,_.maxY),g=Math.max(g,_.maxZ);let e=m-d,t=h-f,n=g-p,r=e*t+t*n+n*e;u+=this.surfaceArea(v)-r}let r=t.parent;_=t.isLeft?r.rightChild:r.leftChild,v=r}while(n.get(v).parent!==null);return c===a||c===i?null:c?{from:e,to:c,areaDiff:l}:null}getConflicts(e,t,n){let r=n.get(e);return[t,e,r.isLeft?r.parent.rightChild:r.parent.leftChild,n.get(t).parent,r.parent]}reinsertNode(e,t,n){let r=n.get(e),i=r.parent,a=r.isLeft?i.rightChild:i.leftChild,o=n.get(i),s=o.parent,c=n.get(t),l=c.parent;o.isLeft?s.leftChild=a:s.rightChild=a,i.leftChild=e,i.rightChild=t,i.triangleOffset=0,i.triangleCount=0,i.minX=Math.min(e.minX,t.minX),i.minY=Math.min(e.minY,t.minY),i.minZ=Math.min(e.minZ,t.minZ),i.maxX=Math.max(e.maxX,t.maxX),i.maxY=Math.max(e.maxY,t.maxY),i.maxZ=Math.max(e.maxZ,t.maxZ),c.isLeft?l.leftChild=i:l.rightChild=i,n.set(a,{parent:s,isLeft:o.isLeft}),n.set(i,{parent:l,isLeft:c.isLeft}),n.set(e,{parent:i,isLeft:!0}),n.set(t,{parent:i,isLeft:!1}),this.refitFrom(s,n),this.refitFrom(l,n)}refitFrom(e,t){let n=e;for(;n;){if(n.triangleCount===0&&n.leftChild&&n.rightChild){let e=n.leftChild,t=n.rightChild;n.minX=Math.min(e.minX,t.minX),n.minY=Math.min(e.minY,t.minY),n.minZ=Math.min(e.minZ,t.minZ),n.maxX=Math.max(e.maxX,t.maxX),n.maxY=Math.max(e.maxY,t.maxY),n.maxZ=Math.max(e.maxZ,t.maxZ)}let e=t.get(n);n=e?e.parent:null}}optimizeBVH(e,t){let n=performance.now();this.stats={reinsertionsApplied:0,iterations:0,timeMs:0};for(let r=0;r<this.maxIterations&&!(performance.now()-n>this.timeBudgetMs);r++){let i=this.buildParentMap(e),a=i.size,o=Math.max(1,Math.floor(a*this.batchSizeRatio));t&&t(`Reinsertion iter ${r+1}/${this.maxIterations}: selecting ${o} candidates`);let s=this.findCandidates(e,o,i),c=[];for(let t=0;t<s.length&&!(performance.now()-n>this.timeBudgetMs);t++){let n=this.findReinsertion(s[t].node,e,i);n&&n.areaDiff>0&&c.push(n)}c.sort((e,t)=>t.areaDiff-e.areaDiff);let l=new Set,u=0;for(let e of c){let t=this.getConflicts(e.from,e.to,i);if(!t.some(e=>l.has(e))){for(let e of t)l.add(e);this.reinsertNode(e.from,e.to,i),u++}}if(this.stats.reinsertionsApplied+=u,this.stats.iterations=r+1,t&&t(`Reinsertion iter ${r+1}: applied ${u} reinsertions`),u===0)break}return this.stats.timeMs=performance.now()-n,this.stats}};wt();var li=St.TRIANGLE_LEAF,ui=16,di=2147483648,fi=(e,t)=>~(e<<4|t)>>>0,pi=e=>e>=di,mi=e=>~e>>>0>>>4,hi=e=>~e&15;function gi(e){let t=new Uint32Array(e.buffer,e.byteOffset,e.length),n=e.length/ui,r=e=>{let n=e*ui;return t[n+3]===li&&t[n+1]>0&&t[n+1]<=15},i=new Uint32Array(n),a=new Uint32Array(n),o=0,s=[0];for(;s.length;){let e=s.pop();i[e]=o,a[o++]=e;let n=e*ui;t[n+3]>=1073741824||(r(t[n+7])||s.push(t[n+7]),r(t[n+3])||s.push(t[n+3]))}let c=new Float32Array(o*ui),l=new Uint32Array(c.buffer);for(let n=0;n<o;n++){let o=a[n]*ui,s=n*ui;c.set(e.subarray(o,o+ui),s),!(t[o+3]>=1073741824)&&(l[s+3]=_i(t,t[o+3],r,i),l[s+7]=_i(t,t[o+7],r,i))}return c}function _i(e,t,n,r){let i=t*ui;return n(t)?fi(e[i],e[i+1]):r[t]}var vi=(e,t,n)=>e>=di?fi(mi(e)+n,hi(e)):e+t;function yi(e,t,n,r=0,i=e.length){for(let a=r;a<i;a+=ui){if(e[a+3]===li){e[a]+=n;continue}e[a+3]=vi(e[a+3],t,n),e[a+7]=vi(e[a+7],t,n)}}Ae(),dr(),wt();var bi=ye(`bvh`),xi=St.TRIANGLE_LEAF,Si=St.FRONTIER,Ci=null;function wi(e){Ci=e}var Ti=K.FLOATS_PER_TRIANGLE,Ei=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),Di=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},Oi=class{constructor(){this.useWorker=!0,this.maxLeafSize=8,this.foldLeaves=!1,this.numBins=32,this.minBins=8,this.maxBins=64,this.totalNodes=0,this.processedTriangles=0,this.totalTriangles=0,this.lastProgressUpdate=0,this.progressUpdateInterval=100,this.traversalCost=1,this.intersectionCost=2.5,this.useMortonCodes=!0,this.mortonBits=10,this.mortonClusterThreshold=128,this.enableObjectMedianFallback=!0,this.enableSpatialMedianFallback=!0,this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0},this.enableReinsertionOptimization=!0,this.reinsertionBatchSizeRatio=.02,this.reinsertionMaxIterations=2,this.initializeBinArrays(),this._partResult={mid:0,lMinX:0,lMinY:0,lMinZ:0,lMaxX:0,lMaxY:0,lMaxZ:0,rMinX:0,rMinY:0,rMinZ:0,rMaxX:0,rMaxY:0,rMaxZ:0},this.centroids=null,this.bMin=null,this.bMax=null,this.indices=null,this.mortonCodes=null,this.triangles=null,this.reorderedTriangleData=null}initializeBinArrays(){let e=this.maxBins;this.binBoundsMin=new Float32Array(e*3),this.binBoundsMax=new Float32Array(e*3),this.binCounts=new Uint32Array(e),this.leftPrefixMin=new Float32Array(e*3),this.leftPrefixMax=new Float32Array(e*3),this.leftPrefixCount=new Uint32Array(e),this.rightPrefixMin=new Float32Array(e*3),this.rightPrefixMax=new Float32Array(e*3),this.rightPrefixCount=new Uint32Array(e)}getOptimalBinCount(e){return e<=16?this.minBins:e<=64?16:e<=256?32:e<=1024?48:this.maxBins}setAdaptiveBinConfig(e){e.minBins!==void 0&&(this.minBins=Math.max(4,e.minBins)),e.maxBins!==void 0&&(this.maxBins=Math.min(128,e.maxBins)),e.baseBins!==void 0&&(this.numBins=e.baseBins),e.maxBins!==void 0&&this.initializeBinArrays()}setMortonConfig(e){e.enabled!==void 0&&(this.useMortonCodes=e.enabled),e.bits!==void 0&&(this.mortonBits=Math.max(6,Math.min(10,e.bits))),e.threshold!==void 0&&(this.mortonClusterThreshold=Math.max(16,e.threshold))}setFallbackConfig(e){e.objectMedian!==void 0&&(this.enableObjectMedianFallback=e.objectMedian),e.spatialMedian!==void 0&&(this.enableSpatialMedianFallback=e.spatialMedian)}setReinsertionConfig(e){e.enabled!==void 0&&(this.enableReinsertionOptimization=e.enabled),e.batchSizeRatio!==void 0&&(this.reinsertionBatchSizeRatio=Math.max(.005,Math.min(.1,e.batchSizeRatio))),e.maxIterations!==void 0&&(this.reinsertionMaxIterations=Math.max(1,Math.min(5,e.maxIterations)))}initializeTriangleArrays(){let e=this.totalTriangles,t=Ei(this.triangles),n=K.POSITION_A_OFFSET,r=K.POSITION_B_OFFSET,i=K.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*Ti,o=t[e+n],s=t[e+n+1],c=t[e+n+2],l=t[e+r],u=t[e+r+1],d=t[e+r+2],f=t[e+i],p=t[e+i+1],m=t[e+i+2],h=a*3;this.centroids[h]=(o+l+f)/3,this.centroids[h+1]=(s+u+p)/3,this.centroids[h+2]=(c+d+m)/3,this.bMin[h]=o<l?o<f?o:f:l<f?l:f,this.bMin[h+1]=s<u?s<p?s:p:u<p?u:p,this.bMin[h+2]=c<d?c<m?c:m:d<m?d:m,this.bMax[h]=o>l?o>f?o:f:l>f?l:f,this.bMax[h+1]=s>u?s>p?s:p:u>p?u:p,this.bMax[h+2]=c>d?c>m?c:m:d>m?d:m,this.indices[a]=a}}expandBits(e){return e=e*65537&4278190335,e=e*257&251719695,e=e*17&3272356035,e=e*5&1227133513,e}morton3D(e,t,n){return(this.expandBits(n)<<2)+(this.expandBits(t)<<1)+this.expandBits(e)}computeMortonCodeForIndex(e,t,n,r,i,a,o){let s=this.centroids,c=e*3,l=(1<<this.mortonBits)-1,u=i>0?(s[c]-t)/i:0,d=a>0?(s[c+1]-n)/a:0,f=o>0?(s[c+2]-r)/o:0,p=Math.max(0,Math.min(l,Math.floor(u*l))),m=Math.max(0,Math.min(l,Math.floor(d*l))),h=Math.max(0,Math.min(l,Math.floor(f*l)));return this.morton3D(p,m,h)}sortTrianglesByMortonCode(){let e=this.totalTriangles;if(!this.useMortonCodes||e<this.mortonClusterThreshold)return;let t=performance.now(),n=this.centroids,r=this.indices,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let t=0;t<e;t++){let e=r[t]*3,u=n[e],d=n[e+1],f=n[e+2];u<i&&(i=u),d<a&&(a=d),f<o&&(o=f),u>s&&(s=u),d>c&&(c=d),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o,p=this.mortonCodes,m=(1<<this.mortonBits)-1,h=u>0?m/u:0,g=d>0?m/d:0,_=f>0?m/f:0;for(let t=0;t<e;t++){let e=r[t],s=e*3,c=(n[s]-i)*h,l=(n[s+1]-a)*g,u=(n[s+2]-o)*_;c=c<0?0:(c>m?m:c)|0,l=l<0?0:(l>m?m:l)|0,u=u<0?0:(u>m?m:u)|0,c=c*65537&4278190335,c=c*257&251719695,c=c*17&3272356035,c=c*5&1227133513,l=l*65537&4278190335,l=l*257&251719695,l=l*17&3272356035,l=l*5&1227133513,u=u*65537&4278190335,u=u*257&251719695,u=u*17&3272356035,u=u*5&1227133513,p[e]=(u<<2)+(l<<1)+c}let v=new Uint32Array(e),y=new Uint32Array(256);for(let t=0;t<32;t+=8){y.fill(0);for(let n=0;n<e;n++)y[p[r[n]]>>>t&255]++;let n=0;for(let e=0;e<256;e++){let t=y[e];y[e]=n,n+=t}for(let n=0;n<e;n++){let e=p[r[n]]>>>t&255;v[y[e]++]=r[n]}r.set(v)}this.splitStats.mortonSortTime+=performance.now()-t}build(e,t=30,n=null){return this.totalTriangles=e.byteLength/(Ti*4),this.processedTriangles=0,this.lastProgressUpdate=performance.now(),this.useWorker&&Ci&&or()?new Promise((r,i)=>{let a=a=>{let o=this.totalTriangles,s=typeof SharedArrayBuffer<`u`;bi.debug(`SharedArrayBuffer ${s?`enabled`:`unavailable (using transfer fallback)`}`);let c=s?new SharedArrayBuffer(o*Ti*4):null;a.onmessage=e=>{let{bvhData:t,triangles:o,originalToBvh:s,error:l,progress:u,splitStats:d}=e.data;if(l){a.terminate(),i(Error(l));return}if(u!==void 0&&n){n(u);return}d&&(this.splitStats=d),a.terminate(),r({bvhData:t,bvhRoot:!0,reorderedTriangles:c?new Float32Array(c):o,originalToBvh:s||null})},a.onerror=e=>{a.terminate(),i(e)};let l=e.buffer,u={triangleData:l,triangleByteOffset:e.byteOffset,triangleByteLength:e.byteLength,triangleCount:o,depth:t,reportProgress:!!n,sharedReorderBuffer:c,reinsertionOptimization:{enabled:this.enableReinsertionOptimization,batchSizeRatio:this.reinsertionBatchSizeRatio,maxIterations:this.reinsertionMaxIterations}};a.postMessage(u,[l])};try{a(Ci())}catch(i){bi.warn(`worker creation failed, falling back to synchronous build:`,i),r(this._buildSyncAndFlatten(e,t,n))}}):new Promise(r=>{r(this._buildSyncAndFlatten(e,t,n))})}_buildSyncAndFlatten(e,t,n){let r=this.buildSync(e,t,n),i=this.flattenBVH(r);return{bvhData:this.foldLeaves?gi(i):i,bvhRoot:!0,reorderedTriangles:this.reorderedTriangleData||null,originalToBvh:this.originalToBvhMap||null}}buildSync(e,t=30,n=null,r=null){let i=performance.now();this.totalNodes=0,this.processedTriangles=0,this.triangles=e,this.totalTriangles=e.byteLength/(Ti*4),this.lastProgressUpdate=performance.now(),this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0,saOrderTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let a=this.totalTriangles,o=performance.now();this.centroids=new Float32Array(a*3),this.bMin=new Float32Array(a*3),this.bMax=new Float32Array(a*3),this.indices=new Uint32Array(a),this.mortonCodes=new Uint32Array(a),this.initializeTriangleArrays(),this.splitStats.initTime=performance.now()-o,this.sortTrianglesByMortonCode();let s=performance.now(),c=this.buildNodeRecursive(0,a,t,n);if(this.splitStats.sahBuildTime=performance.now()-s,this.enableReinsertionOptimization&&this.totalTriangles>1e3){let e=new ci(this.traversalCost,this.intersectionCost);e.setBatchSizeRatio(this.reinsertionBatchSizeRatio),e.setMaxIterations(this.reinsertionMaxIterations);let t=n?e=>{n(e)}:null;try{e.optimizeBVH(c,t)}catch(e){bi.error(`reinsertion optimizer failed:`,e)}let r=e.getStatistics();this.splitStats.reinsertionOptimizationTime=r.timeMs,this.splitStats.reinsertionsApplied=r.reinsertionsApplied,this.splitStats.reinsertionIterations=r.iterations}let l=performance.now();this.applySAOrdering(c),this.splitStats.saOrderTime=performance.now()-l;let u=performance.now(),d=this.triangles,f=r||new d.constructor(a*Ti);for(let e=0;e<a;e++){let t=this.indices[e]*Ti,n=e*Ti;f.set(d.subarray(t,t+Ti),n)}this.reorderedTriangleData=f;let p=new Uint32Array(a);for(let e=0;e<a;e++)p[this.indices[e]]=e;this.originalToBvhMap=p,this.splitStats.reorderTime=performance.now()-u,this.splitStats.totalBuildTime=performance.now()-i;let m=this.splitStats.totalBuildTime,h=this.splitStats;return bi.debug(`${H.n(a)} tris → ${H.n(this.totalNodes)} nodes in ${H.ms(m)} | SAH ${h.sahSplits} objMed ${h.objectMedianSplits} spatMed ${h.spatialMedianSplits} failed ${h.failedSplits}`+(h.reinsertionsApplied?` | reinsertions ${h.reinsertionsApplied}`:``)),n&&n(100),this.centroids=null,this.bMin=null,this.bMax=null,this.mortonCodes=null,c}updateProgress(e,t){if(!t)return;this.processedTriangles+=e;let n=performance.now();n-this.lastProgressUpdate<this.progressUpdateInterval||(this.lastProgressUpdate=n,t(Math.min(Math.floor(this.processedTriangles/this.totalTriangles*100),99)))}buildNodeRecursiveToDepth(e,t,n,r,i,a,o,s,c,l,u){let d=new Di;this.totalNodes++;let f=t-e;if(a===void 0?this.updateNodeBounds(d,e,t):(d.minX=a,d.minY=o,d.minZ=s,d.maxX=c,d.maxY=l,d.maxZ=u),f<=this.maxLeafSize||n<=0)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;if(r<=0&&f>this.maxLeafSize*16){let r=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=r,this.frontierTasks.push({taskId:r,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}let p=this.findBestSplitPositionSAH(e,t,d);if(!p.success){if(this.splitStats.failedSplits++,r>0||f<=this.maxLeafSize*16)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;let a=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=a,this.frontierTasks.push({taskId:a,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}p.method===`SAH`?this.splitStats.sahSplits++:p.method===`object_median`?this.splitStats.objectMedianSplits++:p.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,p.axis,p.pos);let m=this._partResult,h=m.mid,g=m.lMinX,_=m.lMinY,v=m.lMinZ,y=m.lMaxX,b=m.lMaxY,x=m.lMaxZ,S=m.rMinX,C=m.rMinY,w=m.rMinZ,T=m.rMaxX,E=m.rMaxY,D=m.rMaxZ;return h===e||h===t?(d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d):(d.leftChild=this.buildNodeRecursiveToDepth(e,h,n-1,r-1,i,g,_,v,y,b,x),d.rightChild=this.buildNodeRecursiveToDepth(h,t,n-1,r-1,i,S,C,w,T,E,D),d)}buildNodeRecursive(e,t,n,r,i,a,o,s,c,l){let u=new Di;this.totalNodes++;let d=t-e;if(i===void 0?this.updateNodeBounds(u,e,t):(u.minX=i,u.minY=a,u.minZ=o,u.maxX=s,u.maxY=c,u.maxZ=l),d<=this.maxLeafSize||n<=0)return u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;let f=this.findBestSplitPositionSAH(e,t,u);if(!f.success)return this.splitStats.failedSplits++,u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;f.method===`SAH`?this.splitStats.sahSplits++:f.method===`object_median`?this.splitStats.objectMedianSplits++:f.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,f.axis,f.pos);let p=this._partResult,m=p.mid,h=p.lMinX,g=p.lMinY,_=p.lMinZ,v=p.lMaxX,y=p.lMaxY,b=p.lMaxZ,x=p.rMinX,S=p.rMinY,C=p.rMinZ,w=p.rMaxX,T=p.rMaxY,E=p.rMaxZ;return m===e||m===t?(u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u):(u.leftChild=this.buildNodeRecursive(e,m,n-1,r,h,g,_,v,y,b),u.rightChild=this.buildNodeRecursive(m,t,n-1,r,x,S,C,w,T,E),u)}partitionWithBounds(e,t,n,r){let i=this.indices,a=this.centroids,o=this.bMin,s=this.bMax,c=e,l=t-1,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(;c<=l;){let e=i[c],t=e*3;a[t+n]<=r?(o[t]<u&&(u=o[t]),o[t+1]<d&&(d=o[t+1]),o[t+2]<f&&(f=o[t+2]),s[t]>p&&(p=s[t]),s[t+1]>m&&(m=s[t+1]),s[t+2]>h&&(h=s[t+2]),c++):(o[t]<g&&(g=o[t]),o[t+1]<_&&(_=o[t+1]),o[t+2]<v&&(v=o[t+2]),s[t]>y&&(y=s[t]),s[t+1]>b&&(b=s[t+1]),s[t+2]>x&&(x=s[t+2]),i[c]=i[l],i[l]=e,l--)}let S=this._partResult;return S.mid=c,S.lMinX=u,S.lMinY=d,S.lMinZ=f,S.lMaxX=p,S.lMaxY=m,S.lMaxZ=h,S.rMinX=g,S.rMinY=_,S.rMinZ=v,S.rMaxX=y,S.rMaxY=b,S.rMaxZ=x,S}updateNodeBounds(e,t,n){let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0,l=this.indices,u=this.bMin,d=this.bMax;for(let e=t;e<n;e++){let t=l[e]*3;u[t]<r&&(r=u[t]),u[t+1]<i&&(i=u[t+1]),u[t+2]<a&&(a=u[t+2]),d[t]>o&&(o=d[t]),d[t+1]>s&&(s=d[t+1]),d[t+2]>c&&(c=d[t+2])}e.minX=r,e.minY=i,e.minZ=a,e.maxX=o,e.maxY=s,e.maxZ=c}findBestSplitPositionSAH(e,t,n){let r=1/0,i=-1,a=0,o=this.computeSurfaceAreaFlat(n.minX,n.minY,n.minZ,n.maxX,n.maxY,n.maxZ),s=t-e,c=this.intersectionCost*s,l=this.getOptimalBinCount(s);this.splitStats.totalSplitAttempts++,this.splitStats.avgBinsUsed=(this.splitStats.avgBinsUsed*(this.splitStats.totalSplitAttempts-1)+l)/this.splitStats.totalSplitAttempts;let u=this.indices,d=this.centroids,f=this.bMin,p=this.bMax,m=this.binBoundsMin,h=this.binBoundsMax,g=this.binCounts,_=this.leftPrefixMin,v=this.leftPrefixMax,y=this.leftPrefixCount,b=this.rightPrefixMin,x=this.rightPrefixMax,S=this.rightPrefixCount,C=1/0,w=-1/0,T=1/0,E=-1/0,D=1/0,O=-1/0;for(let n=e;n<t;n++){let e=u[n]*3,t=d[e],r=d[e+1],i=d[e+2];t<C&&(C=t),t>w&&(w=t),r<T&&(T=r),r>E&&(E=r),i<D&&(D=i),i>O&&(O=i)}let k=[C,T,D],A=[w,E,O];for(let n=0;n<3;n++){let s=k[n],C=A[n];if(C-s<1e-6)continue;for(let e=0;e<l;e++){g[e]=0;let t=e*3;m[t]=1/0,m[t+1]=1/0,m[t+2]=1/0,h[t]=-1/0,h[t+1]=-1/0,h[t+2]=-1/0}let w=l/(C-s);for(let r=e;r<t;r++){let e=u[r],t=d[e*3+n],i=Math.floor((t-s)*w);i>=l&&(i=l-1),g[i]++;let a=i*3,o=e*3;f[o]<m[a]&&(m[a]=f[o]),f[o+1]<m[a+1]&&(m[a+1]=f[o+1]),f[o+2]<m[a+2]&&(m[a+2]=f[o+2]),p[o]>h[a]&&(h[a]=p[o]),p[o+1]>h[a+1]&&(h[a+1]=p[o+1]),p[o+2]>h[a+2]&&(h[a+2]=p[o+2])}y[0]=g[0],_[0]=m[0],_[1]=m[1],_[2]=m[2],v[0]=h[0],v[1]=h[1],v[2]=h[2];for(let e=1;e<l;e++){let t=e*3,n=(e-1)*3;y[e]=y[e-1]+g[e];let r=_[n],i=m[t],a=_[n+1],o=m[t+1],s=_[n+2],c=m[t+2];_[t]=r<i?r:i,_[t+1]=a<o?a:o,_[t+2]=s<c?s:c;let l=v[n],u=h[t],d=v[n+1],f=h[t+1],p=v[n+2],b=h[t+2];v[t]=l>u?l:u,v[t+1]=d>f?d:f,v[t+2]=p>b?p:b}let T=l-1,E=T*3;S[T]=g[T],b[E]=m[E],b[E+1]=m[E+1],b[E+2]=m[E+2],x[E]=h[E],x[E+1]=h[E+1],x[E+2]=h[E+2];for(let e=T-1;e>=0;e--){let t=e*3,n=(e+1)*3;S[e]=S[e+1]+g[e];let r=b[n],i=m[t],a=b[n+1],o=m[t+1],s=b[n+2],c=m[t+2];b[t]=r<i?r:i,b[t+1]=a<o?a:o,b[t+2]=s<c?s:c;let l=x[n],u=h[t],d=x[n+1],f=h[t+1],p=x[n+2],_=h[t+2];x[t]=l>u?l:u,x[t+1]=d>f?d:f,x[t+2]=p>_?p:_}for(let e=1;e<l;e++){let t=(e-1)*3,u=e*3,d=y[e-1],f=S[e];if(d===0||f===0)continue;let p=v[t]-_[t],m=v[t+1]-_[t+1],h=v[t+2]-_[t+2],g=2*(p*m+m*h+h*p),w=x[u]-b[u],T=x[u+1]-b[u+1],E=x[u+2]-b[u+2],D=2*(w*T+T*E+E*w),O=this.traversalCost+g/o*d*this.intersectionCost+D/o*f*this.intersectionCost;O<r&&O<c&&(r=O,i=n,a=s+(C-s)*e/l)}}return i===-1?this.enableObjectMedianFallback?this.findObjectMedianSplit(e,t):this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`fallbacks_disabled`}:{success:!0,axis:i,pos:a,method:`SAH`,binsUsed:l}}findObjectMedianSplit(e,t){let n=this.indices,r=this.centroids,i=-1,a=-1;for(let o=0;o<3;o++){let s=1/0,c=-1/0;for(let i=e;i<t;i++){let e=r[n[i]*3+o];e<s&&(s=e),e>c&&(c=e)}let l=c-s;l>a&&(a=l,i=o)}if(i===-1||a<1e-10)return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_failed`};let o=t-e,s=e+Math.floor(o/2);this.quickselect(e,t,s,i);let c=r[n[s]*3+i],l=!0;for(let e=s+1;e<t;e++)if(r[n[e]*3+i]>c){l=!1;break}if(l){let a=-1/0;for(let t=e;t<s;t++){let e=r[n[t]*3+i];e>a&&(a=e)}if(a<c)c=(a+c)*.5;else return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_degenerate`}}return{success:!0,axis:i,pos:c,method:`object_median`}}findSpatialMedianSplit(e,t){let n=this.indices,r=this.centroids,i=this.bMin,a=this.bMax,o=-1,s=-1,c=0,l=0;for(let r=0;r<3;r++){let u=1/0,d=-1/0;for(let o=e;o<t;o++){let e=n[o]*3+r;i[e]<u&&(u=i[e]),a[e]>d&&(d=a[e])}let f=d-u;f>s&&(s=f,o=r,c=u,l=d)}if(o===-1||s<1e-12)return{success:!1,method:`spatial_median_failed`};let u=(c+l)*.5,d=t-e,f=0;for(let i=e;i<t;i++)r[n[i]*3+o]<=u&&f++;if(f===0||f===d){let i=e+Math.floor(d/2);this.quickselect(e,t,i,o);let a=r[n[i]*3+o],s=!0;for(let i=e;i<t;i++)if(r[n[i]*3+o]!==a){s=!1;break}if(s)return{success:!1,method:`spatial_median_degenerate`};let c=-1/0;for(let t=e;t<i;t++){let e=r[n[t]*3+o];e>c&&(c=e)}if(c<a)u=(c+a)*.5;else{let e=1/0;for(let a=i+1;a<t;a++){let t=r[n[a]*3+o];t<e&&(e=t)}u=(a+e)*.5}}return{success:!0,axis:o,pos:u,method:`spatial_median`}}quickselect(e,t,n,r){let i=this.indices,a=this.centroids,o=e,s=t-1;for(;o<s;){let e=o+s>>>1,t=a[i[o]*3+r],c=a[i[e]*3+r],l=a[i[s]*3+r];if(t>c){let t=i[o];i[o]=i[e],i[e]=t}if(t>l){let e=i[o];i[o]=i[s],i[s]=e}if(c>l){let t=i[e];i[e]=i[s],i[s]=t}let u=a[i[e]*3+r],d=o,f=s;for(;d<=f;){for(;a[i[d]*3+r]<u;)d++;for(;a[i[f]*3+r]>u;)f--;if(d<=f){let e=i[d];i[d]=i[f],i[f]=e,d++,f--}}f<n&&(o=d),d>n&&(s=f)}}applySAOrdering(e){if(!e||!e.leftChild)return;let t=[e],n=[];for(;t.length>0;){let e=t.pop();!e.leftChild||!e.rightChild||(n.push(e),t.push(e.leftChild),t.push(e.rightChild))}for(let e=n.length-1;e>=0;e--){let t=n[e],r=t.leftChild,i=t.rightChild,a=r.maxX-r.minX,o=r.maxY-r.minY,s=r.maxZ-r.minZ,c=i.maxX-i.minX,l=i.maxY-i.minY,u=i.maxZ-i.minZ;c*l+l*u+u*c>a*o+o*s+s*a&&(t.leftChild=i,t.rightChild=r)}}flattenBVH(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}gt(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=ht(r);for(let e=0;e<t.length;e++){let n=t[e],a=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[a]=e.minX,r[a+1]=e.minY,r[a+2]=e.minZ,i[a+3]=e._flatIndex,r[a+4]=e.maxX,r[a+5]=e.maxY,r[a+6]=e.maxZ,i[a+7]=t._flatIndex,r[a+8]=t.minX,r[a+9]=t.minY,r[a+10]=t.minZ,r[a+12]=t.maxX,r[a+13]=t.maxY,r[a+14]=t.maxZ}else i[a]=n.triangleOffset,i[a+1]=n.triangleCount,i[a+3]=xi}return r}flattenBVHWithFrontier(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}gt(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=[],a=ht(r);for(let e=0;e<t.length;e++){let n=t[e],o=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[o]=e.minX,r[o+1]=e.minY,r[o+2]=e.minZ,a[o+3]=e._flatIndex,r[o+4]=e.maxX,r[o+5]=e.maxY,r[o+6]=e.maxZ,a[o+7]=t._flatIndex,r[o+8]=t.minX,r[o+9]=t.minY,r[o+10]=t.minZ,r[o+12]=t.maxX,r[o+13]=t.maxY,r[o+14]=t.maxZ}else if(n.isFrontier){let t=n.frontierTaskId;a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+2]=t,a[o+3]=Si,i.push({taskId:t,flatIndex:e})}else a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+3]=xi}return{flatData:r,frontierMap:i,nodeCount:t.length}}assembleParallelBVH(e,t,n,r){let i=[...r].sort((e,t)=>e.taskId-t.taskId),a=t;for(let e=0;e<i.length;e++)a+=i[e].nodeCount;gt(a,`assembled BLAS node count`);let o=new Float32Array(a*16),s=ht(o);o.set(e);let c=new Map;for(let e of n)c.set(e.taskId,e.flatIndex);let l=t;for(let e=0;e<i.length;e++){let t=i[e],n=t.flatData,r=t.nodeCount,a=l*16;o.set(n,a);for(let e=0;e<r;e++){let t=a+e*16;s[t+3]<xi&&(s[t+3]+=l,s[t+7]+=l)}let u=c.get(t.taskId);if(u!==void 0){let e=u*16,t=a;for(let n=0;n<16;n++)o[e+n]=o[t+n]}l+=r}return o}computeSurfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}};wt();var ki=K.FLOATS_PER_TRIANGLE,Ai=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),ji=e=>e instanceof Uint32Array?e:new Uint32Array(e.buffer,e.byteOffset,e.length),Mi=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:e,idx:t?e.viewAs(Uint32Array):ji(e)}},Ni=(e,t)=>e.chunked?e.f.chunkFor(t):e.f,Pi=(e,t)=>e.chunked?e.idx.chunkFor(t):e.idx,Fi=(e,t)=>e.chunked?e.chunked.baseOf(t):t*Li,Ii=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:t?t.viewAs(Float32Array):Ai(e),u:t?e:ji(e)}},Li=16,Ri=St.TRIANGLE_LEAF,zi=St.BLAS_POINTER_LEAF,Bi=1e-12;function Vi(e,t,n,r,i,a){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)<=Bi*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,ee=-1/0,te=-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>ee&&(ee=s),c<I&&(I=c),c>te&&(te=c)}i[a]=P,i[a+1]=F,i[a+2]=I,i[a+3]=L,i[a+4]=ee,i[a+5]=te}function Hi(e,t,n,r,i){let a=K.POSITION_A_OFFSET,o=K.POSITION_B_OFFSET,s=K.POSITION_C_OFFSET,c=1/0,l=1/0,u=1/0,d=-1/0,f=-1/0,p=-1/0;for(let r=0;r<n;r++){let n=t+r,i=e.chunked?e.f.chunkFor(n):e.f,m=e.chunked?e.chunked.baseOf(n):n*ki;c=Math.min(c,i[m+a],i[m+o],i[m+s]),l=Math.min(l,i[m+a+1],i[m+o+1],i[m+s+1]),u=Math.min(u,i[m+a+2],i[m+o+2],i[m+s+2]),d=Math.max(d,i[m+a],i[m+o],i[m+s]),f=Math.max(f,i[m+a+1],i[m+o+1],i[m+s+1]),p=Math.max(p,i[m+a+2],i[m+o+2],i[m+s+2])}r[i]=c,r[i+1]=l,r[i+2]=u,r[i+3]=d,r[i+4]=f,r[i+5]=p}var Ui=new Float32Array(12);function Wi(e,t,n,r){let i=Ni(e,t),a=Pi(e,t),o=Fi(e,t);if(a[o+3]===Ri){Hi(n,a[o],a[o+1],r,0);return}for(let e=0;e<3;e++)r[e]=Math.min(i[o+e],i[o+8+e]),r[3+e]=Math.max(i[o+4+e],i[o+12+e])}function Gi(e,t,n,r,i){let a=Ni(e,t),o=Pi(e,t),s=Fi(e,t),c=(t-i)*6,l=o[s+3];if(l===Ri){Hi(n,o[s],o[s+1],r,c);return}if(l===zi){Vi(a,s,r,(o[s]-i)*6,r,c);return}let u=o[s+7],d=r,f=(l-i)*6;pi(l)&&(Hi(n,mi(l),hi(l),Ui,0),d=Ui,f=0);let p=r,m=(u-i)*6;pi(u)&&(Hi(n,mi(u),hi(u),Ui,6),p=Ui,m=6),a[s]=d[f],a[s+1]=d[f+1],a[s+2]=d[f+2],a[s+4]=d[f+3],a[s+5]=d[f+4],a[s+6]=d[f+5],a[s+8]=p[m],a[s+9]=p[m+1],a[s+10]=p[m+2],a[s+12]=p[m+3],a[s+13]=p[m+4],a[s+14]=p[m+5];for(let e=0;e<3;e++)r[c+e]=Math.min(d[f+e],p[m+e]),r[c+3+e]=Math.max(d[f+3+e],p[m+3+e])}var Ki=class{constructor(){this._bounds=null,this._boundsNodeCount=0,this._tlasBounds=null,this._rootBox=null}updateTrianglePositions(e,t,n){let r=n.length,i=Ii(e);for(let e=0;e<r;e++){let r=n[e],a=i.chunked?i.f.chunkFor(e):i.f,o=i.chunked?i.u.chunkFor(e):i.u,s=i.chunked?i.chunked.baseOf(e):e*ki,c=r*9,l=t[c],u=t[c+1],d=t[c+2],f=t[c+3],p=t[c+4],m=t[c+5],h=t[c+6],g=t[c+7],_=t[c+8];a[s+K.POSITION_A_OFFSET]=l,a[s+K.POSITION_A_OFFSET+1]=u,a[s+K.POSITION_A_OFFSET+2]=d,a[s+K.POSITION_B_OFFSET]=f,a[s+K.POSITION_B_OFFSET+1]=p,a[s+K.POSITION_B_OFFSET+2]=m,a[s+K.POSITION_C_OFFSET]=h,a[s+K.POSITION_C_OFFSET+1]=g,a[s+K.POSITION_C_OFFSET+2]=_;let v=f-l,y=p-u,b=m-d,x=h-l,S=g-u,C=_-d,w=mt(y*C-b*S,b*x-v*C,v*S-y*x);o[s+K.NORMAL_A_PACKED_OFFSET]=w,o[s+K.NORMAL_B_PACKED_OFFSET]=w,o[s+K.NORMAL_C_PACKED_OFFSET]=w}}refitRange(e,t,n,r){let i=Ii(t);r>this._boundsNodeCount&&(this._bounds=new Float32Array(r*6),this._boundsNodeCount=r);let a=Mi(e);for(let e=n+r-1;e>=n;e--)Gi(a,e,i,this._bounds,n)}refitPartial(e,t,n,r){for(let r=0;r<n.length;r+=2)this.refitRange(e,t,n[r],n[r+1]);let i=Ii(t),a=Mi(e);(!this._tlasBounds||this._tlasBounds.length<r*6)&&(this._tlasBounds=new Float32Array(r*6));let o=this._tlasBounds,s=this._rootBox||=new Float32Array(6);for(let e=r-1;e>=0;e--){let t=Pi(a,e),n=Fi(a,e);t[n+3]===zi?(Wi(a,t[n],i,s),Vi(Ni(a,e),n,s,0,o,e*6)):Gi(a,e,i,o,0)}}refit(e,t,n){let r=Ii(t);n!==this._boundsNodeCount&&(this._bounds=new Float32Array(n*6),this._boundsNodeCount=n);let i=Mi(e);for(let e=n-1;e>=0;e--)Gi(i,e,r,this._bounds,0)}},qi="var e=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.batchSizeRatio=.02,this.maxIterations=2,this.timeBudgetMs=15e3,this.stats={reinsertionsApplied:0,iterations:0,timeMs:0}}setBatchSizeRatio(e){this.batchSizeRatio=Math.max(.005,Math.min(.1,e))}setMaxIterations(e){this.maxIterations=Math.max(1,Math.min(5,e))}getStatistics(){return{...this.stats}}surfaceArea(e){let t=e.maxX-e.minX,n=e.maxY-e.minY,r=e.maxZ-e.minZ;return t*n+n*r+r*t}buildParentMap(e){let t=new Map;t.set(e,{parent:null,isLeft:!1});let n=[e];for(;n.length>0;){let e=n.pop();e.triangleCount>0||(e.leftChild&&(t.set(e.leftChild,{parent:e,isLeft:!0}),n.push(e.leftChild)),e.rightChild&&(t.set(e.rightChild,{parent:e,isLeft:!1}),n.push(e.rightChild)))}return t}findCandidates(e,t,n){let r=[],i=[e];for(;i.length>0;){let a=i.pop();if(a!==e&&n.get(a).parent!==e){let e=this.surfaceArea(a);r.length<t?(r.push({node:a,cost:e}),r.length===t&&this._heapify(r)):e>r[0].cost&&(r[0]={node:a,cost:e},this._siftDown(r,0))}a.triangleCount===0&&(a.leftChild&&i.push(a.leftChild),a.rightChild&&i.push(a.rightChild))}return r}_heapify(e){for(let t=(e.length>>1)-1;t>=0;t--)this._siftDown(e,t)}_siftDown(e,t){let n=e.length;for(;;){let r=t,i=2*t+1,a=2*t+2;if(i<n&&e[i].cost<e[r].cost&&(r=i),a<n&&e[a].cost<e[r].cost&&(r=a),r===t)break;let o=e[t];e[t]=e[r],e[r]=o,t=r}}findReinsertion(e,t,n){let r=n.get(e),i=r.parent;if(!i)return null;let a=r.isLeft?i.rightChild:i.leftChild,o=this.surfaceArea(e),s=this.surfaceArea(i),c=null,l=0,u=s,d=a.minX,f=a.minY,p=a.minZ,m=a.maxX,h=a.maxY,g=a.maxZ,_=a,v=i,y=[];do{for(y.length=0,y.push(u,_);y.length>0;){let t=y.pop(),n=y.pop();if(n-o<=l)continue;let r=Math.min(t.minX,e.minX),i=Math.min(t.minY,e.minY),a=Math.min(t.minZ,e.minZ),s=Math.max(t.maxX,e.maxX),u=Math.max(t.maxY,e.maxY),d=Math.max(t.maxZ,e.maxZ),f=s-r,p=u-i,m=d-a,h=n-(f*p+p*m+m*f);if(h>l&&(c=t,l=h),t.triangleCount===0&&t.leftChild&&t.rightChild){let e=h+this.surfaceArea(t);y.push(e,t.leftChild),y.push(e,t.rightChild)}}let t=n.get(v);if(!t||t.parent===null)break;if(v!==i){d=Math.min(d,_.minX),f=Math.min(f,_.minY),p=Math.min(p,_.minZ),m=Math.max(m,_.maxX),h=Math.max(h,_.maxY),g=Math.max(g,_.maxZ);let e=m-d,t=h-f,n=g-p,r=e*t+t*n+n*e;u+=this.surfaceArea(v)-r}let r=t.parent;_=t.isLeft?r.rightChild:r.leftChild,v=r}while(n.get(v).parent!==null);return c===a||c===i?null:c?{from:e,to:c,areaDiff:l}:null}getConflicts(e,t,n){let r=n.get(e);return[t,e,r.isLeft?r.parent.rightChild:r.parent.leftChild,n.get(t).parent,r.parent]}reinsertNode(e,t,n){let r=n.get(e),i=r.parent,a=r.isLeft?i.rightChild:i.leftChild,o=n.get(i),s=o.parent,c=n.get(t),l=c.parent;o.isLeft?s.leftChild=a:s.rightChild=a,i.leftChild=e,i.rightChild=t,i.triangleOffset=0,i.triangleCount=0,i.minX=Math.min(e.minX,t.minX),i.minY=Math.min(e.minY,t.minY),i.minZ=Math.min(e.minZ,t.minZ),i.maxX=Math.max(e.maxX,t.maxX),i.maxY=Math.max(e.maxY,t.maxY),i.maxZ=Math.max(e.maxZ,t.maxZ),c.isLeft?l.leftChild=i:l.rightChild=i,n.set(a,{parent:s,isLeft:o.isLeft}),n.set(i,{parent:l,isLeft:c.isLeft}),n.set(e,{parent:i,isLeft:!0}),n.set(t,{parent:i,isLeft:!1}),this.refitFrom(s,n),this.refitFrom(l,n)}refitFrom(e,t){let n=e;for(;n;){if(n.triangleCount===0&&n.leftChild&&n.rightChild){let e=n.leftChild,t=n.rightChild;n.minX=Math.min(e.minX,t.minX),n.minY=Math.min(e.minY,t.minY),n.minZ=Math.min(e.minZ,t.minZ),n.maxX=Math.max(e.maxX,t.maxX),n.maxY=Math.max(e.maxY,t.maxY),n.maxZ=Math.max(e.maxZ,t.maxZ)}let e=t.get(n);n=e?e.parent:null}}optimizeBVH(e,t){let n=performance.now();this.stats={reinsertionsApplied:0,iterations:0,timeMs:0};for(let r=0;r<this.maxIterations&&!(performance.now()-n>this.timeBudgetMs);r++){let i=this.buildParentMap(e),a=i.size,o=Math.max(1,Math.floor(a*this.batchSizeRatio));t&&t(`Reinsertion iter ${r+1}/${this.maxIterations}: selecting ${o} candidates`);let s=this.findCandidates(e,o,i),c=[];for(let t=0;t<s.length&&!(performance.now()-n>this.timeBudgetMs);t++){let n=this.findReinsertion(s[t].node,e,i);n&&n.areaDiff>0&&c.push(n)}c.sort((e,t)=>t.areaDiff-e.areaDiff);let l=new Set,u=0;for(let e of c){let t=this.getConflicts(e.from,e.to,i);if(!t.some(e=>l.has(e))){for(let e of t)l.add(e);this.reinsertNode(e.from,e.to,i),u++}}if(this.stats.reinsertionsApplied+=u,this.stats.iterations=r+1,t&&t(`Reinsertion iter ${r+1}: applied ${u} reinsertions`),u===0)break}return this.stats.timeMs=performance.now()-n,this.stats}};const t={silent:0,error:1,warn:2,info:3,debug:4},n=`info`,r=`rayzeeLogLevel`,i=`rayzeeLogNamespaces`,a=`color:#7c8494`,o=`color:inherit`;let s=null,c=null;function l(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function u(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function d(){if(s!==null)return s;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in t?(s=t[e],s):(s=t[l(r)]??t[n],s)}function f(){if(c!==null)return c;let e=globalThis.__RAYZEE_LOG_NS__??l(i);return c=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],c}function p(e,n){if(n<t.debug)return!0;let r=f();return r.length===0||r.some(t=>e===t||e.startsWith(`${t}:`))}function m(e,n,r){if(e>d()||!p(n,e))return;let i=e===t.error?console.error:e===t.warn?console.warn:console.log,s=`[${n}]`;typeof r[0]==`string`?i(`%c${s}%c ${r[0]}`,a,o,...r.slice(1)):i(`%c${s}`,a,...r)}const h={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`)=>`${h.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},g={levels:t,setLevel(e){return e in t?(globalThis.__RAYZEE_LOG_LEVEL__=e,s=t[e],u(r,e===n?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(t).join(`, `)}`),this.getLevel())},getLevel(){let e=d();return Object.keys(t).find(n=>t[n]===e)},isEnabled(e){return(t[e]??t.debug)<=d()},only(...e){let t=e.flat().filter(Boolean);return c=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),u(i,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return s=null,c=null,this.getLevel()}};function _(e){return{namespace:e,error:(...n)=>m(t.error,e,n),warn:(...n)=>m(t.warn,e,n),info:(...n)=>m(t.info,e,n),debug:(...n)=>m(t.debug,e,n),isEnabled:e=>g.isEnabled(e),summary(n,r=[]){let i=r.filter(Boolean);if(i.length===0||!console.groupCollapsed){m(t.info,e,[n]),i.forEach(n=>m(t.debug,e,[n]));return}t.info>d()||((d()>=t.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${n}`,a,o),i.forEach(e=>console.log(e)),console.groupEnd())}}}function v(e){e&&e in t&&(globalThis.__RAYZEE_LOG_LEVEL__=e,s=t[e])}const y={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},b={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826};function x(e){return new Uint32Array(e.buffer,e.byteOffset,e.length)}function S(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 C=b.TRIANGLE_LEAF,w=(e,t)=>~(e<<4|t)>>>0;function T(e){let t=new Uint32Array(e.buffer,e.byteOffset,e.length),n=e.length/16,r=e=>{let n=e*16;return t[n+3]===C&&t[n+1]>0&&t[n+1]<=15},i=new Uint32Array(n),a=new Uint32Array(n),o=0,s=[0];for(;s.length;){let e=s.pop();i[e]=o,a[o++]=e;let n=e*16;t[n+3]>=1073741824||(r(t[n+7])||s.push(t[n+7]),r(t[n+3])||s.push(t[n+3]))}let c=new Float32Array(o*16),l=new Uint32Array(c.buffer);for(let n=0;n<o;n++){let o=a[n]*16,s=n*16;c.set(e.subarray(o,o+16),s),!(t[o+3]>=1073741824)&&(l[s+3]=E(t,t[o+3],r,i),l[s+7]=E(t,t[o+7],r,i))}return c}function E(e,t,n,r){let i=t*16;return n(t)?w(e[i],e[i+1]):r[t]}const D=_(`bvh`),O=b.TRIANGLE_LEAF,k=b.FRONTIER,A=y.FLOATS_PER_TRIANGLE,j=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length);var M=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},N=class{constructor(){this.useWorker=!0,this.maxLeafSize=8,this.foldLeaves=!1,this.numBins=32,this.minBins=8,this.maxBins=64,this.totalNodes=0,this.processedTriangles=0,this.totalTriangles=0,this.lastProgressUpdate=0,this.progressUpdateInterval=100,this.traversalCost=1,this.intersectionCost=2.5,this.useMortonCodes=!0,this.mortonBits=10,this.mortonClusterThreshold=128,this.enableObjectMedianFallback=!0,this.enableSpatialMedianFallback=!0,this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0},this.enableReinsertionOptimization=!0,this.reinsertionBatchSizeRatio=.02,this.reinsertionMaxIterations=2,this.initializeBinArrays(),this._partResult={mid:0,lMinX:0,lMinY:0,lMinZ:0,lMaxX:0,lMaxY:0,lMaxZ:0,rMinX:0,rMinY:0,rMinZ:0,rMaxX:0,rMaxY:0,rMaxZ:0},this.centroids=null,this.bMin=null,this.bMax=null,this.indices=null,this.mortonCodes=null,this.triangles=null,this.reorderedTriangleData=null}initializeBinArrays(){let e=this.maxBins;this.binBoundsMin=new Float32Array(e*3),this.binBoundsMax=new Float32Array(e*3),this.binCounts=new Uint32Array(e),this.leftPrefixMin=new Float32Array(e*3),this.leftPrefixMax=new Float32Array(e*3),this.leftPrefixCount=new Uint32Array(e),this.rightPrefixMin=new Float32Array(e*3),this.rightPrefixMax=new Float32Array(e*3),this.rightPrefixCount=new Uint32Array(e)}getOptimalBinCount(e){return e<=16?this.minBins:e<=64?16:e<=256?32:e<=1024?48:this.maxBins}setAdaptiveBinConfig(e){e.minBins!==void 0&&(this.minBins=Math.max(4,e.minBins)),e.maxBins!==void 0&&(this.maxBins=Math.min(128,e.maxBins)),e.baseBins!==void 0&&(this.numBins=e.baseBins),e.maxBins!==void 0&&this.initializeBinArrays()}setMortonConfig(e){e.enabled!==void 0&&(this.useMortonCodes=e.enabled),e.bits!==void 0&&(this.mortonBits=Math.max(6,Math.min(10,e.bits))),e.threshold!==void 0&&(this.mortonClusterThreshold=Math.max(16,e.threshold))}setFallbackConfig(e){e.objectMedian!==void 0&&(this.enableObjectMedianFallback=e.objectMedian),e.spatialMedian!==void 0&&(this.enableSpatialMedianFallback=e.spatialMedian)}setReinsertionConfig(e){e.enabled!==void 0&&(this.enableReinsertionOptimization=e.enabled),e.batchSizeRatio!==void 0&&(this.reinsertionBatchSizeRatio=Math.max(.005,Math.min(.1,e.batchSizeRatio))),e.maxIterations!==void 0&&(this.reinsertionMaxIterations=Math.max(1,Math.min(5,e.maxIterations)))}initializeTriangleArrays(){let e=this.totalTriangles,t=j(this.triangles),n=y.POSITION_A_OFFSET,r=y.POSITION_B_OFFSET,i=y.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*A,o=t[e+n],s=t[e+n+1],c=t[e+n+2],l=t[e+r],u=t[e+r+1],d=t[e+r+2],f=t[e+i],p=t[e+i+1],m=t[e+i+2],h=a*3;this.centroids[h]=(o+l+f)/3,this.centroids[h+1]=(s+u+p)/3,this.centroids[h+2]=(c+d+m)/3,this.bMin[h]=o<l?o<f?o:f:l<f?l:f,this.bMin[h+1]=s<u?s<p?s:p:u<p?u:p,this.bMin[h+2]=c<d?c<m?c:m:d<m?d:m,this.bMax[h]=o>l?o>f?o:f:l>f?l:f,this.bMax[h+1]=s>u?s>p?s:p:u>p?u:p,this.bMax[h+2]=c>d?c>m?c:m:d>m?d:m,this.indices[a]=a}}expandBits(e){return e=e*65537&4278190335,e=e*257&251719695,e=e*17&3272356035,e=e*5&1227133513,e}morton3D(e,t,n){return(this.expandBits(n)<<2)+(this.expandBits(t)<<1)+this.expandBits(e)}computeMortonCodeForIndex(e,t,n,r,i,a,o){let s=this.centroids,c=e*3,l=(1<<this.mortonBits)-1,u=i>0?(s[c]-t)/i:0,d=a>0?(s[c+1]-n)/a:0,f=o>0?(s[c+2]-r)/o:0,p=Math.max(0,Math.min(l,Math.floor(u*l))),m=Math.max(0,Math.min(l,Math.floor(d*l))),h=Math.max(0,Math.min(l,Math.floor(f*l)));return this.morton3D(p,m,h)}sortTrianglesByMortonCode(){let e=this.totalTriangles;if(!this.useMortonCodes||e<this.mortonClusterThreshold)return;let t=performance.now(),n=this.centroids,r=this.indices,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let t=0;t<e;t++){let e=r[t]*3,u=n[e],d=n[e+1],f=n[e+2];u<i&&(i=u),d<a&&(a=d),f<o&&(o=f),u>s&&(s=u),d>c&&(c=d),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o,p=this.mortonCodes,m=(1<<this.mortonBits)-1,h=u>0?m/u:0,g=d>0?m/d:0,_=f>0?m/f:0;for(let t=0;t<e;t++){let e=r[t],s=e*3,c=(n[s]-i)*h,l=(n[s+1]-a)*g,u=(n[s+2]-o)*_;c=c<0?0:(c>m?m:c)|0,l=l<0?0:(l>m?m:l)|0,u=u<0?0:(u>m?m:u)|0,c=c*65537&4278190335,c=c*257&251719695,c=c*17&3272356035,c=c*5&1227133513,l=l*65537&4278190335,l=l*257&251719695,l=l*17&3272356035,l=l*5&1227133513,u=u*65537&4278190335,u=u*257&251719695,u=u*17&3272356035,u=u*5&1227133513,p[e]=(u<<2)+(l<<1)+c}let v=new Uint32Array(e),y=new Uint32Array(256);for(let t=0;t<32;t+=8){y.fill(0);for(let n=0;n<e;n++)y[p[r[n]]>>>t&255]++;let n=0;for(let e=0;e<256;e++){let t=y[e];y[e]=n,n+=t}for(let n=0;n<e;n++){let e=p[r[n]]>>>t&255;v[y[e]++]=r[n]}r.set(v)}this.splitStats.mortonSortTime+=performance.now()-t}build(e,t=30,n=null){if(this.totalTriangles=e.byteLength/(A*4),this.processedTriangles=0,this.lastProgressUpdate=performance.now(),!(this.useWorker&&null))return new Promise(r=>{r(this._buildSyncAndFlatten(e,t,n))})}_buildSyncAndFlatten(e,t,n){let r=this.buildSync(e,t,n),i=this.flattenBVH(r);return{bvhData:this.foldLeaves?T(i):i,bvhRoot:!0,reorderedTriangles:this.reorderedTriangleData||null,originalToBvh:this.originalToBvhMap||null}}buildSync(t,n=30,r=null,i=null){let a=performance.now();this.totalNodes=0,this.processedTriangles=0,this.triangles=t,this.totalTriangles=t.byteLength/(A*4),this.lastProgressUpdate=performance.now(),this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0,saOrderTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let o=this.totalTriangles,s=performance.now();this.centroids=new Float32Array(o*3),this.bMin=new Float32Array(o*3),this.bMax=new Float32Array(o*3),this.indices=new Uint32Array(o),this.mortonCodes=new Uint32Array(o),this.initializeTriangleArrays(),this.splitStats.initTime=performance.now()-s,this.sortTrianglesByMortonCode();let c=performance.now(),l=this.buildNodeRecursive(0,o,n,r);if(this.splitStats.sahBuildTime=performance.now()-c,this.enableReinsertionOptimization&&this.totalTriangles>1e3){let t=new e(this.traversalCost,this.intersectionCost);t.setBatchSizeRatio(this.reinsertionBatchSizeRatio),t.setMaxIterations(this.reinsertionMaxIterations);let n=r?e=>{r(e)}:null;try{t.optimizeBVH(l,n)}catch(e){D.error(`reinsertion optimizer failed:`,e)}let i=t.getStatistics();this.splitStats.reinsertionOptimizationTime=i.timeMs,this.splitStats.reinsertionsApplied=i.reinsertionsApplied,this.splitStats.reinsertionIterations=i.iterations}let u=performance.now();this.applySAOrdering(l),this.splitStats.saOrderTime=performance.now()-u;let d=performance.now(),f=this.triangles,p=i||new f.constructor(o*A);for(let e=0;e<o;e++){let t=this.indices[e]*A,n=e*A;p.set(f.subarray(t,t+A),n)}this.reorderedTriangleData=p;let m=new Uint32Array(o);for(let e=0;e<o;e++)m[this.indices[e]]=e;this.originalToBvhMap=m,this.splitStats.reorderTime=performance.now()-d,this.splitStats.totalBuildTime=performance.now()-a;let g=this.splitStats.totalBuildTime,_=this.splitStats;return D.debug(`${h.n(o)} tris → ${h.n(this.totalNodes)} nodes in ${h.ms(g)} | SAH ${_.sahSplits} objMed ${_.objectMedianSplits} spatMed ${_.spatialMedianSplits} failed ${_.failedSplits}`+(_.reinsertionsApplied?` | reinsertions ${_.reinsertionsApplied}`:``)),r&&r(100),this.centroids=null,this.bMin=null,this.bMax=null,this.mortonCodes=null,l}updateProgress(e,t){if(!t)return;this.processedTriangles+=e;let n=performance.now();n-this.lastProgressUpdate<this.progressUpdateInterval||(this.lastProgressUpdate=n,t(Math.min(Math.floor(this.processedTriangles/this.totalTriangles*100),99)))}buildNodeRecursiveToDepth(e,t,n,r,i,a,o,s,c,l,u){let d=new M;this.totalNodes++;let f=t-e;if(a===void 0?this.updateNodeBounds(d,e,t):(d.minX=a,d.minY=o,d.minZ=s,d.maxX=c,d.maxY=l,d.maxZ=u),f<=this.maxLeafSize||n<=0)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;if(r<=0&&f>this.maxLeafSize*16){let r=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=r,this.frontierTasks.push({taskId:r,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}let p=this.findBestSplitPositionSAH(e,t,d);if(!p.success){if(this.splitStats.failedSplits++,r>0||f<=this.maxLeafSize*16)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;let a=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=a,this.frontierTasks.push({taskId:a,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}p.method===`SAH`?this.splitStats.sahSplits++:p.method===`object_median`?this.splitStats.objectMedianSplits++:p.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,p.axis,p.pos);let m=this._partResult,h=m.mid,g=m.lMinX,_=m.lMinY,v=m.lMinZ,y=m.lMaxX,b=m.lMaxY,x=m.lMaxZ,S=m.rMinX,C=m.rMinY,w=m.rMinZ,T=m.rMaxX,E=m.rMaxY,D=m.rMaxZ;return h===e||h===t?(d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d):(d.leftChild=this.buildNodeRecursiveToDepth(e,h,n-1,r-1,i,g,_,v,y,b,x),d.rightChild=this.buildNodeRecursiveToDepth(h,t,n-1,r-1,i,S,C,w,T,E,D),d)}buildNodeRecursive(e,t,n,r,i,a,o,s,c,l){let u=new M;this.totalNodes++;let d=t-e;if(i===void 0?this.updateNodeBounds(u,e,t):(u.minX=i,u.minY=a,u.minZ=o,u.maxX=s,u.maxY=c,u.maxZ=l),d<=this.maxLeafSize||n<=0)return u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;let f=this.findBestSplitPositionSAH(e,t,u);if(!f.success)return this.splitStats.failedSplits++,u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;f.method===`SAH`?this.splitStats.sahSplits++:f.method===`object_median`?this.splitStats.objectMedianSplits++:f.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,f.axis,f.pos);let p=this._partResult,m=p.mid,h=p.lMinX,g=p.lMinY,_=p.lMinZ,v=p.lMaxX,y=p.lMaxY,b=p.lMaxZ,x=p.rMinX,S=p.rMinY,C=p.rMinZ,w=p.rMaxX,T=p.rMaxY,E=p.rMaxZ;return m===e||m===t?(u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u):(u.leftChild=this.buildNodeRecursive(e,m,n-1,r,h,g,_,v,y,b),u.rightChild=this.buildNodeRecursive(m,t,n-1,r,x,S,C,w,T,E),u)}partitionWithBounds(e,t,n,r){let i=this.indices,a=this.centroids,o=this.bMin,s=this.bMax,c=e,l=t-1,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(;c<=l;){let e=i[c],t=e*3;a[t+n]<=r?(o[t]<u&&(u=o[t]),o[t+1]<d&&(d=o[t+1]),o[t+2]<f&&(f=o[t+2]),s[t]>p&&(p=s[t]),s[t+1]>m&&(m=s[t+1]),s[t+2]>h&&(h=s[t+2]),c++):(o[t]<g&&(g=o[t]),o[t+1]<_&&(_=o[t+1]),o[t+2]<v&&(v=o[t+2]),s[t]>y&&(y=s[t]),s[t+1]>b&&(b=s[t+1]),s[t+2]>x&&(x=s[t+2]),i[c]=i[l],i[l]=e,l--)}let S=this._partResult;return S.mid=c,S.lMinX=u,S.lMinY=d,S.lMinZ=f,S.lMaxX=p,S.lMaxY=m,S.lMaxZ=h,S.rMinX=g,S.rMinY=_,S.rMinZ=v,S.rMaxX=y,S.rMaxY=b,S.rMaxZ=x,S}updateNodeBounds(e,t,n){let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0,l=this.indices,u=this.bMin,d=this.bMax;for(let e=t;e<n;e++){let t=l[e]*3;u[t]<r&&(r=u[t]),u[t+1]<i&&(i=u[t+1]),u[t+2]<a&&(a=u[t+2]),d[t]>o&&(o=d[t]),d[t+1]>s&&(s=d[t+1]),d[t+2]>c&&(c=d[t+2])}e.minX=r,e.minY=i,e.minZ=a,e.maxX=o,e.maxY=s,e.maxZ=c}findBestSplitPositionSAH(e,t,n){let r=1/0,i=-1,a=0,o=this.computeSurfaceAreaFlat(n.minX,n.minY,n.minZ,n.maxX,n.maxY,n.maxZ),s=t-e,c=this.intersectionCost*s,l=this.getOptimalBinCount(s);this.splitStats.totalSplitAttempts++,this.splitStats.avgBinsUsed=(this.splitStats.avgBinsUsed*(this.splitStats.totalSplitAttempts-1)+l)/this.splitStats.totalSplitAttempts;let u=this.indices,d=this.centroids,f=this.bMin,p=this.bMax,m=this.binBoundsMin,h=this.binBoundsMax,g=this.binCounts,_=this.leftPrefixMin,v=this.leftPrefixMax,y=this.leftPrefixCount,b=this.rightPrefixMin,x=this.rightPrefixMax,S=this.rightPrefixCount,C=1/0,w=-1/0,T=1/0,E=-1/0,D=1/0,O=-1/0;for(let n=e;n<t;n++){let e=u[n]*3,t=d[e],r=d[e+1],i=d[e+2];t<C&&(C=t),t>w&&(w=t),r<T&&(T=r),r>E&&(E=r),i<D&&(D=i),i>O&&(O=i)}let k=[C,T,D],A=[w,E,O];for(let n=0;n<3;n++){let s=k[n],C=A[n];if(C-s<1e-6)continue;for(let e=0;e<l;e++){g[e]=0;let t=e*3;m[t]=1/0,m[t+1]=1/0,m[t+2]=1/0,h[t]=-1/0,h[t+1]=-1/0,h[t+2]=-1/0}let w=l/(C-s);for(let r=e;r<t;r++){let e=u[r],t=d[e*3+n],i=Math.floor((t-s)*w);i>=l&&(i=l-1),g[i]++;let a=i*3,o=e*3;f[o]<m[a]&&(m[a]=f[o]),f[o+1]<m[a+1]&&(m[a+1]=f[o+1]),f[o+2]<m[a+2]&&(m[a+2]=f[o+2]),p[o]>h[a]&&(h[a]=p[o]),p[o+1]>h[a+1]&&(h[a+1]=p[o+1]),p[o+2]>h[a+2]&&(h[a+2]=p[o+2])}y[0]=g[0],_[0]=m[0],_[1]=m[1],_[2]=m[2],v[0]=h[0],v[1]=h[1],v[2]=h[2];for(let e=1;e<l;e++){let t=e*3,n=(e-1)*3;y[e]=y[e-1]+g[e];let r=_[n],i=m[t],a=_[n+1],o=m[t+1],s=_[n+2],c=m[t+2];_[t]=r<i?r:i,_[t+1]=a<o?a:o,_[t+2]=s<c?s:c;let l=v[n],u=h[t],d=v[n+1],f=h[t+1],p=v[n+2],b=h[t+2];v[t]=l>u?l:u,v[t+1]=d>f?d:f,v[t+2]=p>b?p:b}let T=l-1,E=T*3;S[T]=g[T],b[E]=m[E],b[E+1]=m[E+1],b[E+2]=m[E+2],x[E]=h[E],x[E+1]=h[E+1],x[E+2]=h[E+2];for(let e=T-1;e>=0;e--){let t=e*3,n=(e+1)*3;S[e]=S[e+1]+g[e];let r=b[n],i=m[t],a=b[n+1],o=m[t+1],s=b[n+2],c=m[t+2];b[t]=r<i?r:i,b[t+1]=a<o?a:o,b[t+2]=s<c?s:c;let l=x[n],u=h[t],d=x[n+1],f=h[t+1],p=x[n+2],_=h[t+2];x[t]=l>u?l:u,x[t+1]=d>f?d:f,x[t+2]=p>_?p:_}for(let e=1;e<l;e++){let t=(e-1)*3,u=e*3,d=y[e-1],f=S[e];if(d===0||f===0)continue;let p=v[t]-_[t],m=v[t+1]-_[t+1],h=v[t+2]-_[t+2],g=2*(p*m+m*h+h*p),w=x[u]-b[u],T=x[u+1]-b[u+1],E=x[u+2]-b[u+2],D=2*(w*T+T*E+E*w),O=this.traversalCost+g/o*d*this.intersectionCost+D/o*f*this.intersectionCost;O<r&&O<c&&(r=O,i=n,a=s+(C-s)*e/l)}}return i===-1?this.enableObjectMedianFallback?this.findObjectMedianSplit(e,t):this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`fallbacks_disabled`}:{success:!0,axis:i,pos:a,method:`SAH`,binsUsed:l}}findObjectMedianSplit(e,t){let n=this.indices,r=this.centroids,i=-1,a=-1;for(let o=0;o<3;o++){let s=1/0,c=-1/0;for(let i=e;i<t;i++){let e=r[n[i]*3+o];e<s&&(s=e),e>c&&(c=e)}let l=c-s;l>a&&(a=l,i=o)}if(i===-1||a<1e-10)return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_failed`};let o=t-e,s=e+Math.floor(o/2);this.quickselect(e,t,s,i);let c=r[n[s]*3+i],l=!0;for(let e=s+1;e<t;e++)if(r[n[e]*3+i]>c){l=!1;break}if(l){let a=-1/0;for(let t=e;t<s;t++){let e=r[n[t]*3+i];e>a&&(a=e)}if(a<c)c=(a+c)*.5;else return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_degenerate`}}return{success:!0,axis:i,pos:c,method:`object_median`}}findSpatialMedianSplit(e,t){let n=this.indices,r=this.centroids,i=this.bMin,a=this.bMax,o=-1,s=-1,c=0,l=0;for(let r=0;r<3;r++){let u=1/0,d=-1/0;for(let o=e;o<t;o++){let e=n[o]*3+r;i[e]<u&&(u=i[e]),a[e]>d&&(d=a[e])}let f=d-u;f>s&&(s=f,o=r,c=u,l=d)}if(o===-1||s<1e-12)return{success:!1,method:`spatial_median_failed`};let u=(c+l)*.5,d=t-e,f=0;for(let i=e;i<t;i++)r[n[i]*3+o]<=u&&f++;if(f===0||f===d){let i=e+Math.floor(d/2);this.quickselect(e,t,i,o);let a=r[n[i]*3+o],s=!0;for(let i=e;i<t;i++)if(r[n[i]*3+o]!==a){s=!1;break}if(s)return{success:!1,method:`spatial_median_degenerate`};let c=-1/0;for(let t=e;t<i;t++){let e=r[n[t]*3+o];e>c&&(c=e)}if(c<a)u=(c+a)*.5;else{let e=1/0;for(let a=i+1;a<t;a++){let t=r[n[a]*3+o];t<e&&(e=t)}u=(a+e)*.5}}return{success:!0,axis:o,pos:u,method:`spatial_median`}}quickselect(e,t,n,r){let i=this.indices,a=this.centroids,o=e,s=t-1;for(;o<s;){let e=o+s>>>1,t=a[i[o]*3+r],c=a[i[e]*3+r],l=a[i[s]*3+r];if(t>c){let t=i[o];i[o]=i[e],i[e]=t}if(t>l){let e=i[o];i[o]=i[s],i[s]=e}if(c>l){let t=i[e];i[e]=i[s],i[s]=t}let u=a[i[e]*3+r],d=o,f=s;for(;d<=f;){for(;a[i[d]*3+r]<u;)d++;for(;a[i[f]*3+r]>u;)f--;if(d<=f){let e=i[d];i[d]=i[f],i[f]=e,d++,f--}}f<n&&(o=d),d>n&&(s=f)}}applySAOrdering(e){if(!e||!e.leftChild)return;let t=[e],n=[];for(;t.length>0;){let e=t.pop();!e.leftChild||!e.rightChild||(n.push(e),t.push(e.leftChild),t.push(e.rightChild))}for(let e=n.length-1;e>=0;e--){let t=n[e],r=t.leftChild,i=t.rightChild,a=r.maxX-r.minX,o=r.maxY-r.minY,s=r.maxZ-r.minZ,c=i.maxX-i.minX,l=i.maxY-i.minY,u=i.maxZ-i.minZ;c*l+l*u+u*c>a*o+o*s+s*a&&(t.leftChild=i,t.rightChild=r)}}flattenBVH(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}S(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=x(r);for(let e=0;e<t.length;e++){let n=t[e],a=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[a]=e.minX,r[a+1]=e.minY,r[a+2]=e.minZ,i[a+3]=e._flatIndex,r[a+4]=e.maxX,r[a+5]=e.maxY,r[a+6]=e.maxZ,i[a+7]=t._flatIndex,r[a+8]=t.minX,r[a+9]=t.minY,r[a+10]=t.minZ,r[a+12]=t.maxX,r[a+13]=t.maxY,r[a+14]=t.maxZ}else i[a]=n.triangleOffset,i[a+1]=n.triangleCount,i[a+3]=O}return r}flattenBVHWithFrontier(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}S(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=[],a=x(r);for(let e=0;e<t.length;e++){let n=t[e],o=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[o]=e.minX,r[o+1]=e.minY,r[o+2]=e.minZ,a[o+3]=e._flatIndex,r[o+4]=e.maxX,r[o+5]=e.maxY,r[o+6]=e.maxZ,a[o+7]=t._flatIndex,r[o+8]=t.minX,r[o+9]=t.minY,r[o+10]=t.minZ,r[o+12]=t.maxX,r[o+13]=t.maxY,r[o+14]=t.maxZ}else if(n.isFrontier){let t=n.frontierTaskId;a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+2]=t,a[o+3]=k,i.push({taskId:t,flatIndex:e})}else a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+3]=O}return{flatData:r,frontierMap:i,nodeCount:t.length}}assembleParallelBVH(e,t,n,r){let i=[...r].sort((e,t)=>e.taskId-t.taskId),a=t;for(let e=0;e<i.length;e++)a+=i[e].nodeCount;S(a,`assembled BLAS node count`);let o=new Float32Array(a*16),s=x(o);o.set(e);let c=new Map;for(let e of n)c.set(e.taskId,e.flatIndex);let l=t;for(let e=0;e<i.length;e++){let t=i[e],n=t.flatData,r=t.nodeCount,a=l*16;o.set(n,a);for(let e=0;e<r;e++){let t=a+e*16;s[t+3]<O&&(s[t+3]+=l,s[t+7]+=l)}let u=c.get(t.taskId);if(u!==void 0){let e=u*16,t=a;for(let n=0;n<16;n++)o[e+n]=o[t+n]}l+=r}return o}computeSurfaceAreaFlat(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 P=_(`bvh`);self.onmessage=function(e){let t=e.data,n=t.type;v(t.logLevel),n===`buildPhase1`?F(t):n===`assemble`?I(t):L(t)};function F(e){let{sharedTriangleData:t,sharedCentroids:n,sharedBMin:r,sharedBMax:i,sharedIndices:a,sharedMortonCodes:o,triangleCount:s,depth:c,parallelDepth:l,reportProgress:u}=e;try{let e=new N,d=u?e=>{self.postMessage({type:`progress`,progress:e})}:null;e.triangles=new Uint32Array(t),e.centroids=new Float32Array(n),e.bMin=new Float32Array(r),e.bMax=new Float32Array(i),e.indices=new Uint32Array(a),e.mortonCodes=new Uint32Array(o),e.totalTriangles=s,e.totalNodes=0,e.processedTriangles=0,e.lastProgressUpdate=performance.now(),e.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let f=performance.now(),p=performance.now();e.initializeTriangleArrays(),e.splitStats.initTime=performance.now()-p,e.sortTrianglesByMortonCode(),e.frontierTasks=[];let m=performance.now(),g=e.buildNodeRecursiveToDepth(0,s,c,l,d);e.splitStats.sahBuildTime=performance.now()-m,e.applySAOrdering(g);let _=performance.now(),{flatData:v,frontierMap:y,nodeCount:b}=e.flattenBVHWithFrontier(g),x=performance.now()-_,S=performance.now()-f;P.debug(`phase 1 ${h.ms(S)} (init ${h.ms(e.splitStats.initTime)} · morton ${h.ms(e.splitStats.mortonSortTime)} · SAH ${h.ms(e.splitStats.sahBuildTime)} · flatten ${h.ms(x)}) · ${e.frontierTasks.length} frontier tasks`),self.postMessage({type:`phase1Result`,topFlatData:v,topNodeCount:b,frontierTasks:e.frontierTasks,frontierMap:y,splitStats:e.splitStats},[v.buffer])}catch(e){P.error(`phase 1 failed:`,e),self.postMessage({type:`error`,error:e.message})}}function I(e){let{topFlatData:t,topNodeCount:n,frontierMap:r,subtreeResults:i,sharedTriangleData:a,sharedIndices:o,sharedReorderBuffer:s,triangleCount:c,foldLeaves:l}=e;try{let e=performance.now(),u=new N().assembleParallelBVH(t,n,r,i),d=l?T(u):u,f=new Uint32Array(o);if(s){let e=new Uint32Array(a),t=new Uint32Array(s);for(let n=0;n<c;n++){let r=f[n]*20,i=n*20;t.set(e.subarray(r,r+20),i)}}let p=new Uint32Array(c);for(let e=0;e<c;e++)p[f[e]]=e;let m=performance.now()-e;P.debug(`phase 3 assemble + reorder ${h.ms(m)} (${h.mb(d.byteLength)} BVH)`),self.postMessage({type:`assembleResult`,bvhData:d,originalToBvh:p,triangleCount:c},[d.buffer,p.buffer])}catch(e){P.error(`assembly failed:`,e),self.postMessage({type:`error`,error:e.message})}}function L(e){let{triangleData:t,triangleByteOffset:n,triangleByteLength:r,depth:i,reportProgress:a,reinsertionOptimization:o,sharedReorderBuffer:s,maxLeafSize:c,numBins:l,maxBins:u,minBins:d,foldLeaves:f}=e,p=new N;c!==void 0&&(p.maxLeafSize=c),l!==void 0&&(p.numBins=l),u!==void 0&&(p.maxBins=u),d!==void 0&&(p.minBins=d);try{o&&p.setReinsertionConfig(o);let e=a?e=>{self.postMessage({progress:e})}:null,c=n===void 0?new Uint32Array(t):new Uint32Array(t,n,r/4),l=s?new Uint32Array(s):null,u=p.buildSync(c,i,e,l),d=performance.now(),m=p.flattenBVH(u),g=f?T(m):m,_=performance.now()-d;P.debug(`flatten ${h.ms(_)} (${h.mb(g.byteLength)})`);let v=p.originalToBvhMap||null;if(s){let e=[g.buffer];v&&e.push(v.buffer),self.postMessage({bvhData:g,originalToBvh:v,triangleCount:c.length/20,splitStats:p.splitStats},e)}else{let e=p.reorderedTriangleData,t=e.byteLength/80,n=[g.buffer,e.buffer];v&&n.push(v.buffer),self.postMessage({bvhData:g,triangles:e,originalToBvh:v,triangleCount:t,splitStats:p.splitStats},n)}}catch(e){P.error(`build failed:`,e),self.postMessage({error:e.message})}}",Ji=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,qi],{type:`text/javascript;charset=utf-8`});function Yi(e){let t;try{if(t=Ji&&(self.URL||self.webkitURL).createObjectURL(Ji),!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(qi),{type:`module`,name:e?.name})}}var Xi="var e=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.batchSizeRatio=.02,this.maxIterations=2,this.timeBudgetMs=15e3,this.stats={reinsertionsApplied:0,iterations:0,timeMs:0}}setBatchSizeRatio(e){this.batchSizeRatio=Math.max(.005,Math.min(.1,e))}setMaxIterations(e){this.maxIterations=Math.max(1,Math.min(5,e))}getStatistics(){return{...this.stats}}surfaceArea(e){let t=e.maxX-e.minX,n=e.maxY-e.minY,r=e.maxZ-e.minZ;return t*n+n*r+r*t}buildParentMap(e){let t=new Map;t.set(e,{parent:null,isLeft:!1});let n=[e];for(;n.length>0;){let e=n.pop();e.triangleCount>0||(e.leftChild&&(t.set(e.leftChild,{parent:e,isLeft:!0}),n.push(e.leftChild)),e.rightChild&&(t.set(e.rightChild,{parent:e,isLeft:!1}),n.push(e.rightChild)))}return t}findCandidates(e,t,n){let r=[],i=[e];for(;i.length>0;){let a=i.pop();if(a!==e&&n.get(a).parent!==e){let e=this.surfaceArea(a);r.length<t?(r.push({node:a,cost:e}),r.length===t&&this._heapify(r)):e>r[0].cost&&(r[0]={node:a,cost:e},this._siftDown(r,0))}a.triangleCount===0&&(a.leftChild&&i.push(a.leftChild),a.rightChild&&i.push(a.rightChild))}return r}_heapify(e){for(let t=(e.length>>1)-1;t>=0;t--)this._siftDown(e,t)}_siftDown(e,t){let n=e.length;for(;;){let r=t,i=2*t+1,a=2*t+2;if(i<n&&e[i].cost<e[r].cost&&(r=i),a<n&&e[a].cost<e[r].cost&&(r=a),r===t)break;let o=e[t];e[t]=e[r],e[r]=o,t=r}}findReinsertion(e,t,n){let r=n.get(e),i=r.parent;if(!i)return null;let a=r.isLeft?i.rightChild:i.leftChild,o=this.surfaceArea(e),s=this.surfaceArea(i),c=null,l=0,u=s,d=a.minX,f=a.minY,p=a.minZ,m=a.maxX,h=a.maxY,g=a.maxZ,_=a,v=i,y=[];do{for(y.length=0,y.push(u,_);y.length>0;){let t=y.pop(),n=y.pop();if(n-o<=l)continue;let r=Math.min(t.minX,e.minX),i=Math.min(t.minY,e.minY),a=Math.min(t.minZ,e.minZ),s=Math.max(t.maxX,e.maxX),u=Math.max(t.maxY,e.maxY),d=Math.max(t.maxZ,e.maxZ),f=s-r,p=u-i,m=d-a,h=n-(f*p+p*m+m*f);if(h>l&&(c=t,l=h),t.triangleCount===0&&t.leftChild&&t.rightChild){let e=h+this.surfaceArea(t);y.push(e,t.leftChild),y.push(e,t.rightChild)}}let t=n.get(v);if(!t||t.parent===null)break;if(v!==i){d=Math.min(d,_.minX),f=Math.min(f,_.minY),p=Math.min(p,_.minZ),m=Math.max(m,_.maxX),h=Math.max(h,_.maxY),g=Math.max(g,_.maxZ);let e=m-d,t=h-f,n=g-p,r=e*t+t*n+n*e;u+=this.surfaceArea(v)-r}let r=t.parent;_=t.isLeft?r.rightChild:r.leftChild,v=r}while(n.get(v).parent!==null);return c===a||c===i?null:c?{from:e,to:c,areaDiff:l}:null}getConflicts(e,t,n){let r=n.get(e);return[t,e,r.isLeft?r.parent.rightChild:r.parent.leftChild,n.get(t).parent,r.parent]}reinsertNode(e,t,n){let r=n.get(e),i=r.parent,a=r.isLeft?i.rightChild:i.leftChild,o=n.get(i),s=o.parent,c=n.get(t),l=c.parent;o.isLeft?s.leftChild=a:s.rightChild=a,i.leftChild=e,i.rightChild=t,i.triangleOffset=0,i.triangleCount=0,i.minX=Math.min(e.minX,t.minX),i.minY=Math.min(e.minY,t.minY),i.minZ=Math.min(e.minZ,t.minZ),i.maxX=Math.max(e.maxX,t.maxX),i.maxY=Math.max(e.maxY,t.maxY),i.maxZ=Math.max(e.maxZ,t.maxZ),c.isLeft?l.leftChild=i:l.rightChild=i,n.set(a,{parent:s,isLeft:o.isLeft}),n.set(i,{parent:l,isLeft:c.isLeft}),n.set(e,{parent:i,isLeft:!0}),n.set(t,{parent:i,isLeft:!1}),this.refitFrom(s,n),this.refitFrom(l,n)}refitFrom(e,t){let n=e;for(;n;){if(n.triangleCount===0&&n.leftChild&&n.rightChild){let e=n.leftChild,t=n.rightChild;n.minX=Math.min(e.minX,t.minX),n.minY=Math.min(e.minY,t.minY),n.minZ=Math.min(e.minZ,t.minZ),n.maxX=Math.max(e.maxX,t.maxX),n.maxY=Math.max(e.maxY,t.maxY),n.maxZ=Math.max(e.maxZ,t.maxZ)}let e=t.get(n);n=e?e.parent:null}}optimizeBVH(e,t){let n=performance.now();this.stats={reinsertionsApplied:0,iterations:0,timeMs:0};for(let r=0;r<this.maxIterations&&!(performance.now()-n>this.timeBudgetMs);r++){let i=this.buildParentMap(e),a=i.size,o=Math.max(1,Math.floor(a*this.batchSizeRatio));t&&t(`Reinsertion iter ${r+1}/${this.maxIterations}: selecting ${o} candidates`);let s=this.findCandidates(e,o,i),c=[];for(let t=0;t<s.length&&!(performance.now()-n>this.timeBudgetMs);t++){let n=this.findReinsertion(s[t].node,e,i);n&&n.areaDiff>0&&c.push(n)}c.sort((e,t)=>t.areaDiff-e.areaDiff);let l=new Set,u=0;for(let e of c){let t=this.getConflicts(e.from,e.to,i);if(!t.some(e=>l.has(e))){for(let e of t)l.add(e);this.reinsertNode(e.from,e.to,i),u++}}if(this.stats.reinsertionsApplied+=u,this.stats.iterations=r+1,t&&t(`Reinsertion iter ${r+1}: applied ${u} reinsertions`),u===0)break}return this.stats.timeMs=performance.now()-n,this.stats}};const t={silent:0,error:1,warn:2,info:3,debug:4},n=`info`,r=`rayzeeLogLevel`,i=`rayzeeLogNamespaces`,a=`color:#7c8494`,o=`color:inherit`;let s=null,c=null;function l(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function u(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function d(){if(s!==null)return s;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in t?(s=t[e],s):(s=t[l(r)]??t[n],s)}function f(){if(c!==null)return c;let e=globalThis.__RAYZEE_LOG_NS__??l(i);return c=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],c}function p(e,n){if(n<t.debug)return!0;let r=f();return r.length===0||r.some(t=>e===t||e.startsWith(`${t}:`))}function m(e,n,r){if(e>d()||!p(n,e))return;let i=e===t.error?console.error:e===t.warn?console.warn:console.log,s=`[${n}]`;typeof r[0]==`string`?i(`%c${s}%c ${r[0]}`,a,o,...r.slice(1)):i(`%c${s}`,a,...r)}const h={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`)=>`${h.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},g={levels:t,setLevel(e){return e in t?(globalThis.__RAYZEE_LOG_LEVEL__=e,s=t[e],u(r,e===n?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(t).join(`, `)}`),this.getLevel())},getLevel(){let e=d();return Object.keys(t).find(n=>t[n]===e)},isEnabled(e){return(t[e]??t.debug)<=d()},only(...e){let t=e.flat().filter(Boolean);return c=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),u(i,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return s=null,c=null,this.getLevel()}};function _(e){return{namespace:e,error:(...n)=>m(t.error,e,n),warn:(...n)=>m(t.warn,e,n),info:(...n)=>m(t.info,e,n),debug:(...n)=>m(t.debug,e,n),isEnabled:e=>g.isEnabled(e),summary(n,r=[]){let i=r.filter(Boolean);if(i.length===0||!console.groupCollapsed){m(t.info,e,[n]),i.forEach(n=>m(t.debug,e,[n]));return}t.info>d()||((d()>=t.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${n}`,a,o),i.forEach(e=>console.log(e)),console.groupEnd())}}}const v={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},y={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826};function b(e){return new Uint32Array(e.buffer,e.byteOffset,e.length)}function x(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 S=y.TRIANGLE_LEAF,C=(e,t)=>~(e<<4|t)>>>0;function w(e){let t=new Uint32Array(e.buffer,e.byteOffset,e.length),n=e.length/16,r=e=>{let n=e*16;return t[n+3]===S&&t[n+1]>0&&t[n+1]<=15},i=new Uint32Array(n),a=new Uint32Array(n),o=0,s=[0];for(;s.length;){let e=s.pop();i[e]=o,a[o++]=e;let n=e*16;t[n+3]>=1073741824||(r(t[n+7])||s.push(t[n+7]),r(t[n+3])||s.push(t[n+3]))}let c=new Float32Array(o*16),l=new Uint32Array(c.buffer);for(let n=0;n<o;n++){let o=a[n]*16,s=n*16;c.set(e.subarray(o,o+16),s),!(t[o+3]>=1073741824)&&(l[s+3]=T(t,t[o+3],r,i),l[s+7]=T(t,t[o+7],r,i))}return c}function T(e,t,n,r){let i=t*16;return n(t)?C(e[i],e[i+1]):r[t]}const E=_(`bvh`),D=y.TRIANGLE_LEAF,O=y.FRONTIER,k=v.FLOATS_PER_TRIANGLE,A=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length);var j=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},M=class{constructor(){this.useWorker=!0,this.maxLeafSize=8,this.foldLeaves=!1,this.numBins=32,this.minBins=8,this.maxBins=64,this.totalNodes=0,this.processedTriangles=0,this.totalTriangles=0,this.lastProgressUpdate=0,this.progressUpdateInterval=100,this.traversalCost=1,this.intersectionCost=2.5,this.useMortonCodes=!0,this.mortonBits=10,this.mortonClusterThreshold=128,this.enableObjectMedianFallback=!0,this.enableSpatialMedianFallback=!0,this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0},this.enableReinsertionOptimization=!0,this.reinsertionBatchSizeRatio=.02,this.reinsertionMaxIterations=2,this.initializeBinArrays(),this._partResult={mid:0,lMinX:0,lMinY:0,lMinZ:0,lMaxX:0,lMaxY:0,lMaxZ:0,rMinX:0,rMinY:0,rMinZ:0,rMaxX:0,rMaxY:0,rMaxZ:0},this.centroids=null,this.bMin=null,this.bMax=null,this.indices=null,this.mortonCodes=null,this.triangles=null,this.reorderedTriangleData=null}initializeBinArrays(){let e=this.maxBins;this.binBoundsMin=new Float32Array(e*3),this.binBoundsMax=new Float32Array(e*3),this.binCounts=new Uint32Array(e),this.leftPrefixMin=new Float32Array(e*3),this.leftPrefixMax=new Float32Array(e*3),this.leftPrefixCount=new Uint32Array(e),this.rightPrefixMin=new Float32Array(e*3),this.rightPrefixMax=new Float32Array(e*3),this.rightPrefixCount=new Uint32Array(e)}getOptimalBinCount(e){return e<=16?this.minBins:e<=64?16:e<=256?32:e<=1024?48:this.maxBins}setAdaptiveBinConfig(e){e.minBins!==void 0&&(this.minBins=Math.max(4,e.minBins)),e.maxBins!==void 0&&(this.maxBins=Math.min(128,e.maxBins)),e.baseBins!==void 0&&(this.numBins=e.baseBins),e.maxBins!==void 0&&this.initializeBinArrays()}setMortonConfig(e){e.enabled!==void 0&&(this.useMortonCodes=e.enabled),e.bits!==void 0&&(this.mortonBits=Math.max(6,Math.min(10,e.bits))),e.threshold!==void 0&&(this.mortonClusterThreshold=Math.max(16,e.threshold))}setFallbackConfig(e){e.objectMedian!==void 0&&(this.enableObjectMedianFallback=e.objectMedian),e.spatialMedian!==void 0&&(this.enableSpatialMedianFallback=e.spatialMedian)}setReinsertionConfig(e){e.enabled!==void 0&&(this.enableReinsertionOptimization=e.enabled),e.batchSizeRatio!==void 0&&(this.reinsertionBatchSizeRatio=Math.max(.005,Math.min(.1,e.batchSizeRatio))),e.maxIterations!==void 0&&(this.reinsertionMaxIterations=Math.max(1,Math.min(5,e.maxIterations)))}initializeTriangleArrays(){let e=this.totalTriangles,t=A(this.triangles),n=v.POSITION_A_OFFSET,r=v.POSITION_B_OFFSET,i=v.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*k,o=t[e+n],s=t[e+n+1],c=t[e+n+2],l=t[e+r],u=t[e+r+1],d=t[e+r+2],f=t[e+i],p=t[e+i+1],m=t[e+i+2],h=a*3;this.centroids[h]=(o+l+f)/3,this.centroids[h+1]=(s+u+p)/3,this.centroids[h+2]=(c+d+m)/3,this.bMin[h]=o<l?o<f?o:f:l<f?l:f,this.bMin[h+1]=s<u?s<p?s:p:u<p?u:p,this.bMin[h+2]=c<d?c<m?c:m:d<m?d:m,this.bMax[h]=o>l?o>f?o:f:l>f?l:f,this.bMax[h+1]=s>u?s>p?s:p:u>p?u:p,this.bMax[h+2]=c>d?c>m?c:m:d>m?d:m,this.indices[a]=a}}expandBits(e){return e=e*65537&4278190335,e=e*257&251719695,e=e*17&3272356035,e=e*5&1227133513,e}morton3D(e,t,n){return(this.expandBits(n)<<2)+(this.expandBits(t)<<1)+this.expandBits(e)}computeMortonCodeForIndex(e,t,n,r,i,a,o){let s=this.centroids,c=e*3,l=(1<<this.mortonBits)-1,u=i>0?(s[c]-t)/i:0,d=a>0?(s[c+1]-n)/a:0,f=o>0?(s[c+2]-r)/o:0,p=Math.max(0,Math.min(l,Math.floor(u*l))),m=Math.max(0,Math.min(l,Math.floor(d*l))),h=Math.max(0,Math.min(l,Math.floor(f*l)));return this.morton3D(p,m,h)}sortTrianglesByMortonCode(){let e=this.totalTriangles;if(!this.useMortonCodes||e<this.mortonClusterThreshold)return;let t=performance.now(),n=this.centroids,r=this.indices,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let t=0;t<e;t++){let e=r[t]*3,u=n[e],d=n[e+1],f=n[e+2];u<i&&(i=u),d<a&&(a=d),f<o&&(o=f),u>s&&(s=u),d>c&&(c=d),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o,p=this.mortonCodes,m=(1<<this.mortonBits)-1,h=u>0?m/u:0,g=d>0?m/d:0,_=f>0?m/f:0;for(let t=0;t<e;t++){let e=r[t],s=e*3,c=(n[s]-i)*h,l=(n[s+1]-a)*g,u=(n[s+2]-o)*_;c=c<0?0:(c>m?m:c)|0,l=l<0?0:(l>m?m:l)|0,u=u<0?0:(u>m?m:u)|0,c=c*65537&4278190335,c=c*257&251719695,c=c*17&3272356035,c=c*5&1227133513,l=l*65537&4278190335,l=l*257&251719695,l=l*17&3272356035,l=l*5&1227133513,u=u*65537&4278190335,u=u*257&251719695,u=u*17&3272356035,u=u*5&1227133513,p[e]=(u<<2)+(l<<1)+c}let v=new Uint32Array(e),y=new Uint32Array(256);for(let t=0;t<32;t+=8){y.fill(0);for(let n=0;n<e;n++)y[p[r[n]]>>>t&255]++;let n=0;for(let e=0;e<256;e++){let t=y[e];y[e]=n,n+=t}for(let n=0;n<e;n++){let e=p[r[n]]>>>t&255;v[y[e]++]=r[n]}r.set(v)}this.splitStats.mortonSortTime+=performance.now()-t}build(e,t=30,n=null){if(this.totalTriangles=e.byteLength/(k*4),this.processedTriangles=0,this.lastProgressUpdate=performance.now(),!(this.useWorker&&null))return new Promise(r=>{r(this._buildSyncAndFlatten(e,t,n))})}_buildSyncAndFlatten(e,t,n){let r=this.buildSync(e,t,n),i=this.flattenBVH(r);return{bvhData:this.foldLeaves?w(i):i,bvhRoot:!0,reorderedTriangles:this.reorderedTriangleData||null,originalToBvh:this.originalToBvhMap||null}}buildSync(t,n=30,r=null,i=null){let a=performance.now();this.totalNodes=0,this.processedTriangles=0,this.triangles=t,this.totalTriangles=t.byteLength/(k*4),this.lastProgressUpdate=performance.now(),this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0,saOrderTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let o=this.totalTriangles,s=performance.now();this.centroids=new Float32Array(o*3),this.bMin=new Float32Array(o*3),this.bMax=new Float32Array(o*3),this.indices=new Uint32Array(o),this.mortonCodes=new Uint32Array(o),this.initializeTriangleArrays(),this.splitStats.initTime=performance.now()-s,this.sortTrianglesByMortonCode();let c=performance.now(),l=this.buildNodeRecursive(0,o,n,r);if(this.splitStats.sahBuildTime=performance.now()-c,this.enableReinsertionOptimization&&this.totalTriangles>1e3){let t=new e(this.traversalCost,this.intersectionCost);t.setBatchSizeRatio(this.reinsertionBatchSizeRatio),t.setMaxIterations(this.reinsertionMaxIterations);let n=r?e=>{r(e)}:null;try{t.optimizeBVH(l,n)}catch(e){E.error(`reinsertion optimizer failed:`,e)}let i=t.getStatistics();this.splitStats.reinsertionOptimizationTime=i.timeMs,this.splitStats.reinsertionsApplied=i.reinsertionsApplied,this.splitStats.reinsertionIterations=i.iterations}let u=performance.now();this.applySAOrdering(l),this.splitStats.saOrderTime=performance.now()-u;let d=performance.now(),f=this.triangles,p=i||new f.constructor(o*k);for(let e=0;e<o;e++){let t=this.indices[e]*k,n=e*k;p.set(f.subarray(t,t+k),n)}this.reorderedTriangleData=p;let m=new Uint32Array(o);for(let e=0;e<o;e++)m[this.indices[e]]=e;this.originalToBvhMap=m,this.splitStats.reorderTime=performance.now()-d,this.splitStats.totalBuildTime=performance.now()-a;let g=this.splitStats.totalBuildTime,_=this.splitStats;return E.debug(`${h.n(o)} tris → ${h.n(this.totalNodes)} nodes in ${h.ms(g)} | SAH ${_.sahSplits} objMed ${_.objectMedianSplits} spatMed ${_.spatialMedianSplits} failed ${_.failedSplits}`+(_.reinsertionsApplied?` | reinsertions ${_.reinsertionsApplied}`:``)),r&&r(100),this.centroids=null,this.bMin=null,this.bMax=null,this.mortonCodes=null,l}updateProgress(e,t){if(!t)return;this.processedTriangles+=e;let n=performance.now();n-this.lastProgressUpdate<this.progressUpdateInterval||(this.lastProgressUpdate=n,t(Math.min(Math.floor(this.processedTriangles/this.totalTriangles*100),99)))}buildNodeRecursiveToDepth(e,t,n,r,i,a,o,s,c,l,u){let d=new j;this.totalNodes++;let f=t-e;if(a===void 0?this.updateNodeBounds(d,e,t):(d.minX=a,d.minY=o,d.minZ=s,d.maxX=c,d.maxY=l,d.maxZ=u),f<=this.maxLeafSize||n<=0)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;if(r<=0&&f>this.maxLeafSize*16){let r=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=r,this.frontierTasks.push({taskId:r,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}let p=this.findBestSplitPositionSAH(e,t,d);if(!p.success){if(this.splitStats.failedSplits++,r>0||f<=this.maxLeafSize*16)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;let a=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=a,this.frontierTasks.push({taskId:a,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}p.method===`SAH`?this.splitStats.sahSplits++:p.method===`object_median`?this.splitStats.objectMedianSplits++:p.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,p.axis,p.pos);let m=this._partResult,h=m.mid,g=m.lMinX,_=m.lMinY,v=m.lMinZ,y=m.lMaxX,b=m.lMaxY,x=m.lMaxZ,S=m.rMinX,C=m.rMinY,w=m.rMinZ,T=m.rMaxX,E=m.rMaxY,D=m.rMaxZ;return h===e||h===t?(d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d):(d.leftChild=this.buildNodeRecursiveToDepth(e,h,n-1,r-1,i,g,_,v,y,b,x),d.rightChild=this.buildNodeRecursiveToDepth(h,t,n-1,r-1,i,S,C,w,T,E,D),d)}buildNodeRecursive(e,t,n,r,i,a,o,s,c,l){let u=new j;this.totalNodes++;let d=t-e;if(i===void 0?this.updateNodeBounds(u,e,t):(u.minX=i,u.minY=a,u.minZ=o,u.maxX=s,u.maxY=c,u.maxZ=l),d<=this.maxLeafSize||n<=0)return u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;let f=this.findBestSplitPositionSAH(e,t,u);if(!f.success)return this.splitStats.failedSplits++,u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;f.method===`SAH`?this.splitStats.sahSplits++:f.method===`object_median`?this.splitStats.objectMedianSplits++:f.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,f.axis,f.pos);let p=this._partResult,m=p.mid,h=p.lMinX,g=p.lMinY,_=p.lMinZ,v=p.lMaxX,y=p.lMaxY,b=p.lMaxZ,x=p.rMinX,S=p.rMinY,C=p.rMinZ,w=p.rMaxX,T=p.rMaxY,E=p.rMaxZ;return m===e||m===t?(u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u):(u.leftChild=this.buildNodeRecursive(e,m,n-1,r,h,g,_,v,y,b),u.rightChild=this.buildNodeRecursive(m,t,n-1,r,x,S,C,w,T,E),u)}partitionWithBounds(e,t,n,r){let i=this.indices,a=this.centroids,o=this.bMin,s=this.bMax,c=e,l=t-1,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(;c<=l;){let e=i[c],t=e*3;a[t+n]<=r?(o[t]<u&&(u=o[t]),o[t+1]<d&&(d=o[t+1]),o[t+2]<f&&(f=o[t+2]),s[t]>p&&(p=s[t]),s[t+1]>m&&(m=s[t+1]),s[t+2]>h&&(h=s[t+2]),c++):(o[t]<g&&(g=o[t]),o[t+1]<_&&(_=o[t+1]),o[t+2]<v&&(v=o[t+2]),s[t]>y&&(y=s[t]),s[t+1]>b&&(b=s[t+1]),s[t+2]>x&&(x=s[t+2]),i[c]=i[l],i[l]=e,l--)}let S=this._partResult;return S.mid=c,S.lMinX=u,S.lMinY=d,S.lMinZ=f,S.lMaxX=p,S.lMaxY=m,S.lMaxZ=h,S.rMinX=g,S.rMinY=_,S.rMinZ=v,S.rMaxX=y,S.rMaxY=b,S.rMaxZ=x,S}updateNodeBounds(e,t,n){let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0,l=this.indices,u=this.bMin,d=this.bMax;for(let e=t;e<n;e++){let t=l[e]*3;u[t]<r&&(r=u[t]),u[t+1]<i&&(i=u[t+1]),u[t+2]<a&&(a=u[t+2]),d[t]>o&&(o=d[t]),d[t+1]>s&&(s=d[t+1]),d[t+2]>c&&(c=d[t+2])}e.minX=r,e.minY=i,e.minZ=a,e.maxX=o,e.maxY=s,e.maxZ=c}findBestSplitPositionSAH(e,t,n){let r=1/0,i=-1,a=0,o=this.computeSurfaceAreaFlat(n.minX,n.minY,n.minZ,n.maxX,n.maxY,n.maxZ),s=t-e,c=this.intersectionCost*s,l=this.getOptimalBinCount(s);this.splitStats.totalSplitAttempts++,this.splitStats.avgBinsUsed=(this.splitStats.avgBinsUsed*(this.splitStats.totalSplitAttempts-1)+l)/this.splitStats.totalSplitAttempts;let u=this.indices,d=this.centroids,f=this.bMin,p=this.bMax,m=this.binBoundsMin,h=this.binBoundsMax,g=this.binCounts,_=this.leftPrefixMin,v=this.leftPrefixMax,y=this.leftPrefixCount,b=this.rightPrefixMin,x=this.rightPrefixMax,S=this.rightPrefixCount,C=1/0,w=-1/0,T=1/0,E=-1/0,D=1/0,O=-1/0;for(let n=e;n<t;n++){let e=u[n]*3,t=d[e],r=d[e+1],i=d[e+2];t<C&&(C=t),t>w&&(w=t),r<T&&(T=r),r>E&&(E=r),i<D&&(D=i),i>O&&(O=i)}let k=[C,T,D],A=[w,E,O];for(let n=0;n<3;n++){let s=k[n],C=A[n];if(C-s<1e-6)continue;for(let e=0;e<l;e++){g[e]=0;let t=e*3;m[t]=1/0,m[t+1]=1/0,m[t+2]=1/0,h[t]=-1/0,h[t+1]=-1/0,h[t+2]=-1/0}let w=l/(C-s);for(let r=e;r<t;r++){let e=u[r],t=d[e*3+n],i=Math.floor((t-s)*w);i>=l&&(i=l-1),g[i]++;let a=i*3,o=e*3;f[o]<m[a]&&(m[a]=f[o]),f[o+1]<m[a+1]&&(m[a+1]=f[o+1]),f[o+2]<m[a+2]&&(m[a+2]=f[o+2]),p[o]>h[a]&&(h[a]=p[o]),p[o+1]>h[a+1]&&(h[a+1]=p[o+1]),p[o+2]>h[a+2]&&(h[a+2]=p[o+2])}y[0]=g[0],_[0]=m[0],_[1]=m[1],_[2]=m[2],v[0]=h[0],v[1]=h[1],v[2]=h[2];for(let e=1;e<l;e++){let t=e*3,n=(e-1)*3;y[e]=y[e-1]+g[e];let r=_[n],i=m[t],a=_[n+1],o=m[t+1],s=_[n+2],c=m[t+2];_[t]=r<i?r:i,_[t+1]=a<o?a:o,_[t+2]=s<c?s:c;let l=v[n],u=h[t],d=v[n+1],f=h[t+1],p=v[n+2],b=h[t+2];v[t]=l>u?l:u,v[t+1]=d>f?d:f,v[t+2]=p>b?p:b}let T=l-1,E=T*3;S[T]=g[T],b[E]=m[E],b[E+1]=m[E+1],b[E+2]=m[E+2],x[E]=h[E],x[E+1]=h[E+1],x[E+2]=h[E+2];for(let e=T-1;e>=0;e--){let t=e*3,n=(e+1)*3;S[e]=S[e+1]+g[e];let r=b[n],i=m[t],a=b[n+1],o=m[t+1],s=b[n+2],c=m[t+2];b[t]=r<i?r:i,b[t+1]=a<o?a:o,b[t+2]=s<c?s:c;let l=x[n],u=h[t],d=x[n+1],f=h[t+1],p=x[n+2],_=h[t+2];x[t]=l>u?l:u,x[t+1]=d>f?d:f,x[t+2]=p>_?p:_}for(let e=1;e<l;e++){let t=(e-1)*3,u=e*3,d=y[e-1],f=S[e];if(d===0||f===0)continue;let p=v[t]-_[t],m=v[t+1]-_[t+1],h=v[t+2]-_[t+2],g=2*(p*m+m*h+h*p),w=x[u]-b[u],T=x[u+1]-b[u+1],E=x[u+2]-b[u+2],D=2*(w*T+T*E+E*w),O=this.traversalCost+g/o*d*this.intersectionCost+D/o*f*this.intersectionCost;O<r&&O<c&&(r=O,i=n,a=s+(C-s)*e/l)}}return i===-1?this.enableObjectMedianFallback?this.findObjectMedianSplit(e,t):this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`fallbacks_disabled`}:{success:!0,axis:i,pos:a,method:`SAH`,binsUsed:l}}findObjectMedianSplit(e,t){let n=this.indices,r=this.centroids,i=-1,a=-1;for(let o=0;o<3;o++){let s=1/0,c=-1/0;for(let i=e;i<t;i++){let e=r[n[i]*3+o];e<s&&(s=e),e>c&&(c=e)}let l=c-s;l>a&&(a=l,i=o)}if(i===-1||a<1e-10)return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_failed`};let o=t-e,s=e+Math.floor(o/2);this.quickselect(e,t,s,i);let c=r[n[s]*3+i],l=!0;for(let e=s+1;e<t;e++)if(r[n[e]*3+i]>c){l=!1;break}if(l){let a=-1/0;for(let t=e;t<s;t++){let e=r[n[t]*3+i];e>a&&(a=e)}if(a<c)c=(a+c)*.5;else return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_degenerate`}}return{success:!0,axis:i,pos:c,method:`object_median`}}findSpatialMedianSplit(e,t){let n=this.indices,r=this.centroids,i=this.bMin,a=this.bMax,o=-1,s=-1,c=0,l=0;for(let r=0;r<3;r++){let u=1/0,d=-1/0;for(let o=e;o<t;o++){let e=n[o]*3+r;i[e]<u&&(u=i[e]),a[e]>d&&(d=a[e])}let f=d-u;f>s&&(s=f,o=r,c=u,l=d)}if(o===-1||s<1e-12)return{success:!1,method:`spatial_median_failed`};let u=(c+l)*.5,d=t-e,f=0;for(let i=e;i<t;i++)r[n[i]*3+o]<=u&&f++;if(f===0||f===d){let i=e+Math.floor(d/2);this.quickselect(e,t,i,o);let a=r[n[i]*3+o],s=!0;for(let i=e;i<t;i++)if(r[n[i]*3+o]!==a){s=!1;break}if(s)return{success:!1,method:`spatial_median_degenerate`};let c=-1/0;for(let t=e;t<i;t++){let e=r[n[t]*3+o];e>c&&(c=e)}if(c<a)u=(c+a)*.5;else{let e=1/0;for(let a=i+1;a<t;a++){let t=r[n[a]*3+o];t<e&&(e=t)}u=(a+e)*.5}}return{success:!0,axis:o,pos:u,method:`spatial_median`}}quickselect(e,t,n,r){let i=this.indices,a=this.centroids,o=e,s=t-1;for(;o<s;){let e=o+s>>>1,t=a[i[o]*3+r],c=a[i[e]*3+r],l=a[i[s]*3+r];if(t>c){let t=i[o];i[o]=i[e],i[e]=t}if(t>l){let e=i[o];i[o]=i[s],i[s]=e}if(c>l){let t=i[e];i[e]=i[s],i[s]=t}let u=a[i[e]*3+r],d=o,f=s;for(;d<=f;){for(;a[i[d]*3+r]<u;)d++;for(;a[i[f]*3+r]>u;)f--;if(d<=f){let e=i[d];i[d]=i[f],i[f]=e,d++,f--}}f<n&&(o=d),d>n&&(s=f)}}applySAOrdering(e){if(!e||!e.leftChild)return;let t=[e],n=[];for(;t.length>0;){let e=t.pop();!e.leftChild||!e.rightChild||(n.push(e),t.push(e.leftChild),t.push(e.rightChild))}for(let e=n.length-1;e>=0;e--){let t=n[e],r=t.leftChild,i=t.rightChild,a=r.maxX-r.minX,o=r.maxY-r.minY,s=r.maxZ-r.minZ,c=i.maxX-i.minX,l=i.maxY-i.minY,u=i.maxZ-i.minZ;c*l+l*u+u*c>a*o+o*s+s*a&&(t.leftChild=i,t.rightChild=r)}}flattenBVH(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}x(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=b(r);for(let e=0;e<t.length;e++){let n=t[e],a=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[a]=e.minX,r[a+1]=e.minY,r[a+2]=e.minZ,i[a+3]=e._flatIndex,r[a+4]=e.maxX,r[a+5]=e.maxY,r[a+6]=e.maxZ,i[a+7]=t._flatIndex,r[a+8]=t.minX,r[a+9]=t.minY,r[a+10]=t.minZ,r[a+12]=t.maxX,r[a+13]=t.maxY,r[a+14]=t.maxZ}else i[a]=n.triangleOffset,i[a+1]=n.triangleCount,i[a+3]=D}return r}flattenBVHWithFrontier(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}x(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=[],a=b(r);for(let e=0;e<t.length;e++){let n=t[e],o=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[o]=e.minX,r[o+1]=e.minY,r[o+2]=e.minZ,a[o+3]=e._flatIndex,r[o+4]=e.maxX,r[o+5]=e.maxY,r[o+6]=e.maxZ,a[o+7]=t._flatIndex,r[o+8]=t.minX,r[o+9]=t.minY,r[o+10]=t.minZ,r[o+12]=t.maxX,r[o+13]=t.maxY,r[o+14]=t.maxZ}else if(n.isFrontier){let t=n.frontierTaskId;a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+2]=t,a[o+3]=O,i.push({taskId:t,flatIndex:e})}else a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+3]=D}return{flatData:r,frontierMap:i,nodeCount:t.length}}assembleParallelBVH(e,t,n,r){let i=[...r].sort((e,t)=>e.taskId-t.taskId),a=t;for(let e=0;e<i.length;e++)a+=i[e].nodeCount;x(a,`assembled BLAS node count`);let o=new Float32Array(a*16),s=b(o);o.set(e);let c=new Map;for(let e of n)c.set(e.taskId,e.flatIndex);let l=t;for(let e=0;e<i.length;e++){let t=i[e],n=t.flatData,r=t.nodeCount,a=l*16;o.set(n,a);for(let e=0;e<r;e++){let t=a+e*16;s[t+3]<D&&(s[t+3]+=l,s[t+7]+=l)}let u=c.get(t.taskId);if(u!==void 0){let e=u*16,t=a;for(let n=0;n<16;n++)o[e+n]=o[t+n]}l+=r}return o}computeSurfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}};self.onmessage=function(t){let{tasks:n,sharedTriangleData:r,sharedCentroids:i,sharedBMin:a,sharedBMax:o,sharedIndices:s,triangleCount:c,maxLeafSize:l,numBins:u,maxBins:d,minBins:f,reinsertionConfig:p,reportProgress:m}=t.data;for(let t=0;t<n.length;t++){let h=n[t];try{let t=new M;t.maxLeafSize=l,t.numBins=u,t.maxBins=d,t.minBins=f,t.triangles=new Float32Array(r),t.centroids=new Float32Array(i),t.bMin=new Float32Array(a),t.bMax=new Float32Array(o),t.indices=new Uint32Array(s),t.totalTriangles=c,t.totalNodes=0,t.processedTriangles=0,t.lastProgressUpdate=performance.now(),t.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let n=m?e=>{self.postMessage({type:`progress`,taskId:h.taskId,progress:e})}:null,g=performance.now(),_=t.buildNodeRecursive(h.start,h.end,h.depth,n,h.preMinX,h.preMinY,h.preMinZ,h.preMaxX,h.preMaxY,h.preMaxZ);if(p&&p.enabled&&h.end-h.start>1e3){let n=new e(t.traversalCost,t.intersectionCost);p.batchSizeRatio&&n.setBatchSizeRatio(p.batchSizeRatio),p.maxIterations&&n.setMaxIterations(p.maxIterations);try{n.optimizeBVH(_,null)}catch(e){console.error(`[BVHSubtreeWorker] Reinsertion error:`,e)}}t.applySAOrdering(_);let v=t.flattenBVH(_),y=v.length/16,b=performance.now()-g;console.log(`[BVHSubtreeWorker] Task ${h.taskId}: ${(h.end-h.start).toLocaleString()} triangles, ${y} nodes, ${Math.round(b)}ms`),self.postMessage({type:`subtreeResult`,taskId:h.taskId,flatData:v,nodeCount:y},[v.buffer])}catch(e){console.error(`[BVHSubtreeWorker] Task ${h.taskId} error:`,e),self.postMessage({type:`error`,taskId:h.taskId,error:e.message})}}};",Zi=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Xi],{type:`text/javascript;charset=utf-8`});function Qi(e){let t;try{if(t=Zi&&(self.URL||self.webkitURL).createObjectURL(Zi),!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(Xi),{type:`module`,name:e?.name})}}Ae(),dr(),wi(()=>cr(Yi));var $i=ye(`bvh`),ea=20,ta=5e4,na=8;function ra(e,t,n,r){let i=e.byteLength/(ea*4),a=Math.min(ir(),na),o=Math.ceil(Math.log2(a*2.5+1));return $i.debug(`parallel build ${H.n(i)} triangles · ${a} workers · parallelDepth ${o}`),new Promise((s,c)=>{(async()=>{let l=e.buffer instanceof SharedArrayBuffer&&e.byteOffset===0&&e.byteLength===e.buffer.byteLength,u=l?e.buffer:new SharedArrayBuffer(e.byteLength);l||new Uint32Array(u).set(e),e=null;let d=new SharedArrayBuffer(i*3*4),f=new SharedArrayBuffer(i*3*4),p=new SharedArrayBuffer(i*3*4),m=new SharedArrayBuffer(i*4),h=new SharedArrayBuffer(i*4),g=cr(Yi),_=null,v=[g],y={id:null},b=!1,x=()=>{y.id&&=(clearTimeout(y.id),null);for(let e of v)try{e.terminate()}catch{}},S=e=>{if(!b){b=!0,$i.warn(`parallel build failed (${e}), falling back to single worker`),x();try{let e=new ArrayBuffer(u.byteLength);new Uint32Array(e).set(new Uint32Array(u)),s(aa(new Uint32Array(e),t,n,r))}catch(e){c(e)}}};g.onerror=e=>{S(`coordinator error: ${e.message}`)},g.onmessage=e=>{let t=e.data;if(t.error||t.type===`error`){S(t.error);return}if(t.type===`progress`&&n){n(Math.floor(t.progress*.3));return}if(t.type===`phase1Result`){_=t.splitStats,ia(t,a,u,d,f,p,m,null,i,n,g,v,x,S,s,y,r).catch(e=>S(e.message));return}if(t.type===`assembleResult`){b=!0,x(),s({bvhData:t.bvhData,bvhRoot:!0,order:new Uint32Array(m),triangles:new Uint32Array(u),originalToBvh:t.originalToBvh||null,splitStats:_||{}});return}},n&&n(0),g.postMessage({type:`buildPhase1`,sharedTriangleData:u,sharedCentroids:d,sharedBMin:f,sharedBMax:p,sharedIndices:m,sharedMortonCodes:h,triangleCount:i,depth:t,parallelDepth:o,reportProgress:!!n})})().catch(e=>{$i.warn(`parallel build setup failed:`,e),c(e)})})}async function ia(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g){let{topFlatData:_,topNodeCount:v,frontierTasks:y,frontierMap:b}=e;if(!y||y.length===0){$i.debug(`no frontier tasks, assembling with top-level tree only`),u.postMessage({type:`assemble`,topFlatData:_,topNodeCount:v,frontierMap:[],subtreeResults:[],sharedTriangleData:n,sharedIndices:o,sharedReorderBuffer:s,triangleCount:c,foldLeaves:g.foldLeaves},[_.buffer]);return}$i.debug(`phase 2 distributing ${y.length} tasks across ${t} workers`);let x=[...y].sort((e,t)=>t.end-t.start-(e.end-e.start)),S=Array.from({length:Math.min(t,x.length)},()=>[]),C=Array(S.length).fill(0);for(let e of x){let t=0;for(let e=1;e<C.length;e++)C[e]<C[t]&&(t=e);S[t].push(e),C[t]+=e.end-e.start}let w=[],T=0,E=y.length,D=y.reduce((e,t)=>e+(t.end-t.start),0),O=0;h.id=setTimeout(()=>{p(`Phase 2 timeout (30s)`)},3e4);let k=()=>{clearTimeout(h.id),h.id=null,l&&l(85);let t=[];e.topFlatData&&e.topFlatData.buffer&&t.push(e.topFlatData.buffer);for(let e of w)e.flatData&&e.flatData.buffer&&t.push(e.flatData.buffer);u.postMessage({type:`assemble`,topFlatData:e.topFlatData,topNodeCount:v,frontierMap:b,subtreeResults:w,sharedTriangleData:n,sharedIndices:o,sharedReorderBuffer:s,triangleCount:c,foldLeaves:g.foldLeaves},t)},A=S.length;for(let e=0;e<A;e++){let t=S[e];if(t.length===0)continue;let s=cr(Qi);d.push(s),s.onerror=e=>{p(`subtree worker error: ${e.message}`)},s.onmessage=e=>{let t=e.data;if(t.type===`error`){p(`subtree task ${t.taskId} error: ${t.error}`);return}if(t.type===`progress`&&l){let e=30+Math.floor(O/D*55);l(Math.min(e,85));return}if(t.type===`subtreeResult`){w.push({taskId:t.taskId,flatData:t.flatData,nodeCount:t.nodeCount});let e=y.find(e=>e.taskId===t.taskId);if(e&&(O+=e.end-e.start),T++,l){let e=30+Math.floor(O/D*55);l(Math.min(e,85))}if(T===E){for(let e of d)if(e!==u)try{e.terminate()}catch{}k()}}},s.postMessage({tasks:t,sharedTriangleData:n,sharedCentroids:r,sharedBMin:i,sharedBMax:a,sharedIndices:o,triangleCount:c,maxLeafSize:g.maxLeafSize,numBins:g.numBins,maxBins:g.maxBins,minBins:g.minBins,reinsertionConfig:g.reinsertionOptimization,reportProgress:!!l})}}function aa(e,t,n,r){return new Promise((i,a)=>{(async()=>{let o=cr(Yi),s=e.byteLength/(ea*4),c=typeof SharedArrayBuffer<`u`?new SharedArrayBuffer(s*ea*4):null;o.onmessage=e=>{let{bvhData:t,triangles:r,originalToBvh:s,error:l,progress:u,splitStats:d}=e.data;if(l){o.terminate(),a(Error(l));return}if(u!==void 0&&n){n(u);return}o.terminate(),i({bvhData:t,bvhRoot:!0,reorderedTriangles:c?new Uint32Array(c):r,originalToBvh:s||null,splitStats:d||{}})},o.onerror=e=>{o.terminate(),a(e)};let l=e.buffer;o.postMessage({triangleData:l,triangleByteOffset:e.byteOffset,triangleByteLength:e.byteLength,triangleCount:s,depth:t,reportProgress:!!n,sharedReorderBuffer:c,reinsertionOptimization:r.reinsertionOptimization,foldLeaves:r.foldLeaves},[l])})().catch(e=>{$i.warn(`single worker fallback failed:`,e),a(e)})})}function oa(e){return or()&&typeof SharedArrayBuffer<`u`&&e>=ta}wt();var sa=Float64Array.from([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ca(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 la(e,t,n){let r=ca(e,t);if(!Number.isFinite(r)||Math.abs(r)<1e-20)return n.set(sa),n;let i=1/r;return n[0]=(e[t+5]*e[t+10]-e[t+6]*e[t+9])*i,n[1]=(e[t+2]*e[t+9]-e[t+1]*e[t+10])*i,n[2]=(e[t+1]*e[t+6]-e[t+2]*e[t+5])*i,n[3]=0,n[4]=(e[t+6]*e[t+8]-e[t+4]*e[t+10])*i,n[5]=(e[t]*e[t+10]-e[t+2]*e[t+8])*i,n[6]=(e[t+2]*e[t+4]-e[t]*e[t+6])*i,n[7]=0,n[8]=(e[t+4]*e[t+9]-e[t+5]*e[t+8])*i,n[9]=(e[t+1]*e[t+8]-e[t]*e[t+9])*i,n[10]=(e[t]*e[t+5]-e[t+1]*e[t+4])*i,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 ua(e,t,n,r){for(let i=0;i<4;i++){let a=n+i*4,o=t[a],s=t[a+1],c=t[a+2],l=t[a+3];for(let t=0;t<4;t++)r[i*4+t]=e[t]*o+e[4+t]*s+e[8+t]*c+e[12+t]*l}return r}function da(e){for(let t=0;t<16;t++)if(e[t]!==sa[t])return!1;return!0}function fa(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=0;i<8;i++){let a=e[t+(i&1?3:0)],f=e[t+(i&2?4:1)],p=e[t+(i&4?5:2)],m=n[r]*a+n[r+4]*f+n[r+8]*p+n[r+12],h=n[r+1]*a+n[r+5]*f+n[r+9]*p+n[r+13],g=n[r+2]*a+n[r+6]*f+n[r+10]*p+n[r+14];m<o&&(o=m),m>l&&(l=m),h<s&&(s=h),h>u&&(u=h),g<c&&(c=g),g>d&&(d=g)}i[a]=o,i[a+1]=s,i[a+2]=c,i[a+3]=l,i[a+4]=u,i[a+5]=d}function pa(e,t){for(let n=0;n<16;n++)if(e[t+n]!==sa[n])return!1;return!0}var ma=class e{constructor(){this.count=0,this.templateCount=0,this.totalBLASNodes=0,this.tlasNodeCount=0,this.allocate(0)}allocate(e,t=e,n=null,r=null){this.count=e,this.templateCount=t,this.isSet=new Uint8Array(e),this.sourceMesh=r&&r.length>=e?r:new Int32Array(e),this.tlasLeafIndex=new Int32Array(e).fill(-1),this.visible=new Uint8Array(e).fill(1),this.flipWinding=new Uint8Array(e),this.tplBakeInverse=null,n&&n.length>=e*16?(this.world=n,this.worldPooled=!0):(this.world=new Float32Array(e*16),this.worldPooled=!1),this.tplTriOffset=new Int32Array(t),this.tplTriCount=new Int32Array(t),this.tplExpandedStart=new Int32Array(t),this.tplNodeCount=new Int32Array(t),this.tplBlasOffset=new Int32Array(t),this.tplOwner=new Int32Array(t).fill(-1),this.tplObjectAABB=new Float32Array(t*6),this._placementRuns=null,this.originalToBvhMap=new Map,this.bvhToOriginal=new Map,this.blasData=new Map}_place(e,t,n,r){this.isSet[e]=1,this.sourceMesh[e]=t;let i=e*16;if(!n){this.world.set(sa,i),this.flipWinding[e]=0;return}if(n!==this.world)for(let e=0;e<16;e++)this.world[i+e]=n[r+e];this.flipWinding[e]=+(ca(this.world,i)<0)}setEntry({meshIndex:e,blasNodeCount:t,triOffset:n,triCount:r,originalToBvhMap:i,bvhData:a,matrixWorld:o=null,matrixOffset:s=0,expandedStart:c=null,sourceMesh:l=null}){let u=l??e;this._place(e,u,o,s),this.tplTriOffset[u]=n,this.tplTriCount[u]=r,this.tplExpandedStart[u]=c??n,this.tplNodeCount[u]=t,this.tplOwner[u]=e,i&&this.originalToBvhMap.set(u,i),a&&this.blasData.set(u,a)}setAlias(e,t,n=null,r=null,i=null,a=0){if(!this.isSet[t])throw Error(`InstanceTable.setAlias: owner ${t} not built`);let o=i??e,s=this.sourceMesh[t];this._place(e,o,n,a),o!==s&&(this.tplTriOffset[o]=this.tplTriOffset[s],this.tplTriCount[o]=this.tplTriCount[s],this.tplNodeCount[o]=this.tplNodeCount[s],this.tplExpandedStart[o]=r??this.tplExpandedStart[s],this.tplOwner[o]=this.tplOwner[s])}get setCount(){let e=0;for(let t=0;t<this.count;t++)e+=this.isSet[t];return e}setPlacementMatrix(e,t,n=0){this._place(e,this.sourceMesh[e],t,n)}placementRunOf(e){if(!this._placementRuns){let e=this._placementRuns=new Map;for(let t=0;t<this.count;t++){let n=this.sourceMesh[t],r=e.get(n);r?r.count++:e.set(n,{start:t,count:1})}}return this._placementRuns.get(e)??null}isOwner(e){return this.tplOwner[this.sourceMesh[e]]===e}triOffsetOf(e){return this.tplTriOffset[this.sourceMesh[e]]}triCountOf(e){return this.tplTriCount[this.sourceMesh[e]]}expandedStartOf(e){return this.tplExpandedStart[this.sourceMesh[e]]}blasOffsetOf(e){return this.tplBlasOffset[this.sourceMesh[e]]}blasNodeCountOf(e){return this.tplNodeCount[this.sourceMesh[e]]}setBlasNodeCount(e,t){this.tplNodeCount[this.sourceMesh[e]]=t}setBvhToOriginal(e,t){this.bvhToOriginal.set(this.sourceMesh[e],t)}bvhToOriginalOf(e){let t=this.sourceMesh[e],n=this.bvhToOriginal.get(t);if(n)return n;let r=this.tplOwner[t];return(r>=0?this.bvhToOriginal.get(this.sourceMesh[r]):null)||null}matrixWorldOf(e){return this.world.subarray(e*16,e*16+16)}matrixInverseOf(e){return la(this.world,e*16,new Float64Array(16))}writeWorldAABB(e,t,n){if(!this.isSet[e]){for(let e=0;e<6;e++)t[n+e]=0;return}fa(this.tplObjectAABB,this.sourceMesh[e]*6,this.world,e*16,t,n)}writeWorldAABBs(e){let t=this.tplObjectAABB,n=this.world,r=this.sourceMesh,i=this.isSet;for(let a=0;a<this.count;a++){let o=a*6;if(!i[a]){e[o]=0,e[o+1]=0,e[o+2]=0,e[o+3]=0,e[o+4]=0,e[o+5]=0;continue}fa(t,r[a]*6,n,a*16,e,o)}}entryAt(e){if(!this.isSet[e])return null;let t=this.sourceMesh[e],n=this.tplOwner[t];return{meshIndex:e,blasOffset:this.tplBlasOffset[t],blasNodeCount:this.tplNodeCount[t],triOffset:this.tplTriOffset[t],triCount:this.tplTriCount[t],expandedStart:this.tplExpandedStart[t],sourceMesh:t,sharedFrom:n===e?null:n,matrixWorld:this.matrixWorldOf(e),matrixInverse:this.matrixInverseOf(e),flipWinding:!!this.flipWinding[e],bvhToOriginal:this.bvhToOriginal.get(t)||null,visible:!!this.visible[e],tlasLeafIndex:this.tlasLeafIndex[e]}}setVisibility(e,t){this.isSet[e]&&(this.visible[e]=+!!t)}computeAABBs(e,{owners:t=!0}={}){for(let n=0;t&&n<this.templateCount;n++){if(this.tplOwner[n]<0)continue;let t=this.blasData.get(n);t&&this._readRootAABB(Array.isArray(t)?t[0]:t,n,e,this.tplObjectAABB,n*6)}for(let e=0;e<this.templateCount;e++){let t=this.tplOwner[e];if(t<0||this.blasData.has(e))continue;let n=this.sourceMesh[t];n!==e&&this.tplObjectAABB.copyWithin(e*6,n*6,n*6+6)}}recomputeAABB(e,t,n){let r=this.sourceMesh[e],i=this.tplBlasOffset[r],a=t.chunks?t.chunkFor(i).subarray(t.baseOf(i),t.baseOf(i)+16):t.subarray(i*16,i*16+16);this._readRootAABB(a,r,n,this.tplObjectAABB,r*6)}_readRootAABB(t,n,r,i,a){e.rootAABB(t,r,this.tplTriOffset[n],this.tplTriCount[n],i,a)}static rootAABB(e,t,n,r,i,a){if(!e||ht(e)[3]===St.TRIANGLE_LEAF){ha(t,n,r,i,a);return}i[a]=Math.min(e[0],e[8]),i[a+1]=Math.min(e[1],e[9]),i[a+2]=Math.min(e[2],e[10]),i[a+3]=Math.max(e[4],e[12]),i[a+4]=Math.max(e[5],e[13]),i[a+5]=Math.max(e[6],e[14])}_computeAABBFromTriangles(e,t,n,r){ha(t,this.tplTriOffset[e],this.tplTriCount[e],n,r)}assignOffsets(e){this.tlasNodeCount=e;let t=e;for(let e=0;e<this.templateCount;e++){let n=this.tplOwner[e];n<0||this.sourceMesh[n]!==e||(this.tplBlasOffset[e]=t,t+=this.tplNodeCount[e])}for(let e=0;e<this.templateCount;e++){let t=this.tplOwner[e];if(t<0)continue;let n=this.sourceMesh[t];n!==e&&(this.tplBlasOffset[e]=this.tplBlasOffset[n])}this.totalBLASNodes=t-e,gt(t,`combined TLAS + BLAS node count`)}get totalNodeCount(){return this.tlasNodeCount+this.totalBLASNodes}clear(){this.allocate(0),this.totalBLASNodes=0,this.tlasNodeCount=0}};function ha(e,t,n,r,i){let a=K.FLOATS_PER_TRIANGLE,o=e&&e.chunks?e.viewAs(Float32Array):null,s=o?null:e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),c=1/0,l=1/0,u=1/0,d=-1/0,f=-1/0,p=-1/0;for(let e=0;e<n;e++){let n=t+e,r=o?o.chunkFor(n):s,i=o?o.baseOf(n):n*a;for(let e=0;e<=8;e+=4){let t=r[i+e],n=r[i+e+1],a=r[i+e+2];t<c&&(c=t),n<l&&(l=n),a<u&&(u=a),t>d&&(d=t),n>f&&(f=n),a>p&&(p=a)}}r[i]=c,r[i+1]=l,r[i+2]=u,r[i+3]=d,r[i+4]=f,r[i+5]=p}wt();var ga=16,_a=32,va=e=>e<_a?e:_a,ya=8,ba=64,xa=new Float64Array(16),Sa=class e{constructor(){this._flatBuffer=null,this._flatBufferCapacity=0,this._binCounts=new Int32Array(_a*3),this._binBounds=new Float64Array(_a*6*3),this._binSuffix=new Float64Array(_a),this._binSuffixCount=new Int32Array(_a),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(t){let n=new Float64Array(t.count*6);t.writeWorldAABBs(n);let r=this.buildStructure(n,t.count);return e.fillLeaves(r.data,r.nodeCount,t),r}buildStructure(t,n){let r=e.nodeCountFor(n);if(n===0)return{data:new Float32Array,nodeCount:0};gt(r,`TLAS node count`);let i=r*ga;i>this._flatBufferCapacity&&(this._flatBuffer=new Float32Array(i),this._flatBufferCapacity=i);let a=this._flatBuffer,o=ht(a);(!this._order||this._order.length<n)&&(this._order=new Int32Array(n));let s=this._order;for(let e=0;e<n;e++)s[e]=e;this._ensureStack(ba);let c=0,l=0,u=0,d=n,f=this._bounds;this._rangeBounds(t,s,u,d,f,0);let p=f[0],m=f[1],h=f[2],g=f[3],_=f[4],v=f[5];for(;;){if(d-u===1){let e=l*ga;o[e]=0,o[e+1]=s[u],a[e+2]=0,o[e+3]=St.BLAS_POINTER_LEAF}else{let e=this._partition(t,s,u,d,p,m,h,g,_,v),n=e-u,r=l+1,i=r+(n*2-1),y=l*ga;a[y]=f[0],a[y+1]=f[1],a[y+2]=f[2],o[y+3]=r,a[y+4]=f[3],a[y+5]=f[4],a[y+6]=f[5],o[y+7]=i,a[y+8]=f[6],a[y+9]=f[7],a[y+10]=f[8],a[y+11]=0,a[y+12]=f[9],a[y+13]=f[10],a[y+14]=f[11],a[y+15]=0;let b=n<=d-e,x=b?0:6,S=b?6:0;c=this._push(c,b?i:r,b?e:u,b?d:e,f,S),l=b?r:i,b?d=e:u=e,p=f[x],m=f[x+1],h=f[x+2],g=f[x+3],_=f[x+4],v=f[x+5];continue}if(c===0)break;c--;let e=c*3,n=c*6;l=this._stackI[e],u=this._stackI[e+1],d=this._stackI[e+2],p=this._stackB[n],m=this._stackB[n+1],h=this._stackB[n+2],g=this._stackB[n+3],_=this._stackB[n+4],v=this._stackB[n+5]}return{data:a.subarray(0,i),nodeCount:r}}_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(t,n,r){let i=r.world,a=r.sourceMesh,o=r.tplBlasOffset,s=r.visible,c=r.tlasLeafIndex,l=ht(t);for(let r=0;r<n;r++){let n=r*ga;if(l[n+3]!==St.BLAS_POINTER_LEAF)continue;let u=l[n+1]&xt;l[n]=o[a[u]],t[n+2]=+!!s[u],e.writeLeafMatrix(t,l,n,i,u),c[u]=r}}static writeLeafMatrix(e,t,n,r,i){let a=xa;la(r,i*16,a),e[n+4]=a[0],e[n+5]=a[4],e[n+6]=a[8],e[n+7]=a[12],e[n+8]=a[1],e[n+9]=a[5],e[n+10]=a[9],e[n+11]=a[13],e[n+12]=a[2],e[n+13]=a[6],e[n+14]=a[10],e[n+15]=a[14],t[n+1]=(i|(pa(r,i*16)?bt: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<=ya)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,s,c,l){let u=this._surfaceArea(i,a,o,s,c,l);if(!(u>0)||!isFinite(u))return n;let d=1/0,f=1/0,p=1/0,m=-1/0,h=-1/0,g=-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<d&&(d=r),r>m&&(m=r),a<f&&(f=a),a>h&&(h=a),o<p&&(p=o),o>g&&(g=o)}let _=this._extent,v=this._cMin;_[0]=m-d,_[1]=h-f,_[2]=g-p,v[0]=d,v[1]=f,v[2]=p;let y=1/0,b=-1,x=-1,S=this._binCounts,C=this._binBounds,w=_[0]>1e-12,T=_[1]>1e-12,E=_[2]>1e-12;if(!w&&!T&&!E)return n;let D=va(r-n),O=w?D/_[0]:0,k=T?D/_[1]:0,A=E?D/_[2]:0;S.fill(0,0,D*3);for(let e=0;e<D*3;e++){let t=e*6;C[t]=C[t+1]=C[t+2]=1/0,C[t+3]=C[t+4]=C[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?O:e===1?k:A;if(t===0)continue;let n=((e===0?(r+s)*.5:e===1?(a+c)*.5:(o+l)*.5)-v[e])*t|0;n<0?n=0:n>=D&&(n=D-1),n+=e*D,S[n]++;let i=n*6;r<C[i]&&(C[i]=r),a<C[i+1]&&(C[i+1]=a),o<C[i+2]&&(C[i+2]=o),s>C[i+3]&&(C[i+3]=s),c>C[i+4]&&(C[i+4]=c),l>C[i+5]&&(C[i+5]=l)}}for(let e=0;e<3;e++){if(!(_[e]>1e-12))continue;let t=e*D,n=this._binSuffix,r=this._binSuffixCount,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0,d=0;for(let e=D-1;e>=1;e--){let u=(t+e)*6;C[u]<i&&(i=C[u]),C[u+1]<a&&(a=C[u+1]),C[u+2]<o&&(o=C[u+2]),C[u+3]>s&&(s=C[u+3]),C[u+4]>c&&(c=C[u+4]),C[u+5]>l&&(l=C[u+5]),d+=S[t+e],n[e]=d?this._surfaceArea(i,a,o,s,c,l):0,r[e]=d}let f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,v=-1/0,w=0;for(let i=1;i<D;i++){let a=(t+i-1)*6;if(C[a]<f&&(f=C[a]),C[a+1]<p&&(p=C[a+1]),C[a+2]<m&&(m=C[a+2]),C[a+3]>h&&(h=C[a+3]),C[a+4]>g&&(g=C[a+4]),C[a+5]>v&&(v=C[a+5]),w+=S[t+i-1],w===0||r[i]===0)continue;let o=1+(this._surfaceArea(f,p,m,h,g,v)*w+n[i]*r[i])/u;o<y&&(y=o,b=e,x=i)}}if(b<0)return n;let j=D/_[b],M=v[b],N=this._bounds;N[0]=N[1]=N[2]=N[6]=N[7]=N[8]=1/0,N[3]=N[4]=N[5]=N[9]=N[10]=N[11]=-1/0;let P=n,F=r-1;for(;P<=F;){let n=t[P]*6,r=((e[n+b]+e[n+3+b])*.5-M)*j|0;r<0?r=0:r>=D&&(r=D-1);let i=r<x?0:6;if(e[n]<N[i]&&(N[i]=e[n]),e[n+1]<N[i+1]&&(N[i+1]=e[n+1]),e[n+2]<N[i+2]&&(N[i+2]=e[n+2]),e[n+3]>N[i+3]&&(N[i+3]=e[n+3]),e[n+4]>N[i+4]&&(N[i+4]=e[n+4]),e[n+5]>N[i+5]&&(N[i+5]=e[n+5]),i===0)P++;else{let e=t[P];t[P]=t[F],t[F]=e,F--}}return P}_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)}};function Ca(e){if(e>0)return{gb:e,assumed:!1};let t=typeof navigator<`u`?navigator.deviceMemory:void 0;return t>0?{gb:t,assumed:!1}:{gb:4,assumed:!0}}function wa({triangles:e,placements:t,geometryBytes:n=0}){let r={triangles:e*Ea,bvh:Math.ceil(e*Oa)*Da,geometry:n,placements:t*ka,orderMaps:e*Aa};return r.total=r.triangles+r.bvh+r.geometry+r.placements+r.orderMaps,r}function Ta(e,{chunkBytes:t=Yt,shared:n=!1,allocate:r=null}={}){let i=Math.min(e,Ia),a=r??(n?e=>new SharedArrayBuffer(e):e=>new ArrayBuffer(e)),o=[],s=0;try{for(;s<i;){let e=Math.min(t,i-s);o.push(a(e)),s+=e}}catch{}for(let e=o.length-1;e>=0;e--)o[e]=null;return o.length=0,{placed:s,want:i,exhausted:s<i,capped:e>i}}var Ea,Da,Oa,ka,Aa,ja,Ma,Na,Pa,Fa,Ia,La,Ra=g((()=>{wt(),$t(),Ea=K.FLOATS_PER_TRIANGLE*4,Da=64,Oa=.9,ka=64,Aa=4,ja=7040*1024*1024,Ma=9216*1024*1024,Na=6e7,Pa=8e6,Fa=1.15,Ia=12*1024*1024*1024,La=class{constructor(){this.reset()}reset(){this.phase=`idle`,this.events=[],this.samples=[],this.allocatedBytes=0,this.peakLiveBytes=0,this.byPhase=Object.create(null)}mark(e){return this.phase=e,this.byPhase[e]??={allocated:0,chunks:0},this}alloc(e,t=`chunk`){if(!(e>0))return;let n=this.byPhase[this.phase]??={allocated:0,chunks:0};n.allocated+=e,n.chunks++,this.allocatedBytes+=e,this.events.push({phase:this.phase,bytes:e,what:t,at:performance.now()})}sample(e,t){let n=0;for(let e in t)n+=t[e]||0;return n>this.peakLiveBytes&&(this.peakLiveBytes=n),this.samples.push({label:e,phase:this.phase,total:n,parts:t,at:performance.now()}),n}get report(){return{allocatedBytes:this.allocatedBytes,peakLiveBytes:this.peakLiveBytes,byPhase:{...this.byPhase},samples:this.samples.slice()}}}}));Ra();var za="const e={VEC4_PER_BVH_NODE:4,FLOATS_PER_VEC4:4,MIN_TEXTURE_WIDTH:4,MAX_CONCURRENT_WORKERS:Math.min(typeof navigator<`u`&&navigator.hardwareConcurrency||4,6),BUFFER_POOL_SIZE:20,CANVAS_POOL_SIZE:12,CACHE_SIZE_LIMIT:50,MAX_TEXTURE_SIZE:8192,DEFAULT_MAX_TEXTURE_SIZE:4096,MAX_TEXTURES_LIMIT:4*256,MATERIAL_BUCKET_COUNT:4,BUCKET_LAYER_STRIDE:256};function t(t,n){let r=Math.ceil(Math.max(1,t)/64)*64;return Math.min(n,Math.max(e.MIN_TEXTURE_WIDTH,r))}let n,r;const i={CHUNK_SIZE:8,ADAPTIVE_CHUNK_SIZE:!0,MEMORY_SAFETY_FACTOR:.8};let a=null;function o(e){if(e.stream===`begin`){let{width:t,height:n,depth:r}=e;a={width:t,height:n,depth:r,context:new OffscreenCanvas(t,n).getContext(`2d`,{willReadFrequently:!0,alpha:!0,desynchronized:!0}),data:new Uint8Array(t*n*r*4)};return}let{width:t,height:n,depth:r,context:i,data:o}=a;if(e.stream===`layer`){i.clearRect(0,0,t,n),i.drawImage(e.bitmap,0,0),e.bitmap.close(),o.set(i.getImageData(0,0,t,n).data,t*n*4*e.index),self.postMessage({stream:`ack`,index:e.index});return}a=null,self.postMessage({data:o.buffer,width:t,height:n,depth:r},[o.buffer])}async function s({shared:e,width:t,height:i,layers:a}){(n.width!==t||n.height!==i)&&(n.width=t,n.height=i),r.imageSmoothingEnabled=!0,r.imageSmoothingQuality=`high`;let o=new Uint8Array(e),s=t*i*4;for(let{index:e,texture:n}of a)try{await p(n,o,e*s,t,i)}catch(t){console.warn(`Failed to process texture ${e}:`,t),o.fill(0,e*s,(e+1)*s)}}self.onmessage=async function(e){if(e.data.shared){try{n||c(e.data.maxTextureSize),await s(e.data),self.postMessage({done:!0})}catch(e){self.postMessage({error:e.message})}return}if(e.data.stream){try{o(e.data)}catch(e){self.postMessage({error:e.message})}return}let{textures:t,maxTextureSize:r,method:i=`direct-transfer`}=e.data;try{n||c(r);let e=await l(t,r,i);self.postMessage(e,[e.data])}catch(e){console.error(`Worker processing failed:`,e),self.postMessage({error:e.message})}};function c(t){let i=Math.min(t,e.MAX_TEXTURE_SIZE);n=new OffscreenCanvas(i,i),r=n.getContext(`2d`,{willReadFrequently:!0,alpha:!0,desynchronized:!0})}async function l(e,t,n){switch(n){case`direct-transfer`:return await g(e,t);case`offscreen-optimized`:return await v(e,t);case`imageBitmap-batch`:return await y(e,t);default:return await g(e,t)}}async function u(e,t,n){let{maxWidth:r,maxHeight:i}=b(e,t),a=e.length,o=d(r,i,a),s=Math.ceil(a/o);console.log(`Processing ${a} textures in ${s} chunks of up to ${o} textures each`),console.log(`Texture dimensions: ${r}x${i}, Est. memory per chunk: ${(r*i*o*4/1024/1024).toFixed(2)}MB`);let c;try{c=new Uint8Array(r*i*a*4)}catch{return console.warn(`Failed to allocate full texture array, reducing dimensions`),await _(e,x(e,t),n)}let l=r*i*o*4,u;try{u=new Uint8Array(l)}catch{return console.warn(`Failed to allocate chunk buffer, reducing dimensions`),await _(e,x(e,t),n)}for(let t=0;t<s;t++){let n=t*o,s=Math.min(n+o,a),l=s-n,d=await f(e.slice(n,s),r,i,u.subarray(0,r*i*l*4)),p=n*r*i*4,m=l*r*i*4;c.set(new Uint8Array(d.data.slice(0,m)),p),t%2==1&&await new Promise(e=>setTimeout(e,0))}return{data:c.buffer,width:r,height:i,depth:a}}function d(e,t,n){if(!i.ADAPTIVE_CHUNK_SIZE)return Math.min(i.CHUNK_SIZE,n);let r=e*t*4/(1024*1024),a;return a=r<=1?16:r<=4?8:r<=16?4:2,Math.min(a,n,i.CHUNK_SIZE*2)}async function f(e,t,i,a){(n.width!==t||n.height!==i)&&(n.width=t,n.height=i);let o=t*i*4;r.imageSmoothingEnabled=!0,r.imageSmoothingQuality=`high`;for(let n=0;n<e.length;n++){let r=e[n];try{await p(r,a,n*o,t,i)}catch(e){console.warn(`Failed to process texture ${n}:`,e);let t=n*o;a.fill(0,t,t+o)}}return{data:a.buffer,width:t,height:i,depth:e.length}}async function p(e,t,n,i,a){let o;if(e.isDirect&&e.bitmap)o=e.bitmap;else if(e.isImageData&&e.data){let t=new ImageData(new Uint8ClampedArray(e.data),e.width,e.height);o=await createImageBitmap(t,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}else if(e.isBlob){let t=new Blob([e.data]);o=await createImageBitmap(t,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}else throw Error(`Unknown texture data format`);r.clearRect(0,0,i,a),r.drawImage(o,0,0,i,a);let s=r.getImageData(0,0,i,a);t.set(s.data,n),(e.isImageData||e.isBlob)&&o.close()}async function m(e,t,n){let r;try{r=new Uint8Array(t*n*e.length*4)}catch(r){console.warn(`Failed to allocate texture array in processTextureChunk, reducing dimensions`);let i=Math.max(1,Math.floor(t/2)),a=Math.max(1,Math.floor(n/2));if(i===t&&a===n)throw r;return await m(e,i,a)}return await f(e,t,n,r)}async function h(e,t,n,r,i){await p(e,n,r*i*4*t,r,i)}async function g(e,t){let{maxWidth:i,maxHeight:a}=b(e,t);(n.width!==i||n.height!==a)&&(n.width=i,n.height=a);let o=e.length,s;try{s=new Uint8Array(i*a*o*4)}catch(n){return console.error(`Failed to allocate texture array:`,n),await u(e,t,`direct-transfer`)}r.imageSmoothingEnabled=!0,r.imageSmoothingQuality=`high`;for(let t=0;t<e.length;t++){let n=e[t];try{await h(n,t,s,i,a)}catch(e){console.warn(`Failed to process texture ${t}:`,e);let n=i*a*4*t;s.fill(0,n,n+i*a*4)}}return{data:s.buffer,width:i,height:a,depth:o}}async function _(e,t,n){let{maxWidth:r,maxHeight:i}=t;return console.log(`Using reduced dimensions: ${r}x${i}`),await m(e,r,i,n)}async function v(e,t){let{maxWidth:i,maxHeight:a}=b(e,t);(n.width!==i||n.height!==a)&&(n.width=i,n.height=a);let o=e.length,s;try{s=new Uint8Array(i*a*o*4)}catch(n){return console.error(`Failed to allocate texture array:`,n),await u(e,t,`offscreen-optimized`)}r.imageSmoothingEnabled=!0,r.imageSmoothingQuality=`high`;for(let t=0;t<e.length;t++){let n=e[t];try{let e;if(n.isBlob){let t=new Blob([n.data]);e=await createImageBitmap(t,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}else{let t=new ImageData(new Uint8ClampedArray(n.data),n.width,n.height);e=await createImageBitmap(t,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}r.clearRect(0,0,i,a),r.drawImage(e,0,0);let o=r.getImageData(0,0,i,a),c=i*a*4*t;s.set(o.data,c),e.close()}catch(e){console.warn(`Failed to process texture ${t}:`,e);let n=i*a*4*t;s.fill(0,n,n+i*a*4)}}return{data:s.buffer,width:i,height:a,depth:o}}async function y(e,t){let{maxWidth:i,maxHeight:a}=b(e,t),o=e.length,s;try{s=new Uint8Array(i*a*o*4)}catch(n){return console.error(`Failed to allocate texture array:`,n),await u(e,t,`imageBitmap-batch`)}let c=Math.min(d(i,a,e.length),e.length);for(let t=0;t<e.length;t+=c){let o=Math.min(t+c,e.length),l=[];for(let n=t;n<o;n++){let t=e[n],r;if(t.isBlob){let e=new Blob([t.data]);r=createImageBitmap(e,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}else{let e=new ImageData(new Uint8ClampedArray(t.data),t.width,t.height);r=createImageBitmap(e,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}l.push(r.then(e=>({bitmap:e,index:n})))}let u=await Promise.all(l);n.width=i,n.height=a,r.imageSmoothingEnabled=!1;for(let{bitmap:e,index:t}of u){r.clearRect(0,0,i,a),r.drawImage(e,0,0);let n=r.getImageData(0,0,i,a),o=i*a*4*t;s.set(n.data,o),e.close()}}return{data:s.buffer,width:i,height:a,depth:o}}function b(n,r){let i=0,a=0;for(let e of n)i=Math.max(i,e.width||0),a=Math.max(a,e.height||0);let o=Math.min(r,e.MAX_TEXTURE_SIZE),s=Math.max(i,a);if(s>o){let e=o/s;i=Math.round(i*e),a=Math.round(a*e)}return i=t(i,o),{maxWidth:i,maxHeight:Math.max(1,a)}}function x(e,t){let n=b(e,t);return{maxWidth:Math.max(64,Math.ceil(n.maxWidth/128)*64),maxHeight:Math.max(1,Math.floor(n.maxHeight/2))}}",Ba=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,za],{type:`text/javascript;charset=utf-8`});function Va(e){let t;try{if(t=Ba&&(self.URL||self.webkitURL).createObjectURL(Ba),!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(za),{type:`module`,name:e?.name})}}var Ha=`function e({data:e,width:t,height:n,flipY:r},i,a,o,s){let c=o*4;if(t===o&&n===s){if(!r){i.set(e.subarray(0,s*c),a);return}for(let t=0;t<s;t++)i.set(e.subarray(t*c,(t+1)*c),a+(s-1-t)*c);return}let l=new Int32Array(o),u=new Int32Array(o),d=new Float64Array(o);for(let e=0;e<o;e++){let n=Math.min(Math.max((e+.5)*t/o-.5,0),t-1),r=Math.floor(n);l[e]=r*4,u[e]=Math.min(r+1,t-1)*4,d[e]=n-r}if(s<=n){for(let f=0;f<s;f++){let p=Math.min(Math.max((f+.5)*n/s-.5,0),n-1),m=Math.floor(p),h=Math.min(m+1,n-1),g=p-m,_=m*t*4,v=h*t*4,y=a+(r?s-1-f:f)*c;for(let t=0;t<o;t++,y+=4){let n=_+l[t],r=_+u[t],a=v+l[t],o=v+u[t],s=d[t];for(let t=0;t<4;t++){let c=e[n+t]+(e[r+t]-e[n+t])*s,l=e[a+t]+(e[o+t]-e[a+t])*s;i[y+t]=Math.round(c+(l-c)*g)}}}return}let f=[{row:-1,data:new Float64Array(c)},{row:-1,data:new Float64Array(c)}],p=(n,r)=>{for(let e of f)if(e.row===n)return e.data;let i=f[0].row===r?f[1]:f[0],a=n*t*4,s=i.data;for(let t=0,n=0;t<o;t++,n+=4){let r=a+l[t],i=a+u[t],o=d[t];s[n]=e[r]+(e[i]-e[r])*o,s[n+1]=e[r+1]+(e[i+1]-e[r+1])*o,s[n+2]=e[r+2]+(e[i+2]-e[r+2])*o,s[n+3]=e[r+3]+(e[i+3]-e[r+3])*o}return i.row=n,s};for(let e=0;e<s;e++){let t=Math.min(Math.max((e+.5)*n/s-.5,0),n-1),o=Math.floor(t),l=Math.min(o+1,n-1),u=t-o,d=p(o,l),f=l===o?d:p(l,o),m=a+(r?s-1-e:e)*c;for(let e=0;e<c;e++)i[m+e]=Math.round(d[e]+(f[e]-d[e])*u)}}self.onmessage=function(t){let{layers:n,width:r,height:i}=t.data;try{let t=r*i*4,a=new Uint8Array(t*n.length);n.forEach((n,o)=>e(n,a,o*t,r,i)),self.postMessage({data:a},[a.buffer])}catch(e){self.postMessage({error:e.message})}};`,Ua=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Ha],{type:`text/javascript;charset=utf-8`});function Wa(e){let t;try{if(t=Ua&&(self.URL||self.webkitURL).createObjectURL(Ua),!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(Ha),{type:`module`,name:e?.name})}}function Ga({data:e,width:t,height:n,flipY:r},i,a,o,s){let c=o*4;if(t===o&&n===s){if(!r){i.set(e.subarray(0,s*c),a);return}for(let t=0;t<s;t++)i.set(e.subarray(t*c,(t+1)*c),a+(s-1-t)*c);return}let l=new Int32Array(o),u=new Int32Array(o),d=new Float64Array(o);for(let e=0;e<o;e++){let n=Math.min(Math.max((e+.5)*t/o-.5,0),t-1),r=Math.floor(n);l[e]=r*4,u[e]=Math.min(r+1,t-1)*4,d[e]=n-r}if(s<=n){for(let f=0;f<s;f++){let p=Math.min(Math.max((f+.5)*n/s-.5,0),n-1),m=Math.floor(p),h=Math.min(m+1,n-1),g=p-m,_=m*t*4,v=h*t*4,y=a+(r?s-1-f:f)*c;for(let t=0;t<o;t++,y+=4){let n=_+l[t],r=_+u[t],a=v+l[t],o=v+u[t],s=d[t];for(let t=0;t<4;t++){let c=e[n+t]+(e[r+t]-e[n+t])*s,l=e[a+t]+(e[o+t]-e[a+t])*s;i[y+t]=Math.round(c+(l-c)*g)}}}return}let f=[{row:-1,data:new Float64Array(c)},{row:-1,data:new Float64Array(c)}],p=(n,r)=>{for(let e of f)if(e.row===n)return e.data;let i=f[0].row===r?f[1]:f[0],a=n*t*4,s=i.data;for(let t=0,n=0;t<o;t++,n+=4){let r=a+l[t],i=a+u[t],o=d[t];s[n]=e[r]+(e[i]-e[r])*o,s[n+1]=e[r+1]+(e[i+1]-e[r+1])*o,s[n+2]=e[r+2]+(e[i+2]-e[r+2])*o,s[n+3]=e[r+3]+(e[i+3]-e[r+3])*o}return i.row=n,s};for(let e=0;e<s;e++){let t=Math.min(Math.max((e+.5)*n/s-.5,0),n-1),o=Math.floor(t),l=Math.min(o+1,n-1),u=t-o,d=p(o,l),f=l===o?d:p(l,o),m=a+(r?s-1-e:e)*c;for(let e=0;e<c;e++)i[m+e]=Math.round(d[e]+(f[e]-d[e])*u)}}function Ka(e,t,n,r,i){i[0]=$a(e),i[1]=$a(t),i[2]=$a(n)}function qa(e,t,n,r,i){i[0]=$a(e*r),i[1]=$a(t*r),i[2]=$a(n*r)}function Ja(e,t,n,r,i){e*=r,t*=r,n*=r,i[0]=$a(e/(e+1)),i[1]=$a(t/(t+1)),i[2]=$a(n/(n+1))}function Ya(e,t,n,r,i){e=Math.max(e*r-.004,0),t=Math.max(t*r-.004,0),n=Math.max(n*r-.004,0);let a=e=>(e*(6.2*e+.5)/(e*(6.2*e+1.7)+.06))**2.2;i[0]=a(e),i[1]=a(t),i[2]=a(n)}function Xa(e,t,n,r,i){e=e*r/.6,t=t*r/.6,n=n*r/.6;let a=.59719*e+.35458*t+.04823*n,o=.076*e+.90834*t+.01566*n,s=.0284*e+.13383*t+.83777*n,c=e=>(e*(e+.0245786)-90537e-9)/(e*(.983729*e+.432951)+.238081);a=c(a),o=c(o),s=c(s),i[0]=$a(1.60475*a-.53108*o-.07367*s),i[1]=$a(-.10208*a+1.10813*o-.00605*s),i[2]=$a(-.00327*a-.07276*o+1.07602*s)}function Za(e,t,n,r,i){e*=r,t*=r,n*=r;let a=.6274*e+.3293*t+.0433*n,o=.0691*e+.9195*t+.0113*n,s=.0164*e+.088*t+.8956*n,c=.856627153315983*a+.0951212405381588*o+.0482516061458583*s,l=.137318972929847*a+.761241990602591*o+.101439036467562*s,u=.11189821299995*a+.0767994186031903*o+.811302368396859*s,d=-12.47393,f=4.026069-d;c=$a((Math.log2(Math.max(c,1e-10))-d)/f),l=$a((Math.log2(Math.max(l,1e-10))-d)/f),u=$a((Math.log2(Math.max(u,1e-10))-d)/f);let p=e=>{let t=e*e,n=t*t;return 15.5*n*t-40.14*n*e+31.96*n-6.868*t*e+.4298*t+.1191*e-.00232};c=p(c),l=p(l),u=p(u);let m=1.1271005818144368*c-.11060664309660323*l-.016493938717834573*u,h=-.1413297634984383*c+1.157823702216272*l-.016493938717834257*u,g=-.14132976349843826*c-.11060664309660294*l+1.2519364065950405*u;m=Math.max(0,m)**2.2,h=Math.max(0,h)**2.2,g=Math.max(0,g)**2.2,i[0]=$a(1.6605*m-.5876*h-.0728*g),i[1]=$a(-.1246*m+1.1329*h-.0083*g),i[2]=$a(-.0182*m-.1006*h+1.1187*g)}function Qa(e,t,n,r,i){let a=.76;e*=r,t*=r,n*=r;let o=Math.min(e,Math.min(t,n)),s=o<.08?o-6.25*o*o:.04;e-=s,t-=s,n-=s;let c=Math.max(e,Math.max(t,n));if(c<a){i[0]=e,i[1]=t,i[2]=n;return}let l=1-a,u=1-l*l/(c+l-a),d=u/c;e*=d,t*=d,n*=d;let f=1-1/(.15*(c-u)+1);i[0]=e+(u-e)*f,i[1]=t+(u-t)*f,i[2]=n+(u-n)*f}var $a,eo,to,no,ro,io,ao,oo=g((()=>{$a=e=>Math.min(Math.max(e,0),1),eo=`
|
|
116
116
|
fn tm_reinhard( c: vec3<f32> ) -> vec3<f32> {
|
|
117
117
|
return clamp( c / ( c + vec3<f32>( 1.0 ) ), vec3<f32>( 0.0 ), vec3<f32>( 1.0 ) );
|
|
118
118
|
}
|
|
@@ -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 bo(){Co.length=0,Co.push(...ao),wo.clear();for(let e of Co)wo.set(e.id,e);so()}var xo,So,Co,wo,To,Eo,Do,Oo,ko,Ao=g((()=>{oo(),xo=200,So=12,Co=[...ao],wo=new Map(Co.map(e=>[e.id,e])),To=1,Eo=new Set,Do=wo,Oo=r.NoToneMapping,ko=r.AgXToneMapping}));Ao();var jo=e=>(t,n,r,i,a)=>e(t>0?t:0,n>0?n:0,r>0?r:0,i,a),Mo=new Map;function No(){Mo.clear();for(let e of Do.values())Mo.set(e.id,jo(e.cpu))}No(),lo(No);function Po(e){return uo(e)?.outputEncoded===!0}function Fo(e){return e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055}function Io(e,t){let n=uo(t);return n?n.appliesExposure?e:1:t===r.NoToneMapping?1:e}var Lo=.2126,Ro=.7152,zo=.0722;function Bo(e,t){if(t===1)return;let n=e[0]*Lo+e[1]*Ro+e[2]*zo;e[0]=n+(e[0]-n)*t,e[1]=n+(e[1]-n)*t,e[2]=n+(e[2]-n)*t}function Vo(e,{exposure:t,toneMapping:n,saturation:i=1,preserveAlpha:a=!1}){let o=Mo.get(n)??Mo.get(r.NoToneMapping),s=Io(t,n),c=Po(n),l=new Uint8ClampedArray(e.length),u=[0,0,0];for(let t=0;t<e.length;t+=4)u[0]=e[t]*s,u[1]=e[t+1]*s,u[2]=e[t+2]*s,Bo(u,i),o(u[0],u[1],u[2],1,u),c?(l[t]=u[0]*255+.5,l[t+1]=u[1]*255+.5,l[t+2]=u[2]*255+.5):(l[t]=Fo(u[0])*255+.5,l[t+1]=Fo(u[1])*255+.5,l[t+2]=Fo(u[2])*255+.5),l[t+3]=a?e[t+3]*255+.5:255;return l}wt(),X(),Ae(),dr();var Ho=ye(`textures`),Uo={MAX_BUFFER_MEMORY:1024*1024*1024,MAX_TEXTURE_MEMORY:2048*1024*1024,CLEANUP_THRESHOLD:.8,STREAM_BATCH_SIZE:4},Wo=8*2**20,Go=16,Ko=4,qo=8192*8192,Jo={busy:0,waiting:[]};async function Yo(){return Jo.busy<Math.max(1,ir()-1)?Jo.busy++:await new Promise(e=>Jo.waiting.push(e)),()=>{let e=Jo.waiting.shift();e?e():Jo.busy--}}var Xo={toSRGB:null,toLinear:null};function Zo(e){if(!Xo[e]){let t=new Uint8Array(256);for(let n=0;n<256;n++){let r=n/255,i=e===`toSRGB`?Fo(r):r<=.04045?r/12.92:((r+.055)/1.055)**2.4;t[n]=Math.max(0,Math.min(255,Math.round(i*255)))}Xo[e]=t}return Xo[e]}var Qo=class{constructor(){this.canvasContextPairs=[],this.maxPoolSize=Nt.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=[]}},$o=class{constructor(e={}){this.pools=new Map,this.memoryUsage=0,this.maxMemoryUsage=e.maxMemory||Uo.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*Uo.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<Nt.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`}},es=class{constructor(e=Nt.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=[]}},ts=class{constructor(e={}){this.useWorkers=typeof Worker<`u`,this.maxConcurrentWorkers=Nt.MAX_CONCURRENT_WORKERS,this.activeWorkers=0,this._issues=e.issues??null,this.maxTextureSize=this._clampTextureSize(e.maxTextureSize??Nt.DEFAULT_MAX_TEXTURE_SIZE),this.canvasPool=new Qo,this.bufferPool=new $o({maxMemory:e.maxBufferMemory||Uo.MAX_BUFFER_MEMORY,sizeStrategy:e.bufferSizeStrategy||`adaptive`}),this.textureCache=new es,this.capabilities=this.detectCapabilities(),this.optimalMethod=this.selectOptimalMethod()}_reportTextureFailure(e,t){if(t instanceof Gt)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)||Nt.DEFAULT_MAX_TEXTURE_SIZE);return Math.max(Nt.MIN_TEXTURE_WIDTH,Math.min(t,Nt.MAX_TEXTURE_SIZE))}setMaxTextureSize(e){let t=this._clampTextureSize(e);return t===this.maxTextureSize?t:(this.maxTextureSize=t,this.textureCache?.dispose(),this.textureCache=new es,this.maxTextureSize)}detectCapabilities(){return{offscreenCanvas:typeof OffscreenCanvas<`u`,imageBitmap:typeof createImageBitmap<`u`,workers:typeof Worker<`u`,hardwareConcurrency:ir()}}selectOptimalMethod(){return this.capabilities.workers&&this.capabilities.offscreenCanvas?`worker-offscreen`:this.capabilities.imageBitmap?`imageBitmap`:`canvas`}_applyColorManagement(e,t,n,i=new Set){let a=kr();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){Ho.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,Ho.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=Zo(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?Ho.info(`re-encoded ${l.length}/${o.length} linear-declared colour map(s) to sRGB so the GPU decode round-trips: ${u}`):Ho.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=kr()?.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 Gt)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>Uo.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 Va;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)<qo)return 0;let t=this.maxConcurrentWorkers-this.activeWorkers;return Math.max(0,Math.min(e.length,Ko,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=cr(Va);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=cr(Va);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>=Uo.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>Go&&(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=r?.data;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=or()&&i*t.length>=Wo?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)=>Ga(e,o,t*i,n,r)),this.createDataArrayTextureFromBuffer(o,n,r,t.length)}async _packInWorker(e,t,n){let r=await Yo(),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=cr(Wa),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%Uo.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=q.FLOATS_PER_MATERIAL,n=new Float32Array(e.length*t);for(let r=0;r<e.length;r++)Mt(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=Nt.VEC4_PER_BVH_NODE*Nt.FLOATS_PER_VEC4;gt(t.length,`BVH node count`);let i=t.length*r,a=new Float32Array(i),o=ht(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]=St.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 es;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:Ft(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:ns(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),i.push({index:e,flipY:n.flipY,promise:ns(n.image.data,n.image.width,n.image.height)});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()}};function ns(e,t,n){let r=new Uint8ClampedArray(e.buffer,e.byteOffset,e.byteLength);return createImageBitmap(new ImageData(r,t,n))}var rs=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=as(E,is(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=as(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 is(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 as(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)}}wt(),Ae(),Fn();var os=Object.freeze({r:0,g:0,b:0});function ss(e){if(!e)return os;if(!kn())return e;let t=[e.r,e.g,e.b];return jn(t),{r:t[0],g:t[1],b:t[2]}}var cs=ye(`emissive`),ls=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=K.FLOATS_PER_TRIANGLE,a=K.MATERIAL_FLAGS_OFFSET,o=K.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]&_t,h=n[p+o],g=t[m];if(!g)continue;let _=d.get(g);_===void 0&&(_=ss(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.world:null,a=n?t*16:0,o=(e,t,n)=>i?i[a]*e+i[a+4]*t+i[a+8]*n+i[a+12]:e,s=(e,t,n)=>i?i[a+1]*e+i[a+5]*t+i[a+9]*n+i[a+13]:t,c=(e,t,n)=>i?i[a+2]*e+i[a+6]*t+i[a+10]*n+i[a+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),ue=Math.max(E,k,M),z=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:ue,bMaxZ:z,nx:I,ny:L,nz:ee,twoSided:ne}),this.totalEmissivePower+=F}}return this.emissiveCount=this.emissiveTriangles.length,this.emissiveCount>0&&cs.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=K.FLOATS_PER_TRIANGLE,o=t.world;this.totalEmissivePower=0;for(let e of this.emissiveTriangles){let s=n?r.chunkFor(e.triangleIndex):i,c=n?n.baseOf(e.triangleIndex):e.triangleIndex*a,l=[s[c],s[c+1],s[c+2],s[c+4],s[c+5],s[c+6],s[c+8],s[c+9],s[c+10]],u=t.placementRunOf?.(e.meshIndex)?.start??-1;if(u>=0&&t.isSet[u]){let e=u*16;for(let t=0;t<9;t+=3){let n=l[t],r=l[t+1],i=l[t+2];l[t]=o[e]*n+o[e+4]*r+o[e+8]*i+o[e+12],l[t+1]=o[e+1]*n+o[e+5]*r+o[e+9]*i+o[e+13],l[t+2]=o[e+2]*n+o[e+6]*r+o[e+10]*i+o[e+14]}}let[d,f,p,m,h,g,_,v,y]=l,b=this._calculateTriangleArea(d,f,p,m,h,g,_,v,y),x=e.emissive;e.power=(.2126*x.r+.7152*x.g+.0722*x.b)*e.emissiveIntensity*b,e.area=b;let S=(h-f)*(y-p)-(g-p)*(v-f),C=(g-p)*(_-d)-(m-d)*(y-p),w=(m-d)*(v-f)-(h-f)*(_-d),T=(Math.sqrt(S*S+C*C+w*w)||1)/e.sideSign;e.nx=S/T,e.ny=C/T,e.nz=w/T,e.cx=(d+m+_)/3,e.cy=(f+h+v)/3,e.cz=(p+g+y)/3,e.bMinX=Math.min(d,m,_),e.bMinY=Math.min(f,h,v),e.bMinZ=Math.min(p,g,y),e.bMaxX=Math.max(d,m,_),e.bMaxY=Math.max(f,h,v),e.bMaxZ=Math.max(p,g,y),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,cs.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 cs.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=ss(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(Math.max(this._totalTriangleCount,1)).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 rs().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,cs.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}};Ae();var us=class{constructor(e=`Build`,{namespace:t=`build`,level:n=`debug`}={}){this.label=e,this.level=n,this.logger=ye(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)}}};nn();var ds=1<<20,fs=1<<21,ps=()=>new Promise(e=>setTimeout(e,0)),ms=[0,1,2,4,5,6,8,9,10];function hs(e,t,n,r=ms){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 gs(e,t){let n=[],r=0;for(let{triOffset:i,triCount:a}of t)n.push(hs(e,i,a)),r+=a,r>=fs&&(r=0,await ps());return n}async function _s(e,t){let n=await e?.area(tn.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 vs(e,t,{index:n,bvh:r,orders:i,isStale:a,label:o=``}){let s=e?.area(tn.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,ds),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+=ds*4)await u.write(`order.u32`,e.subarray(t,Math.min(e.length,t+ds*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 ys(e,t,n,r){for(let i=0;i<r;i+=ds){let a=Math.min(ds,r-i),o=await e.slice(i*64,(i+a)*64).arrayBuffer();t.setRecords(n+i,new Float32Array(o))}}async function bs(e,t,n){return new Uint32Array(await e.slice(t*4,(t+n)*4).arrayBuffer())}wt();var xs=16,Ss=K.POSITION_A_OFFSET,Cs=K.POSITION_B_OFFSET,ws=K.POSITION_C_OFFSET;async function Ts(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+Ss]+o[n+Cs]+o[n+ws],c[r]=o[n+Ss+1]+o[n+Cs+1]+o[n+ws+1],l[r]=o[n+Ss+2]+o[n+Cs+2]+o[n+ws+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 Ds(u,o,Es(o,e,t),e,t,n),{left:f(e,n),right:f(n,t)}},p=f(0,n);return await i?.(),await Os(e,t,n,u,i),{order:u,pieces:d,tree:p}}function Es(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 Ds(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 Os(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 ks(e,t,n,r){let i=t.length-1,a=[],o=i;for(let{bvhData:e}of n)a.push(o),o+=e.length/xs;let s=new Float32Array(i*xs),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];yi(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*xs;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 As,js=g((()=>{As=`11.2.0`})),Ms,Ns=g((()=>{js(),Ms=As}));function Ps(e,t,n=Fs){return e>=n&&t/Is<e/3}var Fs,Is,Ls=g((()=>{Fs=1e4,Is=15e5}));Ns(),Ls();var Rs="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};n.TRIANGLE_LEAF;const r=e=>e>=2147483648,i=e=>~e>>>0>>>4,a=e=>~e&15,o=e.FLOATS_PER_TRIANGLE,s=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),c=e=>e instanceof Uint32Array?e:new Uint32Array(e.buffer,e.byteOffset,e.length),l=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:e,idx:t?e.viewAs(Uint32Array):c(e)}},u=(e,t)=>e.chunked?e.f.chunkFor(t):e.f,d=(e,t)=>e.chunked?e.idx.chunkFor(t):e.idx,f=(e,t)=>e.chunked?e.chunked.baseOf(t):t*m,p=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:t?t.viewAs(Float32Array):s(e),u:t?e:c(e)}},m=16,h=n.TRIANGLE_LEAF,g=n.BLAS_POINTER_LEAF;function _(e,t,n,r,i,a){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 v(t,n,r,i,a){let s=e.POSITION_A_OFFSET,c=e.POSITION_B_OFFSET,l=e.POSITION_C_OFFSET,u=1/0,d=1/0,f=1/0,p=-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*o;u=Math.min(u,i[a+s],i[a+c],i[a+l]),d=Math.min(d,i[a+s+1],i[a+c+1],i[a+l+1]),f=Math.min(f,i[a+s+2],i[a+c+2],i[a+l+2]),p=Math.max(p,i[a+s],i[a+c],i[a+l]),m=Math.max(m,i[a+s+1],i[a+c+1],i[a+l+1]),h=Math.max(h,i[a+s+2],i[a+c+2],i[a+l+2])}i[a]=u,i[a+1]=d,i[a+2]=f,i[a+3]=p,i[a+4]=m,i[a+5]=h}const y=new Float32Array(12);function b(e,t,n,r){let i=u(e,t),a=d(e,t),o=f(e,t);if(a[o+3]===h){v(n,a[o],a[o+1],r,0);return}for(let e=0;e<3;e++)r[e]=Math.min(i[o+e],i[o+8+e]),r[3+e]=Math.max(i[o+4+e],i[o+12+e])}function x(e,t,n,o,s){let c=u(e,t),l=d(e,t),p=f(e,t),m=(t-s)*6,b=l[p+3];if(b===h){v(n,l[p],l[p+1],o,m);return}if(b===g){_(c,p,o,(l[p]-s)*6,o,m);return}let x=l[p+7],S=o,C=(b-s)*6;r(b)&&(v(n,i(b),a(b),y,0),S=y,C=0);let w=o,T=(x-s)*6;r(x)&&(v(n,i(x),a(x),y,6),w=y,T=6),c[p]=S[C],c[p+1]=S[C+1],c[p+2]=S[C+2],c[p+4]=S[C+3],c[p+5]=S[C+4],c[p+6]=S[C+5],c[p+8]=w[T],c[p+9]=w[T+1],c[p+10]=w[T+2],c[p+12]=w[T+3],c[p+13]=w[T+4],c[p+14]=w[T+5];for(let e=0;e<3;e++)o[m+e]=Math.min(S[C+e],w[T+e]),o[m+3+e]=Math.max(S[C+3+e],w[T+3+e])}var S=class{constructor(){this._bounds=null,this._boundsNodeCount=0,this._tlasBounds=null,this._rootBox=null}updateTrianglePositions(n,r,i){let a=i.length,s=p(n);for(let n=0;n<a;n++){let a=i[n],c=s.chunked?s.f.chunkFor(n):s.f,l=s.chunked?s.u.chunkFor(n):s.u,u=s.chunked?s.chunked.baseOf(n):n*o,d=a*9,f=r[d],p=r[d+1],m=r[d+2],h=r[d+3],g=r[d+4],_=r[d+5],v=r[d+6],y=r[d+7],b=r[d+8];c[u+e.POSITION_A_OFFSET]=f,c[u+e.POSITION_A_OFFSET+1]=p,c[u+e.POSITION_A_OFFSET+2]=m,c[u+e.POSITION_B_OFFSET]=h,c[u+e.POSITION_B_OFFSET+1]=g,c[u+e.POSITION_B_OFFSET+2]=_,c[u+e.POSITION_C_OFFSET]=v,c[u+e.POSITION_C_OFFSET+1]=y,c[u+e.POSITION_C_OFFSET+2]=b;let x=h-f,S=g-p,C=_-m,w=v-f,T=y-p,E=b-m,D=t(S*E-C*T,C*w-x*E,x*T-S*w);l[u+e.NORMAL_A_PACKED_OFFSET]=D,l[u+e.NORMAL_B_PACKED_OFFSET]=D,l[u+e.NORMAL_C_PACKED_OFFSET]=D}}refitRange(e,t,n,r){let i=p(t);r>this._boundsNodeCount&&(this._bounds=new Float32Array(r*6),this._boundsNodeCount=r);let a=l(e);for(let e=n+r-1;e>=n;e--)x(a,e,i,this._bounds,n)}refitPartial(e,t,n,r){for(let r=0;r<n.length;r+=2)this.refitRange(e,t,n[r],n[r+1]);let i=p(t),a=l(e);(!this._tlasBounds||this._tlasBounds.length<r*6)&&(this._tlasBounds=new Float32Array(r*6));let o=this._tlasBounds,s=this._rootBox||=new Float32Array(6);for(let e=r-1;e>=0;e--){let t=d(a,e),n=f(a,e);t[n+3]===g?(b(a,t[n],i,s),_(u(a,e),n,s,0,o,e*6)):x(a,e,i,o,0)}}refit(e,t,n){let r=p(t);n!==this._boundsNodeCount&&(this._bounds=new Float32Array(n*6),this._boundsNodeCount=n);let i=l(e);for(let e=n-1;e>=0;e--)x(i,e,r,this._bounds,0)}};const C=64*1024*1024;function w(e,t,n){return n?new e(new SharedArrayBuffer(t*e.BYTES_PER_ELEMENT)):new e(t)}var T=class e{constructor(e,t,n,r=C,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(w(n,e*t,i)),s-=e}this.chunks.length===0&&this.chunks.push(w(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=C,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]=w(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=await this._store.read(e,t*this.LaneType.BYTES_PER_ELEMENT),r=w(this.LaneType,t,this.shared);new Uint8Array(r.buffer,r.byteOffset,r.byteLength).set(new Uint8Array(n)),this.chunks[e]=r;for(let t of this._liveViews())t.chunks[e]=new t.LaneType(r.buffer,r.byteOffset,r.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=w(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 E=new S;let D=null,O=null,k=0;self.onmessage=function(e){let{type:t}=e.data;if(t===`init`){D=T.adopt(e.data.sharedBvhBufs.map(e=>new Float32Array(e)),e.data.bvhRecordCount,16,e.data.bvhRecordsPerChunk),O=T.adopt(e.data.sharedTriBufs.map(e=>new Uint32Array(e)),e.data.triRecordCount,e.data.triLanesPerRecord,e.data.triRecordsPerChunk),k=D.recordCount;return}if(t===`refit`)try{let t=performance.now(),{blasRanges:n,tlasNodeCount:r}=e.data;n?E.refitPartial(D,O,n,r):E.refit(D,O,k),self.postMessage({type:`refitComplete`,refitTimeMs:performance.now()-t})}catch(e){console.error(`[BVHRefitWorker] Refit error:`,e),self.postMessage({type:`error`,error:e.message})}};",zs=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Rs],{type:`text/javascript;charset=utf-8`});function Bs(e){let t;try{if(t=zs&&(self.URL||self.webkitURL).createObjectURL(zs),!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(Rs),{type:`module`,name:e?.name})}}var Vs="const e={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826};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]);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=new Float64Array(e.count*6);e.writeWorldAABBs(t);let n=this.buildStructure(t,e.count);return r.fillLeaves(n.data,n.nodeCount,e),n}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=a.world,s=a.sourceMesh,c=a.tplBlasOffset,l=a.visible,u=a.tlasLeafIndex,d=t(n);for(let t=0;t<i;t++){let i=t*16;if(d[i+3]!==e.BLAS_POINTER_LEAF)continue;let a=d[i+1]&1073741823;d[i]=c[s[a]],n[i+2]=+!!l[a],r.writeLeafMatrix(n,d,i,o,a),u[a]=t}}static writeLeafMatrix(e,t,n,r,i){let s=c;a(r,i*16,s),e[n+4]=s[0],e[n+5]=s[4],e[n+6]=s[8],e[n+7]=s[12],e[n+8]=s[1],e[n+9]=s[5],e[n+10]=s[9],e[n+11]=s[13],e[n+12]=s[2],e[n+13]=s[6],e[n+14]=s[10],e[n+15]=s[14],t[n+1]=(i|(o(r,i*16)?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})}};",Hs=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Vs],{type:`text/javascript;charset=utf-8`});function Us(e){let t;try{if(t=Hs&&(self.URL||self.webkitURL).createObjectURL(Hs),!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(Vs),{type:`module`,name:e?.name})}}$t(),Ae(),wt(),X(),Pr(),Br(),dr();var Ws=5e4,Gs=2e5,Ks=2e6,qs=1<<19,Js=4e7,Ys=1.5*1024**3,Xs=256*1024*1024,Zs=ye(`scene`),Qs=e=>Array.isArray(e)?e:[e],$s=e=>Qs(e).reduce((e,t)=>e+t.byteLength,0),ec=64*1024*1024;async function tc(e,t,n){for(let r of Qs(n))await e.writeAt(t,r),t+=r.byteLength}function nc(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 rc=class{constructor(e={}){this.config={useWorkers:!0,bvhDepth:30,maxLeafSize:4,verbose:!1,useFloat32Array:!0,textureQuality:`adaptive`,maxTextureSize:Nt.DEFAULT_MAX_TEXTURE_SIZE,enableTextureCache:!0,maxConcurrentTextureTasks:Math.min(ir(),6),maxSceneBytes:Ma,sceneCache:!0,sceneCacheMinBuildMs:Fs,...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 La,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 Dn({issues:this.config.issues}),this.bvhBuilder=new Oi,this.bvhBuilder.maxLeafSize=this.config.maxLeafSize,this.textureCreator=new ts({maxTextureSize:this.config.maxTextureSize,issues:this.config.issues}),this.emissiveTriangleBuilder=new ls,this.tlasBuilder=new Sa,this._tlasWorker=null,this._tlasWorkerFailed=!1}_log(e,t){t===void 0?Zs.debug(e):Zs.debug(e,t)}_preflightMemory(e){let t=this.config.maxSceneBytes??9663676416,n=this.geometryExtractor.surveyScene(e),r=wa(n);if(this._progressive&&(r.total-=r.bvh),this._streaming){let t=Ys+nc(e)*(K.FLOATS_PER_TRIANGLE*4+44);r.total-=Math.max(0,r.triangles-t)}let i={...n,estimate:r,safeBytes:ja,maxBytes:t,fits:r.total<=ja};if(this.memoryPreflight=i,r.total<1610612736)return i;if(Zs.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(ja)} 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:ja}),i}_checkAssemblyHeadroom(e){let t=e*64;if(t<1610612736)return!0;let n=Ta(Math.ceil(t*Fa),{shared:Xt});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?.world?.byteLength??0,blasScratch:0,orderMaps:0};if(e){for(let n of e.blasData.values())t.blasScratch+=n?$s(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;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;Zs.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,qt(e=>this.memory.alloc(e));let r=new us(e.name??``,{namespace:`scene`});try{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/(K.FLOATS_PER_TRIANGLE*4)),this._foldLeaves=i>Js,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=xn(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`,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=>Zs.debug(`storing BLASes failed:`,e))),this}catch(e){throw this.processingStage=`error`,Zs.error(`processing failed:`,e),z({status:`Error: ${e.message}`,failed:!0,progress:100}),e}finally{this._disposeGeometrySpill(),qt(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 Zs.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:`Extracting geometry and building BVHs...`,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=Qt.lazy(o,K.FLOATS_PER_TRIANGLE,Uint32Array),c=s.recordsPerChunk*s.lanesPerRecord*4,l=await on.create(r,`${a}:tri`,c,{label:`Triangle records`,expectedBytes:o*c/s.recordsPerChunk}),u=l&&await on.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 fn.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);ma.rootAABB(Qs(r)[0],v,t.start,t.count,i,0),p.set(e,{result:n,aabb:i});let a=f.blasBytes;f.blasBytes+=$s(r),f.blasAt.set(e,a),n.nodeCount=$s(r)/64,n.bvhData=null,this._queueSpill(f,()=>tc(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`)},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>Xs&&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>Ys&&(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),Zs.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=gt(e.triangleCount,`triangle count`),this._foldLeaves&&this.triangleCount>134217728)throw RangeError(`${this.triangleCount.toLocaleString()} triangles is past the ${Ct.toLocaleString()} a folded BVH leaf can address`);this.expandedTriangleCount=e.expandedTriangleCount??e.triangleCount,this.instanceSource=e.instanceSource||null,this.instanceMatrices=e.instanceMatrices||null,this.instanceCount=e.instanceCount||0,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.maps=e.maps,this.normalMaps=e.normalMaps,this.bumpMaps=e.bumpMaps,this.roughnessMaps=e.roughnessMaps,this.metalnessMaps=e.metalnessMaps,this.emissiveMaps=e.emissiveMaps,this.displacementMaps=e.displacementMaps,this.anisotropyMaps=e.anisotropyMaps,this.transmissionMaps=e.transmissionMaps,this.clearcoatMaps=e.clearcoatMaps,this.clearcoatRoughnessMaps=e.clearcoatRoughnessMaps,this.sheenColorMaps=e.sheenColorMaps,this.sheenRoughnessMaps=e.sheenRoughnessMaps,this.iridescenceMaps=e.iridescenceMaps,this.iridescenceThicknessMaps=e.iridescenceThicknessMaps,this.specularIntensityMaps=e.specularIntensityMaps,this.specularColorMaps=e.specularColorMaps,this.diffuseTransmissionMaps=e.diffuseTransmissionMaps??[],this.diffuseTransmissionColorMaps=e.diffuseTransmissionColorMaps??[],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.instanceMatrices:null,o=e=>n?i[e]:e;this.instanceTable=new ma,this.instanceTable.allocate(r,t.length,a,n?i:null),this.instanceTable.tplBakeInverse=this.bakeInverse;let s=this._streamed;this._streamed=null;let c=[],l=[],u=[],d=new Map,f=new Map;for(let e=0;e<r;e++){let n=t[o(e)];if(!n||n.count===0)continue;let r=f.get(n.start);if(r!==void 0){d.set(e,r);continue}f.set(n.start,e),s?u.push({m:e,range:n}):this._isLargeMesh(n)?l.push({m:e,range:n}):c.push({m:e,range:n})}let p=this._blasWorkerOpts(),m=c.length+l.length,h=0,g=()=>{h++,z({status:`Building BLAS ${h}/${m}...`,progress:25+Math.floor(h/m*45)})},_=[...c,...l].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),v=s?null:await this._restoreBLASes(_,Sa.nodeCountFor(r),p),y=s?s.state:!v&&this._progressive&&this.triangles.chunks.length>1?await this._beginProgressiveSpill(_):null,b=y&&!s?(e,t,n)=>this._onBLASBuilt(y,o(e),t,n):null;if(s)for(let[e,t]of s.templates)this.instanceTable.tplObjectAABB.set(t.aabb,e*6);v&&(c.length=0,l.length=0,z({status:`Restored stored BVHs`,progress:68}));let x=v?Promise.resolve(v.results):s?Promise.resolve(u.map(({m:e,range:t})=>({m:e,range:t,result:s.templates.get(o(e)).result}))):this._buildBLASesWithPool(c,p,g,b),S=[],C=(async()=>{for(let{m:e,range:t}of l){let n=await this._buildLargeBLAS(t,p);b?.(e,t,n),S.push({m:e,range:t,result:n}),g()}})(),[w]=await Promise.all([x,C]);if(y&&(await y.chain,y.error))throw y.error;let T={sah:0,objMed:0,spatMed:0,failed:0};for(let{m:e,range:t,result:r}of[...w,...S]){let i=r.splitStats;i&&(T.sah+=i.sahSplits??0,T.objMed+=i.objectMedianSplits??0,T.spatMed+=i.spatialMedianSplits??0,T.failed+=i.failedSplits??0,this.performanceMetrics.blasWorkerTime+=i.totalBuildTime??0),this.instanceTable.setEntry({meshIndex:e,blasNodeCount:r.nodeCount??$s(r.bvhData)/64,triOffset:t.start,triCount:t.count,originalToBvhMap:r.originalToBvh||null,bvhData:r.bvhData,matrixWorld:n?a:this.meshes?.[e]?.matrixWorld?.elements??null,matrixOffset:n?e*16:0,expandedStart:t.expandedStart,sourceMesh:o(e)})}for(let[e,r]of d)this.instanceTable.setAlias(e,r,n?a:this.meshes?.[e]?.matrixWorld?.elements??null,t[o(e)].expandedStart,o(e),n?e*16:0);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 E=performance.now(),D=this.instanceTable;this.instanceTable.computeAABBs(this.triangles,{owners:!y}),this.instanceTable.assignOffsets(Sa.nodeCountFor(D.count));let O=this.instanceTable.totalNodeCount,k=await this._buildTLAS(D);this.performanceMetrics.tlasBuildTime=performance.now()-E,this.memory.mark(`assemble`);let A=performance.now();y||this._checkAssemblyHeadroom(O),this._setBVHData(Qt.lazy(O,16,Float32Array,void 0,Xt));let j=y?await this._beginBVHSpill(y,D.tlasNodeCount):null;this.bvh.setRecords(0,k),k=null,this.tlasBuilder.releaseFlattenBuffer();let M=Math.max(1,Math.ceil(D.templateCount/32));if(v){try{let e=performance.now();await ys(v.nodes,this.bvh,D.tlasNodeCount,O-D.tlasNodeCount),this.performanceMetrics.blasRestore.readMs=performance.now()-e}finally{v.release()}D.blasData.clear()}else{for(let e=0;e<D.templateCount;e++){let t=y?await this._readSpilledBLAS(y,e):D.blasData.get(e);if(!t)continue;let n=D.tplBlasOffset[e],r=n;for(let e of Qs(t))this.bvh.setRecords(r,e),r+=e.length/16;this._offsetBLASInPlace(n,r-n,n,D.tplTriOffset[e]),D.blasData.delete(e),await j?.(r),e%M===0&&this._sampleMemory(`assembling ${e}/${D.templateCount}`)}await j?.(O,!0),y&&await y.blasStore.dispose()}if(this._setBVHData(this.bvh.materializeAll()),v)for(let[e,t]of v.orders)D.bvhToOriginal.set(e,t);else this._buildBvhToOriginalMaps();this.performanceMetrics.bvhAssembleTime=performance.now()-A,D.originalToBvhMap.clear(),D.blasData.clear(),this.bvhRoot=!0,this._disposeRefitWorker();let N=performance.now()-e;Zs.debug(H.list([`${H.n(D.setCount)} BLASes + TLAS`,`${H.n(this.bvh.recordCount)} nodes`,`SAH ${H.n(T.sah)} · objMed ${T.objMed} · spatMed ${T.spatMed} · failed ${T.failed}`,H.ms(N)])),z({status:`BVH construction complete`,progress:75})}catch(e){throw Zs.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:be()}}_isLargeMesh(e){return e.count>=Gs&&oa(e.count)}async _buildLargeBLAS(e,t){if(e.count>Ks)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 ra(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 Ts(n,e.start,e.count,qs,{pause:()=>new Promise(e=>setTimeout(e,0))}),o=this._blasPool(t,null,null,Math.min(ir(),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),ma.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{...ks(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:${Ms}:${JSON.stringify(t)}:${n}:${this._sceneKey}`}async _restoreBLASes(e,t,n){if(!this._sceneKey||this.config.sceneCache===!1)return null;let r=Mr(Lr().cacheNamespace);if(!r)return null;this._blasKey=this._blasCacheKey(n);let i=await _s(r,this._blasKey);if(!i)return null;let a=e=>(Zs.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 gs(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 bs(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},Zs.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=Mr(Lr().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 gs(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 vs(t,r,{index:{v:2,tlasNodeCount:n.tlasNodeCount,totalNodes:n.totalNodeCount,templates:d},bvh:this.bvh,orders:u,isStale:a,label:e});return f&&Zs.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 on.create(t,`${i}:tri`,a,{label:`Triangle records`,expectedBytes:r.byteLength}),s=o&&await on.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`),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(Qs(a)[0],t,this.triangles,i.tplObjectAABB,t*6);let o=e.blasBytes;e.blasBytes+=$s(a),e.blasAt.set(t,o),r.nodeCount=$s(a)/64,r.bvhData=null,this._queueSpill(e,()=>tc(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;e.uploadTriangles(t);let i=n.lanesPerRecord;for(let n=K.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+=ec)i.push(new Float32Array(await e.blasStore.readAt(n+t,Math.min(ec,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 on.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);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),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),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);yi(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=cr(Yi);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 Zs.error(`texture creation failed:`,e),e}}_bucketTextures(){let e=this.config.maxTextureSize,t=Nt.MATERIAL_BUCKET_COUNT,n=Nt.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=Vt(r(i),e,t),s=Vt(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=Ht(e.image.width,e.image.height,a),s=e.source?.uuid??e.uuid,c=r[o].get(s);if(c!==void 0)return Ut(o,c);if(t[o].length>=n)return Zs.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=Ut(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._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){Zs.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.maps=n.maps,this.normalMaps=n.normalMaps,this.bumpMaps=n.bumpMaps,this.roughnessMaps=n.roughnessMaps,this.metalnessMaps=n.metalnessMaps,this.emissiveMaps=n.emissiveMaps,this.displacementMaps=n.displacementMaps,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 Zs.error(`material rebuild failed:`,e),e}finally{this.isProcessing=!1}}_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=Qt.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._tlasLeafBoxesOf=null,!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||=cr(Bs),!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=K.FLOATS_PER_TRIANGLE,o=[],s=[],c=0;for(let e=0;e<i.count;e++){if(!i.isSet[e]||!i.isOwner(e))continue;c++;let t=n(e);if(!t)continue;if(this._updateMeshTrianglePositions(e,t),s.push(i.blasOffsetOf(e),i.blasNodeCountOf(e)),r){let t=r(e);t&&this._patchMeshSmoothNormals(e,t)}let l=i.triOffsetOf(e)*a,u=i.triCountOf(e)*a,d=o.at(-1);d&&d.offset+d.count===l?d.count+=u:o.push({offset:l,count:u})}let l=i.tlasNodeCount,u=l>0&&s.length/2<c,d=u?[this.computeTLASDirtyRange()]:null;for(let e=0;u&&e<s.length;e+=2)d.push({offset:s[e]*16,count:s[e+1]*16});return new Promise((e,t)=>{this._refitWorker.onmessage=n=>{let r=n.data;r.type===`refitComplete`?e({refitTimeMs:r.refitTimeMs,triRanges:o,bvhRanges:d}):r.type===`error`&&t(Error(r.error))},this._refitWorker.postMessage({type:`refit`,blasRanges:u?s:null,tlasNodeCount:l})})}_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 Ki;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._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);this._movedPlacements?.length!==n.count&&(this._movedPlacements=new Uint8Array(n.count));let i=this._movedPlacements,a=0;for(let t of e){let e=this.meshes?.[t],o=n.placementRunOf(t);if(!e||!o)continue;e.updateMatrixWorld(!0);let s=e.matrixWorld.elements,c=e.isInstancedMesh?this._ownInstanceMatrices(e):null,l=n.tplBakeInverse?.get(n.sourceMesh[o.start])??null;for(let e=0;e<o.count;e++){let t=o.start+e;n.isSet[t]&&(c?(ua(s,c,e*16,r),n.setPlacementMatrix(t,r)):l?(ua(s,l,0,r),n.setPlacementMatrix(t,r)):n.setPlacementMatrix(t,s),this._writeLeafMatrix(t),i[t]=1,a++)}}return this._refitTLAS(i),i.fill(0),{refitTimeMs:performance.now()-t,placements:a}}_ownInstanceMatrices(e){let t=e.instanceMatrix;return t?.array?(t.array.buffer===this.instanceTable.world.buffer&&(t.array=t.array.slice(),t.needsUpdate=!0),t.array):null}_writeLeafMatrix(e){let t=this.instanceTable.tlasLeafIndex[e];t<0||Sa.writeLeafMatrix(this.bvh.chunkFor(t),this.bvhIndexChunks.chunkFor(t),this.bvh.baseOf(t),this.instanceTable.world,e)}computeTLASDirtyRange(){return{offset:0,count:this.instanceTable.tlasNodeCount*16}}computeBLASDirtyRanges(e){let t=K.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.tlasNodeCount*16}),{triRanges:n,bvhRanges:r}}uploadToPathTracer(e,t,n,r,{keepUserLights:i=!1}={}){return this.triangles?(e.setTriangleData(this.triangles,this.triangleCount),this.bvh?(e.setBVHData(this.bvh),e.setInstanceTable(this.instanceTable),this.materialData?e.materialData.setMaterialData(this.materialData,this.materials.map(e=>e.sources)):Zs.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):(Zs.error(`failed to get BVH data`),!1)):(Zs.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)}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 on.create(e,`${a}:tri`,o(t),{label:`Triangle records`,expectedBytes:t.byteLength}),c=s&&await on.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?.tlasNodeCount??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 Zs.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?.(),this.spilled||this._disposeSpill()})().finally(()=>{this._paging=null}),this._paging}async _restoreGeometry(e){let t=this._geometrySpill;if(!t?.bytes)return;z({status:`Reading scene geometry back...`,progress:84});let n=performance.now(),r=t.bytes;await t.restore(),this._disposeGeometrySpill(),this._geometryBytes=xn(e),Zs.info(`read ${H.mb(r)} of scene geometry back from disk in ${H.ms(performance.now()-n)}`),t.error&&Zs.warn(`some scene geometry stayed in memory, its spill write failed:`,t.error)}_disposeGeometrySpill(){let e=this._geometrySpill;this._geometrySpill=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)}async _buildTLAS(e){let t=e.count;if(t>=Ws&&!this._tlasWorkerFailed)try{let n=new Float64Array(t*6);e.writeWorldAABBs(n);let{tlasData:r,nodeCount:i}=await this._runTLASWorker(n,t);return Sa.fillLeaves(r,i,e),r}catch(e){this._tlasWorkerFailed=!0,Zs.warn(`TLAS worker unavailable (${e.message}); building on the main thread`)}return this.tlasBuilder.build(e).data}_runTLASWorker(e,t){this._tlasWorker||=cr(Us);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:be()},[e.buffer])})}_setBVHData(e){this._tlasLeafBoxesOf=null;let t=e?e instanceof Qt?e:Qt.adopt([e],e.length/16,16,e.length/16):null;this.bvh=t,t&&this._foldLeaves&&(t.foldedLeaves=!0),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=K.FLOATS_PER_TRIANGLE,n=e?e instanceof Qt?e:Qt.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=K.POSITION_A_OFFSET,r=K.POSITION_B_OFFSET,i=K.POSITION_C_OFFSET,a=K.NORMAL_A_PACKED_OFFSET,o=K.NORMAL_B_PACKED_OFFSET,s=K.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=da(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=mt(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=K.NORMAL_A_PACKED_OFFSET,o=K.NORMAL_B_PACKED_OFFSET,s=K.NORMAL_C_PACKED_OFFSET,c=r,l=!c||da(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]]=mt(f,p,m)}}}_refitTLAS(e=null){let t=this.instanceTable.tlasNodeCount;(!this._tlasBounds||this._tlasBounds.length<t*6)&&(this._tlasBounds=new Float32Array(t*6),this._tlasLeafBoxesOf=null);let n=this.instanceTable,r=e&&this._tlasLeafBoxesOf===n;for(let i=t-1;i>=0;i--){let t=this.bvhIndexChunks.chunkFor(i),a=this.bvh.chunkFor(i),o=this.bvh.baseOf(i),s=t[o+3];if(s===St.BLAS_POINTER_LEAF){let a=t[o+1]&xt;a<n.count&&!(r&&!e[a])&&n.writeWorldAABB(a,this._tlasBounds,i*6)}else if(s<St.TRIANGLE_LEAF){let e=s,n=t[o+7],r=e*6,c=n*6,l=this._tlasBounds;a[o]=l[r],a[o+1]=l[r+1],a[o+2]=l[r+2],a[o+4]=l[r+3],a[o+5]=l[r+4],a[o+6]=l[r+5],a[o+8]=l[c],a[o+9]=l[c+1],a[o+10]=l[c+2],a[o+12]=l[c+3],a[o+13]=l[c+4],a[o+14]=l[c+5];let u=i*6;l[u]=Math.min(l[r],l[c]),l[u+1]=Math.min(l[r+1],l[c+1]),l[u+2]=Math.min(l[r+2],l[c+2]),l[u+3]=Math.max(l[r+3],l[c+3]),l[u+4]=Math.max(l[r+4],l[c+4]),l[u+5]=Math.max(l[r+5],l[c+5])}}this._tlasLeafBoxesOf=n}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){Zs.error(`background BLAS rebuild failed (mesh ${e}):`,o.error);return}n===this._rebuildGeneration&&this._swapBLAS(e,r,o,t)},i.onerror=t=>{Zs.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,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,cr(Yi))}}_swapBLAS(e,t,n,r){this._geometryVersion=(this._geometryVersion??0)+1;let i=n.bvhData,a=i.length/16;if(a>t.blasNodeCount){Zs.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}},ic=[[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]],ac=[[-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]],oc=[[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 sc(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=ic[i],o=ac[i],s=oc[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)]}Fn();var cc=1/(4*Math.PI);function lc(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]=sc(t.temperature??6500);i[0]*=e,i[1]*=n,i[2]*=r}return jn(i),{r:i[0],g:i[1],b:i[2],intensity:r}}var uc=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=lc(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=lc(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=lc(e);this.pointLightCache.push({data:[t.x,t.y,t.z,i.r,i.g,i.b,i.intensity*cc,e.distance||0,e.decay===void 0?2:e.decay],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=lc(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*cc,e.angle||Math.PI/4,e.penumbra||0,e.distance||0,e.decay===void 0?2:e.decay,o,c,u,d,0,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}))}}},dc,fc,pc,mc,hc,gc,_c,vc,yc,bc,xc,Sc,Cc,wc,Tc,Ec,Dc=g((()=>{dc=C({origin:`vec3`,direction:`vec3`}),fc=C({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`,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`}),pc=C({transmission:`float`,clearcoat:`float`,clearcoatRoughness:`float`,sheenColor:`vec3`,sheenRoughness:`float`,iridescence:`float`,iridescenceThickness:`float`,specularIntensity:`float`,specularColor:`vec3`,diffuseTransmission:`float`,diffuseTransmissionColor:`vec3`}),mc=C({color:`vec4`,ior:`float`,transmission:`float`,attenuationColor:`vec3`,attenuationDistance:`float`,albedoMapIndex:`int`,opacity:`float`,transparent:`bool`,alphaTest:`float`,alphaMode:`int`,albedoTransform:`mat3`}),hc=C({shadowed:`vec3`,unoccluded:`vec3`}),C({position:`vec3`,radius:`float`,material:fc}),gc=C({didHit:`bool`,dst:`float`,hitPoint:`vec3`,normal:`vec3`,uv:`vec2`,materialIndex:`int`,meshIndex:`int`,instanceLeaf:`int`,triangleIndex:`int`,boxTests:`int`,triTests:`int`}),C({posA:`vec3`,posB:`vec3`,posC:`vec3`,uvA:`vec2`,uvB:`vec2`,uvC:`vec2`,normalA:`vec3`,normalB:`vec3`,normalC:`vec3`,material:fc,materialIndex:`int`,meshIndex:`int`}),C({color:`vec4`,samples:`int`}),_c=C({direction:`vec3`,value:`vec3`,pdf:`float`,isTransmission:`bool`,colorWeight:`vec3`,isDiffuseTransmission:`bool`}),vc=C({specular:`float`,diffuse:`float`,sheen:`float`,clearcoat:`float`,transmission:`float`,iridescence:`float`,diffuseTransmission:`float`}),yc=C({Ta:`vec3`,Ba:`vec3`}),bc=C({NoL:`float`,NoV:`float`,NoH:`float`,VoH:`float`,LoH:`float`,ToH:`float`,BoH:`float`,ToV:`float`,BoV:`float`,ToL:`float`,BoL:`float`}),xc=C({compensation:`vec3`,E_total:`vec3`}),Sc=C({f0:`vec3`,f90:`float`,eta:`float`,F0m:`vec3`,F0:`vec3`}),Cc=C({albedo:`vec4`,emissive:`vec3`,metalness:`float`,roughness:`float`,normal:`vec3`,hasTextures:`bool`}),wc=C({isMetallic:`bool`,isRough:`bool`,isSmooth:`bool`,isTransmissive:`bool`,hasClearcoat:`bool`,isEmissive:`bool`,complexityScore:`float`}),Tc=C({albedoUV:`vec2`,normalUV:`vec2`,metalnessUV:`vec2`,emissiveUV:`vec2`,bumpUV:`vec2`,roughnessUV:`vec2`,normalBumpSameUV:`bool`,metalRoughSameUV:`bool`,albedoEmissiveSameUV:`bool`,allSameUV:`bool`}),Ec=C({invRoughness:`float`,metalFactor:`float`,iorFactor:`float`,maxSheenColor:`float`}),C({traversals:`int`,transmissiveTraversals:`int`,rayType:`int`,isPrimaryRay:`bool`,actualBounceDepth:`int`})})),Oc,kc,Ac,jc,Mc,Nc,Pc,Fc,Ic,Lc,Rc,zc,Bc,Vc,Hc,Uc,Wc,Gc,Kc,qc,Jc,Yc,Xc,Zc,Qc,$c,el,tl,Z,nl,rl,il,al,ol,sl,cl,ll,ul,dl,fl,pl,ml,hl=g((()=>{Dc(),wt(),Oc=(0,n.wgslFn)(`
|
|
247
|
+
`,bindings:n}}function bo(){Co.length=0,Co.push(...ao),wo.clear();for(let e of Co)wo.set(e.id,e);so()}var xo,So,Co,wo,To,Eo,Do,Oo,ko,Ao=g((()=>{oo(),xo=200,So=12,Co=[...ao],wo=new Map(Co.map(e=>[e.id,e])),To=1,Eo=new Set,Do=wo,Oo=r.NoToneMapping,ko=r.AgXToneMapping}));Ao();var jo=e=>(t,n,r,i,a)=>e(t>0?t:0,n>0?n:0,r>0?r:0,i,a),Mo=new Map;function No(){Mo.clear();for(let e of Do.values())Mo.set(e.id,jo(e.cpu))}No(),lo(No);function Po(e){return uo(e)?.outputEncoded===!0}function Fo(e){return e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055}function Io(e,t){let n=uo(t);return n?n.appliesExposure?e:1:t===r.NoToneMapping?1:e}var Lo=.2126,Ro=.7152,zo=.0722;function Bo(e,t){if(t===1)return;let n=e[0]*Lo+e[1]*Ro+e[2]*zo;e[0]=n+(e[0]-n)*t,e[1]=n+(e[1]-n)*t,e[2]=n+(e[2]-n)*t}function Vo(e,{exposure:t,toneMapping:n,saturation:i=1,preserveAlpha:a=!1}){let o=Mo.get(n)??Mo.get(r.NoToneMapping),s=Io(t,n),c=Po(n),l=new Uint8ClampedArray(e.length),u=[0,0,0];for(let t=0;t<e.length;t+=4)u[0]=e[t]*s,u[1]=e[t+1]*s,u[2]=e[t+2]*s,Bo(u,i),o(u[0],u[1],u[2],1,u),c?(l[t]=u[0]*255+.5,l[t+1]=u[1]*255+.5,l[t+2]=u[2]*255+.5):(l[t]=Fo(u[0])*255+.5,l[t+1]=Fo(u[1])*255+.5,l[t+2]=Fo(u[2])*255+.5),l[t+3]=a?e[t+3]*255+.5:255;return l}wt(),X(),Ae(),dr();var Ho=ye(`textures`),Uo={MAX_BUFFER_MEMORY:1024*1024*1024,MAX_TEXTURE_MEMORY:2048*1024*1024,CLEANUP_THRESHOLD:.8,STREAM_BATCH_SIZE:4},Wo=8*2**20,Go=16,Ko=4,qo=8192*8192,Jo={busy:0,waiting:[]};async function Yo(){return Jo.busy<Math.max(1,ir()-1)?Jo.busy++:await new Promise(e=>Jo.waiting.push(e)),()=>{let e=Jo.waiting.shift();e?e():Jo.busy--}}var Xo={toSRGB:null,toLinear:null};function Zo(e){if(!Xo[e]){let t=new Uint8Array(256);for(let n=0;n<256;n++){let r=n/255,i=e===`toSRGB`?Fo(r):r<=.04045?r/12.92:((r+.055)/1.055)**2.4;t[n]=Math.max(0,Math.min(255,Math.round(i*255)))}Xo[e]=t}return Xo[e]}var Qo=class{constructor(){this.canvasContextPairs=[],this.maxPoolSize=Nt.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=[]}},$o=class{constructor(e={}){this.pools=new Map,this.memoryUsage=0,this.maxMemoryUsage=e.maxMemory||Uo.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*Uo.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<Nt.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`}},es=class{constructor(e=Nt.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=[]}},ts=class{constructor(e={}){this.useWorkers=typeof Worker<`u`,this.maxConcurrentWorkers=Nt.MAX_CONCURRENT_WORKERS,this.activeWorkers=0,this._issues=e.issues??null,this.maxTextureSize=this._clampTextureSize(e.maxTextureSize??Nt.DEFAULT_MAX_TEXTURE_SIZE),this.canvasPool=new Qo,this.bufferPool=new $o({maxMemory:e.maxBufferMemory||Uo.MAX_BUFFER_MEMORY,sizeStrategy:e.bufferSizeStrategy||`adaptive`}),this.textureCache=new es,this.capabilities=this.detectCapabilities(),this.optimalMethod=this.selectOptimalMethod()}_reportTextureFailure(e,t){if(t instanceof Gt)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)||Nt.DEFAULT_MAX_TEXTURE_SIZE);return Math.max(Nt.MIN_TEXTURE_WIDTH,Math.min(t,Nt.MAX_TEXTURE_SIZE))}setMaxTextureSize(e){let t=this._clampTextureSize(e);return t===this.maxTextureSize?t:(this.maxTextureSize=t,this.textureCache?.dispose(),this.textureCache=new es,this.maxTextureSize)}detectCapabilities(){return{offscreenCanvas:typeof OffscreenCanvas<`u`,imageBitmap:typeof createImageBitmap<`u`,workers:typeof Worker<`u`,hardwareConcurrency:ir()}}selectOptimalMethod(){return this.capabilities.workers&&this.capabilities.offscreenCanvas?`worker-offscreen`:this.capabilities.imageBitmap?`imageBitmap`:`canvas`}_applyColorManagement(e,t,n,i=new Set){let a=kr();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){Ho.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,Ho.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=Zo(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?Ho.info(`re-encoded ${l.length}/${o.length} linear-declared colour map(s) to sRGB so the GPU decode round-trips: ${u}`):Ho.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=kr()?.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 Gt)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>Uo.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 Va;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)<qo)return 0;let t=this.maxConcurrentWorkers-this.activeWorkers;return Math.max(0,Math.min(e.length,Ko,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=cr(Va);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=cr(Va);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>=Uo.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>Go&&(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=r?.data;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=or()&&i*t.length>=Wo?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)=>Ga(e,o,t*i,n,r)),this.createDataArrayTextureFromBuffer(o,n,r,t.length)}async _packInWorker(e,t,n){let r=await Yo(),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=cr(Wa),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%Uo.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=q.FLOATS_PER_MATERIAL,n=new Float32Array(e.length*t);for(let r=0;r<e.length;r++)Mt(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=Nt.VEC4_PER_BVH_NODE*Nt.FLOATS_PER_VEC4;gt(t.length,`BVH node count`);let i=t.length*r,a=new Float32Array(i),o=ht(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]=St.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 es;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:Ft(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:ns(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),i.push({index:e,flipY:n.flipY,promise:ns(n.image.data,n.image.width,n.image.height)});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()}};function ns(e,t,n){let r=new Uint8ClampedArray(e.buffer,e.byteOffset,e.byteLength);return createImageBitmap(new ImageData(r,t,n))}var rs=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=as(E,is(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=as(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 is(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 as(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)}}wt(),Ae(),Fn();var os=Object.freeze({r:0,g:0,b:0});function ss(e){if(!e)return os;if(!kn())return e;let t=[e.r,e.g,e.b];return jn(t),{r:t[0],g:t[1],b:t[2]}}var cs=ye(`emissive`),ls=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=K.FLOATS_PER_TRIANGLE,a=K.MATERIAL_FLAGS_OFFSET,o=K.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]&_t,h=n[p+o],g=t[m];if(!g)continue;let _=d.get(g);_===void 0&&(_=ss(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.world:null,a=n?t*16:0,o=(e,t,n)=>i?i[a]*e+i[a+4]*t+i[a+8]*n+i[a+12]:e,s=(e,t,n)=>i?i[a+1]*e+i[a+5]*t+i[a+9]*n+i[a+13]:t,c=(e,t,n)=>i?i[a+2]*e+i[a+6]*t+i[a+10]*n+i[a+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),ue=Math.max(E,k,M),z=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:ue,bMaxZ:z,nx:I,ny:L,nz:ee,twoSided:ne}),this.totalEmissivePower+=F}}return this.emissiveCount=this.emissiveTriangles.length,this.emissiveCount>0&&cs.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=K.FLOATS_PER_TRIANGLE,o=t.world;this.totalEmissivePower=0;for(let e of this.emissiveTriangles){let s=n?r.chunkFor(e.triangleIndex):i,c=n?n.baseOf(e.triangleIndex):e.triangleIndex*a,l=[s[c],s[c+1],s[c+2],s[c+4],s[c+5],s[c+6],s[c+8],s[c+9],s[c+10]],u=t.placementRunOf?.(e.meshIndex)?.start??-1;if(u>=0&&t.isSet[u]){let e=u*16;for(let t=0;t<9;t+=3){let n=l[t],r=l[t+1],i=l[t+2];l[t]=o[e]*n+o[e+4]*r+o[e+8]*i+o[e+12],l[t+1]=o[e+1]*n+o[e+5]*r+o[e+9]*i+o[e+13],l[t+2]=o[e+2]*n+o[e+6]*r+o[e+10]*i+o[e+14]}}let[d,f,p,m,h,g,_,v,y]=l,b=this._calculateTriangleArea(d,f,p,m,h,g,_,v,y),x=e.emissive;e.power=(.2126*x.r+.7152*x.g+.0722*x.b)*e.emissiveIntensity*b,e.area=b;let S=(h-f)*(y-p)-(g-p)*(v-f),C=(g-p)*(_-d)-(m-d)*(y-p),w=(m-d)*(v-f)-(h-f)*(_-d),T=(Math.sqrt(S*S+C*C+w*w)||1)/e.sideSign;e.nx=S/T,e.ny=C/T,e.nz=w/T,e.cx=(d+m+_)/3,e.cy=(f+h+v)/3,e.cz=(p+g+y)/3,e.bMinX=Math.min(d,m,_),e.bMinY=Math.min(f,h,v),e.bMinZ=Math.min(p,g,y),e.bMaxX=Math.max(d,m,_),e.bMaxY=Math.max(f,h,v),e.bMaxZ=Math.max(p,g,y),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,cs.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 cs.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=ss(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(Math.max(this._totalTriangleCount,1)).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 rs().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,cs.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}};Ae();var us=class{constructor(e=`Build`,{namespace:t=`build`,level:n=`debug`}={}){this.label=e,this.level=n,this.logger=ye(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)}}};nn();var ds=1<<20,fs=1<<21,ps=()=>new Promise(e=>setTimeout(e,0)),ms=[0,1,2,4,5,6,8,9,10];function hs(e,t,n,r=ms){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 gs(e,t){let n=[],r=0;for(let{triOffset:i,triCount:a}of t)n.push(hs(e,i,a)),r+=a,r>=fs&&(r=0,await ps());return n}async function _s(e,t){let n=await e?.area(tn.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 vs(e,t,{index:n,bvh:r,orders:i,isStale:a,label:o=``}){let s=e?.area(tn.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,ds),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+=ds*4)await u.write(`order.u32`,e.subarray(t,Math.min(e.length,t+ds*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 ys(e,t,n,r){for(let i=0;i<r;i+=ds){let a=Math.min(ds,r-i),o=await e.slice(i*64,(i+a)*64).arrayBuffer();t.setRecords(n+i,new Float32Array(o))}}async function bs(e,t,n){return new Uint32Array(await e.slice(t*4,(t+n)*4).arrayBuffer())}wt();var xs=16,Ss=K.POSITION_A_OFFSET,Cs=K.POSITION_B_OFFSET,ws=K.POSITION_C_OFFSET;async function Ts(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+Ss]+o[n+Cs]+o[n+ws],c[r]=o[n+Ss+1]+o[n+Cs+1]+o[n+ws+1],l[r]=o[n+Ss+2]+o[n+Cs+2]+o[n+ws+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 Ds(u,o,Es(o,e,t),e,t,n),{left:f(e,n),right:f(n,t)}},p=f(0,n);return await i?.(),await Os(e,t,n,u,i),{order:u,pieces:d,tree:p}}function Es(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 Ds(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 Os(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 ks(e,t,n,r){let i=t.length-1,a=[],o=i;for(let{bvhData:e}of n)a.push(o),o+=e.length/xs;let s=new Float32Array(i*xs),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];yi(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*xs;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 As,js=g((()=>{As=`11.2.1`})),Ms,Ns=g((()=>{js(),Ms=As}));function Ps(e,t,n=Fs){return e>=n&&t/Is<e/3}var Fs,Is,Ls=g((()=>{Fs=1e4,Is=15e5}));Ns(),Ls();var Rs="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};n.TRIANGLE_LEAF;const r=e=>e>=2147483648,i=e=>~e>>>0>>>4,a=e=>~e&15,o=e.FLOATS_PER_TRIANGLE,s=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),c=e=>e instanceof Uint32Array?e:new Uint32Array(e.buffer,e.byteOffset,e.length),l=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:e,idx:t?e.viewAs(Uint32Array):c(e)}},u=(e,t)=>e.chunked?e.f.chunkFor(t):e.f,d=(e,t)=>e.chunked?e.idx.chunkFor(t):e.idx,f=(e,t)=>e.chunked?e.chunked.baseOf(t):t*m,p=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:t?t.viewAs(Float32Array):s(e),u:t?e:c(e)}},m=16,h=n.TRIANGLE_LEAF,g=n.BLAS_POINTER_LEAF;function _(e,t,n,r,i,a){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 v(t,n,r,i,a){let s=e.POSITION_A_OFFSET,c=e.POSITION_B_OFFSET,l=e.POSITION_C_OFFSET,u=1/0,d=1/0,f=1/0,p=-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*o;u=Math.min(u,i[a+s],i[a+c],i[a+l]),d=Math.min(d,i[a+s+1],i[a+c+1],i[a+l+1]),f=Math.min(f,i[a+s+2],i[a+c+2],i[a+l+2]),p=Math.max(p,i[a+s],i[a+c],i[a+l]),m=Math.max(m,i[a+s+1],i[a+c+1],i[a+l+1]),h=Math.max(h,i[a+s+2],i[a+c+2],i[a+l+2])}i[a]=u,i[a+1]=d,i[a+2]=f,i[a+3]=p,i[a+4]=m,i[a+5]=h}const y=new Float32Array(12);function b(e,t,n,r){let i=u(e,t),a=d(e,t),o=f(e,t);if(a[o+3]===h){v(n,a[o],a[o+1],r,0);return}for(let e=0;e<3;e++)r[e]=Math.min(i[o+e],i[o+8+e]),r[3+e]=Math.max(i[o+4+e],i[o+12+e])}function x(e,t,n,o,s){let c=u(e,t),l=d(e,t),p=f(e,t),m=(t-s)*6,b=l[p+3];if(b===h){v(n,l[p],l[p+1],o,m);return}if(b===g){_(c,p,o,(l[p]-s)*6,o,m);return}let x=l[p+7],S=o,C=(b-s)*6;r(b)&&(v(n,i(b),a(b),y,0),S=y,C=0);let w=o,T=(x-s)*6;r(x)&&(v(n,i(x),a(x),y,6),w=y,T=6),c[p]=S[C],c[p+1]=S[C+1],c[p+2]=S[C+2],c[p+4]=S[C+3],c[p+5]=S[C+4],c[p+6]=S[C+5],c[p+8]=w[T],c[p+9]=w[T+1],c[p+10]=w[T+2],c[p+12]=w[T+3],c[p+13]=w[T+4],c[p+14]=w[T+5];for(let e=0;e<3;e++)o[m+e]=Math.min(S[C+e],w[T+e]),o[m+3+e]=Math.max(S[C+3+e],w[T+3+e])}var S=class{constructor(){this._bounds=null,this._boundsNodeCount=0,this._tlasBounds=null,this._rootBox=null}updateTrianglePositions(n,r,i){let a=i.length,s=p(n);for(let n=0;n<a;n++){let a=i[n],c=s.chunked?s.f.chunkFor(n):s.f,l=s.chunked?s.u.chunkFor(n):s.u,u=s.chunked?s.chunked.baseOf(n):n*o,d=a*9,f=r[d],p=r[d+1],m=r[d+2],h=r[d+3],g=r[d+4],_=r[d+5],v=r[d+6],y=r[d+7],b=r[d+8];c[u+e.POSITION_A_OFFSET]=f,c[u+e.POSITION_A_OFFSET+1]=p,c[u+e.POSITION_A_OFFSET+2]=m,c[u+e.POSITION_B_OFFSET]=h,c[u+e.POSITION_B_OFFSET+1]=g,c[u+e.POSITION_B_OFFSET+2]=_,c[u+e.POSITION_C_OFFSET]=v,c[u+e.POSITION_C_OFFSET+1]=y,c[u+e.POSITION_C_OFFSET+2]=b;let x=h-f,S=g-p,C=_-m,w=v-f,T=y-p,E=b-m,D=t(S*E-C*T,C*w-x*E,x*T-S*w);l[u+e.NORMAL_A_PACKED_OFFSET]=D,l[u+e.NORMAL_B_PACKED_OFFSET]=D,l[u+e.NORMAL_C_PACKED_OFFSET]=D}}refitRange(e,t,n,r){let i=p(t);r>this._boundsNodeCount&&(this._bounds=new Float32Array(r*6),this._boundsNodeCount=r);let a=l(e);for(let e=n+r-1;e>=n;e--)x(a,e,i,this._bounds,n)}refitPartial(e,t,n,r){for(let r=0;r<n.length;r+=2)this.refitRange(e,t,n[r],n[r+1]);let i=p(t),a=l(e);(!this._tlasBounds||this._tlasBounds.length<r*6)&&(this._tlasBounds=new Float32Array(r*6));let o=this._tlasBounds,s=this._rootBox||=new Float32Array(6);for(let e=r-1;e>=0;e--){let t=d(a,e),n=f(a,e);t[n+3]===g?(b(a,t[n],i,s),_(u(a,e),n,s,0,o,e*6)):x(a,e,i,o,0)}}refit(e,t,n){let r=p(t);n!==this._boundsNodeCount&&(this._bounds=new Float32Array(n*6),this._boundsNodeCount=n);let i=l(e);for(let e=n-1;e>=0;e--)x(i,e,r,this._bounds,0)}};const C=64*1024*1024;function w(e,t,n){return n?new e(new SharedArrayBuffer(t*e.BYTES_PER_ELEMENT)):new e(t)}var T=class e{constructor(e,t,n,r=C,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(w(n,e*t,i)),s-=e}this.chunks.length===0&&this.chunks.push(w(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=C,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]=w(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=await this._store.read(e,t*this.LaneType.BYTES_PER_ELEMENT),r=w(this.LaneType,t,this.shared);new Uint8Array(r.buffer,r.byteOffset,r.byteLength).set(new Uint8Array(n)),this.chunks[e]=r;for(let t of this._liveViews())t.chunks[e]=new t.LaneType(r.buffer,r.byteOffset,r.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=w(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 E=new S;let D=null,O=null,k=0;self.onmessage=function(e){let{type:t}=e.data;if(t===`init`){D=T.adopt(e.data.sharedBvhBufs.map(e=>new Float32Array(e)),e.data.bvhRecordCount,16,e.data.bvhRecordsPerChunk),O=T.adopt(e.data.sharedTriBufs.map(e=>new Uint32Array(e)),e.data.triRecordCount,e.data.triLanesPerRecord,e.data.triRecordsPerChunk),k=D.recordCount;return}if(t===`refit`)try{let t=performance.now(),{blasRanges:n,tlasNodeCount:r}=e.data;n?E.refitPartial(D,O,n,r):E.refit(D,O,k),self.postMessage({type:`refitComplete`,refitTimeMs:performance.now()-t})}catch(e){console.error(`[BVHRefitWorker] Refit error:`,e),self.postMessage({type:`error`,error:e.message})}};",zs=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Rs],{type:`text/javascript;charset=utf-8`});function Bs(e){let t;try{if(t=zs&&(self.URL||self.webkitURL).createObjectURL(zs),!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(Rs),{type:`module`,name:e?.name})}}var Vs="const e={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826};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]);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=new Float64Array(e.count*6);e.writeWorldAABBs(t);let n=this.buildStructure(t,e.count);return r.fillLeaves(n.data,n.nodeCount,e),n}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=a.world,s=a.sourceMesh,c=a.tplBlasOffset,l=a.visible,u=a.tlasLeafIndex,d=t(n);for(let t=0;t<i;t++){let i=t*16;if(d[i+3]!==e.BLAS_POINTER_LEAF)continue;let a=d[i+1]&1073741823;d[i]=c[s[a]],n[i+2]=+!!l[a],r.writeLeafMatrix(n,d,i,o,a),u[a]=t}}static writeLeafMatrix(e,t,n,r,i){let s=c;a(r,i*16,s),e[n+4]=s[0],e[n+5]=s[4],e[n+6]=s[8],e[n+7]=s[12],e[n+8]=s[1],e[n+9]=s[5],e[n+10]=s[9],e[n+11]=s[13],e[n+12]=s[2],e[n+13]=s[6],e[n+14]=s[10],e[n+15]=s[14],t[n+1]=(i|(o(r,i*16)?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})}};",Hs=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Vs],{type:`text/javascript;charset=utf-8`});function Us(e){let t;try{if(t=Hs&&(self.URL||self.webkitURL).createObjectURL(Hs),!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(Vs),{type:`module`,name:e?.name})}}$t(),Ae(),wt(),X(),Pr(),Br(),dr();var Ws=5e4,Gs=2e5,Ks=2e6,qs=1<<19,Js=4e7,Ys=1.5*1024**3,Xs=256*1024*1024,Zs=ye(`scene`),Qs=e=>Array.isArray(e)?e:[e],$s=e=>Qs(e).reduce((e,t)=>e+t.byteLength,0),ec=64*1024*1024;async function tc(e,t,n){for(let r of Qs(n))await e.writeAt(t,r),t+=r.byteLength}function nc(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 rc=class{constructor(e={}){this.config={useWorkers:!0,bvhDepth:30,maxLeafSize:4,verbose:!1,useFloat32Array:!0,textureQuality:`adaptive`,maxTextureSize:Nt.DEFAULT_MAX_TEXTURE_SIZE,enableTextureCache:!0,maxConcurrentTextureTasks:Math.min(ir(),6),maxSceneBytes:Ma,sceneCache:!0,sceneCacheMinBuildMs:Fs,...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 La,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 Dn({issues:this.config.issues}),this.bvhBuilder=new Oi,this.bvhBuilder.maxLeafSize=this.config.maxLeafSize,this.textureCreator=new ts({maxTextureSize:this.config.maxTextureSize,issues:this.config.issues}),this.emissiveTriangleBuilder=new ls,this.tlasBuilder=new Sa,this._tlasWorker=null,this._tlasWorkerFailed=!1}_log(e,t){t===void 0?Zs.debug(e):Zs.debug(e,t)}_preflightMemory(e){let t=this.config.maxSceneBytes??9663676416,n=this.geometryExtractor.surveyScene(e),r=wa(n);if(this._progressive&&(r.total-=r.bvh),this._streaming){let t=Ys+nc(e)*(K.FLOATS_PER_TRIANGLE*4+44);r.total-=Math.max(0,r.triangles-t)}let i={...n,estimate:r,safeBytes:ja,maxBytes:t,fits:r.total<=ja};if(this.memoryPreflight=i,r.total<1610612736)return i;if(Zs.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(ja)} 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:ja}),i}_checkAssemblyHeadroom(e){let t=e*64;if(t<1610612736)return!0;let n=Ta(Math.ceil(t*Fa),{shared:Xt});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?.world?.byteLength??0,blasScratch:0,orderMaps:0};if(e){for(let n of e.blasData.values())t.blasScratch+=n?$s(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;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;Zs.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,qt(e=>this.memory.alloc(e));let r=new us(e.name??``,{namespace:`scene`});try{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/(K.FLOATS_PER_TRIANGLE*4)),this._foldLeaves=i>Js,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=xn(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`,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=>Zs.debug(`storing BLASes failed:`,e))),this}catch(e){throw this.processingStage=`error`,Zs.error(`processing failed:`,e),z({status:`Error: ${e.message}`,failed:!0,progress:100}),e}finally{this._disposeGeometrySpill(),qt(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 Zs.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:`Extracting geometry and building BVHs...`,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=Qt.lazy(o,K.FLOATS_PER_TRIANGLE,Uint32Array),c=s.recordsPerChunk*s.lanesPerRecord*4,l=await on.create(r,`${a}:tri`,c,{label:`Triangle records`,expectedBytes:o*c/s.recordsPerChunk}),u=l&&await on.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 fn.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);ma.rootAABB(Qs(r)[0],v,t.start,t.count,i,0),p.set(e,{result:n,aabb:i});let a=f.blasBytes;f.blasBytes+=$s(r),f.blasAt.set(e,a),n.nodeCount=$s(r)/64,n.bvhData=null,this._queueSpill(f,()=>tc(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`)},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>Xs&&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>Ys&&(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),Zs.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=gt(e.triangleCount,`triangle count`),this._foldLeaves&&this.triangleCount>134217728)throw RangeError(`${this.triangleCount.toLocaleString()} triangles is past the ${Ct.toLocaleString()} a folded BVH leaf can address`);this.expandedTriangleCount=e.expandedTriangleCount??e.triangleCount,this.instanceSource=e.instanceSource||null,this.instanceMatrices=e.instanceMatrices||null,this.instanceCount=e.instanceCount||0,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.maps=e.maps,this.normalMaps=e.normalMaps,this.bumpMaps=e.bumpMaps,this.roughnessMaps=e.roughnessMaps,this.metalnessMaps=e.metalnessMaps,this.emissiveMaps=e.emissiveMaps,this.displacementMaps=e.displacementMaps,this.anisotropyMaps=e.anisotropyMaps,this.transmissionMaps=e.transmissionMaps,this.clearcoatMaps=e.clearcoatMaps,this.clearcoatRoughnessMaps=e.clearcoatRoughnessMaps,this.sheenColorMaps=e.sheenColorMaps,this.sheenRoughnessMaps=e.sheenRoughnessMaps,this.iridescenceMaps=e.iridescenceMaps,this.iridescenceThicknessMaps=e.iridescenceThicknessMaps,this.specularIntensityMaps=e.specularIntensityMaps,this.specularColorMaps=e.specularColorMaps,this.diffuseTransmissionMaps=e.diffuseTransmissionMaps??[],this.diffuseTransmissionColorMaps=e.diffuseTransmissionColorMaps??[],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.instanceMatrices:null,o=e=>n?i[e]:e;this.instanceTable=new ma,this.instanceTable.allocate(r,t.length,a,n?i:null),this.instanceTable.tplBakeInverse=this.bakeInverse;let s=this._streamed;this._streamed=null;let c=[],l=[],u=[],d=new Map,f=new Map;for(let e=0;e<r;e++){let n=t[o(e)];if(!n||n.count===0)continue;let r=f.get(n.start);if(r!==void 0){d.set(e,r);continue}f.set(n.start,e),s?u.push({m:e,range:n}):this._isLargeMesh(n)?l.push({m:e,range:n}):c.push({m:e,range:n})}let p=this._blasWorkerOpts(),m=c.length+l.length,h=0,g=()=>{h++,z({status:`Building BLAS ${h}/${m}...`,progress:25+Math.floor(h/m*45)})},_=[...c,...l].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),v=s?null:await this._restoreBLASes(_,Sa.nodeCountFor(r),p),y=s?s.state:!v&&this._progressive&&this.triangles.chunks.length>1?await this._beginProgressiveSpill(_):null,b=y&&!s?(e,t,n)=>this._onBLASBuilt(y,o(e),t,n):null;if(s)for(let[e,t]of s.templates)this.instanceTable.tplObjectAABB.set(t.aabb,e*6);v&&(c.length=0,l.length=0,z({status:`Restored stored BVHs`,progress:68}));let x=v?Promise.resolve(v.results):s?Promise.resolve(u.map(({m:e,range:t})=>({m:e,range:t,result:s.templates.get(o(e)).result}))):this._buildBLASesWithPool(c,p,g,b),S=[],C=(async()=>{for(let{m:e,range:t}of l){let n=await this._buildLargeBLAS(t,p);b?.(e,t,n),S.push({m:e,range:t,result:n}),g()}})(),[w]=await Promise.all([x,C]);if(y&&(await y.chain,y.error))throw y.error;let T={sah:0,objMed:0,spatMed:0,failed:0};for(let{m:e,range:t,result:r}of[...w,...S]){let i=r.splitStats;i&&(T.sah+=i.sahSplits??0,T.objMed+=i.objectMedianSplits??0,T.spatMed+=i.spatialMedianSplits??0,T.failed+=i.failedSplits??0,this.performanceMetrics.blasWorkerTime+=i.totalBuildTime??0),this.instanceTable.setEntry({meshIndex:e,blasNodeCount:r.nodeCount??$s(r.bvhData)/64,triOffset:t.start,triCount:t.count,originalToBvhMap:r.originalToBvh||null,bvhData:r.bvhData,matrixWorld:n?a:this.meshes?.[e]?.matrixWorld?.elements??null,matrixOffset:n?e*16:0,expandedStart:t.expandedStart,sourceMesh:o(e)})}for(let[e,r]of d)this.instanceTable.setAlias(e,r,n?a:this.meshes?.[e]?.matrixWorld?.elements??null,t[o(e)].expandedStart,o(e),n?e*16:0);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 E=performance.now(),D=this.instanceTable;this.instanceTable.computeAABBs(this.triangles,{owners:!y}),this.instanceTable.assignOffsets(Sa.nodeCountFor(D.count));let O=this.instanceTable.totalNodeCount,k=await this._buildTLAS(D);this.performanceMetrics.tlasBuildTime=performance.now()-E,this.memory.mark(`assemble`);let A=performance.now();y||this._checkAssemblyHeadroom(O),this._setBVHData(Qt.lazy(O,16,Float32Array,void 0,Xt));let j=y?await this._beginBVHSpill(y,D.tlasNodeCount):null;this.bvh.setRecords(0,k),k=null,this.tlasBuilder.releaseFlattenBuffer();let M=Math.max(1,Math.ceil(D.templateCount/32));if(v){try{let e=performance.now();await ys(v.nodes,this.bvh,D.tlasNodeCount,O-D.tlasNodeCount),this.performanceMetrics.blasRestore.readMs=performance.now()-e}finally{v.release()}D.blasData.clear()}else{for(let e=0;e<D.templateCount;e++){let t=y?await this._readSpilledBLAS(y,e):D.blasData.get(e);if(!t)continue;let n=D.tplBlasOffset[e],r=n;for(let e of Qs(t))this.bvh.setRecords(r,e),r+=e.length/16;this._offsetBLASInPlace(n,r-n,n,D.tplTriOffset[e]),D.blasData.delete(e),await j?.(r),e%M===0&&this._sampleMemory(`assembling ${e}/${D.templateCount}`)}await j?.(O,!0),y&&await y.blasStore.dispose()}if(this._setBVHData(this.bvh.materializeAll()),v)for(let[e,t]of v.orders)D.bvhToOriginal.set(e,t);else this._buildBvhToOriginalMaps();this.performanceMetrics.bvhAssembleTime=performance.now()-A,D.originalToBvhMap.clear(),D.blasData.clear(),this.bvhRoot=!0,this._disposeRefitWorker();let N=performance.now()-e;Zs.debug(H.list([`${H.n(D.setCount)} BLASes + TLAS`,`${H.n(this.bvh.recordCount)} nodes`,`SAH ${H.n(T.sah)} · objMed ${T.objMed} · spatMed ${T.spatMed} · failed ${T.failed}`,H.ms(N)])),z({status:`BVH construction complete`,progress:75})}catch(e){throw Zs.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:be()}}_isLargeMesh(e){return e.count>=Gs&&oa(e.count)}async _buildLargeBLAS(e,t){if(e.count>Ks)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 ra(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 Ts(n,e.start,e.count,qs,{pause:()=>new Promise(e=>setTimeout(e,0))}),o=this._blasPool(t,null,null,Math.min(ir(),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),ma.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{...ks(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:${Ms}:${JSON.stringify(t)}:${n}:${this._sceneKey}`}async _restoreBLASes(e,t,n){if(!this._sceneKey||this.config.sceneCache===!1)return null;let r=Mr(Lr().cacheNamespace);if(!r)return null;this._blasKey=this._blasCacheKey(n);let i=await _s(r,this._blasKey);if(!i)return null;let a=e=>(Zs.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 gs(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 bs(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},Zs.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=Mr(Lr().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 gs(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 vs(t,r,{index:{v:2,tlasNodeCount:n.tlasNodeCount,totalNodes:n.totalNodeCount,templates:d},bvh:this.bvh,orders:u,isStale:a,label:e});return f&&Zs.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 on.create(t,`${i}:tri`,a,{label:`Triangle records`,expectedBytes:r.byteLength}),s=o&&await on.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`),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(Qs(a)[0],t,this.triangles,i.tplObjectAABB,t*6);let o=e.blasBytes;e.blasBytes+=$s(a),e.blasAt.set(t,o),r.nodeCount=$s(a)/64,r.bvhData=null,this._queueSpill(e,()=>tc(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;e.uploadTriangles(t);let i=n.lanesPerRecord;for(let n=K.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+=ec)i.push(new Float32Array(await e.blasStore.readAt(n+t,Math.min(ec,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 on.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);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),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),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);yi(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=cr(Yi);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 Zs.error(`texture creation failed:`,e),e}}_bucketTextures(){let e=this.config.maxTextureSize,t=Nt.MATERIAL_BUCKET_COUNT,n=Nt.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=Vt(r(i),e,t),s=Vt(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=Ht(e.image.width,e.image.height,a),s=e.source?.uuid??e.uuid,c=r[o].get(s);if(c!==void 0)return Ut(o,c);if(t[o].length>=n)return Zs.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=Ut(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._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){Zs.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.maps=n.maps,this.normalMaps=n.normalMaps,this.bumpMaps=n.bumpMaps,this.roughnessMaps=n.roughnessMaps,this.metalnessMaps=n.metalnessMaps,this.emissiveMaps=n.emissiveMaps,this.displacementMaps=n.displacementMaps,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 Zs.error(`material rebuild failed:`,e),e}finally{this.isProcessing=!1}}_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=Qt.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._tlasLeafBoxesOf=null,!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||=cr(Bs),!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=K.FLOATS_PER_TRIANGLE,o=[],s=[],c=0;for(let e=0;e<i.count;e++){if(!i.isSet[e]||!i.isOwner(e))continue;c++;let t=n(e);if(!t)continue;if(this._updateMeshTrianglePositions(e,t),s.push(i.blasOffsetOf(e),i.blasNodeCountOf(e)),r){let t=r(e);t&&this._patchMeshSmoothNormals(e,t)}let l=i.triOffsetOf(e)*a,u=i.triCountOf(e)*a,d=o.at(-1);d&&d.offset+d.count===l?d.count+=u:o.push({offset:l,count:u})}let l=i.tlasNodeCount,u=l>0&&s.length/2<c,d=u?[this.computeTLASDirtyRange()]:null;for(let e=0;u&&e<s.length;e+=2)d.push({offset:s[e]*16,count:s[e+1]*16});return new Promise((e,t)=>{this._refitWorker.onmessage=n=>{let r=n.data;r.type===`refitComplete`?e({refitTimeMs:r.refitTimeMs,triRanges:o,bvhRanges:d}):r.type===`error`&&t(Error(r.error))},this._refitWorker.postMessage({type:`refit`,blasRanges:u?s:null,tlasNodeCount:l})})}_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 Ki;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._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);this._movedPlacements?.length!==n.count&&(this._movedPlacements=new Uint8Array(n.count));let i=this._movedPlacements,a=0;for(let t of e){let e=this.meshes?.[t],o=n.placementRunOf(t);if(!e||!o)continue;e.updateMatrixWorld(!0);let s=e.matrixWorld.elements,c=e.isInstancedMesh?this._ownInstanceMatrices(e):null,l=n.tplBakeInverse?.get(n.sourceMesh[o.start])??null;for(let e=0;e<o.count;e++){let t=o.start+e;n.isSet[t]&&(c?(ua(s,c,e*16,r),n.setPlacementMatrix(t,r)):l?(ua(s,l,0,r),n.setPlacementMatrix(t,r)):n.setPlacementMatrix(t,s),this._writeLeafMatrix(t),i[t]=1,a++)}}return this._refitTLAS(i),i.fill(0),{refitTimeMs:performance.now()-t,placements:a}}_ownInstanceMatrices(e){let t=e.instanceMatrix;return t?.array?(t.array.buffer===this.instanceTable.world.buffer&&(t.array=t.array.slice(),t.needsUpdate=!0),t.array):null}_writeLeafMatrix(e){let t=this.instanceTable.tlasLeafIndex[e];t<0||Sa.writeLeafMatrix(this.bvh.chunkFor(t),this.bvhIndexChunks.chunkFor(t),this.bvh.baseOf(t),this.instanceTable.world,e)}computeTLASDirtyRange(){return{offset:0,count:this.instanceTable.tlasNodeCount*16}}computeBLASDirtyRanges(e){let t=K.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.tlasNodeCount*16}),{triRanges:n,bvhRanges:r}}uploadToPathTracer(e,t,n,r,{keepUserLights:i=!1}={}){return this.triangles?(e.setTriangleData(this.triangles,this.triangleCount),this.bvh?(e.setBVHData(this.bvh),e.setInstanceTable(this.instanceTable),this.materialData?e.materialData.setMaterialData(this.materialData,this.materials.map(e=>e.sources)):Zs.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):(Zs.error(`failed to get BVH data`),!1)):(Zs.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)}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 on.create(e,`${a}:tri`,o(t),{label:`Triangle records`,expectedBytes:t.byteLength}),c=s&&await on.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?.tlasNodeCount??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 Zs.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?.(),this.spilled||this._disposeSpill()})().finally(()=>{this._paging=null}),this._paging}async _restoreGeometry(e){let t=this._geometrySpill;if(!t?.bytes)return;z({status:`Reading scene geometry back...`,progress:84});let n=performance.now(),r=t.bytes;await t.restore(),this._disposeGeometrySpill(),this._geometryBytes=xn(e),Zs.info(`read ${H.mb(r)} of scene geometry back from disk in ${H.ms(performance.now()-n)}`),t.error&&Zs.warn(`some scene geometry stayed in memory, its spill write failed:`,t.error)}_disposeGeometrySpill(){let e=this._geometrySpill;this._geometrySpill=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)}async _buildTLAS(e){let t=e.count;if(t>=Ws&&!this._tlasWorkerFailed)try{let n=new Float64Array(t*6);e.writeWorldAABBs(n);let{tlasData:r,nodeCount:i}=await this._runTLASWorker(n,t);return Sa.fillLeaves(r,i,e),r}catch(e){this._tlasWorkerFailed=!0,Zs.warn(`TLAS worker unavailable (${e.message}); building on the main thread`)}return this.tlasBuilder.build(e).data}_runTLASWorker(e,t){this._tlasWorker||=cr(Us);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:be()},[e.buffer])})}_setBVHData(e){this._tlasLeafBoxesOf=null;let t=e?e instanceof Qt?e:Qt.adopt([e],e.length/16,16,e.length/16):null;this.bvh=t,t&&this._foldLeaves&&(t.foldedLeaves=!0),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=K.FLOATS_PER_TRIANGLE,n=e?e instanceof Qt?e:Qt.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=K.POSITION_A_OFFSET,r=K.POSITION_B_OFFSET,i=K.POSITION_C_OFFSET,a=K.NORMAL_A_PACKED_OFFSET,o=K.NORMAL_B_PACKED_OFFSET,s=K.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=da(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=mt(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=K.NORMAL_A_PACKED_OFFSET,o=K.NORMAL_B_PACKED_OFFSET,s=K.NORMAL_C_PACKED_OFFSET,c=r,l=!c||da(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]]=mt(f,p,m)}}}_refitTLAS(e=null){let t=this.instanceTable.tlasNodeCount;(!this._tlasBounds||this._tlasBounds.length<t*6)&&(this._tlasBounds=new Float32Array(t*6),this._tlasLeafBoxesOf=null);let n=this.instanceTable,r=e&&this._tlasLeafBoxesOf===n;for(let i=t-1;i>=0;i--){let t=this.bvhIndexChunks.chunkFor(i),a=this.bvh.chunkFor(i),o=this.bvh.baseOf(i),s=t[o+3];if(s===St.BLAS_POINTER_LEAF){let a=t[o+1]&xt;a<n.count&&!(r&&!e[a])&&n.writeWorldAABB(a,this._tlasBounds,i*6)}else if(s<St.TRIANGLE_LEAF){let e=s,n=t[o+7],r=e*6,c=n*6,l=this._tlasBounds;a[o]=l[r],a[o+1]=l[r+1],a[o+2]=l[r+2],a[o+4]=l[r+3],a[o+5]=l[r+4],a[o+6]=l[r+5],a[o+8]=l[c],a[o+9]=l[c+1],a[o+10]=l[c+2],a[o+12]=l[c+3],a[o+13]=l[c+4],a[o+14]=l[c+5];let u=i*6;l[u]=Math.min(l[r],l[c]),l[u+1]=Math.min(l[r+1],l[c+1]),l[u+2]=Math.min(l[r+2],l[c+2]),l[u+3]=Math.max(l[r+3],l[c+3]),l[u+4]=Math.max(l[r+4],l[c+4]),l[u+5]=Math.max(l[r+5],l[c+5])}}this._tlasLeafBoxesOf=n}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){Zs.error(`background BLAS rebuild failed (mesh ${e}):`,o.error);return}n===this._rebuildGeneration&&this._swapBLAS(e,r,o,t)},i.onerror=t=>{Zs.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,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,cr(Yi))}}_swapBLAS(e,t,n,r){this._geometryVersion=(this._geometryVersion??0)+1;let i=n.bvhData,a=i.length/16;if(a>t.blasNodeCount){Zs.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}},ic=[[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]],ac=[[-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]],oc=[[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 sc(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=ic[i],o=ac[i],s=oc[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)]}Fn();var cc=1/(4*Math.PI);function lc(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]=sc(t.temperature??6500);i[0]*=e,i[1]*=n,i[2]*=r}return jn(i),{r:i[0],g:i[1],b:i[2],intensity:r}}var uc=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=lc(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=lc(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=lc(e);this.pointLightCache.push({data:[t.x,t.y,t.z,i.r,i.g,i.b,i.intensity*cc,e.distance||0,e.decay===void 0?2:e.decay],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=lc(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*cc,e.angle||Math.PI/4,e.penumbra||0,e.distance||0,e.decay===void 0?2:e.decay,o,c,u,d,0,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}))}}},dc,fc,pc,mc,hc,gc,_c,vc,yc,bc,xc,Sc,Cc,wc,Tc,Ec,Dc=g((()=>{dc=C({origin:`vec3`,direction:`vec3`}),fc=C({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`,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`}),pc=C({transmission:`float`,clearcoat:`float`,clearcoatRoughness:`float`,sheenColor:`vec3`,sheenRoughness:`float`,iridescence:`float`,iridescenceThickness:`float`,specularIntensity:`float`,specularColor:`vec3`,diffuseTransmission:`float`,diffuseTransmissionColor:`vec3`}),mc=C({color:`vec4`,ior:`float`,transmission:`float`,attenuationColor:`vec3`,attenuationDistance:`float`,albedoMapIndex:`int`,opacity:`float`,transparent:`bool`,alphaTest:`float`,alphaMode:`int`,albedoTransform:`mat3`}),hc=C({shadowed:`vec3`,unoccluded:`vec3`}),C({position:`vec3`,radius:`float`,material:fc}),gc=C({didHit:`bool`,dst:`float`,hitPoint:`vec3`,normal:`vec3`,uv:`vec2`,materialIndex:`int`,meshIndex:`int`,instanceLeaf:`int`,triangleIndex:`int`,boxTests:`int`,triTests:`int`}),C({posA:`vec3`,posB:`vec3`,posC:`vec3`,uvA:`vec2`,uvB:`vec2`,uvC:`vec2`,normalA:`vec3`,normalB:`vec3`,normalC:`vec3`,material:fc,materialIndex:`int`,meshIndex:`int`}),C({color:`vec4`,samples:`int`}),_c=C({direction:`vec3`,value:`vec3`,pdf:`float`,isTransmission:`bool`,colorWeight:`vec3`,isDiffuseTransmission:`bool`}),vc=C({specular:`float`,diffuse:`float`,sheen:`float`,clearcoat:`float`,transmission:`float`,iridescence:`float`,diffuseTransmission:`float`}),yc=C({Ta:`vec3`,Ba:`vec3`}),bc=C({NoL:`float`,NoV:`float`,NoH:`float`,VoH:`float`,LoH:`float`,ToH:`float`,BoH:`float`,ToV:`float`,BoV:`float`,ToL:`float`,BoL:`float`}),xc=C({compensation:`vec3`,E_total:`vec3`}),Sc=C({f0:`vec3`,f90:`float`,eta:`float`,F0m:`vec3`,F0:`vec3`}),Cc=C({albedo:`vec4`,emissive:`vec3`,metalness:`float`,roughness:`float`,normal:`vec3`,hasTextures:`bool`}),wc=C({isMetallic:`bool`,isRough:`bool`,isSmooth:`bool`,isTransmissive:`bool`,hasClearcoat:`bool`,isEmissive:`bool`,complexityScore:`float`}),Tc=C({albedoUV:`vec2`,normalUV:`vec2`,metalnessUV:`vec2`,emissiveUV:`vec2`,bumpUV:`vec2`,roughnessUV:`vec2`,normalBumpSameUV:`bool`,metalRoughSameUV:`bool`,albedoEmissiveSameUV:`bool`,allSameUV:`bool`}),Ec=C({invRoughness:`float`,metalFactor:`float`,iorFactor:`float`,maxSheenColor:`float`}),C({traversals:`int`,transmissiveTraversals:`int`,rayType:`int`,isPrimaryRay:`bool`,actualBounceDepth:`int`})})),Oc,kc,Ac,jc,Mc,Nc,Pc,Fc,Ic,Lc,Rc,zc,Bc,Vc,Hc,Uc,Wc,Gc,Kc,qc,Jc,Yc,Xc,Zc,Qc,$c,el,tl,Z,nl,rl,il,al,ol,sl,cl,ll,ul,dl,fl,pl,ml,hl=g((()=>{Dc(),wt(),Oc=(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 );
|
|
@@ -912,7 +912,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
|
|
|
912
912
|
let linear = rayzee_source( gid.x, srcY );
|
|
913
913
|
rayzee_store( gid.y * params.width + gid.x, linear, rayzee_tone_map( linear.rgb, params.mode, params.exposure, params.saturation ) );
|
|
914
914
|
}
|
|
915
|
-
`,p_=32,m_=class{constructor(e,t=`rayzee:tonemap`,{input:n=`packed`,output:r=`rgba8`}={}){this.device=e,this.label=t,this.input=n,this.output=r,this.width=0,this.height=0,this._pipeline=null,this._storage=null,this._map=null,this._params=null,this._paramData=new ArrayBuffer(p_),this._paramU32=new Uint32Array(this._paramData),this._paramF32=new Float32Array(this._paramData),this._shaderVersion=-1,this._bindings=[],this._tables=new Map,this.disposed=!1}_ensurePipeline(){let{wgsl:e,bindings:t,version:n}=o_();this._pipeline&&this._shaderVersion===n||(this._bindings=t,this._shaderVersion=n,this._pipeline=this.device.createComputePipeline({label:this.label,layout:`auto`,compute:{module:this.device.createShaderModule({label:this.label,code:f_(e,this.input,this.output)}),entryPoint:`main`}}))}_ensureTables(){let e=new Set;for(let{index:t,transform:n}of this._bindings){let{data:r,size:i}=n.table;e.add(t);let a=this._tables.get(t);if(a&&a.data===r)continue;a?.texture.destroy();let o=this.device.createTexture({label:`${this.label}-${n.wgslConst}`,size:[i,i,i],dimension:`3d`,format:`rgba16float`,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST});this.device.queue.writeTexture({texture:o},r,{bytesPerRow:i*8,rowsPerImage:i},[i,i,i]),this._tables.set(t,{texture:o,data:r,view:o.createView()})}for(let[t,n]of this._tables)e.has(t)||(n.texture.destroy(),this._tables.delete(t))}ensureSize(e,t){if(this._ensurePipeline(),this._ensureTables(),this.width===e&&this.height===t&&this._storage)return;this._releaseBuffers();let n=e*t*d_[this.output];this._storage=this.device.createBuffer({label:`${this.label}-out`,size:n,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this._map=this.device.createBuffer({label:`${this.label}-map`,size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this._params=this.device.createBuffer({label:`${this.label}-params`,size:p_,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.width=e,this.height=t}async toRGBA8(e,t){return new Uint8ClampedArray(await this._run(e,t))}async toPlanar(e,t){return new Float32Array(await this._run(e,t))}async _run(e,{exposure:t=1,toneMapping:n=0,saturation:r=1,flipY:i=!1,preserveAlpha:a=!1}={}){if(this.disposed)throw Error(`PackedToneMapper: disposed`);if(!this._storage)throw Error(`PackedToneMapper: call ensureSize() first`);this._ensurePipeline(),this._ensureTables();let{width:o,height:s}=this,c=o*s*d_[this.output];this._paramU32[0]=o,this._paramU32[1]=s,this._paramU32[2]=n>>>0,this._paramU32[3]=+!!i,this._paramF32[4]=t,this._paramF32[5]=r,this._paramU32[6]=+!!a,this.device.queue.writeBuffer(this._params,0,this._paramData);let l=[...this._tables.entries()].map(([e,t])=>({binding:e,resource:t.view})),u=this.device.createBindGroup({layout:this._pipeline.getBindGroupLayout(0),entries:[...l,{binding:0,resource:this.input===`texture`?e.createView():{buffer:e,size:o*s*8}},{binding:1,resource:{buffer:this._storage}},{binding:2,resource:{buffer:this._params}}]}),d=this.device.createCommandEncoder({label:this.label}),f=d.beginComputePass();f.setPipeline(this._pipeline),f.setBindGroup(0,u),f.dispatchWorkgroups(Math.ceil(o/8),Math.ceil(s/8)),f.end(),d.copyBufferToBuffer(this._storage,0,this._map,0,c),this.device.queue.submit([d.finish()]),await this._map.mapAsync(GPUMapMode.READ);let p=this._map.getMappedRange().slice(0);return this._map.unmap(),p}release(){this._releaseBuffers(),this.width=this.height=0}_releaseBuffers(){this._storage?.destroy(),this._map?.destroy(),this._params?.destroy(),this._storage=null,this._map=null,this._params=null}dispose(){if(!this.disposed){this.disposed=!0,this._releaseBuffers();for(let e of this._tables.values())e.texture.destroy();this._tables.clear(),this._pipeline=null}}}}));h_(),Ao(),Fn(),X();var g_=class{constructor({issues:e=null}={}){this._issues=e,this._renderer=null,this._offRegistry=lo(()=>{this._renderer&&vo(this._renderer)})}get hasConfig(){return!1}get workingSpace(){return Dr}get workingSpaceAdopted(){return!1}get inputKey(){return`-`}attachRenderer(e){this._renderer=e;let t=vo(e);return e.outputColorSpace=r.SRGBColorSpace,t}listViews(){return fo()}get activeView(){return null}setActiveView(e){let t=uo(e);if(!t)throw Error(`no view transform with id ${e}`);if(t.outputEncoded)throw Error(`"${t.name}" returns display-encoded colour: it needs rayzee/addons/color`);return this._renderer&&(this._renderer.toneMapping=e),t}_publishWorkingMatrix(){On(null,Dr)}loadConfig(){let e=`colour configs need the OCIO pipeline: renderer.setColorManagement( ColorManagement ), from rayzee/addons/color`;return this._issues?.record(Y.CAPABILITY_MISSING,e,{capability:`color`}),Promise.reject(Error(e))}unloadConfig(){}setWorkingSpace(){}exportPixels(e){return{rgba:e,colorSpace:Dr}}status(){let e=this._renderer?uo(this._renderer.toneMapping):null;return{config:null,workingSpace:Dr,workingSpaceAdopted:!1,activeTransform:e?{id:e.id,name:e.name,source:e.source}:null,activeView:null,context:null,exportSpace:null,views:fo(),registryVersion:co(),bakeError:e?.error??null}}dispose(){this._offRegistry?.(),this._renderer=null,this._issues=null,kr()===this&&(On(null),Ar(null))}};dr();var __=[[/\.jpe?g(\?|#|$)/i,`image/jpeg`],[/\.webp(\?|#|$)/i,`image/webp`],[/\.avif(\?|#|$)/i,`image/avif`]];function v_(e){return e.mimeType?e.mimeType:e.uri?.startsWith(`data:`)?e.uri.slice(5,e.uri.indexOf(`;`)):__.find(([t])=>t.test(e.uri??``))?.[1]??`image/png`}function y_(e){for(let t=8;t+12<=e.length;){let n=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0,r=t+12+n;if(e[t+4]===73&&e[t+5]===69&&e[t+6]===78&&e[t+7]===68)return e.subarray(0,r);t=r}return e}function b_({data:e,width:t,height:n},{shared:i=!1}={}){let a=new Uint8Array(e.buffer,e.byteOffset,t*n*4),o=a;i&&typeof SharedArrayBuffer<`u`&&!(a.buffer instanceof SharedArrayBuffer)&&(o=new Uint8Array(new SharedArrayBuffer(a.byteLength)),o.set(a));let s=new r.DataTexture(o,t,n,r.RGBAFormat,r.UnsignedByteType);return s.needsUpdate=!0,s}function x_(e,t){return rr().decodeImage(t===`image/png`?y_(e):e,t)}async function S_(e){let t=await fetch(e);if(!t.ok)throw Error(`HTTP ${t.status}`);return new Uint8Array(await t.arrayBuffer())}function C_(e,t){return t.bufferView===void 0?S_(e.options.manager.resolveURL(r.LoaderUtils.resolveURL(t.uri,e.options.path))):e.getDependency(`bufferView`,t.bufferView).then(e=>new Uint8Array(e))}var w_=(e,t)=>!!t&&t!==e.textureLoader&&typeof t.parse==`function`;function T_(e,t,n){if(e.sourceCache[t]!==void 0)return e.sourceCache[t].then(e=>e.clone());let r=C_(e,e.json.images[t]).then(e=>new Promise((t,r)=>{n.parse(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),t,r)}));return e.sourceCache[t]=r,r}async function E_(e,t=v_({uri:e})){let n=b_(await x_(await S_(e),t));return n.flipY=!0,n}function D_(e,t=null){return e.loadImageSource=function(e,n){if(w_(this,n))return T_(this,e,n);let r=this.json.images[e],i=Error(`no image decoder in this runtime: configurePlatform( nodePlatform( { decodeImage } ) ) — see "Running in Node"`);return t?.(r.uri??`bufferView ${r.bufferView}`,i),Promise.reject(i)},{name:`RAYZEE_missing_image_decoder`}}function O_(e,t=null){return e.loadImageSource=function(e,n){if(w_(this,n))return T_(this,e,n);if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(e=>e.clone());let r=this.json.images[e],i=v_(r),a=r.uri??`bufferView ${r.bufferView}`,o=C_(this,r).then(e=>x_(e,i)).then(e=>{let t=b_(e,{shared:!0});return r.extras&&typeof r.extras==`object`&&Object.assign(t.userData,r.extras),t.userData.mimeType=i,t}).catch(e=>{throw t?.(a,e),e});return this.sourceCache[e]=o,o},{name:`RAYZEE_platform_images`}}var k_=`KHR_materials_diffuse_transmission`;function A_(e){let t=(t,n,r,i)=>{let a={};return e.assignTexture(a,n,r,i).then(()=>{a[n]&&(t[n]=a[n])})};return{name:k_,afterRoot(n){let i=e.json.materials??[],a=new Set,o=[];for(let s of n.scenes??[])s.traverse(n=>{let s=Array.isArray(n.material)?n.material:n.material?[n.material]:[];for(let n of s){if(a.has(n))continue;a.add(n);let s=e.associations.get(n)?.materials,c=s===void 0?null:i[s]?.extensions?.[k_];if(!c)continue;n.diffuseTransmission=c.diffuseTransmissionFactor??0;let[l,u,d]=c.diffuseTransmissionColorFactor??[1,1,1];n.diffuseTransmissionColor=new r.Color().setRGB(l,u,d,r.LinearSRGBColorSpace),c.diffuseTransmissionTexture&&o.push(t(n,`diffuseTransmissionMap`,c.diffuseTransmissionTexture)),c.diffuseTransmissionColorTexture&&o.push(t(n,`diffuseTransmissionColorMap`,c.diffuseTransmissionColorTexture,r.SRGBColorSpace))}});return Promise.all(o)}}}Br();var j_=`KHR_draco_mesh_compression`,M_=`KHR_texture_basisu`,N_=[`EXT_meshopt_compression`,`KHR_meshopt_compression`],P_=new TextDecoder;function F_(e){if(typeof e==`string`)return e;if(!(e instanceof ArrayBuffer))return JSON.stringify(e?.extensionsUsed??[]);let t=new DataView(e);if(!(e.byteLength>=20&&t.getUint32(0,!0)===1179937895))return P_.decode(e);let n=Math.min(t.getUint32(12,!0),e.byteLength-20);return P_.decode(new Uint8Array(e,20,n))}async function I_(e,t,n){let{dracoDecoderPath:r,ktx2TranscoderPath:i}=Lr(),[a,o,s]=await Promise.all([t.includes(j_)&&!e.dracoLoader?import(`three/addons/loaders/DRACOLoader.js`):null,t.includes(M_)&&!e.ktx2Loader?import(`three/addons/loaders/KTX2Loader.js`):null,N_.some(e=>t.includes(e))&&!e.meshoptDecoder?import(`three/addons/libs/meshopt_decoder.module.js`):null]);if(a){let t=new a.DRACOLoader;t.setDecoderConfig({type:`js`}),t.setDecoderPath(r),e.setDRACOLoader(t)}if(o){let t=new o.KTX2Loader;t.setTranscoderPath(i),n&&(t.detectSupport(n),t.workerConfig={astcSupported:!1,etc1Supported:!1,etc2Supported:!1,dxtSupported:!1,bptcSupported:!1,pvrtcSupported:!1}),e.setKTX2Loader(t)}s&&e.setMeshoptDecoder(s.MeshoptDecoder)}function L_(e,t){let n=e.parse.bind(e);return e.parse=(r,i,a,o)=>{I_(e,F_(r),t).then(()=>n(r,i,a,o),e=>o?.(e))},e}function R_(e){if(typeof e==`string`)try{let t=JSON.parse(e);return t&&typeof t==`object`?t:null}catch{return null}return e&&typeof e==`object`?e:null}function z_(e){let t=typeof e==`string`?parseFloat(e):e;return Number.isFinite(t)?t:void 0}function B_(e){let t=R_(e);if(!t)return null;let n=e=>e&&(e.environment!==void 0||e.render!==void 0),r=R_(t.rayzee);return n(r)?r:n(t)?t:null}function V_(e){let t=R_(e);if(!t)return null;let n=G_.map(e=>t[e]).find(e=>typeof e==`string`&&e.trim());if(!n)return null;let r=z_(t.rotation),i=z_(t.intensity),a={sourceFile:n.trim()};return r!==void 0&&(a.rotation=r),i!==void 0&&(a.intensity=Math.max(0,i)),a}function H_(e){let t=R_(e);if(!t)return null;let n={};for(let e of K_){let r=z_(t[e]);r!==void 0&&r>0&&(n[e]=Math.round(r))}return Object.keys(n).length?n:null}function U_(e){let t=B_(e);if(!t)return null;let n=V_(t.environment),r=H_(t.render);return!n&&!r?null:{...n?{environment:n}:{},...r?{render:r}:{}}}function W_(e){if(!e)return null;let t=[e.userData,e.asset?.extras,e.scene?.userData];Array.isArray(e.scenes)&&t.push(...e.scenes.map(e=>e?.userData));for(let e of t){let t=U_(e);if(t)return t}return null}var G_,K_,q_=g((()=>{G_=[`sourceFile`,`url`,`file`],K_=[`maxBounces`,`samples`,`width`,`height`]}));Yr(),fe(),dr(),q_(),X();var J_={glb:{type:`model`,name:`GLB (GLTF Binary)`},gltf:{type:`model`,name:`GLTF`},hdr:{type:`environment`,name:`HDR (High Dynamic Range)`},png:{type:`image`,name:`PNG`},jpg:{type:`image`,name:`JPEG`},jpeg:{type:`image`,name:`JPEG`},webp:{type:`image`,name:`WebP`}},Y_={addOn:`rayzee/addons/archives`,install:`assetLoader.setArchiveImporter()`},X_={addOn:`rayzee/addons/formats`,install:`assetLoader.registerFormat()`},Z_={zip:Y_,gz:Y_,tgz:Y_,tar:Y_,fbx:X_,obj:X_,stl:X_,ply:X_,dae:X_,"3mf":X_,usd:X_,usda:X_,usdc:X_,usdz:X_,exr:X_};function Q_(e){let t=new r.BufferGeometry;for(let n in e.attributes)t.setAttribute(n,e.attributes[n]);e.index&&t.setIndex(e.index);for(let n of e.groups)t.addGroup(n.start,n.count,n.materialIndex);return t}var $_=683;function ev(e,t,n,i){if(!(i.normalize??!0))return Math.PI;let a=i.shape===`ellipse`||i.shape===`disk`?Math.PI/4:1,o=e.getWorldScale(new r.Vector3),s=Math.PI*a*Math.abs(t*o.x*n*o.y);return Number.isFinite(s)?s:Math.PI}var tv=class e extends r.EventDispatcher{constructor(e,t,n,{issues:i=null,areaLightIntensityScale:a=null}={}){super(),this.scene=e,this.camera=t,this.controls=n,this.targetModel=null,this.floorPlane=null,this.sceneScale=1,this.sceneSize=new r.Vector3(1,1,1),this.loaderCache={},this.uploadedFileInfo=null,this.animations=[],this.renderer=null,this.sceneMetadata=null,this._loadingManager=new r.LoadingManager,this._loadCancelled=!1,this._urlAbort=null,this.storage=null,this._downloads=null,this._sourceKey=null,this._appended=!1,this.archives=null,this._archiveLoader=null,this._formats=new Map,this._issues=i,this._areaLightIntensityScale=a??(()=>G.areaLightIntensityScale),this._loadingManager.onError=e=>{this._loadCancelled||this._issues?.record(Y.ASSET_UNREACHABLE,`asset "${e}" could not be fetched — anything depending on it renders without it`,{url:e})}}cancelActiveLoad(){this._loadCancelled=!0,this._loadingManager.abort(),this._urlAbort?.abort()}async _viaCache(t,n,r,{cacheKey:i=t,cachePolicy:a}={}){if(!this.storage||!e._isNetworkUrl(t)||/\.gltf$/i.test(t.split(/[?#]/)[0]))return{url:t,release:()=>{},cached:!1};let o=new AbortController;this._urlAbort=o;try{return await Ig(t,{downloads:this.downloads,key:i,policy:a,name:kg(t),signal:o.signal,onProgress:this._downloadProgress(n,r)})}catch(e){throw this._isCancellation(e)?this._cancellationError():e}finally{this._urlAbort=null}}get sceneSourceKey(){return this._appended?null:this._sourceKey}_keyed(e,t){return t?`${e}::${t}`:null}get downloads(){return this._downloads?._storage!==this.storage&&(this._downloads=new Ng(this.storage)),this._downloads}_isCancellation(e){return this._loadCancelled||e?.name===`AbortError`||e?.code===`LOAD_CANCELLED`}_cancellationError(){let e=Error(`Load cancelled`);return e.code=`LOAD_CANCELLED`,e}_downloadProgress(e,t){return n=>{let r=n?.loaded||0,i=n?.lengthComputable&&n.total||0;z({isLoading:!0,status:e,loadedBytes:r,totalBytes:i,canCancel:!!t,progress:i?Math.min(60,2+Math.round(r/i*58)):2})}}_downloadComplete(e=`Processing Data...`,t=62){z({status:e,progress:t,canCancel:!1,loadedBytes:null,totalBytes:null})}static _isNetworkUrl(e){return typeof e==`string`&&/^https?:/i.test(e)}_adoptExternalObject(e){let t;try{t=(0,l.clone)(e)}catch(t){throw Error(`Cannot render "${e.name||e.type}": its userData must be JSON-serializable.`,{cause:t})}return t.userData.__rayzeeExternal=!0,this.scene?.children.some(t=>t.uuid===e.uuid)||(t.uuid=e.uuid),e.parent&&(e.parent.updateWorldMatrix(!0,!1),t.applyMatrix4(e.parent.matrixWorld)),t}releaseTargetModel(){this.sceneMetadata=null,this._sourceKey=null,this._appended=!1,this.archives?.release(),this.targetModel&&(this.removeModelRoot(this.targetModel),this.targetModel=null,this.animations=[])}setRenderer(e){this.renderer=e}setArchiveImporter(e){this.archives=e}setArchiveImporterLoader(e,t){this._archiveLoader={load:e,formats:t,pending:null}}async _archiveImporter(){return!this.archives&&this._archiveLoader&&(this.archives=await(this._archiveLoader.pending??=this._archiveLoader.load())),this.archives}get _archiveFormats(){return this.archives?.constructor.FORMATS??this._archiveLoader?.formats??null}registerFormat(...e){for(let t of e)for(let e of t.extensions)this._formats.set(e,t);return this}getFileFormat(e){let t=e.split(`.`).pop().toLowerCase();return J_[t]||this._formats.get(t)||this._archiveFormats?.[t]||null}formatError(e){let t=Z_[e.split(`.`).pop().toLowerCase()];return Error(t?`${e}: this format is read by ${t.addOn} — install it with ${t.install}`:`Unsupported file format: ${e}`)}async inspectArchive(e){let t=await this._archiveImporter();if(!t)throw this.formatError(e.name??`archive.zip`);return await t.inspectArchive(e)}flushPendingGraph(e){this.archives?.flushPendingGraph(e)}readFileAsArrayBuffer(e){return e.arrayBuffer()}readFileAsText(e){return e.text()}async loadAssetFromFile(e,t={}){let n=e.name,r=this.getFileFormat(n);if(!r)throw this.formatError(n);z({isLoading:!0,status:`Loading ${r.name}...`,progress:2});try{let i;switch(r.type){case`model`:i=await this.loadModelFromFile(e,n);break;case`environment`:case`image`:i=await this.loadEnvironmentFromFile(e,n);break;case`archive`:i=await(await this._archiveImporter()).loadArchiveFromFile(e,n,t);break;default:throw Error(`Unknown asset type: ${r.type}`)}return i}catch(e){throw e?.code!==`ARCHIVE_NEEDS_ELEMENT`&&this.dispatchEvent({type:`error`,message:e.message,filename:n}),e}}async loadFolder(e,t={}){let n=await this._archiveImporter();if(!n)throw Error(`${e.name}: folders are read by ${Y_.addOn} — install it with ${Y_.install}`);z({isLoading:!0,status:`Loading ${e.name}...`,progress:2});try{return await n.loadFolder(e,t)}catch(t){throw t?.code===`ARCHIVE_NEEDS_ELEMENT`?t.file=e:this.dispatchEvent({type:`error`,message:t.message,filename:e.name}),t}}async loadAssetFromUrl(t,n={}){let{filename:r=kg(t),cacheKey:i=t,cachePolicy:a,...o}=n;if(!this.getFileFormat(r))throw this.formatError(r);this._loadCancelled=!1;let s=e._isNetworkUrl(t),c=`Downloading ${r}...`,l=new AbortController;this._urlAbort=l,z({isLoading:!0,status:c,progress:2,canCancel:s,loadedBytes:0,totalBytes:0});let u;try{u=await this.downloads.fetch(t,{key:i,name:r,policy:a,signal:l.signal,onProgress:this._downloadProgress(c,s)})}catch(e){throw this._isCancellation(e)?this._cancellationError():e}finally{this._urlAbort=null}this._downloadComplete();try{return await this.loadAssetFromFile(u.file,o)}catch(e){throw e?.code===`ARCHIVE_NEEDS_ELEMENT`&&(e.file=u.file),e}finally{u.release()}}async loadModelFromFile(e,t){let n=this.storage?this._keyed(`file`,Ug(await Vg(e))):null,r=await this._loadModelFileByExtension(e,t);return this._sourceKey=n,r}async _loadModelFileByExtension(e,t){let n=t.split(`.`).pop().toLowerCase();if(n===`glb`||n===`gltf`)return await this.loadGLBFromArrayBuffer(await this.readFileAsArrayBuffer(e),t);let r=this._formats.get(n);if(r?.type!==`model`)throw this.formatError(t);return await this._loadModelWithFormat(r,e,t)}async _loadModelWithFormat(e,t,n){try{z({isLoading:!0,status:`Processing ${e.label} Data...`,progress:5}),await new Promise(e=>setTimeout(e,0));let{model:r,result:i=r}=await e.parse(t,{filename:n,cache:this.loaderCache});return this.releaseTargetModel(),this.targetModel=r,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r,filename:n}),i}catch(t){throw console.error(`Error loading ${e.label}:`,t),this.dispatchEvent({type:`error`,message:t.message,filename:n}),t}}async loadEnvironmentFromFile(e,t){let n=URL.createObjectURL(e);this.uploadedFileInfo={name:t,type:e.type,size:e.size};try{let r=await this.loadEnvironment(n);return Vr(r,Ug(await Vg(e))),this.dispatchEvent({type:`load`,texture:r,filename:t}),r}finally{URL.revokeObjectURL(n)}}async loadEnvironment(t){this._loadCancelled=!1;try{this.dispatchEvent({type:`beforeEnvironmentLoad`,url:t});let n;if(t.startsWith(`blob:`))n=await this.loadEnvironmentFromBlob(t);else{let e=t.split(/[?#]/)[0].split(`.`).pop().toLowerCase();n=await this.loadEnvironmentByExtension(t,e)}return n.generateMipmaps=!0,e._isNetworkUrl(t)&&Vr(n,t),this.applyEnvironmentToScene(n),this.dispatchEvent({type:`load`,texture:n,url:t,filename:t.split(/[?#]/)[0].split(`/`).pop()}),n}catch(e){throw this._isCancellation(e)?this._cancellationError():(console.error(`Error loading environment:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e)}}async loadEnvironmentFromBlob(e){let t=await(await fetch(e)).blob(),n=this.determineEnvironmentExtension(t,e),r=URL.createObjectURL(t);try{return await this.loadEnvironmentByExtension(r,n)}finally{URL.revokeObjectURL(r)}}determineEnvironmentExtension(e,t){let n;if(e.type===`image/x-exr`||e.type.includes(`exr`))n=`exr`;else if(e.type===`image/vnd.radiance`||e.type.includes(`hdr`))n=`hdr`;else{let e=t.split(`/`).pop();if(e){let t=e.match(/\.([^.]+)$/);t&&(n=t[1].toLowerCase())}}return!n&&this.uploadedFileInfo&&(n=this.uploadedFileInfo.name.split(`.`).pop().toLowerCase()),n}async loadEnvironmentByExtension(t,n,{loader:i=null}={}){let a=this._formats.get(n);if(!i&&a?.type===`environment`&&(i=this.loaderCache[n]??=await a.createLoader(this._loadingManager)),!i&&n===`hdr`&&(i=this.loaderCache.hdr??=new s.HDRLoader(this._loadingManager).setDataType(r.FloatType)),!i&&Z_[n])throw this.formatError(`environment.${n}`);let o=e._isNetworkUrl(t),c=`Downloading Environment...`,l=await this._viaCache(t,c,o),u=l.cached?void 0:this._downloadProgress(c,o),d;try{i?d=await i.loadAsync(l.url,u):rr().decodeImage?(d=await E_(l.url,`image/${n===`jpg`?`jpeg`:n}`),d.colorSpace=r.SRGBColorSpace):(this.loaderCache.texture||(this.loaderCache.texture=new r.TextureLoader(this._loadingManager)),d=await this.loaderCache.texture.loadAsync(l.url,u),d.colorSpace=r.SRGBColorSpace)}finally{l.release()}return this._downloadComplete(`Processing Environment...`,62),d.mapping=r.EquirectangularReflectionMapping,d.minFilter=r.LinearFilter,d.magFilter=r.LinearFilter,d}applyEnvironmentToScene(e){this.scene.background=e,this.scene.environment=e}async createGLTFLoader(){let e=L_(new o.GLTFLoader(this._loadingManager),this.renderer),t=(e,t)=>this._reportImageFailure(e,t);return rr().decodeImage?e.register(e=>O_(e,t)):ar()||e.register(e=>D_(e,t)),e.register(e=>A_(e)),e}_reportImageFailure(e,t){try{this._issues?.record(Y.TEXTURE_BUILD_FAILED,`image ${e} could not be decoded (${t?.message??t}) — the surfaces using it render untextured`,{image:e,cause:String(t?.message??t)})}catch(e){this._deferredError??=e}}_throwDeferred(){let e=this._deferredError;if(this._deferredError=null,e)throw e}_disposeGLTFLoader(e){e&&(e.dracoLoader?.dispose(),e.ktx2Loader?.dispose())}async loadExampleModels(e,t){if(!t||!t[e])throw Error(`No model file at index ${e}`);let n=`${t[e].url}`;return await this.loadModel(n)}async loadModel(t,n={}){this._loadCancelled=!1;let i=await this.createGLTFLoader(),a=e._isNetworkUrl(t),o=null;try{z({isLoading:!0,status:`Downloading Model...`,progress:2,canCancel:a,loadedBytes:0,totalBytes:0}),o=await this._viaCache(t,`Downloading Model...`,a,n),o.cached&&i.setResourcePath(r.LoaderUtils.extractUrlBase(t));let e=await sr(()=>i.loadAsync(o.url,o.cached?void 0:this._downloadProgress(`Downloading Model...`,a)));return this._downloadComplete(),this._throwDeferred(),this.releaseTargetModel(),this._sourceKey=a?this._keyed(`url`,n.cacheKey??t):null,this.targetModel=e.scene,this.animations=e.animations||[],this.sceneMetadata=W_(e),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:e.scene,filename:t.split(`/`).pop()}),e}catch(e){throw this._isCancellation(e)?this._cancellationError():(console.error(`Error loading model:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e)}finally{o?.release(),this._disposeGLTFLoader(i)}}_processAndParent(e){this.processModelObjects(e),this.scene.add(e),e.updateMatrixWorld(!0)}async appendModel(t,n={}){this._loadCancelled=!1;let i=await this.createGLTFLoader(),a=e._isNetworkUrl(t),o=null;try{z({isLoading:!0,status:`Downloading Model...`,progress:2,canCancel:a,loadedBytes:0,totalBytes:0}),o=await this._viaCache(t,`Downloading Model...`,a,n),o.cached&&i.setResourcePath(r.LoaderUtils.extractUrlBase(t));let e=await sr(()=>i.loadAsync(o.url,o.cached?void 0:this._downloadProgress(`Downloading Model...`,a)));return this._downloadComplete(),this._throwDeferred(),this._appended=!0,this._processAndParent(e.scene),{root:e.scene,animations:e.animations||[]}}catch(e){throw this._isCancellation(e)?this._cancellationError():e}finally{o?.release(),this._disposeGLTFLoader(i)}}appendObject3D(e,t=`object3d`){this._appended=!0;let n=this._adoptExternalObject(e);return n.name=e.name||t,this._processAndParent(n),{root:n}}removeModelRoot(e){e&&(e.userData.__rayzeeExternal?(ae(e),e.parent?.remove(e)):ie(e))}async loadGLBFromArrayBuffer(e,t=`model.glb`){let n=await this.createGLTFLoader();try{z({isLoading:!0,status:`Processing GLB Data...`,progress:5}),await new Promise(e=>setTimeout(e,0));let r=await sr(()=>n.parseAsync(e,``));return this._throwDeferred(),this.releaseTargetModel(),this.targetModel=r.scene,this.animations=r.animations||[],this.sceneMetadata=W_(r),z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r.scene,filename:t}),r}catch(e){throw console.error(`Error loading GLB:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}finally{this._disposeGLTFLoader(n)}}async loadObject3D(e,t=`object3d`){this.releaseTargetModel();let n=this._adoptExternalObject(e);return n.name=e.name||t,this.targetModel=n,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}async onModelLoad(e){let t=new us(`onModelLoad`);t.start(`Camera extraction`);let n=this.extractCamerasFromModel(e);t.end(`Camera extraction`),t.start(`Camera setup`);let i=new r.Box3().setFromObject(e),a=i.getCenter(new r.Vector3),o=i.getSize(new r.Vector3);this.controls?.target.copy(a);let s=Math.max(o.x,o.y,o.z),c=this.camera.fov*(Math.PI/180),l=Math.abs(s/Math.sin(c/2)/2),u=Math.PI/6,d=new r.Vector3(Math.cos(u)*l,l/Math.sqrt(2),Math.sin(u)*l);if(this.camera.position.copy(d.add(a)),this.camera.lookAt(a),this.camera.near=s/100,this.camera.far=s*100,this.camera.updateProjectionMatrix(),this.controls&&(this.controls.maxDistance=l*10,this.controls.saveState(),this.controls.update()),t.end(`Camera setup`),this.floorPlane){let e=i.min.y;this.floorPlane.position.y=e,this.floorPlane.rotation.x=-Math.PI/2,this.floorPlane.scale.setScalar(s*5)}t.start(`Process model objects`),this.processModelObjects(e),t.end(`Process model objects`),t.start(`Scene add`),this.scene.add(e),t.end(`Scene add`);let f=s;return this.sceneSize.copy(o),t.start(`setupPathTracing`),await this.setupPathTracing(e,f),t.end(`setupPathTracing`),t.print(),this.dispatchEvent({type:`modelProcessed`,model:e,cameras:n,sceneData:{center:a,size:o,maxDim:s,sceneScale:f}}),this.dispatchEvent({type:`SceneRebuild`}),{center:a,size:o,maxDim:s,sceneScale:f}}extractCamerasFromModel(e){let t=[];return e.updateWorldMatrix(!0,!0),e.traverse(e=>{if(e.isCamera){let n=e.clone();n.userData.__rayzeeSourceUuid=e.uuid,e.getWorldPosition(n.position),e.getWorldQuaternion(n.quaternion),e.getWorldScale(n.scale),n.scale.set(Math.sign(n.scale.x)||1,Math.sign(n.scale.y)||1,Math.sign(n.scale.z)||1),(!n.name||n.name===``)&&(n.name=`Model Camera ${t.length+1}`),n.isPerspectiveCamera&&(n.aspect=this.camera.aspect,n.updateProjectionMatrix()),t.push(n)}}),t}processModelObjects(e){let t=[],n=[];e.traverse(e=>{let i=e.userData;e.isRectAreaLight&&!i.__radianceConverted&&(e.intensity*=ev(e,e.width,e.height,i),i.__radianceConverted=!0),(e.isPointLight||e.isSpotLight)&&!i.__candelaConverted&&(e.intensity*=4*Math.PI/$_,i.__candelaConverted=!0),e.isDirectionalLight&&!i.__luxConverted&&(e.intensity/=$_,i.__luxConverted=!0);let a=e.name.startsWith(`RectAreaLightPlaceholder`);if(a&&!(i.name&&i.type===`RectAreaLight`)&&!e.parent?.name?.startsWith(`RectAreaLightPlaceholder`)&&n.push(e.name),a&&i.name&&i.type===`RectAreaLight`){let t=i.normalize??!0,n=i.shape??`rectangle`,a=i.intensity*ev(e,i.width,i.height,i),o=new r.RectAreaLight(new r.Color(...i.color),a*this._areaLightIntensityScale(),i.width,i.height);o.userData.normalize=t,o.userData.spread=Number.isFinite(i.spread)?i.spread:Math.PI,o.userData.shape=n,o.userData.__radianceConverted=!0,o.name=i.name,e.add(o)}e.isMesh&&Array.isArray(e.material)&&t.push(e)}),n.length&&this._issues?.record(Y.LIGHT_PLACEHOLDER_SKIPPED,`${n.length} area-light placeholder(s) lack userData.name or userData.type 'RectAreaLight' — no light was made for them`,{count:n.length,names:n.slice(0,10)});let i=e.userData.__rayzeeExternal===!0;for(let e of t){if(!e.parent)continue;console.log(`Found multi-material mesh:`,e.name),i&&(e.geometry=Q_(e.geometry));let t=(0,c.createMeshesFromMultiMaterialMesh)(e);for(let e of t.children)e.geometry.userData.__rayzeeOwned=!0;e.parent.add(t),e.parent.remove(e)}}async setupPathTracing(e,t){this.sceneScale=t}createFloorPlane(){this.floorPlane=new r.Mesh(new r.CircleGeometry,new r.MeshPhysicalMaterial({transparent:!1,color:3158064,roughness:1,metalness:0,opacity:0,transmission:0})),this.floorPlane.name=`Ground`,this.floorPlane.visible=!1,this.scene.add(this.floorPlane)}setFloorPlane(e){this.floorPlane=e}getSceneScale(){return this.sceneScale}getSceneSize(){return this.sceneSize.clone()}getTargetModel(){return this.targetModel}getSupportedFormats(e=null){let t={...J_,...this._archiveFormats};for(let[e,{type:n,name:r}]of this._formats)t[e]={type:n,name:r};if(e){let n={};for(let[r,i]of Object.entries(t))i.type===e&&(n[r]=i);return n}return t}dispose(){for(let e in this.loaderCache){let t=this.loaderCache[e];t&&typeof t.dispose==`function`&&t.dispose()}this.loaderCache={},this._listeners=void 0,this._loadingManager.onError=void 0,this._issues=null,this._urlAbort?.abort(),this._urlAbort=null,this.storage=null,this._downloads=null,this.archives?.release(),this.archives=null,this._archiveLoader=null,this.releaseTargetModel()}removeAllEventListeners(){this._listeners=void 0}},nv={addEventListener(){},removeEventListener(){},dispatchEvent(){return!0}},rv=class{constructor(e){this.canvas=e,this._configuration=null,this._texture=null}configure(e){this.unconfigure(),this._configuration=e}unconfigure(){this._texture?.destroy(),this._texture=null,this._configuration=null}getConfiguration(){return this._configuration}getCurrentTexture(){if(!this._configuration)throw Error(`HeadlessGPUContext: getCurrentTexture() before configure()`);let e=Math.max(1,this.canvas.width),t=Math.max(1,this.canvas.height);if(this._texture?.width!==e||this._texture?.height!==t){let{device:n,format:r,usage:i}=this._configuration;this._texture?.destroy(),this._texture=n.createTexture({label:`headless-canvas`,size:[e,t],format:r,usage:i})}return this._texture}};function iv(e=1,t=1){let n={...nv,defaultView:null},r={...nv,isHeadlessCanvas:!0,width:e,height:t,clientWidth:0,clientHeight:0,style:{},parentNode:null,ownerDocument:n,getRootNode:()=>n,getBoundingClientRect(){return{x:0,y:0,left:0,top:0,right:this.width,bottom:this.height,width:this.width,height:this.height}},setPointerCapture(){},releasePointerCapture(){},hasPointerCapture:()=>!1,focus(){},getContext:e=>e===`webgpu`?i:null},i=new rv(r);return r}var av=class extends r.PerspectiveCamera{constructor(e,t,n,r){super(e,t,n,r),this.orthographic=!1,this.orthoHalfHeight=1}get isPerspectiveCamera(){return!this.orthographic}set isPerspectiveCamera(e){}get isOrthographicCamera(){return this.orthographic}get top(){return this.orthoHalfHeight}get bottom(){return-this.orthoHalfHeight}get right(){return this.orthoHalfHeight*this.aspect}get left(){return-this.orthoHalfHeight*this.aspect}updateProjectionMatrix(){this.orthographic?r.OrthographicCamera.prototype.updateProjectionMatrix.call(this):super.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.orthographic=e.orthographic===!0,this.orthoHalfHeight=e.orthoHalfHeight??this.orthoHalfHeight,this}},ov=`__rayzeeUserLight`,sv={DirectionalLight:r.DirectionalLight,PointLight:r.PointLight,SpotLight:r.SpotLight,RectAreaLight:r.RectAreaLight},cv=class extends r.EventDispatcher{constructor(e,t,n,r={}){super(),this.scene=e,this.sceneHelpers=t,this.pathTracer=n,this._onReset=r.onReset||null,this._onLightRemoved=r.onLightRemoved||null}addLight(e){let t={DirectionalLight:{position:[1,1,1],intensity:1,color:`#ffffff`},PointLight:{position:[0,2,0],intensity:1e3,color:`#ffffff`},SpotLight:{position:[0,1,0],intensity:1e3,color:`#ffffff`,angle:15},RectAreaLight:{position:[0,2,0],intensity:100,color:`#ffffff`,width:2,height:2}}[e];if(!t)return null;let n;if(e===`DirectionalLight`)n=new r.DirectionalLight(t.color,t.intensity),n.position.fromArray(t.position);else if(e===`PointLight`)n=new r.PointLight(t.color,t.intensity),n.position.fromArray(t.position);else if(e===`SpotLight`){n=new r.SpotLight(t.color,t.intensity),n.position.fromArray(t.position),n.angle=r.MathUtils.degToRad(t.angle);let e=new r.Object3D;this.scene.add(e),n.target=e}else e===`RectAreaLight`&&(n=new r.RectAreaLight(t.color,t.intensity,t.width,t.height),n.position.fromArray(t.position),n.lookAt(0,0,0),n.userData.normalize=!0,n.userData.spread=Math.PI,n.userData.shape=`rectangle`);n.userData[ov]=!0,n.userData.temperature=6500,n.userData.useTemperature=!1,n.userData.exposure=0;let i=this.scene.getObjectsByProperty(`isLight`,!0).length;return n.name=`${e.replace(`Light`,``)} ${i+1}`,this.scene.add(n),this.updateLights(),this._syncHelpers(),this._onReset?.(),this._buildDescriptor(n)}getLight(e){let t=this.scene.getObjectByProperty(`uuid`,e);return t?.isLight?t:null}setIntensity(e,t){let n=this.getLight(e);return n?(n.intensity=t,this.updateLights(),this._onReset?.(),!0):!1}removeLight(e){let t=this.scene.getObjectByProperty(`uuid`,e);return!t||!t.isLight?!1:(this._onLightRemoved?.(t),this.sceneHelpers.remove(t),t.target&&t.target.removeFromParent(),t.removeFromParent(),this.updateLights(),this._onReset?.(),!0)}clearLights(){this.sceneHelpers.clear(),this._removeAllLights(),this.updateLights(),this._onReset?.()}getLights(){return this.scene.getObjectsByProperty(`isLight`,!0).map(e=>this._buildDescriptor(e))}updateLights(){this.pathTracer?.updateLights(),this.sceneHelpers?.visible&&this.sceneHelpers.update()}transferSceneLights(e,{keepUserLights:t=!1}={}){this._removeAllLights(t?e=>!e.userData?.[ov]:void 0);let n=e.getObjectsByProperty(`isLight`,!0);if(!n||n.length===0){this.updateLights();return}for(let e of n){let t=e.clone();if(e.updateWorldMatrix(!0,!1),e.getWorldPosition(t.position),e.getWorldQuaternion(t.quaternion),e.getWorldScale(t.scale),t.isRectAreaLight&&(t.width*=t.scale.x,t.height*=t.scale.y,t.scale.set(1,1,1)),(e.isSpotLight||e.isDirectionalLight)&&e.target){let n=new r.Object3D;e.target.updateWorldMatrix(!0,!1),e.target.getWorldPosition(n.position),this.scene.add(n),t.target=n}this.scene.add(t)}this.updateLights(),this._syncHelpers()}setShowLightHelper(e){this.sceneHelpers.visible=e,e?this._syncHelpers():this.sceneHelpers.clear()}serialize(){return this.scene.getObjectsByProperty(`isLight`,!0).map(e=>{let t={type:e.type,name:e.name,visible:e.visible,color:[e.color.r,e.color.g,e.color.b],intensity:e.intensity,position:e.position.toArray(),quaternion:e.quaternion.toArray(),scale:e.scale.toArray(),userData:In(e.userData)??{}};return e.isSpotLight&&Object.assign(t,{angle:e.angle,penumbra:e.penumbra,distance:e.distance,decay:e.decay}),e.isPointLight&&Object.assign(t,{distance:e.distance,decay:e.decay}),e.isRectAreaLight&&Object.assign(t,{width:e.width,height:e.height}),e.target&&(e.isSpotLight||e.isDirectionalLight)&&(t.target=e.target.position.toArray()),t})}restore(e){this.sceneHelpers?.clear(),this._removeAllLights();let t=[];for(let n of e??[]){let e=sv[n.type];if(!e)continue;let i=new e;i.name=n.name??``,i.visible=n.visible!==!1,i.color.setRGB(...n.color),i.intensity=n.intensity,i.position.fromArray(n.position),i.quaternion.fromArray(n.quaternion),i.scale.fromArray(n.scale??[1,1,1]),i.userData=Ln(n.userData)??{};for(let e of[`angle`,`penumbra`,`distance`,`decay`,`width`,`height`])typeof n[e]==`number`&&(i[e]=n[e]);if(n.target){let e=new r.Object3D;e.position.fromArray(n.target),this.scene.add(e),i.target=e}this.scene.add(i),t.push(i)}return this.updateLights(),this._syncHelpers(),this._onReset?.(),t}add(e){return this.addLight(e)}remove(e){return this.removeLight(e)}clear(){this.clearLights()}getAll(){return this.getLights()}sync(){this.updateLights()}showHelpers(e){this.setShowLightHelper(e)}dispose(){this._disposed||(this._disposed=!0,this._onLightRemoved=null,this.sceneHelpers?.clear(),this._removeAllLights(),this._onReset=null,this.pathTracer=null,this.sceneHelpers=null,this.scene=null)}_removeAllLights(e){this.scene.getObjectsByProperty(`isLight`,!0).filter(t=>!e||e(t)).forEach(e=>{this._onLightRemoved?.(e),e.target&&this.scene.remove(e.target),this.scene.remove(e)})}_syncHelpers(){if(!this.sceneHelpers.visible)return;let e=this.scene.getObjectsByProperty(`isLight`,!0);this.sceneHelpers.sync(e)}_buildDescriptor(e){let t=0;e.type===`SpotLight`&&e.angle!==void 0?t=r.MathUtils.radToDeg(e.angle):e.type===`DirectionalLight`&&(t=r.MathUtils.radToDeg(e.userData?.angle??0));let n={uuid:e.uuid,name:e.name,type:e.type,visible:e.visible,intensity:e.intensity,color:`#${e.color.getHexString()}`,position:[e.position.x,e.position.y,e.position.z],angle:t,temperature:e.userData?.temperature??6500,useTemperature:e.userData?.useTemperature??!1,exposure:e.userData?.exposure??0};if(e.type===`RectAreaLight`){n.width=e.width,n.height=e.height,n.normalize=e.userData?.normalize??!0,n.spread=r.MathUtils.radToDeg(e.userData?.spread??Math.PI);let t=e.userData?.shape;n.shape=t===`square`||t===`rectangle`||t===`disk`||t===`ellipse`?t:t===1?`ellipse`:`rectangle`;let i=e.getWorldDirection(e.position.clone());n.target=[e.position.x+i.x,e.position.y+i.y,e.position.z+i.z]}else e.type===`SpotLight`&&e.target?(n.target=[e.target.position.x,e.target.position.y,e.target.position.z],n.distance=e.distance??0,n.penumbra=e.penumbra??0,n.decay=e.decay??2):e.type===`PointLight`&&(n.distance=e.distance??0,n.decay=e.decay??2);return(e.type===`SpotLight`||e.type===`DirectionalLight`)&&e.userData?.gobo&&(n.gobo=e.userData.gobo.name,n.goboIntensity=e.userData.gobo.intensity,n.goboInverted=!!e.userData.gobo.inverted,e.type===`DirectionalLight`&&(n.goboScale=e.userData.gobo.scale??5)),e.type===`SpotLight`&&e.userData?.ies&&(n.ies=e.userData.ies.name,n.iesIntensity=e.userData.ies.intensity??1,n.fixtureLumens=e.userData.ies.fixtureLumens??null),n}};wt(),fe(),Ae(),I(),X(),Br(),Xg(),Ao(),Ra(),Ns();var lv=({element:e,pbrtEntry:t}={})=>({...e===void 0?{}:{element:e},...t===void 0?{}:{pbrtEntry:t}}),uv=new WeakMap,dv=new Set([...Object.values(P),...Object.values(F)]),fv=new Set;async function pv(e,t){if(!t||typeof self<`u`)return e.init();globalThis.self={requestAnimationFrame:()=>0,cancelAnimationFrame:()=>{}};try{return await e.init()}finally{delete globalThis.self}}var mv=ye(`engine`);function hv(){let e=new Float32Array(16);return new Uint32Array(e.buffer)[3]=St.TRIANGLE_LEAF,e}function gv(e,t){e.lost.then(e=>{t.app&&t.app._handleDeviceLost(e)})}var _v=/swiftshader|llvmpipe|lavapipe|basic render|microsoft basic|warp/i;function vv(e){let t=e.info??{},n=`${t.vendor??``} ${t.architecture??``} ${t.device??``} ${t.description??``}`;return{vendor:t.vendor??``,architecture:t.architecture??``,device:t.device??``,description:t.description??``,isSoftware:t.isFallbackAdapter===!0||e.isFallbackAdapter===!0||_v.test(n)}}var yv=class extends r.EventDispatcher{constructor(e,t={}){super(),this._headless=t.headless===!0||!e,e??=iv();try{uv.get(e)?.dispose()}catch(e){mv.warn(`prior canvas owner dispose failed`,e)}if(uv.set(e,this),this.canvas=e,this._autoResize=!this._headless&&t.autoResize!==!1,this._maxSceneBytes=t.maxSceneBytes,this._hostMemoryGB=t.hostMemoryGB,this._storageOption=t.storage,this._storageOpener=null,this._memorySpill=t.memorySpill===!0,this.storage=null,this._storageRelease=null,this._applySceneMetadataEnabled=t.applySceneMetadata!==!1,this._unlitRestore=null,this._applyingSceneMetadata=!1,t.profile!==void 0)throw Error("the `profile` option was removed: the engine has one set of defaults. For the old 'physical' profile set `dofMode: 'physical'` through `settings`.");this._issues=new Kt({strict:t.strict===!0,onIssue:e=>this.dispatchEvent({type:P.ISSUE,issue:e})}),this.color=new g_({issues:this._issues}),Ar(this.color),this.settings=new a_(G,{issues:this._issues}),this.renderer=null,this.scene=null,this.meshScene=null,this._sceneHelpers=null,this.assetLoader=null,this._sdf=null,this.pipeline=null,this._pendingReservedRenderSize=null,this.stages={},this.camera=null,this.lightManager=null,this.environmentManager=null,this.isInitialized=!1,this.pauseRendering=!1,this._pathTracerEnabled=!0,this._rasterPrecompile=null,this.animationManagerId=null,this.needsReset=!1,this._loadingInProgress=!1,this._needsDisplayRefresh=!1,this._paused=!1,this._emissiveSamplingUserSet=!1,this.completion=new Sg,this._resizeDebounceTimer=null,this._displayWidth=0,this._displayHeight=0,this._renderScale=1,this._renderWidth=0,this._renderHeight=0,this._trackedListeners=[],this._disposed=!1,this._deviceLost=!1,this._gpuDevice=null,this._deviceLostHolder=null,this._deterministic=!1,this._dispatchPinned=!1,this._deterministicRestore=null,this.adapterInfo=null}_addTrackedListener(e,t,n){e&&(e.addEventListener(t,n),this._trackedListeners.push({target:e,type:t,handler:n}))}_removeTrackedListeners(){for(let{target:e,type:t,handler:n}of this._trackedListeners)try{e.removeEventListener(t,n)}catch(e){mv.warn(`failed to remove listener`,t,e)}this._trackedListeners.length=0}async init(){let e=this._initStorage();return await this._initRenderer(),this._applyPendingReservedRenderSize(),this.camera=this._createCamera(),this._initScenes(),this._initAssetPipeline(),this._initPipeline(),await this._initManagers(),this._wireEvents(),await e,this._attachStorage(),this.stages.pathTracer.setTriangleData(new Uint32Array(K.FLOATS_PER_TRIANGLE),0),this.stages.pathTracer.setBVHData(hv()),this.stages.pathTracer.materialData.setMaterialData(new Float32Array(16)),this.stages.pathTracer.setupMaterial(),this.isInitialized=!0,mv.debug(`WebGPU path tracer app initialized`),this}async setStorageOpener(e){this._storageOpener=e,!(!this.isInitialized||this.storage||this._disposed)&&(await this._initStorage(),this._attachStorage())}async _initStorage(){let e=this._storageOption??(this._issues.strict&&!Ir(`storage`)?!1:Lr().storage);if(e!==!1){if(e&&typeof e==`object`)this.storage=e;else{if(!this._storageOpener){(this._storageOption!==void 0||Ir(`storage`))&&this._issues.warn(Y.CAPABILITY_MISSING,`on-disk storage needs rayzee/addons/storage: setStorageOpener( acquireSharedStorage )`);return}let{storage:e,reason:t,release:n}=await this._storageOpener(Lr().cacheNamespace);if(this._disposed){n();return}if(!e){this._issues.warn(Y.STORAGE_UNAVAILABLE,`on-disk storage is off: ${t}`,{reason:t});return}this.storage=e,this._storageRelease=n}this._addTrackedListener(this.storage,`change`,e=>this.dispatchEvent({type:P.STORAGE_CHANGED,area:e.area})),this._addTrackedListener(this.storage,`issue`,e=>this._issues.warn(e.code,e.message,e.detail))}}_attachStorage(){this.assetLoader&&(this.assetLoader.storage=this.storage)}dispatchEvent(e){super.dispatchEvent(e);let t=F[e.type];t&&super.dispatchEvent({...e,type:t})}addEventListener(e,t){!dv.has(e)&&!fv.has(e)&&(fv.add(e),mv.warn(`no engine event is named "${e}", so this listener will never fire — see EngineEvents`)),super.addEventListener(e,t)}animate(){if(this._headless)throw Error(`a headless app has no render loop — drive it with renderFrames() or renderUntilComplete()`);if(this._deviceLost)return;if(this.animationManagerId=requestAnimationFrame(()=>this.animate()),this._loadingInProgress||this._sdf?.isProcessing){this.dispatchEvent({type:P.FRAME});return}this._beginFrame();let e=this.needsReset;if(this.needsReset&&=(this.stages.pathTracer?.noteViewChanged(),this.reset(!0),!1),this.camera.updateMatrixWorld(),!this.pathTracerEnabled){this.renderer.render(this.meshScene,this.camera),this._renderHelperOverlay();return}if(!this.pauseRendering){if(this._beforeTrace(),this.stages.pathTracer?.isReady){if(this.stages.pathTracer.isComplete&&this.completion.renderCompleteDispatched){this._needsDisplayRefresh&&(this._needsDisplayRefresh=!1,this.stages.compositor.render(this.pipeline.context),this._renderHelperOverlay()),this.stopAnimation();return}if(this._holdTrace(e)){this._renderHelperOverlay(),this.dispatchEvent({type:P.FRAME});return}if(this.stages.pathTracer.readbackWait()){this.dispatchEvent({type:P.FRAME});return}this._traceFrame({liveDenoise:!0}),this.stages.pathTracer.isComplete&&this.completion.markComplete()&&(this._renderCompleted(),this.dispatchEvent({type:P.RENDER_COMPLETE,...this._completionInfo()}))}this._renderHelperOverlay(),this.dispatchEvent({type:P.FRAME})}}_traceFrame({liveDenoise:e=!1}={}){let t=this.stages.pathTracer;this.pipeline.render(),this._afterTrace(t,e),t.isComplete||this.completion.updateTime(),this._ensureVRAMWiring();let n=t.vramTracker,r=t.frameCount??0;n&&(r<=1||r%30==0)&&n.measure(),de({timeElapsed:this.completion.timeElapsed,samples:ee(t),memoryUsed:n?.current??0,memoryPeak:n?.peak??0}),this.completion.isTimeLimitReached(t,this.settings.get(`renderLimitMode`),this.settings.get(`renderTimeLimit`))&&(t.isComplete=!0)}_completionInfo(){return{samples:this.stages.pathTracer.frameCount,timeElapsed:this.completion.timeElapsed,budgetOverrun:this.completion.budgetOverrun,reason:this.completion.stopCondition(this.stages.pathTracer)??`samples`}}stopAnimation(){this.animationManagerId&&=(cancelAnimationFrame(this.animationManagerId),null)}_handleDeviceLost(e){this._deviceLost||(this._deviceLost=!0,mv.error(`WebGPU device lost (${e?.reason||`unknown`}): ${e?.message||``}`),this.stopAnimation(),this.dispatchEvent({type:P.DEVICE_LOST,reason:e?.reason,message:e?.message}))}wake(){this._deviceLost||this._headless||!this.animationManagerId&&this.isInitialized&&!this._paused&&this.animate()}pause(){this._paused=!0,this.stopAnimation()}resume(){this._paused=!1,!this.animationManagerId&&!this._headless&&this.animate()}reset(e=!1,{motion:t=!1}={}){t&&this.stages.pathTracer?.noteViewChanged(),this._beforeReset(e||t),this.pipeline&&(this.pipeline.reset(),e||this.pipeline.eventBus.emit(`pipeline:historyReset`)),this._afterReset(),this.completion.reset(),this.wake(),this.dispatchEvent({type:P.RENDER_RESET})}dispose(){if(!this._disposed){if(this._disposed=!0,this.dispatchEvent({type:P.DISPOSE}),this.stopAnimation(),clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=null,this._removeTrackedListeners(),L(null),this._storageRelease?.(),this._storageRelease=null,this.storage=null,this._sceneSource=this._sceneSourceInput=null,this._issues.detach(),this.color?.dispose(),this.color=null,this._textureReadback?.dispose(),this._textureReadback=null,this._readbackToneMapper?.dispose(),this._readbackToneMapper=null,this._disposeExtensions(),this.lightManager?.dispose(),this.pipeline?.dispose(),this._sdf?.dispose(),this._sdf=null,this.assetLoader?.dispose(),this.assetLoader=null,this.meshScene){this.meshScene.environment?.dispose(),this.meshScene.environment=null;for(let e of[...this.meshScene.children])ie(e);this.meshScene.clear(),this.meshScene=null}this._sceneHelpers?.clear(),this._sceneHelpers=null,this.scene?.clear(),this.scene=null;try{let e=(0,n.texture)().value,t=(0,n.cubeTexture)().value;e?._listeners?.dispose&&(e._listeners.dispose.length=0),t?._listeners?.dispose&&(t._listeners.dispose.length=0)}catch(e){mv.warn(`failed to clear TSL texture singleton listeners`,e)}this.canvas&&uv.get(this.canvas)===this&&uv.delete(this.canvas),this._gpuDevice&&=(this._gpuDevice.onuncapturederror=null,null),this._deviceLostHolder&&=(this._deviceLostHolder.app=null,null),re(this.renderer),this.renderer=null,this.stages={},this.isInitialized=!1}}unloadScene(){if(this.isInitialized){if(this._loadingInProgress)throw Error(`PathTracerApp.unloadScene: cannot unload while a load is in progress`);this._disposed||(this._releaseSceneState(),this.assetLoader?.releaseTargetModel(),this._sceneSource=this._sceneSourceInput=null,this.lightManager?.clearLights?.(),this.stages.pathTracer&&(this.stages.pathTracer.setTriangleData(new Uint32Array(K.FLOATS_PER_TRIANGLE),0),this.stages.pathTracer.setBVHData(hv()),this.stages.pathTracer.materialData.setMaterialData(new Float32Array(16)),this.stages.pathTracer.setEmissiveTriangleData?.(new Float32Array,0,0),this.stages.pathTracer.setupMaterial()),this._dropDisplay(),this.reset(),this.dispatchEvent({type:P.SCENE_UNLOADED}))}}async loadModel(e,t={}){await this._loadWithSceneRebuild(()=>this.assetLoader.loadModel(e,t),{type:P.MODEL_LOADED,url:e},{kind:`url`,url:e,cacheKey:t.cacheKey??null})}async loadObject3D(e,t=`object3d`){await this._loadWithSceneRebuild(()=>this.assetLoader.loadObject3D(e,t),{type:P.OBJECT3D_LOADED,name:t},{kind:`object3d`,name:t})}_busyError(e){let t=Error(`${e}: another load is already in progress`);return t.code=`LOAD_IN_PROGRESS`,t}async loadEnvironment(e){if(this._loadingInProgress)throw this._busyError(`PathTracerApp.loadEnvironment`);this._loadingInProgress=!0;try{await this.assetLoader.loadEnvironment(e);let t=this.meshScene.environment;t&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(t),this.pipeline?.eventBus.emit(`pipeline:lightingChanged`),this.reset(),this.dispatchEvent({type:P.ENVIRONMENT_LOADED,url:e})}finally{this._loadingInProgress=!1}}async inspectArchive(e){return await this.assetLoader.inspectArchive(e)}async loadFile(e,t={}){if(t=this._sceneBudgets(t),typeof e==`string`){let n=t.filename??kg(e),r=this.assetLoader?.getFileFormat(n);if(!r)throw this.assetLoader.formatError(n);if(r.type===`environment`||r.type===`image`)return this.loadEnvironment(e);await this._loadWithSceneRebuild(()=>this.assetLoader.loadAssetFromUrl(e,{...t,filename:n}),{type:P.MODEL_LOADED,filename:n},{kind:`url`,url:e,filename:n,cacheKey:t.cacheKey??null,...lv(t)});return}if(e_(e)){let n=Zg(e,{isModel:e=>this.assetLoader?.getFileFormat(e)?.type===`model`});if(n.files.length===0)throw Error(`${n.name} holds no files to load`);await this._loadWithSceneRebuild(()=>this.assetLoader.loadFolder(n,t),{type:P.MODEL_LOADED,filename:n.name},async()=>{let e=await Hg(n);return{kind:`local-folder`,folder:e,key:Ug(e),...n.flat?{flat:!0}:{},...lv(t)}}),this._sceneSourceInput=n;return}let n=this.assetLoader?.getFileFormat(e?.name||``);if(!n)throw this.assetLoader.formatError(e?.name||``);if(n.type!==`environment`&&n.type!==`image`){let n=Vg(e).catch(()=>({name:e.name,size:e.size,lastModified:e.lastModified??0,sample:null}));await this._loadWithSceneRebuild(()=>this.assetLoader.loadAssetFromFile(e,t),{type:P.MODEL_LOADED,filename:e.name},async()=>{let e=await n;return{kind:`local-file`,file:e,key:e.sample?Ug(e):null,...lv(t)}}),this._sceneSourceInput=e;return}if(this._loadingInProgress)throw this._busyError(`PathTracerApp.loadFile`);this._loadingInProgress=!0;try{await this.assetLoader.loadAssetFromFile(e);let t=this.meshScene.environment;t&&this.stages.pathTracer&&await this.stages.pathTracer.environment.applyHDRI(t),this.pipeline?.eventBus.emit(`pipeline:lightingChanged`),this.reset(),this.dispatchEvent({type:P.ENVIRONMENT_LOADED,filename:e.name})}finally{this._loadingInProgress=!1}}async loadExampleModels(e,t){await this._loadWithSceneRebuild(()=>this.assetLoader.loadExampleModels(e,t),{type:P.MODEL_LOADED,index:e},{kind:`url`,url:t[e]?.url??null,cacheKey:null})}cancelLoad(){this._loadingInProgress&&this.assetLoader?.cancelActiveLoad()}async setMaxTextureSize(e,{reprocess:t=!0}={}){let n=this.settings.get(`maxTextureSize`),r=this._sdf?.setMaxTextureSize(e)??e;if(this.settings.set(`maxTextureSize`,r,{reset:!1}),typeof this.stages?.pathTracer?.sdfs?.setMaxTextureSize==`function`&&this.stages.pathTracer.sdfs.setMaxTextureSize(r),t&&r!==n&&this._sdf?.triangles&&!this._loadingInProgress){this._loadingInProgress=!0;try{await this.loadSceneData(),this.reset(),this.dispatchEvent({type:P.TEXTURES_REPROCESSED,maxTextureSize:r})}finally{this._loadingInProgress=!1}}}get sceneSource(){return this._sceneSource??null}get sceneSourceFile(){return this._sceneSourceInput&&!e_(this._sceneSourceInput)?this._sceneSourceInput:null}get sceneSourceFolder(){return e_(this._sceneSourceInput)?this._sceneSourceInput:null}async _loadWithSceneRebuild(e,t,n=null){if(this._loadingInProgress)throw this._busyError(`PathTracerApp`);this._loadingInProgress=!0;try{await e(),this._sceneSource=typeof n==`function`?await n():n,this._sceneSourceInput=null,this._emissiveSamplingUserSet=!1,this._clearAppendedModels(),this._modelReplaced(),await this.loadSceneData({pendingEnvironment:this._beginSceneMetadataEnvironment()}),this._maybeSpill(),this.pipeline?.eventBus.emit(`pipeline:lightingChanged`),this._dropDisplay(),this.reset(),this.dispatchEvent(t),this._modelAnnounced()}catch(e){throw(!e||e.code!==`LOAD_IN_PROGRESS`)&&this._discardFailedLoad(),e?.code===`ARCHIVE_NEEDS_ELEMENT`?ue():e?.code!==`LOAD_IN_PROGRESS`&&z({status:`Error: ${e?.message??e}`,failed:!0,progress:100}),e}finally{this._loadingInProgress=!1}}_discardFailedLoad(){this._sceneSource=this._sceneSourceInput=null;try{this._clearAppendedModels(),this.assetLoader?.releaseTargetModel(),this._dropDisplay(),this.reset()}catch(e){console.warn(`PathTracerApp: could not clear the scene after a failed load`,e)}}get sceneMetadata(){return this.assetLoader?.sceneMetadata??null}_beginSceneMetadataEnvironment(){this._restoreUnlitSettings();let e=this.sceneMetadata?.environment;return this._applySceneMetadataEnabled&&e?.enabled===!1?(this._applyUnlitSettings(),null):!this._applySceneMetadataEnabled||!e?.sourceFile||!this.stages.pathTracer?null:(this.stages.pathTracer.environment.beginHDRI(),this._applyingSceneMetadata=!0,this.assetLoader.loadEnvironment(e.sourceFile).catch(t=>(this._issues.record(Y.ENVIRONMENT_LOAD_FAILED,`authored environment "${e.sourceFile}" failed to load — lighting falls back to the previous environment`,{sourceFile:e.sourceFile,cause:String(t?.message??t)}),null)).finally(()=>{this._applyingSceneMetadata=!1}))}_applySceneMetadataSettings(e){let t=this.sceneMetadata,n=t?.environment;if(!n||n.enabled===!1)return;let r={enableEnvironment:!0,showBackground:!0,transparentBackground:!1};n.intensity!==void 0&&(r.environmentIntensity=n.intensity,r.backgroundIntensity=n.intensity),n.rotation!==void 0&&(r.environmentRotation=n.rotation),this.settings.setMany(r,{reset:!1,source:i_.SCENE_METADATA}),this.scene&&(this.scene.background=e),this.dispatchEvent({type:P.SCENE_METADATA_APPLIED,metadata:t,environment:{...n}})}_applyUnlitSettings(){let e=this.settings.getEffective(),t={enableEnvironment:!1,showBackground:!1};this._unlitRestore=Object.fromEntries(Object.keys(t).map(t=>[t,{value:e[t].value,source:e[t].source}])),this.settings.setMany(t,{reset:!1,source:i_.SCENE_METADATA}),this.dispatchEvent({type:P.SCENE_METADATA_APPLIED,metadata:this.sceneMetadata,environment:{enabled:!1}})}_restoreUnlitSettings(){let e=this._unlitRestore;if(!e)return;this._unlitRestore=null;let t=this.settings.getEffective();for(let[n,{value:r,source:i}]of Object.entries(e))t[n]?.source===i_.SCENE_METADATA&&this.settings.set(n,r,{reset:!1,source:i});this.dispatchEvent({type:P.SCENE_METADATA_APPLIED,metadata:this.sceneMetadata,environment:{enabled:this.settings.get(`enableEnvironment`)}})}async loadSceneData({pendingEnvironment:e=null,keepUserLights:t=!1}={}){this._releaseSceneState({keepSelection:!!this._preserveSelectionOnRebuild}),this._tagPrimarySceneObject();let n=new us(``,{namespace:`scene`,level:`info`}),r=()=>this.stages.pathTracer.environment.envParams.mode===`hdri`?this.meshScene.environment:null,i=r(),a=null;if(e?(n.start(`Environment fetch + CDF (concurrent)`),a=e.then(async e=>{e&&(await this.stages.pathTracer.environment.applyHDRI(e),this._applySceneMetadataSettings(e))}).catch(e=>this._issues.record(Y.ENVIRONMENT_LOAD_FAILED,`authored environment failed to install — the scene is lit by whatever was already loaded`,{cause:String(e?.message??e)})).finally(()=>n.end(`Environment fetch + CDF (concurrent)`))):i?.image?.data&&(n.start(`Environment CDF build (worker)`),this.stages.pathTracer.scene.environment=i,a=this.stages.pathTracer.environment.buildEnvironmentCDF().then(()=>{n.end(`Environment CDF build (worker)`),this._applySceneMetadataEnabled&&this._applySceneMetadataSettings(i)})),n.start(`BVH build (SceneProcessor)`),this._sdf.setMaxTextureSize(this.settings.get(`maxTextureSize`)),await this._sdf.buildBVH(this.meshScene,{sceneKey:this.assetLoader?.sceneSourceKey??null,progressive:this._progressiveSpill()}),this.assetLoader?.flushPendingGraph(this._sdf.performanceMetrics.totalProcessingTime),n.end(`BVH build (SceneProcessor)`),z({status:`Transferring data to GPU...`,progress:86}),await new Promise(e=>setTimeout(e,0)),n.start(`GPU data transfer`),!this._sdf.uploadToPathTracer(this.stages.pathTracer,this.lightManager,this.meshScene,r(),{keepUserLights:t}))return!1;this.stages.pathTracer._meshRefs=this.stages.pathTracer._collectMeshRefs(this.meshScene),this.stages.pathTracer.setMeshVisibilityData(this.stages.pathTracer._meshRefs),this._refreshEmissiveForVisibility(),n.end(`GPU data transfer`),z({status:`Compiling shaders...`,progress:90}),await new Promise(e=>setTimeout(e,0)),n.start(`Material setup (TSL compile)`),this.stages.pathTracer.setupMaterial(),n.end(`Material setup (TSL compile)`),this._rasterPrecompile=null,this._pathTracerEnabled||(n.start(`Pipeline precompile`),await this.precompileRaster(),n.end(`Pipeline precompile`)),a&&(z({status:`Finalizing environment map...`,progress:95}),await a,this.stages.pathTracer.environment.applyCDFResults());let o=this.getSceneMinY();if(this.settings.set(`groundProjectionLevel`,o,{reset:!1}),this.settings.set(`groundCatcherHeight`,o,{reset:!1}),!this._emissiveSamplingUserSet){let e=(this._sdf?.emissiveTriangleBuilder?.emissiveTriangles?.length??this._sdf?.emissiveTriangleCount??0)>0;this.settings.set(`enableEmissiveTriangleSampling`,e,{reset:!1})}return n.start(`Apply settings`),this.settings.applyAll(),this.stages.compositor.setTransparentBackground(this.settings.get(`transparentBackground`)),n.end(`Apply settings`),n.print(this._sceneSummaryParts()),ue(),this._sceneRebuilt(),this.dispatchEvent({type:P.SCENE_REBUILD}),!0}_sceneSummaryParts(){let e=this.stages.pathTracer,t=this._sdf?.instanceTable?.setCount??0,n=this._sdf?.geometryExtractor?.maps?.length??0;return[H.count(e.triangleCount,`tri`),t?H.count(t,`mesh`,`meshes`):null,H.count(e.materialData.materialCount,`material`),n?H.count(n,`map`):null,H.count(e.bvhNodeCount,`BVH node`)]}_tagPrimarySceneObject(){let e=this.sceneModel;e&&(e.userData.__rayzeeSceneObject=!0)}_clearAppendedModels(){let e=this.meshScene;if(!e)return;let t=this.assetLoader?.floorPlane,n=this.sceneModel;for(let r of[...e.children])r===t||r===n||r.userData?.__rayzeeSceneObject&&this.assetLoader.removeModelRoot(r)}async _finishRebuildNoReframe(e){await this.loadSceneData({keepUserLights:!0}),this._maybeSpill(),this._sceneBoundsChanged(),this.pipeline?.eventBus.emit(`pipeline:lightingChanged`),this.reset(),e&&this.dispatchEvent(e)}async addModel(e,{name:t,cacheKey:n}={}){if(this._loadingInProgress)throw Error(`PathTracerApp.addModel: another load is already in progress`);this._loadingInProgress=!0,this._preserveSelectionOnRebuild=!0;try{let{root:r}=await this.assetLoader.appendModel(e,{cacheKey:n});return r.userData.__rayzeeSceneObject=!0,r.userData.__rayzeeSourceUrl=e,n&&(r.userData.__rayzeeCacheKey=n),t&&(r.userData.__rayzeeName=t),await this._finishRebuildNoReframe({type:P.MODEL_ADDED,url:e,id:r.uuid}),r.uuid}finally{this._preserveSelectionOnRebuild=!1,this._loadingInProgress=!1}}async addModelFromObject3D(e,{name:t}={}){if(this._loadingInProgress)throw Error(`PathTracerApp.addModelFromObject3D: another load is already in progress`);this._loadingInProgress=!0,this._preserveSelectionOnRebuild=!0;try{let{root:n}=this.assetLoader.appendObject3D(e,t||`object3d`);return n.userData.__rayzeeSceneObject=!0,t&&(n.userData.__rayzeeName=t),await this._finishRebuildNoReframe({type:P.MODEL_ADDED,id:n.uuid}),n.uuid}finally{this._preserveSelectionOnRebuild=!1,this._loadingInProgress=!1}}async removeSceneObject(e){if(!this.meshScene)return!1;let t=this.assetLoader?.floorPlane;if(t&&t.uuid===e)return!1;let n=this.getSceneObject(e);if(!n)return!1;if(this._loadingInProgress)throw Error(`PathTracerApp.removeSceneObject: another load is already in progress`);this._loadingInProgress=!0;try{return this._releaseSceneState(),n===this.sceneModel?this.assetLoader.releaseTargetModel():this.assetLoader.removeModelRoot(n),await this._finishRebuildNoReframe({type:P.SCENE_OBJECT_REMOVED,id:e}),!0}finally{this._loadingInProgress=!1}}setSceneObjectVisibility(e,t){return this.setMeshVisibilityByUuid(e,t)}_sceneBudgets(e){return!this._memorySpill||!this.storage?e:{maxTriangles:Na,maxPlacements:Pa,...e}}_progressiveSpill(){if(!this._memorySpill||!this.storage||(this.assetLoader?.animations?.length??0)>0)return null;let e=this.stages.pathTracer;return{storage:this.storage,uploader:(t,n)=>n===`triangles`?e.createTriangleChunkUploader(t):e.createChunkUploader(t)}}_maybeSpill(){!this._memorySpill||!this.storage||(this.assetLoader?.animations?.length??0)>0||this._sdf?.spillToDisk(this.storage).then(e=>e&&this.dispatchEvent({type:P.SCENE_SPILLED,...e})).catch(e=>this._issues.warn(Y.STORAGE_WRITE_FAILED,`memory spill failed: ${e.message}`))}async ensureSceneResident(){this._sdf?.spilled&&await this._sdf.ensureResident()}get sceneMeshes(){return this._sdf?.meshes??[]}get sceneModel(){return this.assetLoader?.targetModel??null}getSceneObject(e){let t=this.meshScene?.children.find(t=>t.uuid===e);return t?.userData?.__rayzeeSceneObject?t:null}async refitBVH(e,t){await this.ensureSceneResident();let{triRanges:n,bvhRanges:r,...i}=await this._sdf.refitBVH(e,t);return this.stages.pathTracer.updateTriangleData(this._sdf.triangles,n),this.stages.pathTracer.updateBVHData(this._sdf.bvh,r),this.reset(!1,{motion:!0}),i}refitBLASes(e,t,n){if(this._sdf?.spilled)throw Error(`refitBLASes: the scene is spilled to disk — await app.ensureSceneResident() first`);let r=this._sdf.refitBLASes(e,t,n),{triRanges:i,bvhRanges:a}=this._sdf.computeBLASDirtyRanges(e);return this.stages.pathTracer.updateBufferRanges(i,a),this.reset(!1,{motion:!0}),this._sdf.scheduleBackgroundRebuild(e,e=>{let t=this._sdf.computeBLASDirtyRanges([e]);this.stages.pathTracer.updateBufferRanges(t.triRanges,t.bvhRanges),this.reset(!1,{motion:!0})}),r}updateMeshTransforms(e){this._notePlacementsMoving(e);let t=this._sdf.updateMeshTransforms(e);return this.stages.pathTracer.updateBufferRanges([],[this._sdf.computeTLASDirtyRange()]),this.reset(!1,{motion:!0}),t}setReservedRenderResolution(e,{allowLower:t=!1}={}){let n=t?e:Math.max(e,U);if(!this.renderer)return this._pendingReservedRenderSize={requestedPx:e,allowLower:t},Math.max(256,Math.min(je,Math.floor(n)||256));let r=this.renderer.backend?.device?.limits?.maxStorageBufferBindingSize||128*1024*1024,i=Ca(this._hostMemoryGB),a=i.gb>=8&&r>=1024*1024*1024?je:2048,o=Me(Math.min(n,a));if(o<Math.floor(e)&&this._issues.warn(Y.RENDER_RESERVE_CAPPED,`reserved render size ${H.n(e)}px was capped to ${H.n(o)}px by this device's limits — renders above ${H.n(o)}px will be declined`+(i.assumed&&i.gb<8?` (host memory unknown, 4 GB assumed: pass hostMemoryGB)`:``),{requested:e,applied:o,deviceMemoryGB:i.gb,assumed:i.assumed,maxStorageBufferBindingSize:r}),(this.stages?.pathTracer?.storageTextures?.writeColor?.image?.width??o)!==o){let e=this.pauseRendering;this.pauseRendering=!0;try{let e=this.renderer.domElement;(e.width>o||e.height>o)&&this.renderer.setSize(Math.min(e.width,o),Math.min(e.height,o),!1);for(let e of Object.values(this.stages))e?.reallocateReservedStorage?.()}finally{this.pauseRendering=e}this.reset(),this.dispatchEvent({type:P.RESERVED_RENDER_SIZE_CHANGED,size:o})}return o}_applyPendingReservedRenderSize(){let e=this._pendingReservedRenderSize;if(!e)return;this._pendingReservedRenderSize=null;let t=this.setReservedRenderResolution(e.requestedPx,{allowLower:e.allowLower});this.dispatchEvent({type:P.RESERVED_RENDER_SIZE_CHANGED,size:t})}getReservedRenderResolution(){return U}_isRenderSizeSupported(e,t){return e>U||t>U?(this._issues.record(Y.RENDER_SIZE_DECLINED,`render resolution ${e}×${t} exceeds the ${U}px storage reserve — resize ignored, so output stays at the previous size. Raise it with setReservedRenderResolution( ${Math.max(e,t)} ) before init().`,{width:e,height:t,reserve:U}),!1):!0}onResize(){let e=this.canvas.clientWidth,t=this.canvas.clientHeight;e===0||t===0||this._isRenderSizeSupported(e,t)&&(this.renderer.setPixelRatio(1),this._setDisplaySize(e,t),!(e===this._renderWidth&&t===this._renderHeight)&&(clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=setTimeout(()=>{this._applyRenderResize(e,t)},300)))}_applyRenderResize(e,t){this._isRenderSizeSupported(e,t)&&(this.pipeline?.setSize(this._scaled(e),this._scaled(t)),this._renderWidth=e,this._renderHeight=t,this._renderSizeChanged(e,t),this.needsReset=!0,this.dispatchEvent({type:P.RESOLUTION_CHANGED,width:e,height:t}))}setCanvasSize(e,t){return e===0||t===0||!this._isRenderSizeSupported(e,t)?null:(this.renderer.setPixelRatio(1),this._setDisplaySize(e,t),clearTimeout(this._resizeDebounceTimer),this._applyRenderResize(e,t),{width:e,height:t})}_scaled(e){return Math.max(1,Math.round(e*this._renderScale))}_setDisplaySize(e,t){this._displayWidth=e,this._displayHeight=t,this.renderer.setSize(this._scaled(e),this._scaled(t),!1),this.camera.aspect=e/t,this.camera.updateProjectionMatrix()}refreshFrame(){this._needsDisplayRefresh=!0,this.wake()}setDeterministicMode(e=!0,{pinDispatch:t=!0}={}){let n=this.stages.pathTracer;if(!n)return!1;if(e)this._deterministicRestore||={settings:{useAdaptiveSampling:this.settings.get(`useAdaptiveSampling`),usePixelFreeze:this.settings.get(`usePixelFreeze`),interactionModeEnabled:this.settings.get(`interactionModeEnabled`),renderLimitMode:this.settings.get(`renderLimitMode`),renderTimeLimit:this.settings.get(`renderTimeLimit`)},bounceEarlyExit:n._bounceEarlyExitThreshold,dynamicDispatch:n._useDynamicDispatch,extras:this._deterministicSnapshot()},this.settings.setMany({useAdaptiveSampling:!1,usePixelFreeze:!1,interactionModeEnabled:!1,renderLimitMode:`frames`,renderTimeLimit:0},{silent:!0}),t?(n._bounceEarlyExitThreshold=-1,n._useDynamicDispatch=!1):(n._bounceEarlyExitThreshold=this._deterministicRestore.bounceEarlyExit,n._useDynamicDispatch=this._deterministicRestore.dynamicDispatch),this._setDeterministicExtras(!0,this._deterministicRestore.extras),n._pinSeedToFrame=!0,this._deterministic=!0,this._dispatchPinned=t;else if(this._deterministicRestore){let e=this._deterministicRestore;this.settings.setMany(e.settings,{silent:!0}),n._bounceEarlyExitThreshold=e.bounceEarlyExit,n._useDynamicDispatch=e.dynamicDispatch,this._setDeterministicExtras(!1,e.extras),n._pinSeedToFrame=!1,this._deterministicRestore=null,this._deterministic=!1,this._dispatchPinned=!1}return this.reset(),this.stopAnimation(),this._deterministic}get issues(){return this._issues.list}get issueErrors(){return this._issues.errors}clearIssues(){this._issues.clear()}get isDeterministic(){return this._deterministic&&this._dispatchPinned}async renderFrames(e,{reset:t=!0,yieldEvery:n=8,onProgress:r,allowEarlyRetire:i=!1}={}){let a=this.stages.pathTracer;if(!a)throw Error(`renderFrames: app is not initialized`);if(!(e>0))throw Error(`renderFrames: count must be positive, got ${e}`);let o=(t?0:a.frameCount)+e;this.settings.get(`maxSamples`)<o&&this.settings.set(`maxSamples`,o,{silent:!0,reset:!1}),t&&this.reset(),this.stopAnimation();let s=e+64,c=0,l=!1;for(;a.frameCount<o&&c<s;){if(this._deviceLost)throw Error(`renderFrames: WebGPU device lost`);if(!a.isReady)throw Error(`renderFrames: path tracer stage is not ready`);let e=a.readbackWait();if(e){await this._awaitReadback(e);continue}if(this.camera.updateMatrixWorld(),this.pipeline.render(),c++,a.isComplete&&a.frameCount<o){l=!0;break}r?.(a.frameCount),n>0&&c%n===0&&await new Promise(e=>setTimeout(e,0))}if(a.frameCount<o&&!(l&&i)){let e=l?"adaptive sampling retired the frame at the convergence threshold — pass `allowEarlyRetire: true`, or disable it with setDeterministicMode()":`something retired the render (maxSamples, a stray reset, or a canvas resize)`;throw Error(`renderFrames: stopped at ${a.frameCount}/${o} samples after ${c} passes — ${e}`)}return a.frameCount}async renderUntilComplete({reset:e=!0,denoise:t=!0,signal:n,drainEvery:r=4,onProgress:i}={}){let a=this.stages.pathTracer;if(!a)throw Error(`renderUntilComplete: app is not initialized`);if(this._loadingInProgress||this._sdf?.isProcessing)throw Error(`renderUntilComplete: a scene is still loading`);let o=a.lockstepReadbacks;a.setLockstepReadbacks(!0);let s=this.settings.getEffective().interactionModeEnabled;this.settings.set(`interactionModeEnabled`,!1,{silent:!0,reset:!1});try{e&&this.reset(),this.stopAnimation();let o=this.renderer.backend.device?.queue,s=0,c=null;for(;!a.isComplete;){if(n?.throwIfAborted(),this._deviceLost)throw Error(`renderUntilComplete: WebGPU device lost`);if(!a.isReady)throw Error(`renderUntilComplete: path tracer stage is not ready`);let e=a.readbackWait();if(e){await this._awaitReadback(e);continue}this.camera.updateMatrixWorld();let t=a.frameCount;if(this._traceFrame(),i?.(a.frameCount),a.frameCount===t&&!a.isComplete&&await new Promise(e=>setTimeout(e,0)),o&&r>0&&++s%r===0){let e=o.onSubmittedWorkDone();c&&await c,c=e}}let l=this._completionInfo();this.completion.markComplete()&&this.dispatchEvent({type:P.RENDER_COMPLETE,...l});let u=t?await this._finalDenoise():!1,{reason:d,...f}=l;return{...f,retiredBy:d,denoised:u}}finally{a.setLockstepReadbacks(o),s&&this.settings.set(`interactionModeEnabled`,s.value,{silent:!0,reset:!1,source:s.source})}}getProvenance(){let e=this.stages.pathTracer,t=this.color?.status();return In({engine:Ms,three:r.REVISION,adapter:this.adapterInfo??null,mode:{headless:this._headless,strict:this._issues.strict,deterministic:this.isDeterministic,lockstep:!!e?.accumulationLockstep},render:e?{width:e.width,height:e.height,samples:e.frameCount,complete:e.isComplete,retiredBy:e.isComplete?this.completion.stopCondition(e)??`samples`:null}:null,color:t?{config:t.config?.id??null,workingSpace:t.workingSpace,view:t.activeView??t.activeTransform?.id??null,context:t.context}:null,scene:this.sceneSource,settings:this.settings.getEffective(),issues:this.issues.map(({code:e,severity:t})=>({code:e,severity:t}))})}setLockstepReadbacks(e=!0){this.stages.pathTracer?.setLockstepReadbacks(e)}async _awaitReadback(e){let t=this.renderer.backend.device?.lost,n=await(t?Promise.race([e.then(()=>null),t]):e);if(n)throw Error(`WebGPU device lost while awaiting a readback: ${n.message??n.reason}`)}async captureRenderCheckpoint(){let e=this.stages.pathTracer;if(!e)return null;let t=await e.captureAccumulation();return{v:1,engine:Ms,savedAt:Date.now(),samples:t.state.frameCount,...t}}restoreRenderCheckpoint(e){if(e?.v!==1)throw Error(`render checkpoint version ${e?.v} is not 1`);let t=this.stages.pathTracer;if(!t)throw Error(`restoreRenderCheckpoint: app is not initialized`);t.restoreAccumulation(e),this.needsReset=!1,this.dispatchEvent({type:P.RENDER_RESET,restored:e.samples})}async renderToBuffer({colorSpace:e=`srgb`,preserveAlpha:t=!1,source:n=`accumulation`}={}){if(e!==`linear`&&e!==`srgb`&&!this.color?.hasConfig)throw Error(`renderToBuffer: colorSpace must be 'linear' or 'srgb' without a colour config loaded, got "${e}"`);let r=this.stages?.pathTracer,i=r?.storageTextures?.readTarget;if(!i)throw Error(`renderToBuffer: no render target — call init() and render at least one sample`);let{width:a,height:o}=r;if(e===`srgb`){let r=n===`display`?this._displaySource(i):null,s={exposure:this.renderer.toneMappingExposure,toneMapping:this.renderer.toneMapping,saturation:this.settings.get(`saturation`)??1,preserveAlpha:t},c=await this._toneMapOnGPU(r?.texture??null,i,a,o,s);return{data:c??Vo(r?await this._readTexture(r.texture,a,o):await this.renderer.readRenderTargetPixelsAsync(i,0,0,a,o,0),s),width:a,height:o,colorSpace:e,source:r?.source??`accumulation`,toneMappedOn:c?`gpu`:`cpu`}}let{data:s,source:c}=n===`display`?await this._readDisplaySource(i,a,o):{data:await this.renderer.readRenderTargetPixelsAsync(i,0,0,a,o,0),source:`accumulation`};if(e===`linear`)return{data:s,width:a,height:o,colorSpace:e,workingSpace:this.color?.workingSpace??null,source:c};let{rgba:l,colorSpace:u}=this.color.exportPixels(s,e);return{data:l,width:a,height:o,colorSpace:u,source:c}}async _toneMapOnGPU(e,t,n,r,i){let a=this.renderer?.backend;if(!a?.device)return this._toneMapFallback(`the renderer has no WebGPU device`);try{let o=e?this._readbackPass().draw(e,n,r).texture:t.textures[0],s=a.get(o).texture;return s?(this._readbackToneMapper??=new m_(a.device,`rayzee:readback-tonemap`,{input:`texture`}),this._readbackToneMapper.ensureSize(n,r),await this._readbackToneMapper.toRGBA8(s,i)):this._toneMapFallback(`the picture has no GPU texture yet`)}catch(e){if(e instanceof Gt)throw e;return this._toneMapFallback(`the GPU pass threw`,e)}finally{this._readbackToneMapper?.release(),e&&this._textureReadback?.release()}}_toneMapFallback(e,t=null){let n=t?String(t?.message??t):null,r=`renderToBuffer: tone mapped on the CPU — ${e}${n?`: ${n}`:``}`;return mv.warn(r),this._issues.warn(Y.OUTPUT_TONEMAP_FALLBACK,r,{reason:e,cause:n}),null}enableGPUTiming(e=!0){let t=this.renderer?.backend;return!t||e&&t.hasFeature?.(`timestamp-query`)!==!0?!1:(t.trackTimestamp=e,t.trackTimestamp===e)}async getGPUTimings(){let e=this.renderer;if(!e?.backend?.trackTimestamp)return null;await e.resolveTimestampsAsync(`compute`),await e.resolveTimestampsAsync(`render`);let t=e.info.compute.timestamp||0,n=e.info.render.timestamp||0;return{compute:t,render:n,total:t+n}}async getKernelGPUTimings(){let e=this.renderer;if(!e?.backend?.trackTimestamp)return null;await e.resolveTimestampsAsync(`compute`);let t=e.backend.timestampQueryPool?.compute?.timestamps;if(!t||t.size===0)return null;let n=new Map,r=this.stages?.pathTracer?._kernelManager?.kernels;if(r)for(let[e,t]of r)n.set(t.id,e);let i=[],a=-1;for(let[e,n]of t){let t=e.split(`:`);if(t.length!==4)continue;let r=Number(t[3].slice(1));Number.isFinite(r)&&(i.push({nodeId:Number(t[2]),f:r,ms:n}),r>a&&(a=r))}let o={},s=0,c=0;for(let e of i){if(e.f!==a)continue;s+=e.ms;let t=n.get(e.nodeId);t===void 0?c+=e.ms:o[t]=(o[t]??0)+e.ms}return{kernels:o,total:s,unattributed:c,frame:a}}getCanvas(){return this.renderer?.domElement?this._displayCanvas()||(this.stages.compositor&&this.pipeline?.context&&this.stages.compositor.render(this.pipeline.context),this.renderer.domElement):null}screenshot({type:e=`image/png`,quality:t}={}){let n=this.getCanvas();return n?new Promise(r=>n.toBlob(r,e,t)):Promise.resolve(null)}getStatistics(){try{return this._sdf?.getStatistics?.()??null}catch{return null}}get pathTracerEnabled(){return this._pathTracerEnabled}set pathTracerEnabled(e){this._pathTracerEnabled=e,e||this.precompileRaster()}precompileRaster(){return!this.renderer||!this.meshScene?Promise.resolve():(this._rasterPrecompile??=this.renderer.compileAsync(this.meshScene,this.camera).catch(e=>mv.warn(`raster fallback precompile failed`,e)),this._rasterPrecompile)}get isLoading(){return this._loadingInProgress}isComplete(){return this.stages.pathTracer?.isComplete??!1}getFrameCount(){return this.stages.pathTracer?.frameCount||0}getConvergenceStats(){return this.stages.pathTracer?.getConvergenceStats?.()??null}get vram(){return this.stages.pathTracer?.vramTracker??null}getMemoryInfo(){return this._ensureVRAMWiring(),this.stages.pathTracer?.vramTracker?.measure()??{current:0,peak:0,byCategory:{}}}getHostMemoryInfo(){let e=this._sdf;return e?.memory?{preflight:e.memoryPreflight,...e.memory.report}:null}_ensureVRAMWiring(){if(this._vramWired)return;let e=this.stages.pathTracer?.vramTracker;if(!e)return;e.register(`stages`,()=>this._collectStageTextures()),this._registerVRAM(e),e.register(`canvas`,()=>[{bytes:this.canvas.width*this.canvas.height*4},...this.renderer?._frameBufferTargets?.values()??[],...this._canvasResources()]);let t=()=>e.measure();this._addTrackedListener(this,P.SCENE_REBUILD,t),this._addTrackedListener(this,P.ENVIRONMENT_LOADED,t),this._addTrackedListener(this,P.RESOLUTION_CHANGED,t),this._vramWired=!0}_collectStageTextures(){let e=[],t=this.stages||{},n=t.pathTracer;for(let r in t){let i=t[r];if(!(!i||i===n||typeof i!=`object`))for(let t in i){let n=i[t];n&&(n.isTexture||n.isRenderTarget)&&e.push(n)}}return e}getSceneMinY(){if(!this.meshScene)return 0;let e=new r.Box3().setFromObject(this.meshScene);return Number.isFinite(e.min.y)?e.min.y:0}getMaterialProperty(e,t){return this.stages.pathTracer?.materialData.getMaterialProperty(e,t)}getMaterialPropertySource(e,t){return this.stages.pathTracer?.materialData.getMaterialPropertySource(e,t)}setMaterialProperty(e,t,n){if(this._sdf?.spilled&&Yn.has(t)){this.ensureSceneResident().then(()=>this.setMaterialProperty(e,t,n));return}this.stages.pathTracer?.materialData.updateMaterialProperty(e,t,n),[`emissive`,`emissiveIntensity`].includes(t)&&this._sdf&&this._uploadEmissivePayload(this._sdf.updateMaterialEmissive(e,t,n)),this.reset()}_uploadEmissivePayload(e){!e||!this.stages.pathTracer||(this.stages.pathTracer.setEmissiveTriangleData(e.rawData,e.emissiveCount,e.totalPower,e.bitTrailMap),e.lightBVHNodeData&&this.stages.pathTracer.setLightBVHData(e.lightBVHNodeData,e.lightBVHNodeCount))}_refreshEmissiveForVisibility(){let e=this._sdf?.instanceTable;if(!e)return;let t=new Set;for(let n=0;n<e.count;n++)e.isSet[n]&&!e.visible[n]&&t.add(e.sourceMesh[n]);this._uploadEmissivePayload(this._sdf.rebuildEmissiveForVisibility(t))}setEmissiveTriangleSampling(e){this._emissiveSamplingUserSet=!0,this.settings.set(`enableEmissiveTriangleSampling`,e)}hasEmissiveGeometry(){return(this._sdf?.emissiveTriangleBuilder?.emissiveTriangles?.length??this._sdf?.emissiveTriangleCount??0)>0}setMeshVisibility(e,t){this.stages.pathTracer?.updateMeshVisibility(e,t),this._refreshEmissiveForVisibility(),this.reset()}updateAllMeshVisibility(){this.stages.pathTracer?.updateAllMeshVisibility(),this._refreshEmissiveForVisibility(),this.reset()}getScene(){return this.meshScene||this.scene}setMeshVisibilityByUuid(e,t){let n=this.getScene()?.getObjectByProperty(`uuid`,e);if(!n)return null;let r=typeof t==`function`?!!t(n.visible):!!t;return n.visible=r,this.updateAllMeshVisibility(),r}setTextureTransform(e,t,n){this.stages.pathTracer?.materialData.updateTextureTransform(e,t,n),this.reset()}_displaySource(e){let t=this.pipeline?.context,n=t&&this.stages.compositor?.resolveLightSource(t);return n&&n.key!==`pathtracer:color`&&n.texture!==e.texture?{texture:n.texture,source:n.key.split(`:`)[0]}:(this._denoiserInUse()&&this._issues.record(Y.OUTPUT_SOURCE_FALLBACK,`renderToBuffer: 'display' was asked for, but no denoiser has published a picture — returned the raw accumulation`,{requested:`display`,read:`accumulation`}),null)}async _readDisplaySource(e,t,n){let r=this._displaySource(e);return r?{data:await this._readTexture(r.texture,t,n),source:r.source}:{data:await this.renderer.readRenderTargetPixelsAsync(e,0,0,t,n,0),source:`accumulation`}}_readbackPass(){return this._textureReadback??=new Cg(this.renderer)}_readTexture(e,t,n){return this._readbackPass().read(e,t,n)}async setTextureColorSpace(e,n){if(!e?.isTexture)throw Error(`setTextureColorSpace wants a three.js texture`);let r=e.userData??={};r.__rayzeeOriginalColorSpace===void 0&&(r.__rayzeeOriginalColorSpace=e.colorSpace);let i=r.__rayzeeOriginalColorSpace;if(delete r.ocioColorSpace,delete r.__rayzeeColorSpaceChoice,n==null)e.colorSpace=i,delete r.__rayzeeOriginalColorSpace;else if(n===`srgb`||n===`linear`)e.colorSpace=n===`srgb`?t.SRGBColorSpace:t.LinearSRGBColorSpace,r.__rayzeeColorSpaceChoice=n;else{if(!this.color?.hasConfig)throw Error(`"${n}" needs a colour config loaded`);r.ocioColorSpace=n,e.colorSpace=t.SRGBColorSpace}e.needsUpdate=!0,this.stages.pathTracer?.sdfs&&await this.rebuildMaterials()}setColorManagement(e){this.color?.dispose(),this.color=new e({issues:this._issues}),Ar(this.color),this.renderer&&this.color.attachRenderer(this.renderer)}async loadColorConfig(e={}){await this._leaveColorWorkingSpace();let t=uo(this.renderer?.toneMapping),n=await this.color.loadConfig(e);return this.color.workingSpaceAdopted&&await this.applyColorWorkingSpace(),(!(t?.source===`ocio`&&uo(this.renderer?.toneMapping)===t)||this.color.workingSpaceAdopted)&&this.reset(),n}async unloadColorConfig(){await this._leaveColorWorkingSpace(),this.color.unloadConfig(),this.reset()}async _leaveColorWorkingSpace(){this.color?.workingSpaceAdopted&&(this.color.setWorkingSpace(null),await this.applyColorWorkingSpace())}async applyColorWorkingSpace(){let e=this.environmentManager?.getEnvironmentTexture?.(),t=!1;if(e&&this.color?.hasConfig)try{t=this.color.convertTexturePixels(e)}catch(e){mv.warn(`environment colour conversion failed: ${e.message}`)}this.stages.pathTracer?.sdfs&&(await this.rebuildMaterials(),this._uploadEmissivePayload(this._sdf?.rebuildEmissiveColors?.()??null)),t&&await this.environmentManager?.buildEnvironmentCDF?.(),e?._isPhysicalSky&&await this.environmentManager.generateProceduralSkyTexture(),this.environmentManager?.refreshSun?.(),this.reset()}async rebuildMaterials(e){await this.ensureSceneResident(),await this.stages.pathTracer?.rebuildMaterials(e||this.meshScene),this.reset()}async _initRenderer(){if(L(e=>this.dispatchEvent(e)),typeof navigator>`u`||!navigator.gpu)throw Error("WebGPU is not available — outside a browser, install one as navigator.gpu (for Node, the `webgpu` package)");let e=await navigator.gpu.requestAdapter({powerPreference:`high-performance`});if(!e)throw Error(`Failed to get WebGPU adapter`);this.adapterInfo=vv(e),this.adapterInfo.isSoftware&&(this._issues.warn(Y.ADAPTER_SOFTWARE,`software GPU adapter "${this.adapterInfo.description||this.adapterInfo.vendor}" — renders are correct but orders of magnitude slower than hardware`,{...this.adapterInfo}),mv.warn(`software GPU adapter — check app.adapterInfo.isSoftware. ${this.adapterInfo.description}`));let n=e.limits,r={maxColorAttachmentBytesPerSample:128};for(let e of[`maxBufferSize`,`maxStorageBufferBindingSize`,`maxSampledTexturesPerShaderStage`,`maxStorageTexturesPerShaderStage`,`maxTextureArrayLayers`,`maxTextureDimension2D`,`maxComputeInvocationsPerWorkgroup`,`maxComputeWorkgroupStorageSize`,`maxComputeWorkgroupSizeX`,`maxComputeWorkgroupSizeY`,`maxComputeWorkgroupSizeZ`]){let t=n[e];t!==void 0&&(r[e]=t)}if(r.maxStorageBuffersPerShaderStage=Math.min(n.maxStorageBuffersPerShaderStage,10),this.renderer=new t.WebGPURenderer({canvas:this.canvas,alpha:!0,powerPreference:`high-performance`,requiredLimits:r}),await pv(this.renderer,this._headless),!this.renderer.backend?.isWebGPUBackend)throw Error(`WebGPU backend unavailable — three.js fell back to WebGL2, which cannot run the path tracer's compute kernels. Check GPU process flags and driver support.`);let a=this.renderer.backend?.device;a?.lost&&(this._gpuDevice=a,this._deviceLostHolder={app:this},gv(a,this._deviceLostHolder),a.onuncapturederror=e=>mv.error(`WebGPU uncaptured error:`,e.error)),t.RectAreaLightNode.setLTC(i.RectAreaLightTexturesLib.init()),this.renderer.outputColorSpace=t.SRGBColorSpace,this.renderer.toneMapping=ko,this.renderer.toneMappingExposure=1,this.renderer.setPixelRatio(1),this.color.attachRenderer(this.renderer)}_initScenes(){this.scene=new r.Scene,this.meshScene=new r.Scene,this._sceneHelpers=new A}_initAssetPipeline(){this._sdf=new rc({issues:this._issues,...this._maxSceneBytes===void 0?{}:{maxSceneBytes:this._maxSceneBytes}}),this.assetLoader=new tv(this.meshScene,this.camera,null,{issues:this._issues,areaLightIntensityScale:()=>this.settings.get(`areaLightIntensityScale`)}),this.assetLoader.setRenderer(this.renderer),this.assetLoader.createFloorPlane()}_initPipeline(){this._createStages();let{clientWidth:e,clientHeight:t}=this.canvas;this.pipeline=new bg(this.renderer,e||1,t||1,{issues:this._issues}),this.pipeline.addStage(this.stages.pathTracer);for(let e of this._extraStages)this.pipeline.addStage(e);this.pipeline.addStage(this.stages.compositor);let n=this.canvas.clientWidth||1,r=this.canvas.clientHeight||1;this._displayWidth=n,this._displayHeight=r,this._renderWidth=n,this._renderHeight=r,this.pipeline.setSize(n,r)}async _initManagers(){this.lightManager=new cv(this.scene,this._sceneHelpers,this.stages.pathTracer,{onReset:()=>this.reset(),onLightRemoved:e=>this._lightRemoved(e)}),this.environmentManager=this.stages.pathTracer.environment,this.environmentManager.issues=this._issues,this.stages.pathTracer.issues=this._issues,this.environmentManager.callbacks.onLightingChanged=()=>this.pipeline.eventBus.emit(`pipeline:lightingChanged`),this.environmentManager.callbacks.onReset=()=>this.reset()}_wireEvents(){this.settings.bind(this._settingsBindings()),this.renderer.toneMappingExposure=this.settings.get(`exposure`)??1,this.onResize(),this.resizeHandler=()=>this.onResize(),this._autoResize&&this._addTrackedListener(window,`resize`,this.resizeHandler),this._onAssetLoaded=async e=>{if(!this._loadingInProgress&&!(this._applyingSceneMetadata&&e.texture)){if(e.model)this._clearAppendedModels(),await this.loadSceneData({pendingEnvironment:this._beginSceneMetadataEnvironment()});else if(e.texture){let e=this.meshScene.environment;e&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(e),ue()}this.pauseRendering=!1,this.reset()}},this._addTrackedListener(this.assetLoader,`load`,this._onAssetLoaded),this.pipeline.eventBus.on(`pathtracer:compiling`,({compiling:e})=>this.dispatchEvent({type:P.SHADERS_COMPILING,compiling:e}))}_createStages(){this.stages.pathTracer=new og(this.renderer,this.scene,this.camera,{hostMemoryGB:this._hostMemoryGB,sortMaterials:this.settings.get(`wavefrontSortMaterials`)}),this._extraStages=this._createExtraStages(),this.stages.compositor=new sg(this.renderer,{saturation:this.settings.get(`saturation`)??G.saturation,pathTracer:this.stages.pathTracer,displaySources:this._displaySources()})}_reconcileCompletion(){let e=this.stages.pathTracer;if(!e)return;let t=this.completion.isLimitReached(e,this.settings.get(`renderLimitMode`),this.settings.get(`renderTimeLimit`));t&&!e.isComplete?e.isComplete=!0:!t&&e.isComplete&&(e.isComplete=!1,this.completion.resumeFromPause(),this._completionReopened(),this.dispatchEvent({type:P.RENDER_RESET}),this.wake())}_forwardEvents(e,t){if(e)for(let n of t)this._addTrackedListener(e,n,e=>this.dispatchEvent(e))}_createCamera(){let e=new av(60,this.canvas.clientWidth/this.canvas.clientHeight||1,.01,1e3);return e.position.set(0,0,5),e}_createExtraStages(){return[]}_displaySources(){return[]}_settingsBindings(){return{stages:this.stages,resetCallback:()=>this.reset(),reconcileCompletion:()=>this._reconcileCompletion(),applyExposure:e=>{this.renderer.toneMappingExposure=e}}}_beginFrame(){}_beforeTrace(){}_holdTrace(){return!1}_afterTrace(){}_renderCompleted(){}_renderHelperOverlay(){this.scene.updateMatrixWorld()}_beforeReset(){}_afterReset(){}_dropDisplay(){}_releaseSceneState(){}_modelReplaced(){}_modelAnnounced(){}_sceneRebuilt(){}_sceneBoundsChanged(){}_notePlacementsMoving(){}_lightRemoved(){}_renderSizeChanged(){}_completionReopened(){}async _finalDenoise(){return!1}_denoiserInUse(){return!1}_displayCanvas(){return null}_registerVRAM(){}_canvasResources(){return[]}_deterministicSnapshot(){return null}_setDeterministicExtras(){}_disposeExtensions(){}},bv=65504,xv=6e4,Sv=.01,Cv={low:{temporalAlpha:.1,gradientStrength:.8,gradientSigmaScale:2.5,gradientNoiseFloor:.05,atrousIterations:3,phiColor:1,phiNormal:64,phiDepth:.1,phiLuminance:6,maxAccumFrames:16,varianceBoost:.5},medium:{temporalAlpha:.03,gradientStrength:1,gradientSigmaScale:2.5,gradientNoiseFloor:.05,atrousIterations:4,phiColor:.5,phiNormal:128,phiDepth:.05,phiLuminance:4,maxAccumFrames:64,varianceBoost:1},high:{temporalAlpha:0,gradientStrength:1,gradientSigmaScale:2.5,gradientNoiseFloor:.05,atrousIterations:6,phiColor:.3,phiNormal:256,phiDepth:.02,phiLuminance:2,maxAccumFrames:128,varianceBoost:1.5}},wv=3,Tv=.1,Ev={maxAccumulatedFrameNum:30,maxFastAccumulatedFrameNum:6,maxStabilizedFrameNum:63,historyFixFrameNum:3,historyFixBasePixelStride:14,prepassBlurRadius:30,minBlurRadius:1,maxBlurRadius:30,lobeAngleFraction:.15,roughnessFraction:.15,planeDistanceSensitivity:.02,minHitDistanceWeight:.1,fastHistoryClampingSigmaScale:2,fireflySuppressorMinRelativeScale:2,enableAntiFirefly:!0,antilagLuminanceSigmaScale:2,antilagLuminanceSensitivity:3,disocclusionThreshold:.01,convergenceS:1,convergenceB:.2,convergenceP:.8,lobeVolumePercent:.1,handoverFrames:0},Dv=[`maxAccumulatedFrameNum`,`maxFastAccumulatedFrameNum`,`maxStabilizedFrameNum`,`historyFixFrameNum`,`prepassBlurRadius`,`maxBlurRadius`,`enableAntiFirefly`],Ov={low:{maxAccumulatedFrameNum:16,maxFastAccumulatedFrameNum:4,maxStabilizedFrameNum:16,historyFixFrameNum:2,prepassBlurRadius:0,maxBlurRadius:20,enableAntiFirefly:!1},medium:{},high:{maxAccumulatedFrameNum:45,maxFastAccumulatedFrameNum:8,historyFixFrameNum:4,prepassBlurRadius:40,maxBlurRadius:40}},kv=Cv.medium,Av={denoiserStrategy:`none`,filterStrength:1,edgeAtrousIterations:5,edgePhiLuminance:4,edgePhiNormal:64,edgePhiDepth:.1,enableOIDN:!1,oidnQuality:`fast`,continuousDenoise:!1,continuousDenoiseInterval:8,oidnTemporalHistory:!0,enableUpscaler:!1,upscalerScale:2,upscalerQuality:`fast`,upscalerHdr:!0,enableASVGF:!1,asvgfQualityPreset:`medium`,asvgfTemporalAlpha:kv.temporalAlpha,asvgfAtrousIterations:kv.atrousIterations,asvgfPhiColor:kv.phiColor,asvgfPhiNormal:kv.phiNormal,asvgfPhiDepth:kv.phiDepth,asvgfPhiLuminance:kv.phiLuminance,asvgfVarianceBoost:kv.varianceBoost,asvgfMaxAccumFrames:kv.maxAccumFrames,asvgfGradientStrength:kv.gradientStrength,asvgfGradientSigmaScale:kv.gradientSigmaScale,asvgfGradientNoiseFloor:kv.gradientNoiseFloor,asvgfDebugMode:0,showAsvgfHeatmap:!1,nrdQualityPreset:`medium`,nrdDebugMode:0};Dc(),hl();var jv=class extends M{constructor(e,i={}){super(`NormalDepth`,{...i,executionMode:j.ALWAYS}),this.renderer=e,this.pathTracer=i.pathTracer,this._dirty=!0,this.cameraWorldMatrix=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraProjectionMatrixInverse=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraRay=Xu(),this.resolutionWidth=(0,n.uniform)(i.width||1),this.resolutionHeight=(0,n.uniform)(i.height||1);let a=i.width||1,o=i.height||1;this._outputStorageTex=new t.StorageTexture(U,U),this._outputStorageTex.type=r.HalfFloatType,this._outputStorageTex.format=r.RGBAFormat,this._outputStorageTex.minFilter=r.NearestFilter,this._outputStorageTex.magFilter=r.NearestFilter,this._shadingStorageTex=new t.StorageTexture(U,U),this._shadingStorageTex.type=r.HalfFloatType,this._shadingStorageTex.format=r.RGBAFormat,this._shadingStorageTex.minFilter=r.NearestFilter,this._shadingStorageTex.magFilter=r.NearestFilter,this._shadingRT=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._leafStorageTex=null,this._leafRT=null,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0));let s={type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this._rtA=new t.RenderTarget(a,o,s),this._rtB=new t.RenderTarget(a,o,s),this._currentIdx=0,this._hasHistory=!1,this._dispatchX=Math.ceil(a/8),this._dispatchY=Math.ceil(o/8),this._triStorageNode=null,this._bvhStorageNode=null,this._matStorageNode=null,this._lastTriAttr=null,this._lastBvhAttr=null,this._lastMatAttr=null,this._computeNode=null,this._computeBuilt=!1,this._linearBuckets=null}setupEventListeners(){this.on(`camera:moved`,()=>{this._dirty=!0}),this.on(`pipeline:reset`,()=>{this._dirty=!0})}_syncStorageBuffers(){let e=this.pathTracer;if(!e)return!1;let t=e.materialData?.materialStorageAttr,r=e.triangleGeoAttr&&e.triangleGeoAttr!==this._lastTriAttr,i=e.bvhStorageAttr&&e.bvhStorageAttr!==this._lastBvhAttr,a=t&&t!==this._lastMatAttr;return(r||i||a)&&(this._computeNode?.dispose?.(),this._computeNode=null,this._computeBuilt=!1,this._triStorageNode=null,this._bvhStorageNode=null,this._matStorageNode=null,this._dirty=!0,this._hasHistory=!1),e.triangleGeoAttr&&!this._triStorageNode&&(this._triStorageNode={geo:(0,n.storage)(e.triangleGeoAttr,`uvec4`,e.triangleGeoAttr.count).toReadOnly(),shade:(0,n.storage)(e.triangleShadeAttr,`uvec4`,e.triangleShadeAttr.count).toReadOnly()}),e.bvhStorageAttr&&!this._bvhStorageNode&&(this._bvhStorageNode=(0,n.storage)(e.bvhStorageAttr,`vec4`,e.bvhStorageAttr.count).toReadOnly()),t&&!this._matStorageNode&&(this._matStorageNode=(0,n.storage)(t,`vec4`,t.count).toReadOnly()),this._linearBuckets&&nf(this._linearBuckets,e.materialData?.linearBuckets),this._lastTriAttr=e.triangleGeoAttr||this._lastTriAttr,this._lastBvhAttr=e.bvhStorageAttr||this._lastBvhAttr,this._lastMatAttr=t||this._lastMatAttr,!!(this._triStorageNode&&this._bvhStorageNode&&this._matStorageNode)}_buildCompute(){let e=this._triStorageNode,t=this._bvhStorageNode,r=this._matStorageNode;this._linearBuckets=tf(this.pathTracer?.materialData?.linearBuckets);let i={srgbBuckets:tf(null),linearBuckets:this._linearBuckets,shadowAlbedoMaps:null,goboMaps:null,iesProfiles:null,alphaShadows:null},a=this.cameraWorldMatrix,o=this.cameraProjectionMatrixInverse,s=this.resolutionWidth,c=this.resolutionHeight,l=this._outputStorageTex,u=this._shadingStorageTex,d=this._leafStorageTex;this._computeNode=zn((0,n.Fn)(([i,a])=>{let o=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(o.lessThan((0,n.int)(s)).and(f.lessThan((0,n.int)(c))),()=>{let p=dc(Zu((0,n.vec2)((0,n.float)(o).add(.5).div(s),(0,n.float)(f).add(.5).div(c)),i,a,this.cameraRay)),m=gc.wrap(Sd(p,t,e)),h=m.normal.mul(.5).add(.5),g=(0,n.min)(m.dst,(0,n.float)(65504)),_=m.didHit.select((0,n.vec4)(h,g),(0,n.vec4)(0,0,0,(0,n.float)(bv)));(0,n.textureStore)(l,(0,n.uvec2)((0,n.uint)(o),(0,n.uint)(f)),_).toWriteOnly(),d&&(0,n.textureStore)(d,(0,n.uvec2)((0,n.uint)(o),(0,n.uint)(f)),(0,n.uvec4)((0,n.uint)(m.instanceLeaf.add(1)),0,0,0)).toWriteOnly();let v=m.normal.toVar(),y=(0,n.float)(1).toVar();(0,n.If)(m.didHit,()=>{let i=fc.wrap(ol(m.materialIndex,r)).toVar(),a=Tc.wrap(cf(m.uv,i)).toVar(),o=(0,n.vec4)(0).toVar();(0,n.If)(i.normalMapIndex.greaterThanEqual((0,n.int)(0)),()=>{o.assign(ff(e,m.triangleIndex,m.normal,i.normalTransform,t,m.instanceLeaf))});let s=pf(m.normal,i,a,o).toVar();v.assign(mf(s,i,a)),y.assign(uf(i,a).y.clamp(.05,1))});let b=m.didHit.select((0,n.vec4)(v.mul(.5).add(.5),y),(0,n.vec4)(0,0,0,1));(0,n.textureStore)(u,(0,n.uvec2)((0,n.uint)(o),(0,n.uint)(f)),b).toWriteOnly()})})(a,o),i).compute([this._dispatchX,this._dispatchY,1],[8,8,1]),this._computeBuilt=!0}render(e){if(!this.enabled||!this._syncStorageBuffers())return;this._computeBuilt||this._buildCompute();let t=this.pathTracer;if(t&&(this.cameraWorldMatrix.value.copy(t.uniforms.get(`cameraWorldMatrix`).value),this.cameraProjectionMatrixInverse.value.copy(t.uniforms.get(`cameraProjectionMatrixInverse`).value),this.cameraRay.sync(t.uniforms)),!this._dirty&&this._hasHistory){let t=this._currentIdx===0?this._rtA:this._rtB;e.setTexture(`pathtracer:normalDepth`,t.texture),e.setTexture(`pathtracer:prevNormalDepth`,t.texture),e.setTexture(`pathtracer:shadingNormal`,this._shadingRT.texture),this._publishLeaf(e);return}let n=e.getTexture(`pathtracer:color`);if(n&&n.image){let e=n.image;e.width>0&&e.height>0&&(e.width!==this._rtA.width||e.height!==this._rtA.height)&&this.setSize(e.width,e.height)}this._hasHistory&&(this._currentIdx=1-this._currentIdx);let r=this._currentIdx===0?this._rtA:this._rtB,i=this._currentIdx===0?this._rtB:this._rtA;this.renderer.compute(this._computeNode),this._srcRegion.max.set(r.width,r.height),this.renderer.copyTextureToTexture(this._outputStorageTex,r.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._shadingStorageTex,this._shadingRT.texture,this._srcRegion),this._leafRT&&this.renderer.copyTextureToTexture(this._leafStorageTex,this._leafRT.texture,this._srcRegion),this._hasHistory||=(this.renderer.copyTextureToTexture(this._outputStorageTex,i.texture,this._srcRegion),!0),e.setTexture(`pathtracer:normalDepth`,r.texture),e.setTexture(`pathtracer:prevNormalDepth`,i.texture),e.setTexture(`pathtracer:shadingNormal`,this._shadingRT.texture),this._publishLeaf(e),this._dirty=!1}releaseGPUMemory(){this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose(),this._leafStorageTex?.dispose(),this.reset(),this._hasHistory=!1}reset(){this._dirty=!0}setSize(e,t){this._rtA.setSize(e,t),this._rtA.texture.needsUpdate=!0,this._rtB.setSize(e,t),this._rtB.texture.needsUpdate=!0,this._shadingRT.setSize(e,t),this._shadingRT.texture.needsUpdate=!0,this._leafRT&&(this._leafRT.setSize(e,t),this._leafRT.texture.needsUpdate=!0),this._hasHistory=!1,this.resolutionWidth.value=e,this.resolutionHeight.value=t,this._dispatchX=Math.ceil(e/8),this._dispatchY=Math.ceil(t/8),this._computeNode&&(this._computeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]),this._dirty=!0}reallocateReservedStorage(){this._computeNode?.dispose(),this._computeNode=null,this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose();let e=()=>{let e=new t.StorageTexture(U,U);return e.type=r.HalfFloatType,e.format=r.RGBAFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e};this._outputStorageTex=e(),this._shadingStorageTex=e(),this._leafStorageTex&&=(this._leafStorageTex.dispose(),this._makeLeafStorage()),this._computeBuilt=!1}setInstanceLeafOutput(e){e=!!e,e!==!!this._leafStorageTex&&(this._computeNode?.dispose(),this._computeNode=null,this._computeBuilt=!1,this._dirty=!0,e?(this._leafStorageTex=this._makeLeafStorage(),this._leafRT=new t.RenderTarget(this._rtA.width,this._rtA.height,{type:r.UnsignedIntType,format:r.RedIntegerFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1})):(this._leafStorageTex.dispose(),this._leafRT.dispose(),this._leafStorageTex=null,this._leafRT=null))}_publishLeaf(e){this._leafRT?e.setTexture(`pathtracer:instanceLeaf`,this._leafRT.texture):e.getTexture(`pathtracer:instanceLeaf`)&&e.removeTexture(`pathtracer:instanceLeaf`)}_makeLeafStorage(){let e=new t.StorageTexture(U,U);return e.type=r.UnsignedIntType,e.format=r.RedIntegerFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e}dispose(){this._computeNode?.dispose(),this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose(),this._shadingRT?.dispose(),this._leafStorageTex?.dispose(),this._leafRT?.dispose(),this._rtA?.dispose(),this._rtB?.dispose()}},Mv=class extends M{constructor(e,i,a={}){super(`MotionVector`,{...a,executionMode:j.ALWAYS}),this.renderer=e,this.camera=i,this.pathTracer=a.pathTracer||null;let o=a.width||1,s=a.height||1;this.prevViewProjectionMatrix=new r.Matrix4,this.currentViewProjectionMatrix=new r.Matrix4,this.matricesInitialized=!1,this.isFirstFrame=!0,this.frameCount=0,this.cameraWorldMatrix=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraProjectionMatrixInverse=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraRay=Xu(),this.prevVP=(0,n.uniform)(new r.Matrix4,`mat4`),this.isFirstFrameU=(0,n.uniform)(1),this.deltaTime=(0,n.uniform)(1/60),this.velocityScale=(0,n.uniform)(1),this.resolutionWidth=(0,n.uniform)(o),this.resolutionHeight=(0,n.uniform)(s),this._normalDepthTexNode=new t.TextureNode,this._screenSpaceStorageTex=new t.StorageTexture(U,U),this._screenSpaceStorageTex.type=r.HalfFloatType,this._screenSpaceStorageTex.format=r.RGBAFormat,this._screenSpaceStorageTex.minFilter=r.NearestFilter,this._screenSpaceStorageTex.magFilter=r.NearestFilter,this._worldSpaceStorageTex=new t.StorageTexture(U,U),this._worldSpaceStorageTex.type=r.HalfFloatType,this._worldSpaceStorageTex.format=r.RGBAFormat,this._worldSpaceStorageTex.minFilter=r.NearestFilter,this._worldSpaceStorageTex.magFilter=r.NearestFilter,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0));let c={type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this.screenSpaceTarget=new t.RenderTarget(o,s,c),this.worldSpaceTarget=new t.RenderTarget(o,s,c),this._dispatchX=Math.ceil(o/16),this._dispatchY=Math.ceil(s/16),this._buildScreenSpaceCompute(),this._buildWorldSpaceCompute()}_buildScreenSpaceCompute(){let e=this._normalDepthTexNode,t=this.cameraWorldMatrix,r=this.cameraProjectionMatrixInverse,i=this.prevVP,a=this.resolutionWidth,o=this.resolutionHeight,s=this._screenSpaceStorageTex;this._screenSpaceComputeNode=(0,n.Fn)(([t,r])=>{let c=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),l=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(c.lessThan((0,n.int)(a)).and(l.lessThan((0,n.int)(o))),()=>{let u=(0,n.textureLoad)(e,(0,n.ivec2)(c,l)).w,d=(0,n.vec2)((0,n.float)(c).add(.5).div(a),(0,n.float)(l).add(.5).div(o)),f=(0,n.vec4)(0,0,u,1).toVar();(0,n.If)(u.lessThan((0,n.float)(6e4)),()=>{let e=Qu(d,u,t,r,this.cameraRay),a=i.mul((0,n.vec4)(e,1)),o=a.xy.div(a.w),s=(0,n.vec2)(o.x.mul(.5).add(.5),o.y.mul(-.5).add(.5)),c=d.sub(s),l=s.x.greaterThanEqual(0).and(s.x.lessThanEqual(1)).and(s.y.greaterThanEqual(0)).and(s.y.lessThanEqual(1));f.assign(l.select((0,n.vec4)(c,u,1),(0,n.vec4)((0,n.float)(1e3),(0,n.float)(1e3),u,0)))}),(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(c),(0,n.uint)(l)),f).toWriteOnly()})})(t,r).compute([this._dispatchX,this._dispatchY,1],[16,16,1])}_buildWorldSpaceCompute(){let e=this._normalDepthTexNode,t=this.cameraWorldMatrix,r=this.cameraProjectionMatrixInverse,i=this.prevVP,a=this.isFirstFrameU,o=this.deltaTime,s=this.velocityScale,c=this.resolutionWidth,l=this.resolutionHeight,u=this._worldSpaceStorageTex;this._worldSpaceComputeNode=(0,n.Fn)(([t,r])=>{let d=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(c)).and(f.lessThan((0,n.int)(l))),()=>{let p=(0,n.textureLoad)(e,(0,n.ivec2)(d,f)).w,m=(0,n.vec4)(0,0,0,0).toVar();(0,n.If)(a.lessThan(.5).and(p.lessThan((0,n.float)(6e4))),()=>{let e=(0,n.vec2)((0,n.float)(d).add(.5).div(c),(0,n.float)(f).add(.5).div(l)),a=Qu(e,p,t,r,this.cameraRay),u=i.mul((0,n.vec4)(a,1)),h=u.xy.div(u.w),g=(0,n.vec2)(h.x.mul(.5).add(.5),h.y.mul(-.5).add(.5)),_=g.x.greaterThanEqual(0).and(g.x.lessThanEqual(1)).and(g.y.greaterThanEqual(0)).and(g.y.lessThanEqual(1)),v=e.sub(g),y=(0,n.vec3)(v.x.div(o).mul(s),v.y.div(o).mul(s),0);m.assign(_.select((0,n.vec4)(y,1),(0,n.vec4)(0,0,0,.5)))}),(0,n.textureStore)(u,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),m).toWriteOnly()})})(t,r).compute([this._dispatchX,this._dispatchY,1],[16,16,1])}_updateCameraMatrices(){let e=this.pathTracer,t,n,r,i;if(e&&e.uniforms)this.cameraRay.sync(e.uniforms),t=e.uniforms.get(`cameraWorldMatrix`).value,n=e.uniforms.get(`cameraViewMatrix`).value,r=e.uniforms.get(`cameraProjectionMatrix`).value,i=e.uniforms.get(`cameraProjectionMatrixInverse`).value;else{let e=this.camera;if(!e)return;t=e.matrixWorld,n=e.matrixWorldInverse,r=e.projectionMatrix,i=e.projectionMatrixInverse}this.matricesInitialized?this.prevViewProjectionMatrix.copy(this.currentViewProjectionMatrix):(this.currentViewProjectionMatrix.multiplyMatrices(r,n),this.prevViewProjectionMatrix.copy(this.currentViewProjectionMatrix),this.matricesInitialized=!0),this.currentViewProjectionMatrix.multiplyMatrices(r,n),this.cameraWorldMatrix.value.copy(t),this.cameraProjectionMatrixInverse.value.copy(i),this.prevVP.value.copy(this.prevViewProjectionMatrix)}setupEventListeners(){this.on(`pipeline:reset`,()=>{this.reset()})}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:normalDepth`);if(!t)return;this._updateCameraMatrices(),this.isFirstFrameU.value=+!!this.isFirstFrame,this.frameCount++;let n=t.image;n&&n.width>0&&n.height>0&&(n.width!==this.screenSpaceTarget.width||n.height!==this.screenSpaceTarget.height)&&this.setSize(n.width,n.height),this._normalDepthTexNode.value=t,this.renderer.compute(this._screenSpaceComputeNode),this.renderer.compute(this._worldSpaceComputeNode),this._srcRegion.max.set(this.screenSpaceTarget.width,this.screenSpaceTarget.height),this.renderer.copyTextureToTexture(this._screenSpaceStorageTex,this.screenSpaceTarget.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._worldSpaceStorageTex,this.worldSpaceTarget.texture,this._srcRegion),e.setTexture(`motionVector:screenSpace`,this.screenSpaceTarget.texture),e.setTexture(`motionVector:worldSpace`,this.worldSpaceTarget.texture),e.setTexture(`motionVector:motion`,this.screenSpaceTarget.texture),this.emit(`motionvector:computed`,{frame:this.frameCount,isFirstFrame:this.isFirstFrame}),this.isFirstFrame=!1}releaseGPUMemory(){this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose(),this.reset()}reset(){this.matricesInitialized||(this.isFirstFrame=!0),this.frameCount=0}setSize(e,t){this.screenSpaceTarget.setSize(e,t),this.screenSpaceTarget.texture.needsUpdate=!0,this.worldSpaceTarget.setSize(e,t),this.worldSpaceTarget.texture.needsUpdate=!0,this.resolutionWidth.value=e,this.resolutionHeight.value=t,this._dispatchX=Math.ceil(e/16),this._dispatchY=Math.ceil(t/16),this._screenSpaceComputeNode&&(this._screenSpaceComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]),this._worldSpaceComputeNode&&(this._worldSpaceComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1])}setVelocityScale(e){this.velocityScale.value=e}setDeltaTime(e){this.deltaTime.value=e}reallocateReservedStorage(){this._screenSpaceComputeNode?.dispose(),this._worldSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose();let e=()=>{let e=new t.StorageTexture(U,U);return e.type=r.HalfFloatType,e.format=r.RGBAFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e};this._screenSpaceStorageTex=e(),this._worldSpaceStorageTex=e(),this._buildScreenSpaceCompute(),this._buildWorldSpaceCompute()}dispose(){this._screenSpaceComputeNode?.dispose(),this._worldSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose(),this.screenSpaceTarget?.dispose(),this.worldSpaceTarget?.dispose(),this._normalDepthTexNode?.dispose()}};hl();var Nv=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,1e7),Pv=e=>(0,n.vec3)(Nv(e.x),Nv(e.y),Nv(e.z)),Fv=class extends M{constructor(e,i={}){super(`ASVGF`,{...i,executionMode:j.PER_CYCLE}),this.renderer=e,this.temporalAlpha=(0,n.uniform)(i.temporalAlpha??Cv.medium.temporalAlpha),this.gradientStrength=(0,n.uniform)(i.gradientStrength??Cv.medium.gradientStrength),this.gradientSigmaScale=(0,n.uniform)(i.gradientSigmaScale??Cv.medium.gradientSigmaScale),this.gradientNoiseFloor=(0,n.uniform)(i.gradientNoiseFloor??Cv.medium.gradientNoiseFloor),this.maxAccumFrames=(0,n.uniform)(i.maxAccumFrames??Cv.medium.maxAccumFrames),this.resW=(0,n.uniform)(i.width||1),this.resH=(0,n.uniform)(i.height||1),this.temporalEnabledU=(0,n.uniform)(1),this.forceResetU=(0,n.uniform)(0),this._colorTexNode=new t.TextureNode,this._albedoTexNode=new t.TextureNode,this._motionTexNode=new t.TextureNode,this._normalDepthTexNode=new t.TextureNode,this._prevNormalDepthTexNode=new t.TextureNode,this._readTemporalTexNode=new t.TextureNode,this._gradientReadTexNode=new t.TextureNode;let a=i.width||1,o=i.height||1;this._temporalTexA=new t.StorageTexture(U,U),this._temporalTexA.type=r.FloatType,this._temporalTexA.format=r.RGBAFormat,this._temporalTexA.minFilter=r.LinearFilter,this._temporalTexA.magFilter=r.LinearFilter,this._temporalTexB=new t.StorageTexture(U,U),this._temporalTexB.type=r.FloatType,this._temporalTexB.format=r.RGBAFormat,this._temporalTexB.minFilter=r.LinearFilter,this._temporalTexB.magFilter=r.LinearFilter,this._outputModulatedTex=new t.StorageTexture(U,U),this._outputModulatedTex.type=r.FloatType,this._outputModulatedTex.format=r.RGBAFormat,this._outputModulatedTex.minFilter=r.LinearFilter,this._outputModulatedTex.magFilter=r.LinearFilter,this._gradientStorageTex=new t.StorageTexture(U,U),this._gradientStorageTex.type=r.HalfFloatType,this._gradientStorageTex.format=r.RGBAFormat,this._gradientStorageTex.minFilter=r.LinearFilter,this._gradientStorageTex.magFilter=r.LinearFilter,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),this._demodulatedRT=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._outputRT=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._gradientRT=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this.currentMoments=0,this._compiled=!1,this._needsWarmReset=!1,this._dispatchX=Math.ceil(a/8),this._dispatchY=Math.ceil(o/8),this._buildGradientCompute(),this._buildTemporalCompute(),this.showHeatmap=!1,this.debugMode=(0,n.uniform)(0,`int`),this._heatmapStorageTex=new t.StorageTexture(U,U),this._heatmapStorageTex.type=r.FloatType,this._heatmapStorageTex.format=r.RGBAFormat,this._heatmapStorageTex.minFilter=r.NearestFilter,this._heatmapStorageTex.magFilter=r.NearestFilter,this.heatmapTarget=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._heatmapRawColorTexNode=new t.TextureNode,this._heatmapColorTexNode=new t.TextureNode,this._heatmapTemporalTexNode=new t.TextureNode,this._heatmapNDTexNode=new t.TextureNode,this._heatmapMotionTexNode=new t.TextureNode,this._heatmapGradientTexNode=new t.TextureNode,this._buildHeatmapCompute()}_buildGradientCompute(){let e=this._colorTexNode,t=this._albedoTexNode,r=this._motionTexNode,i=this._readTemporalTexNode,a=this.gradientNoiseFloor,o=this.gradientSigmaScale,s=this._gradientStorageTex,c=this.resW,l=this.resH,u=(0,n.workgroupArray)(`float`,144),d=(0,n.workgroupArray)(`float`,144);this._gradientNode=(0,n.Fn)(()=>{let f=n.localId.x,p=n.localId.y,m=p.mul(8).add(f),h=(0,n.int)(n.workgroupId.x).mul(8).sub(2).toVar(),g=(0,n.int)(n.workgroupId.y).mul(8).sub(2).toVar(),_=a=>{let o=a.mod((0,n.uint)(12)),s=a.div((0,n.uint)(12)),f=h.add((0,n.int)(o)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),p=g.add((0,n.int)(s)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),m=(0,n.textureLoad)(e,(0,n.ivec2)(f,p)).xyz,_=(0,n.textureLoad)(t,(0,n.ivec2)(f,p)).xyz,v=Kc(Pv(m.div((0,n.max)(_,(0,n.vec3)(Sv))))).toVar();u.element(a).assign(v);let y=(0,n.textureLoad)(r,(0,n.ivec2)(f,p)),b=(0,n.float)(f).sub(y.x.mul(c)),x=(0,n.float)(p).sub(y.y.mul(l)),S=(0,n.int)(b.add(.5)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),C=(0,n.int)(x.add(.5)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),w=y.w.greaterThan(.5),T=(0,n.textureLoad)(i,(0,n.ivec2)(S,C)).xyz,E=w.select(Kc(T),v);d.element(a).assign(E)};_(m);let v=m.add((0,n.uint)(64));(0,n.If)(v.lessThan((0,n.uint)(144)),()=>{_(v)});let y=m.add((0,n.uint)(128));(0,n.If)(y.lessThan((0,n.uint)(144)),()=>{_(y)}),(0,n.workgroupBarrier)();let b=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(f)),x=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(p));(0,n.If)(b.lessThan((0,n.int)(c)).and(x.lessThan((0,n.int)(l))),()=>{let e=(0,n.float)(0).toVar(),t=(0,n.float)(0).toVar();for(let r=-2;r<=2;r++)for(let i=-2;i<=2;i++){let a=p.add((0,n.uint)(2+r)).mul((0,n.uint)(12)).add(f.add((0,n.uint)(2+i))),o=u.element(a);e.addAssign(o),t.addAssign(o.mul(o))}let m=e.div(25),h=(0,n.sqrt)((0,n.max)(t.div(25).sub(m.mul(m)),(0,n.float)(0))).mul(o).toVar(),g=(0,n.float)(0).toVar();for(let e=-2;e<=2;e++)for(let t=-2;t<=2;t++){let r=p.add((0,n.uint)(2+e)).mul((0,n.uint)(12)).add(f.add((0,n.uint)(2+t))),i=u.element(r),o=d.element(r),s=(0,n.max)((0,n.max)((0,n.abs)(i.sub(o)).sub(h),(0,n.float)(0)).div((0,n.max)((0,n.max)(i,o),(0,n.float)(.001))).sub(a),(0,n.float)(0)).div((0,n.max)((0,n.float)(1).sub(a),(0,n.float)(1e-4)));g.addAssign(s.mul(s))}let _=g.div(25).clamp(0,1).toVar(),v=(0,n.textureLoad)(r,(0,n.ivec2)(b,x)),y=(0,n.int)((0,n.float)(b).sub(v.x.mul(c)).add(.5)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),S=(0,n.int)((0,n.float)(x).sub(v.y.mul(l)).add(.5)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),C=v.w.greaterThan(.5).select((0,n.textureLoad)(i,(0,n.ivec2)(y,S)).w,(0,n.float)(0)).div(4).clamp(0,1),w=_.mul(C);(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(b),(0,n.uint)(x)),(0,n.vec4)(w,_,h,1)).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}_buildTemporalCompute(){this._temporalNodeA=this._buildTemporalForDirection(this._temporalTexA),this._temporalNodeB=this._buildTemporalForDirection(this._temporalTexB)}_buildTemporalForDirection(e){let t=this._colorTexNode,r=this._albedoTexNode,i=this._motionTexNode,a=this._normalDepthTexNode,o=this._prevNormalDepthTexNode,s=this._readTemporalTexNode,c=this._gradientReadTexNode,l=this._outputModulatedTex,u=this.maxAccumFrames,d=this.temporalAlpha,f=this.gradientStrength,p=this.temporalEnabledU,m=this.forceResetU,h=this.resW,g=this.resH;return(0,n.Fn)(()=>{let _=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),v=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(_.lessThan((0,n.int)(h)).and(v.lessThan((0,n.int)(g))),()=>{let y=(0,n.ivec2)(_,v),b=(0,n.textureLoad)(t,y),x=b.xyz,S=b.w,C=(0,n.textureLoad)(r,y).xyz,w=(0,n.max)(C,(0,n.vec3)(Sv)),T=Pv(x.div(w)),E=(0,n.vec4)(T,1).toVar(),D=(0,n.vec4)(x,S).toVar();(0,n.If)(p.greaterThan(.5).and(m.lessThan(.5)),()=>{let e=(0,n.textureLoad)(i,y),t=e.w.greaterThan(.5),r=(0,n.float)(_).sub(e.x.mul(h)),l=(0,n.float)(v).sub(e.y.mul(g)),p=r.greaterThanEqual(0).and(r.lessThan((0,n.float)(h))).and(l.greaterThanEqual(0)).and(l.lessThan((0,n.float)(g)));(0,n.If)(t.and(p),()=>{let e=(0,n.textureLoad)(a,y),t=e.xyz.mul(2).sub(1),i=e.w,p=(0,n.int)(r),m=(0,n.int)(l),_=p.add((0,n.int)(1)),v=m.add((0,n.int)(1)),b=r.sub((0,n.float)(p)),x=l.sub((0,n.float)(m)),C=p.clamp((0,n.int)(0),(0,n.int)(h).sub(1)),O=_.clamp((0,n.int)(0),(0,n.int)(h).sub(1)),k=m.clamp((0,n.int)(0),(0,n.int)(g).sub(1)),A=v.clamp((0,n.int)(0),(0,n.int)(g).sub(1)),j=(0,n.float)(1).sub(b).mul((0,n.float)(1).sub(x)),M=b.mul((0,n.float)(1).sub(x)),N=(0,n.float)(1).sub(b).mul(x),P=b.mul(x),F=(e,r,a)=>{let s=(0,n.textureLoad)(o,(0,n.ivec2)(e,r)),c=s.xyz.mul(2).sub(1),l=s.w,u=(0,n.pow)((0,n.dot)(t,c).clamp(0,1),(0,n.float)(16)),d=(0,n.exp)((0,n.abs)(i.sub(l)).div((0,n.max)(i,(0,n.float)(.001))).div((0,n.float)(.05)).negate());return a.mul(u).mul(d)},I=F(C,k,j),L=F(O,k,M),ee=F(C,A,N),te=F(O,A,P),R=I.add(L).add(ee).add(te);(0,n.If)(R.greaterThan((0,n.float)(.01)),()=>{let e=(0,n.textureLoad)(s,(0,n.ivec2)(C,k)),t=(0,n.textureLoad)(s,(0,n.ivec2)(O,k)),r=(0,n.textureLoad)(s,(0,n.ivec2)(C,A)),i=(0,n.textureLoad)(s,(0,n.ivec2)(O,A)),a=(0,n.float)(1).div(R),o=e.xyz.mul(I).add(t.xyz.mul(L)).add(r.xyz.mul(ee)).add(i.xyz.mul(te)).mul(a),l=e.w.mul(I).add(t.w.mul(L)).add(r.w.mul(ee)).add(i.w.mul(te)).mul(a),p=(0,n.textureLoad)(c,y).x.mul(f).clamp(0,1),m=Pv((0,n.mix)(o,T,(0,n.mix)((0,n.max)((0,n.float)(1).div(l.add(1)),d),(0,n.float)(1),p))),h=(0,n.min)(l.add(1),u);E.assign((0,n.vec4)(m,h)),D.assign((0,n.vec4)(m.mul(w),S))})})}),(0,n.textureStore)(e,(0,n.uvec2)((0,n.uint)(_),(0,n.uint)(v)),E).toWriteOnly(),(0,n.textureStore)(l,(0,n.uvec2)((0,n.uint)(_),(0,n.uint)(v)),D).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}_buildHeatmapCompute(){let e=this._heatmapRawColorTexNode,t=this._heatmapColorTexNode,r=this._heatmapTemporalTexNode,i=this._heatmapNDTexNode,a=this._heatmapMotionTexNode,o=this._heatmapGradientTexNode,s=this._heatmapStorageTex,c=this.debugMode,l=this.resW,u=this.resH;this._heatmapComputeNode=(0,n.Fn)(()=>{let d=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(l)).and(f.lessThan((0,n.int)(u))),()=>{let p=(0,n.ivec2)(d,f),m=(0,n.vec4)(0,0,0,1).toVar();(0,n.If)(c.equal((0,n.int)(0)),()=>{let e=(0,n.textureLoad)(t,p).xyz;m.assign((0,n.vec4)(e,1))}).ElseIf(c.equal((0,n.int)(1)),()=>{let t=(0,n.float)(0).toVar(),r=(0,n.float)(0).toVar();for(let i=-1;i<=1;i++)for(let a=-1;a<=1;a++){let o=(0,n.textureLoad)(e,(0,n.ivec2)(d.add(a).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),f.add(i).clamp((0,n.int)(0),(0,n.int)(u).sub(1)))).xyz,s=Kc(o);t.addAssign(s),r.addAssign(s.mul(s))}t.divAssign(9),r.divAssign(9);let i=(0,n.max)(r.sub(t.mul(t)),(0,n.float)(0)).div((0,n.max)(t.mul(t),(0,n.float)(1e-4))).mul(10).clamp(0,1),a=i.sub(.5).mul(4).clamp(0,1),o=i.mul(4).clamp(0,1).sub(i.sub(.75).mul(4).clamp(0,1)),s=(0,n.float)(1).sub(i.sub(.25).mul(4).clamp(0,1));m.assign((0,n.vec4)(a,o,s,1))}).ElseIf(c.equal((0,n.int)(2)),()=>{let e=(0,n.textureLoad)(r,p).w.div(32).clamp(0,1);m.assign((0,n.vec4)((0,n.float)(1).sub(e),e,(0,n.float)(.2),1))}).ElseIf(c.equal((0,n.int)(3)),()=>{let e=(0,n.textureLoad)(a,p),t=(0,n.abs)(e.x).mul(100).clamp(0,1),r=(0,n.abs)(e.y).mul(100).clamp(0,1),i=t.add(r).clamp(0,1);m.assign((0,n.vec4)(t,r,i.mul(.3),1))}).ElseIf(c.equal((0,n.int)(4)),()=>{let e=(0,n.textureLoad)(i,p);m.assign((0,n.vec4)(e.xyz,1))}).Else(()=>{let e=(0,n.textureLoad)(o,p).x.mul(5).clamp(0,1);m.assign((0,n.vec4)(e,e.mul(.5),(0,n.float)(1).sub(e),1))}),(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),m).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}setupEventListeners(){this.on(`pipeline:historyReset`,()=>this.resetTemporalData())}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:color`),n=e.getTexture(`pathtracer:albedo`),r=e.getTexture(`pathtracer:normalDepth`),i=e.getTexture(`pathtracer:prevNormalDepth`)||r,a=e.getTexture(`motionVector:screenSpace`);if(!t)return;let o=t.image;o&&o.width>0&&o.height>0&&(o.width!==this._outputRT.width||o.height!==this._outputRT.height)&&this.setSize(o.width,o.height),this._colorTexNode.value=t,n&&(this._albedoTexNode.value=n),a&&(this._motionTexNode.value=a),r&&(this._normalDepthTexNode.value=r),i&&(this._prevNormalDepthTexNode.value=i);let s=this.currentMoments===0?this._temporalTexB:this._temporalTexA,c=this.currentMoments===0?this._temporalNodeA:this._temporalNodeB,l=this.currentMoments===0?this._temporalTexA:this._temporalTexB;this._compiled||=(this.renderer.compute(this._gradientNode),this.renderer.compute(this._temporalNodeA),this.renderer.compute(this._temporalNodeB),!0),this._readTemporalTexNode.value=s,this._gradientReadTexNode.value=this._gradientStorageTex;let u=this.gradientStrength.value>0||this.showHeatmap;u&&this.renderer.compute(this._gradientNode),this.forceResetU.value=+!!this._needsWarmReset,this.renderer.compute(c),this._needsWarmReset=!1,this._srcRegion.max.set(this.resW.value,this.resH.value),this.renderer.copyTextureToTexture(l,this._demodulatedRT.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._outputModulatedTex,this._outputRT.texture,this._srcRegion),u&&this.renderer.copyTextureToTexture(this._gradientStorageTex,this._gradientRT.texture,this._srcRegion),e.setTexture(`asvgf:demodulated`,this._demodulatedRT.texture),e.setTexture(`asvgf:output`,this._outputRT.texture),e.setTexture(`asvgf:gradient`,this._gradientRT.texture),this.currentMoments=1-this.currentMoments,this.showHeatmap&&(this._heatmapRawColorTexNode.value=t,this._heatmapColorTexNode.value=this._outputModulatedTex,this._heatmapTemporalTexNode.value=l,r&&(this._heatmapNDTexNode.value=r),a&&(this._heatmapMotionTexNode.value=a),this._heatmapGradientTexNode.value=this._gradientStorageTex,this.renderer.compute(this._heatmapComputeNode),this._srcRegion.max.set(this.heatmapTarget.width,this.heatmapTarget.height),this.renderer.copyTextureToTexture(this._heatmapStorageTex,this.heatmapTarget.texture,this._srcRegion))}setHeatmapEnabled(e){this.showHeatmap=e}setTemporalEnabled(e){this.temporalEnabledU.value=+!!e}updateParameters(e){e&&(e.temporalAlpha!==void 0&&(this.temporalAlpha.value=e.temporalAlpha),e.gradientStrength!==void 0&&(this.gradientStrength.value=e.gradientStrength),e.gradientSigmaScale!==void 0&&(this.gradientSigmaScale.value=e.gradientSigmaScale),e.gradientNoiseFloor!==void 0&&(this.gradientNoiseFloor.value=e.gradientNoiseFloor),e.maxAccumFrames!==void 0&&(this.maxAccumFrames.value=e.maxAccumFrames),e.debugMode!==void 0&&(this.debugMode.value=e.debugMode))}resetTemporalData(){this.currentMoments=0,this._needsWarmReset=!0}reallocateReservedStorage(){this._gradientNode?.dispose(),this._temporalNodeA?.dispose(),this._temporalNodeB?.dispose(),this._heatmapComputeNode?.dispose(),this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._heatmapStorageTex?.dispose();let e=(e,n)=>{let i=new t.StorageTexture(U,U);return i.type=e,i.format=r.RGBAFormat,i.minFilter=n,i.magFilter=n,i};this._temporalTexA=e(r.FloatType,r.LinearFilter),this._temporalTexB=e(r.FloatType,r.LinearFilter),this._outputModulatedTex=e(r.FloatType,r.LinearFilter),this._gradientStorageTex=e(r.HalfFloatType,r.LinearFilter),this._heatmapStorageTex=e(r.FloatType,r.NearestFilter),this._buildGradientCompute(),this._buildTemporalCompute(),this._buildHeatmapCompute(),this._compiled=!1,this.currentMoments=0,this._needsWarmReset=!0}setSize(e,t){this._demodulatedRT.setSize(e,t),this._demodulatedRT.texture.needsUpdate=!0,this._outputRT.setSize(e,t),this._outputRT.texture.needsUpdate=!0,this._gradientRT.setSize(e,t),this._gradientRT.texture.needsUpdate=!0,this.heatmapTarget.setSize(e,t),this.heatmapTarget.texture.needsUpdate=!0,this.resW.value=e,this.resH.value=t,this._dispatchX=Math.ceil(e/8),this._dispatchY=Math.ceil(t/8),this._gradientNode.dispatchSize=[this._dispatchX,this._dispatchY,1],this._temporalNodeA.dispatchSize=[this._dispatchX,this._dispatchY,1],this._temporalNodeB.dispatchSize=[this._dispatchX,this._dispatchY,1],this._heatmapComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]}reset(){}releaseGPUMemory(){this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._heatmapStorageTex?.dispose(),this.context?.removeTexture(`asvgf:demodulated`),this.context?.removeTexture(`asvgf:output`),this.context?.removeTexture(`asvgf:gradient`),this._demodulatedRT?.texture?.dispose(),this._outputRT?.texture?.dispose(),this._gradientRT?.texture?.dispose(),this.heatmapTarget?.texture?.dispose(),this.resetTemporalData()}dispose(){this._gradientNode?.dispose(),this._temporalNodeA?.dispose(),this._temporalNodeB?.dispose(),this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._demodulatedRT?.dispose(),this._outputRT?.dispose(),this._gradientRT?.dispose(),this._heatmapComputeNode?.dispose(),this._heatmapStorageTex?.dispose(),this.heatmapTarget?.dispose(),this._colorTexNode?.dispose(),this._albedoTexNode?.dispose(),this._motionTexNode?.dispose(),this._normalDepthTexNode?.dispose(),this._prevNormalDepthTexNode?.dispose(),this._readTemporalTexNode?.dispose(),this._gradientReadTexNode?.dispose(),this._heatmapRawColorTexNode?.dispose(),this._heatmapColorTexNode?.dispose(),this._heatmapTemporalTexNode?.dispose(),this._heatmapNDTexNode?.dispose(),this._heatmapMotionTexNode?.dispose(),this._heatmapGradientTexNode?.dispose()}};hl();var Iv=1e-6,Lv=1.5/255,Rv=.01,zv=3,Bv=2,Vv=2,Hv=3,Uv=2,Wv=38,Gv=.1,Kv=4,qv=Math.cos(89*Math.PI/180),Jv=.5,Yv=16,Xv={pre:{radiusScale:1,fractionScale:2},blur:{radiusScale:1,fractionScale:1},post:{radiusScale:2,fractionScale:.5}},Zv=.25*Math.SQRT2,Qv=[[-1,0,1],[0,1,1],[1,0,1],[0,-1,1],[-Zv,Zv,.5],[Zv,Zv,.5],[Zv,-Zv,.5],[-Zv,-Zv,.5]],$v=(e,t,r)=>(0,n.smoothstep)(0,1,(0,n.float)(1).sub(e.mul(t).add(r).abs())),ey=(e,t,r)=>{let i=e.mul(t).add(r).abs().mul(-zv);return(0,n.float)(1).div(i.mul(i).sub(i).add(1))},ty=e=>(0,n.mix)((0,n.float)(1.570796),(0,n.float)(1.395402),(0,n.saturate)(e)).mul((0,n.sqrt)((0,n.saturate)((0,n.float)(1).sub(e)))),ny=(e,t)=>(0,n.float)(1).sub((0,n.exp2)(e.mul(e).mul(-200))).mul((0,n.pow)((0,n.saturate)(e),t)),ry=(e,t)=>(0,n.saturate)(e).mul((0,n.sqrt)(t.div((0,n.float)(1).sub(t).add(Iv)))),iy=(e,t,r,i)=>{let a=(0,n.max)((0,n.atan)(ry(r,i.mul((0,n.mix)((0,n.saturate)(t),(0,n.float)(1),e)))),(0,n.float)(Lv));return(0,n.float)(1).div(a)},ay=(e,t)=>{let r=(0,n.float)(1).div((0,n.mix)((0,n.float)(Rv),(0,n.float)(1),(0,n.saturate)(e.mul(t))));return(0,n.vec2)(r,e.mul(r).negate())},oy=(e,t,r)=>{let i=(0,n.float)(1).div((0,n.mix)((0,n.float)(r),(0,n.float)(1),(0,n.mix)(e.mul(e),e,(0,n.saturate)(t))));return(0,n.vec2)(i,e.mul(i).negate())},sy=(e,t)=>{let r=(0,n.float)(1).div(t);return(0,n.vec2)(r,e.mul(r).negate())},cy=(e,t,r,i)=>{let a=(0,n.float)(1).div(e.mul(t));return(0,n.vec2)(a,(0,n.dot)(i,r).mul(a).negate())},ly=e=>(0,n.vec2)(1).sub((0,n.vec2)(1).sub((0,n.fract)(e.mul(.5)).mul(2)).abs()).min(.99999),uy=e=>(0,n.vec3)((0,n.dot)(e,(0,n.vec3)(.25,.5,.25)),(0,n.dot)(e,(0,n.vec3)(.5,0,-.5)),(0,n.dot)(e,(0,n.vec3)(-.25,.5,-.25))),dy=e=>{let t=e.x.sub(e.z);return(0,n.max)((0,n.vec3)(t.add(e.y),e.x.add(e.z),t.sub(e.y)),(0,n.vec3)(0))},fy=(e,t)=>t.add(Iv).div(e.add(Iv)),py=(e,t)=>(0,n.vec4)(e.xyz.mul(fy(e.x,t)),e.w),my=e=>(0,n.vec4)(uy(dy(e.xyz)),(0,n.saturate)(e.w)),hy=(e,t)=>(0,n.sqrt)(t.sub(e.mul(e)).abs()),gy=(e,t)=>(0,n.vec2)(e.x.mul(t.x).add(e.y.mul(t.y)),e.z.mul(t.x).add(e.w.mul(t.y))),_y=(e,t)=>(0,n.select)(e.equal(0),(0,n.vec4)(0),t);function vy(e){let t=Math.imul(e|0,2654435761)>>>0;return t^=t>>>15,t=Math.imul(t,2246822507)>>>0,t^=t>>>13,t=Math.imul(t,3266489909)>>>0,t^=t>>>16,t/4294967296}var yy=class extends M{constructor(e,i={}){super(`NRD`,{...i,executionMode:j.PER_CYCLE}),this.renderer=e,this.pathTracer=i.pathTracer||null,this.settings={...Ev,...i.settings||{}},this._releaseHitDistance=this.pathTracer?.requestOutput?.(`hitDistance`,{encode:(e,t)=>e.div((0,n.max)(t.mul(.1).add(3),(0,n.float)(1e-4))).clamp(0,1)})??null;let a=i.width||1,o=i.height||1;this.resW=(0,n.uniform)(a),this.resH=(0,n.uniform)(o),this.minRectDimMulUnproject=(0,n.uniform)(1),this.inputFrames=(0,n.uniform)(0),this.resetU=(0,n.uniform)(0),this.debugMode=(0,n.uniform)(0,`int`),this.rotPre=(0,n.uniform)(new r.Vector4(1,0,0,1),`vec4`),this.rotBlur=(0,n.uniform)(new r.Vector4(1,0,0,1),`vec4`),this.rotPost=(0,n.uniform)(new r.Vector4(1,0,0,1),`vec4`),this.camWorld=(0,n.uniform)(new r.Matrix4,`mat4`),this.camProjInv=(0,n.uniform)(new r.Matrix4,`mat4`),this.camView=(0,n.uniform)(new r.Matrix4,`mat4`),this.prevCamView=(0,n.uniform)(new r.Matrix4,`mat4`),this.camPos=(0,n.uniform)(new r.Vector3,`vec3`),this.prevCamPos=(0,n.uniform)(new r.Vector3,`vec3`),this.viewVector=(0,n.uniform)(new r.Vector3,`vec3`),this.prevViewVector=(0,n.uniform)(new r.Vector3,`vec3`),this.cameraRay=Xu(),this.u={};for(let e of[`maxAccum`,`maxFast`,`stabilizationStrength`,`historyFixFrameNum`,`historyFixStride`,`prepassBlurRadius`,`minBlurRadius`,`maxBlurRadius`,`lobeAngleFraction`,`roughnessFraction`,`planeDistSensitivity`,`minHitDistanceWeight`,`fastClampSigmaScale`,`fireflyMinRelativeScale`,`antiFirefly`,`disocclusionThreshold`,`lobeVolumePercent`,`handoverFrames`])this.u[e]=(0,n.uniform)(0);this.u.antilag=(0,n.uniform)(new r.Vector2,`vec2`),this.u.convergence=(0,n.uniform)(new r.Vector3,`vec3`),this._syncUniforms(),this._colorTexNode=new t.TextureNode,this._albedoTexNode=new t.TextureNode,this._ndTexNode=new t.TextureNode,this._snTexNode=new t.TextureNode,this._motionTexNode=new t.TextureNode,this._placeholders=new Map;let s=()=>{let e=new r.DataTexture(new Float32Array(4),1,1,r.RGBAFormat,r.FloatType);e.needsUpdate=!0;let n=new t.TextureNode(e);return this._placeholders.set(n,e),n};this._nTmpA=s(),this._nTmpB=s(),this._nHist=s(),this._nFast=s(),this._nInternal=s(),this._nGeom=s(),this._nData=s(),this._nStabRead=s(),this._allocStorage(),this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),this.outputTarget=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._compiled=!1,this._needsReset=!0,this._stabPing=0,this._camInitialized=!1,this._dispatchX=Math.ceil(a/Yv),this._dispatchY=Math.ceil(o/Yv),this._buildKernels()}_allocStorage(){let e=()=>Pe(r.HalfFloatType);this._tmpA=e(),this._tmpB=e(),this._hist=e(),this._fastHist=e(),this._internal=e(),this._geomPrev=e(),this._stabA=e(),this._stabB=e(),this._dataT=e()}_disposeStorage(){for(let e of[this._tmpA,this._tmpB,this._hist,this._fastHist,this._internal,this._geomPrev,this._stabA,this._stabB,this._dataT])e?.dispose()}_disposeKernels(){for(let e of this._kernels??[])e?.dispose()}updateParameters(e){if(e){for(let t of Object.keys(e))t===`debugMode`?this.debugMode.value=e.debugMode|0:t in Ev&&(this.settings[t]=e[t]);this._syncUniforms()}}_syncUniforms(){let e=this.settings,t=this.u,n=Math.min(e.maxAccumulatedFrameNum,63),r=Math.min(e.maxStabilizedFrameNum,n),i=Math.max(e.maxBlurRadius,e.minBlurRadius);t.maxAccum.value=n,t.maxFast.value=e.maxFastAccumulatedFrameNum,t.stabilizationStrength.value=r/(1+r),t.historyFixFrameNum.value=e.historyFixFrameNum,t.historyFixStride.value=e.historyFixBasePixelStride,t.prepassBlurRadius.value=e.prepassBlurRadius,t.minBlurRadius.value=e.minBlurRadius,t.maxBlurRadius.value=i,t.lobeAngleFraction.value=e.lobeAngleFraction*e.lobeAngleFraction,t.roughnessFraction.value=e.roughnessFraction,t.planeDistSensitivity.value=e.planeDistanceSensitivity,t.minHitDistanceWeight.value=e.minHitDistanceWeight;let a=Math.min(1,Math.max(0,i/2));t.fastClampSigmaScale.value=3+(e.fastHistoryClampingSigmaScale-3)*a,t.fireflyMinRelativeScale.value=e.fireflySuppressorMinRelativeScale,t.antiFirefly.value=+!!e.enableAntiFirefly,t.antilag.value.set(e.antilagLuminanceSigmaScale,e.antilagLuminanceSensitivity),t.disocclusionThreshold.value=e.disocclusionThreshold,t.convergence.value.set(e.convergenceS,e.convergenceB,e.convergenceP),t.lobeVolumePercent.value=e.lobeVolumePercent,t.handoverFrames.value=e.handoverFrames>0?e.handoverFrames:2*n}_worldPosAt(e,t,n,r){return Qu(e,t,n,r,this.cameraRay)}_viewVector(e,t,r){return(0,n.select)(Yu(this.cameraRay.cameraProjection),r,(0,n.normalize)(t.sub(e)))}_frustumSize(e){return this.minRectDimMulUnproject.mul((0,n.select)(Yu(this.cameraRay.cameraProjection),(0,n.float)(1),e))}_pixelUv(e,t){return(0,n.vec2)((0,n.float)(e).add(.5).div(this.resW),(0,n.float)(t).add(.5).div(this.resH))}_clampCoord(e,t){return(0,n.ivec2)(e.clamp((0,n.int)(0),(0,n.int)(this.resW).sub(1)),t.clamp((0,n.int)(0),(0,n.int)(this.resH).sub(1)))}_uvToCoord(e){return this._clampCoord((0,n.int)(e.x.mul(this.resW)),(0,n.int)(e.y.mul(this.resH)))}_advancedNonLinear(e){let t=this.u.convergence,r=(0,n.saturate)(e.div((0,n.float)(1).add(this.u.maxAccum.mul(t.z)))),i=t.x.mul((0,n.mix)(t.y,(0,n.float)(1),r));return(0,n.float)(1).div((0,n.float)(1).add(i.mul(e)))}_handover(e){return(0,n.saturate)(e.div((0,n.max)(this.u.handoverFrames,1)))}_bilinear(e){let t=e.mul((0,n.vec2)(this.resW,this.resH)).sub(.5),r=(0,n.floor)(t),i=(0,n.saturate)(t.sub(r)),a=(0,n.int)(r.x),o=(0,n.int)(r.y),s=(e,t)=>(0,n.select)(e.greaterThanEqual((0,n.int)(0)).and(t.greaterThanEqual((0,n.int)(0))).and(e.lessThan((0,n.int)(this.resW))).and(t.lessThan((0,n.int)(this.resH))),(0,n.float)(1),(0,n.float)(0));return{f:i,taps:[this._clampCoord(a,o),this._clampCoord(a.add(1),o),this._clampCoord(a,o.add(1)),this._clampCoord(a.add(1),o.add(1))],inScreen:[s(a,o),s(a.add(1),o),s(a,o.add(1)),s(a.add(1),o.add(1))],customWeights:e=>[e[0].mul((0,n.float)(1).sub(i.x)).mul((0,n.float)(1).sub(i.y)),e[1].mul(i.x).mul((0,n.float)(1).sub(i.y)),e[2].mul((0,n.float)(1).sub(i.x)).mul(i.y),e[3].mul(i.x).mul(i.y)],filter:e=>(0,n.mix)((0,n.mix)(e[0],e[1],i.x),(0,n.mix)(e[2],e[3],i.x),i.y)}}_applyCustomWeights(e,t,r){let i=e[0].mul(t[0]).add(e[1].mul(t[1])).add(e[2].mul(t[2])).add(e[3].mul(t[3])),a=t[0].add(t[1]).add(t[2]).add(t[3]);return(0,n.select)(a.lessThan(1e-4),r,i.div((0,n.max)(a,1e-4)))}_sampleHistory(e,t,r,i,a){let o=(0,n.vec4)(0).toVar();return(0,n.If)(a,()=>{let r=(0,n.saturate)(t).mul((0,n.vec2)(this.resW,this.resH)),i=(0,n.floor)(r.sub(.5)).add(.5),a=(0,n.saturate)(r.sub(i)),s=Jv,c=a.mul(a.mul(a.mul(-s).add(2*s)).sub(s)),l=a.mul(a.mul(a.mul(2-s).sub(3-s))).add(1),u=a.mul(a.mul(a.mul(-(2-s)).add(3-2*s)).add(s)),d=a.mul(a.mul(a.mul(s).sub(s))),f=[c.x,l.x,u.x,d.x],p=[c.y,l.y,u.y,d.y],m=(0,n.int)(i.x).sub(1),h=(0,n.int)(i.y).sub(1),g=(0,n.vec4)(0).toVar(),_=(0,n.float)(0).toVar();for(let t=0;t<4;t++)for(let n=0;n<4;n++){if((n===0||n===3)&&(t===0||t===3))continue;let r=f[n].mul(p[t]);g.addAssign(e(this._clampCoord(m.add(n),h.add(t))).mul(r)),_.addAssign(r)}o.assign((0,n.select)(_.lessThan(1e-4),(0,n.vec4)(0),g.div((0,n.max)(_,1e-4))))}).Else(()=>{o.assign(this._applyCustomWeights(r.taps.map(t=>e(t)),i,(0,n.vec4)(0)))}),o}_buildKernels(){this._kPre=this._buildSpatial(`pre`),this._kTa=this._buildTemporalAccumulation(),this._kHf=this._buildHistoryFix(),this._kBlur=this._buildSpatial(`blur`),this._kPost=this._buildSpatial(`post`),this._kTsA=this._buildTemporalStabilization(this._stabA),this._kTsB=this._buildTemporalStabilization(this._stabB),this._kernels=[this._kPre,this._kTa,this._kHf,this._kBlur,this._kPost,this._kTsA,this._kTsB]}_dispatchOf(e){return e(this.camWorld,this.camProjInv).compute([this._dispatchX,this._dispatchY,1],[Yv,Yv,1])}_buildSpatial(e){let t=e===`pre`,{radiusScale:r,fractionScale:i}=Xv[e],a=this.u,o=this._colorTexNode,s=this._albedoTexNode,c=this._ndTexNode,l=this._snTexNode,u=this._nData,d=e===`blur`?this._nTmpA:this._nTmpB,f=e===`blur`?this._tmpB:t?this._tmpA:this._hist,p=this._geomPrev,m=t?this.rotPre:e===`blur`?this.rotBlur:this.rotPost,h=t?a.prepassBlurRadius:a.maxBlurRadius,g=this.camView,_=this.camPos,v=this.resW,y=this.resH,b=this.inputFrames,x=t?e=>{let t=(0,n.textureLoad)(o,e),r=(0,n.textureLoad)(s,e);return(0,n.vec4)(uy(Bc(t.xyz.div((0,n.max)(r.xyz,(0,n.vec3)(Sv))))),zc(r.w,Rc).min(1))}:e=>(0,n.textureLoad)(d,e),S=(0,n.Fn)(([o,s])=>{let d=(0,n.int)(n.workgroupId.x).mul(Yv).add((0,n.int)(n.localId.x)),S=(0,n.int)(n.workgroupId.y).mul(Yv).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(v)).and(S.lessThan((0,n.int)(y))),()=>{let C=(0,n.ivec2)(d,S),w=(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(S)),T=(0,n.textureLoad)(c,C).w.toVar(),E=T.greaterThanEqual(xv),D=(0,n.textureLoad)(l,C).toVar(),O=(0,n.normalize)(D.xyz.mul(2).sub(1)).toVar(),k=D.w.clamp(.05,1).toVar(),A=(0,n.float)(xv).toVar(),j=x(C).toVar();(0,n.If)(E.not(),()=>{let e=this._pixelUv(d,S),f=this._worldPosAt(e,T,o,s).toVar();A.assign(g.mul((0,n.vec4)(f,1)).z.abs()),(0,n.If)(h.greaterThan(0),()=>{let d=(0,n.dot)(O,this._viewVector(f,_,this.viewVector)).abs().toVar(),p=this._frustumSize(A).toVar(),S=b.add(1),w=t?(0,n.max)(b,(0,n.float)(10)):(0,n.textureLoad)(u,C).y.add(b),T=(t?(0,n.float)(1).div(w.add(1)):this._advancedNonLinear(w)).toVar(),E=ny(k,.5).toVar(),D=A.mul(Tv).add(3),M=j.w.toVar(),N=(0,n.saturate)(M.mul(D).div(p)),P=(0,n.float)(1).sub(this._handover(S)),F=(t?N.div(S):N.mul(T)).mul(P),I=a.minBlurRadius.mul((0,n.saturate)((0,n.float)(2).sub(w.div((0,n.max)(a.maxAccum,1))))),L=(0,n.max)((0,n.saturate)((0,n.sqrt)((0,n.saturate)(F)).mul(r)).mul(h).mul(E),I.mul(E)).toVar(),ee=cy(a.planeDistSensitivity,p,f,O).toVar(),te=iy(T,a.lobeAngleFraction,k,a.lobeVolumePercent).div(i).toVar(),R=ay(k,a.roughnessFraction.mul(i)).toVar(),ne=sy(M,T).toVar(),re=a.minHitDistanceWeight.mul(i).mul(E);t||(re=re.mul(T)),re=re.toVar();let ie=(0,n.vec2)(1);if(!t){let e=g.mul((0,n.vec4)(O,0)).xy;ie=(0,n.mix)((0,n.vec2)(1).sub(e.abs()),(0,n.vec2)(1),d),ie=ie.div((0,n.max)(ie.x,ie.y))}let ae=ie.mul((0,n.vec2)((0,n.float)(1).div(v),(0,n.float)(1).div(y))).mul(L).toVar(),oe=(0,n.float)(1).toVar();for(let t=0;t<Qv.length;t++){let r=Qv[t],i=e.add(gy(m,(0,n.vec2)(r[0],r[1])).mul(ae)),a=ly(i),u=(0,n.select)(a.x.notEqual(i.x).or(a.y.notEqual(i.y)),(0,n.float)(1),(0,n.float)(Math.exp(-.66*r[2]*r[2]))).toVar(),d=this._uvToCoord(a),f=(0,n.textureLoad)(c,d).w,p=this._worldPosAt(a,f,o,s),h=(0,n.textureLoad)(l,d),g=ty((0,n.dot)(O,(0,n.normalize)(h.xyz.mul(2).sub(1))));u.mulAssign($v(g,te,(0,n.float)(0))),u.mulAssign($v(h.w,R.x,R.y)),u.mulAssign($v((0,n.dot)(O,p),ee.x,ee.y)),u.assign((0,n.select)(f.greaterThanEqual(xv),(0,n.float)(0),u));let _=_y(u,x(d));u.mulAssign(re.add(ey(_.w,ne.x,ne.y))),oe.addAssign(u),j.addAssign(_.mul(u))}j.divAssign((0,n.max)(oe,1e-6)),t||j.assign((0,n.vec4)(j.xyz,M))})}),(0,n.textureStore)(f,w,j).toWriteOnly(),e===`post`&&(0,n.textureStore)(p,w,(0,n.vec4)(O,A)).toWriteOnly()})});return this._dispatchOf(S)}_buildTemporalAccumulation(){let e=this.u,t=this._ndTexNode,r=this._snTexNode,i=this._motionTexNode,a=this._nTmpA,o=this._nHist,s=this._nFast,c=this._nInternal,l=this._nGeom,u=this._tmpB,d=this._dataT,f=this.camView,p=this.prevCamView,m=this.camPos,h=this.prevCamPos,g=this.resW,_=this.resH,v=this.inputFrames,y=this.resetU,b=(0,n.Fn)(([b,x])=>{let S=(0,n.int)(n.workgroupId.x).mul(Yv).add((0,n.int)(n.localId.x)),C=(0,n.int)(n.workgroupId.y).mul(Yv).add((0,n.int)(n.localId.y));(0,n.If)(S.lessThan((0,n.int)(g)).and(C.lessThan((0,n.int)(_))),()=>{let g=(0,n.ivec2)(S,C),_=(0,n.uvec2)((0,n.uint)(S),(0,n.uint)(C)),w=(0,n.textureLoad)(t,g).w,T=(0,n.textureLoad)(a,g).toVar();(0,n.If)(w.greaterThanEqual(xv),()=>{(0,n.textureStore)(u,_,T).toWriteOnly(),(0,n.textureStore)(d,_,(0,n.vec4)(0)).toWriteOnly(),(0,n.Return)()});let E=e.maxAccum.mul((0,n.float)(1).sub(y)).toVar(),D=e.maxFast.mul((0,n.float)(1).sub(y)).toVar(),O=(0,n.textureLoad)(r,g),k=(0,n.normalize)(O.xyz.mul(2).sub(1)).toVar(),A=O.w.clamp(.05,1).toVar(),j=this._pixelUv(S,C),M=this._worldPosAt(j,w,b,x).toVar(),N=f.mul((0,n.vec4)(M,1)).z.abs().toVar(),P=(0,n.dot)(k,this._viewVector(M,m,this.viewVector)).abs().toVar(),F=this._frustumSize(N).toVar(),I=(0,n.vec3)(0).toVar();I.addAssign(k.mul(.25));for(let e=-1;e<=0;e++)for(let i=-1;i<=0;i++){if(i===0&&e===0)continue;let a=this._clampCoord(S.add(i),C.add(e)),o=(0,n.normalize)((0,n.textureLoad)(r,a).xyz.mul(2).sub(1)),s=(0,n.textureLoad)(t,a).w.lessThan(xv);I.addAssign((0,n.select)(s,o,k).mul(.25))}let L=(0,n.textureLoad)(i,g),ee=j.sub(L.xy).toVar(),te=p.mul((0,n.vec4)(M,1)).z.abs().toVar(),R=this._bilinear(ee),ne=F.mul((0,n.saturate)(e.disocclusionThreshold.div((0,n.max)(P,.05)))).sub(Iv).toVar(),re=(0,n.float)(1).sub(y),ie=[],ae=[];for(let e=0;e<4;e++){let t=(0,n.textureLoad)(l,R.taps[e]),r=(0,n.select)((0,n.dot)(t.xyz,I).greaterThan(qv),(0,n.float)(1),(0,n.float)(0)),i=(0,n.select)(t.w.sub(te).abs().lessThanEqual(ne),(0,n.float)(1),(0,n.float)(0)),a=(0,n.select)(t.w.lessThan(xv),(0,n.float)(1),(0,n.float)(0));ie.push(r.mul(i).mul(a).mul(R.inScreen[e]).mul(re).toVar()),ae.push((0,n.textureLoad)(c,R.taps[e]).x)}let oe=R.customWeights(ie).map(e=>e.toVar()),se=ie[0].add(ie[1]).add(ie[2]).add(ie[3]).greaterThan(3.5).toVar(),ce=ie[0].add(ie[1].mul(2)).add(ie[2].mul(4)).add(ie[3].mul(8)),le=this._applyCustomWeights(ae,oe,(0,n.float)(0)).toVar(),ue=(0,n.dot)(k,this._viewVector(M,h,this.prevViewVector)).abs().add(.001).div(P.add(.001)).toVar();ue.assign((0,n.mix)((0,n.float)(.1),(0,n.float)(1),(0,n.saturate)(ue.mul(ue))));let z=(0,n.sqrt)((0,n.saturate)(R.filter(ie))).mul(ue).toVar();le.assign(le.mul((0,n.mix)(z,(0,n.float)(1),(0,n.float)(1).div(le.add(1))))),le.assign((0,n.min)(le,E));let de=my(this._sampleHistory(e=>(0,n.textureLoad)(o,e),ee,R,oe,se)).toVar(),fe=(0,n.max)(this._applyCustomWeights(R.taps.map(e=>(0,n.textureLoad)(s,e).x),oe,(0,n.float)(0)),0).toVar(),pe=v.add(1),me=this._handover(pe).toVar(),he=le.mul((0,n.float)(1).sub(me)),ge=pe.div(pe.add(he)).toVar(),_e=(0,n.float)(1).div((0,n.float)(1).add(ny(A,.25).mul(.5).mul(E))),ve=(0,n.vec4)((0,n.mix)(de.xyz,T.xyz,ge),(0,n.mix)(de.w,T.w,(0,n.max)(ge,_e))).toVar(),ye=e.fireflyMinRelativeScale.add((0,n.float)(Wv).div(le.add(1))).toVar(),B=le.mul(e.maxBlurRadius).mul(Gv).toVar();B.assign(B.div(B.add(1)).mul((0,n.float)(1).sub(me)));let be=(0,n.mix)(ve.x,(0,n.min)(ve.x,de.x.mul(ye)),B);ve.assign(py(ve,be));let xe=(0,n.float)(1.2).add((0,n.float)(1).div(le.add(1)));ve.assign((0,n.vec4)(ve.xyz,(0,n.mix)(ve.w,(0,n.min)(ve.w,de.w.mul(xe)),B))),(0,n.textureStore)(u,_,ve).toWriteOnly();let Se=(0,n.min)(le,D).mul((0,n.float)(1).sub(me)),Ce=pe.div(pe.add(Se)),V=(0,n.mix)(fe,T.x,Ce).toVar(),we=(0,n.min)(V,de.x.mul(ye).mul(Kv));V.assign((0,n.mix)(V,we,B)),(0,n.textureStore)(d,_,(0,n.vec4)(V,le,ce,(0,n.select)(se,(0,n.float)(1),(0,n.float)(0)))).toWriteOnly()})});return this._dispatchOf(b)}_buildHistoryFix(){let e=this.u,t=this._ndTexNode,r=this._snTexNode,i=this._nTmpB,a=this._nData,o=this._tmpA,s=this._fastHist,c=this.camView,l=this.resW,u=this.resH,d=this.inputFrames,f=(0,n.Fn)(([f,p])=>{let m=(0,n.int)(n.workgroupId.x).mul(Yv).add((0,n.int)(n.localId.x)),h=(0,n.int)(n.workgroupId.y).mul(Yv).add((0,n.int)(n.localId.y));(0,n.If)(m.lessThan((0,n.int)(l)).and(h.lessThan((0,n.int)(u))),()=>{let g=(0,n.ivec2)(m,h),_=(0,n.uvec2)((0,n.uint)(m),(0,n.uint)(h)),v=(0,n.textureLoad)(t,g).w;(0,n.If)(v.greaterThanEqual(xv),()=>{let e=(0,n.textureLoad)(i,g);(0,n.textureStore)(o,_,e).toWriteOnly(),(0,n.textureStore)(s,_,(0,n.vec4)(e.x,0,0,0)).toWriteOnly(),(0,n.Return)()});let y=(0,n.textureLoad)(a,g).toVar(),b=y.y.toVar(),x=b.add(d),S=this._handover(d.add(1)).toVar(),C=(0,n.textureLoad)(r,g),w=(0,n.normalize)(C.xyz.mul(2).sub(1)).toVar(),T=C.w.clamp(.05,1).toVar(),E=this._pixelUv(m,h),D=this._worldPosAt(E,v,f,p).toVar(),O=c.mul((0,n.vec4)(D,1)).z.abs(),k=this._frustumSize(O).toVar(),A=(0,n.textureLoad)(i,g).toVar(),j=(0,n.float)(1).div(x.add(1)).toVar(),M=O.mul(Tv).add(3),N=(0,n.saturate)(A.w.mul(M).div(k)),P=A.w.toVar(),F=(0,n.round)((0,n.select)(x.lessThan(e.historyFixFrameNum),(0,n.float)(1),(0,n.float)(0)).mul(.5).mul(2/Bv).mul(e.historyFixStride).mul((0,n.mix)((0,n.float)(.25).add((0,n.sqrt)(N).mul(.75)),(0,n.float)(1),j))).toVar();(0,n.If)(F.notEqual(0),()=>{let o=iy(j,e.lobeAngleFraction,T,e.lobeVolumePercent).toVar(),s=cy(e.planeDistSensitivity,k,D,w).toVar(),c=sy(P,j).toVar(),d=oy(T.mul(T),(0,n.sqrt)(e.roughnessFraction),Rv).toVar(),m=(0,n.float)(1).add(b).toVar();A.mulAssign(m);for(let e=-Bv;e<=Bv;e++)for(let h=-Bv;h<=Bv;h++){if(h===0&&e===0||Math.abs(h)+Math.abs(e)===Bv*2)continue;let g=ly(E.add((0,n.vec2)(h,e).mul(F).mul((0,n.vec2)((0,n.float)(1).div(l),(0,n.float)(1).div(u))))),_=this._uvToCoord(g),v=(0,n.textureLoad)(t,_).w,y=this._worldPosAt(g,v,f,p),b=(0,n.textureLoad)(r,_),x=ey(ty((0,n.dot)((0,n.normalize)(b.xyz.mul(2).sub(1)),w)),o,(0,n.float)(0)).toVar();x.mulAssign(ey(b.w.mul(b.w),d.x,d.y)),x.mulAssign((0,n.float)(1).add((0,n.textureLoad)(a,_).y)),x.mulAssign($v((0,n.dot)(w,y),s.x,s.y)),x.assign((0,n.select)(v.greaterThanEqual(xv),(0,n.float)(0),x));let S=_y(x,(0,n.textureLoad)(i,_));x.mulAssign(ey(S.w,c.x,c.y)),m.addAssign(x),A.addAssign(S.mul(x))}A.divAssign((0,n.max)(m,1e-6))});let I=A.x.toVar(),L=(0,n.saturate)(b.div((0,n.max)(e.historyFixFrameNum,Iv))),ee=(0,n.mix)(I,y.x,L).toVar();(0,n.textureStore)(s,_,(0,n.vec4)(ee,0,0,0)).toWriteOnly();let te=ee.toVar(),R=ee.mul(ee).toVar(),ne=(0,n.float)(0).toVar(),re=(0,n.float)(0).toVar(),ie=(e,r,i)=>{let o=this._clampCoord(m.add(e),h.add(r)),s=(0,n.textureLoad)(t,o).w,c=(0,n.select)(s.greaterThanEqual(xv),ee,(0,n.textureLoad)(a,o).x);Math.abs(e)<=Vv&&Math.abs(r)<=Vv&&(te.addAssign(c),R.addAssign(c.mul(c))),i&&(ne.addAssign(c),re.addAssign(c.mul(c)))},ae=e.antiFirefly.greaterThan(.5);for(let e=-Vv;e<=Vv;e++)for(let t=-Vv;t<=Vv;t++)t===0&&e===0||ie(t,e,Math.abs(t)>1||Math.abs(e)>1);(0,n.If)(ae,()=>{for(let e=-Hv;e<=Hv;e++)for(let t=-Hv;t<=Hv;t++)Math.abs(t)<=Vv&&Math.abs(e)<=Vv||ie(t,e,!0)}),(0,n.If)(ae,()=>{let e=1/((Hv*2+1)**2-9),t=ne.mul(e),r=hy(t,re.mul(e)).mul(Uv);I.assign((0,n.mix)(I.clamp(t.sub(r),t.add(r)),I,S))});{let t=1/(Vv*2+1)**2,r=te.mul(t),i=hy(r,R.mul(t)).mul(e.fastClampSigmaScale),a=I.clamp(r.sub(i),r.add(i)),o=(0,n.select)(e.maxFast.lessThan(e.maxAccum),(0,n.float)(1),(0,n.float)(0)),s=(0,n.mix)((0,n.float)(1).div((0,n.float)(1).add(o.mul(b).mul(2))),(0,n.float)(1),S);I.assign((0,n.mix)(a,I,s))}(0,n.textureStore)(o,_,py(A,I)).toWriteOnly()})});return this._dispatchOf(f)}_buildTemporalStabilization(e){let t=this.u,r=this._colorTexNode,i=this._albedoTexNode,a=this._ndTexNode,o=this._snTexNode,s=this._motionTexNode,c=this._nHist,l=this._nData,u=this._nStabRead,d=this._internal,f=this._tmpA,p=this.resW,m=this.resH,h=this.inputFrames,g=this.resetU,_=this.debugMode;return(0,n.Fn)(()=>{let v=(0,n.int)(n.workgroupId.x).mul(Yv).add((0,n.int)(n.localId.x)),y=(0,n.int)(n.workgroupId.y).mul(Yv).add((0,n.int)(n.localId.y));(0,n.If)(v.lessThan((0,n.int)(p)).and(y.lessThan((0,n.int)(m))),()=>{let p=(0,n.ivec2)(v,y),m=(0,n.uvec2)((0,n.uint)(v),(0,n.uint)(y)),b=(0,n.textureLoad)(a,p).w,x=(0,n.textureLoad)(r,p).toVar();(0,n.If)(b.greaterThanEqual(xv),()=>{(0,n.textureStore)(f,m,x).toWriteOnly(),(0,n.textureStore)(e,m,(0,n.vec4)((0,n.textureLoad)(c,p).x,0,0,0)).toWriteOnly(),(0,n.textureStore)(d,m,(0,n.vec4)(0,1,0,0)).toWriteOnly(),(0,n.Return)()});let S=(0,n.textureLoad)(o,p).w.clamp(.05,1),C=this._pixelUv(v,y),w=(0,n.textureLoad)(s,p),T=C.sub(w.xy).toVar(),E=(0,n.textureLoad)(l,p).toVar(),D=E.y.toVar(),O=(0,n.uint)(E.z.add(.5)).toVar(),k=E.w.greaterThan(.5),A=this._bilinear(T),j=[1,2,4,8].map(e=>(0,n.select)(O.bitAnd((0,n.uint)(e)).notEqual((0,n.uint)(0)),(0,n.float)(1),(0,n.float)(0))),M=A.customWeights(j).map(e=>e.toVar()),N=(0,n.sqrt)((0,n.saturate)(A.filter(j))).toVar(),P=(0,n.textureLoad)(c,p).toVar(),F=P.x.toVar(),I=F.toVar(),L=F.mul(F).toVar();for(let e=-1;e<=1;e++)for(let t=-1;t<=1;t++){if(t===0&&e===0)continue;let r=this._clampCoord(v.add(t),y.add(e)),i=(0,n.textureLoad)(a,r).w,o=(0,n.select)(i.greaterThanEqual(xv),F,(0,n.textureLoad)(c,r).x);I.addAssign(o),L.addAssign(o.mul(o))}I.divAssign(9),L.divAssign(9);let ee=hy(I,L).toVar();(0,n.If)(D.lessThan(t.historyFixFrameNum),()=>{F.assign((0,n.min)(F,I.mul((0,n.float)(1.2).add((0,n.float)(1).div(D.add(1))))))});let te=(0,n.max)(this._sampleHistory(e=>(0,n.textureLoad)(u,e),T,A,M,k).x,0).toVar(),R=ee.mul(t.antilag.x),ne=t.antilag.y.mul(4),re=te.clamp(I.sub(R),I.add(R)),ie=te.sub(re).abs().div((0,n.max)(te,re).add(Iv)),ae=(0,n.float)(1).div((0,n.float)(1).add(ie.mul(D.mul(N)).div(ne))).toVar(),oe=(0,n.min)(D,t.historyFixFrameNum);D.assign((0,n.mix)(oe,D,ae));let se=h.add(1),ce=this._handover(se),le=N.mul((0,n.float)(1).sub(this._advancedNonLinear(D.mul((0,n.float)(1).sub(ce)).div(se)))).mul(ae).toVar(),ue=(0,n.float)(1).add(le.mul(6)),z=t.stabilizationStrength.mul((0,n.float)(1).sub(g)),de=(0,n.mix)(F,te.clamp(I.sub(ee.mul(ue)),I.add(ee.mul(ue))),(0,n.min)(le,z)).toVar();P.assign(py(P,de)),(0,n.textureStore)(e,m,(0,n.vec4)(de,0,0,0)).toWriteOnly();let fe=t.maxAccum.mul((0,n.float)(1).sub(g));(0,n.textureStore)(d,m,(0,n.vec4)((0,n.min)(D.add(1),fe),S,0,0)).toWriteOnly();let pe=(0,n.textureLoad)(i,p),me=(0,n.vec4)(dy(P.xyz).mul((0,n.max)(pe.xyz,(0,n.vec3)(Sv))),x.w).toVar();(0,n.If)(_.equal((0,n.int)(1)),()=>{let e=(0,n.saturate)(D.div((0,n.max)(t.maxAccum,1)));me.assign((0,n.vec4)((0,n.float)(1).sub(e),e,.2,1))}).ElseIf(_.equal((0,n.int)(2)),()=>{me.assign((0,n.vec4)((0,n.vec3)(P.w),1))}).ElseIf(_.equal((0,n.int)(3)),()=>{me.assign((0,n.vec4)((0,n.vec3)(S),1))}).ElseIf(_.equal((0,n.int)(4)),()=>{let e=E.x.div(E.x.add(1));me.assign((0,n.vec4)((0,n.vec3)(e),1))}).ElseIf(_.equal((0,n.int)(5)),()=>{me.assign((0,n.vec4)((0,n.vec3)(E.z.div(15)),1))}),(0,n.textureStore)(f,m,me).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[Yv,Yv,1])}setupEventListeners(){this.on(`pipeline:historyReset`,()=>this.resetHistory())}resetHistory(){this._needsReset=!0}_updateCamera(){let e=this.pathTracer;if(!e?.uniforms)return;let t=e.uniforms.get(`cameraWorldMatrix`).value,n=e.uniforms.get(`cameraViewMatrix`).value,r=e.uniforms.get(`cameraProjectionMatrixInverse`).value,i=e.uniforms.get(`cameraProjectionMatrix`).value;this._camInitialized&&(this.prevCamView.value.copy(this.camView.value),this.prevCamPos.value.copy(this.camPos.value),this.prevViewVector.value.copy(this.viewVector.value)),this.camWorld.value.copy(t),this.camProjInv.value.copy(r),this.camView.value.copy(n),this.camPos.value.setFromMatrixPosition(t),this.viewVector.value.setFromMatrixColumn(t,2).normalize(),this.cameraRay.sync(e.uniforms),this._camInitialized||=(this.prevCamView.value.copy(n),this.prevCamPos.value.copy(this.camPos.value),this.prevViewVector.value.copy(this.viewVector.value),!0);let a=i.elements[5]||1,o=1/(.5*this.resH.value*a);this.minRectDimMulUnproject.value=Math.min(this.resW.value,this.resH.value)*o}_updateRotators(e){let t=(t,n)=>{let r=vy(e*3+n)*Math.PI*2;t.value.set(Math.cos(r),Math.sin(r),-Math.sin(r),Math.cos(r))};t(this.rotPre,0),t(this.rotBlur,1),t(this.rotPost,2)}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:color`),n=e.getTexture(`pathtracer:albedo`),r=e.getTexture(`pathtracer:normalDepth`),i=e.getTexture(`pathtracer:shadingNormal`),a=e.getTexture(`motionVector:screenSpace`);if(!t)return;if(!n||!r||!i||!a){e.setTexture(`nrd:output`,t);return}let o=t.image;o&&o.width>0&&o.height>0&&(o.width!==this.outputTarget.width||o.height!==this.outputTarget.height)&&this.setSize(o.width,o.height);let s=e.getState(`pathtracer:samples`)??this.pathTracer?.frameCount??0;if(s+1>=this.u.handoverFrames.value){e.setTexture(`nrd:output`,t),this._needsReset=!0;return}if(this._colorTexNode.value=t,this._albedoTexNode.value=n,this._ndTexNode.value=r,this._snTexNode.value=i,this._motionTexNode.value=a,this._updateCamera(),this.inputFrames.value=s,this._updateRotators(this.pathTracer?.uniforms?.get(`seedFrame`)?.value??e.getState(`frame`)??0),this.resetU.value=+!!this._needsReset,!this._compiled){for(let e of this._kernels)this.renderer.compute(e);this._compiled=!0}this._nTmpA.value=this._tmpA,this._nTmpB.value=this._tmpB,this._nHist.value=this._hist,this._nFast.value=this._fastHist,this._nInternal.value=this._internal,this._nGeom.value=this._geomPrev,this._nData.value=this._dataT,this._nStabRead.value=this._stabPing===0?this._stabB:this._stabA,this.renderer.compute(this._kPre),this.renderer.compute(this._kTa),this.renderer.compute(this._kHf),this.renderer.compute(this._kBlur),this.renderer.compute(this._kPost),this.renderer.compute(this._stabPing===0?this._kTsA:this._kTsB),this._srcRegion.max.set(this.outputTarget.width,this.outputTarget.height),this.renderer.copyTextureToTexture(this._tmpA,this.outputTarget.texture,this._srcRegion),e.setTexture(`nrd:output`,this.outputTarget.texture),this._stabPing=1-this._stabPing,this._needsReset=!1,this._needsReset=!1}setSize(e,t){this.outputTarget.setSize(e,t),this.outputTarget.texture.needsUpdate=!0,this.resW.value=e,this.resH.value=t,this._dispatchX=Math.ceil(e/Yv),this._dispatchY=Math.ceil(t/Yv);let n=[this._dispatchX,this._dispatchY,1];for(let e of this._kernels)e&&(e.dispatchSize=n);this._needsReset=!0}releaseGPUMemory(){this._disposeStorage(),this.context?.removeTexture(`nrd:output`),this.outputTarget?.texture?.dispose(),this._needsReset=!0}reallocateReservedStorage(){this._disposeKernels(),this._disposeStorage();for(let[e,t]of this._placeholders)e.value=t;this._allocStorage(),this._buildKernels(),this._compiled=!1,this._needsReset=!0,this._stabPing=0}dispose(){this._releaseHitDistance?.(),this._releaseHitDistance=null,this._disposeKernels(),this._disposeStorage(),this.outputTarget?.dispose();for(let e of[this._colorTexNode,this._albedoTexNode,this._ndTexNode,this._snTexNode,this._motionTexNode])e?.dispose();for(let[e,t]of this._placeholders)e.dispose(),t.dispose();this._placeholders.clear()}};hl();var by=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,1e7),xy=(0,n.wgslFn)(`
|
|
915
|
+
`,p_=32,m_=class{constructor(e,t=`rayzee:tonemap`,{input:n=`packed`,output:r=`rgba8`}={}){this.device=e,this.label=t,this.input=n,this.output=r,this.width=0,this.height=0,this._pipeline=null,this._storage=null,this._map=null,this._params=null,this._paramData=new ArrayBuffer(p_),this._paramU32=new Uint32Array(this._paramData),this._paramF32=new Float32Array(this._paramData),this._shaderVersion=-1,this._bindings=[],this._tables=new Map,this.disposed=!1}_ensurePipeline(){let{wgsl:e,bindings:t,version:n}=o_();this._pipeline&&this._shaderVersion===n||(this._bindings=t,this._shaderVersion=n,this._pipeline=this.device.createComputePipeline({label:this.label,layout:`auto`,compute:{module:this.device.createShaderModule({label:this.label,code:f_(e,this.input,this.output)}),entryPoint:`main`}}))}_ensureTables(){let e=new Set;for(let{index:t,transform:n}of this._bindings){let{data:r,size:i}=n.table;e.add(t);let a=this._tables.get(t);if(a&&a.data===r)continue;a?.texture.destroy();let o=this.device.createTexture({label:`${this.label}-${n.wgslConst}`,size:[i,i,i],dimension:`3d`,format:`rgba16float`,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST});this.device.queue.writeTexture({texture:o},r,{bytesPerRow:i*8,rowsPerImage:i},[i,i,i]),this._tables.set(t,{texture:o,data:r,view:o.createView()})}for(let[t,n]of this._tables)e.has(t)||(n.texture.destroy(),this._tables.delete(t))}ensureSize(e,t){if(this._ensurePipeline(),this._ensureTables(),this.width===e&&this.height===t&&this._storage)return;this._releaseBuffers();let n=e*t*d_[this.output];this._storage=this.device.createBuffer({label:`${this.label}-out`,size:n,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this._map=this.device.createBuffer({label:`${this.label}-map`,size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this._params=this.device.createBuffer({label:`${this.label}-params`,size:p_,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.width=e,this.height=t}async toRGBA8(e,t){return new Uint8ClampedArray(await this._run(e,t))}async toPlanar(e,t){return new Float32Array(await this._run(e,t))}async _run(e,{exposure:t=1,toneMapping:n=0,saturation:r=1,flipY:i=!1,preserveAlpha:a=!1}={}){if(this.disposed)throw Error(`PackedToneMapper: disposed`);if(!this._storage)throw Error(`PackedToneMapper: call ensureSize() first`);this._ensurePipeline(),this._ensureTables();let{width:o,height:s}=this,c=o*s*d_[this.output];this._paramU32[0]=o,this._paramU32[1]=s,this._paramU32[2]=n>>>0,this._paramU32[3]=+!!i,this._paramF32[4]=t,this._paramF32[5]=r,this._paramU32[6]=+!!a,this.device.queue.writeBuffer(this._params,0,this._paramData);let l=[...this._tables.entries()].map(([e,t])=>({binding:e,resource:t.view})),u=this.device.createBindGroup({layout:this._pipeline.getBindGroupLayout(0),entries:[...l,{binding:0,resource:this.input===`texture`?e.createView():{buffer:e,size:o*s*8}},{binding:1,resource:{buffer:this._storage}},{binding:2,resource:{buffer:this._params}}]}),d=this.device.createCommandEncoder({label:this.label}),f=d.beginComputePass();f.setPipeline(this._pipeline),f.setBindGroup(0,u),f.dispatchWorkgroups(Math.ceil(o/8),Math.ceil(s/8)),f.end(),d.copyBufferToBuffer(this._storage,0,this._map,0,c),this.device.queue.submit([d.finish()]),await this._map.mapAsync(GPUMapMode.READ);let p=this._map.getMappedRange().slice(0);return this._map.unmap(),p}release(){this._releaseBuffers(),this.width=this.height=0}_releaseBuffers(){this._storage?.destroy(),this._map?.destroy(),this._params?.destroy(),this._storage=null,this._map=null,this._params=null}dispose(){if(!this.disposed){this.disposed=!0,this._releaseBuffers();for(let e of this._tables.values())e.texture.destroy();this._tables.clear(),this._pipeline=null}}}}));h_(),Ao(),Fn(),X();var g_=class{constructor({issues:e=null}={}){this._issues=e,this._renderer=null,this._offRegistry=lo(()=>{this._renderer&&vo(this._renderer)})}get hasConfig(){return!1}get workingSpace(){return Dr}get workingSpaceAdopted(){return!1}get inputKey(){return`-`}attachRenderer(e){this._renderer=e;let t=vo(e);return e.outputColorSpace=r.SRGBColorSpace,t}listViews(){return fo()}get activeView(){return null}setActiveView(e){let t=uo(e);if(!t)throw Error(`no view transform with id ${e}`);if(t.outputEncoded)throw Error(`"${t.name}" returns display-encoded colour: it needs rayzee/addons/color`);return this._renderer&&(this._renderer.toneMapping=e),t}_publishWorkingMatrix(){On(null,Dr)}loadConfig(){let e=`colour configs need the OCIO pipeline: renderer.setColorManagement( ColorManagement ), from rayzee/addons/color`;return this._issues?.record(Y.CAPABILITY_MISSING,e,{capability:`color`}),Promise.reject(Error(e))}unloadConfig(){}setWorkingSpace(){}exportPixels(e){return{rgba:e,colorSpace:Dr}}status(){let e=this._renderer?uo(this._renderer.toneMapping):null;return{config:null,workingSpace:Dr,workingSpaceAdopted:!1,activeTransform:e?{id:e.id,name:e.name,source:e.source}:null,activeView:null,context:null,exportSpace:null,views:fo(),registryVersion:co(),bakeError:e?.error??null}}dispose(){this._offRegistry?.(),this._renderer=null,this._issues=null,kr()===this&&(On(null),Ar(null))}};dr();var __=[[/\.jpe?g(\?|#|$)/i,`image/jpeg`],[/\.webp(\?|#|$)/i,`image/webp`],[/\.avif(\?|#|$)/i,`image/avif`]];function v_(e){return e.mimeType?e.mimeType:e.uri?.startsWith(`data:`)?e.uri.slice(5,e.uri.indexOf(`;`)):__.find(([t])=>t.test(e.uri??``))?.[1]??`image/png`}function y_(e){for(let t=8;t+12<=e.length;){let n=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0,r=t+12+n;if(e[t+4]===73&&e[t+5]===69&&e[t+6]===78&&e[t+7]===68)return e.subarray(0,r);t=r}return e}function b_({data:e,width:t,height:n},{shared:i=!1}={}){let a=new Uint8Array(e.buffer,e.byteOffset,t*n*4),o=a;i&&typeof SharedArrayBuffer<`u`&&!(a.buffer instanceof SharedArrayBuffer)&&(o=new Uint8Array(new SharedArrayBuffer(a.byteLength)),o.set(a));let s=new r.DataTexture(o,t,n,r.RGBAFormat,r.UnsignedByteType);return s.needsUpdate=!0,s}function x_(e,t){return rr().decodeImage(t===`image/png`?y_(e):e,t)}async function S_(e){let t=await fetch(e);if(!t.ok)throw Error(`HTTP ${t.status}`);return new Uint8Array(await t.arrayBuffer())}function C_(e,t){return t.bufferView===void 0?S_(e.options.manager.resolveURL(r.LoaderUtils.resolveURL(t.uri,e.options.path))):e.getDependency(`bufferView`,t.bufferView).then(e=>new Uint8Array(e))}var w_=(e,t)=>!!t&&t!==e.textureLoader&&typeof t.parse==`function`;function T_(e,t,n){if(e.sourceCache[t]!==void 0)return e.sourceCache[t].then(e=>e.clone());let r=C_(e,e.json.images[t]).then(e=>new Promise((t,r)=>{n.parse(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),t,r)}));return e.sourceCache[t]=r,r}async function E_(e,t=v_({uri:e})){let n=b_(await x_(await S_(e),t));return n.flipY=!0,n}function D_(e,t=null){return e.loadImageSource=function(e,n){if(w_(this,n))return T_(this,e,n);let r=this.json.images[e],i=Error(`no image decoder in this runtime: configurePlatform( nodePlatform( { decodeImage } ) ) — see "Running in Node"`);return t?.(r.uri??`bufferView ${r.bufferView}`,i),Promise.reject(i)},{name:`RAYZEE_missing_image_decoder`}}function O_(e,t=null){return e.loadImageSource=function(e,n){if(w_(this,n))return T_(this,e,n);if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(e=>e.clone());let r=this.json.images[e],i=v_(r),a=r.uri??`bufferView ${r.bufferView}`,o=C_(this,r).then(e=>x_(e,i)).then(e=>{let t=b_(e,{shared:!0});return r.extras&&typeof r.extras==`object`&&Object.assign(t.userData,r.extras),t.userData.mimeType=i,t}).catch(e=>{throw t?.(a,e),e});return this.sourceCache[e]=o,o},{name:`RAYZEE_platform_images`}}var k_=`KHR_materials_diffuse_transmission`;function A_(e){let t=(t,n,r,i)=>{let a={};return e.assignTexture(a,n,r,i).then(()=>{a[n]&&(t[n]=a[n])})};return{name:k_,afterRoot(n){let i=e.json.materials??[],a=new Set,o=[];for(let s of n.scenes??[])s.traverse(n=>{let s=Array.isArray(n.material)?n.material:n.material?[n.material]:[];for(let n of s){if(a.has(n))continue;a.add(n);let s=e.associations.get(n)?.materials,c=s===void 0?null:i[s]?.extensions?.[k_];if(!c)continue;n.diffuseTransmission=c.diffuseTransmissionFactor??0;let[l,u,d]=c.diffuseTransmissionColorFactor??[1,1,1];n.diffuseTransmissionColor=new r.Color().setRGB(l,u,d,r.LinearSRGBColorSpace),c.diffuseTransmissionTexture&&o.push(t(n,`diffuseTransmissionMap`,c.diffuseTransmissionTexture)),c.diffuseTransmissionColorTexture&&o.push(t(n,`diffuseTransmissionColorMap`,c.diffuseTransmissionColorTexture,r.SRGBColorSpace))}});return Promise.all(o)}}}Br();var j_=`KHR_draco_mesh_compression`,M_=`KHR_texture_basisu`,N_=[`EXT_meshopt_compression`,`KHR_meshopt_compression`],P_=new TextDecoder;function F_(e){if(typeof e==`string`)return e;if(!(e instanceof ArrayBuffer))return JSON.stringify(e?.extensionsUsed??[]);let t=new DataView(e);if(!(e.byteLength>=20&&t.getUint32(0,!0)===1179937895))return P_.decode(e);let n=Math.min(t.getUint32(12,!0),e.byteLength-20);return P_.decode(new Uint8Array(e,20,n))}async function I_(e,t,n){let{dracoDecoderPath:r,ktx2TranscoderPath:i}=Lr(),[a,o,s]=await Promise.all([t.includes(j_)&&!e.dracoLoader?import(`three/addons/loaders/DRACOLoader.js`):null,t.includes(M_)&&!e.ktx2Loader?import(`three/addons/loaders/KTX2Loader.js`):null,N_.some(e=>t.includes(e))&&!e.meshoptDecoder?import(`three/addons/libs/meshopt_decoder.module.js`):null]);if(a){let t=new a.DRACOLoader;t.setDecoderConfig({type:`js`}),t.setDecoderPath(r),e.setDRACOLoader(t)}if(o){let t=new o.KTX2Loader;t.setTranscoderPath(i),n&&(t.detectSupport(n),t.workerConfig={astcSupported:!1,etc1Supported:!1,etc2Supported:!1,dxtSupported:!1,bptcSupported:!1,pvrtcSupported:!1}),e.setKTX2Loader(t)}s&&e.setMeshoptDecoder(s.MeshoptDecoder)}function L_(e,t){let n=e.parse.bind(e);return e.parse=(r,i,a,o)=>{I_(e,F_(r),t).then(()=>n(r,i,a,o),e=>o?.(e))},e}function R_(e){if(typeof e==`string`)try{let t=JSON.parse(e);return t&&typeof t==`object`?t:null}catch{return null}return e&&typeof e==`object`?e:null}function z_(e){let t=typeof e==`string`?parseFloat(e):e;return Number.isFinite(t)?t:void 0}function B_(e){let t=R_(e);if(!t)return null;let n=e=>e&&(e.environment!==void 0||e.render!==void 0),r=R_(t.rayzee);return n(r)?r:n(t)?t:null}function V_(e){let t=R_(e);if(!t)return null;let n=G_.map(e=>t[e]).find(e=>typeof e==`string`&&e.trim());if(!n)return null;let r=z_(t.rotation),i=z_(t.intensity),a={sourceFile:n.trim()};return r!==void 0&&(a.rotation=r),i!==void 0&&(a.intensity=Math.max(0,i)),a}function H_(e){let t=R_(e);if(!t)return null;let n={};for(let e of K_){let r=z_(t[e]);r!==void 0&&r>0&&(n[e]=Math.round(r))}return Object.keys(n).length?n:null}function U_(e){let t=B_(e);if(!t)return null;let n=V_(t.environment),r=H_(t.render);return!n&&!r?null:{...n?{environment:n}:{},...r?{render:r}:{}}}function W_(e){if(!e)return null;let t=[e.userData,e.asset?.extras,e.scene?.userData];Array.isArray(e.scenes)&&t.push(...e.scenes.map(e=>e?.userData));for(let e of t){let t=U_(e);if(t)return t}return null}var G_,K_,q_=g((()=>{G_=[`sourceFile`,`url`,`file`],K_=[`maxBounces`,`samples`,`width`,`height`]}));Yr(),fe(),dr(),q_(),X();var J_={glb:{type:`model`,name:`GLB (GLTF Binary)`},gltf:{type:`model`,name:`GLTF`},hdr:{type:`environment`,name:`HDR (High Dynamic Range)`},png:{type:`image`,name:`PNG`},jpg:{type:`image`,name:`JPEG`},jpeg:{type:`image`,name:`JPEG`},webp:{type:`image`,name:`WebP`}},Y_={addOn:`rayzee/addons/archives`,install:`assetLoader.setArchiveImporter()`},X_={addOn:`rayzee/addons/formats`,install:`assetLoader.registerFormat()`},Z_={zip:Y_,gz:Y_,tgz:Y_,tar:Y_,fbx:X_,obj:X_,stl:X_,ply:X_,dae:X_,"3mf":X_,usd:X_,usda:X_,usdc:X_,usdz:X_,exr:X_};function Q_(e){let t=new r.BufferGeometry;for(let n in e.attributes)t.setAttribute(n,e.attributes[n]);e.index&&t.setIndex(e.index);for(let n of e.groups)t.addGroup(n.start,n.count,n.materialIndex);return t}var $_=683;function ev(e,t,n,i){if(!(i.normalize??!0))return Math.PI;let a=i.shape===`ellipse`||i.shape===`disk`?Math.PI/4:1,o=e.getWorldScale(new r.Vector3),s=Math.PI*a*Math.abs(t*o.x*n*o.y);return Number.isFinite(s)?s:Math.PI}var tv=class e extends r.EventDispatcher{constructor(e,t,n,{issues:i=null,areaLightIntensityScale:a=null}={}){super(),this.scene=e,this.camera=t,this.controls=n,this.targetModel=null,this.floorPlane=null,this.sceneScale=1,this.sceneSize=new r.Vector3(1,1,1),this.loaderCache={},this.uploadedFileInfo=null,this.animations=[],this.renderer=null,this.sceneMetadata=null,this._loadingManager=new r.LoadingManager,this._loadCancelled=!1,this._urlAbort=null,this.storage=null,this._downloads=null,this._sourceKey=null,this._appended=!1,this.archives=null,this._archiveLoader=null,this._formats=new Map,this._issues=i,this._areaLightIntensityScale=a??(()=>G.areaLightIntensityScale),this._loadingManager.onError=e=>{this._loadCancelled||this._issues?.record(Y.ASSET_UNREACHABLE,`asset "${e}" could not be fetched — anything depending on it renders without it`,{url:e})}}cancelActiveLoad(){this._loadCancelled=!0,this._loadingManager.abort(),this._urlAbort?.abort()}async _viaCache(t,n,r,{cacheKey:i=t,cachePolicy:a}={}){if(!this.storage||!e._isNetworkUrl(t)||/\.gltf$/i.test(t.split(/[?#]/)[0]))return{url:t,release:()=>{},cached:!1};let o=new AbortController;this._urlAbort=o;try{return await Ig(t,{downloads:this.downloads,key:i,policy:a,name:kg(t),signal:o.signal,onProgress:this._downloadProgress(n,r)})}catch(e){throw this._isCancellation(e)?this._cancellationError():e}finally{this._urlAbort=null}}get sceneSourceKey(){return this._appended?null:this._sourceKey}_keyed(e,t){return t?`${e}::${t}`:null}get downloads(){return this._downloads?._storage!==this.storage&&(this._downloads=new Ng(this.storage)),this._downloads}_isCancellation(e){return this._loadCancelled||e?.name===`AbortError`||e?.code===`LOAD_CANCELLED`}_cancellationError(){let e=Error(`Load cancelled`);return e.code=`LOAD_CANCELLED`,e}_downloadProgress(e,t){return n=>{let r=n?.loaded||0,i=n?.lengthComputable&&n.total||0;z({isLoading:!0,status:e,loadedBytes:r,totalBytes:i,canCancel:!!t,progress:i?Math.min(60,2+Math.round(r/i*58)):2})}}_downloadComplete(e=`Processing Data...`,t=62){z({status:e,progress:t,canCancel:!1,loadedBytes:null,totalBytes:null})}static _isNetworkUrl(e){return typeof e==`string`&&/^https?:/i.test(e)}_adoptExternalObject(e){let t;try{t=(0,l.clone)(e)}catch(t){throw Error(`Cannot render "${e.name||e.type}": its userData must be JSON-serializable.`,{cause:t})}return t.userData.__rayzeeExternal=!0,this.scene?.children.some(t=>t.uuid===e.uuid)||(t.uuid=e.uuid),e.parent&&(e.parent.updateWorldMatrix(!0,!1),t.applyMatrix4(e.parent.matrixWorld)),t}releaseTargetModel(){this.sceneMetadata=null,this._sourceKey=null,this._appended=!1,this.archives?.release(),this.targetModel&&(this.removeModelRoot(this.targetModel),this.targetModel=null,this.animations=[])}setRenderer(e){this.renderer=e}setArchiveImporter(e){this.archives=e}setArchiveImporterLoader(e,t){this._archiveLoader={load:e,formats:t,pending:null}}async _archiveImporter(){return!this.archives&&this._archiveLoader&&(this.archives=await(this._archiveLoader.pending??=this._archiveLoader.load())),this.archives}get _archiveFormats(){return this.archives?.constructor.FORMATS??this._archiveLoader?.formats??null}registerFormat(...e){for(let t of e)for(let e of t.extensions)this._formats.set(e,t);return this}getFileFormat(e){let t=e.split(`.`).pop().toLowerCase();return J_[t]||this._formats.get(t)||this._archiveFormats?.[t]||null}formatError(e){let t=Z_[e.split(`.`).pop().toLowerCase()];return Error(t?`${e}: this format is read by ${t.addOn} — install it with ${t.install}`:`Unsupported file format: ${e}`)}async inspectArchive(e){let t=await this._archiveImporter();if(!t)throw this.formatError(e.name??`archive.zip`);return await t.inspectArchive(e)}flushPendingGraph(e){this.archives?.flushPendingGraph(e)}readFileAsArrayBuffer(e){return e.arrayBuffer()}readFileAsText(e){return e.text()}async loadAssetFromFile(e,t={}){let n=e.name,r=this.getFileFormat(n);if(!r)throw this.formatError(n);z({isLoading:!0,status:`Loading ${r.name}...`,progress:2});try{let i;switch(r.type){case`model`:i=await this.loadModelFromFile(e,n);break;case`environment`:case`image`:i=await this.loadEnvironmentFromFile(e,n);break;case`archive`:i=await(await this._archiveImporter()).loadArchiveFromFile(e,n,t);break;default:throw Error(`Unknown asset type: ${r.type}`)}return i}catch(e){throw e?.code!==`ARCHIVE_NEEDS_ELEMENT`&&this.dispatchEvent({type:`error`,message:e.message,filename:n}),e}}async loadFolder(e,t={}){let n=await this._archiveImporter();if(!n)throw Error(`${e.name}: folders are read by ${Y_.addOn} — install it with ${Y_.install}`);z({isLoading:!0,status:`Loading ${e.name}...`,progress:2});try{return await n.loadFolder(e,t)}catch(t){throw t?.code===`ARCHIVE_NEEDS_ELEMENT`?t.file=e:this.dispatchEvent({type:`error`,message:t.message,filename:e.name}),t}}async loadAssetFromUrl(t,n={}){let{filename:r=kg(t),cacheKey:i=t,cachePolicy:a,...o}=n;if(!this.getFileFormat(r))throw this.formatError(r);this._loadCancelled=!1;let s=e._isNetworkUrl(t),c=`Downloading ${r}...`,l=new AbortController;this._urlAbort=l,z({isLoading:!0,status:c,progress:2,canCancel:s,loadedBytes:0,totalBytes:0});let u;try{u=await this.downloads.fetch(t,{key:i,name:r,policy:a,signal:l.signal,onProgress:this._downloadProgress(c,s)})}catch(e){throw this._isCancellation(e)?this._cancellationError():e}finally{this._urlAbort=null}this._downloadComplete();try{return await this.loadAssetFromFile(u.file,o)}catch(e){throw e?.code===`ARCHIVE_NEEDS_ELEMENT`&&(e.file=u.file),e}finally{u.release()}}async loadModelFromFile(e,t){let n=this.storage?this._keyed(`file`,Ug(await Vg(e))):null,r=await this._loadModelFileByExtension(e,t);return this._sourceKey=n,r}async _loadModelFileByExtension(e,t){let n=t.split(`.`).pop().toLowerCase();if(n===`glb`||n===`gltf`)return await this.loadGLBFromArrayBuffer(await this.readFileAsArrayBuffer(e),t);let r=this._formats.get(n);if(r?.type!==`model`)throw this.formatError(t);return await this._loadModelWithFormat(r,e,t)}async _loadModelWithFormat(e,t,n){try{z({isLoading:!0,status:`Processing ${e.label} Data...`,progress:5}),await new Promise(e=>setTimeout(e,0));let{model:r,result:i=r}=await e.parse(t,{filename:n,cache:this.loaderCache});return this.releaseTargetModel(),this.targetModel=r,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r,filename:n}),i}catch(t){throw console.error(`Error loading ${e.label}:`,t),this.dispatchEvent({type:`error`,message:t.message,filename:n}),t}}async loadEnvironmentFromFile(e,t){let n=URL.createObjectURL(e);this.uploadedFileInfo={name:t,type:e.type,size:e.size};try{let r=await this.loadEnvironment(n);return Vr(r,Ug(await Vg(e))),this.dispatchEvent({type:`load`,texture:r,filename:t}),r}finally{URL.revokeObjectURL(n)}}async loadEnvironment(t){this._loadCancelled=!1;try{this.dispatchEvent({type:`beforeEnvironmentLoad`,url:t});let n;if(t.startsWith(`blob:`))n=await this.loadEnvironmentFromBlob(t);else{let e=t.split(/[?#]/)[0].split(`.`).pop().toLowerCase();n=await this.loadEnvironmentByExtension(t,e)}return n.generateMipmaps=!0,e._isNetworkUrl(t)&&Vr(n,t),this.applyEnvironmentToScene(n),this.dispatchEvent({type:`load`,texture:n,url:t,filename:t.split(/[?#]/)[0].split(`/`).pop()}),n}catch(e){throw this._isCancellation(e)?this._cancellationError():(console.error(`Error loading environment:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e)}}async loadEnvironmentFromBlob(e){let t=await(await fetch(e)).blob(),n=this.determineEnvironmentExtension(t,e),r=URL.createObjectURL(t);try{return await this.loadEnvironmentByExtension(r,n)}finally{URL.revokeObjectURL(r)}}determineEnvironmentExtension(e,t){let n;if(e.type===`image/x-exr`||e.type.includes(`exr`))n=`exr`;else if(e.type===`image/vnd.radiance`||e.type.includes(`hdr`))n=`hdr`;else{let e=t.split(`/`).pop();if(e){let t=e.match(/\.([^.]+)$/);t&&(n=t[1].toLowerCase())}}return!n&&this.uploadedFileInfo&&(n=this.uploadedFileInfo.name.split(`.`).pop().toLowerCase()),n}async loadEnvironmentByExtension(t,n,{loader:i=null}={}){let a=this._formats.get(n);if(!i&&a?.type===`environment`&&(i=this.loaderCache[n]??=await a.createLoader(this._loadingManager)),!i&&n===`hdr`&&(i=this.loaderCache.hdr??=new s.HDRLoader(this._loadingManager).setDataType(r.FloatType)),!i&&Z_[n])throw this.formatError(`environment.${n}`);let o=e._isNetworkUrl(t),c=`Downloading Environment...`,l=await this._viaCache(t,c,o),u=l.cached?void 0:this._downloadProgress(c,o),d;try{i?d=await i.loadAsync(l.url,u):rr().decodeImage?(d=await E_(l.url,`image/${n===`jpg`?`jpeg`:n}`),d.colorSpace=r.SRGBColorSpace):(this.loaderCache.texture||(this.loaderCache.texture=new r.TextureLoader(this._loadingManager)),d=await this.loaderCache.texture.loadAsync(l.url,u),d.colorSpace=r.SRGBColorSpace)}finally{l.release()}return this._downloadComplete(`Processing Environment...`,62),d.mapping=r.EquirectangularReflectionMapping,d.minFilter=r.LinearFilter,d.magFilter=r.LinearFilter,d}applyEnvironmentToScene(e){this.scene.background=e,this.scene.environment=e}async createGLTFLoader(){let e=L_(new o.GLTFLoader(this._loadingManager),this.renderer),t=(e,t)=>this._reportImageFailure(e,t);return rr().decodeImage?e.register(e=>O_(e,t)):ar()||e.register(e=>D_(e,t)),e.register(e=>A_(e)),e}_reportImageFailure(e,t){try{this._issues?.record(Y.TEXTURE_BUILD_FAILED,`image ${e} could not be decoded (${t?.message??t}) — the surfaces using it render untextured`,{image:e,cause:String(t?.message??t)})}catch(e){this._deferredError??=e}}_throwDeferred(){let e=this._deferredError;if(this._deferredError=null,e)throw e}_disposeGLTFLoader(e){e&&(e.dracoLoader?.dispose(),e.ktx2Loader?.dispose())}async loadExampleModels(e,t){if(!t||!t[e])throw Error(`No model file at index ${e}`);let n=`${t[e].url}`;return await this.loadModel(n)}async loadModel(t,n={}){this._loadCancelled=!1;let i=await this.createGLTFLoader(),a=e._isNetworkUrl(t),o=null;try{z({isLoading:!0,status:`Downloading Model...`,progress:2,canCancel:a,loadedBytes:0,totalBytes:0}),o=await this._viaCache(t,`Downloading Model...`,a,n),o.cached&&i.setResourcePath(r.LoaderUtils.extractUrlBase(t));let e=await sr(()=>i.loadAsync(o.url,o.cached?void 0:this._downloadProgress(`Downloading Model...`,a)));return this._downloadComplete(),this._throwDeferred(),this.releaseTargetModel(),this._sourceKey=a?this._keyed(`url`,n.cacheKey??t):null,this.targetModel=e.scene,this.animations=e.animations||[],this.sceneMetadata=W_(e),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:e.scene,filename:t.split(`/`).pop()}),e}catch(e){throw this._isCancellation(e)?this._cancellationError():(console.error(`Error loading model:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e)}finally{o?.release(),this._disposeGLTFLoader(i)}}_processAndParent(e){this.processModelObjects(e),this.scene.add(e),e.updateMatrixWorld(!0)}async appendModel(t,n={}){this._loadCancelled=!1;let i=await this.createGLTFLoader(),a=e._isNetworkUrl(t),o=null;try{z({isLoading:!0,status:`Downloading Model...`,progress:2,canCancel:a,loadedBytes:0,totalBytes:0}),o=await this._viaCache(t,`Downloading Model...`,a,n),o.cached&&i.setResourcePath(r.LoaderUtils.extractUrlBase(t));let e=await sr(()=>i.loadAsync(o.url,o.cached?void 0:this._downloadProgress(`Downloading Model...`,a)));return this._downloadComplete(),this._throwDeferred(),this._appended=!0,this._processAndParent(e.scene),{root:e.scene,animations:e.animations||[]}}catch(e){throw this._isCancellation(e)?this._cancellationError():e}finally{o?.release(),this._disposeGLTFLoader(i)}}appendObject3D(e,t=`object3d`){this._appended=!0;let n=this._adoptExternalObject(e);return n.name=e.name||t,this._processAndParent(n),{root:n}}removeModelRoot(e){e&&(e.userData.__rayzeeExternal?(ae(e),e.parent?.remove(e)):ie(e))}async loadGLBFromArrayBuffer(e,t=`model.glb`){let n=await this.createGLTFLoader();try{z({isLoading:!0,status:`Processing GLB Data...`,progress:5}),await new Promise(e=>setTimeout(e,0));let r=await sr(()=>n.parseAsync(e,``));return this._throwDeferred(),this.releaseTargetModel(),this.targetModel=r.scene,this.animations=r.animations||[],this.sceneMetadata=W_(r),z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r.scene,filename:t}),r}catch(e){throw console.error(`Error loading GLB:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}finally{this._disposeGLTFLoader(n)}}async loadObject3D(e,t=`object3d`){this.releaseTargetModel();let n=this._adoptExternalObject(e);return n.name=e.name||t,this.targetModel=n,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}async onModelLoad(e){let t=new us(`onModelLoad`);t.start(`Camera extraction`);let n=this.extractCamerasFromModel(e);t.end(`Camera extraction`),t.start(`Camera setup`);let i=new r.Box3().setFromObject(e),a=i.getCenter(new r.Vector3),o=i.getSize(new r.Vector3);this.controls?.target.copy(a);let s=Math.max(o.x,o.y,o.z),c=this.camera.fov*(Math.PI/180),l=Math.abs(s/Math.sin(c/2)/2),u=Math.PI/6,d=new r.Vector3(Math.cos(u)*l,l/Math.sqrt(2),Math.sin(u)*l);if(this.camera.position.copy(d.add(a)),this.camera.lookAt(a),this.camera.near=s/100,this.camera.far=s*100,this.camera.updateProjectionMatrix(),this.controls&&(this.controls.maxDistance=l*10,this.controls.saveState(),this.controls.update()),t.end(`Camera setup`),this.floorPlane){let e=i.min.y;this.floorPlane.position.y=e,this.floorPlane.rotation.x=-Math.PI/2,this.floorPlane.scale.setScalar(s*5)}t.start(`Process model objects`),this.processModelObjects(e),t.end(`Process model objects`),t.start(`Scene add`),this.scene.add(e),t.end(`Scene add`);let f=s;return this.sceneSize.copy(o),t.start(`setupPathTracing`),await this.setupPathTracing(e,f),t.end(`setupPathTracing`),t.print(),this.dispatchEvent({type:`modelProcessed`,model:e,cameras:n,sceneData:{center:a,size:o,maxDim:s,sceneScale:f}}),this.dispatchEvent({type:`SceneRebuild`}),{center:a,size:o,maxDim:s,sceneScale:f}}extractCamerasFromModel(e){let t=[];return e.updateWorldMatrix(!0,!0),e.traverse(e=>{if(e.isCamera){let n=e.clone();n.userData.__rayzeeSourceUuid=e.uuid,e.getWorldPosition(n.position),e.getWorldQuaternion(n.quaternion),e.getWorldScale(n.scale),n.scale.set(Math.sign(n.scale.x)||1,Math.sign(n.scale.y)||1,Math.sign(n.scale.z)||1),(!n.name||n.name===``)&&(n.name=`Model Camera ${t.length+1}`),n.isPerspectiveCamera&&(n.aspect=this.camera.aspect,n.updateProjectionMatrix()),t.push(n)}}),t}processModelObjects(e){let t=[],n=[];e.traverse(e=>{let i=e.userData;e.isRectAreaLight&&!i.__radianceConverted&&(e.intensity*=ev(e,e.width,e.height,i),i.__radianceConverted=!0),(e.isPointLight||e.isSpotLight)&&!i.__candelaConverted&&(e.intensity*=4*Math.PI/$_,i.__candelaConverted=!0),e.isDirectionalLight&&!i.__luxConverted&&(e.intensity/=$_,i.__luxConverted=!0);let a=e.name.startsWith(`RectAreaLightPlaceholder`);if(a&&!(i.name&&i.type===`RectAreaLight`)&&!e.parent?.name?.startsWith(`RectAreaLightPlaceholder`)&&n.push(e.name),a&&i.name&&i.type===`RectAreaLight`){let t=i.normalize??!0,n=i.shape??`rectangle`,a=i.intensity*ev(e,i.width,i.height,i),o=new r.RectAreaLight(new r.Color(...i.color),a*this._areaLightIntensityScale(),i.width,i.height);o.userData.normalize=t,o.userData.spread=Number.isFinite(i.spread)?i.spread:Math.PI,o.userData.shape=n,o.userData.__radianceConverted=!0,o.name=i.name,e.add(o)}e.isMesh&&Array.isArray(e.material)&&t.push(e)}),n.length&&this._issues?.record(Y.LIGHT_PLACEHOLDER_SKIPPED,`${n.length} area-light placeholder(s) lack userData.name or userData.type 'RectAreaLight' — no light was made for them`,{count:n.length,names:n.slice(0,10)});let i=e.userData.__rayzeeExternal===!0;for(let e of t){if(!e.parent)continue;console.log(`Found multi-material mesh:`,e.name),i&&(e.geometry=Q_(e.geometry));let t=(0,c.createMeshesFromMultiMaterialMesh)(e);for(let e of t.children)e.geometry.userData.__rayzeeOwned=!0;e.parent.add(t),e.parent.remove(e)}}async setupPathTracing(e,t){this.sceneScale=t}createFloorPlane(){this.floorPlane=new r.Mesh(new r.CircleGeometry,new r.MeshPhysicalMaterial({transparent:!1,color:3158064,roughness:1,metalness:0,opacity:0,transmission:0})),this.floorPlane.name=`Ground`,this.floorPlane.visible=!1,this.scene.add(this.floorPlane)}setFloorPlane(e){this.floorPlane=e}getSceneScale(){return this.sceneScale}getSceneSize(){return this.sceneSize.clone()}getTargetModel(){return this.targetModel}getSupportedFormats(e=null){let t={...J_,...this._archiveFormats};for(let[e,{type:n,name:r}]of this._formats)t[e]={type:n,name:r};if(e){let n={};for(let[r,i]of Object.entries(t))i.type===e&&(n[r]=i);return n}return t}dispose(){for(let e in this.loaderCache){let t=this.loaderCache[e];t&&typeof t.dispose==`function`&&t.dispose()}this.loaderCache={},this._listeners=void 0,this._loadingManager.onError=void 0,this._issues=null,this._urlAbort?.abort(),this._urlAbort=null,this.storage=null,this._downloads=null,this.archives?.release(),this.archives=null,this._archiveLoader=null,this.releaseTargetModel()}removeAllEventListeners(){this._listeners=void 0}},nv={addEventListener(){},removeEventListener(){},dispatchEvent(){return!0}},rv=class{constructor(e){this.canvas=e,this._configuration=null,this._texture=null}configure(e){this.unconfigure(),this._configuration=e}unconfigure(){this._texture?.destroy(),this._texture=null,this._configuration=null}getConfiguration(){return this._configuration}getCurrentTexture(){if(!this._configuration)throw Error(`HeadlessGPUContext: getCurrentTexture() before configure()`);let e=Math.max(1,this.canvas.width),t=Math.max(1,this.canvas.height);if(this._texture?.width!==e||this._texture?.height!==t){let{device:n,format:r,usage:i}=this._configuration;this._texture?.destroy(),this._texture=n.createTexture({label:`headless-canvas`,size:[e,t],format:r,usage:i})}return this._texture}};function iv(e=1,t=1){let n={...nv,defaultView:null},r={...nv,isHeadlessCanvas:!0,width:e,height:t,clientWidth:0,clientHeight:0,style:{},parentNode:null,ownerDocument:n,getRootNode:()=>n,getBoundingClientRect(){return{x:0,y:0,left:0,top:0,right:this.width,bottom:this.height,width:this.width,height:this.height}},setPointerCapture(){},releasePointerCapture(){},hasPointerCapture:()=>!1,focus(){},getContext:e=>e===`webgpu`?i:null},i=new rv(r);return r}var av=class extends r.PerspectiveCamera{constructor(e,t,n,r){super(e,t,n,r),this.orthographic=!1,this.orthoHalfHeight=1}get isPerspectiveCamera(){return!this.orthographic}set isPerspectiveCamera(e){}get isOrthographicCamera(){return this.orthographic}get top(){return this.orthoHalfHeight}get bottom(){return-this.orthoHalfHeight}get right(){return this.orthoHalfHeight*this.aspect}get left(){return-this.orthoHalfHeight*this.aspect}updateProjectionMatrix(){this.orthographic?r.OrthographicCamera.prototype.updateProjectionMatrix.call(this):super.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.orthographic=e.orthographic===!0,this.orthoHalfHeight=e.orthoHalfHeight??this.orthoHalfHeight,this}},ov=`__rayzeeUserLight`,sv={DirectionalLight:r.DirectionalLight,PointLight:r.PointLight,SpotLight:r.SpotLight,RectAreaLight:r.RectAreaLight},cv=class extends r.EventDispatcher{constructor(e,t,n,r={}){super(),this.scene=e,this.sceneHelpers=t,this.pathTracer=n,this._onReset=r.onReset||null,this._onLightRemoved=r.onLightRemoved||null}addLight(e){let t={DirectionalLight:{position:[1,1,1],intensity:1,color:`#ffffff`},PointLight:{position:[0,2,0],intensity:1e3,color:`#ffffff`},SpotLight:{position:[0,1,0],intensity:1e3,color:`#ffffff`,angle:15},RectAreaLight:{position:[0,2,0],intensity:100,color:`#ffffff`,width:2,height:2}}[e];if(!t)return null;let n;if(e===`DirectionalLight`)n=new r.DirectionalLight(t.color,t.intensity),n.position.fromArray(t.position);else if(e===`PointLight`)n=new r.PointLight(t.color,t.intensity),n.position.fromArray(t.position);else if(e===`SpotLight`){n=new r.SpotLight(t.color,t.intensity),n.position.fromArray(t.position),n.angle=r.MathUtils.degToRad(t.angle);let e=new r.Object3D;this.scene.add(e),n.target=e}else e===`RectAreaLight`&&(n=new r.RectAreaLight(t.color,t.intensity,t.width,t.height),n.position.fromArray(t.position),n.lookAt(0,0,0),n.userData.normalize=!0,n.userData.spread=Math.PI,n.userData.shape=`rectangle`);n.userData[ov]=!0,n.userData.temperature=6500,n.userData.useTemperature=!1,n.userData.exposure=0;let i=this.scene.getObjectsByProperty(`isLight`,!0).length;return n.name=`${e.replace(`Light`,``)} ${i+1}`,this.scene.add(n),this.updateLights(),this._syncHelpers(),this._onReset?.(),this._buildDescriptor(n)}getLight(e){let t=this.scene.getObjectByProperty(`uuid`,e);return t?.isLight?t:null}setIntensity(e,t){let n=this.getLight(e);return n?(n.intensity=t,this.updateLights(),this._onReset?.(),!0):!1}removeLight(e){let t=this.scene.getObjectByProperty(`uuid`,e);return!t||!t.isLight?!1:(this._onLightRemoved?.(t),this.sceneHelpers.remove(t),t.target&&t.target.removeFromParent(),t.removeFromParent(),this.updateLights(),this._onReset?.(),!0)}clearLights(){this.sceneHelpers.clear(),this._removeAllLights(),this.updateLights(),this._onReset?.()}getLights(){return this.scene.getObjectsByProperty(`isLight`,!0).map(e=>this._buildDescriptor(e))}updateLights(){this.pathTracer?.updateLights(),this.sceneHelpers?.visible&&this.sceneHelpers.update()}transferSceneLights(e,{keepUserLights:t=!1}={}){this._removeAllLights(t?e=>!e.userData?.[ov]:void 0);let n=e.getObjectsByProperty(`isLight`,!0);if(!n||n.length===0){this.updateLights();return}for(let e of n){let t=e.clone();if(e.updateWorldMatrix(!0,!1),e.getWorldPosition(t.position),e.getWorldQuaternion(t.quaternion),e.getWorldScale(t.scale),t.isRectAreaLight&&(t.width*=t.scale.x,t.height*=t.scale.y,t.scale.set(1,1,1)),(e.isSpotLight||e.isDirectionalLight)&&e.target){let n=new r.Object3D;e.target.updateWorldMatrix(!0,!1),e.target.getWorldPosition(n.position),this.scene.add(n),t.target=n}this.scene.add(t)}this.updateLights(),this._syncHelpers()}setShowLightHelper(e){this.sceneHelpers.visible=e,e?this._syncHelpers():this.sceneHelpers.clear()}serialize(){return this.scene.getObjectsByProperty(`isLight`,!0).map(e=>{let t={type:e.type,name:e.name,visible:e.visible,color:[e.color.r,e.color.g,e.color.b],intensity:e.intensity,position:e.position.toArray(),quaternion:e.quaternion.toArray(),scale:e.scale.toArray(),userData:In(e.userData)??{}};return e.isSpotLight&&Object.assign(t,{angle:e.angle,penumbra:e.penumbra,distance:e.distance,decay:e.decay}),e.isPointLight&&Object.assign(t,{distance:e.distance,decay:e.decay}),e.isRectAreaLight&&Object.assign(t,{width:e.width,height:e.height}),e.target&&(e.isSpotLight||e.isDirectionalLight)&&(t.target=e.target.position.toArray()),t})}restore(e){this.sceneHelpers?.clear(),this._removeAllLights();let t=[];for(let n of e??[]){let e=sv[n.type];if(!e)continue;let i=new e;i.name=n.name??``,i.visible=n.visible!==!1,i.color.setRGB(...n.color),i.intensity=n.intensity,i.position.fromArray(n.position),i.quaternion.fromArray(n.quaternion),i.scale.fromArray(n.scale??[1,1,1]),i.userData=Ln(n.userData)??{};for(let e of[`angle`,`penumbra`,`distance`,`decay`,`width`,`height`])typeof n[e]==`number`&&(i[e]=n[e]);if(n.target){let e=new r.Object3D;e.position.fromArray(n.target),this.scene.add(e),i.target=e}this.scene.add(i),t.push(i)}return this.updateLights(),this._syncHelpers(),this._onReset?.(),t}add(e){return this.addLight(e)}remove(e){return this.removeLight(e)}clear(){this.clearLights()}getAll(){return this.getLights()}sync(){this.updateLights()}showHelpers(e){this.setShowLightHelper(e)}dispose(){this._disposed||(this._disposed=!0,this._onLightRemoved=null,this.sceneHelpers?.clear(),this._removeAllLights(),this._onReset=null,this.pathTracer=null,this.sceneHelpers=null,this.scene=null)}_removeAllLights(e){this.scene.getObjectsByProperty(`isLight`,!0).filter(t=>!e||e(t)).forEach(e=>{this._onLightRemoved?.(e),e.target&&this.scene.remove(e.target),this.scene.remove(e)})}_syncHelpers(){if(!this.sceneHelpers.visible)return;let e=this.scene.getObjectsByProperty(`isLight`,!0);this.sceneHelpers.sync(e)}_buildDescriptor(e){let t=0;e.type===`SpotLight`&&e.angle!==void 0?t=r.MathUtils.radToDeg(e.angle):e.type===`DirectionalLight`&&(t=r.MathUtils.radToDeg(e.userData?.angle??0));let n={uuid:e.uuid,name:e.name,type:e.type,visible:e.visible,intensity:e.intensity,color:`#${e.color.getHexString()}`,position:[e.position.x,e.position.y,e.position.z],angle:t,temperature:e.userData?.temperature??6500,useTemperature:e.userData?.useTemperature??!1,exposure:e.userData?.exposure??0};if(e.type===`RectAreaLight`){n.width=e.width,n.height=e.height,n.normalize=e.userData?.normalize??!0,n.spread=r.MathUtils.radToDeg(e.userData?.spread??Math.PI);let t=e.userData?.shape;n.shape=t===`square`||t===`rectangle`||t===`disk`||t===`ellipse`?t:t===1?`ellipse`:`rectangle`;let i=e.getWorldDirection(e.position.clone());n.target=[e.position.x+i.x,e.position.y+i.y,e.position.z+i.z]}else e.type===`SpotLight`&&e.target?(n.target=[e.target.position.x,e.target.position.y,e.target.position.z],n.distance=e.distance??0,n.penumbra=e.penumbra??0,n.decay=e.decay??2):e.type===`PointLight`&&(n.distance=e.distance??0,n.decay=e.decay??2);return(e.type===`SpotLight`||e.type===`DirectionalLight`)&&e.userData?.gobo&&(n.gobo=e.userData.gobo.name,n.goboIntensity=e.userData.gobo.intensity,n.goboInverted=!!e.userData.gobo.inverted,e.type===`DirectionalLight`&&(n.goboScale=e.userData.gobo.scale??5)),e.type===`SpotLight`&&e.userData?.ies&&(n.ies=e.userData.ies.name,n.iesIntensity=e.userData.ies.intensity??1,n.fixtureLumens=e.userData.ies.fixtureLumens??null),n}};wt(),fe(),Ae(),I(),X(),Br(),Xg(),Ao(),Ra(),Ns();var lv=({element:e,pbrtEntry:t}={})=>({...e===void 0?{}:{element:e},...t===void 0?{}:{pbrtEntry:t}}),uv=new WeakMap,dv=new Set([...Object.values(P),...Object.values(F)]),fv=new Set;async function pv(e,t){if(!t||typeof self<`u`)return e.init();globalThis.self={requestAnimationFrame:()=>0,cancelAnimationFrame:()=>{}};try{return await e.init()}finally{delete globalThis.self}}var mv=ye(`engine`);function hv(){let e=new Float32Array(16);return new Uint32Array(e.buffer)[3]=St.TRIANGLE_LEAF,e}function gv(e,t){e.lost.then(e=>{t.app&&t.app._handleDeviceLost(e)})}var _v=/swiftshader|llvmpipe|lavapipe|basic render|microsoft basic|warp/i;function vv(e){let t=e.info??{},n=`${t.vendor??``} ${t.architecture??``} ${t.device??``} ${t.description??``}`;return{vendor:t.vendor??``,architecture:t.architecture??``,device:t.device??``,description:t.description??``,isSoftware:t.isFallbackAdapter===!0||e.isFallbackAdapter===!0||_v.test(n)}}var yv=class extends r.EventDispatcher{constructor(e,t={}){super(),this._headless=t.headless===!0||!e,e??=iv();try{uv.get(e)?.dispose()}catch(e){mv.warn(`prior canvas owner dispose failed`,e)}if(uv.set(e,this),this.canvas=e,this._autoResize=!this._headless&&t.autoResize!==!1,this._maxSceneBytes=t.maxSceneBytes,this._hostMemoryGB=t.hostMemoryGB,this._storageOption=t.storage,this._storageOpener=null,this._memorySpill=t.memorySpill===!0,this.storage=null,this._storageRelease=null,this._applySceneMetadataEnabled=t.applySceneMetadata!==!1,this._unlitRestore=null,this._applyingSceneMetadata=!1,t.profile!==void 0)throw Error("the `profile` option was removed: the engine has one set of defaults. For the old 'physical' profile set `areaLightIntensityScale: 1` and `dofMode: 'physical'` through `settings`.");this._issues=new Kt({strict:t.strict===!0,onIssue:e=>this.dispatchEvent({type:P.ISSUE,issue:e})}),this.color=new g_({issues:this._issues}),Ar(this.color),this.settings=new a_(G,{issues:this._issues}),this.renderer=null,this.scene=null,this.meshScene=null,this._sceneHelpers=null,this.assetLoader=null,this._sdf=null,this.pipeline=null,this._pendingReservedRenderSize=null,this.stages={},this.camera=null,this.lightManager=null,this.environmentManager=null,this.isInitialized=!1,this.pauseRendering=!1,this._pathTracerEnabled=!0,this._rasterPrecompile=null,this.animationManagerId=null,this.needsReset=!1,this._loadingInProgress=!1,this._needsDisplayRefresh=!1,this._paused=!1,this._emissiveSamplingUserSet=!1,this.completion=new Sg,this._resizeDebounceTimer=null,this._displayWidth=0,this._displayHeight=0,this._renderScale=1,this._renderWidth=0,this._renderHeight=0,this._trackedListeners=[],this._disposed=!1,this._deviceLost=!1,this._gpuDevice=null,this._deviceLostHolder=null,this._deterministic=!1,this._dispatchPinned=!1,this._deterministicRestore=null,this.adapterInfo=null}_addTrackedListener(e,t,n){e&&(e.addEventListener(t,n),this._trackedListeners.push({target:e,type:t,handler:n}))}_removeTrackedListeners(){for(let{target:e,type:t,handler:n}of this._trackedListeners)try{e.removeEventListener(t,n)}catch(e){mv.warn(`failed to remove listener`,t,e)}this._trackedListeners.length=0}async init(){let e=this._initStorage();return await this._initRenderer(),this._applyPendingReservedRenderSize(),this.camera=this._createCamera(),this._initScenes(),this._initAssetPipeline(),this._initPipeline(),await this._initManagers(),this._wireEvents(),await e,this._attachStorage(),this.stages.pathTracer.setTriangleData(new Uint32Array(K.FLOATS_PER_TRIANGLE),0),this.stages.pathTracer.setBVHData(hv()),this.stages.pathTracer.materialData.setMaterialData(new Float32Array(16)),this.stages.pathTracer.setupMaterial(),this.isInitialized=!0,mv.debug(`WebGPU path tracer app initialized`),this}async setStorageOpener(e){this._storageOpener=e,!(!this.isInitialized||this.storage||this._disposed)&&(await this._initStorage(),this._attachStorage())}async _initStorage(){let e=this._storageOption??(this._issues.strict&&!Ir(`storage`)?!1:Lr().storage);if(e!==!1){if(e&&typeof e==`object`)this.storage=e;else{if(!this._storageOpener){(this._storageOption!==void 0||Ir(`storage`))&&this._issues.warn(Y.CAPABILITY_MISSING,`on-disk storage needs rayzee/addons/storage: setStorageOpener( acquireSharedStorage )`);return}let{storage:e,reason:t,release:n}=await this._storageOpener(Lr().cacheNamespace);if(this._disposed){n();return}if(!e){this._issues.warn(Y.STORAGE_UNAVAILABLE,`on-disk storage is off: ${t}`,{reason:t});return}this.storage=e,this._storageRelease=n}this._addTrackedListener(this.storage,`change`,e=>this.dispatchEvent({type:P.STORAGE_CHANGED,area:e.area})),this._addTrackedListener(this.storage,`issue`,e=>this._issues.warn(e.code,e.message,e.detail))}}_attachStorage(){this.assetLoader&&(this.assetLoader.storage=this.storage)}dispatchEvent(e){super.dispatchEvent(e);let t=F[e.type];t&&super.dispatchEvent({...e,type:t})}addEventListener(e,t){!dv.has(e)&&!fv.has(e)&&(fv.add(e),mv.warn(`no engine event is named "${e}", so this listener will never fire — see EngineEvents`)),super.addEventListener(e,t)}animate(){if(this._headless)throw Error(`a headless app has no render loop — drive it with renderFrames() or renderUntilComplete()`);if(this._deviceLost)return;if(this.animationManagerId=requestAnimationFrame(()=>this.animate()),this._loadingInProgress||this._sdf?.isProcessing){this.dispatchEvent({type:P.FRAME});return}this._beginFrame();let e=this.needsReset;if(this.needsReset&&=(this.stages.pathTracer?.noteViewChanged(),this.reset(!0),!1),this.camera.updateMatrixWorld(),!this.pathTracerEnabled){this.renderer.render(this.meshScene,this.camera),this._renderHelperOverlay();return}if(!this.pauseRendering){if(this._beforeTrace(),this.stages.pathTracer?.isReady){if(this.stages.pathTracer.isComplete&&this.completion.renderCompleteDispatched){this._needsDisplayRefresh&&(this._needsDisplayRefresh=!1,this.stages.compositor.render(this.pipeline.context),this._renderHelperOverlay()),this.stopAnimation();return}if(this._holdTrace(e)){this._renderHelperOverlay(),this.dispatchEvent({type:P.FRAME});return}if(this.stages.pathTracer.readbackWait()){this.dispatchEvent({type:P.FRAME});return}this._traceFrame({liveDenoise:!0}),this.stages.pathTracer.isComplete&&this.completion.markComplete()&&(this._renderCompleted(),this.dispatchEvent({type:P.RENDER_COMPLETE,...this._completionInfo()}))}this._renderHelperOverlay(),this.dispatchEvent({type:P.FRAME})}}_traceFrame({liveDenoise:e=!1}={}){let t=this.stages.pathTracer;this.pipeline.render(),this._afterTrace(t,e),t.isComplete||this.completion.updateTime(),this._ensureVRAMWiring();let n=t.vramTracker,r=t.frameCount??0;n&&(r<=1||r%30==0)&&n.measure(),de({timeElapsed:this.completion.timeElapsed,samples:ee(t),memoryUsed:n?.current??0,memoryPeak:n?.peak??0}),this.completion.isTimeLimitReached(t,this.settings.get(`renderLimitMode`),this.settings.get(`renderTimeLimit`))&&(t.isComplete=!0)}_completionInfo(){return{samples:this.stages.pathTracer.frameCount,timeElapsed:this.completion.timeElapsed,budgetOverrun:this.completion.budgetOverrun,reason:this.completion.stopCondition(this.stages.pathTracer)??`samples`}}stopAnimation(){this.animationManagerId&&=(cancelAnimationFrame(this.animationManagerId),null)}_handleDeviceLost(e){this._deviceLost||(this._deviceLost=!0,mv.error(`WebGPU device lost (${e?.reason||`unknown`}): ${e?.message||``}`),this.stopAnimation(),this.dispatchEvent({type:P.DEVICE_LOST,reason:e?.reason,message:e?.message}))}wake(){this._deviceLost||this._headless||!this.animationManagerId&&this.isInitialized&&!this._paused&&this.animate()}pause(){this._paused=!0,this.stopAnimation()}resume(){this._paused=!1,!this.animationManagerId&&!this._headless&&this.animate()}reset(e=!1,{motion:t=!1}={}){t&&this.stages.pathTracer?.noteViewChanged(),this._beforeReset(e||t),this.pipeline&&(this.pipeline.reset(),e||this.pipeline.eventBus.emit(`pipeline:historyReset`)),this._afterReset(),this.completion.reset(),this.wake(),this.dispatchEvent({type:P.RENDER_RESET})}dispose(){if(!this._disposed){if(this._disposed=!0,this.dispatchEvent({type:P.DISPOSE}),this.stopAnimation(),clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=null,this._removeTrackedListeners(),L(null),this._storageRelease?.(),this._storageRelease=null,this.storage=null,this._sceneSource=this._sceneSourceInput=null,this._issues.detach(),this.color?.dispose(),this.color=null,this._textureReadback?.dispose(),this._textureReadback=null,this._readbackToneMapper?.dispose(),this._readbackToneMapper=null,this._disposeExtensions(),this.lightManager?.dispose(),this.pipeline?.dispose(),this._sdf?.dispose(),this._sdf=null,this.assetLoader?.dispose(),this.assetLoader=null,this.meshScene){this.meshScene.environment?.dispose(),this.meshScene.environment=null;for(let e of[...this.meshScene.children])ie(e);this.meshScene.clear(),this.meshScene=null}this._sceneHelpers?.clear(),this._sceneHelpers=null,this.scene?.clear(),this.scene=null;try{let e=(0,n.texture)().value,t=(0,n.cubeTexture)().value;e?._listeners?.dispose&&(e._listeners.dispose.length=0),t?._listeners?.dispose&&(t._listeners.dispose.length=0)}catch(e){mv.warn(`failed to clear TSL texture singleton listeners`,e)}this.canvas&&uv.get(this.canvas)===this&&uv.delete(this.canvas),this._gpuDevice&&=(this._gpuDevice.onuncapturederror=null,null),this._deviceLostHolder&&=(this._deviceLostHolder.app=null,null),re(this.renderer),this.renderer=null,this.stages={},this.isInitialized=!1}}unloadScene(){if(this.isInitialized){if(this._loadingInProgress)throw Error(`PathTracerApp.unloadScene: cannot unload while a load is in progress`);this._disposed||(this._releaseSceneState(),this.assetLoader?.releaseTargetModel(),this._sceneSource=this._sceneSourceInput=null,this.lightManager?.clearLights?.(),this.stages.pathTracer&&(this.stages.pathTracer.setTriangleData(new Uint32Array(K.FLOATS_PER_TRIANGLE),0),this.stages.pathTracer.setBVHData(hv()),this.stages.pathTracer.materialData.setMaterialData(new Float32Array(16)),this.stages.pathTracer.setEmissiveTriangleData?.(new Float32Array,0,0),this.stages.pathTracer.setupMaterial()),this._dropDisplay(),this.reset(),this.dispatchEvent({type:P.SCENE_UNLOADED}))}}async loadModel(e,t={}){await this._loadWithSceneRebuild(()=>this.assetLoader.loadModel(e,t),{type:P.MODEL_LOADED,url:e},{kind:`url`,url:e,cacheKey:t.cacheKey??null})}async loadObject3D(e,t=`object3d`){await this._loadWithSceneRebuild(()=>this.assetLoader.loadObject3D(e,t),{type:P.OBJECT3D_LOADED,name:t},{kind:`object3d`,name:t})}_busyError(e){let t=Error(`${e}: another load is already in progress`);return t.code=`LOAD_IN_PROGRESS`,t}async loadEnvironment(e){if(this._loadingInProgress)throw this._busyError(`PathTracerApp.loadEnvironment`);this._loadingInProgress=!0;try{await this.assetLoader.loadEnvironment(e);let t=this.meshScene.environment;t&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(t),this.pipeline?.eventBus.emit(`pipeline:lightingChanged`),this.reset(),this.dispatchEvent({type:P.ENVIRONMENT_LOADED,url:e})}finally{this._loadingInProgress=!1}}async inspectArchive(e){return await this.assetLoader.inspectArchive(e)}async loadFile(e,t={}){if(t=this._sceneBudgets(t),typeof e==`string`){let n=t.filename??kg(e),r=this.assetLoader?.getFileFormat(n);if(!r)throw this.assetLoader.formatError(n);if(r.type===`environment`||r.type===`image`)return this.loadEnvironment(e);await this._loadWithSceneRebuild(()=>this.assetLoader.loadAssetFromUrl(e,{...t,filename:n}),{type:P.MODEL_LOADED,filename:n},{kind:`url`,url:e,filename:n,cacheKey:t.cacheKey??null,...lv(t)});return}if(e_(e)){let n=Zg(e,{isModel:e=>this.assetLoader?.getFileFormat(e)?.type===`model`});if(n.files.length===0)throw Error(`${n.name} holds no files to load`);await this._loadWithSceneRebuild(()=>this.assetLoader.loadFolder(n,t),{type:P.MODEL_LOADED,filename:n.name},async()=>{let e=await Hg(n);return{kind:`local-folder`,folder:e,key:Ug(e),...n.flat?{flat:!0}:{},...lv(t)}}),this._sceneSourceInput=n;return}let n=this.assetLoader?.getFileFormat(e?.name||``);if(!n)throw this.assetLoader.formatError(e?.name||``);if(n.type!==`environment`&&n.type!==`image`){let n=Vg(e).catch(()=>({name:e.name,size:e.size,lastModified:e.lastModified??0,sample:null}));await this._loadWithSceneRebuild(()=>this.assetLoader.loadAssetFromFile(e,t),{type:P.MODEL_LOADED,filename:e.name},async()=>{let e=await n;return{kind:`local-file`,file:e,key:e.sample?Ug(e):null,...lv(t)}}),this._sceneSourceInput=e;return}if(this._loadingInProgress)throw this._busyError(`PathTracerApp.loadFile`);this._loadingInProgress=!0;try{await this.assetLoader.loadAssetFromFile(e);let t=this.meshScene.environment;t&&this.stages.pathTracer&&await this.stages.pathTracer.environment.applyHDRI(t),this.pipeline?.eventBus.emit(`pipeline:lightingChanged`),this.reset(),this.dispatchEvent({type:P.ENVIRONMENT_LOADED,filename:e.name})}finally{this._loadingInProgress=!1}}async loadExampleModels(e,t){await this._loadWithSceneRebuild(()=>this.assetLoader.loadExampleModels(e,t),{type:P.MODEL_LOADED,index:e},{kind:`url`,url:t[e]?.url??null,cacheKey:null})}cancelLoad(){this._loadingInProgress&&this.assetLoader?.cancelActiveLoad()}async setMaxTextureSize(e,{reprocess:t=!0}={}){let n=this.settings.get(`maxTextureSize`),r=this._sdf?.setMaxTextureSize(e)??e;if(this.settings.set(`maxTextureSize`,r,{reset:!1}),typeof this.stages?.pathTracer?.sdfs?.setMaxTextureSize==`function`&&this.stages.pathTracer.sdfs.setMaxTextureSize(r),t&&r!==n&&this._sdf?.triangles&&!this._loadingInProgress){this._loadingInProgress=!0;try{await this.loadSceneData(),this.reset(),this.dispatchEvent({type:P.TEXTURES_REPROCESSED,maxTextureSize:r})}finally{this._loadingInProgress=!1}}}get sceneSource(){return this._sceneSource??null}get sceneSourceFile(){return this._sceneSourceInput&&!e_(this._sceneSourceInput)?this._sceneSourceInput:null}get sceneSourceFolder(){return e_(this._sceneSourceInput)?this._sceneSourceInput:null}async _loadWithSceneRebuild(e,t,n=null){if(this._loadingInProgress)throw this._busyError(`PathTracerApp`);this._loadingInProgress=!0;try{await e(),this._sceneSource=typeof n==`function`?await n():n,this._sceneSourceInput=null,this._emissiveSamplingUserSet=!1,this._clearAppendedModels(),this._modelReplaced(),await this.loadSceneData({pendingEnvironment:this._beginSceneMetadataEnvironment()}),this._maybeSpill(),this.pipeline?.eventBus.emit(`pipeline:lightingChanged`),this._dropDisplay(),this.reset(),this.dispatchEvent(t),this._modelAnnounced()}catch(e){throw(!e||e.code!==`LOAD_IN_PROGRESS`)&&this._discardFailedLoad(),e?.code===`ARCHIVE_NEEDS_ELEMENT`?ue():e?.code!==`LOAD_IN_PROGRESS`&&z({status:`Error: ${e?.message??e}`,failed:!0,progress:100}),e}finally{this._loadingInProgress=!1}}_discardFailedLoad(){this._sceneSource=this._sceneSourceInput=null;try{this._clearAppendedModels(),this.assetLoader?.releaseTargetModel(),this._dropDisplay(),this.reset()}catch(e){console.warn(`PathTracerApp: could not clear the scene after a failed load`,e)}}get sceneMetadata(){return this.assetLoader?.sceneMetadata??null}_beginSceneMetadataEnvironment(){this._restoreUnlitSettings();let e=this.sceneMetadata?.environment;return this._applySceneMetadataEnabled&&e?.enabled===!1?(this._applyUnlitSettings(),null):!this._applySceneMetadataEnabled||!e?.sourceFile||!this.stages.pathTracer?null:(this.stages.pathTracer.environment.beginHDRI(),this._applyingSceneMetadata=!0,this.assetLoader.loadEnvironment(e.sourceFile).catch(t=>(this._issues.record(Y.ENVIRONMENT_LOAD_FAILED,`authored environment "${e.sourceFile}" failed to load — lighting falls back to the previous environment`,{sourceFile:e.sourceFile,cause:String(t?.message??t)}),null)).finally(()=>{this._applyingSceneMetadata=!1}))}_applySceneMetadataSettings(e){let t=this.sceneMetadata,n=t?.environment;if(!n||n.enabled===!1)return;let r={enableEnvironment:!0,showBackground:!0,transparentBackground:!1};n.intensity!==void 0&&(r.environmentIntensity=n.intensity,r.backgroundIntensity=n.intensity),n.rotation!==void 0&&(r.environmentRotation=n.rotation),this.settings.setMany(r,{reset:!1,source:i_.SCENE_METADATA}),this.scene&&(this.scene.background=e),this.dispatchEvent({type:P.SCENE_METADATA_APPLIED,metadata:t,environment:{...n}})}_applyUnlitSettings(){let e=this.settings.getEffective(),t={enableEnvironment:!1,showBackground:!1};this._unlitRestore=Object.fromEntries(Object.keys(t).map(t=>[t,{value:e[t].value,source:e[t].source}])),this.settings.setMany(t,{reset:!1,source:i_.SCENE_METADATA}),this.dispatchEvent({type:P.SCENE_METADATA_APPLIED,metadata:this.sceneMetadata,environment:{enabled:!1}})}_restoreUnlitSettings(){let e=this._unlitRestore;if(!e)return;this._unlitRestore=null;let t=this.settings.getEffective();for(let[n,{value:r,source:i}]of Object.entries(e))t[n]?.source===i_.SCENE_METADATA&&this.settings.set(n,r,{reset:!1,source:i});this.dispatchEvent({type:P.SCENE_METADATA_APPLIED,metadata:this.sceneMetadata,environment:{enabled:this.settings.get(`enableEnvironment`)}})}async loadSceneData({pendingEnvironment:e=null,keepUserLights:t=!1}={}){this._releaseSceneState({keepSelection:!!this._preserveSelectionOnRebuild}),this._tagPrimarySceneObject();let n=new us(``,{namespace:`scene`,level:`info`}),r=()=>this.stages.pathTracer.environment.envParams.mode===`hdri`?this.meshScene.environment:null,i=r(),a=null;if(e?(n.start(`Environment fetch + CDF (concurrent)`),a=e.then(async e=>{e&&(await this.stages.pathTracer.environment.applyHDRI(e),this._applySceneMetadataSettings(e))}).catch(e=>this._issues.record(Y.ENVIRONMENT_LOAD_FAILED,`authored environment failed to install — the scene is lit by whatever was already loaded`,{cause:String(e?.message??e)})).finally(()=>n.end(`Environment fetch + CDF (concurrent)`))):i?.image?.data&&(n.start(`Environment CDF build (worker)`),this.stages.pathTracer.scene.environment=i,a=this.stages.pathTracer.environment.buildEnvironmentCDF().then(()=>{n.end(`Environment CDF build (worker)`),this._applySceneMetadataEnabled&&this._applySceneMetadataSettings(i)})),n.start(`BVH build (SceneProcessor)`),this._sdf.setMaxTextureSize(this.settings.get(`maxTextureSize`)),await this._sdf.buildBVH(this.meshScene,{sceneKey:this.assetLoader?.sceneSourceKey??null,progressive:this._progressiveSpill()}),this.assetLoader?.flushPendingGraph(this._sdf.performanceMetrics.totalProcessingTime),n.end(`BVH build (SceneProcessor)`),z({status:`Transferring data to GPU...`,progress:86}),await new Promise(e=>setTimeout(e,0)),n.start(`GPU data transfer`),!this._sdf.uploadToPathTracer(this.stages.pathTracer,this.lightManager,this.meshScene,r(),{keepUserLights:t}))return!1;this.stages.pathTracer._meshRefs=this.stages.pathTracer._collectMeshRefs(this.meshScene),this.stages.pathTracer.setMeshVisibilityData(this.stages.pathTracer._meshRefs),this._refreshEmissiveForVisibility(),n.end(`GPU data transfer`),z({status:`Compiling shaders...`,progress:90}),await new Promise(e=>setTimeout(e,0)),n.start(`Material setup (TSL compile)`),this.stages.pathTracer.setupMaterial(),n.end(`Material setup (TSL compile)`),this._rasterPrecompile=null,this._pathTracerEnabled||(n.start(`Pipeline precompile`),await this.precompileRaster(),n.end(`Pipeline precompile`)),a&&(z({status:`Finalizing environment map...`,progress:95}),await a,this.stages.pathTracer.environment.applyCDFResults());let o=this.getSceneMinY();if(this.settings.set(`groundProjectionLevel`,o,{reset:!1}),this.settings.set(`groundCatcherHeight`,o,{reset:!1}),!this._emissiveSamplingUserSet){let e=(this._sdf?.emissiveTriangleBuilder?.emissiveTriangles?.length??this._sdf?.emissiveTriangleCount??0)>0;this.settings.set(`enableEmissiveTriangleSampling`,e,{reset:!1})}return n.start(`Apply settings`),this.settings.applyAll(),this.stages.compositor.setTransparentBackground(this.settings.get(`transparentBackground`)),n.end(`Apply settings`),n.print(this._sceneSummaryParts()),ue(),this._sceneRebuilt(),this.dispatchEvent({type:P.SCENE_REBUILD}),!0}_sceneSummaryParts(){let e=this.stages.pathTracer,t=this._sdf?.instanceTable?.setCount??0,n=this._sdf?.geometryExtractor?.maps?.length??0;return[H.count(e.triangleCount,`tri`),t?H.count(t,`mesh`,`meshes`):null,H.count(e.materialData.materialCount,`material`),n?H.count(n,`map`):null,H.count(e.bvhNodeCount,`BVH node`)]}_tagPrimarySceneObject(){let e=this.sceneModel;e&&(e.userData.__rayzeeSceneObject=!0)}_clearAppendedModels(){let e=this.meshScene;if(!e)return;let t=this.assetLoader?.floorPlane,n=this.sceneModel;for(let r of[...e.children])r===t||r===n||r.userData?.__rayzeeSceneObject&&this.assetLoader.removeModelRoot(r)}async _finishRebuildNoReframe(e){await this.loadSceneData({keepUserLights:!0}),this._maybeSpill(),this._sceneBoundsChanged(),this.pipeline?.eventBus.emit(`pipeline:lightingChanged`),this.reset(),e&&this.dispatchEvent(e)}async addModel(e,{name:t,cacheKey:n}={}){if(this._loadingInProgress)throw Error(`PathTracerApp.addModel: another load is already in progress`);this._loadingInProgress=!0,this._preserveSelectionOnRebuild=!0;try{let{root:r}=await this.assetLoader.appendModel(e,{cacheKey:n});return r.userData.__rayzeeSceneObject=!0,r.userData.__rayzeeSourceUrl=e,n&&(r.userData.__rayzeeCacheKey=n),t&&(r.userData.__rayzeeName=t),await this._finishRebuildNoReframe({type:P.MODEL_ADDED,url:e,id:r.uuid}),r.uuid}finally{this._preserveSelectionOnRebuild=!1,this._loadingInProgress=!1}}async addModelFromObject3D(e,{name:t}={}){if(this._loadingInProgress)throw Error(`PathTracerApp.addModelFromObject3D: another load is already in progress`);this._loadingInProgress=!0,this._preserveSelectionOnRebuild=!0;try{let{root:n}=this.assetLoader.appendObject3D(e,t||`object3d`);return n.userData.__rayzeeSceneObject=!0,t&&(n.userData.__rayzeeName=t),await this._finishRebuildNoReframe({type:P.MODEL_ADDED,id:n.uuid}),n.uuid}finally{this._preserveSelectionOnRebuild=!1,this._loadingInProgress=!1}}async removeSceneObject(e){if(!this.meshScene)return!1;let t=this.assetLoader?.floorPlane;if(t&&t.uuid===e)return!1;let n=this.getSceneObject(e);if(!n)return!1;if(this._loadingInProgress)throw Error(`PathTracerApp.removeSceneObject: another load is already in progress`);this._loadingInProgress=!0;try{return this._releaseSceneState(),n===this.sceneModel?this.assetLoader.releaseTargetModel():this.assetLoader.removeModelRoot(n),await this._finishRebuildNoReframe({type:P.SCENE_OBJECT_REMOVED,id:e}),!0}finally{this._loadingInProgress=!1}}setSceneObjectVisibility(e,t){return this.setMeshVisibilityByUuid(e,t)}_sceneBudgets(e){return!this._memorySpill||!this.storage?e:{maxTriangles:Na,maxPlacements:Pa,...e}}_progressiveSpill(){if(!this._memorySpill||!this.storage||(this.assetLoader?.animations?.length??0)>0)return null;let e=this.stages.pathTracer;return{storage:this.storage,uploader:(t,n)=>n===`triangles`?e.createTriangleChunkUploader(t):e.createChunkUploader(t)}}_maybeSpill(){!this._memorySpill||!this.storage||(this.assetLoader?.animations?.length??0)>0||this._sdf?.spillToDisk(this.storage).then(e=>e&&this.dispatchEvent({type:P.SCENE_SPILLED,...e})).catch(e=>this._issues.warn(Y.STORAGE_WRITE_FAILED,`memory spill failed: ${e.message}`))}async ensureSceneResident(){this._sdf?.spilled&&await this._sdf.ensureResident()}get sceneMeshes(){return this._sdf?.meshes??[]}get sceneModel(){return this.assetLoader?.targetModel??null}getSceneObject(e){let t=this.meshScene?.children.find(t=>t.uuid===e);return t?.userData?.__rayzeeSceneObject?t:null}async refitBVH(e,t){await this.ensureSceneResident();let{triRanges:n,bvhRanges:r,...i}=await this._sdf.refitBVH(e,t);return this.stages.pathTracer.updateTriangleData(this._sdf.triangles,n),this.stages.pathTracer.updateBVHData(this._sdf.bvh,r),this.reset(!1,{motion:!0}),i}refitBLASes(e,t,n){if(this._sdf?.spilled)throw Error(`refitBLASes: the scene is spilled to disk — await app.ensureSceneResident() first`);let r=this._sdf.refitBLASes(e,t,n),{triRanges:i,bvhRanges:a}=this._sdf.computeBLASDirtyRanges(e);return this.stages.pathTracer.updateBufferRanges(i,a),this.reset(!1,{motion:!0}),this._sdf.scheduleBackgroundRebuild(e,e=>{let t=this._sdf.computeBLASDirtyRanges([e]);this.stages.pathTracer.updateBufferRanges(t.triRanges,t.bvhRanges),this.reset(!1,{motion:!0})}),r}updateMeshTransforms(e){this._notePlacementsMoving(e);let t=this._sdf.updateMeshTransforms(e);return this.stages.pathTracer.updateBufferRanges([],[this._sdf.computeTLASDirtyRange()]),this.reset(!1,{motion:!0}),t}setReservedRenderResolution(e,{allowLower:t=!1}={}){let n=t?e:Math.max(e,U);if(!this.renderer)return this._pendingReservedRenderSize={requestedPx:e,allowLower:t},Math.max(256,Math.min(je,Math.floor(n)||256));let r=this.renderer.backend?.device?.limits?.maxStorageBufferBindingSize||128*1024*1024,i=Ca(this._hostMemoryGB),a=i.gb>=8&&r>=1024*1024*1024?je:2048,o=Me(Math.min(n,a));if(o<Math.floor(e)&&this._issues.warn(Y.RENDER_RESERVE_CAPPED,`reserved render size ${H.n(e)}px was capped to ${H.n(o)}px by this device's limits — renders above ${H.n(o)}px will be declined`+(i.assumed&&i.gb<8?` (host memory unknown, 4 GB assumed: pass hostMemoryGB)`:``),{requested:e,applied:o,deviceMemoryGB:i.gb,assumed:i.assumed,maxStorageBufferBindingSize:r}),(this.stages?.pathTracer?.storageTextures?.writeColor?.image?.width??o)!==o){let e=this.pauseRendering;this.pauseRendering=!0;try{let e=this.renderer.domElement;(e.width>o||e.height>o)&&this.renderer.setSize(Math.min(e.width,o),Math.min(e.height,o),!1);for(let e of Object.values(this.stages))e?.reallocateReservedStorage?.()}finally{this.pauseRendering=e}this.reset(),this.dispatchEvent({type:P.RESERVED_RENDER_SIZE_CHANGED,size:o})}return o}_applyPendingReservedRenderSize(){let e=this._pendingReservedRenderSize;if(!e)return;this._pendingReservedRenderSize=null;let t=this.setReservedRenderResolution(e.requestedPx,{allowLower:e.allowLower});this.dispatchEvent({type:P.RESERVED_RENDER_SIZE_CHANGED,size:t})}getReservedRenderResolution(){return U}_isRenderSizeSupported(e,t){return e>U||t>U?(this._issues.record(Y.RENDER_SIZE_DECLINED,`render resolution ${e}×${t} exceeds the ${U}px storage reserve — resize ignored, so output stays at the previous size. Raise it with setReservedRenderResolution( ${Math.max(e,t)} ) before init().`,{width:e,height:t,reserve:U}),!1):!0}onResize(){let e=this.canvas.clientWidth,t=this.canvas.clientHeight;e===0||t===0||this._isRenderSizeSupported(e,t)&&(this.renderer.setPixelRatio(1),this._setDisplaySize(e,t),!(e===this._renderWidth&&t===this._renderHeight)&&(clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=setTimeout(()=>{this._applyRenderResize(e,t)},300)))}_applyRenderResize(e,t){this._isRenderSizeSupported(e,t)&&(this.pipeline?.setSize(this._scaled(e),this._scaled(t)),this._renderWidth=e,this._renderHeight=t,this._renderSizeChanged(e,t),this.needsReset=!0,this.dispatchEvent({type:P.RESOLUTION_CHANGED,width:e,height:t}))}setCanvasSize(e,t){return e===0||t===0||!this._isRenderSizeSupported(e,t)?null:(this.renderer.setPixelRatio(1),this._setDisplaySize(e,t),clearTimeout(this._resizeDebounceTimer),this._applyRenderResize(e,t),{width:e,height:t})}_scaled(e){return Math.max(1,Math.round(e*this._renderScale))}_setDisplaySize(e,t){this._displayWidth=e,this._displayHeight=t,this.renderer.setSize(this._scaled(e),this._scaled(t),!1),this.camera.aspect=e/t,this.camera.updateProjectionMatrix()}refreshFrame(){this._needsDisplayRefresh=!0,this.wake()}setDeterministicMode(e=!0,{pinDispatch:t=!0}={}){let n=this.stages.pathTracer;if(!n)return!1;if(e)this._deterministicRestore||={settings:{useAdaptiveSampling:this.settings.get(`useAdaptiveSampling`),usePixelFreeze:this.settings.get(`usePixelFreeze`),interactionModeEnabled:this.settings.get(`interactionModeEnabled`),renderLimitMode:this.settings.get(`renderLimitMode`),renderTimeLimit:this.settings.get(`renderTimeLimit`)},bounceEarlyExit:n._bounceEarlyExitThreshold,dynamicDispatch:n._useDynamicDispatch,extras:this._deterministicSnapshot()},this.settings.setMany({useAdaptiveSampling:!1,usePixelFreeze:!1,interactionModeEnabled:!1,renderLimitMode:`frames`,renderTimeLimit:0},{silent:!0}),t?(n._bounceEarlyExitThreshold=-1,n._useDynamicDispatch=!1):(n._bounceEarlyExitThreshold=this._deterministicRestore.bounceEarlyExit,n._useDynamicDispatch=this._deterministicRestore.dynamicDispatch),this._setDeterministicExtras(!0,this._deterministicRestore.extras),n._pinSeedToFrame=!0,this._deterministic=!0,this._dispatchPinned=t;else if(this._deterministicRestore){let e=this._deterministicRestore;this.settings.setMany(e.settings,{silent:!0}),n._bounceEarlyExitThreshold=e.bounceEarlyExit,n._useDynamicDispatch=e.dynamicDispatch,this._setDeterministicExtras(!1,e.extras),n._pinSeedToFrame=!1,this._deterministicRestore=null,this._deterministic=!1,this._dispatchPinned=!1}return this.reset(),this.stopAnimation(),this._deterministic}get issues(){return this._issues.list}get issueErrors(){return this._issues.errors}clearIssues(){this._issues.clear()}get isDeterministic(){return this._deterministic&&this._dispatchPinned}async renderFrames(e,{reset:t=!0,yieldEvery:n=8,onProgress:r,allowEarlyRetire:i=!1}={}){let a=this.stages.pathTracer;if(!a)throw Error(`renderFrames: app is not initialized`);if(!(e>0))throw Error(`renderFrames: count must be positive, got ${e}`);let o=(t?0:a.frameCount)+e;this.settings.get(`maxSamples`)<o&&this.settings.set(`maxSamples`,o,{silent:!0,reset:!1}),t&&this.reset(),this.stopAnimation();let s=e+64,c=0,l=!1;for(;a.frameCount<o&&c<s;){if(this._deviceLost)throw Error(`renderFrames: WebGPU device lost`);if(!a.isReady)throw Error(`renderFrames: path tracer stage is not ready`);let e=a.readbackWait();if(e){await this._awaitReadback(e);continue}if(this.camera.updateMatrixWorld(),this.pipeline.render(),c++,a.isComplete&&a.frameCount<o){l=!0;break}r?.(a.frameCount),n>0&&c%n===0&&await new Promise(e=>setTimeout(e,0))}if(a.frameCount<o&&!(l&&i)){let e=l?"adaptive sampling retired the frame at the convergence threshold — pass `allowEarlyRetire: true`, or disable it with setDeterministicMode()":`something retired the render (maxSamples, a stray reset, or a canvas resize)`;throw Error(`renderFrames: stopped at ${a.frameCount}/${o} samples after ${c} passes — ${e}`)}return a.frameCount}async renderUntilComplete({reset:e=!0,denoise:t=!0,signal:n,drainEvery:r=4,onProgress:i}={}){let a=this.stages.pathTracer;if(!a)throw Error(`renderUntilComplete: app is not initialized`);if(this._loadingInProgress||this._sdf?.isProcessing)throw Error(`renderUntilComplete: a scene is still loading`);let o=a.lockstepReadbacks;a.setLockstepReadbacks(!0);let s=this.settings.getEffective().interactionModeEnabled;this.settings.set(`interactionModeEnabled`,!1,{silent:!0,reset:!1});try{e&&this.reset(),this.stopAnimation();let o=this.renderer.backend.device?.queue,s=0,c=null;for(;!a.isComplete;){if(n?.throwIfAborted(),this._deviceLost)throw Error(`renderUntilComplete: WebGPU device lost`);if(!a.isReady)throw Error(`renderUntilComplete: path tracer stage is not ready`);let e=a.readbackWait();if(e){await this._awaitReadback(e);continue}this.camera.updateMatrixWorld();let t=a.frameCount;if(this._traceFrame(),i?.(a.frameCount),a.frameCount===t&&!a.isComplete&&await new Promise(e=>setTimeout(e,0)),o&&r>0&&++s%r===0){let e=o.onSubmittedWorkDone();c&&await c,c=e}}let l=this._completionInfo();this.completion.markComplete()&&this.dispatchEvent({type:P.RENDER_COMPLETE,...l});let u=t?await this._finalDenoise():!1,{reason:d,...f}=l;return{...f,retiredBy:d,denoised:u}}finally{a.setLockstepReadbacks(o),s&&this.settings.set(`interactionModeEnabled`,s.value,{silent:!0,reset:!1,source:s.source})}}getProvenance(){let e=this.stages.pathTracer,t=this.color?.status();return In({engine:Ms,three:r.REVISION,adapter:this.adapterInfo??null,mode:{headless:this._headless,strict:this._issues.strict,deterministic:this.isDeterministic,lockstep:!!e?.accumulationLockstep},render:e?{width:e.width,height:e.height,samples:e.frameCount,complete:e.isComplete,retiredBy:e.isComplete?this.completion.stopCondition(e)??`samples`:null}:null,color:t?{config:t.config?.id??null,workingSpace:t.workingSpace,view:t.activeView??t.activeTransform?.id??null,context:t.context}:null,scene:this.sceneSource,settings:this.settings.getEffective(),issues:this.issues.map(({code:e,severity:t})=>({code:e,severity:t}))})}setLockstepReadbacks(e=!0){this.stages.pathTracer?.setLockstepReadbacks(e)}async _awaitReadback(e){let t=this.renderer.backend.device?.lost,n=await(t?Promise.race([e.then(()=>null),t]):e);if(n)throw Error(`WebGPU device lost while awaiting a readback: ${n.message??n.reason}`)}async captureRenderCheckpoint(){let e=this.stages.pathTracer;if(!e)return null;let t=await e.captureAccumulation();return{v:1,engine:Ms,savedAt:Date.now(),samples:t.state.frameCount,...t}}restoreRenderCheckpoint(e){if(e?.v!==1)throw Error(`render checkpoint version ${e?.v} is not 1`);let t=this.stages.pathTracer;if(!t)throw Error(`restoreRenderCheckpoint: app is not initialized`);t.restoreAccumulation(e),this.needsReset=!1,this.dispatchEvent({type:P.RENDER_RESET,restored:e.samples})}async renderToBuffer({colorSpace:e=`srgb`,preserveAlpha:t=!1,source:n=`accumulation`}={}){if(e!==`linear`&&e!==`srgb`&&!this.color?.hasConfig)throw Error(`renderToBuffer: colorSpace must be 'linear' or 'srgb' without a colour config loaded, got "${e}"`);let r=this.stages?.pathTracer,i=r?.storageTextures?.readTarget;if(!i)throw Error(`renderToBuffer: no render target — call init() and render at least one sample`);let{width:a,height:o}=r;if(e===`srgb`){let r=n===`display`?this._displaySource(i):null,s={exposure:this.renderer.toneMappingExposure,toneMapping:this.renderer.toneMapping,saturation:this.settings.get(`saturation`)??1,preserveAlpha:t},c=await this._toneMapOnGPU(r?.texture??null,i,a,o,s);return{data:c??Vo(r?await this._readTexture(r.texture,a,o):await this.renderer.readRenderTargetPixelsAsync(i,0,0,a,o,0),s),width:a,height:o,colorSpace:e,source:r?.source??`accumulation`,toneMappedOn:c?`gpu`:`cpu`}}let{data:s,source:c}=n===`display`?await this._readDisplaySource(i,a,o):{data:await this.renderer.readRenderTargetPixelsAsync(i,0,0,a,o,0),source:`accumulation`};if(e===`linear`)return{data:s,width:a,height:o,colorSpace:e,workingSpace:this.color?.workingSpace??null,source:c};let{rgba:l,colorSpace:u}=this.color.exportPixels(s,e);return{data:l,width:a,height:o,colorSpace:u,source:c}}async _toneMapOnGPU(e,t,n,r,i){let a=this.renderer?.backend;if(!a?.device)return this._toneMapFallback(`the renderer has no WebGPU device`);try{let o=e?this._readbackPass().draw(e,n,r).texture:t.textures[0],s=a.get(o).texture;return s?(this._readbackToneMapper??=new m_(a.device,`rayzee:readback-tonemap`,{input:`texture`}),this._readbackToneMapper.ensureSize(n,r),await this._readbackToneMapper.toRGBA8(s,i)):this._toneMapFallback(`the picture has no GPU texture yet`)}catch(e){if(e instanceof Gt)throw e;return this._toneMapFallback(`the GPU pass threw`,e)}finally{this._readbackToneMapper?.release(),e&&this._textureReadback?.release()}}_toneMapFallback(e,t=null){let n=t?String(t?.message??t):null,r=`renderToBuffer: tone mapped on the CPU — ${e}${n?`: ${n}`:``}`;return mv.warn(r),this._issues.warn(Y.OUTPUT_TONEMAP_FALLBACK,r,{reason:e,cause:n}),null}enableGPUTiming(e=!0){let t=this.renderer?.backend;return!t||e&&t.hasFeature?.(`timestamp-query`)!==!0?!1:(t.trackTimestamp=e,t.trackTimestamp===e)}async getGPUTimings(){let e=this.renderer;if(!e?.backend?.trackTimestamp)return null;await e.resolveTimestampsAsync(`compute`),await e.resolveTimestampsAsync(`render`);let t=e.info.compute.timestamp||0,n=e.info.render.timestamp||0;return{compute:t,render:n,total:t+n}}async getKernelGPUTimings(){let e=this.renderer;if(!e?.backend?.trackTimestamp)return null;await e.resolveTimestampsAsync(`compute`);let t=e.backend.timestampQueryPool?.compute?.timestamps;if(!t||t.size===0)return null;let n=new Map,r=this.stages?.pathTracer?._kernelManager?.kernels;if(r)for(let[e,t]of r)n.set(t.id,e);let i=[],a=-1;for(let[e,n]of t){let t=e.split(`:`);if(t.length!==4)continue;let r=Number(t[3].slice(1));Number.isFinite(r)&&(i.push({nodeId:Number(t[2]),f:r,ms:n}),r>a&&(a=r))}let o={},s=0,c=0;for(let e of i){if(e.f!==a)continue;s+=e.ms;let t=n.get(e.nodeId);t===void 0?c+=e.ms:o[t]=(o[t]??0)+e.ms}return{kernels:o,total:s,unattributed:c,frame:a}}getCanvas(){return this.renderer?.domElement?this._displayCanvas()||(this.stages.compositor&&this.pipeline?.context&&this.stages.compositor.render(this.pipeline.context),this.renderer.domElement):null}screenshot({type:e=`image/png`,quality:t}={}){let n=this.getCanvas();return n?new Promise(r=>n.toBlob(r,e,t)):Promise.resolve(null)}getStatistics(){try{return this._sdf?.getStatistics?.()??null}catch{return null}}get pathTracerEnabled(){return this._pathTracerEnabled}set pathTracerEnabled(e){this._pathTracerEnabled=e,e||this.precompileRaster()}precompileRaster(){return!this.renderer||!this.meshScene?Promise.resolve():(this._rasterPrecompile??=this.renderer.compileAsync(this.meshScene,this.camera).catch(e=>mv.warn(`raster fallback precompile failed`,e)),this._rasterPrecompile)}get isLoading(){return this._loadingInProgress}isComplete(){return this.stages.pathTracer?.isComplete??!1}getFrameCount(){return this.stages.pathTracer?.frameCount||0}getConvergenceStats(){return this.stages.pathTracer?.getConvergenceStats?.()??null}get vram(){return this.stages.pathTracer?.vramTracker??null}getMemoryInfo(){return this._ensureVRAMWiring(),this.stages.pathTracer?.vramTracker?.measure()??{current:0,peak:0,byCategory:{}}}getHostMemoryInfo(){let e=this._sdf;return e?.memory?{preflight:e.memoryPreflight,...e.memory.report}:null}_ensureVRAMWiring(){if(this._vramWired)return;let e=this.stages.pathTracer?.vramTracker;if(!e)return;e.register(`stages`,()=>this._collectStageTextures()),this._registerVRAM(e),e.register(`canvas`,()=>[{bytes:this.canvas.width*this.canvas.height*4},...this.renderer?._frameBufferTargets?.values()??[],...this._canvasResources()]);let t=()=>e.measure();this._addTrackedListener(this,P.SCENE_REBUILD,t),this._addTrackedListener(this,P.ENVIRONMENT_LOADED,t),this._addTrackedListener(this,P.RESOLUTION_CHANGED,t),this._vramWired=!0}_collectStageTextures(){let e=[],t=this.stages||{},n=t.pathTracer;for(let r in t){let i=t[r];if(!(!i||i===n||typeof i!=`object`))for(let t in i){let n=i[t];n&&(n.isTexture||n.isRenderTarget)&&e.push(n)}}return e}getSceneMinY(){if(!this.meshScene)return 0;let e=new r.Box3().setFromObject(this.meshScene);return Number.isFinite(e.min.y)?e.min.y:0}getMaterialProperty(e,t){return this.stages.pathTracer?.materialData.getMaterialProperty(e,t)}getMaterialPropertySource(e,t){return this.stages.pathTracer?.materialData.getMaterialPropertySource(e,t)}setMaterialProperty(e,t,n){if(this._sdf?.spilled&&Yn.has(t)){this.ensureSceneResident().then(()=>this.setMaterialProperty(e,t,n));return}this.stages.pathTracer?.materialData.updateMaterialProperty(e,t,n),[`emissive`,`emissiveIntensity`].includes(t)&&this._sdf&&this._uploadEmissivePayload(this._sdf.updateMaterialEmissive(e,t,n)),this.reset()}_uploadEmissivePayload(e){!e||!this.stages.pathTracer||(this.stages.pathTracer.setEmissiveTriangleData(e.rawData,e.emissiveCount,e.totalPower,e.bitTrailMap),e.lightBVHNodeData&&this.stages.pathTracer.setLightBVHData(e.lightBVHNodeData,e.lightBVHNodeCount))}_refreshEmissiveForVisibility(){let e=this._sdf?.instanceTable;if(!e)return;let t=new Set;for(let n=0;n<e.count;n++)e.isSet[n]&&!e.visible[n]&&t.add(e.sourceMesh[n]);this._uploadEmissivePayload(this._sdf.rebuildEmissiveForVisibility(t))}setEmissiveTriangleSampling(e){this._emissiveSamplingUserSet=!0,this.settings.set(`enableEmissiveTriangleSampling`,e)}hasEmissiveGeometry(){return(this._sdf?.emissiveTriangleBuilder?.emissiveTriangles?.length??this._sdf?.emissiveTriangleCount??0)>0}setMeshVisibility(e,t){this.stages.pathTracer?.updateMeshVisibility(e,t),this._refreshEmissiveForVisibility(),this.reset()}updateAllMeshVisibility(){this.stages.pathTracer?.updateAllMeshVisibility(),this._refreshEmissiveForVisibility(),this.reset()}getScene(){return this.meshScene||this.scene}setMeshVisibilityByUuid(e,t){let n=this.getScene()?.getObjectByProperty(`uuid`,e);if(!n)return null;let r=typeof t==`function`?!!t(n.visible):!!t;return n.visible=r,this.updateAllMeshVisibility(),r}setTextureTransform(e,t,n){this.stages.pathTracer?.materialData.updateTextureTransform(e,t,n),this.reset()}_displaySource(e){let t=this.pipeline?.context,n=t&&this.stages.compositor?.resolveLightSource(t);return n&&n.key!==`pathtracer:color`&&n.texture!==e.texture?{texture:n.texture,source:n.key.split(`:`)[0]}:(this._denoiserInUse()&&this._issues.record(Y.OUTPUT_SOURCE_FALLBACK,`renderToBuffer: 'display' was asked for, but no denoiser has published a picture — returned the raw accumulation`,{requested:`display`,read:`accumulation`}),null)}async _readDisplaySource(e,t,n){let r=this._displaySource(e);return r?{data:await this._readTexture(r.texture,t,n),source:r.source}:{data:await this.renderer.readRenderTargetPixelsAsync(e,0,0,t,n,0),source:`accumulation`}}_readbackPass(){return this._textureReadback??=new Cg(this.renderer)}_readTexture(e,t,n){return this._readbackPass().read(e,t,n)}async setTextureColorSpace(e,n){if(!e?.isTexture)throw Error(`setTextureColorSpace wants a three.js texture`);let r=e.userData??={};r.__rayzeeOriginalColorSpace===void 0&&(r.__rayzeeOriginalColorSpace=e.colorSpace);let i=r.__rayzeeOriginalColorSpace;if(delete r.ocioColorSpace,delete r.__rayzeeColorSpaceChoice,n==null)e.colorSpace=i,delete r.__rayzeeOriginalColorSpace;else if(n===`srgb`||n===`linear`)e.colorSpace=n===`srgb`?t.SRGBColorSpace:t.LinearSRGBColorSpace,r.__rayzeeColorSpaceChoice=n;else{if(!this.color?.hasConfig)throw Error(`"${n}" needs a colour config loaded`);r.ocioColorSpace=n,e.colorSpace=t.SRGBColorSpace}e.needsUpdate=!0,this.stages.pathTracer?.sdfs&&await this.rebuildMaterials()}setColorManagement(e){this.color?.dispose(),this.color=new e({issues:this._issues}),Ar(this.color),this.renderer&&this.color.attachRenderer(this.renderer)}async loadColorConfig(e={}){await this._leaveColorWorkingSpace();let t=uo(this.renderer?.toneMapping),n=await this.color.loadConfig(e);return this.color.workingSpaceAdopted&&await this.applyColorWorkingSpace(),(!(t?.source===`ocio`&&uo(this.renderer?.toneMapping)===t)||this.color.workingSpaceAdopted)&&this.reset(),n}async unloadColorConfig(){await this._leaveColorWorkingSpace(),this.color.unloadConfig(),this.reset()}async _leaveColorWorkingSpace(){this.color?.workingSpaceAdopted&&(this.color.setWorkingSpace(null),await this.applyColorWorkingSpace())}async applyColorWorkingSpace(){let e=this.environmentManager?.getEnvironmentTexture?.(),t=!1;if(e&&this.color?.hasConfig)try{t=this.color.convertTexturePixels(e)}catch(e){mv.warn(`environment colour conversion failed: ${e.message}`)}this.stages.pathTracer?.sdfs&&(await this.rebuildMaterials(),this._uploadEmissivePayload(this._sdf?.rebuildEmissiveColors?.()??null)),t&&await this.environmentManager?.buildEnvironmentCDF?.(),e?._isPhysicalSky&&await this.environmentManager.generateProceduralSkyTexture(),this.environmentManager?.refreshSun?.(),this.reset()}async rebuildMaterials(e){await this.ensureSceneResident(),await this.stages.pathTracer?.rebuildMaterials(e||this.meshScene),this.reset()}async _initRenderer(){if(L(e=>this.dispatchEvent(e)),typeof navigator>`u`||!navigator.gpu)throw Error("WebGPU is not available — outside a browser, install one as navigator.gpu (for Node, the `webgpu` package)");let e=await navigator.gpu.requestAdapter({powerPreference:`high-performance`});if(!e)throw Error(`Failed to get WebGPU adapter`);this.adapterInfo=vv(e),this.adapterInfo.isSoftware&&(this._issues.warn(Y.ADAPTER_SOFTWARE,`software GPU adapter "${this.adapterInfo.description||this.adapterInfo.vendor}" — renders are correct but orders of magnitude slower than hardware`,{...this.adapterInfo}),mv.warn(`software GPU adapter — check app.adapterInfo.isSoftware. ${this.adapterInfo.description}`));let n=e.limits,r={maxColorAttachmentBytesPerSample:128};for(let e of[`maxBufferSize`,`maxStorageBufferBindingSize`,`maxSampledTexturesPerShaderStage`,`maxStorageTexturesPerShaderStage`,`maxTextureArrayLayers`,`maxTextureDimension2D`,`maxComputeInvocationsPerWorkgroup`,`maxComputeWorkgroupStorageSize`,`maxComputeWorkgroupSizeX`,`maxComputeWorkgroupSizeY`,`maxComputeWorkgroupSizeZ`]){let t=n[e];t!==void 0&&(r[e]=t)}if(r.maxStorageBuffersPerShaderStage=Math.min(n.maxStorageBuffersPerShaderStage,10),this.renderer=new t.WebGPURenderer({canvas:this.canvas,alpha:!0,powerPreference:`high-performance`,requiredLimits:r}),await pv(this.renderer,this._headless),!this.renderer.backend?.isWebGPUBackend)throw Error(`WebGPU backend unavailable — three.js fell back to WebGL2, which cannot run the path tracer's compute kernels. Check GPU process flags and driver support.`);let a=this.renderer.backend?.device;a?.lost&&(this._gpuDevice=a,this._deviceLostHolder={app:this},gv(a,this._deviceLostHolder),a.onuncapturederror=e=>mv.error(`WebGPU uncaptured error:`,e.error)),t.RectAreaLightNode.setLTC(i.RectAreaLightTexturesLib.init()),this.renderer.outputColorSpace=t.SRGBColorSpace,this.renderer.toneMapping=ko,this.renderer.toneMappingExposure=1,this.renderer.setPixelRatio(1),this.color.attachRenderer(this.renderer)}_initScenes(){this.scene=new r.Scene,this.meshScene=new r.Scene,this._sceneHelpers=new A}_initAssetPipeline(){this._sdf=new rc({issues:this._issues,...this._maxSceneBytes===void 0?{}:{maxSceneBytes:this._maxSceneBytes}}),this.assetLoader=new tv(this.meshScene,this.camera,null,{issues:this._issues,areaLightIntensityScale:()=>this.settings.get(`areaLightIntensityScale`)}),this.assetLoader.setRenderer(this.renderer),this.assetLoader.createFloorPlane()}_initPipeline(){this._createStages();let{clientWidth:e,clientHeight:t}=this.canvas;this.pipeline=new bg(this.renderer,e||1,t||1,{issues:this._issues}),this.pipeline.addStage(this.stages.pathTracer);for(let e of this._extraStages)this.pipeline.addStage(e);this.pipeline.addStage(this.stages.compositor);let n=this.canvas.clientWidth||1,r=this.canvas.clientHeight||1;this._displayWidth=n,this._displayHeight=r,this._renderWidth=n,this._renderHeight=r,this.pipeline.setSize(n,r)}async _initManagers(){this.lightManager=new cv(this.scene,this._sceneHelpers,this.stages.pathTracer,{onReset:()=>this.reset(),onLightRemoved:e=>this._lightRemoved(e)}),this.environmentManager=this.stages.pathTracer.environment,this.environmentManager.issues=this._issues,this.stages.pathTracer.issues=this._issues,this.environmentManager.callbacks.onLightingChanged=()=>this.pipeline.eventBus.emit(`pipeline:lightingChanged`),this.environmentManager.callbacks.onReset=()=>this.reset()}_wireEvents(){this.settings.bind(this._settingsBindings()),this.renderer.toneMappingExposure=this.settings.get(`exposure`)??1,this.onResize(),this.resizeHandler=()=>this.onResize(),this._autoResize&&this._addTrackedListener(window,`resize`,this.resizeHandler),this._onAssetLoaded=async e=>{if(!this._loadingInProgress&&!(this._applyingSceneMetadata&&e.texture)){if(e.model)this._clearAppendedModels(),await this.loadSceneData({pendingEnvironment:this._beginSceneMetadataEnvironment()});else if(e.texture){let e=this.meshScene.environment;e&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(e),ue()}this.pauseRendering=!1,this.reset()}},this._addTrackedListener(this.assetLoader,`load`,this._onAssetLoaded),this.pipeline.eventBus.on(`pathtracer:compiling`,({compiling:e})=>this.dispatchEvent({type:P.SHADERS_COMPILING,compiling:e}))}_createStages(){this.stages.pathTracer=new og(this.renderer,this.scene,this.camera,{hostMemoryGB:this._hostMemoryGB,sortMaterials:this.settings.get(`wavefrontSortMaterials`)}),this._extraStages=this._createExtraStages(),this.stages.compositor=new sg(this.renderer,{saturation:this.settings.get(`saturation`)??G.saturation,pathTracer:this.stages.pathTracer,displaySources:this._displaySources()})}_reconcileCompletion(){let e=this.stages.pathTracer;if(!e)return;let t=this.completion.isLimitReached(e,this.settings.get(`renderLimitMode`),this.settings.get(`renderTimeLimit`));t&&!e.isComplete?e.isComplete=!0:!t&&e.isComplete&&(e.isComplete=!1,this.completion.resumeFromPause(),this._completionReopened(),this.dispatchEvent({type:P.RENDER_RESET}),this.wake())}_forwardEvents(e,t){if(e)for(let n of t)this._addTrackedListener(e,n,e=>this.dispatchEvent(e))}_createCamera(){let e=new av(60,this.canvas.clientWidth/this.canvas.clientHeight||1,.01,1e3);return e.position.set(0,0,5),e}_createExtraStages(){return[]}_displaySources(){return[]}_settingsBindings(){return{stages:this.stages,resetCallback:()=>this.reset(),reconcileCompletion:()=>this._reconcileCompletion(),applyExposure:e=>{this.renderer.toneMappingExposure=e}}}_beginFrame(){}_beforeTrace(){}_holdTrace(){return!1}_afterTrace(){}_renderCompleted(){}_renderHelperOverlay(){this.scene.updateMatrixWorld()}_beforeReset(){}_afterReset(){}_dropDisplay(){}_releaseSceneState(){}_modelReplaced(){}_modelAnnounced(){}_sceneRebuilt(){}_sceneBoundsChanged(){}_notePlacementsMoving(){}_lightRemoved(){}_renderSizeChanged(){}_completionReopened(){}async _finalDenoise(){return!1}_denoiserInUse(){return!1}_displayCanvas(){return null}_registerVRAM(){}_canvasResources(){return[]}_deterministicSnapshot(){return null}_setDeterministicExtras(){}_disposeExtensions(){}},bv=65504,xv=6e4,Sv=.01,Cv={low:{temporalAlpha:.1,gradientStrength:.8,gradientSigmaScale:2.5,gradientNoiseFloor:.05,atrousIterations:3,phiColor:1,phiNormal:64,phiDepth:.1,phiLuminance:6,maxAccumFrames:16,varianceBoost:.5},medium:{temporalAlpha:.03,gradientStrength:1,gradientSigmaScale:2.5,gradientNoiseFloor:.05,atrousIterations:4,phiColor:.5,phiNormal:128,phiDepth:.05,phiLuminance:4,maxAccumFrames:64,varianceBoost:1},high:{temporalAlpha:0,gradientStrength:1,gradientSigmaScale:2.5,gradientNoiseFloor:.05,atrousIterations:6,phiColor:.3,phiNormal:256,phiDepth:.02,phiLuminance:2,maxAccumFrames:128,varianceBoost:1.5}},wv=3,Tv=.1,Ev={maxAccumulatedFrameNum:30,maxFastAccumulatedFrameNum:6,maxStabilizedFrameNum:63,historyFixFrameNum:3,historyFixBasePixelStride:14,prepassBlurRadius:30,minBlurRadius:1,maxBlurRadius:30,lobeAngleFraction:.15,roughnessFraction:.15,planeDistanceSensitivity:.02,minHitDistanceWeight:.1,fastHistoryClampingSigmaScale:2,fireflySuppressorMinRelativeScale:2,enableAntiFirefly:!0,antilagLuminanceSigmaScale:2,antilagLuminanceSensitivity:3,disocclusionThreshold:.01,convergenceS:1,convergenceB:.2,convergenceP:.8,lobeVolumePercent:.1,handoverFrames:0},Dv=[`maxAccumulatedFrameNum`,`maxFastAccumulatedFrameNum`,`maxStabilizedFrameNum`,`historyFixFrameNum`,`prepassBlurRadius`,`maxBlurRadius`,`enableAntiFirefly`],Ov={low:{maxAccumulatedFrameNum:16,maxFastAccumulatedFrameNum:4,maxStabilizedFrameNum:16,historyFixFrameNum:2,prepassBlurRadius:0,maxBlurRadius:20,enableAntiFirefly:!1},medium:{},high:{maxAccumulatedFrameNum:45,maxFastAccumulatedFrameNum:8,historyFixFrameNum:4,prepassBlurRadius:40,maxBlurRadius:40}},kv=Cv.medium,Av={denoiserStrategy:`none`,filterStrength:1,edgeAtrousIterations:5,edgePhiLuminance:4,edgePhiNormal:64,edgePhiDepth:.1,enableOIDN:!1,oidnQuality:`fast`,continuousDenoise:!1,continuousDenoiseInterval:8,oidnTemporalHistory:!0,enableUpscaler:!1,upscalerScale:2,upscalerQuality:`fast`,upscalerHdr:!0,enableASVGF:!1,asvgfQualityPreset:`medium`,asvgfTemporalAlpha:kv.temporalAlpha,asvgfAtrousIterations:kv.atrousIterations,asvgfPhiColor:kv.phiColor,asvgfPhiNormal:kv.phiNormal,asvgfPhiDepth:kv.phiDepth,asvgfPhiLuminance:kv.phiLuminance,asvgfVarianceBoost:kv.varianceBoost,asvgfMaxAccumFrames:kv.maxAccumFrames,asvgfGradientStrength:kv.gradientStrength,asvgfGradientSigmaScale:kv.gradientSigmaScale,asvgfGradientNoiseFloor:kv.gradientNoiseFloor,asvgfDebugMode:0,showAsvgfHeatmap:!1,nrdQualityPreset:`medium`,nrdDebugMode:0};Dc(),hl();var jv=class extends M{constructor(e,i={}){super(`NormalDepth`,{...i,executionMode:j.ALWAYS}),this.renderer=e,this.pathTracer=i.pathTracer,this._dirty=!0,this.cameraWorldMatrix=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraProjectionMatrixInverse=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraRay=Xu(),this.resolutionWidth=(0,n.uniform)(i.width||1),this.resolutionHeight=(0,n.uniform)(i.height||1);let a=i.width||1,o=i.height||1;this._outputStorageTex=new t.StorageTexture(U,U),this._outputStorageTex.type=r.HalfFloatType,this._outputStorageTex.format=r.RGBAFormat,this._outputStorageTex.minFilter=r.NearestFilter,this._outputStorageTex.magFilter=r.NearestFilter,this._shadingStorageTex=new t.StorageTexture(U,U),this._shadingStorageTex.type=r.HalfFloatType,this._shadingStorageTex.format=r.RGBAFormat,this._shadingStorageTex.minFilter=r.NearestFilter,this._shadingStorageTex.magFilter=r.NearestFilter,this._shadingRT=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._leafStorageTex=null,this._leafRT=null,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0));let s={type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this._rtA=new t.RenderTarget(a,o,s),this._rtB=new t.RenderTarget(a,o,s),this._currentIdx=0,this._hasHistory=!1,this._dispatchX=Math.ceil(a/8),this._dispatchY=Math.ceil(o/8),this._triStorageNode=null,this._bvhStorageNode=null,this._matStorageNode=null,this._lastTriAttr=null,this._lastBvhAttr=null,this._lastMatAttr=null,this._computeNode=null,this._computeBuilt=!1,this._linearBuckets=null}setupEventListeners(){this.on(`camera:moved`,()=>{this._dirty=!0}),this.on(`pipeline:reset`,()=>{this._dirty=!0})}_syncStorageBuffers(){let e=this.pathTracer;if(!e)return!1;let t=e.materialData?.materialStorageAttr,r=e.triangleGeoAttr&&e.triangleGeoAttr!==this._lastTriAttr,i=e.bvhStorageAttr&&e.bvhStorageAttr!==this._lastBvhAttr,a=t&&t!==this._lastMatAttr;return(r||i||a)&&(this._computeNode?.dispose?.(),this._computeNode=null,this._computeBuilt=!1,this._triStorageNode=null,this._bvhStorageNode=null,this._matStorageNode=null,this._dirty=!0,this._hasHistory=!1),e.triangleGeoAttr&&!this._triStorageNode&&(this._triStorageNode={geo:(0,n.storage)(e.triangleGeoAttr,`uvec4`,e.triangleGeoAttr.count).toReadOnly(),shade:(0,n.storage)(e.triangleShadeAttr,`uvec4`,e.triangleShadeAttr.count).toReadOnly()}),e.bvhStorageAttr&&!this._bvhStorageNode&&(this._bvhStorageNode=(0,n.storage)(e.bvhStorageAttr,`vec4`,e.bvhStorageAttr.count).toReadOnly()),t&&!this._matStorageNode&&(this._matStorageNode=(0,n.storage)(t,`vec4`,t.count).toReadOnly()),this._linearBuckets&&nf(this._linearBuckets,e.materialData?.linearBuckets),this._lastTriAttr=e.triangleGeoAttr||this._lastTriAttr,this._lastBvhAttr=e.bvhStorageAttr||this._lastBvhAttr,this._lastMatAttr=t||this._lastMatAttr,!!(this._triStorageNode&&this._bvhStorageNode&&this._matStorageNode)}_buildCompute(){let e=this._triStorageNode,t=this._bvhStorageNode,r=this._matStorageNode;this._linearBuckets=tf(this.pathTracer?.materialData?.linearBuckets);let i={srgbBuckets:tf(null),linearBuckets:this._linearBuckets,shadowAlbedoMaps:null,goboMaps:null,iesProfiles:null,alphaShadows:null},a=this.cameraWorldMatrix,o=this.cameraProjectionMatrixInverse,s=this.resolutionWidth,c=this.resolutionHeight,l=this._outputStorageTex,u=this._shadingStorageTex,d=this._leafStorageTex;this._computeNode=zn((0,n.Fn)(([i,a])=>{let o=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(o.lessThan((0,n.int)(s)).and(f.lessThan((0,n.int)(c))),()=>{let p=dc(Zu((0,n.vec2)((0,n.float)(o).add(.5).div(s),(0,n.float)(f).add(.5).div(c)),i,a,this.cameraRay)),m=gc.wrap(Sd(p,t,e)),h=m.normal.mul(.5).add(.5),g=(0,n.min)(m.dst,(0,n.float)(65504)),_=m.didHit.select((0,n.vec4)(h,g),(0,n.vec4)(0,0,0,(0,n.float)(bv)));(0,n.textureStore)(l,(0,n.uvec2)((0,n.uint)(o),(0,n.uint)(f)),_).toWriteOnly(),d&&(0,n.textureStore)(d,(0,n.uvec2)((0,n.uint)(o),(0,n.uint)(f)),(0,n.uvec4)((0,n.uint)(m.instanceLeaf.add(1)),0,0,0)).toWriteOnly();let v=m.normal.toVar(),y=(0,n.float)(1).toVar();(0,n.If)(m.didHit,()=>{let i=fc.wrap(ol(m.materialIndex,r)).toVar(),a=Tc.wrap(cf(m.uv,i)).toVar(),o=(0,n.vec4)(0).toVar();(0,n.If)(i.normalMapIndex.greaterThanEqual((0,n.int)(0)),()=>{o.assign(ff(e,m.triangleIndex,m.normal,i.normalTransform,t,m.instanceLeaf))});let s=pf(m.normal,i,a,o).toVar();v.assign(mf(s,i,a)),y.assign(uf(i,a).y.clamp(.05,1))});let b=m.didHit.select((0,n.vec4)(v.mul(.5).add(.5),y),(0,n.vec4)(0,0,0,1));(0,n.textureStore)(u,(0,n.uvec2)((0,n.uint)(o),(0,n.uint)(f)),b).toWriteOnly()})})(a,o),i).compute([this._dispatchX,this._dispatchY,1],[8,8,1]),this._computeBuilt=!0}render(e){if(!this.enabled||!this._syncStorageBuffers())return;this._computeBuilt||this._buildCompute();let t=this.pathTracer;if(t&&(this.cameraWorldMatrix.value.copy(t.uniforms.get(`cameraWorldMatrix`).value),this.cameraProjectionMatrixInverse.value.copy(t.uniforms.get(`cameraProjectionMatrixInverse`).value),this.cameraRay.sync(t.uniforms)),!this._dirty&&this._hasHistory){let t=this._currentIdx===0?this._rtA:this._rtB;e.setTexture(`pathtracer:normalDepth`,t.texture),e.setTexture(`pathtracer:prevNormalDepth`,t.texture),e.setTexture(`pathtracer:shadingNormal`,this._shadingRT.texture),this._publishLeaf(e);return}let n=e.getTexture(`pathtracer:color`);if(n&&n.image){let e=n.image;e.width>0&&e.height>0&&(e.width!==this._rtA.width||e.height!==this._rtA.height)&&this.setSize(e.width,e.height)}this._hasHistory&&(this._currentIdx=1-this._currentIdx);let r=this._currentIdx===0?this._rtA:this._rtB,i=this._currentIdx===0?this._rtB:this._rtA;this.renderer.compute(this._computeNode),this._srcRegion.max.set(r.width,r.height),this.renderer.copyTextureToTexture(this._outputStorageTex,r.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._shadingStorageTex,this._shadingRT.texture,this._srcRegion),this._leafRT&&this.renderer.copyTextureToTexture(this._leafStorageTex,this._leafRT.texture,this._srcRegion),this._hasHistory||=(this.renderer.copyTextureToTexture(this._outputStorageTex,i.texture,this._srcRegion),!0),e.setTexture(`pathtracer:normalDepth`,r.texture),e.setTexture(`pathtracer:prevNormalDepth`,i.texture),e.setTexture(`pathtracer:shadingNormal`,this._shadingRT.texture),this._publishLeaf(e),this._dirty=!1}releaseGPUMemory(){this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose(),this._leafStorageTex?.dispose(),this.reset(),this._hasHistory=!1}reset(){this._dirty=!0}setSize(e,t){this._rtA.setSize(e,t),this._rtA.texture.needsUpdate=!0,this._rtB.setSize(e,t),this._rtB.texture.needsUpdate=!0,this._shadingRT.setSize(e,t),this._shadingRT.texture.needsUpdate=!0,this._leafRT&&(this._leafRT.setSize(e,t),this._leafRT.texture.needsUpdate=!0),this._hasHistory=!1,this.resolutionWidth.value=e,this.resolutionHeight.value=t,this._dispatchX=Math.ceil(e/8),this._dispatchY=Math.ceil(t/8),this._computeNode&&(this._computeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]),this._dirty=!0}reallocateReservedStorage(){this._computeNode?.dispose(),this._computeNode=null,this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose();let e=()=>{let e=new t.StorageTexture(U,U);return e.type=r.HalfFloatType,e.format=r.RGBAFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e};this._outputStorageTex=e(),this._shadingStorageTex=e(),this._leafStorageTex&&=(this._leafStorageTex.dispose(),this._makeLeafStorage()),this._computeBuilt=!1}setInstanceLeafOutput(e){e=!!e,e!==!!this._leafStorageTex&&(this._computeNode?.dispose(),this._computeNode=null,this._computeBuilt=!1,this._dirty=!0,e?(this._leafStorageTex=this._makeLeafStorage(),this._leafRT=new t.RenderTarget(this._rtA.width,this._rtA.height,{type:r.UnsignedIntType,format:r.RedIntegerFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1})):(this._leafStorageTex.dispose(),this._leafRT.dispose(),this._leafStorageTex=null,this._leafRT=null))}_publishLeaf(e){this._leafRT?e.setTexture(`pathtracer:instanceLeaf`,this._leafRT.texture):e.getTexture(`pathtracer:instanceLeaf`)&&e.removeTexture(`pathtracer:instanceLeaf`)}_makeLeafStorage(){let e=new t.StorageTexture(U,U);return e.type=r.UnsignedIntType,e.format=r.RedIntegerFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e}dispose(){this._computeNode?.dispose(),this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose(),this._shadingRT?.dispose(),this._leafStorageTex?.dispose(),this._leafRT?.dispose(),this._rtA?.dispose(),this._rtB?.dispose()}},Mv=class extends M{constructor(e,i,a={}){super(`MotionVector`,{...a,executionMode:j.ALWAYS}),this.renderer=e,this.camera=i,this.pathTracer=a.pathTracer||null;let o=a.width||1,s=a.height||1;this.prevViewProjectionMatrix=new r.Matrix4,this.currentViewProjectionMatrix=new r.Matrix4,this.matricesInitialized=!1,this.isFirstFrame=!0,this.frameCount=0,this.cameraWorldMatrix=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraProjectionMatrixInverse=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraRay=Xu(),this.prevVP=(0,n.uniform)(new r.Matrix4,`mat4`),this.isFirstFrameU=(0,n.uniform)(1),this.deltaTime=(0,n.uniform)(1/60),this.velocityScale=(0,n.uniform)(1),this.resolutionWidth=(0,n.uniform)(o),this.resolutionHeight=(0,n.uniform)(s),this._normalDepthTexNode=new t.TextureNode,this._screenSpaceStorageTex=new t.StorageTexture(U,U),this._screenSpaceStorageTex.type=r.HalfFloatType,this._screenSpaceStorageTex.format=r.RGBAFormat,this._screenSpaceStorageTex.minFilter=r.NearestFilter,this._screenSpaceStorageTex.magFilter=r.NearestFilter,this._worldSpaceStorageTex=new t.StorageTexture(U,U),this._worldSpaceStorageTex.type=r.HalfFloatType,this._worldSpaceStorageTex.format=r.RGBAFormat,this._worldSpaceStorageTex.minFilter=r.NearestFilter,this._worldSpaceStorageTex.magFilter=r.NearestFilter,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0));let c={type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this.screenSpaceTarget=new t.RenderTarget(o,s,c),this.worldSpaceTarget=new t.RenderTarget(o,s,c),this._dispatchX=Math.ceil(o/16),this._dispatchY=Math.ceil(s/16),this._buildScreenSpaceCompute(),this._buildWorldSpaceCompute()}_buildScreenSpaceCompute(){let e=this._normalDepthTexNode,t=this.cameraWorldMatrix,r=this.cameraProjectionMatrixInverse,i=this.prevVP,a=this.resolutionWidth,o=this.resolutionHeight,s=this._screenSpaceStorageTex;this._screenSpaceComputeNode=(0,n.Fn)(([t,r])=>{let c=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),l=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(c.lessThan((0,n.int)(a)).and(l.lessThan((0,n.int)(o))),()=>{let u=(0,n.textureLoad)(e,(0,n.ivec2)(c,l)).w,d=(0,n.vec2)((0,n.float)(c).add(.5).div(a),(0,n.float)(l).add(.5).div(o)),f=(0,n.vec4)(0,0,u,1).toVar();(0,n.If)(u.lessThan((0,n.float)(6e4)),()=>{let e=Qu(d,u,t,r,this.cameraRay),a=i.mul((0,n.vec4)(e,1)),o=a.xy.div(a.w),s=(0,n.vec2)(o.x.mul(.5).add(.5),o.y.mul(-.5).add(.5)),c=d.sub(s),l=s.x.greaterThanEqual(0).and(s.x.lessThanEqual(1)).and(s.y.greaterThanEqual(0)).and(s.y.lessThanEqual(1));f.assign(l.select((0,n.vec4)(c,u,1),(0,n.vec4)((0,n.float)(1e3),(0,n.float)(1e3),u,0)))}),(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(c),(0,n.uint)(l)),f).toWriteOnly()})})(t,r).compute([this._dispatchX,this._dispatchY,1],[16,16,1])}_buildWorldSpaceCompute(){let e=this._normalDepthTexNode,t=this.cameraWorldMatrix,r=this.cameraProjectionMatrixInverse,i=this.prevVP,a=this.isFirstFrameU,o=this.deltaTime,s=this.velocityScale,c=this.resolutionWidth,l=this.resolutionHeight,u=this._worldSpaceStorageTex;this._worldSpaceComputeNode=(0,n.Fn)(([t,r])=>{let d=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(c)).and(f.lessThan((0,n.int)(l))),()=>{let p=(0,n.textureLoad)(e,(0,n.ivec2)(d,f)).w,m=(0,n.vec4)(0,0,0,0).toVar();(0,n.If)(a.lessThan(.5).and(p.lessThan((0,n.float)(6e4))),()=>{let e=(0,n.vec2)((0,n.float)(d).add(.5).div(c),(0,n.float)(f).add(.5).div(l)),a=Qu(e,p,t,r,this.cameraRay),u=i.mul((0,n.vec4)(a,1)),h=u.xy.div(u.w),g=(0,n.vec2)(h.x.mul(.5).add(.5),h.y.mul(-.5).add(.5)),_=g.x.greaterThanEqual(0).and(g.x.lessThanEqual(1)).and(g.y.greaterThanEqual(0)).and(g.y.lessThanEqual(1)),v=e.sub(g),y=(0,n.vec3)(v.x.div(o).mul(s),v.y.div(o).mul(s),0);m.assign(_.select((0,n.vec4)(y,1),(0,n.vec4)(0,0,0,.5)))}),(0,n.textureStore)(u,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),m).toWriteOnly()})})(t,r).compute([this._dispatchX,this._dispatchY,1],[16,16,1])}_updateCameraMatrices(){let e=this.pathTracer,t,n,r,i;if(e&&e.uniforms)this.cameraRay.sync(e.uniforms),t=e.uniforms.get(`cameraWorldMatrix`).value,n=e.uniforms.get(`cameraViewMatrix`).value,r=e.uniforms.get(`cameraProjectionMatrix`).value,i=e.uniforms.get(`cameraProjectionMatrixInverse`).value;else{let e=this.camera;if(!e)return;t=e.matrixWorld,n=e.matrixWorldInverse,r=e.projectionMatrix,i=e.projectionMatrixInverse}this.matricesInitialized?this.prevViewProjectionMatrix.copy(this.currentViewProjectionMatrix):(this.currentViewProjectionMatrix.multiplyMatrices(r,n),this.prevViewProjectionMatrix.copy(this.currentViewProjectionMatrix),this.matricesInitialized=!0),this.currentViewProjectionMatrix.multiplyMatrices(r,n),this.cameraWorldMatrix.value.copy(t),this.cameraProjectionMatrixInverse.value.copy(i),this.prevVP.value.copy(this.prevViewProjectionMatrix)}setupEventListeners(){this.on(`pipeline:reset`,()=>{this.reset()})}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:normalDepth`);if(!t)return;this._updateCameraMatrices(),this.isFirstFrameU.value=+!!this.isFirstFrame,this.frameCount++;let n=t.image;n&&n.width>0&&n.height>0&&(n.width!==this.screenSpaceTarget.width||n.height!==this.screenSpaceTarget.height)&&this.setSize(n.width,n.height),this._normalDepthTexNode.value=t,this.renderer.compute(this._screenSpaceComputeNode),this.renderer.compute(this._worldSpaceComputeNode),this._srcRegion.max.set(this.screenSpaceTarget.width,this.screenSpaceTarget.height),this.renderer.copyTextureToTexture(this._screenSpaceStorageTex,this.screenSpaceTarget.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._worldSpaceStorageTex,this.worldSpaceTarget.texture,this._srcRegion),e.setTexture(`motionVector:screenSpace`,this.screenSpaceTarget.texture),e.setTexture(`motionVector:worldSpace`,this.worldSpaceTarget.texture),e.setTexture(`motionVector:motion`,this.screenSpaceTarget.texture),this.emit(`motionvector:computed`,{frame:this.frameCount,isFirstFrame:this.isFirstFrame}),this.isFirstFrame=!1}releaseGPUMemory(){this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose(),this.reset()}reset(){this.matricesInitialized||(this.isFirstFrame=!0),this.frameCount=0}setSize(e,t){this.screenSpaceTarget.setSize(e,t),this.screenSpaceTarget.texture.needsUpdate=!0,this.worldSpaceTarget.setSize(e,t),this.worldSpaceTarget.texture.needsUpdate=!0,this.resolutionWidth.value=e,this.resolutionHeight.value=t,this._dispatchX=Math.ceil(e/16),this._dispatchY=Math.ceil(t/16),this._screenSpaceComputeNode&&(this._screenSpaceComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]),this._worldSpaceComputeNode&&(this._worldSpaceComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1])}setVelocityScale(e){this.velocityScale.value=e}setDeltaTime(e){this.deltaTime.value=e}reallocateReservedStorage(){this._screenSpaceComputeNode?.dispose(),this._worldSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose();let e=()=>{let e=new t.StorageTexture(U,U);return e.type=r.HalfFloatType,e.format=r.RGBAFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e};this._screenSpaceStorageTex=e(),this._worldSpaceStorageTex=e(),this._buildScreenSpaceCompute(),this._buildWorldSpaceCompute()}dispose(){this._screenSpaceComputeNode?.dispose(),this._worldSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose(),this.screenSpaceTarget?.dispose(),this.worldSpaceTarget?.dispose(),this._normalDepthTexNode?.dispose()}};hl();var Nv=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,1e7),Pv=e=>(0,n.vec3)(Nv(e.x),Nv(e.y),Nv(e.z)),Fv=class extends M{constructor(e,i={}){super(`ASVGF`,{...i,executionMode:j.PER_CYCLE}),this.renderer=e,this.temporalAlpha=(0,n.uniform)(i.temporalAlpha??Cv.medium.temporalAlpha),this.gradientStrength=(0,n.uniform)(i.gradientStrength??Cv.medium.gradientStrength),this.gradientSigmaScale=(0,n.uniform)(i.gradientSigmaScale??Cv.medium.gradientSigmaScale),this.gradientNoiseFloor=(0,n.uniform)(i.gradientNoiseFloor??Cv.medium.gradientNoiseFloor),this.maxAccumFrames=(0,n.uniform)(i.maxAccumFrames??Cv.medium.maxAccumFrames),this.resW=(0,n.uniform)(i.width||1),this.resH=(0,n.uniform)(i.height||1),this.temporalEnabledU=(0,n.uniform)(1),this.forceResetU=(0,n.uniform)(0),this._colorTexNode=new t.TextureNode,this._albedoTexNode=new t.TextureNode,this._motionTexNode=new t.TextureNode,this._normalDepthTexNode=new t.TextureNode,this._prevNormalDepthTexNode=new t.TextureNode,this._readTemporalTexNode=new t.TextureNode,this._gradientReadTexNode=new t.TextureNode;let a=i.width||1,o=i.height||1;this._temporalTexA=new t.StorageTexture(U,U),this._temporalTexA.type=r.FloatType,this._temporalTexA.format=r.RGBAFormat,this._temporalTexA.minFilter=r.LinearFilter,this._temporalTexA.magFilter=r.LinearFilter,this._temporalTexB=new t.StorageTexture(U,U),this._temporalTexB.type=r.FloatType,this._temporalTexB.format=r.RGBAFormat,this._temporalTexB.minFilter=r.LinearFilter,this._temporalTexB.magFilter=r.LinearFilter,this._outputModulatedTex=new t.StorageTexture(U,U),this._outputModulatedTex.type=r.FloatType,this._outputModulatedTex.format=r.RGBAFormat,this._outputModulatedTex.minFilter=r.LinearFilter,this._outputModulatedTex.magFilter=r.LinearFilter,this._gradientStorageTex=new t.StorageTexture(U,U),this._gradientStorageTex.type=r.HalfFloatType,this._gradientStorageTex.format=r.RGBAFormat,this._gradientStorageTex.minFilter=r.LinearFilter,this._gradientStorageTex.magFilter=r.LinearFilter,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),this._demodulatedRT=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._outputRT=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._gradientRT=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this.currentMoments=0,this._compiled=!1,this._needsWarmReset=!1,this._dispatchX=Math.ceil(a/8),this._dispatchY=Math.ceil(o/8),this._buildGradientCompute(),this._buildTemporalCompute(),this.showHeatmap=!1,this.debugMode=(0,n.uniform)(0,`int`),this._heatmapStorageTex=new t.StorageTexture(U,U),this._heatmapStorageTex.type=r.FloatType,this._heatmapStorageTex.format=r.RGBAFormat,this._heatmapStorageTex.minFilter=r.NearestFilter,this._heatmapStorageTex.magFilter=r.NearestFilter,this.heatmapTarget=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._heatmapRawColorTexNode=new t.TextureNode,this._heatmapColorTexNode=new t.TextureNode,this._heatmapTemporalTexNode=new t.TextureNode,this._heatmapNDTexNode=new t.TextureNode,this._heatmapMotionTexNode=new t.TextureNode,this._heatmapGradientTexNode=new t.TextureNode,this._buildHeatmapCompute()}_buildGradientCompute(){let e=this._colorTexNode,t=this._albedoTexNode,r=this._motionTexNode,i=this._readTemporalTexNode,a=this.gradientNoiseFloor,o=this.gradientSigmaScale,s=this._gradientStorageTex,c=this.resW,l=this.resH,u=(0,n.workgroupArray)(`float`,144),d=(0,n.workgroupArray)(`float`,144);this._gradientNode=(0,n.Fn)(()=>{let f=n.localId.x,p=n.localId.y,m=p.mul(8).add(f),h=(0,n.int)(n.workgroupId.x).mul(8).sub(2).toVar(),g=(0,n.int)(n.workgroupId.y).mul(8).sub(2).toVar(),_=a=>{let o=a.mod((0,n.uint)(12)),s=a.div((0,n.uint)(12)),f=h.add((0,n.int)(o)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),p=g.add((0,n.int)(s)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),m=(0,n.textureLoad)(e,(0,n.ivec2)(f,p)).xyz,_=(0,n.textureLoad)(t,(0,n.ivec2)(f,p)).xyz,v=Kc(Pv(m.div((0,n.max)(_,(0,n.vec3)(Sv))))).toVar();u.element(a).assign(v);let y=(0,n.textureLoad)(r,(0,n.ivec2)(f,p)),b=(0,n.float)(f).sub(y.x.mul(c)),x=(0,n.float)(p).sub(y.y.mul(l)),S=(0,n.int)(b.add(.5)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),C=(0,n.int)(x.add(.5)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),w=y.w.greaterThan(.5),T=(0,n.textureLoad)(i,(0,n.ivec2)(S,C)).xyz,E=w.select(Kc(T),v);d.element(a).assign(E)};_(m);let v=m.add((0,n.uint)(64));(0,n.If)(v.lessThan((0,n.uint)(144)),()=>{_(v)});let y=m.add((0,n.uint)(128));(0,n.If)(y.lessThan((0,n.uint)(144)),()=>{_(y)}),(0,n.workgroupBarrier)();let b=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(f)),x=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(p));(0,n.If)(b.lessThan((0,n.int)(c)).and(x.lessThan((0,n.int)(l))),()=>{let e=(0,n.float)(0).toVar(),t=(0,n.float)(0).toVar();for(let r=-2;r<=2;r++)for(let i=-2;i<=2;i++){let a=p.add((0,n.uint)(2+r)).mul((0,n.uint)(12)).add(f.add((0,n.uint)(2+i))),o=u.element(a);e.addAssign(o),t.addAssign(o.mul(o))}let m=e.div(25),h=(0,n.sqrt)((0,n.max)(t.div(25).sub(m.mul(m)),(0,n.float)(0))).mul(o).toVar(),g=(0,n.float)(0).toVar();for(let e=-2;e<=2;e++)for(let t=-2;t<=2;t++){let r=p.add((0,n.uint)(2+e)).mul((0,n.uint)(12)).add(f.add((0,n.uint)(2+t))),i=u.element(r),o=d.element(r),s=(0,n.max)((0,n.max)((0,n.abs)(i.sub(o)).sub(h),(0,n.float)(0)).div((0,n.max)((0,n.max)(i,o),(0,n.float)(.001))).sub(a),(0,n.float)(0)).div((0,n.max)((0,n.float)(1).sub(a),(0,n.float)(1e-4)));g.addAssign(s.mul(s))}let _=g.div(25).clamp(0,1).toVar(),v=(0,n.textureLoad)(r,(0,n.ivec2)(b,x)),y=(0,n.int)((0,n.float)(b).sub(v.x.mul(c)).add(.5)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),S=(0,n.int)((0,n.float)(x).sub(v.y.mul(l)).add(.5)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),C=v.w.greaterThan(.5).select((0,n.textureLoad)(i,(0,n.ivec2)(y,S)).w,(0,n.float)(0)).div(4).clamp(0,1),w=_.mul(C);(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(b),(0,n.uint)(x)),(0,n.vec4)(w,_,h,1)).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}_buildTemporalCompute(){this._temporalNodeA=this._buildTemporalForDirection(this._temporalTexA),this._temporalNodeB=this._buildTemporalForDirection(this._temporalTexB)}_buildTemporalForDirection(e){let t=this._colorTexNode,r=this._albedoTexNode,i=this._motionTexNode,a=this._normalDepthTexNode,o=this._prevNormalDepthTexNode,s=this._readTemporalTexNode,c=this._gradientReadTexNode,l=this._outputModulatedTex,u=this.maxAccumFrames,d=this.temporalAlpha,f=this.gradientStrength,p=this.temporalEnabledU,m=this.forceResetU,h=this.resW,g=this.resH;return(0,n.Fn)(()=>{let _=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),v=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(_.lessThan((0,n.int)(h)).and(v.lessThan((0,n.int)(g))),()=>{let y=(0,n.ivec2)(_,v),b=(0,n.textureLoad)(t,y),x=b.xyz,S=b.w,C=(0,n.textureLoad)(r,y).xyz,w=(0,n.max)(C,(0,n.vec3)(Sv)),T=Pv(x.div(w)),E=(0,n.vec4)(T,1).toVar(),D=(0,n.vec4)(x,S).toVar();(0,n.If)(p.greaterThan(.5).and(m.lessThan(.5)),()=>{let e=(0,n.textureLoad)(i,y),t=e.w.greaterThan(.5),r=(0,n.float)(_).sub(e.x.mul(h)),l=(0,n.float)(v).sub(e.y.mul(g)),p=r.greaterThanEqual(0).and(r.lessThan((0,n.float)(h))).and(l.greaterThanEqual(0)).and(l.lessThan((0,n.float)(g)));(0,n.If)(t.and(p),()=>{let e=(0,n.textureLoad)(a,y),t=e.xyz.mul(2).sub(1),i=e.w,p=(0,n.int)(r),m=(0,n.int)(l),_=p.add((0,n.int)(1)),v=m.add((0,n.int)(1)),b=r.sub((0,n.float)(p)),x=l.sub((0,n.float)(m)),C=p.clamp((0,n.int)(0),(0,n.int)(h).sub(1)),O=_.clamp((0,n.int)(0),(0,n.int)(h).sub(1)),k=m.clamp((0,n.int)(0),(0,n.int)(g).sub(1)),A=v.clamp((0,n.int)(0),(0,n.int)(g).sub(1)),j=(0,n.float)(1).sub(b).mul((0,n.float)(1).sub(x)),M=b.mul((0,n.float)(1).sub(x)),N=(0,n.float)(1).sub(b).mul(x),P=b.mul(x),F=(e,r,a)=>{let s=(0,n.textureLoad)(o,(0,n.ivec2)(e,r)),c=s.xyz.mul(2).sub(1),l=s.w,u=(0,n.pow)((0,n.dot)(t,c).clamp(0,1),(0,n.float)(16)),d=(0,n.exp)((0,n.abs)(i.sub(l)).div((0,n.max)(i,(0,n.float)(.001))).div((0,n.float)(.05)).negate());return a.mul(u).mul(d)},I=F(C,k,j),L=F(O,k,M),ee=F(C,A,N),te=F(O,A,P),R=I.add(L).add(ee).add(te);(0,n.If)(R.greaterThan((0,n.float)(.01)),()=>{let e=(0,n.textureLoad)(s,(0,n.ivec2)(C,k)),t=(0,n.textureLoad)(s,(0,n.ivec2)(O,k)),r=(0,n.textureLoad)(s,(0,n.ivec2)(C,A)),i=(0,n.textureLoad)(s,(0,n.ivec2)(O,A)),a=(0,n.float)(1).div(R),o=e.xyz.mul(I).add(t.xyz.mul(L)).add(r.xyz.mul(ee)).add(i.xyz.mul(te)).mul(a),l=e.w.mul(I).add(t.w.mul(L)).add(r.w.mul(ee)).add(i.w.mul(te)).mul(a),p=(0,n.textureLoad)(c,y).x.mul(f).clamp(0,1),m=Pv((0,n.mix)(o,T,(0,n.mix)((0,n.max)((0,n.float)(1).div(l.add(1)),d),(0,n.float)(1),p))),h=(0,n.min)(l.add(1),u);E.assign((0,n.vec4)(m,h)),D.assign((0,n.vec4)(m.mul(w),S))})})}),(0,n.textureStore)(e,(0,n.uvec2)((0,n.uint)(_),(0,n.uint)(v)),E).toWriteOnly(),(0,n.textureStore)(l,(0,n.uvec2)((0,n.uint)(_),(0,n.uint)(v)),D).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}_buildHeatmapCompute(){let e=this._heatmapRawColorTexNode,t=this._heatmapColorTexNode,r=this._heatmapTemporalTexNode,i=this._heatmapNDTexNode,a=this._heatmapMotionTexNode,o=this._heatmapGradientTexNode,s=this._heatmapStorageTex,c=this.debugMode,l=this.resW,u=this.resH;this._heatmapComputeNode=(0,n.Fn)(()=>{let d=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(l)).and(f.lessThan((0,n.int)(u))),()=>{let p=(0,n.ivec2)(d,f),m=(0,n.vec4)(0,0,0,1).toVar();(0,n.If)(c.equal((0,n.int)(0)),()=>{let e=(0,n.textureLoad)(t,p).xyz;m.assign((0,n.vec4)(e,1))}).ElseIf(c.equal((0,n.int)(1)),()=>{let t=(0,n.float)(0).toVar(),r=(0,n.float)(0).toVar();for(let i=-1;i<=1;i++)for(let a=-1;a<=1;a++){let o=(0,n.textureLoad)(e,(0,n.ivec2)(d.add(a).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),f.add(i).clamp((0,n.int)(0),(0,n.int)(u).sub(1)))).xyz,s=Kc(o);t.addAssign(s),r.addAssign(s.mul(s))}t.divAssign(9),r.divAssign(9);let i=(0,n.max)(r.sub(t.mul(t)),(0,n.float)(0)).div((0,n.max)(t.mul(t),(0,n.float)(1e-4))).mul(10).clamp(0,1),a=i.sub(.5).mul(4).clamp(0,1),o=i.mul(4).clamp(0,1).sub(i.sub(.75).mul(4).clamp(0,1)),s=(0,n.float)(1).sub(i.sub(.25).mul(4).clamp(0,1));m.assign((0,n.vec4)(a,o,s,1))}).ElseIf(c.equal((0,n.int)(2)),()=>{let e=(0,n.textureLoad)(r,p).w.div(32).clamp(0,1);m.assign((0,n.vec4)((0,n.float)(1).sub(e),e,(0,n.float)(.2),1))}).ElseIf(c.equal((0,n.int)(3)),()=>{let e=(0,n.textureLoad)(a,p),t=(0,n.abs)(e.x).mul(100).clamp(0,1),r=(0,n.abs)(e.y).mul(100).clamp(0,1),i=t.add(r).clamp(0,1);m.assign((0,n.vec4)(t,r,i.mul(.3),1))}).ElseIf(c.equal((0,n.int)(4)),()=>{let e=(0,n.textureLoad)(i,p);m.assign((0,n.vec4)(e.xyz,1))}).Else(()=>{let e=(0,n.textureLoad)(o,p).x.mul(5).clamp(0,1);m.assign((0,n.vec4)(e,e.mul(.5),(0,n.float)(1).sub(e),1))}),(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),m).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}setupEventListeners(){this.on(`pipeline:historyReset`,()=>this.resetTemporalData())}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:color`),n=e.getTexture(`pathtracer:albedo`),r=e.getTexture(`pathtracer:normalDepth`),i=e.getTexture(`pathtracer:prevNormalDepth`)||r,a=e.getTexture(`motionVector:screenSpace`);if(!t)return;let o=t.image;o&&o.width>0&&o.height>0&&(o.width!==this._outputRT.width||o.height!==this._outputRT.height)&&this.setSize(o.width,o.height),this._colorTexNode.value=t,n&&(this._albedoTexNode.value=n),a&&(this._motionTexNode.value=a),r&&(this._normalDepthTexNode.value=r),i&&(this._prevNormalDepthTexNode.value=i);let s=this.currentMoments===0?this._temporalTexB:this._temporalTexA,c=this.currentMoments===0?this._temporalNodeA:this._temporalNodeB,l=this.currentMoments===0?this._temporalTexA:this._temporalTexB;this._compiled||=(this.renderer.compute(this._gradientNode),this.renderer.compute(this._temporalNodeA),this.renderer.compute(this._temporalNodeB),!0),this._readTemporalTexNode.value=s,this._gradientReadTexNode.value=this._gradientStorageTex;let u=this.gradientStrength.value>0||this.showHeatmap;u&&this.renderer.compute(this._gradientNode),this.forceResetU.value=+!!this._needsWarmReset,this.renderer.compute(c),this._needsWarmReset=!1,this._srcRegion.max.set(this.resW.value,this.resH.value),this.renderer.copyTextureToTexture(l,this._demodulatedRT.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._outputModulatedTex,this._outputRT.texture,this._srcRegion),u&&this.renderer.copyTextureToTexture(this._gradientStorageTex,this._gradientRT.texture,this._srcRegion),e.setTexture(`asvgf:demodulated`,this._demodulatedRT.texture),e.setTexture(`asvgf:output`,this._outputRT.texture),e.setTexture(`asvgf:gradient`,this._gradientRT.texture),this.currentMoments=1-this.currentMoments,this.showHeatmap&&(this._heatmapRawColorTexNode.value=t,this._heatmapColorTexNode.value=this._outputModulatedTex,this._heatmapTemporalTexNode.value=l,r&&(this._heatmapNDTexNode.value=r),a&&(this._heatmapMotionTexNode.value=a),this._heatmapGradientTexNode.value=this._gradientStorageTex,this.renderer.compute(this._heatmapComputeNode),this._srcRegion.max.set(this.heatmapTarget.width,this.heatmapTarget.height),this.renderer.copyTextureToTexture(this._heatmapStorageTex,this.heatmapTarget.texture,this._srcRegion))}setHeatmapEnabled(e){this.showHeatmap=e}setTemporalEnabled(e){this.temporalEnabledU.value=+!!e}updateParameters(e){e&&(e.temporalAlpha!==void 0&&(this.temporalAlpha.value=e.temporalAlpha),e.gradientStrength!==void 0&&(this.gradientStrength.value=e.gradientStrength),e.gradientSigmaScale!==void 0&&(this.gradientSigmaScale.value=e.gradientSigmaScale),e.gradientNoiseFloor!==void 0&&(this.gradientNoiseFloor.value=e.gradientNoiseFloor),e.maxAccumFrames!==void 0&&(this.maxAccumFrames.value=e.maxAccumFrames),e.debugMode!==void 0&&(this.debugMode.value=e.debugMode))}resetTemporalData(){this.currentMoments=0,this._needsWarmReset=!0}reallocateReservedStorage(){this._gradientNode?.dispose(),this._temporalNodeA?.dispose(),this._temporalNodeB?.dispose(),this._heatmapComputeNode?.dispose(),this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._heatmapStorageTex?.dispose();let e=(e,n)=>{let i=new t.StorageTexture(U,U);return i.type=e,i.format=r.RGBAFormat,i.minFilter=n,i.magFilter=n,i};this._temporalTexA=e(r.FloatType,r.LinearFilter),this._temporalTexB=e(r.FloatType,r.LinearFilter),this._outputModulatedTex=e(r.FloatType,r.LinearFilter),this._gradientStorageTex=e(r.HalfFloatType,r.LinearFilter),this._heatmapStorageTex=e(r.FloatType,r.NearestFilter),this._buildGradientCompute(),this._buildTemporalCompute(),this._buildHeatmapCompute(),this._compiled=!1,this.currentMoments=0,this._needsWarmReset=!0}setSize(e,t){this._demodulatedRT.setSize(e,t),this._demodulatedRT.texture.needsUpdate=!0,this._outputRT.setSize(e,t),this._outputRT.texture.needsUpdate=!0,this._gradientRT.setSize(e,t),this._gradientRT.texture.needsUpdate=!0,this.heatmapTarget.setSize(e,t),this.heatmapTarget.texture.needsUpdate=!0,this.resW.value=e,this.resH.value=t,this._dispatchX=Math.ceil(e/8),this._dispatchY=Math.ceil(t/8),this._gradientNode.dispatchSize=[this._dispatchX,this._dispatchY,1],this._temporalNodeA.dispatchSize=[this._dispatchX,this._dispatchY,1],this._temporalNodeB.dispatchSize=[this._dispatchX,this._dispatchY,1],this._heatmapComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]}reset(){}releaseGPUMemory(){this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._heatmapStorageTex?.dispose(),this.context?.removeTexture(`asvgf:demodulated`),this.context?.removeTexture(`asvgf:output`),this.context?.removeTexture(`asvgf:gradient`),this._demodulatedRT?.texture?.dispose(),this._outputRT?.texture?.dispose(),this._gradientRT?.texture?.dispose(),this.heatmapTarget?.texture?.dispose(),this.resetTemporalData()}dispose(){this._gradientNode?.dispose(),this._temporalNodeA?.dispose(),this._temporalNodeB?.dispose(),this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._demodulatedRT?.dispose(),this._outputRT?.dispose(),this._gradientRT?.dispose(),this._heatmapComputeNode?.dispose(),this._heatmapStorageTex?.dispose(),this.heatmapTarget?.dispose(),this._colorTexNode?.dispose(),this._albedoTexNode?.dispose(),this._motionTexNode?.dispose(),this._normalDepthTexNode?.dispose(),this._prevNormalDepthTexNode?.dispose(),this._readTemporalTexNode?.dispose(),this._gradientReadTexNode?.dispose(),this._heatmapRawColorTexNode?.dispose(),this._heatmapColorTexNode?.dispose(),this._heatmapTemporalTexNode?.dispose(),this._heatmapNDTexNode?.dispose(),this._heatmapMotionTexNode?.dispose(),this._heatmapGradientTexNode?.dispose()}};hl();var Iv=1e-6,Lv=1.5/255,Rv=.01,zv=3,Bv=2,Vv=2,Hv=3,Uv=2,Wv=38,Gv=.1,Kv=4,qv=Math.cos(89*Math.PI/180),Jv=.5,Yv=16,Xv={pre:{radiusScale:1,fractionScale:2},blur:{radiusScale:1,fractionScale:1},post:{radiusScale:2,fractionScale:.5}},Zv=.25*Math.SQRT2,Qv=[[-1,0,1],[0,1,1],[1,0,1],[0,-1,1],[-Zv,Zv,.5],[Zv,Zv,.5],[Zv,-Zv,.5],[-Zv,-Zv,.5]],$v=(e,t,r)=>(0,n.smoothstep)(0,1,(0,n.float)(1).sub(e.mul(t).add(r).abs())),ey=(e,t,r)=>{let i=e.mul(t).add(r).abs().mul(-zv);return(0,n.float)(1).div(i.mul(i).sub(i).add(1))},ty=e=>(0,n.mix)((0,n.float)(1.570796),(0,n.float)(1.395402),(0,n.saturate)(e)).mul((0,n.sqrt)((0,n.saturate)((0,n.float)(1).sub(e)))),ny=(e,t)=>(0,n.float)(1).sub((0,n.exp2)(e.mul(e).mul(-200))).mul((0,n.pow)((0,n.saturate)(e),t)),ry=(e,t)=>(0,n.saturate)(e).mul((0,n.sqrt)(t.div((0,n.float)(1).sub(t).add(Iv)))),iy=(e,t,r,i)=>{let a=(0,n.max)((0,n.atan)(ry(r,i.mul((0,n.mix)((0,n.saturate)(t),(0,n.float)(1),e)))),(0,n.float)(Lv));return(0,n.float)(1).div(a)},ay=(e,t)=>{let r=(0,n.float)(1).div((0,n.mix)((0,n.float)(Rv),(0,n.float)(1),(0,n.saturate)(e.mul(t))));return(0,n.vec2)(r,e.mul(r).negate())},oy=(e,t,r)=>{let i=(0,n.float)(1).div((0,n.mix)((0,n.float)(r),(0,n.float)(1),(0,n.mix)(e.mul(e),e,(0,n.saturate)(t))));return(0,n.vec2)(i,e.mul(i).negate())},sy=(e,t)=>{let r=(0,n.float)(1).div(t);return(0,n.vec2)(r,e.mul(r).negate())},cy=(e,t,r,i)=>{let a=(0,n.float)(1).div(e.mul(t));return(0,n.vec2)(a,(0,n.dot)(i,r).mul(a).negate())},ly=e=>(0,n.vec2)(1).sub((0,n.vec2)(1).sub((0,n.fract)(e.mul(.5)).mul(2)).abs()).min(.99999),uy=e=>(0,n.vec3)((0,n.dot)(e,(0,n.vec3)(.25,.5,.25)),(0,n.dot)(e,(0,n.vec3)(.5,0,-.5)),(0,n.dot)(e,(0,n.vec3)(-.25,.5,-.25))),dy=e=>{let t=e.x.sub(e.z);return(0,n.max)((0,n.vec3)(t.add(e.y),e.x.add(e.z),t.sub(e.y)),(0,n.vec3)(0))},fy=(e,t)=>t.add(Iv).div(e.add(Iv)),py=(e,t)=>(0,n.vec4)(e.xyz.mul(fy(e.x,t)),e.w),my=e=>(0,n.vec4)(uy(dy(e.xyz)),(0,n.saturate)(e.w)),hy=(e,t)=>(0,n.sqrt)(t.sub(e.mul(e)).abs()),gy=(e,t)=>(0,n.vec2)(e.x.mul(t.x).add(e.y.mul(t.y)),e.z.mul(t.x).add(e.w.mul(t.y))),_y=(e,t)=>(0,n.select)(e.equal(0),(0,n.vec4)(0),t);function vy(e){let t=Math.imul(e|0,2654435761)>>>0;return t^=t>>>15,t=Math.imul(t,2246822507)>>>0,t^=t>>>13,t=Math.imul(t,3266489909)>>>0,t^=t>>>16,t/4294967296}var yy=class extends M{constructor(e,i={}){super(`NRD`,{...i,executionMode:j.PER_CYCLE}),this.renderer=e,this.pathTracer=i.pathTracer||null,this.settings={...Ev,...i.settings||{}},this._releaseHitDistance=this.pathTracer?.requestOutput?.(`hitDistance`,{encode:(e,t)=>e.div((0,n.max)(t.mul(.1).add(3),(0,n.float)(1e-4))).clamp(0,1)})??null;let a=i.width||1,o=i.height||1;this.resW=(0,n.uniform)(a),this.resH=(0,n.uniform)(o),this.minRectDimMulUnproject=(0,n.uniform)(1),this.inputFrames=(0,n.uniform)(0),this.resetU=(0,n.uniform)(0),this.debugMode=(0,n.uniform)(0,`int`),this.rotPre=(0,n.uniform)(new r.Vector4(1,0,0,1),`vec4`),this.rotBlur=(0,n.uniform)(new r.Vector4(1,0,0,1),`vec4`),this.rotPost=(0,n.uniform)(new r.Vector4(1,0,0,1),`vec4`),this.camWorld=(0,n.uniform)(new r.Matrix4,`mat4`),this.camProjInv=(0,n.uniform)(new r.Matrix4,`mat4`),this.camView=(0,n.uniform)(new r.Matrix4,`mat4`),this.prevCamView=(0,n.uniform)(new r.Matrix4,`mat4`),this.camPos=(0,n.uniform)(new r.Vector3,`vec3`),this.prevCamPos=(0,n.uniform)(new r.Vector3,`vec3`),this.viewVector=(0,n.uniform)(new r.Vector3,`vec3`),this.prevViewVector=(0,n.uniform)(new r.Vector3,`vec3`),this.cameraRay=Xu(),this.u={};for(let e of[`maxAccum`,`maxFast`,`stabilizationStrength`,`historyFixFrameNum`,`historyFixStride`,`prepassBlurRadius`,`minBlurRadius`,`maxBlurRadius`,`lobeAngleFraction`,`roughnessFraction`,`planeDistSensitivity`,`minHitDistanceWeight`,`fastClampSigmaScale`,`fireflyMinRelativeScale`,`antiFirefly`,`disocclusionThreshold`,`lobeVolumePercent`,`handoverFrames`])this.u[e]=(0,n.uniform)(0);this.u.antilag=(0,n.uniform)(new r.Vector2,`vec2`),this.u.convergence=(0,n.uniform)(new r.Vector3,`vec3`),this._syncUniforms(),this._colorTexNode=new t.TextureNode,this._albedoTexNode=new t.TextureNode,this._ndTexNode=new t.TextureNode,this._snTexNode=new t.TextureNode,this._motionTexNode=new t.TextureNode,this._placeholders=new Map;let s=()=>{let e=new r.DataTexture(new Float32Array(4),1,1,r.RGBAFormat,r.FloatType);e.needsUpdate=!0;let n=new t.TextureNode(e);return this._placeholders.set(n,e),n};this._nTmpA=s(),this._nTmpB=s(),this._nHist=s(),this._nFast=s(),this._nInternal=s(),this._nGeom=s(),this._nData=s(),this._nStabRead=s(),this._allocStorage(),this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),this.outputTarget=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._compiled=!1,this._needsReset=!0,this._stabPing=0,this._camInitialized=!1,this._dispatchX=Math.ceil(a/Yv),this._dispatchY=Math.ceil(o/Yv),this._buildKernels()}_allocStorage(){let e=()=>Pe(r.HalfFloatType);this._tmpA=e(),this._tmpB=e(),this._hist=e(),this._fastHist=e(),this._internal=e(),this._geomPrev=e(),this._stabA=e(),this._stabB=e(),this._dataT=e()}_disposeStorage(){for(let e of[this._tmpA,this._tmpB,this._hist,this._fastHist,this._internal,this._geomPrev,this._stabA,this._stabB,this._dataT])e?.dispose()}_disposeKernels(){for(let e of this._kernels??[])e?.dispose()}updateParameters(e){if(e){for(let t of Object.keys(e))t===`debugMode`?this.debugMode.value=e.debugMode|0:t in Ev&&(this.settings[t]=e[t]);this._syncUniforms()}}_syncUniforms(){let e=this.settings,t=this.u,n=Math.min(e.maxAccumulatedFrameNum,63),r=Math.min(e.maxStabilizedFrameNum,n),i=Math.max(e.maxBlurRadius,e.minBlurRadius);t.maxAccum.value=n,t.maxFast.value=e.maxFastAccumulatedFrameNum,t.stabilizationStrength.value=r/(1+r),t.historyFixFrameNum.value=e.historyFixFrameNum,t.historyFixStride.value=e.historyFixBasePixelStride,t.prepassBlurRadius.value=e.prepassBlurRadius,t.minBlurRadius.value=e.minBlurRadius,t.maxBlurRadius.value=i,t.lobeAngleFraction.value=e.lobeAngleFraction*e.lobeAngleFraction,t.roughnessFraction.value=e.roughnessFraction,t.planeDistSensitivity.value=e.planeDistanceSensitivity,t.minHitDistanceWeight.value=e.minHitDistanceWeight;let a=Math.min(1,Math.max(0,i/2));t.fastClampSigmaScale.value=3+(e.fastHistoryClampingSigmaScale-3)*a,t.fireflyMinRelativeScale.value=e.fireflySuppressorMinRelativeScale,t.antiFirefly.value=+!!e.enableAntiFirefly,t.antilag.value.set(e.antilagLuminanceSigmaScale,e.antilagLuminanceSensitivity),t.disocclusionThreshold.value=e.disocclusionThreshold,t.convergence.value.set(e.convergenceS,e.convergenceB,e.convergenceP),t.lobeVolumePercent.value=e.lobeVolumePercent,t.handoverFrames.value=e.handoverFrames>0?e.handoverFrames:2*n}_worldPosAt(e,t,n,r){return Qu(e,t,n,r,this.cameraRay)}_viewVector(e,t,r){return(0,n.select)(Yu(this.cameraRay.cameraProjection),r,(0,n.normalize)(t.sub(e)))}_frustumSize(e){return this.minRectDimMulUnproject.mul((0,n.select)(Yu(this.cameraRay.cameraProjection),(0,n.float)(1),e))}_pixelUv(e,t){return(0,n.vec2)((0,n.float)(e).add(.5).div(this.resW),(0,n.float)(t).add(.5).div(this.resH))}_clampCoord(e,t){return(0,n.ivec2)(e.clamp((0,n.int)(0),(0,n.int)(this.resW).sub(1)),t.clamp((0,n.int)(0),(0,n.int)(this.resH).sub(1)))}_uvToCoord(e){return this._clampCoord((0,n.int)(e.x.mul(this.resW)),(0,n.int)(e.y.mul(this.resH)))}_advancedNonLinear(e){let t=this.u.convergence,r=(0,n.saturate)(e.div((0,n.float)(1).add(this.u.maxAccum.mul(t.z)))),i=t.x.mul((0,n.mix)(t.y,(0,n.float)(1),r));return(0,n.float)(1).div((0,n.float)(1).add(i.mul(e)))}_handover(e){return(0,n.saturate)(e.div((0,n.max)(this.u.handoverFrames,1)))}_bilinear(e){let t=e.mul((0,n.vec2)(this.resW,this.resH)).sub(.5),r=(0,n.floor)(t),i=(0,n.saturate)(t.sub(r)),a=(0,n.int)(r.x),o=(0,n.int)(r.y),s=(e,t)=>(0,n.select)(e.greaterThanEqual((0,n.int)(0)).and(t.greaterThanEqual((0,n.int)(0))).and(e.lessThan((0,n.int)(this.resW))).and(t.lessThan((0,n.int)(this.resH))),(0,n.float)(1),(0,n.float)(0));return{f:i,taps:[this._clampCoord(a,o),this._clampCoord(a.add(1),o),this._clampCoord(a,o.add(1)),this._clampCoord(a.add(1),o.add(1))],inScreen:[s(a,o),s(a.add(1),o),s(a,o.add(1)),s(a.add(1),o.add(1))],customWeights:e=>[e[0].mul((0,n.float)(1).sub(i.x)).mul((0,n.float)(1).sub(i.y)),e[1].mul(i.x).mul((0,n.float)(1).sub(i.y)),e[2].mul((0,n.float)(1).sub(i.x)).mul(i.y),e[3].mul(i.x).mul(i.y)],filter:e=>(0,n.mix)((0,n.mix)(e[0],e[1],i.x),(0,n.mix)(e[2],e[3],i.x),i.y)}}_applyCustomWeights(e,t,r){let i=e[0].mul(t[0]).add(e[1].mul(t[1])).add(e[2].mul(t[2])).add(e[3].mul(t[3])),a=t[0].add(t[1]).add(t[2]).add(t[3]);return(0,n.select)(a.lessThan(1e-4),r,i.div((0,n.max)(a,1e-4)))}_sampleHistory(e,t,r,i,a){let o=(0,n.vec4)(0).toVar();return(0,n.If)(a,()=>{let r=(0,n.saturate)(t).mul((0,n.vec2)(this.resW,this.resH)),i=(0,n.floor)(r.sub(.5)).add(.5),a=(0,n.saturate)(r.sub(i)),s=Jv,c=a.mul(a.mul(a.mul(-s).add(2*s)).sub(s)),l=a.mul(a.mul(a.mul(2-s).sub(3-s))).add(1),u=a.mul(a.mul(a.mul(-(2-s)).add(3-2*s)).add(s)),d=a.mul(a.mul(a.mul(s).sub(s))),f=[c.x,l.x,u.x,d.x],p=[c.y,l.y,u.y,d.y],m=(0,n.int)(i.x).sub(1),h=(0,n.int)(i.y).sub(1),g=(0,n.vec4)(0).toVar(),_=(0,n.float)(0).toVar();for(let t=0;t<4;t++)for(let n=0;n<4;n++){if((n===0||n===3)&&(t===0||t===3))continue;let r=f[n].mul(p[t]);g.addAssign(e(this._clampCoord(m.add(n),h.add(t))).mul(r)),_.addAssign(r)}o.assign((0,n.select)(_.lessThan(1e-4),(0,n.vec4)(0),g.div((0,n.max)(_,1e-4))))}).Else(()=>{o.assign(this._applyCustomWeights(r.taps.map(t=>e(t)),i,(0,n.vec4)(0)))}),o}_buildKernels(){this._kPre=this._buildSpatial(`pre`),this._kTa=this._buildTemporalAccumulation(),this._kHf=this._buildHistoryFix(),this._kBlur=this._buildSpatial(`blur`),this._kPost=this._buildSpatial(`post`),this._kTsA=this._buildTemporalStabilization(this._stabA),this._kTsB=this._buildTemporalStabilization(this._stabB),this._kernels=[this._kPre,this._kTa,this._kHf,this._kBlur,this._kPost,this._kTsA,this._kTsB]}_dispatchOf(e){return e(this.camWorld,this.camProjInv).compute([this._dispatchX,this._dispatchY,1],[Yv,Yv,1])}_buildSpatial(e){let t=e===`pre`,{radiusScale:r,fractionScale:i}=Xv[e],a=this.u,o=this._colorTexNode,s=this._albedoTexNode,c=this._ndTexNode,l=this._snTexNode,u=this._nData,d=e===`blur`?this._nTmpA:this._nTmpB,f=e===`blur`?this._tmpB:t?this._tmpA:this._hist,p=this._geomPrev,m=t?this.rotPre:e===`blur`?this.rotBlur:this.rotPost,h=t?a.prepassBlurRadius:a.maxBlurRadius,g=this.camView,_=this.camPos,v=this.resW,y=this.resH,b=this.inputFrames,x=t?e=>{let t=(0,n.textureLoad)(o,e),r=(0,n.textureLoad)(s,e);return(0,n.vec4)(uy(Bc(t.xyz.div((0,n.max)(r.xyz,(0,n.vec3)(Sv))))),zc(r.w,Rc).min(1))}:e=>(0,n.textureLoad)(d,e),S=(0,n.Fn)(([o,s])=>{let d=(0,n.int)(n.workgroupId.x).mul(Yv).add((0,n.int)(n.localId.x)),S=(0,n.int)(n.workgroupId.y).mul(Yv).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(v)).and(S.lessThan((0,n.int)(y))),()=>{let C=(0,n.ivec2)(d,S),w=(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(S)),T=(0,n.textureLoad)(c,C).w.toVar(),E=T.greaterThanEqual(xv),D=(0,n.textureLoad)(l,C).toVar(),O=(0,n.normalize)(D.xyz.mul(2).sub(1)).toVar(),k=D.w.clamp(.05,1).toVar(),A=(0,n.float)(xv).toVar(),j=x(C).toVar();(0,n.If)(E.not(),()=>{let e=this._pixelUv(d,S),f=this._worldPosAt(e,T,o,s).toVar();A.assign(g.mul((0,n.vec4)(f,1)).z.abs()),(0,n.If)(h.greaterThan(0),()=>{let d=(0,n.dot)(O,this._viewVector(f,_,this.viewVector)).abs().toVar(),p=this._frustumSize(A).toVar(),S=b.add(1),w=t?(0,n.max)(b,(0,n.float)(10)):(0,n.textureLoad)(u,C).y.add(b),T=(t?(0,n.float)(1).div(w.add(1)):this._advancedNonLinear(w)).toVar(),E=ny(k,.5).toVar(),D=A.mul(Tv).add(3),M=j.w.toVar(),N=(0,n.saturate)(M.mul(D).div(p)),P=(0,n.float)(1).sub(this._handover(S)),F=(t?N.div(S):N.mul(T)).mul(P),I=a.minBlurRadius.mul((0,n.saturate)((0,n.float)(2).sub(w.div((0,n.max)(a.maxAccum,1))))),L=(0,n.max)((0,n.saturate)((0,n.sqrt)((0,n.saturate)(F)).mul(r)).mul(h).mul(E),I.mul(E)).toVar(),ee=cy(a.planeDistSensitivity,p,f,O).toVar(),te=iy(T,a.lobeAngleFraction,k,a.lobeVolumePercent).div(i).toVar(),R=ay(k,a.roughnessFraction.mul(i)).toVar(),ne=sy(M,T).toVar(),re=a.minHitDistanceWeight.mul(i).mul(E);t||(re=re.mul(T)),re=re.toVar();let ie=(0,n.vec2)(1);if(!t){let e=g.mul((0,n.vec4)(O,0)).xy;ie=(0,n.mix)((0,n.vec2)(1).sub(e.abs()),(0,n.vec2)(1),d),ie=ie.div((0,n.max)(ie.x,ie.y))}let ae=ie.mul((0,n.vec2)((0,n.float)(1).div(v),(0,n.float)(1).div(y))).mul(L).toVar(),oe=(0,n.float)(1).toVar();for(let t=0;t<Qv.length;t++){let r=Qv[t],i=e.add(gy(m,(0,n.vec2)(r[0],r[1])).mul(ae)),a=ly(i),u=(0,n.select)(a.x.notEqual(i.x).or(a.y.notEqual(i.y)),(0,n.float)(1),(0,n.float)(Math.exp(-.66*r[2]*r[2]))).toVar(),d=this._uvToCoord(a),f=(0,n.textureLoad)(c,d).w,p=this._worldPosAt(a,f,o,s),h=(0,n.textureLoad)(l,d),g=ty((0,n.dot)(O,(0,n.normalize)(h.xyz.mul(2).sub(1))));u.mulAssign($v(g,te,(0,n.float)(0))),u.mulAssign($v(h.w,R.x,R.y)),u.mulAssign($v((0,n.dot)(O,p),ee.x,ee.y)),u.assign((0,n.select)(f.greaterThanEqual(xv),(0,n.float)(0),u));let _=_y(u,x(d));u.mulAssign(re.add(ey(_.w,ne.x,ne.y))),oe.addAssign(u),j.addAssign(_.mul(u))}j.divAssign((0,n.max)(oe,1e-6)),t||j.assign((0,n.vec4)(j.xyz,M))})}),(0,n.textureStore)(f,w,j).toWriteOnly(),e===`post`&&(0,n.textureStore)(p,w,(0,n.vec4)(O,A)).toWriteOnly()})});return this._dispatchOf(S)}_buildTemporalAccumulation(){let e=this.u,t=this._ndTexNode,r=this._snTexNode,i=this._motionTexNode,a=this._nTmpA,o=this._nHist,s=this._nFast,c=this._nInternal,l=this._nGeom,u=this._tmpB,d=this._dataT,f=this.camView,p=this.prevCamView,m=this.camPos,h=this.prevCamPos,g=this.resW,_=this.resH,v=this.inputFrames,y=this.resetU,b=(0,n.Fn)(([b,x])=>{let S=(0,n.int)(n.workgroupId.x).mul(Yv).add((0,n.int)(n.localId.x)),C=(0,n.int)(n.workgroupId.y).mul(Yv).add((0,n.int)(n.localId.y));(0,n.If)(S.lessThan((0,n.int)(g)).and(C.lessThan((0,n.int)(_))),()=>{let g=(0,n.ivec2)(S,C),_=(0,n.uvec2)((0,n.uint)(S),(0,n.uint)(C)),w=(0,n.textureLoad)(t,g).w,T=(0,n.textureLoad)(a,g).toVar();(0,n.If)(w.greaterThanEqual(xv),()=>{(0,n.textureStore)(u,_,T).toWriteOnly(),(0,n.textureStore)(d,_,(0,n.vec4)(0)).toWriteOnly(),(0,n.Return)()});let E=e.maxAccum.mul((0,n.float)(1).sub(y)).toVar(),D=e.maxFast.mul((0,n.float)(1).sub(y)).toVar(),O=(0,n.textureLoad)(r,g),k=(0,n.normalize)(O.xyz.mul(2).sub(1)).toVar(),A=O.w.clamp(.05,1).toVar(),j=this._pixelUv(S,C),M=this._worldPosAt(j,w,b,x).toVar(),N=f.mul((0,n.vec4)(M,1)).z.abs().toVar(),P=(0,n.dot)(k,this._viewVector(M,m,this.viewVector)).abs().toVar(),F=this._frustumSize(N).toVar(),I=(0,n.vec3)(0).toVar();I.addAssign(k.mul(.25));for(let e=-1;e<=0;e++)for(let i=-1;i<=0;i++){if(i===0&&e===0)continue;let a=this._clampCoord(S.add(i),C.add(e)),o=(0,n.normalize)((0,n.textureLoad)(r,a).xyz.mul(2).sub(1)),s=(0,n.textureLoad)(t,a).w.lessThan(xv);I.addAssign((0,n.select)(s,o,k).mul(.25))}let L=(0,n.textureLoad)(i,g),ee=j.sub(L.xy).toVar(),te=p.mul((0,n.vec4)(M,1)).z.abs().toVar(),R=this._bilinear(ee),ne=F.mul((0,n.saturate)(e.disocclusionThreshold.div((0,n.max)(P,.05)))).sub(Iv).toVar(),re=(0,n.float)(1).sub(y),ie=[],ae=[];for(let e=0;e<4;e++){let t=(0,n.textureLoad)(l,R.taps[e]),r=(0,n.select)((0,n.dot)(t.xyz,I).greaterThan(qv),(0,n.float)(1),(0,n.float)(0)),i=(0,n.select)(t.w.sub(te).abs().lessThanEqual(ne),(0,n.float)(1),(0,n.float)(0)),a=(0,n.select)(t.w.lessThan(xv),(0,n.float)(1),(0,n.float)(0));ie.push(r.mul(i).mul(a).mul(R.inScreen[e]).mul(re).toVar()),ae.push((0,n.textureLoad)(c,R.taps[e]).x)}let oe=R.customWeights(ie).map(e=>e.toVar()),se=ie[0].add(ie[1]).add(ie[2]).add(ie[3]).greaterThan(3.5).toVar(),ce=ie[0].add(ie[1].mul(2)).add(ie[2].mul(4)).add(ie[3].mul(8)),le=this._applyCustomWeights(ae,oe,(0,n.float)(0)).toVar(),ue=(0,n.dot)(k,this._viewVector(M,h,this.prevViewVector)).abs().add(.001).div(P.add(.001)).toVar();ue.assign((0,n.mix)((0,n.float)(.1),(0,n.float)(1),(0,n.saturate)(ue.mul(ue))));let z=(0,n.sqrt)((0,n.saturate)(R.filter(ie))).mul(ue).toVar();le.assign(le.mul((0,n.mix)(z,(0,n.float)(1),(0,n.float)(1).div(le.add(1))))),le.assign((0,n.min)(le,E));let de=my(this._sampleHistory(e=>(0,n.textureLoad)(o,e),ee,R,oe,se)).toVar(),fe=(0,n.max)(this._applyCustomWeights(R.taps.map(e=>(0,n.textureLoad)(s,e).x),oe,(0,n.float)(0)),0).toVar(),pe=v.add(1),me=this._handover(pe).toVar(),he=le.mul((0,n.float)(1).sub(me)),ge=pe.div(pe.add(he)).toVar(),_e=(0,n.float)(1).div((0,n.float)(1).add(ny(A,.25).mul(.5).mul(E))),ve=(0,n.vec4)((0,n.mix)(de.xyz,T.xyz,ge),(0,n.mix)(de.w,T.w,(0,n.max)(ge,_e))).toVar(),ye=e.fireflyMinRelativeScale.add((0,n.float)(Wv).div(le.add(1))).toVar(),B=le.mul(e.maxBlurRadius).mul(Gv).toVar();B.assign(B.div(B.add(1)).mul((0,n.float)(1).sub(me)));let be=(0,n.mix)(ve.x,(0,n.min)(ve.x,de.x.mul(ye)),B);ve.assign(py(ve,be));let xe=(0,n.float)(1.2).add((0,n.float)(1).div(le.add(1)));ve.assign((0,n.vec4)(ve.xyz,(0,n.mix)(ve.w,(0,n.min)(ve.w,de.w.mul(xe)),B))),(0,n.textureStore)(u,_,ve).toWriteOnly();let Se=(0,n.min)(le,D).mul((0,n.float)(1).sub(me)),Ce=pe.div(pe.add(Se)),V=(0,n.mix)(fe,T.x,Ce).toVar(),we=(0,n.min)(V,de.x.mul(ye).mul(Kv));V.assign((0,n.mix)(V,we,B)),(0,n.textureStore)(d,_,(0,n.vec4)(V,le,ce,(0,n.select)(se,(0,n.float)(1),(0,n.float)(0)))).toWriteOnly()})});return this._dispatchOf(b)}_buildHistoryFix(){let e=this.u,t=this._ndTexNode,r=this._snTexNode,i=this._nTmpB,a=this._nData,o=this._tmpA,s=this._fastHist,c=this.camView,l=this.resW,u=this.resH,d=this.inputFrames,f=(0,n.Fn)(([f,p])=>{let m=(0,n.int)(n.workgroupId.x).mul(Yv).add((0,n.int)(n.localId.x)),h=(0,n.int)(n.workgroupId.y).mul(Yv).add((0,n.int)(n.localId.y));(0,n.If)(m.lessThan((0,n.int)(l)).and(h.lessThan((0,n.int)(u))),()=>{let g=(0,n.ivec2)(m,h),_=(0,n.uvec2)((0,n.uint)(m),(0,n.uint)(h)),v=(0,n.textureLoad)(t,g).w;(0,n.If)(v.greaterThanEqual(xv),()=>{let e=(0,n.textureLoad)(i,g);(0,n.textureStore)(o,_,e).toWriteOnly(),(0,n.textureStore)(s,_,(0,n.vec4)(e.x,0,0,0)).toWriteOnly(),(0,n.Return)()});let y=(0,n.textureLoad)(a,g).toVar(),b=y.y.toVar(),x=b.add(d),S=this._handover(d.add(1)).toVar(),C=(0,n.textureLoad)(r,g),w=(0,n.normalize)(C.xyz.mul(2).sub(1)).toVar(),T=C.w.clamp(.05,1).toVar(),E=this._pixelUv(m,h),D=this._worldPosAt(E,v,f,p).toVar(),O=c.mul((0,n.vec4)(D,1)).z.abs(),k=this._frustumSize(O).toVar(),A=(0,n.textureLoad)(i,g).toVar(),j=(0,n.float)(1).div(x.add(1)).toVar(),M=O.mul(Tv).add(3),N=(0,n.saturate)(A.w.mul(M).div(k)),P=A.w.toVar(),F=(0,n.round)((0,n.select)(x.lessThan(e.historyFixFrameNum),(0,n.float)(1),(0,n.float)(0)).mul(.5).mul(2/Bv).mul(e.historyFixStride).mul((0,n.mix)((0,n.float)(.25).add((0,n.sqrt)(N).mul(.75)),(0,n.float)(1),j))).toVar();(0,n.If)(F.notEqual(0),()=>{let o=iy(j,e.lobeAngleFraction,T,e.lobeVolumePercent).toVar(),s=cy(e.planeDistSensitivity,k,D,w).toVar(),c=sy(P,j).toVar(),d=oy(T.mul(T),(0,n.sqrt)(e.roughnessFraction),Rv).toVar(),m=(0,n.float)(1).add(b).toVar();A.mulAssign(m);for(let e=-Bv;e<=Bv;e++)for(let h=-Bv;h<=Bv;h++){if(h===0&&e===0||Math.abs(h)+Math.abs(e)===Bv*2)continue;let g=ly(E.add((0,n.vec2)(h,e).mul(F).mul((0,n.vec2)((0,n.float)(1).div(l),(0,n.float)(1).div(u))))),_=this._uvToCoord(g),v=(0,n.textureLoad)(t,_).w,y=this._worldPosAt(g,v,f,p),b=(0,n.textureLoad)(r,_),x=ey(ty((0,n.dot)((0,n.normalize)(b.xyz.mul(2).sub(1)),w)),o,(0,n.float)(0)).toVar();x.mulAssign(ey(b.w.mul(b.w),d.x,d.y)),x.mulAssign((0,n.float)(1).add((0,n.textureLoad)(a,_).y)),x.mulAssign($v((0,n.dot)(w,y),s.x,s.y)),x.assign((0,n.select)(v.greaterThanEqual(xv),(0,n.float)(0),x));let S=_y(x,(0,n.textureLoad)(i,_));x.mulAssign(ey(S.w,c.x,c.y)),m.addAssign(x),A.addAssign(S.mul(x))}A.divAssign((0,n.max)(m,1e-6))});let I=A.x.toVar(),L=(0,n.saturate)(b.div((0,n.max)(e.historyFixFrameNum,Iv))),ee=(0,n.mix)(I,y.x,L).toVar();(0,n.textureStore)(s,_,(0,n.vec4)(ee,0,0,0)).toWriteOnly();let te=ee.toVar(),R=ee.mul(ee).toVar(),ne=(0,n.float)(0).toVar(),re=(0,n.float)(0).toVar(),ie=(e,r,i)=>{let o=this._clampCoord(m.add(e),h.add(r)),s=(0,n.textureLoad)(t,o).w,c=(0,n.select)(s.greaterThanEqual(xv),ee,(0,n.textureLoad)(a,o).x);Math.abs(e)<=Vv&&Math.abs(r)<=Vv&&(te.addAssign(c),R.addAssign(c.mul(c))),i&&(ne.addAssign(c),re.addAssign(c.mul(c)))},ae=e.antiFirefly.greaterThan(.5);for(let e=-Vv;e<=Vv;e++)for(let t=-Vv;t<=Vv;t++)t===0&&e===0||ie(t,e,Math.abs(t)>1||Math.abs(e)>1);(0,n.If)(ae,()=>{for(let e=-Hv;e<=Hv;e++)for(let t=-Hv;t<=Hv;t++)Math.abs(t)<=Vv&&Math.abs(e)<=Vv||ie(t,e,!0)}),(0,n.If)(ae,()=>{let e=1/((Hv*2+1)**2-9),t=ne.mul(e),r=hy(t,re.mul(e)).mul(Uv);I.assign((0,n.mix)(I.clamp(t.sub(r),t.add(r)),I,S))});{let t=1/(Vv*2+1)**2,r=te.mul(t),i=hy(r,R.mul(t)).mul(e.fastClampSigmaScale),a=I.clamp(r.sub(i),r.add(i)),o=(0,n.select)(e.maxFast.lessThan(e.maxAccum),(0,n.float)(1),(0,n.float)(0)),s=(0,n.mix)((0,n.float)(1).div((0,n.float)(1).add(o.mul(b).mul(2))),(0,n.float)(1),S);I.assign((0,n.mix)(a,I,s))}(0,n.textureStore)(o,_,py(A,I)).toWriteOnly()})});return this._dispatchOf(f)}_buildTemporalStabilization(e){let t=this.u,r=this._colorTexNode,i=this._albedoTexNode,a=this._ndTexNode,o=this._snTexNode,s=this._motionTexNode,c=this._nHist,l=this._nData,u=this._nStabRead,d=this._internal,f=this._tmpA,p=this.resW,m=this.resH,h=this.inputFrames,g=this.resetU,_=this.debugMode;return(0,n.Fn)(()=>{let v=(0,n.int)(n.workgroupId.x).mul(Yv).add((0,n.int)(n.localId.x)),y=(0,n.int)(n.workgroupId.y).mul(Yv).add((0,n.int)(n.localId.y));(0,n.If)(v.lessThan((0,n.int)(p)).and(y.lessThan((0,n.int)(m))),()=>{let p=(0,n.ivec2)(v,y),m=(0,n.uvec2)((0,n.uint)(v),(0,n.uint)(y)),b=(0,n.textureLoad)(a,p).w,x=(0,n.textureLoad)(r,p).toVar();(0,n.If)(b.greaterThanEqual(xv),()=>{(0,n.textureStore)(f,m,x).toWriteOnly(),(0,n.textureStore)(e,m,(0,n.vec4)((0,n.textureLoad)(c,p).x,0,0,0)).toWriteOnly(),(0,n.textureStore)(d,m,(0,n.vec4)(0,1,0,0)).toWriteOnly(),(0,n.Return)()});let S=(0,n.textureLoad)(o,p).w.clamp(.05,1),C=this._pixelUv(v,y),w=(0,n.textureLoad)(s,p),T=C.sub(w.xy).toVar(),E=(0,n.textureLoad)(l,p).toVar(),D=E.y.toVar(),O=(0,n.uint)(E.z.add(.5)).toVar(),k=E.w.greaterThan(.5),A=this._bilinear(T),j=[1,2,4,8].map(e=>(0,n.select)(O.bitAnd((0,n.uint)(e)).notEqual((0,n.uint)(0)),(0,n.float)(1),(0,n.float)(0))),M=A.customWeights(j).map(e=>e.toVar()),N=(0,n.sqrt)((0,n.saturate)(A.filter(j))).toVar(),P=(0,n.textureLoad)(c,p).toVar(),F=P.x.toVar(),I=F.toVar(),L=F.mul(F).toVar();for(let e=-1;e<=1;e++)for(let t=-1;t<=1;t++){if(t===0&&e===0)continue;let r=this._clampCoord(v.add(t),y.add(e)),i=(0,n.textureLoad)(a,r).w,o=(0,n.select)(i.greaterThanEqual(xv),F,(0,n.textureLoad)(c,r).x);I.addAssign(o),L.addAssign(o.mul(o))}I.divAssign(9),L.divAssign(9);let ee=hy(I,L).toVar();(0,n.If)(D.lessThan(t.historyFixFrameNum),()=>{F.assign((0,n.min)(F,I.mul((0,n.float)(1.2).add((0,n.float)(1).div(D.add(1))))))});let te=(0,n.max)(this._sampleHistory(e=>(0,n.textureLoad)(u,e),T,A,M,k).x,0).toVar(),R=ee.mul(t.antilag.x),ne=t.antilag.y.mul(4),re=te.clamp(I.sub(R),I.add(R)),ie=te.sub(re).abs().div((0,n.max)(te,re).add(Iv)),ae=(0,n.float)(1).div((0,n.float)(1).add(ie.mul(D.mul(N)).div(ne))).toVar(),oe=(0,n.min)(D,t.historyFixFrameNum);D.assign((0,n.mix)(oe,D,ae));let se=h.add(1),ce=this._handover(se),le=N.mul((0,n.float)(1).sub(this._advancedNonLinear(D.mul((0,n.float)(1).sub(ce)).div(se)))).mul(ae).toVar(),ue=(0,n.float)(1).add(le.mul(6)),z=t.stabilizationStrength.mul((0,n.float)(1).sub(g)),de=(0,n.mix)(F,te.clamp(I.sub(ee.mul(ue)),I.add(ee.mul(ue))),(0,n.min)(le,z)).toVar();P.assign(py(P,de)),(0,n.textureStore)(e,m,(0,n.vec4)(de,0,0,0)).toWriteOnly();let fe=t.maxAccum.mul((0,n.float)(1).sub(g));(0,n.textureStore)(d,m,(0,n.vec4)((0,n.min)(D.add(1),fe),S,0,0)).toWriteOnly();let pe=(0,n.textureLoad)(i,p),me=(0,n.vec4)(dy(P.xyz).mul((0,n.max)(pe.xyz,(0,n.vec3)(Sv))),x.w).toVar();(0,n.If)(_.equal((0,n.int)(1)),()=>{let e=(0,n.saturate)(D.div((0,n.max)(t.maxAccum,1)));me.assign((0,n.vec4)((0,n.float)(1).sub(e),e,.2,1))}).ElseIf(_.equal((0,n.int)(2)),()=>{me.assign((0,n.vec4)((0,n.vec3)(P.w),1))}).ElseIf(_.equal((0,n.int)(3)),()=>{me.assign((0,n.vec4)((0,n.vec3)(S),1))}).ElseIf(_.equal((0,n.int)(4)),()=>{let e=E.x.div(E.x.add(1));me.assign((0,n.vec4)((0,n.vec3)(e),1))}).ElseIf(_.equal((0,n.int)(5)),()=>{me.assign((0,n.vec4)((0,n.vec3)(E.z.div(15)),1))}),(0,n.textureStore)(f,m,me).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[Yv,Yv,1])}setupEventListeners(){this.on(`pipeline:historyReset`,()=>this.resetHistory())}resetHistory(){this._needsReset=!0}_updateCamera(){let e=this.pathTracer;if(!e?.uniforms)return;let t=e.uniforms.get(`cameraWorldMatrix`).value,n=e.uniforms.get(`cameraViewMatrix`).value,r=e.uniforms.get(`cameraProjectionMatrixInverse`).value,i=e.uniforms.get(`cameraProjectionMatrix`).value;this._camInitialized&&(this.prevCamView.value.copy(this.camView.value),this.prevCamPos.value.copy(this.camPos.value),this.prevViewVector.value.copy(this.viewVector.value)),this.camWorld.value.copy(t),this.camProjInv.value.copy(r),this.camView.value.copy(n),this.camPos.value.setFromMatrixPosition(t),this.viewVector.value.setFromMatrixColumn(t,2).normalize(),this.cameraRay.sync(e.uniforms),this._camInitialized||=(this.prevCamView.value.copy(n),this.prevCamPos.value.copy(this.camPos.value),this.prevViewVector.value.copy(this.viewVector.value),!0);let a=i.elements[5]||1,o=1/(.5*this.resH.value*a);this.minRectDimMulUnproject.value=Math.min(this.resW.value,this.resH.value)*o}_updateRotators(e){let t=(t,n)=>{let r=vy(e*3+n)*Math.PI*2;t.value.set(Math.cos(r),Math.sin(r),-Math.sin(r),Math.cos(r))};t(this.rotPre,0),t(this.rotBlur,1),t(this.rotPost,2)}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:color`),n=e.getTexture(`pathtracer:albedo`),r=e.getTexture(`pathtracer:normalDepth`),i=e.getTexture(`pathtracer:shadingNormal`),a=e.getTexture(`motionVector:screenSpace`);if(!t)return;if(!n||!r||!i||!a){e.setTexture(`nrd:output`,t);return}let o=t.image;o&&o.width>0&&o.height>0&&(o.width!==this.outputTarget.width||o.height!==this.outputTarget.height)&&this.setSize(o.width,o.height);let s=e.getState(`pathtracer:samples`)??this.pathTracer?.frameCount??0;if(s+1>=this.u.handoverFrames.value){e.setTexture(`nrd:output`,t),this._needsReset=!0;return}if(this._colorTexNode.value=t,this._albedoTexNode.value=n,this._ndTexNode.value=r,this._snTexNode.value=i,this._motionTexNode.value=a,this._updateCamera(),this.inputFrames.value=s,this._updateRotators(this.pathTracer?.uniforms?.get(`seedFrame`)?.value??e.getState(`frame`)??0),this.resetU.value=+!!this._needsReset,!this._compiled){for(let e of this._kernels)this.renderer.compute(e);this._compiled=!0}this._nTmpA.value=this._tmpA,this._nTmpB.value=this._tmpB,this._nHist.value=this._hist,this._nFast.value=this._fastHist,this._nInternal.value=this._internal,this._nGeom.value=this._geomPrev,this._nData.value=this._dataT,this._nStabRead.value=this._stabPing===0?this._stabB:this._stabA,this.renderer.compute(this._kPre),this.renderer.compute(this._kTa),this.renderer.compute(this._kHf),this.renderer.compute(this._kBlur),this.renderer.compute(this._kPost),this.renderer.compute(this._stabPing===0?this._kTsA:this._kTsB),this._srcRegion.max.set(this.outputTarget.width,this.outputTarget.height),this.renderer.copyTextureToTexture(this._tmpA,this.outputTarget.texture,this._srcRegion),e.setTexture(`nrd:output`,this.outputTarget.texture),this._stabPing=1-this._stabPing,this._needsReset=!1,this._needsReset=!1}setSize(e,t){this.outputTarget.setSize(e,t),this.outputTarget.texture.needsUpdate=!0,this.resW.value=e,this.resH.value=t,this._dispatchX=Math.ceil(e/Yv),this._dispatchY=Math.ceil(t/Yv);let n=[this._dispatchX,this._dispatchY,1];for(let e of this._kernels)e&&(e.dispatchSize=n);this._needsReset=!0}releaseGPUMemory(){this._disposeStorage(),this.context?.removeTexture(`nrd:output`),this.outputTarget?.texture?.dispose(),this._needsReset=!0}reallocateReservedStorage(){this._disposeKernels(),this._disposeStorage();for(let[e,t]of this._placeholders)e.value=t;this._allocStorage(),this._buildKernels(),this._compiled=!1,this._needsReset=!0,this._stabPing=0}dispose(){this._releaseHitDistance?.(),this._releaseHitDistance=null,this._disposeKernels(),this._disposeStorage(),this.outputTarget?.dispose();for(let e of[this._colorTexNode,this._albedoTexNode,this._ndTexNode,this._snTexNode,this._motionTexNode])e?.dispose();for(let[e,t]of this._placeholders)e.dispose(),t.dispose();this._placeholders.clear()}};hl();var by=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,1e7),xy=(0,n.wgslFn)(`
|
|
916
916
|
fn temporalAccumulate(
|
|
917
917
|
lum: f32,
|
|
918
918
|
prevMean: f32,
|