rayzee 9.4.1 → 9.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -4
- package/dist/rayzee.es.js +9 -55
- package/dist/rayzee.umd.js +4 -4
- package/package.json +1 -1
- package/src/EngineDefaults.js +1 -6
- package/src/PathTracerApp.js +1 -1
- package/src/Processor/SimpleSky.js +1 -62
- package/src/managers/EnvironmentManager.js +9 -58
package/dist/rayzee.umd.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require(`three/webgpu`),require(`three/tsl`),require(`three`),require(`three/addons/lights/RectAreaLightTexturesLib.js`),require(`three/addons/helpers/RectAreaLightHelper.js`),require(`three/addons/loaders/GLTFLoader.js`),require(`three/addons/loaders/HDRLoader.js`),require(`three/addons/loaders/DRACOLoader.js`),require(`three/addons/loaders/KTX2Loader.js`),require(`three/addons/loaders/EXRLoader.js`),require(`three/addons/utils/SceneUtils.js`),require(`three/addons/utils/SkeletonUtils.js`),require(`three/addons/libs/meshopt_decoder.module.js`),require(`three/addons/libs/fflate.module.js`),require(`three/addons/controls/OrbitControls.js`),require(`three/addons/tsl/display/OutlineNode.js`),require(`three/addons/controls/TransformControls.js`)):typeof define==`function`&&define.amd?define([`exports`,`three/webgpu`,`three/tsl`,`three`,`three/addons/lights/RectAreaLightTexturesLib.js`,`three/addons/helpers/RectAreaLightHelper.js`,`three/addons/loaders/GLTFLoader.js`,`three/addons/loaders/HDRLoader.js`,`three/addons/loaders/DRACOLoader.js`,`three/addons/loaders/KTX2Loader.js`,`three/addons/loaders/EXRLoader.js`,`three/addons/utils/SceneUtils.js`,`three/addons/utils/SkeletonUtils.js`,`three/addons/libs/meshopt_decoder.module.js`,`three/addons/libs/fflate.module.js`,`three/addons/controls/OrbitControls.js`,`three/addons/tsl/display/OutlineNode.js`,`three/addons/controls/TransformControls.js`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.Rayzee={},e.THREE,e.THREE,e.THREE,e.THREE,e.THREE,e.THREE,e.THREE,e.THREE,e.THREE,e.THREE,e.THREE,e.THREE,e.THREE,e.THREE,e.THREE,e.THREE,e.THREE))})(this,function(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var v=Object.defineProperty,y=(e,t)=>()=>(e&&(t=e(e=0)),t),b=(e,t)=>{let n={};for(var r in e)v(n,r,{get:e[r],enumerable:!0});return t||v(n,Symbol.toStringTag,{value:`Module`}),n},x=t.WebGPUBackend.prototype.createNodeBuilder;t.WebGPUBackend.prototype.createNodeBuilder=function(e,t){let n=x.call(this,e,t);return Object.defineProperty(n,`allowGlobalVariables`,{get(){return this.material!==null},set(){},configurable:!0}),n};function S(e,n,r=Float32Array){let i=new t.StorageInstancedBufferAttribute(new r(0),n);return i.count=e,i.gpuByteLength=e*n*r.BYTES_PER_ELEMENT,i.isGPUOnly=!0,i}var C=t.WebGPUBackend.prototype.createStorageAttribute;t.WebGPUBackend.prototype.createStorageAttribute=function(e){let t=this.attributeUtils._getBufferAttribute(e);if(!t.isGPUOnly)return C.call(this,e);let n=this.get(t);n.buffer===void 0&&(n.buffer=this.device.createBuffer({label:t.name,size:t.gpuByteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}))};function w(e,t,n){let r=e.backend;r.createStorageAttribute(t);let i=r.get(t).buffer,a=0;for(let e of n)r.device.queue.writeBuffer(i,a,e,0,e.length),a+=e.byteLength;if(a!==t.gpuByteLength)throw RangeError(`uploadStorageChunks wrote ${a} bytes into a ${t.gpuByteLength}-byte buffer`)}function T(e,t,n,r,i){let a=e.backend;a.createStorageAttribute(t);let o=a.get(t).buffer,s=n.recordsPerChunk*n.lanesPerRecord,c=n.chunks[0].BYTES_PER_ELEMENT,l=r+i,u=r;for(;u<l;){let e=Math.floor(u/s),t=n.chunks[e],r=u-e*s,i=Math.min(t.length-r,l-u);a.device.queue.writeBuffer(o,u*c,t,r,i),u+=i}}var E=t.WebGPUBackend.prototype.updateAttribute;t.WebGPUBackend.prototype.updateAttribute=function(e){if(!this.attributeUtils._getBufferAttribute(e).isGPUOnly)return E.call(this,e)};var D=4096;function O(e){if(!this.trackTimestamp||this.isDisposed||this.currentQueryIndex+2>this.maxQueries)return null;let t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e,t),t}var k=t.WebGPUBackend.prototype.initTimestampQuery;t.WebGPUBackend.prototype.initTimestampQuery=function(e,t,n){let r=this.trackTimestamp&&!this.timestampQueryPool[e];if(k.call(this,e,t,n),r){let r=this.timestampQueryPool[e];if(r&&r.maxQueries<D&&n.timestampWrites){let i=r.constructor,a=new i(this.device,e,D);a.allocateQueriesForContext=O,a.allocateQueriesForContext(t),this.timestampQueryPool[e]=a,n.timestampWrites.querySet=a.querySet,r.dispose()}}let i=n.timestampWrites;i&&i.beginningOfPassWriteIndex==null&&(n.timestampWrites=void 0)};function A(e,t){return new Proxy(e,{get(e,n,r){if(typeof n==`string`&&t.has(n))return e.get(n);let i=Reflect.get(e,n,r);return n===`toVar`&&typeof i==`function`?(...n)=>A(i.apply(e,n),t):i}})}function j(e,t=null){let r=(0,n.struct)(e,t),i=new Set(Object.keys(e)),a=(...e)=>A(r(...e),i);return a.layout=r.layout,a.isStruct=!0,a.wrap=e=>A(e,i),a}t.ContextNode.prototype.setup=function(e){let t=e.addContext(this.value);this.node.build(e),e.setContext(t)};var M=class{constructor(){this.scene=new r.Scene,this._helpers=new Map,this.visible=!1}add(e){if(this._helpers.has(e.uuid))return this._helpers.get(e.uuid);let t=this._createHelper(e);return t?(this._helpers.set(e.uuid,t),this.scene.add(t),t):null}remove(e){let t=this._helpers.get(e.uuid);t&&(t.dispose(),this.scene.remove(t),this._helpers.delete(e.uuid))}has(e){return this._helpers.has(e.uuid)}get isDrawing(){return this.visible&&this._helpers.size>0}update(){for(let e of this._helpers.values())e.update?.()}sync(e){let t=new Set(e.map(e=>e.uuid));for(let[e,n]of this._helpers)t.has(e)||(n.dispose(),this.scene.remove(n),this._helpers.delete(e));for(let t of e)this.add(t)}clear(){for(let e of this._helpers.values())e.dispose(),this.scene.remove(e);this._helpers.clear()}render(e,t){if(!this.isDrawing)return;let n=e.autoClear;e.autoClear=!1,e.clearDepth(),e.setRenderTarget(null),e.render(this.scene,t),e.autoClear=n}dispose(){this.clear()}_createHelper(e){return e.isRectAreaLight?new a.RectAreaLightHelper(e):e.isPointLight?new r.PointLightHelper(e,.5):e.isSpotLight?new r.SpotLightHelper(e):e.isDirectionalLight?new r.DirectionalLightHelper(e,.5):null}},N={ALWAYS:`always`,PER_CYCLE:`per_cycle`,PER_TILE:`per_tile`,CONDITIONAL:`conditional`},P=class{constructor(e,t={}){this.name=e,this.enabled=t.enabled!==!1,this.executionMode=t.executionMode||N.ALWAYS,this.context=null,this.eventBus=null}initialize(e,t){this.context=e,this.eventBus=t,this.setupEventListeners()}setupEventListeners(){}shouldExecuteThisFrame(e){if(!this.enabled)return!1;let t=e.getState(`renderMode`)||0,n=e.getState(`tileRenderingComplete`);switch(this.executionMode){case N.ALWAYS:return!0;case N.PER_CYCLE:return t===0?!0:n===!0;case N.PER_TILE:return!0;case N.CONDITIONAL:return this.shouldExecute(e);default:return this.warn(`Unknown execution mode: ${this.executionMode}`),!0}}shouldExecute(e){return!0}render(e,t){throw Error(`render() must be implemented in ${this.name}`)}reset(){}setSize(e,t){}dispose(){}emit(e,t){this.eventBus&&this.eventBus.emit(e,t)}on(e,t){this.eventBus&&this.eventBus.on(e,t)}once(e,t){this.eventBus&&this.eventBus.once(e,t)}off(e,t){this.eventBus&&this.eventBus.off(e,t)}enable(){this.enabled||(this.enabled=!0,this.emit(`stage:enabled`,{stage:this.name}))}disable(){this.enabled&&(this.enabled=!1,this.emit(`stage:disabled`,{stage:this.name}))}toggle(){this.enabled?this.disable():this.enable()}isEnabled(){return this.enabled}log(...e){console.log(`[${this.name}]`,...e)}warn(...e){console.warn(`[${this.name}]`,...e)}error(...e){console.error(`[${this.name}]`,...e)}},F=class{constructor(e,t,n={}){this.renderer=e,this.material=t,this.interactionModeEnabled=n.enabled===void 0?!0:n.enabled,this.interactionDelay=n.delay||100,this.interactionMode=!1,this.interactionTimeout=null,this.originalValues={},this.appliedValues={},this.wasAccumulationEnabled=!0,this.interactionQualitySettings={enableAccumulation:!1,...n.qualitySettings},this.onEnterCallback=n.onEnter||null,this.onExitCallback=n.onExit||null,this.onResetCallback=n.onReset||null}enterInteractionMode(){this.interactionModeEnabled&&(this.interactionMode?clearTimeout(this.interactionTimeout):(this.interactionMode=!0,this.originalValues={},this.appliedValues={},this.material.uniforms.enableAccumulation&&(this.wasAccumulationEnabled=this.material.uniforms.enableAccumulation.value),Object.keys(this.interactionQualitySettings).forEach(e=>{e===`pixelRatio`?(this.originalValues.dpr=this.renderer.getPixelRatio(),this.renderer.setPixelRatio(this.interactionQualitySettings.pixelRatio)):e===`enableAccumulation`||this.material.uniforms[e]&&(this.originalValues[e]=this.material.uniforms[e].value,this.material.uniforms[e].value=this._resolveQualityValue(e,this.interactionQualitySettings[e]),this.appliedValues[e]=this.material.uniforms[e].value)}),this.material.uniforms.enableAccumulation&&(this.originalValues.enableAccumulation=this.material.uniforms.enableAccumulation.value,this.material.uniforms.enableAccumulation.value=!1),this.material.uniforms.cameraIsMoving&&(this.originalValues.cameraIsMoving=this.material.uniforms.cameraIsMoving.value,this.material.uniforms.cameraIsMoving.value=!0),this.onEnterCallback&&this.onEnterCallback()),this.interactionTimeout=setTimeout(()=>{this.exitInteractionMode()},this.interactionDelay))}exitInteractionMode(){this.interactionMode&&(Object.keys(this.originalValues).forEach(e=>{if(e===`dpr`)this.renderer.setPixelRatio(this.originalValues.dpr);else if(this.material.uniforms[e]){let t=this.appliedValues[e];(t===void 0||this.material.uniforms[e].value===t)&&(this.material.uniforms[e].value=this.originalValues[e])}}),this.interactionMode=!1,this.originalValues={},this.appliedValues={},this.onExitCallback&&this.onExitCallback(),this.onResetCallback&&this.onResetCallback())}updateInteractionMode(e){e&&this.enterInteractionMode()}setInteractionModeEnabled(e){this.interactionModeEnabled=e,!e&&this.interactionMode&&(clearTimeout(this.interactionTimeout),this.exitInteractionMode())}updateQualitySettings(e){Object.assign(this.interactionQualitySettings,e),this.interactionMode&&Object.keys(e).forEach(t=>{t===`pixelRatio`?this.renderer.setPixelRatio(e.pixelRatio):this.material.uniforms[t]&&(this.material.uniforms[t].value=this._resolveQualityValue(t,e[t]),this.appliedValues[t]=this.material.uniforms[t].value)})}_resolveQualityValue(e,t){return typeof t==`function`?t(this.originalValues[e]??this.material.uniforms[e].value):t}setInteractionDelay(e){this.interactionDelay=e}getState(){return{interactionMode:this.interactionMode,interactionModeEnabled:this.interactionModeEnabled,interactionDelay:this.interactionDelay,hasTimeout:this.interactionTimeout!==null,qualitySettings:{...this.interactionQualitySettings},originalValues:{...this.originalValues},wasAccumulationEnabled:this.wasAccumulationEnabled}}forceExitInteractionMode(){this.interactionTimeout&&=(clearTimeout(this.interactionTimeout),null),this.exitInteractionMode()}isInInteractionMode(){return this.interactionMode}setCallbacks(e){e.onEnter&&(this.onEnterCallback=e.onEnter),e.onExit&&(this.onExitCallback=e.onExit),e.onReset&&(this.onResetCallback=e.onReset)}static createQualityPreset(e){let t={"ultra-low":{maxBounceCount:1,pixelRatio:.125,enableAccumulation:!1},low:{maxBounceCount:1,pixelRatio:.25,enableAccumulation:!1},medium:{maxBounceCount:2,pixelRatio:.5,enableAccumulation:!1},high:{maxBounceCount:3,pixelRatio:.75,enableAccumulation:!0}};return t[e]||t.low}dispose(){this.interactionTimeout&&=(clearTimeout(this.interactionTimeout),null),this.interactionMode&&this.forceExitInteractionMode(),this.onEnterCallback=null,this.onExitCallback=null,this.onResetCallback=null}},I,L,R=y((()=>{I={RENDER_COMPLETE:`engine:renderComplete`,RENDER_RESET:`engine:renderReset`,FRAME:`engine:frame`,DENOISING_START:`engine:denoisingStart`,DENOISING_END:`engine:denoisingEnd`,UPSCALING_START:`engine:upscalingStart`,UPSCALING_PROGRESS:`engine:upscalingProgress`,UPSCALING_END:`engine:upscalingEnd`,LOADING_UPDATE:`engine:loadingUpdate`,LOADING_RESET:`engine:loadingReset`,STATS_UPDATE:`engine:statsUpdate`,OBJECT_SELECTED:`engine:objectSelected`,OBJECT_DESELECTED:`engine:objectDeselected`,OBJECT_DOUBLE_CLICKED:`engine:objectDoubleClicked`,SELECT_MODE_CHANGED:`engine:selectModeChanged`,OBJECT_TRANSFORM_START:`engine:objectTransformStart`,OBJECT_TRANSFORM_END:`engine:objectTransformEnd`,TRANSFORM_MODE_CHANGED:`engine:transformModeChanged`,CAMERA_SWITCHED:`engine:cameraSwitched`,CAMERAS_UPDATED:`engine:camerasUpdated`,FOCUS_CHANGED:`engine:focusChanged`,AUTO_FOCUS_UPDATED:`engine:autoFocusUpdated`,ORTHO_HEIGHT_UPDATED:`engine:orthoHeightUpdated`,AUTO_EXPOSURE_UPDATED:`engine:autoExposureUpdated`,AF_POINT_PLACED:`engine:afPointPlaced`,SETTING_CHANGED:`engine:settingChanged`,ANIMATION_STARTED:`engine:animationStarted`,ANIMATION_PAUSED:`engine:animationPaused`,ANIMATION_STOPPED:`engine:animationStopped`,ANIMATION_FINISHED:`engine:animationFinished`,TIMELINE_CHANGED:`engine:timelineChanged`,VIDEO_RENDER_PROGRESS:`engine:videoRenderProgress`,VIDEO_RENDER_COMPLETE:`engine:videoRenderComplete`,DISPOSE:`engine:dispose`,DEVICE_LOST:`engine:deviceLost`,ISSUE:`engine:issue`,MODEL_LOADED:`engine:modelLoaded`,OBJECT3D_LOADED:`engine:object3dLoaded`,MODEL_ADDED:`engine:modelAdded`,SCENE_OBJECT_REMOVED:`engine:sceneObjectRemoved`,SCENE_UNLOADED:`engine:sceneUnloaded`,SCENE_REBUILD:`engine:sceneRebuild`,SCENE_SPILLED:`engine:sceneSpilled`,SCENE_METADATA_APPLIED:`engine:sceneMetadataApplied`,ENVIRONMENT_LOADED:`engine:environmentLoaded`,TEXTURES_REPROCESSED:`engine:texturesReprocessed`,RESOLUTION_CHANGED:`engine:resolutionChanged`,RESERVED_RENDER_SIZE_CHANGED:`engine:reservedRenderSizeChanged`,STORAGE_CHANGED:`engine:storageChanged`},L=Object.freeze({[I.RENDER_COMPLETE]:`RenderComplete`,[I.RENDER_RESET]:`RenderReset`,[I.CAMERA_SWITCHED]:`CameraSwitched`,[I.CAMERAS_UPDATED]:`CamerasUpdated`,[I.FOCUS_CHANGED]:`focusChanged`,[I.MODEL_LOADED]:`ModelLoaded`,[I.OBJECT3D_LOADED]:`Object3DLoaded`,[I.MODEL_ADDED]:`ModelAdded`,[I.SCENE_OBJECT_REMOVED]:`SceneObjectRemoved`,[I.SCENE_UNLOADED]:`SceneUnloaded`,[I.SCENE_REBUILD]:`SceneRebuild`,[I.SCENE_SPILLED]:`SceneSpilled`,[I.SCENE_METADATA_APPLIED]:`SceneMetadataApplied`,[I.ENVIRONMENT_LOADED]:`EnvironmentLoaded`,[I.TEXTURES_REPROCESSED]:`TexturesReprocessed`,[I.RESOLUTION_CHANGED]:`resolution_changed`,[I.RESERVED_RENDER_SIZE_CHANGED]:`reserved_render_size_changed`})}));R();var ee=null;function te(e){ee=e}var ne=()=>ee?.({type:I.LOADING_RESET}),z=e=>{ee?.({type:I.LOADING_UPDATE,...e})},B=e=>{ee?.({type:I.STATS_UPDATE,...e})};function re(e){return e.frameCount||0}function ie(e){if(Array.isArray(e))e.forEach(e=>{e.userData&&e.userData.isFallback||(ae(e),e.dispose())});else{if(e.userData&&e.userData.isFallback)return;ae(e),e.dispose()}}function ae(e){e&&[`alphaMap`,`aoMap`,`bumpMap`,`clearcoatMap`,`clearcoatNormalMap`,`clearcoatRoughnessMap`,`displacementMap`,`emissiveMap`,`envMap`,`gradientMap`,`lightMap`,`map`,`metalnessMap`,`normalMap`,`roughnessMap`,`specularMap`,`sheenColorMap`,`sheenRoughnessMap`,`specularIntensityMap`,`specularColorMap`,`thicknessMap`,`transmissionMap`].forEach(t=>{e[t]&&(e[t].dispose(),e[t]=null)})}function oe({material:e,geometry:t,children:n}){if(e&&ie(e),t&&t.dispose(),n.length>0)for(let e of n)oe(e)}function se(e){if(!e)return;e._canvasTarget&&e._onCanvasTargetResize&&e._canvasTarget.removeEventListener(`resize`,e._onCanvasTargetResize);let t=e.dispose();return e._canvasTarget=null,t}function ce(e,t=[]){if(e&&!(t.includes(e.name)||e.isScene)){if(e.isMaterial){ie(e);return}for(;e.children.length>0;)for(let t of e.children)ce(t);oe(e),e.removeFromParent(),e.clear()}}function le(e){e?.traverse(e=>{e.geometry?.userData?.__rayzeeOwned&&e.geometry.dispose()})}function ue(e,t){return t}function de(e,t=!1){return t?1:1/(e+1)}function fe(){let e=0,t=0,n=0,r=0;return{start(){e=performance.now()},end(){t=performance.now();let i=t-e;return r+=i,n++,i},getAverageFrameTime(){return n>0?r/n:0},getFPS(){let e=this.getAverageFrameTime();return e>0?1e3/e:0},reset(){n=0,r=0}}}var pe=Math.PI/180;function me(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 he({hours:e,dayOfYear:t,latitude:n}){let r=me(t),i=(e-12)*15*pe,a=n*pe,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)))/pe;return{azimuth:(Math.atan2(Math.sin(i),Math.cos(i)*Math.sin(a)-Math.tan(r)*Math.cos(a))/pe+540)%360,elevation:s}}function ge({elevation:e,dayOfYear:t,latitude:n,afternoon:r=!1}){let i=me(t),a=n*pe,o=(Math.sin(e*pe)-Math.sin(a)*Math.sin(i))/(Math.cos(a)*Math.cos(i)),s=Math.acos(Math.min(1,Math.max(-1,o)))/pe/15;return r?12+s:12-s}var _e=e=>[0,31,59,90,120,151,181,212,243,273,304,334][e-1]+21,ve=Object.freeze({time:10,month:3,latitude:40}),ye=he({hours:ve.time,dayOfYear:_e(ve.month),latitude:ve.latitude}),be=Object.freeze({viewer:Object.freeze({areaLightIntensityScale:.1,environmentRotation:0,toneMapping:6,saturation:1,dofMode:`look`}),physical:Object.freeze({areaLightIntensityScale:1,environmentRotation:0,toneMapping:6,saturation:1,dofMode:`physical`})});function xe(e=`viewer`){let t=be[e];if(!t)throw Error(`unknown render profile "${e}" — expected one of ${Object.keys(be).join(`, `)}`);return t}var V={resolution:512,canvasWidth:512,canvasHeight:512,maxTextureSize:4096,toneMapping:be.viewer.toneMapping,exposure:1,saturation:be.viewer.saturation,enableEnvironment:!0,showBackground:!0,transparentBackground:!1,environmentIntensity:1,backgroundIntensity:1,backgroundColor:`#000000`,backgroundBlurriness:0,backgroundBlurSamples:8,environmentRotation:be.viewer.environmentRotation,groundProjectionEnabled:!1,groundProjectionRadius:100,groundProjectionHeight:15,groundProjectionLevel:0,enableGroundCatcher:!1,groundCatcherHeight:0,globalIlluminationIntensity:1,environmentMode:`hdri`,gradientZenithColor:`#0077BE`,gradientHorizonColor:`#87CEEB`,gradientGroundColor:`#654321`,solidSkyColor:`#87CEEB`,skySunAzimuth:180-ye.azimuth,skySunElevation:ye.elevation,skySunStrength:1,skySunSize:.53,skyTurbidity:2,skyOzone:300,skyAirDensity:1,skyGroundAlbedo:`#959595`,skyAltitude:50,skyPreset:`clearDay`,cameraProjection:`perspective`,panoramaLonRange:[-180,180],panoramaLatRange:[-90,90],panoramaLevelHorizon:!0,enableDOF:!1,fov:55,focusDistance:.8,aperture:5.6,focalLength:50,apertureScale:1,anamorphicRatio:1,unitsPerMetre:1,dofMode:be.viewer.dofMode,dofBlur:.05,autoFocusMode:`auto`,afScreenPoint:{x:.5,y:.5},afSmoothingFactor:.15,enablePathTracer:!0,enableAccumulation:!0,pauseRendering:!1,maxSamples:60,bounces:3,transmissiveBounces:5,maxSubsurfaceSteps:8,maxTransparentBounces:32,useAdaptiveSampling:!0,noiseThreshold:.1,adaptiveMinSamples:8,adaptiveStopFraction:.9,usePixelFreeze:!0,pixelFreezeThreshold:.02,pixelFreezeStability:8,convergenceOverlay:!1,samplingTechnique:2,enableEmissiveTriangleSampling:!1,emissiveBoost:1,fireflyThreshold:3,shadowTerminatorOffset:.1,wavefrontSortMaterials:!0,renderLimitMode:`frames`,renderTimeLimit:30,renderMode:0,enableAlphaShadows:!1,tilesHelper:!0,showLightHelper:!1,directionalLightIntensity:0,directionalLightColor:`#ffffff`,directionalLightPosition:[1,1,1],directionalLightAngle:0,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,debugMode:0,debugThreshold:100,debugModel:0,enableBloom:!1,bloomStrength:.2,bloomRadius:.15,bloomThreshold:.85,interactionModeEnabled:!0,interactionRenderScale:.5,debugVisScale:100,denoiserStrategy:`none`,enableASVGF:!1,asvgfTemporalAlpha:.1,asvgfAtrousIterations:8,asvgfPhiColor:10,asvgfPhiNormal:128,asvgfPhiDepth:1,asvgfVarianceBoost:1,asvgfMaxAccumFrames:32,asvgfGradientStrength:1,asvgfGradientSigmaScale:2,asvgfGradientNoiseFloor:0,asvgfDebugMode:0,asvgfQualityPreset:`medium`,showAsvgfHeatmap:!1,nrdQualityPreset:`medium`,nrdDebugMode:0,autoExposure:!1,autoExposureKeyValue:.18,autoExposureMinExposure:.1,autoExposureMaxExposure:20,autoExposureAdaptSpeedBright:3,autoExposureAdaptSpeedDark:.5},Se=Object.freeze({perspective:0,equirectangular:1,orthographic:2}),Ce=6e4,we=3,Te=.1,Ee=.01,H=4096,U=2048;function De(e){return U=Math.max(256,Math.min(H,Math.floor(e)||256)),U}var Oe={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}},ke={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},Ae=[`maxAccumulatedFrameNum`,`maxFastAccumulatedFrameNum`,`maxStabilizedFrameNum`,`historyFixFrameNum`,`prepassBlurRadius`,`maxBlurRadius`,`enableAntiFirefly`],je={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}},Me={fov:{min:10,max:90,default:V.fov},focusDistance:{min:.3,max:100,default:V.focusDistance},aperture:{options:[1.4,2,2.8,4,5.6,8,11,16],default:V.aperture},focalLength:{min:0,max:200,default:V.focalLength}},Ne={clearDay:{name:`Clear Day`,sunAzimuth:180-ye.azimuth,sunElevation:ye.elevation,turbidity:2,exposure:0},clearMorning:{name:`Clear Morning`,sunAzimuth:90,sunElevation:15,turbidity:2,exposure:1.4},clearNoon:{name:`Clear Noon`,sunAzimuth:180,sunElevation:70,turbidity:2,exposure:0},hazyAfternoon:{name:`Hazy Afternoon`,sunAzimuth:225,sunElevation:35,turbidity:4.5,exposure:.4},goldenHour:{name:`Golden Hour`,sunAzimuth:270,sunElevation:6,turbidity:2.5,exposure:2.7},sunset:{name:`Sunset`,sunAzimuth:270,sunElevation:1,turbidity:3,exposure:4.2},blueHour:{name:`Blue Hour`,sunAzimuth:270,sunElevation:-4,turbidity:2,exposure:7},mountain:{name:`Mountain Air`,sunAzimuth:135,sunElevation:40,turbidity:1.3,altitude:3e3,exposure:0}},Pe={portrait:{name:`Portrait`,description:`Shallow depth of field, background blur`,dofBlur:.1,aperture:1.4,focalLength:135,apertureScale:1},landscape:{name:`Landscape`,description:`Maximum depth of field, everything in focus`,dofBlur:.001,aperture:16,focalLength:24,apertureScale:.5},macro:{name:`Macro`,description:`Very thin focus plane for close-ups`,dofBlur:.14,aperture:1.4,focalLength:100,apertureScale:2},product:{name:`Product`,description:`Sharp detail with subtle background separation`,dofBlur:.013,aperture:2.8,focalLength:85,apertureScale:.4},architectural:{name:`Architectural`,description:`Deep focus for rooms and buildings`,dofBlur:.001,aperture:11,focalLength:16,apertureScale:.5},cinematic:{name:`Cinematic`,description:`Dramatic depth separation with anamorphic bokeh`,dofBlur:.13,aperture:1.4,focalLength:200,apertureScale:1,anamorphicRatio:1.5}},Fe={MANUAL:`manual`,AUTO:`auto`},Ie={SMOOTHING_FACTOR:.15,RESET_THRESHOLD:.05,FALLBACK_DISTANCE:10,SNAP_THRESHOLD:.5},W={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},Le=16777215;function Re(e){return!e||!((e.transmission||0)===0&&(!(e.transparent|0)||(e.opacity??1)>=1))?0:e.alphaMode|0?2:1}function ze(e,t){return(e&Le|(t?.side??0)<<24|Re(t)<<26)>>>0}function Be(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}var G={SLOTS_PER_MATERIAL:33,FLOATS_PER_MATERIAL:132,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,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,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}},Ve=e=>Number.isFinite(e)&&e>0?e:0,K=He({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});function He(e){for(let t of Object.values(e))typeof t==`object`&&Object.freeze(t);return Object.freeze(e)}var Ue=1073741824,We=1073741824,Ge=1073741823,Ke={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826},qe=1<<27;function Je(e){return new Uint32Array(e.buffer,e.byteOffset,e.length)}function Ye(e,t){if(e>=1073741824)throw RangeError(`${t} is ${e.toLocaleString()}, at or past the BVH index limit of ${Ue.toLocaleString()}. Node indices are stored as u32 bit patterns and the leaf tags occupy everything above that.`);return e}var Xe={PIXELS_PER_MATERIAL:30,RGBA_COMPONENTS:4,VEC4_PER_TRIANGLE:8,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},Ze=64;function Qe(e,t){let n=Math.ceil(Math.max(1,e)/Ze)*Ze;return Math.min(t,Math.max(Xe.MIN_TEXTURE_WIDTH,n))}function $e(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 et(e,t){return Qe(e.width,t)*e.height*e.count*4}function q(e,t){return e.reduce((e,n)=>e+et(n,t),0)}function tt(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=$e(r[t].units.concat(r[i].units)),o=et(a,n)-et(r[t],n)-et(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 nt(e,t,n){let r=[];for(let e=t-1;e>=0;e--)r.push(Math.max(Xe.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($e)}function rt(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($e(t))}else e===a?o.push($e(n[e].units.concat([r]))):o.push(n[e]);if(q(o,t)<q(n,t)){n=o,e=!0;break}}}if(!e)break}return n}function it(e,t,n=Xe.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=>$e([e]));if(a.length>n){let e=nt(i,n,t),r=tt(a,n,t);a=q(e,t)<q(r,t)?e:r,a=rt(a,t)}return a.map(e=>({width:Qe(e.width,t),height:e.height})).sort((e,t)=>e.width*e.height-t.width*t.height)}function at(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 ot(e,t){return e*Xe.BUCKET_LAYER_STRIDE+t}var st=[0,0,1,1,0,0,0,1],ct={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},lt={maxSamples:V.maxSamples,bounces:V.bounces,renderMode:V.renderMode,enableAlphaShadows:V.enableAlphaShadows,transmissiveBounces:12,maxSubsurfaceSteps:V.maxSubsurfaceSteps,enableOIDN:!0,oidnQuality:`fast`,interactionModeEnabled:!0,useAdaptiveSampling:!0,noiseThreshold:.1,usePixelFreeze:!0};function ut(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??V.noiseThreshold,adaptiveStopFraction:e.adaptiveStopFraction??V.adaptiveStopFraction,adaptiveMinSamples:e.adaptiveMinSamples??V.adaptiveMinSamples,usePixelFreeze:e.usePixelFreeze??!1,pixelFreezeThreshold:e.pixelFreezeThreshold??V.pixelFreezeThreshold,pixelFreezeStability:e.pixelFreezeStability??V.pixelFreezeStability,interactionModeEnabled:e.interactionModeEnabled??V.interactionModeEnabled}}var dt={MAX_BUFFER_MEMORY:1024*1024*1024,MAX_TEXTURE_MEMORY:2048*1024*1024,CLEANUP_THRESHOLD:.8,CHUNK_SIZE_THRESHOLD:64*1024*1024,STREAM_BATCH_SIZE:4};function ft(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function pt(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function mt(){if(Dt!==null)return Dt;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in xt?(Dt=xt[e],Dt):(Dt=xt[ft(Ct)]??xt[St],Dt)}function ht(){if(Ot!==null)return Ot;let e=globalThis.__RAYZEE_LOG_NS__??ft(wt);return Ot=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],Ot}function gt(e,t){if(t<xt.debug)return!0;let n=ht();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function _t(e,t,n){if(e>mt()||!gt(t,e))return;let r=e===xt.error?console.error:e===xt.warn?console.warn:console.log,i=`[${t}]`;typeof n[0]==`string`?r(`%c${i}%c ${n[0]}`,Tt,Et,...n.slice(1)):r(`%c${i}`,Tt,...n)}function vt(e){return{namespace:e,error:(...t)=>_t(xt.error,e,t),warn:(...t)=>_t(xt.warn,e,t),info:(...t)=>_t(xt.info,e,t),debug:(...t)=>_t(xt.debug,e,t),isEnabled:e=>kt.isEnabled(e),summary(t,n=[]){let r=n.filter(Boolean);if(r.length===0||!console.groupCollapsed){_t(xt.info,e,[t]),r.forEach(t=>_t(xt.debug,e,[t]));return}xt.info>mt()||((mt()>=xt.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,Tt,Et),r.forEach(e=>console.log(e)),console.groupEnd())}}}function yt(e,t,...n){At.has(t)||(At.add(t),e.warn(...n))}function bt(){return kt.getLevel()}var xt,St,Ct,wt,Tt,Et,Dt,Ot,J,kt,At,jt=y((()=>{xt={silent:0,error:1,warn:2,info:3,debug:4},St=`info`,Ct=`rayzeeLogLevel`,wt=`rayzeeLogNamespaces`,Tt=`color:#7c8494`,Et=`color:inherit`,Dt=null,Ot=null,J={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`)=>`${J.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},kt={levels:xt,setLevel(e){return e in xt?(globalThis.__RAYZEE_LOG_LEVEL__=e,Dt=xt[e],pt(Ct,e===St?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(xt).join(`, `)}`),this.getLevel())},getLevel(){let e=mt();return Object.keys(xt).find(t=>xt[t]===e)},isEnabled(e){return(xt[e]??xt.debug)<=mt()},only(...e){let t=e.flat().filter(Boolean);return Ot=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),pt(wt,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return Dt=null,Ot=null,this.getLevel()}},At=new Set}));jt();var Mt=vt(`gpu`);function Nt(e=r.FloatType,n=r.LinearFilter){let i=new t.StorageTexture(U,U);return i.type=e,i.format=r.RGBAFormat,i.minFilter=n,i.magFilter=n,i}var Pt=()=>Nt(),Ft=class{constructor(e,t){this.writeColor=null,this.writeNormalDepth=null,this.writeAlbedo=null,this.readTarget=null,this.currentTarget=0,this.renderWidth=0,this.renderHeight=0,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),e>0&&t>0&&this.create(e,t)}create(e,n){this.dispose(),this.renderWidth=e,this.renderHeight=n,this.writeColor=Pt(),this.writeNormalDepth=Pt(),this.writeAlbedo=Pt(),this.readTarget=new t.RenderTarget(e,n,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1,count:3}),this.readTarget.textures[0].name=`gColor`,this.readTarget.textures[1].name=`gNormalDepth`,this.readTarget.textures[2].name=`gAlbedo`,Mt.debug(`storage texture pool ${J.px(e,n)} — 3 write StorageTextures + 1 MRT RenderTarget`)}ensureSize(e,t){return this.writeColor?this.renderWidth!==e||this.renderHeight!==t?(this.setSize(e,t),!0):!1:(this.create(e,t),!0)}getReadTextures(){return{color:this.readTarget.textures[0],normalDepth:this.readTarget.textures[1],albedo:this.readTarget.textures[2]}}getWriteTextures(){return{color:this.writeColor,normalDepth:this.writeNormalDepth,albedo:this.writeAlbedo}}copyToReadTargets(e,t=!0){this._srcRegion.max.set(this.renderWidth,this.renderHeight),e.copyTextureToTexture(this.writeColor,this.readTarget.textures[0],this._srcRegion),t&&(e.copyTextureToTexture(this.writeNormalDepth,this.readTarget.textures[1],this._srcRegion),e.copyTextureToTexture(this.writeAlbedo,this.readTarget.textures[2],this._srcRegion))}clear(e){if(!this.readTarget||!e)return;let t=e.getRenderTarget();e.setRenderTarget(this.readTarget),e.clear(!0,!1,!1),e.setRenderTarget(t)}swap(){this.currentTarget=1-this.currentTarget}setSize(e,t){if(this.renderWidth=e,this.renderHeight=t,this.readTarget){this.readTarget.setSize(e,t);for(let e of this.readTarget.textures)e.needsUpdate=!0}}dispose(){this.writeColor?.dispose(),this.writeNormalDepth?.dispose(),this.writeAlbedo?.dispose(),this.readTarget?.dispose(),this.writeColor=null,this.writeNormalDepth=null,this.writeAlbedo=null,this.readTarget=null}},It=(0,n.uniform)(0,`int`),Lt=It,Rt=(0,n.wgslFn)(`
|
|
1
|
+
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require(`three/webgpu`),require(`three/tsl`),require(`three`),require(`three/addons/lights/RectAreaLightTexturesLib.js`),require(`three/addons/helpers/RectAreaLightHelper.js`),require(`three/addons/loaders/GLTFLoader.js`),require(`three/addons/loaders/HDRLoader.js`),require(`three/addons/loaders/DRACOLoader.js`),require(`three/addons/loaders/KTX2Loader.js`),require(`three/addons/loaders/EXRLoader.js`),require(`three/addons/utils/SceneUtils.js`),require(`three/addons/utils/SkeletonUtils.js`),require(`three/addons/libs/meshopt_decoder.module.js`),require(`three/addons/libs/fflate.module.js`),require(`three/addons/controls/OrbitControls.js`),require(`three/addons/tsl/display/OutlineNode.js`),require(`three/addons/controls/TransformControls.js`)):typeof define==`function`&&define.amd?define([`exports`,`three/webgpu`,`three/tsl`,`three`,`three/addons/lights/RectAreaLightTexturesLib.js`,`three/addons/helpers/RectAreaLightHelper.js`,`three/addons/loaders/GLTFLoader.js`,`three/addons/loaders/HDRLoader.js`,`three/addons/loaders/DRACOLoader.js`,`three/addons/loaders/KTX2Loader.js`,`three/addons/loaders/EXRLoader.js`,`three/addons/utils/SceneUtils.js`,`three/addons/utils/SkeletonUtils.js`,`three/addons/libs/meshopt_decoder.module.js`,`three/addons/libs/fflate.module.js`,`three/addons/controls/OrbitControls.js`,`three/addons/tsl/display/OutlineNode.js`,`three/addons/controls/TransformControls.js`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.Rayzee={},e.THREE,e.THREE,e.THREE,e.THREE,e.THREE,e.THREE,e.THREE,e.THREE,e.THREE,e.THREE,e.THREE,e.THREE,e.THREE,e.THREE,e.THREE,e.THREE,e.THREE))})(this,function(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var v=Object.defineProperty,y=(e,t)=>()=>(e&&(t=e(e=0)),t),b=(e,t)=>{let n={};for(var r in e)v(n,r,{get:e[r],enumerable:!0});return t||v(n,Symbol.toStringTag,{value:`Module`}),n},x=t.WebGPUBackend.prototype.createNodeBuilder;t.WebGPUBackend.prototype.createNodeBuilder=function(e,t){let n=x.call(this,e,t);return Object.defineProperty(n,`allowGlobalVariables`,{get(){return this.material!==null},set(){},configurable:!0}),n};function S(e,n,r=Float32Array){let i=new t.StorageInstancedBufferAttribute(new r(0),n);return i.count=e,i.gpuByteLength=e*n*r.BYTES_PER_ELEMENT,i.isGPUOnly=!0,i}var C=t.WebGPUBackend.prototype.createStorageAttribute;t.WebGPUBackend.prototype.createStorageAttribute=function(e){let t=this.attributeUtils._getBufferAttribute(e);if(!t.isGPUOnly)return C.call(this,e);let n=this.get(t);n.buffer===void 0&&(n.buffer=this.device.createBuffer({label:t.name,size:t.gpuByteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}))};function w(e,t,n){let r=e.backend;r.createStorageAttribute(t);let i=r.get(t).buffer,a=0;for(let e of n)r.device.queue.writeBuffer(i,a,e,0,e.length),a+=e.byteLength;if(a!==t.gpuByteLength)throw RangeError(`uploadStorageChunks wrote ${a} bytes into a ${t.gpuByteLength}-byte buffer`)}function T(e,t,n,r,i){let a=e.backend;a.createStorageAttribute(t);let o=a.get(t).buffer,s=n.recordsPerChunk*n.lanesPerRecord,c=n.chunks[0].BYTES_PER_ELEMENT,l=r+i,u=r;for(;u<l;){let e=Math.floor(u/s),t=n.chunks[e],r=u-e*s,i=Math.min(t.length-r,l-u);a.device.queue.writeBuffer(o,u*c,t,r,i),u+=i}}var E=t.WebGPUBackend.prototype.updateAttribute;t.WebGPUBackend.prototype.updateAttribute=function(e){if(!this.attributeUtils._getBufferAttribute(e).isGPUOnly)return E.call(this,e)};var D=4096;function O(e){if(!this.trackTimestamp||this.isDisposed||this.currentQueryIndex+2>this.maxQueries)return null;let t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e,t),t}var k=t.WebGPUBackend.prototype.initTimestampQuery;t.WebGPUBackend.prototype.initTimestampQuery=function(e,t,n){let r=this.trackTimestamp&&!this.timestampQueryPool[e];if(k.call(this,e,t,n),r){let r=this.timestampQueryPool[e];if(r&&r.maxQueries<D&&n.timestampWrites){let i=r.constructor,a=new i(this.device,e,D);a.allocateQueriesForContext=O,a.allocateQueriesForContext(t),this.timestampQueryPool[e]=a,n.timestampWrites.querySet=a.querySet,r.dispose()}}let i=n.timestampWrites;i&&i.beginningOfPassWriteIndex==null&&(n.timestampWrites=void 0)};function A(e,t){return new Proxy(e,{get(e,n,r){if(typeof n==`string`&&t.has(n))return e.get(n);let i=Reflect.get(e,n,r);return n===`toVar`&&typeof i==`function`?(...n)=>A(i.apply(e,n),t):i}})}function j(e,t=null){let r=(0,n.struct)(e,t),i=new Set(Object.keys(e)),a=(...e)=>A(r(...e),i);return a.layout=r.layout,a.isStruct=!0,a.wrap=e=>A(e,i),a}t.ContextNode.prototype.setup=function(e){let t=e.addContext(this.value);this.node.build(e),e.setContext(t)};var M=class{constructor(){this.scene=new r.Scene,this._helpers=new Map,this.visible=!1}add(e){if(this._helpers.has(e.uuid))return this._helpers.get(e.uuid);let t=this._createHelper(e);return t?(this._helpers.set(e.uuid,t),this.scene.add(t),t):null}remove(e){let t=this._helpers.get(e.uuid);t&&(t.dispose(),this.scene.remove(t),this._helpers.delete(e.uuid))}has(e){return this._helpers.has(e.uuid)}get isDrawing(){return this.visible&&this._helpers.size>0}update(){for(let e of this._helpers.values())e.update?.()}sync(e){let t=new Set(e.map(e=>e.uuid));for(let[e,n]of this._helpers)t.has(e)||(n.dispose(),this.scene.remove(n),this._helpers.delete(e));for(let t of e)this.add(t)}clear(){for(let e of this._helpers.values())e.dispose(),this.scene.remove(e);this._helpers.clear()}render(e,t){if(!this.isDrawing)return;let n=e.autoClear;e.autoClear=!1,e.clearDepth(),e.setRenderTarget(null),e.render(this.scene,t),e.autoClear=n}dispose(){this.clear()}_createHelper(e){return e.isRectAreaLight?new a.RectAreaLightHelper(e):e.isPointLight?new r.PointLightHelper(e,.5):e.isSpotLight?new r.SpotLightHelper(e):e.isDirectionalLight?new r.DirectionalLightHelper(e,.5):null}},N={ALWAYS:`always`,PER_CYCLE:`per_cycle`,PER_TILE:`per_tile`,CONDITIONAL:`conditional`},P=class{constructor(e,t={}){this.name=e,this.enabled=t.enabled!==!1,this.executionMode=t.executionMode||N.ALWAYS,this.context=null,this.eventBus=null}initialize(e,t){this.context=e,this.eventBus=t,this.setupEventListeners()}setupEventListeners(){}shouldExecuteThisFrame(e){if(!this.enabled)return!1;let t=e.getState(`renderMode`)||0,n=e.getState(`tileRenderingComplete`);switch(this.executionMode){case N.ALWAYS:return!0;case N.PER_CYCLE:return t===0?!0:n===!0;case N.PER_TILE:return!0;case N.CONDITIONAL:return this.shouldExecute(e);default:return this.warn(`Unknown execution mode: ${this.executionMode}`),!0}}shouldExecute(e){return!0}render(e,t){throw Error(`render() must be implemented in ${this.name}`)}reset(){}setSize(e,t){}dispose(){}emit(e,t){this.eventBus&&this.eventBus.emit(e,t)}on(e,t){this.eventBus&&this.eventBus.on(e,t)}once(e,t){this.eventBus&&this.eventBus.once(e,t)}off(e,t){this.eventBus&&this.eventBus.off(e,t)}enable(){this.enabled||(this.enabled=!0,this.emit(`stage:enabled`,{stage:this.name}))}disable(){this.enabled&&(this.enabled=!1,this.emit(`stage:disabled`,{stage:this.name}))}toggle(){this.enabled?this.disable():this.enable()}isEnabled(){return this.enabled}log(...e){console.log(`[${this.name}]`,...e)}warn(...e){console.warn(`[${this.name}]`,...e)}error(...e){console.error(`[${this.name}]`,...e)}},F=class{constructor(e,t,n={}){this.renderer=e,this.material=t,this.interactionModeEnabled=n.enabled===void 0?!0:n.enabled,this.interactionDelay=n.delay||100,this.interactionMode=!1,this.interactionTimeout=null,this.originalValues={},this.appliedValues={},this.wasAccumulationEnabled=!0,this.interactionQualitySettings={enableAccumulation:!1,...n.qualitySettings},this.onEnterCallback=n.onEnter||null,this.onExitCallback=n.onExit||null,this.onResetCallback=n.onReset||null}enterInteractionMode(){this.interactionModeEnabled&&(this.interactionMode?clearTimeout(this.interactionTimeout):(this.interactionMode=!0,this.originalValues={},this.appliedValues={},this.material.uniforms.enableAccumulation&&(this.wasAccumulationEnabled=this.material.uniforms.enableAccumulation.value),Object.keys(this.interactionQualitySettings).forEach(e=>{e===`pixelRatio`?(this.originalValues.dpr=this.renderer.getPixelRatio(),this.renderer.setPixelRatio(this.interactionQualitySettings.pixelRatio)):e===`enableAccumulation`||this.material.uniforms[e]&&(this.originalValues[e]=this.material.uniforms[e].value,this.material.uniforms[e].value=this._resolveQualityValue(e,this.interactionQualitySettings[e]),this.appliedValues[e]=this.material.uniforms[e].value)}),this.material.uniforms.enableAccumulation&&(this.originalValues.enableAccumulation=this.material.uniforms.enableAccumulation.value,this.material.uniforms.enableAccumulation.value=!1),this.material.uniforms.cameraIsMoving&&(this.originalValues.cameraIsMoving=this.material.uniforms.cameraIsMoving.value,this.material.uniforms.cameraIsMoving.value=!0),this.onEnterCallback&&this.onEnterCallback()),this.interactionTimeout=setTimeout(()=>{this.exitInteractionMode()},this.interactionDelay))}exitInteractionMode(){this.interactionMode&&(Object.keys(this.originalValues).forEach(e=>{if(e===`dpr`)this.renderer.setPixelRatio(this.originalValues.dpr);else if(this.material.uniforms[e]){let t=this.appliedValues[e];(t===void 0||this.material.uniforms[e].value===t)&&(this.material.uniforms[e].value=this.originalValues[e])}}),this.interactionMode=!1,this.originalValues={},this.appliedValues={},this.onExitCallback&&this.onExitCallback(),this.onResetCallback&&this.onResetCallback())}updateInteractionMode(e){e&&this.enterInteractionMode()}setInteractionModeEnabled(e){this.interactionModeEnabled=e,!e&&this.interactionMode&&(clearTimeout(this.interactionTimeout),this.exitInteractionMode())}updateQualitySettings(e){Object.assign(this.interactionQualitySettings,e),this.interactionMode&&Object.keys(e).forEach(t=>{t===`pixelRatio`?this.renderer.setPixelRatio(e.pixelRatio):this.material.uniforms[t]&&(this.material.uniforms[t].value=this._resolveQualityValue(t,e[t]),this.appliedValues[t]=this.material.uniforms[t].value)})}_resolveQualityValue(e,t){return typeof t==`function`?t(this.originalValues[e]??this.material.uniforms[e].value):t}setInteractionDelay(e){this.interactionDelay=e}getState(){return{interactionMode:this.interactionMode,interactionModeEnabled:this.interactionModeEnabled,interactionDelay:this.interactionDelay,hasTimeout:this.interactionTimeout!==null,qualitySettings:{...this.interactionQualitySettings},originalValues:{...this.originalValues},wasAccumulationEnabled:this.wasAccumulationEnabled}}forceExitInteractionMode(){this.interactionTimeout&&=(clearTimeout(this.interactionTimeout),null),this.exitInteractionMode()}isInInteractionMode(){return this.interactionMode}setCallbacks(e){e.onEnter&&(this.onEnterCallback=e.onEnter),e.onExit&&(this.onExitCallback=e.onExit),e.onReset&&(this.onResetCallback=e.onReset)}static createQualityPreset(e){let t={"ultra-low":{maxBounceCount:1,pixelRatio:.125,enableAccumulation:!1},low:{maxBounceCount:1,pixelRatio:.25,enableAccumulation:!1},medium:{maxBounceCount:2,pixelRatio:.5,enableAccumulation:!1},high:{maxBounceCount:3,pixelRatio:.75,enableAccumulation:!0}};return t[e]||t.low}dispose(){this.interactionTimeout&&=(clearTimeout(this.interactionTimeout),null),this.interactionMode&&this.forceExitInteractionMode(),this.onEnterCallback=null,this.onExitCallback=null,this.onResetCallback=null}},I,L,R=y((()=>{I={RENDER_COMPLETE:`engine:renderComplete`,RENDER_RESET:`engine:renderReset`,FRAME:`engine:frame`,DENOISING_START:`engine:denoisingStart`,DENOISING_END:`engine:denoisingEnd`,UPSCALING_START:`engine:upscalingStart`,UPSCALING_PROGRESS:`engine:upscalingProgress`,UPSCALING_END:`engine:upscalingEnd`,LOADING_UPDATE:`engine:loadingUpdate`,LOADING_RESET:`engine:loadingReset`,STATS_UPDATE:`engine:statsUpdate`,OBJECT_SELECTED:`engine:objectSelected`,OBJECT_DESELECTED:`engine:objectDeselected`,OBJECT_DOUBLE_CLICKED:`engine:objectDoubleClicked`,SELECT_MODE_CHANGED:`engine:selectModeChanged`,OBJECT_TRANSFORM_START:`engine:objectTransformStart`,OBJECT_TRANSFORM_END:`engine:objectTransformEnd`,TRANSFORM_MODE_CHANGED:`engine:transformModeChanged`,CAMERA_SWITCHED:`engine:cameraSwitched`,CAMERAS_UPDATED:`engine:camerasUpdated`,FOCUS_CHANGED:`engine:focusChanged`,AUTO_FOCUS_UPDATED:`engine:autoFocusUpdated`,ORTHO_HEIGHT_UPDATED:`engine:orthoHeightUpdated`,AUTO_EXPOSURE_UPDATED:`engine:autoExposureUpdated`,AF_POINT_PLACED:`engine:afPointPlaced`,SETTING_CHANGED:`engine:settingChanged`,ANIMATION_STARTED:`engine:animationStarted`,ANIMATION_PAUSED:`engine:animationPaused`,ANIMATION_STOPPED:`engine:animationStopped`,ANIMATION_FINISHED:`engine:animationFinished`,TIMELINE_CHANGED:`engine:timelineChanged`,VIDEO_RENDER_PROGRESS:`engine:videoRenderProgress`,VIDEO_RENDER_COMPLETE:`engine:videoRenderComplete`,DISPOSE:`engine:dispose`,DEVICE_LOST:`engine:deviceLost`,ISSUE:`engine:issue`,MODEL_LOADED:`engine:modelLoaded`,OBJECT3D_LOADED:`engine:object3dLoaded`,MODEL_ADDED:`engine:modelAdded`,SCENE_OBJECT_REMOVED:`engine:sceneObjectRemoved`,SCENE_UNLOADED:`engine:sceneUnloaded`,SCENE_REBUILD:`engine:sceneRebuild`,SCENE_SPILLED:`engine:sceneSpilled`,SCENE_METADATA_APPLIED:`engine:sceneMetadataApplied`,ENVIRONMENT_LOADED:`engine:environmentLoaded`,TEXTURES_REPROCESSED:`engine:texturesReprocessed`,RESOLUTION_CHANGED:`engine:resolutionChanged`,RESERVED_RENDER_SIZE_CHANGED:`engine:reservedRenderSizeChanged`,STORAGE_CHANGED:`engine:storageChanged`},L=Object.freeze({[I.RENDER_COMPLETE]:`RenderComplete`,[I.RENDER_RESET]:`RenderReset`,[I.CAMERA_SWITCHED]:`CameraSwitched`,[I.CAMERAS_UPDATED]:`CamerasUpdated`,[I.FOCUS_CHANGED]:`focusChanged`,[I.MODEL_LOADED]:`ModelLoaded`,[I.OBJECT3D_LOADED]:`Object3DLoaded`,[I.MODEL_ADDED]:`ModelAdded`,[I.SCENE_OBJECT_REMOVED]:`SceneObjectRemoved`,[I.SCENE_UNLOADED]:`SceneUnloaded`,[I.SCENE_REBUILD]:`SceneRebuild`,[I.SCENE_SPILLED]:`SceneSpilled`,[I.SCENE_METADATA_APPLIED]:`SceneMetadataApplied`,[I.ENVIRONMENT_LOADED]:`EnvironmentLoaded`,[I.TEXTURES_REPROCESSED]:`TexturesReprocessed`,[I.RESOLUTION_CHANGED]:`resolution_changed`,[I.RESERVED_RENDER_SIZE_CHANGED]:`reserved_render_size_changed`})}));R();var ee=null;function te(e){ee=e}var ne=()=>ee?.({type:I.LOADING_RESET}),z=e=>{ee?.({type:I.LOADING_UPDATE,...e})},B=e=>{ee?.({type:I.STATS_UPDATE,...e})};function re(e){return e.frameCount||0}function ie(e){if(Array.isArray(e))e.forEach(e=>{e.userData&&e.userData.isFallback||(ae(e),e.dispose())});else{if(e.userData&&e.userData.isFallback)return;ae(e),e.dispose()}}function ae(e){e&&[`alphaMap`,`aoMap`,`bumpMap`,`clearcoatMap`,`clearcoatNormalMap`,`clearcoatRoughnessMap`,`displacementMap`,`emissiveMap`,`envMap`,`gradientMap`,`lightMap`,`map`,`metalnessMap`,`normalMap`,`roughnessMap`,`specularMap`,`sheenColorMap`,`sheenRoughnessMap`,`specularIntensityMap`,`specularColorMap`,`thicknessMap`,`transmissionMap`].forEach(t=>{e[t]&&(e[t].dispose(),e[t]=null)})}function oe({material:e,geometry:t,children:n}){if(e&&ie(e),t&&t.dispose(),n.length>0)for(let e of n)oe(e)}function se(e){if(!e)return;e._canvasTarget&&e._onCanvasTargetResize&&e._canvasTarget.removeEventListener(`resize`,e._onCanvasTargetResize);let t=e.dispose();return e._canvasTarget=null,t}function ce(e,t=[]){if(e&&!(t.includes(e.name)||e.isScene)){if(e.isMaterial){ie(e);return}for(;e.children.length>0;)for(let t of e.children)ce(t);oe(e),e.removeFromParent(),e.clear()}}function le(e){e?.traverse(e=>{e.geometry?.userData?.__rayzeeOwned&&e.geometry.dispose()})}function ue(e,t){return t}function de(e,t=!1){return t?1:1/(e+1)}function fe(){let e=0,t=0,n=0,r=0;return{start(){e=performance.now()},end(){t=performance.now();let i=t-e;return r+=i,n++,i},getAverageFrameTime(){return n>0?r/n:0},getFPS(){let e=this.getAverageFrameTime();return e>0?1e3/e:0},reset(){n=0,r=0}}}var pe=Math.PI/180;function me(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 he({hours:e,dayOfYear:t,latitude:n}){let r=me(t),i=(e-12)*15*pe,a=n*pe,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)))/pe;return{azimuth:(Math.atan2(Math.sin(i),Math.cos(i)*Math.sin(a)-Math.tan(r)*Math.cos(a))/pe+540)%360,elevation:s}}function ge({elevation:e,dayOfYear:t,latitude:n,afternoon:r=!1}){let i=me(t),a=n*pe,o=(Math.sin(e*pe)-Math.sin(a)*Math.sin(i))/(Math.cos(a)*Math.cos(i)),s=Math.acos(Math.min(1,Math.max(-1,o)))/pe/15;return r?12+s:12-s}var _e=e=>[0,31,59,90,120,151,181,212,243,273,304,334][e-1]+21,ve=Object.freeze({time:10,month:3,latitude:40}),ye=he({hours:ve.time,dayOfYear:_e(ve.month),latitude:ve.latitude}),be=Object.freeze({viewer:Object.freeze({areaLightIntensityScale:.1,environmentRotation:0,toneMapping:6,saturation:1,dofMode:`look`}),physical:Object.freeze({areaLightIntensityScale:1,environmentRotation:0,toneMapping:6,saturation:1,dofMode:`physical`})});function xe(e=`viewer`){let t=be[e];if(!t)throw Error(`unknown render profile "${e}" — expected one of ${Object.keys(be).join(`, `)}`);return t}var V={resolution:512,canvasWidth:512,canvasHeight:512,maxTextureSize:4096,toneMapping:be.viewer.toneMapping,exposure:1,saturation:be.viewer.saturation,enableEnvironment:!0,showBackground:!0,transparentBackground:!1,environmentIntensity:1,backgroundIntensity:1,backgroundColor:`#000000`,backgroundBlurriness:0,backgroundBlurSamples:8,environmentRotation:be.viewer.environmentRotation,groundProjectionEnabled:!1,groundProjectionRadius:100,groundProjectionHeight:15,groundProjectionLevel:0,enableGroundCatcher:!1,groundCatcherHeight:0,globalIlluminationIntensity:1,environmentMode:`hdri`,solidSkyColor:`#87CEEB`,skySunAzimuth:180-ye.azimuth,skySunElevation:ye.elevation,skySunStrength:1,skySunSize:.53,skyTurbidity:2,skyOzone:300,skyAirDensity:1,skyGroundAlbedo:`#959595`,skyAltitude:50,skyPreset:`clearDay`,cameraProjection:`perspective`,panoramaLonRange:[-180,180],panoramaLatRange:[-90,90],panoramaLevelHorizon:!0,enableDOF:!1,fov:55,focusDistance:.8,aperture:5.6,focalLength:50,apertureScale:1,anamorphicRatio:1,unitsPerMetre:1,dofMode:be.viewer.dofMode,dofBlur:.05,autoFocusMode:`auto`,afScreenPoint:{x:.5,y:.5},afSmoothingFactor:.15,enablePathTracer:!0,enableAccumulation:!0,pauseRendering:!1,maxSamples:60,bounces:3,transmissiveBounces:5,maxSubsurfaceSteps:8,maxTransparentBounces:32,useAdaptiveSampling:!0,noiseThreshold:.1,adaptiveMinSamples:8,adaptiveStopFraction:.9,usePixelFreeze:!0,pixelFreezeThreshold:.02,pixelFreezeStability:8,convergenceOverlay:!1,samplingTechnique:2,enableEmissiveTriangleSampling:!1,emissiveBoost:1,fireflyThreshold:3,shadowTerminatorOffset:.1,wavefrontSortMaterials:!0,renderLimitMode:`frames`,renderTimeLimit:30,renderMode:0,enableAlphaShadows:!1,tilesHelper:!0,showLightHelper:!1,directionalLightIntensity:0,directionalLightColor:`#ffffff`,directionalLightPosition:[1,1,1],directionalLightAngle:0,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,debugMode:0,debugThreshold:100,debugModel:0,enableBloom:!1,bloomStrength:.2,bloomRadius:.15,bloomThreshold:.85,interactionModeEnabled:!0,interactionRenderScale:.5,debugVisScale:100,denoiserStrategy:`none`,enableASVGF:!1,asvgfTemporalAlpha:.1,asvgfAtrousIterations:8,asvgfPhiColor:10,asvgfPhiNormal:128,asvgfPhiDepth:1,asvgfVarianceBoost:1,asvgfMaxAccumFrames:32,asvgfGradientStrength:1,asvgfGradientSigmaScale:2,asvgfGradientNoiseFloor:0,asvgfDebugMode:0,asvgfQualityPreset:`medium`,showAsvgfHeatmap:!1,nrdQualityPreset:`medium`,nrdDebugMode:0,autoExposure:!1,autoExposureKeyValue:.18,autoExposureMinExposure:.1,autoExposureMaxExposure:20,autoExposureAdaptSpeedBright:3,autoExposureAdaptSpeedDark:.5},Se=Object.freeze({perspective:0,equirectangular:1,orthographic:2}),Ce=6e4,we=3,Te=.1,Ee=.01,H=4096,U=2048;function De(e){return U=Math.max(256,Math.min(H,Math.floor(e)||256)),U}var Oe={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}},ke={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},Ae=[`maxAccumulatedFrameNum`,`maxFastAccumulatedFrameNum`,`maxStabilizedFrameNum`,`historyFixFrameNum`,`prepassBlurRadius`,`maxBlurRadius`,`enableAntiFirefly`],je={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}},Me={fov:{min:10,max:90,default:V.fov},focusDistance:{min:.3,max:100,default:V.focusDistance},aperture:{options:[1.4,2,2.8,4,5.6,8,11,16],default:V.aperture},focalLength:{min:0,max:200,default:V.focalLength}},Ne={clearDay:{name:`Clear Day`,sunAzimuth:180-ye.azimuth,sunElevation:ye.elevation,turbidity:2,exposure:0},clearMorning:{name:`Clear Morning`,sunAzimuth:90,sunElevation:15,turbidity:2,exposure:1.4},clearNoon:{name:`Clear Noon`,sunAzimuth:180,sunElevation:70,turbidity:2,exposure:0},hazyAfternoon:{name:`Hazy Afternoon`,sunAzimuth:225,sunElevation:35,turbidity:4.5,exposure:.4},goldenHour:{name:`Golden Hour`,sunAzimuth:270,sunElevation:6,turbidity:2.5,exposure:2.7},sunset:{name:`Sunset`,sunAzimuth:270,sunElevation:1,turbidity:3,exposure:4.2},blueHour:{name:`Blue Hour`,sunAzimuth:270,sunElevation:-4,turbidity:2,exposure:7},mountain:{name:`Mountain Air`,sunAzimuth:135,sunElevation:40,turbidity:1.3,altitude:3e3,exposure:0}},Pe={portrait:{name:`Portrait`,description:`Shallow depth of field, background blur`,dofBlur:.1,aperture:1.4,focalLength:135,apertureScale:1},landscape:{name:`Landscape`,description:`Maximum depth of field, everything in focus`,dofBlur:.001,aperture:16,focalLength:24,apertureScale:.5},macro:{name:`Macro`,description:`Very thin focus plane for close-ups`,dofBlur:.14,aperture:1.4,focalLength:100,apertureScale:2},product:{name:`Product`,description:`Sharp detail with subtle background separation`,dofBlur:.013,aperture:2.8,focalLength:85,apertureScale:.4},architectural:{name:`Architectural`,description:`Deep focus for rooms and buildings`,dofBlur:.001,aperture:11,focalLength:16,apertureScale:.5},cinematic:{name:`Cinematic`,description:`Dramatic depth separation with anamorphic bokeh`,dofBlur:.13,aperture:1.4,focalLength:200,apertureScale:1,anamorphicRatio:1.5}},Fe={MANUAL:`manual`,AUTO:`auto`},Ie={SMOOTHING_FACTOR:.15,RESET_THRESHOLD:.05,FALLBACK_DISTANCE:10,SNAP_THRESHOLD:.5},W={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},Le=16777215;function Re(e){return!e||!((e.transmission||0)===0&&(!(e.transparent|0)||(e.opacity??1)>=1))?0:e.alphaMode|0?2:1}function ze(e,t){return(e&Le|(t?.side??0)<<24|Re(t)<<26)>>>0}function Be(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}var G={SLOTS_PER_MATERIAL:33,FLOATS_PER_MATERIAL:132,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,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,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}},Ve=e=>Number.isFinite(e)&&e>0?e:0,K=He({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});function He(e){for(let t of Object.values(e))typeof t==`object`&&Object.freeze(t);return Object.freeze(e)}var Ue=1073741824,We=1073741824,Ge=1073741823,Ke={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826},qe=1<<27;function Je(e){return new Uint32Array(e.buffer,e.byteOffset,e.length)}function Ye(e,t){if(e>=1073741824)throw RangeError(`${t} is ${e.toLocaleString()}, at or past the BVH index limit of ${Ue.toLocaleString()}. Node indices are stored as u32 bit patterns and the leaf tags occupy everything above that.`);return e}var Xe={PIXELS_PER_MATERIAL:30,RGBA_COMPONENTS:4,VEC4_PER_TRIANGLE:8,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},Ze=64;function Qe(e,t){let n=Math.ceil(Math.max(1,e)/Ze)*Ze;return Math.min(t,Math.max(Xe.MIN_TEXTURE_WIDTH,n))}function $e(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 et(e,t){return Qe(e.width,t)*e.height*e.count*4}function q(e,t){return e.reduce((e,n)=>e+et(n,t),0)}function tt(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=$e(r[t].units.concat(r[i].units)),o=et(a,n)-et(r[t],n)-et(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 nt(e,t,n){let r=[];for(let e=t-1;e>=0;e--)r.push(Math.max(Xe.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($e)}function rt(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($e(t))}else e===a?o.push($e(n[e].units.concat([r]))):o.push(n[e]);if(q(o,t)<q(n,t)){n=o,e=!0;break}}}if(!e)break}return n}function it(e,t,n=Xe.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=>$e([e]));if(a.length>n){let e=nt(i,n,t),r=tt(a,n,t);a=q(e,t)<q(r,t)?e:r,a=rt(a,t)}return a.map(e=>({width:Qe(e.width,t),height:e.height})).sort((e,t)=>e.width*e.height-t.width*t.height)}function at(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 ot(e,t){return e*Xe.BUCKET_LAYER_STRIDE+t}var st=[0,0,1,1,0,0,0,1],ct={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},lt={maxSamples:V.maxSamples,bounces:V.bounces,renderMode:V.renderMode,enableAlphaShadows:V.enableAlphaShadows,transmissiveBounces:12,maxSubsurfaceSteps:V.maxSubsurfaceSteps,enableOIDN:!0,oidnQuality:`fast`,interactionModeEnabled:!0,useAdaptiveSampling:!0,noiseThreshold:.1,usePixelFreeze:!0};function ut(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??V.noiseThreshold,adaptiveStopFraction:e.adaptiveStopFraction??V.adaptiveStopFraction,adaptiveMinSamples:e.adaptiveMinSamples??V.adaptiveMinSamples,usePixelFreeze:e.usePixelFreeze??!1,pixelFreezeThreshold:e.pixelFreezeThreshold??V.pixelFreezeThreshold,pixelFreezeStability:e.pixelFreezeStability??V.pixelFreezeStability,interactionModeEnabled:e.interactionModeEnabled??V.interactionModeEnabled}}var dt={MAX_BUFFER_MEMORY:1024*1024*1024,MAX_TEXTURE_MEMORY:2048*1024*1024,CLEANUP_THRESHOLD:.8,CHUNK_SIZE_THRESHOLD:64*1024*1024,STREAM_BATCH_SIZE:4};function ft(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function pt(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function mt(){if(Dt!==null)return Dt;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in xt?(Dt=xt[e],Dt):(Dt=xt[ft(Ct)]??xt[St],Dt)}function ht(){if(Ot!==null)return Ot;let e=globalThis.__RAYZEE_LOG_NS__??ft(wt);return Ot=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],Ot}function gt(e,t){if(t<xt.debug)return!0;let n=ht();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function _t(e,t,n){if(e>mt()||!gt(t,e))return;let r=e===xt.error?console.error:e===xt.warn?console.warn:console.log,i=`[${t}]`;typeof n[0]==`string`?r(`%c${i}%c ${n[0]}`,Tt,Et,...n.slice(1)):r(`%c${i}`,Tt,...n)}function vt(e){return{namespace:e,error:(...t)=>_t(xt.error,e,t),warn:(...t)=>_t(xt.warn,e,t),info:(...t)=>_t(xt.info,e,t),debug:(...t)=>_t(xt.debug,e,t),isEnabled:e=>kt.isEnabled(e),summary(t,n=[]){let r=n.filter(Boolean);if(r.length===0||!console.groupCollapsed){_t(xt.info,e,[t]),r.forEach(t=>_t(xt.debug,e,[t]));return}xt.info>mt()||((mt()>=xt.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,Tt,Et),r.forEach(e=>console.log(e)),console.groupEnd())}}}function yt(e,t,...n){At.has(t)||(At.add(t),e.warn(...n))}function bt(){return kt.getLevel()}var xt,St,Ct,wt,Tt,Et,Dt,Ot,J,kt,At,jt=y((()=>{xt={silent:0,error:1,warn:2,info:3,debug:4},St=`info`,Ct=`rayzeeLogLevel`,wt=`rayzeeLogNamespaces`,Tt=`color:#7c8494`,Et=`color:inherit`,Dt=null,Ot=null,J={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`)=>`${J.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},kt={levels:xt,setLevel(e){return e in xt?(globalThis.__RAYZEE_LOG_LEVEL__=e,Dt=xt[e],pt(Ct,e===St?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(xt).join(`, `)}`),this.getLevel())},getLevel(){let e=mt();return Object.keys(xt).find(t=>xt[t]===e)},isEnabled(e){return(xt[e]??xt.debug)<=mt()},only(...e){let t=e.flat().filter(Boolean);return Ot=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),pt(wt,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return Dt=null,Ot=null,this.getLevel()}},At=new Set}));jt();var Mt=vt(`gpu`);function Nt(e=r.FloatType,n=r.LinearFilter){let i=new t.StorageTexture(U,U);return i.type=e,i.format=r.RGBAFormat,i.minFilter=n,i.magFilter=n,i}var Pt=()=>Nt(),Ft=class{constructor(e,t){this.writeColor=null,this.writeNormalDepth=null,this.writeAlbedo=null,this.readTarget=null,this.currentTarget=0,this.renderWidth=0,this.renderHeight=0,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),e>0&&t>0&&this.create(e,t)}create(e,n){this.dispose(),this.renderWidth=e,this.renderHeight=n,this.writeColor=Pt(),this.writeNormalDepth=Pt(),this.writeAlbedo=Pt(),this.readTarget=new t.RenderTarget(e,n,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1,count:3}),this.readTarget.textures[0].name=`gColor`,this.readTarget.textures[1].name=`gNormalDepth`,this.readTarget.textures[2].name=`gAlbedo`,Mt.debug(`storage texture pool ${J.px(e,n)} — 3 write StorageTextures + 1 MRT RenderTarget`)}ensureSize(e,t){return this.writeColor?this.renderWidth!==e||this.renderHeight!==t?(this.setSize(e,t),!0):!1:(this.create(e,t),!0)}getReadTextures(){return{color:this.readTarget.textures[0],normalDepth:this.readTarget.textures[1],albedo:this.readTarget.textures[2]}}getWriteTextures(){return{color:this.writeColor,normalDepth:this.writeNormalDepth,albedo:this.writeAlbedo}}copyToReadTargets(e,t=!0){this._srcRegion.max.set(this.renderWidth,this.renderHeight),e.copyTextureToTexture(this.writeColor,this.readTarget.textures[0],this._srcRegion),t&&(e.copyTextureToTexture(this.writeNormalDepth,this.readTarget.textures[1],this._srcRegion),e.copyTextureToTexture(this.writeAlbedo,this.readTarget.textures[2],this._srcRegion))}clear(e){if(!this.readTarget||!e)return;let t=e.getRenderTarget();e.setRenderTarget(this.readTarget),e.clear(!0,!1,!1),e.setRenderTarget(t)}swap(){this.currentTarget=1-this.currentTarget}setSize(e,t){if(this.renderWidth=e,this.renderHeight=t,this.readTarget){this.readTarget.setSize(e,t);for(let e of this.readTarget.textures)e.needsUpdate=!0}}dispose(){this.writeColor?.dispose(),this.writeNormalDepth?.dispose(),this.writeAlbedo?.dispose(),this.readTarget?.dispose(),this.writeColor=null,this.writeNormalDepth=null,this.writeAlbedo=null,this.readTarget=null}},It=(0,n.uniform)(0,`int`),Lt=It,Rt=(0,n.wgslFn)(`
|
|
2
2
|
fn pcgHash( state: u32 ) -> u32 {
|
|
3
3
|
|
|
4
4
|
var s = state;
|
|
@@ -298,7 +298,7 @@
|
|
|
298
298
|
return ( c0 * v.x + cross( r2, r0 ) * v.y + cross( r0, r1 ) * v.z ) * inv;
|
|
299
299
|
|
|
300
300
|
}
|
|
301
|
-
`),_a=(e,t)=>ga({r0:e[0].xyz,r1:e[1].xyz,r2:e[2].xyz,v:t.sub((0,n.vec3)(e[0].w,e[1].w,e[2].w))});jt();var va=vt(`gpu`),ya={ORIGIN_META:0,DIR_FLAGS:1,THROUGHPUT_PDF:2,RADIANCE_ALPHA:3,MEDIUM_STACK:4,MEDIUM_SIGMA_A:5,SSS_SIGMA_S:6},ba={DIST_TRI_BARY:0,NORMAL_MAT:1,RNG:2},xa=0,Sa=(e,t)=>t===0?e:e.add(t*xa);function Ca(e,t){t&&e?._attributes?.delete?.(t)}var wa=class{constructor(e=0,t=null){this.capacity=0,this._renderer=t,this._attrs={},this.rayBuffer=null,this.hitBuffer=null,e>0&&this.allocate(e)}allocate(e){this.dispose(),this.capacity=e,xa=e;let t=e*7,r=S(t,4);this._attrs.ray=r,this.rayBuffer={rw:(0,n.storage)(r,`vec4`),ro:(0,n.storage)(r,`vec4`).toReadOnly()};let i=e*3,a=S(i,4,Uint32Array);this._attrs.hit=a,this.hitBuffer={rw:(0,n.storage)(a,`uvec4`),ro:(0,n.storage)(a,`uvec4`).toReadOnly()},this.rayBytes=t*16,this.hitBytes=i*16,this.totalBytes=this.rayBytes+this.hitBytes,va.debug(`ray pool capacity ${J.n(e)} · ${J.mb(this.totalBytes)} (rays ${J.mb(this.rayBytes)} · hits ${J.mb(this.hitBytes)})`)}resize(e){return e<=this.capacity&&this.capacity>0?!1:(this.allocate(e),!0)}dispose(){Ca(this._renderer,this._attrs.ray),Ca(this._renderer,this._attrs.hit),this._attrs={},this.rayBuffer=null,this.hitBuffer=null,this.capacity=0}},Ta=(e,t)=>e.element(Sa(t,ya.ORIGIN_META)).xyz,Ea=(e,t)=>e.element(Sa(t,ya.DIR_FLAGS)).xyz,Da=(e,t)=>(0,n.floatBitsToUint)(e.element(Sa(t,ya.DIR_FLAGS)).w),Oa=(e,t)=>e.element(Sa(t,ya.THROUGHPUT_PDF)).xyz,ka=(e,t)=>e.element(Sa(t,ya.THROUGHPUT_PDF)).w,Aa=(e,t)=>e.element(Sa(t,ya.RADIANCE_ALPHA)),ja=e=>(0,n.uint)(e).mul(1),Ma=(e,t,r,i,a,o=null)=>{let s=ja(t),c=o===null?(0,n.unpackUnorm2x16)(e.element(s).w).y:(0,n.float)(o);return e.element(s).assign((0,n.uvec4)((0,n.packSnorm2x16)((0,n.vec2)(r.x,r.y)),(0,n.packSnorm2x16)((0,n.vec2)(r.z,i)),(0,n.packUnorm2x16)((0,n.vec2)(a.x,a.y)),(0,n.packUnorm2x16)((0,n.vec2)(a.z,c))))},Na=(e,t,r)=>{let i=ja(t),a=e.element(i).toVar();return e.element(i).assign((0,n.uvec4)(a.x,a.y,a.z,(0,n.packUnorm2x16)((0,n.vec2)((0,n.unpackUnorm2x16)(a.w).x,r))))},Pa=(e,t)=>e.element(ja(t)),Fa=e=>(0,n.unpackUnorm2x16)(e.w).y,Ia=e=>{let t=(0,n.unpackSnorm2x16)(e.x),r=(0,n.unpackSnorm2x16)(e.y);return(0,n.vec4)((0,n.vec3)(t.x,t.y,r.x).mul(.5).add(.5),r.y)},La=e=>(0,n.vec3)((0,n.unpackUnorm2x16)(e.z),(0,n.unpackUnorm2x16)(e.w).x),Ra=e=>{let t=(0,n.clamp)((0,n.floor)((0,n.log2)((0,n.max)(e,1e-6))),-8,7),r=(0,n.clamp)((0,n.float)(e).mul((0,n.exp2)(t.negate())).sub(1).mul(64),0,63);return(0,n.select)((0,n.float)(e).lessThan(.004),(0,n.uint)(0),(0,n.uint)(t.add(8)).shiftLeft(6).bitOr((0,n.uint)(r)))},za=(e,t)=>{let r=(0,n.floatBitsToUint)(e.element(Sa(t,ya.ORIGIN_META)).w).shiftRight(22),i=(0,n.float)(r.shiftRight(6).bitAnd((0,n.uint)(15))).sub(8),a=(0,n.float)(r.bitAnd((0,n.uint)(63))).div(64).add(1);return(0,n.select)(r.equal((0,n.uint)(0)),(0,n.float)(0),a.mul((0,n.exp2)(i)))},Ba=(e,t,r,i,a,o=(0,n.uint)(0),s=null)=>{let c=(0,n.uint)(i).bitAnd((0,n.uint)(255)).bitOr((0,n.uint)(a).bitAnd((0,n.uint)(255)).shiftLeft(8)).bitOr((0,n.uint)(o).bitAnd((0,n.uint)(63)).shiftLeft(16));return s!==null&&(c=c.bitOr(Ra(s).shiftLeft(22))),e.element(Sa(t,ya.ORIGIN_META)).assign((0,n.vec4)(r,(0,n.uintBitsToFloat)(c)))},Va=(e,t,r,i)=>e.element(Sa(t,ya.DIR_FLAGS)).assign((0,n.vec4)(r,(0,n.uintBitsToFloat)(i))),Ha=(e,t,r,i)=>e.element(Sa(t,ya.THROUGHPUT_PDF)).assign((0,n.vec4)(r,i)),Ua=(e,t,n)=>e.element(Sa(t,ya.RADIANCE_ALPHA)).assign(n),Wa=(e,t)=>(0,n.uintBitsToFloat)(e.element(Sa(t,ba.DIST_TRI_BARY)).x),Ga=(e,t)=>e.element(Sa(t,ba.DIST_TRI_BARY)).y,Ka=(e,t)=>(0,n.uintBitsToFloat)(e.element(Sa(t,ba.DIST_TRI_BARY)).zw),qa=(e,t)=>ia(e.element(Sa(t,ba.NORMAL_MAT)).x),Ja=(e,t)=>(0,n.uint)(e.element(Sa(t,ba.NORMAL_MAT)).y),Ya=(e,t)=>(0,n.int)(e.element(Sa(t,ba.NORMAL_MAT)).z).sub((0,n.int)(1)),Xa=(e,t)=>e.element(Sa(t,ba.NORMAL_MAT)).w,Za=(e,t)=>e.element(Sa(t,ba.RNG)).x,Qa=(e,t,r)=>e.element(Sa(t,ba.RNG)).assign((0,n.uvec4)(r,0,0,0)),$a=(e,t,r,i,a,o,s,c,l,u=(0,n.uint)(0))=>{e.element(Sa(t,ba.DIST_TRI_BARY)).assign((0,n.uvec4)((0,n.floatBitsToUint)(r),i,(0,n.floatBitsToUint)(a),(0,n.floatBitsToUint)(o))),e.element(Sa(t,ba.NORMAL_MAT)).assign((0,n.uvec4)(ra(s),c,l,u))},eo=(e,t)=>{let r=e.element(Sa(t,ya.MEDIUM_STACK)),i=(0,n.floatBitsToUint)(r.x);return{stackDepth:i.bitAnd(255),transTraversals:i.shiftRight(8).bitAnd(255),wavelength:i.shiftRight(16).bitAnd(65535),ior1:r.y,ior2:r.z,ior3:r.w}},to=(e,t,r,i,a,o,s,c=(0,n.uint)(0))=>e.element(Sa(t,ya.MEDIUM_STACK)).assign((0,n.vec4)((0,n.uintBitsToFloat)(r.bitOr(i.shiftLeft(8)).bitOr(c.shiftLeft(16))),a,o,s)),no=(e,t)=>e.element(Sa(t,ya.MEDIUM_SIGMA_A)).xyz,ro=(e,t,r)=>{let i=e.element(Sa(t,ya.MEDIUM_SIGMA_A)).w.toVar();e.element(Sa(t,ya.MEDIUM_SIGMA_A)).assign((0,n.vec4)(r,i))},io=e=>{let t=(0,n.clamp)(e,(0,n.vec3)(0),(0,n.vec3)(1)).mul(1023).add(.5);return(0,n.uint)(t.x).bitOr((0,n.uint)(t.y).shiftLeft(10)).bitOr((0,n.uint)(t.z).shiftLeft(20))},ao=e=>(0,n.vec3)((0,n.float)(e.bitAnd((0,n.uint)(1023))),(0,n.float)(e.shiftRight(10).bitAnd((0,n.uint)(1023))),(0,n.float)(e.shiftRight(20).bitAnd((0,n.uint)(1023)))).div(1023),oo=(e,t)=>ao((0,n.floatBitsToUint)(e.element(Sa(t,ya.MEDIUM_SIGMA_A)).w)),so=(e,t,r)=>{let i=e.element(Sa(t,ya.MEDIUM_SIGMA_A)).xyz.toVar();e.element(Sa(t,ya.MEDIUM_SIGMA_A)).assign((0,n.vec4)(i,(0,n.uintBitsToFloat)(io(r))))},co=(e,t)=>(0,n.int)((0,n.floatBitsToUint)(e.element(Sa(t,ya.ORIGIN_META)).w).bitAnd(255)),lo=(e,t)=>(0,n.int)((0,n.floatBitsToUint)(e.element(Sa(t,ya.ORIGIN_META)).w).shiftRight(8).bitAnd(255)),uo=(e,t)=>(0,n.int)((0,n.floatBitsToUint)(e.element(Sa(t,ya.ORIGIN_META)).w).shiftRight(16).bitAnd((0,n.uint)(63))),fo=(e,t)=>{let n=e.element(Sa(t,ya.SSS_SIGMA_S));return{sigmaS:n.xyz,g:n.w}},po=(e,t,r,i)=>e.element(Sa(t,ya.SSS_SIGMA_S)).assign((0,n.vec4)(r,i)),mo=6360,ho=6420,go=1.2,_o=.9,vo=.76,yo=1.3,bo=380,xo=25,So=1/32,Co=[1.11776,1.14259,1.01249,1.14716,1.72765,1.73054,1.6887,1.61253,1.91198,2.03474,2.02042,2.02212,1.93377,1.95809,1.91686,1.8298,1.8685,1.8931,1.85149,1.8504,1.8341,1.8345,1.8147,1.78158,1.7533,1.6965,1.68194,1.64654,1.6048,1.52143,1.55622,1.5113,1.474,1.4482,1.41018,1.36775,1.34188,1.31429,1.28303,1.26758,1.2367,1.2082,1.18737,1.14683,1.12362,1.1058,1.07124,1.04992],wo=[118e-29,2182e-31,2818e-31,6636e-31,1527e-30,2763e-30,552e-29,8451e-30,1582e-29,2316e-29,3669e-29,4924e-29,7752e-29,9016e-29,148e-27,1602e-28,2139e-28,2755e-28,3091e-28,35e-26,4266e-28,4672e-28,4398e-28,4701e-28,5019e-28,4305e-28,374e-27,3215e-28,2662e-28,2238e-28,1852e-28,1473e-28,1209e-28,9423e-29,7455e-29,6566e-29,5105e-29,415e-28,4228e-29,3237e-29,2451e-29,2801e-29,2534e-29,1624e-29,1465e-29,2078e-29,1383e-29,7105e-30],To=[1299e-7,3917e-9,6061e-7,2321e-7,6965e-9,.001086,4149e-7,1239e-8,.001946,7416e-7,2202e-8,.003486,.001368,39e-6,.006450001,.002236,64e-6,.01054999,.004243,12e-5,.02005001,.00765,217e-6,.03621,.01431,396e-6,.06785001,.02319,64e-5,.1102,.04351,.00121,.2074,.07763,.00218,.3713,.13438,.004,.6456,.21477,.0073,1.0390501,.2839,.0116,1.3856,.3285,.01684,1.62296,.34828,.023,1.74706,.34806,.0298,1.7826,.3362,.038,1.77211,.3187,.048,1.7441,.2908,.06,1.6692,.2511,.0739,1.5281,.19536,.09098,1.28764,.1421,.1126,1.0419,.09564,.13902,.8129501,.05795001,.1693,.6162,.03201,.20802,.46518,.0147,.2586,.3533,.0049,.323,.272,.0024,.4073,.2123,.0093,.503,.1582,.0291,.6082,.1117,.06327,.71,.07824999,.1096,.7932,.05725001,.1655,.862,.04216,.2257499,.9148501,.02984,.2904,.954,.0203,.3597,.9803,.0134,.4334499,.9949501,.008749999,.5120501,1,.005749999,.5945,.995,.0039,.6784,.9786,.002749999,.7621,.952,.0021,.8425,.9154,.0018,.9163,.87,.001650001,.9786,.8163,.0014,1.0263,.757,.0011,1.0567,.6949,.001,1.0622,.631,8e-4,1.0456,.5668,6e-4,1.0026,.503,34e-5,.9384,.4412,24e-5,.8544499,.381,19e-5,.7514,.321,1e-4,.6424,.265,4999999e-11,.5419,.217,3e-5,.4479,.175,2e-5,.3608,.1382,1e-5,.2835,.107,0,.2187,.0816,0,.1649,.061,0,.1212,.04458,0,.0874,.032,0,.0636,.0232,0,.04677,.017,0,.0329,.01192,0,.0227,.00821,0,.01584,.005723,0,.01135916,.004102,0,.008110916,.002929,0,.005790346,.002091,0,.004109457,.001484,0,.002899327,.001047,0,.00204919,74e-5,0,.001439971,52e-5,0,.0009999493,3611e-7,0,.0006900786,2492e-7,0,.0004760213,1719e-7,0,.0003323011,12e-5,0,.0002348261,848e-7,0,.0001661505,6e-5,0,117413e-9,424e-7,0,8307527e-11,3e-5,0,5870652e-11,212e-7,0,4150994e-11,1499e-8,0,2935326e-11,106e-7,0,2067383e-11,74657e-10,0,1455977e-11,52578e-10,0,1025398e-11,37029e-10,0,7221456e-12,26078e-10,0,5085868e-12,18366e-10,0,3581652e-12,12934e-10,0,2522525e-12,9.1093e-7,0,1776509e-12,6.4153e-7,0,1251141e-12,4.5181e-7,0],Eo=[3.2406,-1.5372,-.4986,-.9689,1.8758,.0415,.0557,-.204,1.057],Do=0xe90f62a5dcb760000;function Oo(e){let t=(e/1e3)**2;return .002152*(1.0455996-341.29061/t-.9023085*t)/(1+.0027059889/t-85.968563*t)}function ko(e,t,n,r,i=1,a=0){let o=e.length/i,s=(r-t)/n;if(s<=0)return e[a];if(s>=o-1)return e[(o-1)*i+a];let c=Math.floor(s),l=s-c;return e[c*i+a]*(1-l)+e[(c+1)*i+a]*l}function Ao(e,t){let n=0,r=bo+e*xo;for(let e=0;e<xo;e++)n+=t(r+e+.5);return n/xo}function jo(e){let t=new Float64Array(16);for(let n=0;n<16;n++)t[n]=Ao(n,e);return t}var Mo=Float64Array.from({length:16},(e,t)=>bo+(t+.5)*xo),No=jo(e=>ko(Co,360,10,e)),Po=jo(e=>Oo(e)/8),Fo=jo(e=>ko(wo,360,10,e)),Io=jo(e=>(e/1e3)**-yo),Lo=(()=>{let e=new Float64Array(48);for(let t=0;t<16;t++)for(let n=0;n<3;n++)e[t*3+n]=Ao(t,e=>ko(To,360,5,e,3,n))*xo;return e})();function Ro(e=1){let t=new Float32Array(48);for(let n=0;n<16;n++){let r=Lo[n*3],i=Lo[n*3+1],a=Lo[n*3+2];for(let o=0;o<3;o++){let s=Eo;t[o*16+n]=(s[o*3]*r+s[o*3+1]*i+s[o*3+2]*a)*e}}return t}function zo(e){let t=0,n=0,r=0;for(let i=0;i<16;i++)t+=e[i]*Lo[i*3],n+=e[i]*Lo[i*3+1],r+=e[i]*Lo[i*3+2];return[t,n,r]}function Bo([e,t,n]){let r=Eo;return[r[0]*e+r[1]*t+r[2]*n,r[3]*e+r[4]*t+r[5]*n,r[6]*e+r[7]*t+r[8]*n]}function Vo(e){return Math.max(0,.0460836582205*e-.04586025928522)}function Ho([e,t,n]){let r=(e,t,n)=>{let r=Math.min(Math.max((n-e)/(t-e),0),1);return r*r*(3-2*r)};return Float64Array.from(Mo,i=>{let a=1-r(470,520,i),o=r(560,610,i);return n*a+e*o+t*(1-a-o)})}function Uo({airDensity:e=1,turbidity:t=2,ozone:n=300,groundAlbedo:r=[.3,.3,.3]}={}){let i=Vo(t)/go,a=n*Do/(15*1e3)*1e3,o=new Float64Array(16),s=new Float64Array(16),c=new Float64Array(16),l=new Float64Array(16);for(let t=0;t<16;t++)o[t]=Po[t]*e,s[t]=Io[t]*i,c[t]=s[t]*_o,l[t]=Fo[t]*a;return{rayleigh:o,mieScattering:c,mieExtinction:s,ozone:l,albedo:Ho(r)}}var Wo=e=>Math.exp(-e/8),Go=e=>Math.exp(-e/go),Ko=e=>Math.max(0,1-Math.abs(e-25)/15);function qo(e){let t=Math.max(e,0);return Math.sqrt(t*(2*mo+t))/(mo+t)}function Jo(e,t,n=1024){let r=Math.max(e,0),i=mo+r,a=i*t,o=r*(2*mo+r);if(t<0&&a*a>=o)return null;let s=-a+Math.sqrt(a*a+(ho-i)*(ho+i)),c=0,l=0,u=0;for(let e=0;e<n;e++){let t=s*(e/n)**2,r=s*((e+1)/n)**2,d=.5*(t+r),f=(o+d*(d+2*a))/(Math.sqrt(i*i+d*(d+2*a))+mo),p=r-t;c+=Wo(f)*p,l+=Go(f)*p,u+=Ko(f)*p}return[c,l,u]}function Yo(e,t){let n=new Float64Array(16);if(!t)return n;let[r,i,a]=t;for(let t=0;t<16;t++)n[t]=Math.exp(-(e.rayleigh[t]*r+e.mieExtinction[t]*i+e.ozone[t]*a));return n}var Xo=[610,550,465].map(e=>-.023+.292/(e/1e3));function Zo(e){let t=Math.sin(e/2);return 4*Math.PI*t*t}function Qo({direction:e,altitude:t,angularDiameter:n,strength:r=1,coefficients:i}){let a=n/2,o=Zo(a),s=qo(t),[c,l,u]=e,d=Math.sin(a),f=new Float64Array(16),p=0,m=e=>{if(e<-s)return;let n=Yo(i,Jo(t,e,512));for(let e=0;e<16;e++)f[e]+=n[e];p++};if(l-d>.1)m(l);else{let e=Math.sqrt(Math.max(0,1-l*l));for(let t=0;t<48;t++){let n=(t+.5)/48,r=-1,i=1;for(let e=0;e<30;e++){let e=.5*(r+i);(Math.asin(e)+e*Math.sqrt(1-e*e)+Math.PI/2)/Math.PI<n?r=e:i=e}m(l+.5*(r+i)*d*e)}}let h=new Float64Array(16),g=l-d>.1?1:48;if(p>0)for(let e=0;e<16;e++)h[e]=No[e]*r/o*f[e]/p;return{radiance:Bo(zo(h)).map(e=>Math.max(0,e*So)),visibleFraction:p/g,solidAngle:o,direction:[c,l,u]}}var $o=e=>3/(16*Math.PI)*(1+e*e);function es(e,t=vo){let n=t*t;return 3/(8*Math.PI)*(1-n)/(2+n)*(1+e*e)/(1+n-2*t*e)**1.5}function ts(e,t,n,r,i=8){let a=n*r,o=e*t,s=new Float32Array(2*o*a);return[$o,e=>es(e)].forEach((c,l)=>{for(let u=0;u<o;u++){let d=-1+2*Math.floor(u/t)/(e-1),f=u%t*Math.PI/(t-1),p=Math.sqrt(Math.max(0,1-d*d)),m=(l*o+u)*a,h=0;for(let e=0;e<a;e++){let t=Math.floor(e/r),a=e%r,o=0;for(let e=0;e<i;e++){let s=-1+2*(t+(e+.5)/i)/n,l=Math.sqrt(Math.max(0,1-s*s));for(let e=0;e<i;e++){let t=Math.PI*(a+(e+.5)/i)/r;o+=c(d*s+p*l*Math.cos(f-t))+c(d*s+p*l*Math.cos(f+t))}}s[m+e]=o,h+=o}for(let e=0;e<a;e++)s[m+e]/=h}}),s}var ns=Math.sqrt(ho*ho-mo*mo),rs=ho-mo,is=Math.PI,as=[0,1,2,3],os=e=>as.map(e);function ss(e){return{r:(0,n.exp)(e.mul(-1/8)),m:(0,n.exp)(e.mul(-1/go)),o:(0,n.max)((0,n.float)(0),(0,n.float)(1).sub((0,n.abs)(e.sub(25)).div(15)))}}function cs(e,t){return os(n=>e.rayleigh[n].mul(t.r).add(e.mieExtinction[n].mul(t.m)).add(e.ozone[n].mul(t.o)))}function ls(e,t){return os(r=>{let i=e[r].mul(t),a=(0,n.exp)(i.negate()),o=(0,n.float)(1).sub(a).div((0,n.max)(i,1e-12));return{weight:(0,n.mix)((0,n.float)(1).sub(i.mul(.5)),o,(0,n.step)(.001,i)).mul(t),transmittance:a}})}function us(e,t,r,i,a,o=1,s=0){let c=(0,n.clamp)(i,0,t-1),l=(0,n.clamp)(a,0,r-1),u=(0,n.floor)(c),d=(0,n.floor)(l),f=c.sub(u),p=l.sub(d),m=(0,n.uint)(u),h=(0,n.uint)(d),g=(0,n.min)(m.add(1),(0,n.uint)(t-1)),_=(0,n.min)(h.add(1),(0,n.uint)(r-1)),v=(n,r)=>e.element(r.mul(t).add(n).mul(o).add(s));return(0,n.mix)((0,n.mix)(v(m,h),v(g,h),f),(0,n.mix)(v(m,_),v(g,_),f),p)}function ds(e,t){let r=e.add(mo),i=(0,n.sqrt)((0,n.max)(e.mul(e.add(2*mo)),0)),a=r.mul(t),o=a.negate().add((0,n.sqrt)((0,n.max)(a.mul(a).add(ns*ns).sub(i.mul(i)),0))),s=(0,n.float)(rs).sub(e),c=i.add(ns);return{x:o.sub(s).div((0,n.max)(c.sub(s),1e-6)).mul(255),y:i.div(ns).mul(63),rho:i,r}}function fs(e,t,r,i,a){let o=ds(r,i),s=us(e,256,64,o.x,o.y).xyz,c=(0,n.smoothstep)(a.negate(),a,i.add(o.rho.div(o.r)));return os(e=>(0,n.exp)(t.rayleigh[e].mul(s.x).add(t.mieExtinction[e].mul(s.y)).add(t.ozone[e].mul(s.z)).negate()).mul(c))}var ps=e=>(0,n.float)(e).div(15).pow(2).mul(rs),ms=e=>(0,n.sqrt)((0,n.clamp)(e.div(rs),0,1)).mul(15),hs=-3*is/180,gs=15*is/180,_s=.5+Math.atan((-is/2-hs)/gs)/is,vs=.5+Math.atan((is/2-hs)/gs)/is,ys=(e,t)=>(0,n.sin)((0,n.clamp)((0,n.tan)((0,n.float)(e).div(t-1).mul(vs-_s).add(_s-.5).mul(is)).mul(gs).add(hs),-is/2,is/2)),bs=(e,t)=>(0,n.atan)((0,n.asin)((0,n.clamp)(e,-1,1)).sub(hs).div(gs)).div(is).add(.5-_s).div(vs-_s).mul(t-1),xs=1e-30,Ss=e=>(0,n.log)((0,n.max)(e,(0,n.vec4)(xs)));function Cs(e,t,r,i,a){let o=[[(0,n.clamp)(bs(r,64),0,63),64],[(0,n.clamp)(ms(t),0,15),16],[(0,n.clamp)(i.add(1).mul(.5*15),0,15),16],[(0,n.clamp)((0,n.acos)((0,n.clamp)(a,-1,1)).mul(7/is),0,7),8]].map(([e,t])=>{let r=(0,n.floor)(e),i=e.sub(r).toVar(),a=(0,n.uint)(r).toVar();return{t:i,i0:a,i1:(0,n.min)(a.add(1),(0,n.uint)(t-1)).toVar()}}),s=[128,8192,8,1],c=[];for(let e=0;e<16;e++){let t=(0,n.uint)(0);o.forEach((n,r)=>{t=t.add((e>>r&1?n.i1:n.i0).mul(s[r]))}),c.push(t.mul(8).toVar())}return Array.from({length:8},(t,r)=>{let i=c.map(t=>e.element(t.add(r)));for(let e=0;e<4;e++){let t=[];for(let r=0;r<i.length;r+=2)t.push((0,n.mix)(i[r],i[r+1],o[e].t));i=t}return(0,n.exp)(i[0])})}function ws(e,t){let r=bs(t,128);return os(t=>(0,n.exp)(us(e,128,1,r,(0,n.float)(0),4,t)))}function Ts(e,t){let r=e.add(mo).toVar(),i=r.mul(t).toVar(),a=e.mul(e.add(2*mo)).toVar(),o=i.mul(i).sub(a),s=t.lessThan(0).and(o.greaterThanEqual(0)).toVar(),c=a.div((0,n.max)(i.negate().add((0,n.sqrt)((0,n.max)(o,0))),1e-9)),l=i.negate().add((0,n.sqrt)((0,n.max)(i.mul(i).add((0,n.float)(ho).sub(r).mul(r.add(ho))),0)));return{r,b:i,cGround:a,hitsGround:s,tMax:s.select(c,l).toVar()}}var Es=(e,t,r)=>e.sub(t.mul(r)).div((0,n.max)((0,n.sqrt)((0,n.float)(1).sub(t.mul(t)).mul((0,n.float)(1).sub(r.mul(r)))),1e-4));function Ds(e,t,r,i){let a=t.mul(t.add(e.b.mul(2))),o=(0,n.sqrt)(e.r.mul(e.r).add(a));return{h:(0,n.max)(e.cGround.add(a).div(o.add(mo)),0),muS:(0,n.clamp)(e.r.mul(r).add(t.mul(i)).div(o),-1,1),mu:(0,n.clamp)(e.b.add(t).div(o),-1,1)}}var Os=e=>e.mul(e).add(1).mul(3/(16*is));function ks(e,t){let r=t*t,i=3/(8*is)*(1-r)/(2+r),a=(0,n.max)((0,n.float)(1+r).sub(e.mul(2*t)),1e-6);return e.mul(e).add(1).mul(i).div(a.mul((0,n.sqrt)(a)))}function As({transmittance:e},t=256){let r=256*64;return(0,n.Fn)(()=>{let i=n.instanceIndex;(0,n.If)(i.greaterThanEqual((0,n.uint)(r)),()=>{(0,n.Return)()});let a=(0,n.float)(i.mod(256)).div(255),o=(0,n.float)(i.div(256)).div(63).mul(ns).toVar(),s=(0,n.sqrt)(o.mul(o).add(mo*mo)).toVar(),c=(0,n.float)(ho).sub(s),l=o.add(ns),u=c.add(a.mul(l.sub(c))).toVar(),d=(0,n.clamp)((0,n.float)(ns*ns).sub(o.mul(o)).sub(u.mul(u)).div((0,n.max)(s.mul(u).mul(2),1e-9)),-1,1).toVar(),f=o.mul(o).toVar(),p=s.mul(d).mul(2).toVar(),m=(0,n.vec3)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(t),type:`int`,condition:`<`},({i:e})=>{let r=(0,n.float)(e).div(t),i=(0,n.float)(e).add(1).div(t),a=u.mul(r.mul(r)),o=u.mul(i.mul(i)),c=a.add(o).mul(.5),l=c.mul(c.add(p)),d=ss((0,n.max)(f.add(l).div((0,n.sqrt)(s.mul(s).add(l)).add(mo)),0));m.addAssign((0,n.vec3)(d.r,d.m,d.o).mul(o.sub(a)))}),e.element(i).assign((0,n.vec4)(m,0))})().compute(r,[64])}var js=4*is/128;function Ms(e,t,r,i){let a=(0,n.float)(e).add((0,n.float)(r.div(i)).add(.5).div(i)).div(16).mul(2).sub(1),o=(0,n.sqrt)((0,n.max)((0,n.float)(1).sub(a.mul(a)),0)),s=(0,n.float)(t).add((0,n.float)(r.mod(i)).add(.5).div(i)).mul(is/8);return(0,n.vec3)(o.mul((0,n.cos)(s)),a,o.mul((0,n.sin)(s)))}function Ns(e,t){let r=bs(t,64);return os(t=>us(e,64,1,r,(0,n.float)(0),4,t))}function Ps(e,{first:t,out:r,cellSamples:i=2,steps:a=20}){let{transmittance:o,transfer:s,multipleScattering:c,groundE:l,coefficients:u,sunSinRadius:d,mieG:f}=e,p=1024*128,m=i*i;return(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(p)),()=>{(0,n.Return)()});let h=e.mod(128),g=e.div(128),_=ys(g.mod(64),64).toVar(),v=(0,n.max)(ps(g.div(64)),.001).toVar(),y=(0,n.vec3)((0,n.sqrt)((0,n.max)((0,n.float)(1).sub(_.mul(_)),0)),_,0).toVar(),b=os(()=>(0,n.vec4)(0).toVar()),x=t?os(()=>(0,n.vec4)(0).toVar()):null;(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(m),type:`int`,condition:`<`,name:`ray`},({ray:e})=>{let r=Ms(h.div(8),h.mod(8),e,i).toVar(),s=(0,n.dot)(r,y).toVar(),p=t?Os(s).toVar():null,m=t?ks(s,f).toVar():null,g=t?null:Array.from({length:8},()=>(0,n.vec4)(0).toVar()),S=Ts(v,r.y),C=os(()=>(0,n.vec4)(1).toVar());(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(a),type:`int`,condition:`<`},({i:e})=>{let r=(0,n.float)(e).div(a),i=(0,n.float)(e).add(1).div(a),l=S.tMax.mul(r.mul(r)),f=S.tMax.mul(i.mul(i)).sub(l),h=Ds(S,l.add(f.mul(.5)),_,s),v=ss(h.h),y=os(e=>u.rayleigh[e].mul(v.r)),w=os(e=>u.mieScattering[e].mul(v.m)),T=ls(cs(u,v),f),E;if(t){let e=fs(o,u,h.h,h.muS,d);E=os(t=>e[t].mul(y[t].mul(p).add(w[t].mul(m))))}else (0,n.If)(e.mod(2).equal(0),()=>{let e=Cs(c,h.h,h.muS,h.mu,Es(s,h.mu,h.muS));for(let t=0;t<8;t++)g[t].assign(e[t])}),E=os(e=>y[e].mul(g[e]).add(w[e].mul(g[4+e])));for(let e of as)b[e].addAssign(C[e].mul(E[e]).mul(T[e].weight)),x&&x[e].addAssign(C[e].mul(y[e].add(w[e])).mul(T[e].weight)),C[e].mulAssign(T[e].transmittance)}),(0,n.If)(S.hitsGround,()=>{let e=(0,n.clamp)(S.r.mul(_).add(S.tMax.mul(s)).div(mo),-1,1),r;if(t){let t=fs(o,u,(0,n.float)(0),e,d);r=os(r=>t[r].mul((0,n.max)(e,0)))}else r=Ns(l,e);for(let e of as)b[e].addAssign(C[e].mul(r[e]).mul(u.albedo[e]).mul(1/is))})});for(let t of as)r.element(e.mul(4).add(t)).assign(b[t].div(m)),x&&s.element(e.mul(4).add(t)).assign(x[t].div(m))})().compute(p,[64])}function Fs(e,{incoming:t,stage:r}){let{transfer:i,phaseCells:a,multipleScattering:o,psiSum:s,groundE:c}=e,l=1024*128,u=r===`last`;return(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(l)),()=>{(0,n.Return)()});let d=e.mod(128),f=e.div(128),p=f.mul(128),m=null;if(u){let e=os(()=>(0,n.vec4)(0).toVar());(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(128),type:`int`,condition:`<`},({i:t})=>{for(let r of as)e[r].addAssign(i.element(p.add((0,n.uint)(t)).mul(4).add(r)))}),m=os(t=>{let r=(0,n.min)(e[t].div(128),.95);return r.div((0,n.float)(1).sub(r)).toVar()})}for(let i=0;i<2;i++){let c=os(()=>(0,n.vec4)(0).toVar());(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(32),type:`int`,condition:`<`},({i:e})=>{let r=a.element((0,n.uint)(i*128).add(d).mul(32).add((0,n.uint)(e))).toVar();for(let i=0;i<4;i++){let a=p.add((0,n.uint)(e).mul(4).add(i)).mul(4),o=r.element((0,n.int)(i));for(let e of as)c[e].addAssign(t.element(a.add(e)).mul(o))}});for(let t of as){let n=e.mul(8).add(i*4+t);r===`first`?(s.element(n).assign(c[t]),o.element(n).assign(Ss(c[t]))):r===`middle`?(s.element(n).addAssign(c[t]),o.element(n).assign(Ss(c[t]))):o.element(n).assign(Ss(s.element(n).add(c[t].mul(m[t].add(1)))))}}u||(0,n.If)(f.lessThan((0,n.uint)(64)).and(d.equal((0,n.uint)(0))),()=>{let e=os(()=>(0,n.vec4)(0).toVar());(0,n.Loop)({start:(0,n.int)(128/2),end:(0,n.int)(128),type:`int`,condition:`<`},({i:r})=>{let i=(0,n.float)((0,n.uint)(r).div(8)).add(.5).div(16).mul(2).sub(1);for(let a of as)e[a].addAssign(t.element(p.add((0,n.uint)(r)).mul(4).add(a)).mul(i))});for(let t of as)c.element(f.mul(4).add(t)).assign(e[t].mul(js))})})().compute(l,[64])}var Is=4;function Ls({transmittance:e,multipleScattering:t,coefficients:r,sunSinRadius:i,mieG:a},o,s,c,l){let u=os(()=>(0,n.vec4)(0).toVar()),d=os(()=>(0,n.vec4)(1).toVar()),f=t?Array.from({length:8},()=>(0,n.vec4)(0).toVar()):null,p=Os(c).toVar(),m=ks(c,a).toVar(),h=o.tMax;return(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(l),type:`int`,condition:`<`},({i:a})=>{let g=(0,n.float)(a).div(l),_=(0,n.float)(a).add(1).div(l),v=h.mul(g.mul(g)),y=h.mul(_.mul(_)).sub(v),b=Ds(o,v.add(y.mul(.5)),s,c),x=ss(b.h),S=os(e=>r.rayleigh[e].mul(x.r)),C=os(e=>r.mieScattering[e].mul(x.m)),w=fs(e,r,b.h,b.muS,i),T=ls(cs(r,x),y);f&&(0,n.If)(a.mod(Is).equal(0),()=>{let e=Cs(t,b.h,b.muS,b.mu,Es(c,b.mu,b.muS));for(let t=0;t<8;t++)f[t].assign(e[t])});for(let e of as){let t=w[e].mul(S[e].mul(p).add(C[e].mul(m)));f&&(t=t.add(S[e].mul(f[e])).add(C[e].mul(f[4+e]))),u[e].addAssign(d[e].mul(t).mul(T[e].weight)),d[e].mulAssign(T[e].transmittance)}}),{L:u,throughput:d}}function Rs(e,{sqrtDirections:t=12,steps:r=32}={}){let{irradiance:i}=e,a=t*t,o=(0,n.float)(.001);return(0,n.Fn)(()=>{let s=n.instanceIndex;(0,n.If)(s.greaterThanEqual((0,n.uint)(128)),()=>{(0,n.Return)()});let c=ys(s,128).toVar(),l=(0,n.vec3)((0,n.sqrt)((0,n.max)((0,n.float)(1).sub(c.mul(c)),0)),c,0).toVar(),u=os(()=>(0,n.vec4)(0).toVar());(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(a),type:`int`,condition:`<`,name:`dirIndex`},({dirIndex:i})=>{let a=(0,n.float)(i.div(t)).add(.5).div(t),s=(0,n.float)(i.mod(t)).add(.5).div(t),d=(0,n.sqrt)(a),f=s.mul(2*is),p=(0,n.vec3)(d.mul((0,n.cos)(f)),(0,n.sqrt)((0,n.max)((0,n.float)(1).sub(a),0)),d.mul((0,n.sin)(f))).toVar(),{L:m}=Ls(e,Ts(o,p.y),c,(0,n.dot)(p,l),r);for(let e of as)u[e].addAssign(m[e])});for(let e of as)i.element(s.mul(4).add(e)).assign(Ss(u[e].mul(is/a)))})().compute(128,[64])}var zs=e=>(0,n.float)(e).div(255).pow(2).mul(is);function Bs(e,{width:t,height:r,steps:i=40,multipleScattering:a=!0}){let{sky:o,skyRows:s,irradiance:c,coefficients:l,rgb:u,sunDirection:d,altitude:f,sunSinRadius:p,transmittance:m}=e,h=a?e:{...e,multipleScattering:null},g=256*r;return[(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(g)),()=>{(0,n.Return)()});let t=(0,n.float)(1).sub((0,n.float)(e.div(256)).add(.5).div(r)).mul(is),a=(0,n.cos)(t).toVar(),o=(0,n.max)(f,.001).toVar(),_=d.y.toVar(),v=(0,n.sin)(t).mul((0,n.cos)(zs(e.mod(256)))).mul((0,n.sqrt)((0,n.max)((0,n.float)(1).sub(_.mul(_)),0))).add(a.mul(_)).toVar(),y=Ts(o,a),{L:b,throughput:x}=Ls(h,y,_,v,i);(0,n.If)(y.hitsGround,()=>{let e=(0,n.clamp)(y.r.mul(_).add(y.tMax.mul(v)).div(mo),-1,1).toVar(),t=fs(m,l,(0,n.float)(0),e,p),r=ws(c,e);for(let i of as)b[i].addAssign(x[i].mul(l.albedo[i]).mul(1/is).mul(t[i].mul((0,n.max)(e,0)).add(r[i])))});let S=os(e=>b[e].mul(l.solar[e])),C=e=>S.reduce((t,r,i)=>t.add((0,n.dot)(r,u[e*4+i])),(0,n.float)(0));s.element(e).assign((0,n.vec4)((0,n.max)((0,n.vec3)(C(0),C(1),C(2)),(0,n.vec3)(0)),1))})().compute(g,[64]),(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(t*r)),()=>{(0,n.Return)()});let i=(0,n.float)(e.mod(t)).add(.5).div(t).sub(.5).mul(2*is).sub((0,n.atan)(d.z,d.x)),a=(0,n.sqrt)((0,n.abs)((0,n.atan)((0,n.sin)(i),(0,n.cos)(i))).div(is)).mul(255).toVar(),c=(0,n.min)((0,n.floor)(a),254).toVar(),l=e.div(t).mul(256).add((0,n.uint)(c)).toVar();o.element(e).assign((0,n.mix)(s.element(l),s.element(l.add(1)),a.sub(c)))})().compute(t*r,[64])]}var Vs=e=>Math.ceil((e+1)*4/256)*64;function Hs(e,t,r){let i=(0,n.int)(0).toVar(),a=(0,n.int)(e-1).toVar();return(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(Math.ceil(Math.log2(e))+1),type:`int`,condition:`<`,name:`step`},()=>{(0,n.If)(i.lessThan(a),()=>{let e=i.add(a).div(2).toVar();(0,n.If)(t(e).lessThan(r),()=>{i.assign(e.add(1))}).Else(()=>{a.assign(e)})})}),i}function Us({pixels:e,rows:t,prefix:r,stats:i,cdf:a,width:o,height:s}){let c=Vs(o),l=e=>(0,n.sin)((0,n.float)(e).add(.5).mul(Math.PI/s)),u=(t,r,i)=>(0,n.dot)(e.element(t.mul(o).add(r)).xyz,zi).mul(i),d=()=>(0,n.If)(n.instanceIndex.greaterThan((0,n.uint)(0)),()=>{(0,n.Return)()});return[(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(s)),()=>{(0,n.Return)()});let r=l(e).toVar(),i=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(o),type:`int`,condition:`<`},({i:t})=>{i.addAssign(u(e,(0,n.uint)(t),r))}),t.element(e).assign((0,n.vec4)(i,0,0,0))})().compute(s,[64]),(0,n.Fn)(()=>{d();let e=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(s),type:`int`,condition:`<`},({i:n})=>{e.addAssign(t.element(n).x)}),i.element(0).assign((0,n.vec4)(e,e.div(o*s),0,0))})().compute(1,[1]),(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(s)),()=>{(0,n.Return)()});let a=l(e).toVar(),c=i.element(0).y.toVar(),d=(0,n.float)(0).toVar(),f=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(o),type:`int`,condition:`<`},({i:t})=>{let i=u(e,(0,n.uint)(t),a).toVar();d.addAssign(i),f.addAssign((0,n.max)(i.sub(c),0)),r.element(e.mul(o).add((0,n.uint)(t))).assign((0,n.vec2)(d,f))}),t.element(e).assign((0,n.vec4)(d,f,0,0))})().compute(s,[64]),(0,n.Fn)(()=>{d();let e=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(s),type:`int`,condition:`<`},({i:n})=>{e.addAssign(t.element(n).y)});let r=e.greaterThan(0).toVar(),l=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(s),type:`int`,condition:`<`},({i:e})=>{let i=t.element(e).toVar();l.addAssign((0,n.select)(r,i.y,i.x)),t.element(e).assign((0,n.vec4)(i.x,i.y,l,0))});let u=i.element(0).toVar();i.element(1).assign((0,n.select)(r,(0,n.vec4)(e,u.y,1,0),(0,n.vec4)(u.x,0,0,0))),(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(s),type:`int`,condition:`<`,name:`row`},({row:e})=>{let r=(0,n.select)(l.greaterThan(0),(0,n.float)(Hs(s,e=>t.element(e).z,(0,n.float)(e).add(1).div(s).mul(l))),(0,n.float)(s-1));a.element((0,n.uint)(e).mul(c).add(o)).assign(r.add(.5).div(s))})})().compute(1,[1]),(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(o*s)),()=>{(0,n.Return)()});let l=e.mod(o),u=e.div(o),d=i.element(1).z.greaterThan(0).toVar(),f=t.element(u).toVar(),p=(0,n.select)(d,f.y,f.x).toVar(),m=u.mul(o).toVar(),h=Hs(o,e=>{let t=r.element(m.add((0,n.uint)(e)));return(0,n.select)(d,t.y,t.x)},(0,n.float)(l).add(1).div(o).mul(p)),g=(0,n.select)(p.greaterThan(0),(0,n.float)(h),(0,n.float)(o-1));a.element(u.mul(c).add(l)).assign(g.add(.5).div(o))})().compute(o*s,[64])]}function Ws(e,t,n){let i=new r.DataTexture(null,e,t,n,r.FloatType);return i.source.dataReady=!1,i.needsUpdate=!0,i._isPhysicalSky=!0,i}var Gs=class{constructor(e=1024,t=512,n={}){this.width=e,this.height=t,this._quality=n,this.lastRenderTime=0,this._texture=Ws(e,t,r.RGBAFormat),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,this._cdfTexture=Ws(e+1,t,r.RedFormat),this._rec709Weights=Ro(So),this._attrs=null,this._kernels=null,this._airKey=null,this._transmittanceBuilt=!1}_init(){let e=e=>Array.from({length:e},()=>(0,n.uniform)(new r.Vector4)),i=e(24);this._uniforms={coefficient:i,rgb:e(12),sunDirection:(0,n.uniform)(new r.Vector3(0,1,0)),altitude:(0,n.uniform)(.05),sunSinRadius:(0,n.uniform)(.0046)};let a=e=>S(e,4);this._attrs={transmittance:a(256*64),incomingA:a(1024*128*4),incomingB:a(1024*128*4),transfer:a(1024*128*4),multipleScattering:a(1024*128*8),psiSum:a(1024*128*8),groundE:a(256),irradiance:a(512),sky:a(this.width*this.height),skyRows:a(256*this.height),cdfRows:a(this.height),cdfPrefix:S(this.width*this.height,2),cdfStats:a(2),cdf:S(Vs(this.width)*this.height,1),phaseCells:new t.StorageInstancedBufferAttribute(ts(16,8,16,8),4)};let o=(e,t=`vec4`)=>(0,n.storage)(this._attrs[e],t,this._attrs[e].count),s=e=>i.slice(e*4,e*4+4),c={transmittance:o(`transmittance`),transfer:o(`transfer`),psiSum:o(`psiSum`),groundE:o(`groundE`),phaseCells:o(`phaseCells`),multipleScattering:o(`multipleScattering`),irradiance:o(`irradiance`),sky:o(`sky`),skyRows:o(`skyRows`),coefficients:{rayleigh:s(0),mieScattering:s(1),mieExtinction:s(2),ozone:s(3),solar:s(4),albedo:s(5)},rgb:this._uniforms.rgb,sunDirection:this._uniforms.sunDirection,altitude:this._uniforms.altitude,sunSinRadius:this._uniforms.sunSinRadius,mieG:vo},l=this._quality,u=o(`incomingA`),d=o(`incomingB`);this._kernels={transmittance:As(c),air:[Ps(c,{first:!0,out:u,...l.incoming}),Fs(c,{incoming:u,stage:`first`}),Ps(c,{first:!1,out:d,...l.incoming}),Fs(c,{incoming:d,stage:`middle`}),Ps(c,{first:!1,out:u,...l.incoming}),Fs(c,{incoming:u,stage:`last`}),Rs(c,l.irradiance)],sky:Bs(c,{width:this.width,height:this.height,...l.sky}),cdf:Us({pixels:c.sky,rows:o(`cdfRows`),prefix:o(`cdfPrefix`,`vec2`),stats:o(`cdfStats`),cdf:o(`cdf`,`float`),width:this.width,height:this.height})},this._setSpectrum(4,No)}_setColorWeights(){let e=this._rec709Weights,t=zr(),n=[0,0,0,0];for(let r=0;r<3;r++)for(let i=0;i<4;i++){for(let a=0;a<4;a++){let o=i*4+a;n[a]=t?t[r*3]*e[o]+t[r*3+1]*e[16+o]+t[r*3+2]*e[32+o]:e[r*16+o]}this._uniforms.rgb[r*4+i].value.fromArray(n)}}_copyToTextures(e){let t=e.backend;e.initTexture(this._texture),e.initTexture(this._cdfTexture);let n=t.device.createCommandEncoder({label:`PhysicalSky`});n.copyBufferToTexture({buffer:t.get(this._attrs.sky).buffer,bytesPerRow:this.width*16,rowsPerImage:this.height},{texture:t.get(this._texture).texture},[this.width,this.height]),n.copyBufferToTexture({buffer:t.get(this._attrs.cdf).buffer,bytesPerRow:Vs(this.width)*4,rowsPerImage:this.height},{texture:t.get(this._cdfTexture).texture},[this.width+1,this.height]),t.device.queue.submit([n.finish()])}_setSpectrum(e,t){for(let n=0;n<4;n++)this._uniforms.coefficient[e*4+n].value.set(t[n*4],t[n*4+1],t[n*4+2],t[n*4+3])}bake(e,t){let n=performance.now();this._kernels||this._init();let r={airDensity:t.airDensity,turbidity:t.turbidity,ozone:t.ozone,groundAlbedo:[...t.groundAlbedo]},i=Uo(r),a=Math.max(t.altitude,1)/1e3,o=t.sunAngularDiameter/2,s=this._uniforms;s.sunDirection.value.fromArray(t.sunDirection).normalize(),s.altitude.value=a,s.sunSinRadius.value=Math.sin(o),this._setColorWeights();let c=[];this._transmittanceBuilt||=(c.push(this._kernels.transmittance),!0);let l=JSON.stringify([r,s.sunSinRadius.value]);l!==this._airKey&&(this._setSpectrum(0,i.rayleigh),this._setSpectrum(1,i.mieScattering),this._setSpectrum(2,i.mieExtinction),this._setSpectrum(3,i.ozone),this._setSpectrum(5,i.albedo),c.push(...this._kernels.air),this._airKey=l),c.push(...this._kernels.sky,...this._kernels.cdf),e.compute(c),this._copyToTextures(e);let u=e.getArrayBufferAsync(this._attrs.cdfStats).then(e=>{let t=new Float32Array(e);return{totalSum:t[4],compensationDelta:t[5]}}),d=Qo({direction:[s.sunDirection.value.x,s.sunDirection.value.y,s.sunDirection.value.z],altitude:a,angularDiameter:t.sunAngularDiameter,strength:t.sunStrength??1,coefficients:i});return d.cosHalfAngle=Math.cos(o),d.sinHalfAngle=Math.sin(o),d.horizonSin=qo(a),this.lastRenderTime=performance.now()-n,{texture:this._texture,cdfTexture:this._cdfTexture,sun:d,stats:u}}async readBack(e){let[t,n,r]=await Promise.all([`sky`,`cdf`,`cdfStats`].map(t=>e.getArrayBufferAsync(this._attrs[t])));return{pixels:new Float32Array(t),cdf:new Float32Array(n),cdfStride:Vs(this.width),stats:new Float32Array(r)}}getLastRenderTime(){return this.lastRenderTime}dispose(e=null){for(let e of Object.values(this._kernels??{}).flat())e.dispose();for(let t of Object.values(this._attrs??{}))Ca(e,t);this._kernels=null,this._attrs=null,this._texture.dispose(),this._cdfTexture.dispose()}},Ks=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}renderGradient(e){let t=performance.now(),{width:n,height:r}=this,i=this._pixels,a=e.zenithColor.r,o=e.zenithColor.g,s=e.zenithColor.b,c=e.horizonColor.r,l=e.horizonColor.g,u=e.horizonColor.b,d=e.groundColor.r,f=e.groundColor.g,p=e.groundColor.b;for(let e=0;e<r;e++){let t=(e+.5)/r,m,h,g;if(t>.5){let e=(t-.5)*2;m=c+(a-c)*e,h=l+(o-l)*e,g=u+(s-u)*e}else{let e=t*2;m=d+(c-d)*e,h=f+(l-f)*e,g=p+(u-p)*e}for(let t=0;t<n;t++){let r=(e*n+t)*4;i[r]=m,i[r+1]=h,i[r+2]=g,i[r+3]=1}}return this._texture.needsUpdate=!0,delete this._texture.userData?.__rayzeeColorSpace,this.lastRenderTime=performance.now()-t,this._texture}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()}};function qs(e){let t=String(e??``);return/(hdr|pq|hlg|2100|st2084)/i.test(t)?null:/^display\s*p3\b/i.test(t)?`display-p3`:/^(srgb|rec\.?\s*1886|bt\.?\s*1886|gamma\s*2\.2\s*rec\.?\s*709)\b(?!.*(p3|2020))/i.test(t)?`srgb`:null}function Js(e){if(e){Object.assign(Zs,e);for(let t of Object.keys(e))Qs.add(t)}}function Ys(e){return Qs.has(e)}function Xs(){return{...Zs}}var Zs,Qs,$s=y((()=>{Zs={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`},Qs=new Set}));$s(),jt();var ec=vt(`ocio`);function tc(e){let t=String(e);/\[OpenColorIO Error\]/.test(t)?ec.error(t):/\[OpenColorIO Warning\]/.test(t)?ec.warn(t):ec.debug(t)}var nc=null,rc=null,ic=null,ac=null,oc=null;async function sc(){let{ocioRuntimeFactory:e,ocioRuntimeUrl:t}=Xs();if(typeof e==`function`)return await e();if(typeof t==`string`&&t)return await import(t);throw Error(`OpenColorIO runtime not configured. Call configureAssets({ ocioRuntimeFactory: () => import('@bb-studio/ocio') }) before loading a config.`)}async function cc(){return rc||(nc||=(async()=>{let e=await sc();if(typeof e.createOcioRuntime!=`function`)throw Error(`OCIO module has no createOcioRuntime() — wrong package or version`);let{ocioWasmUrl:t}=Xs();return rc=await e.createOcioRuntime({...t?{wasmUrl:t}:{},moduleOptions:{print:tc,printErr:tc}}),rc})().catch(e=>{throw nc=null,e}),await nc)}async function lc(){return(await cc()).ocio.listBuiltinConfigs()}async function uc({builtin:e,text:t,files:n=[],configPath:r=`config.ocio`,id:i}={}){let a=await cc();if(e)ic=a.loadBuiltinConfig(e),ac=e,oc=gc(a,e);else{let e=n.map(e=>({relativePath:e.relativePath??e.path??e.name,data:e.data instanceof Uint8Array?e.data:new Uint8Array(e.data)}));if(t!==void 0&&e.unshift({relativePath:r,data:new TextEncoder().encode(t)}),!e.some(e=>e.relativePath===r))throw Error(`config package has no "${r}" — pass configPath to name the .ocio file`);ic=a.loadConfigPackage({configRelativePath:r,files:e},i?{id:i}:void 0),ac=i??ic.id;let o=e.find(e=>e.relativePath===r);oc=o?new TextDecoder().decode(o.data):null}return hc()}function dc(){ic=null,ac=null,oc=null}function fc(){return ic!==null}function pc(){return ic?rc:null}function mc(){return ic}function hc(){if(!ic)return null;let e=Object.fromEntries(ic.roles.map(e=>[e.name,e.colorSpace]));return{id:ac,name:oc?.match(/^name:\s*(\S.*?)\s*$/m)?.[1]??null,ocioVersion:ic.ocioVersion,version:ic.version,roles:e,sceneLinear:e.scene_linear??null,colorPicking:e.color_picking??e.texture_paint??null,texturePaint:e.texture_paint??e.color_picking??null,data:e.data??null,compositingLog:e.compositing_log??e.color_timing??null,colorSpaces:ic.colorSpaces.map(e=>({name:e.name,family:e.family,categories:e.categories??[],encoding:e.encoding,isData:e.isData,aliases:e.aliases,description:e.description})),displays:ic.displays.slice(),defaultDisplay:ic.defaultDisplay,views:Object.fromEntries(Object.entries(ic.viewsByDisplay).map(([e,t])=>[e,t.map(e=>({name:e.name,transform:e.transform,colorSpace:e.colorSpace,looks:e.looks,description:e.description}))])),defaultViews:{...ic.defaultViewsByDisplay},looks:ic.looks.map(e=>({name:e.name,processSpace:e.processSpace,description:e.description,forward:e.hasForwardTransform,inverse:e.hasInverseTransform})),namedTransforms:ic.namedTransforms.map(e=>e.name),fileRules:ic.fileRules.map(e=>({index:e.index,name:e.name,colorSpace:e.colorSpace,pattern:e.pattern,extension:e.extension,regex:e.regex})),contextVariables:_c()}}function gc(e,t){try{return e.ocio.getBuiltinConfigYaml(t)}catch{return null}}function _c(){if(!oc)return[];let e=new Map,t=oc.split(/\r?\n/),n=t.findIndex(e=>/^environment:\s*(\{\s*\})?\s*$/.test(e));if(n>=0&&!/\{\s*\}/.test(t[n]))for(let r=n+1;r<t.length;r++){let n=t[r];if(/^\S/.test(n))break;let i=n.match(/^\s+([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*?)\s*$/);i&&e.set(i[1],{name:i[1],default:i[2].replace(/^["']|["']$/g,``)||null,declared:!0})}for(let t of oc.matchAll(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g))e.has(t[1])||e.set(t[1],{name:t[1],default:null,declared:!1});return[...e.values()].sort((e,t)=>e.name.localeCompare(t.name))}function vc(){dc(),rc?.dispose?.(),rc=null,nc=null}var yc=1<<20,bc=new Map,xc=new Map,Sc=4096,Cc=new Map;function wc(e,t,n){return`${e}\u0000${t}\u0000${n?JSON.stringify(n):``}`}function Tc(){for(let e of bc.values())e.dispose?.();bc.clear(),xc.clear(),Cc.clear()}function Ec(e,t,{context:n=null}={}){if(!pc()||e===t)return null;let r=wc(e,t,n),i=bc.get(r);if(i!==void 0)return i;try{i=Ac().createColorSpaceProcessor(e,t,n?{context:n}:void 0),i.isNoOp&&(i.dispose(),i=null)}catch(n){throw Error(`no OCIO transform from "${e}" to "${t}": ${n.message}`)}return bc.set(r,i),i}var Dc=null,Oc=null,kc=!1;function Ac(){let e=pc();if(!e)throw Error(`no OCIO config loaded`);if(e.config)return e.config;let t=mc();if(Dc&&Oc===t.id)return Dc;if(kc&&Dc?.dispose?.(),!t.id?.startsWith(`ocio://`))throw Error(`OCIO runtime exposes no Config handle for this config`);return Dc=e.ocio.createBuiltinConfig(t.id),kc=!0,Oc=t.id,Dc}function jc(){kc&&Dc?.dispose?.(),Dc=null,Oc=null,kc=!1,Tc()}function Mc(e,t,n,{context:r=null}={}){let i=pc();if(!i||t===n)return[e[0],e[1],e[2]];let a=`${wc(t,n,r)}\u0000${e[0]},${e[1]},${e[2]}`,o=xc.get(a);if(o)return o.slice();let s=i.transformRgb(t,n,[e[0],e[1],e[2]],r?{context:r}:void 0);return xc.size>=Sc&&xc.clear(),xc.set(a,s),s.slice()}function Nc(e,t,n,{context:r=null}={}){if(e.length%4!=0)throw Error(`convertPixelsF32 wants 4 floats per pixel`);let i=Ec(t,n,{context:r});if(!i)return e;let a=e.length/4;if(a<=yc)return i.applyRGBAF32(e),e;for(let t=0;t<a;t+=yc){let n=Math.min(yc,a-t);i.applyRGBAF32(e.subarray(t*4,(t+n)*4))}return e}var Pc=.055;function Fc(e){return e<=.04045?e/12.92:((e+Pc)/(1+Pc))**2.4}function Ic(e){return e<=0?0:e<=.0031308?12.92*e:(1+Pc)*e**(1/2.4)-Pc}var Lc=new Float32Array(256);for(let e=0;e<256;e++)Lc[e]=Fc(e/255);var Rc=new Float32Array(256);for(let e=0;e<256;e++)Rc[e]=e/255;function zc(e){return e===`srgb`?Lc:Rc}function Bc(e,t,n,{context:r=null,inputEncoding:i=`raw`,outputEncoding:a=`srgb`}={}){if(e.length%4!=0)throw Error(`convertEncodedRGBA8 wants 4 bytes per pixel`);let o=Ec(t,n,{context:r});if(!o)return e;let s=e.length/4,c=zc(i),l=a===`srgb`?Uc:Wc,u=new Float32Array(Math.min(yc,s)*4);for(let t=0;t<s;t+=yc){let n=Math.min(yc,s-t),r=n*4===u.length?u:u.subarray(0,n*4);for(let i=0;i<n;i++){let n=(t+i)*4,a=i*4;r[a]=c[e[n]],r[a+1]=c[e[n+1]],r[a+2]=c[e[n+2]],r[a+3]=1}o.applyRGBAF32(r);for(let i=0;i<n;i++){let n=(t+i)*4,a=i*4;e[n]=l(r[a]),e[n+1]=l(r[a+1]),e[n+2]=l(r[a+2])}}return e}var Vc=65536,Hc=new Uint8Array(Vc+1);for(let e=0;e<=Vc;e++){let t=e/Vc;Hc[e]=Math.round(Ic(t*t)*255)}function Uc(e){return e>0?e>=1?255:Hc[Math.sqrt(e)*Vc+.5|0]:0}function Wc(e){return e>0?e>=1?255:e*255+.5|0:0}function Gc(e,t,n=`srgb`){if(!t)return e;let r=zc(n),i=n===`srgb`?Uc:Wc,[a,o,s,c,l,u,d,f,p]=t;for(let t=0;t<e.length;t+=4){let n=r[e[t]],m=r[e[t+1]],h=r[e[t+2]];e[t]=i(a*n+o*m+s*h),e[t+1]=i(c*n+l*m+u*h),e[t+2]=i(d*n+f*m+p*h)}return e}function Kc(e,t,{context:n=null,tolerance:r=1e-4}={}){if(!pc())return null;if(e===t)return[1,0,0,0,1,0,0,0,1];let i=wc(e,t,n);if(Cc.has(i))return Cc.get(i);let a=Ec(e,t,{context:n});if(!a)return Cc.set(i,[1,0,0,0,1,0,0,0,1]),Cc.get(i);let o=e=>{let t=new Float32Array([e[0],e[1],e[2],1]);return a.applyRGBAF32(t),[t[0],t[1],t[2]]},s=[o([1,0,0]),o([0,1,0]),o([0,0,1])],c=[s[0][0],s[1][0],s[2][0],s[0][1],s[1][1],s[2][1],s[0][2],s[1][2],s[2][2]],l=e=>[c[0]*e[0]+c[1]*e[1]+c[2]*e[2],c[3]*e[0]+c[4]*e[1]+c[5]*e[2],c[6]*e[0]+c[7]*e[1]+c[8]*e[2]],u=[[.18,.18,.18],[.5,.25,.75],[2,.1,.4],[.02,.9,.3],[8,4,1],[.001,.002,.004]],d=!0;for(let e of u){let t=o(e),n=l(e),i=Math.max(.001,Math.abs(n[0]),Math.abs(n[1]),Math.abs(n[2]));for(let e=0;e<3;e++)Math.abs(t[e]-n[e])>r*i&&(d=!1);if(!d)break}let f=d?c:null;return Cc.set(i,f),f}function qc(e){let t=mc();if(!t)return!1;let n=t.colorSpaces.find(t=>t.name===e||t.aliases?.includes(e));return n?n.isData:!1}function Jc(e){let t=mc();return!t||!e?!1:t.colorSpaces.some(t=>t.name===e||t.aliases?.includes(e))}function Yc(e,t,n,r,i){i[0]=nl(e),i[1]=nl(t),i[2]=nl(n)}function Xc(e,t,n,r,i){i[0]=nl(e*r),i[1]=nl(t*r),i[2]=nl(n*r)}function Zc(e,t,n,r,i){e*=r,t*=r,n*=r,i[0]=nl(e/(e+1)),i[1]=nl(t/(t+1)),i[2]=nl(n/(n+1))}function Qc(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 $c(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]=nl(1.60475*a-.53108*o-.07367*s),i[1]=nl(-.10208*a+1.10813*o-.00605*s),i[2]=nl(-.00327*a-.07276*o+1.07602*s)}function el(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=nl((Math.log2(Math.max(c,1e-10))-d)/f),l=nl((Math.log2(Math.max(l,1e-10))-d)/f),u=nl((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]=nl(1.6605*m-.5876*h-.0728*g),i[1]=nl(-.1246*m+1.1329*h-.0083*g),i[2]=nl(-.0182*m-.1006*h+1.1187*g)}function tl(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 nl,rl,il,al,ol,sl,cl,ll=y((()=>{nl=e=>Math.min(Math.max(e,0),1),rl=`
|
|
301
|
+
`),_a=(e,t)=>ga({r0:e[0].xyz,r1:e[1].xyz,r2:e[2].xyz,v:t.sub((0,n.vec3)(e[0].w,e[1].w,e[2].w))});jt();var va=vt(`gpu`),ya={ORIGIN_META:0,DIR_FLAGS:1,THROUGHPUT_PDF:2,RADIANCE_ALPHA:3,MEDIUM_STACK:4,MEDIUM_SIGMA_A:5,SSS_SIGMA_S:6},ba={DIST_TRI_BARY:0,NORMAL_MAT:1,RNG:2},xa=0,Sa=(e,t)=>t===0?e:e.add(t*xa);function Ca(e,t){t&&e?._attributes?.delete?.(t)}var wa=class{constructor(e=0,t=null){this.capacity=0,this._renderer=t,this._attrs={},this.rayBuffer=null,this.hitBuffer=null,e>0&&this.allocate(e)}allocate(e){this.dispose(),this.capacity=e,xa=e;let t=e*7,r=S(t,4);this._attrs.ray=r,this.rayBuffer={rw:(0,n.storage)(r,`vec4`),ro:(0,n.storage)(r,`vec4`).toReadOnly()};let i=e*3,a=S(i,4,Uint32Array);this._attrs.hit=a,this.hitBuffer={rw:(0,n.storage)(a,`uvec4`),ro:(0,n.storage)(a,`uvec4`).toReadOnly()},this.rayBytes=t*16,this.hitBytes=i*16,this.totalBytes=this.rayBytes+this.hitBytes,va.debug(`ray pool capacity ${J.n(e)} · ${J.mb(this.totalBytes)} (rays ${J.mb(this.rayBytes)} · hits ${J.mb(this.hitBytes)})`)}resize(e){return e<=this.capacity&&this.capacity>0?!1:(this.allocate(e),!0)}dispose(){Ca(this._renderer,this._attrs.ray),Ca(this._renderer,this._attrs.hit),this._attrs={},this.rayBuffer=null,this.hitBuffer=null,this.capacity=0}},Ta=(e,t)=>e.element(Sa(t,ya.ORIGIN_META)).xyz,Ea=(e,t)=>e.element(Sa(t,ya.DIR_FLAGS)).xyz,Da=(e,t)=>(0,n.floatBitsToUint)(e.element(Sa(t,ya.DIR_FLAGS)).w),Oa=(e,t)=>e.element(Sa(t,ya.THROUGHPUT_PDF)).xyz,ka=(e,t)=>e.element(Sa(t,ya.THROUGHPUT_PDF)).w,Aa=(e,t)=>e.element(Sa(t,ya.RADIANCE_ALPHA)),ja=e=>(0,n.uint)(e).mul(1),Ma=(e,t,r,i,a,o=null)=>{let s=ja(t),c=o===null?(0,n.unpackUnorm2x16)(e.element(s).w).y:(0,n.float)(o);return e.element(s).assign((0,n.uvec4)((0,n.packSnorm2x16)((0,n.vec2)(r.x,r.y)),(0,n.packSnorm2x16)((0,n.vec2)(r.z,i)),(0,n.packUnorm2x16)((0,n.vec2)(a.x,a.y)),(0,n.packUnorm2x16)((0,n.vec2)(a.z,c))))},Na=(e,t,r)=>{let i=ja(t),a=e.element(i).toVar();return e.element(i).assign((0,n.uvec4)(a.x,a.y,a.z,(0,n.packUnorm2x16)((0,n.vec2)((0,n.unpackUnorm2x16)(a.w).x,r))))},Pa=(e,t)=>e.element(ja(t)),Fa=e=>(0,n.unpackUnorm2x16)(e.w).y,Ia=e=>{let t=(0,n.unpackSnorm2x16)(e.x),r=(0,n.unpackSnorm2x16)(e.y);return(0,n.vec4)((0,n.vec3)(t.x,t.y,r.x).mul(.5).add(.5),r.y)},La=e=>(0,n.vec3)((0,n.unpackUnorm2x16)(e.z),(0,n.unpackUnorm2x16)(e.w).x),Ra=e=>{let t=(0,n.clamp)((0,n.floor)((0,n.log2)((0,n.max)(e,1e-6))),-8,7),r=(0,n.clamp)((0,n.float)(e).mul((0,n.exp2)(t.negate())).sub(1).mul(64),0,63);return(0,n.select)((0,n.float)(e).lessThan(.004),(0,n.uint)(0),(0,n.uint)(t.add(8)).shiftLeft(6).bitOr((0,n.uint)(r)))},za=(e,t)=>{let r=(0,n.floatBitsToUint)(e.element(Sa(t,ya.ORIGIN_META)).w).shiftRight(22),i=(0,n.float)(r.shiftRight(6).bitAnd((0,n.uint)(15))).sub(8),a=(0,n.float)(r.bitAnd((0,n.uint)(63))).div(64).add(1);return(0,n.select)(r.equal((0,n.uint)(0)),(0,n.float)(0),a.mul((0,n.exp2)(i)))},Ba=(e,t,r,i,a,o=(0,n.uint)(0),s=null)=>{let c=(0,n.uint)(i).bitAnd((0,n.uint)(255)).bitOr((0,n.uint)(a).bitAnd((0,n.uint)(255)).shiftLeft(8)).bitOr((0,n.uint)(o).bitAnd((0,n.uint)(63)).shiftLeft(16));return s!==null&&(c=c.bitOr(Ra(s).shiftLeft(22))),e.element(Sa(t,ya.ORIGIN_META)).assign((0,n.vec4)(r,(0,n.uintBitsToFloat)(c)))},Va=(e,t,r,i)=>e.element(Sa(t,ya.DIR_FLAGS)).assign((0,n.vec4)(r,(0,n.uintBitsToFloat)(i))),Ha=(e,t,r,i)=>e.element(Sa(t,ya.THROUGHPUT_PDF)).assign((0,n.vec4)(r,i)),Ua=(e,t,n)=>e.element(Sa(t,ya.RADIANCE_ALPHA)).assign(n),Wa=(e,t)=>(0,n.uintBitsToFloat)(e.element(Sa(t,ba.DIST_TRI_BARY)).x),Ga=(e,t)=>e.element(Sa(t,ba.DIST_TRI_BARY)).y,Ka=(e,t)=>(0,n.uintBitsToFloat)(e.element(Sa(t,ba.DIST_TRI_BARY)).zw),qa=(e,t)=>ia(e.element(Sa(t,ba.NORMAL_MAT)).x),Ja=(e,t)=>(0,n.uint)(e.element(Sa(t,ba.NORMAL_MAT)).y),Ya=(e,t)=>(0,n.int)(e.element(Sa(t,ba.NORMAL_MAT)).z).sub((0,n.int)(1)),Xa=(e,t)=>e.element(Sa(t,ba.NORMAL_MAT)).w,Za=(e,t)=>e.element(Sa(t,ba.RNG)).x,Qa=(e,t,r)=>e.element(Sa(t,ba.RNG)).assign((0,n.uvec4)(r,0,0,0)),$a=(e,t,r,i,a,o,s,c,l,u=(0,n.uint)(0))=>{e.element(Sa(t,ba.DIST_TRI_BARY)).assign((0,n.uvec4)((0,n.floatBitsToUint)(r),i,(0,n.floatBitsToUint)(a),(0,n.floatBitsToUint)(o))),e.element(Sa(t,ba.NORMAL_MAT)).assign((0,n.uvec4)(ra(s),c,l,u))},eo=(e,t)=>{let r=e.element(Sa(t,ya.MEDIUM_STACK)),i=(0,n.floatBitsToUint)(r.x);return{stackDepth:i.bitAnd(255),transTraversals:i.shiftRight(8).bitAnd(255),wavelength:i.shiftRight(16).bitAnd(65535),ior1:r.y,ior2:r.z,ior3:r.w}},to=(e,t,r,i,a,o,s,c=(0,n.uint)(0))=>e.element(Sa(t,ya.MEDIUM_STACK)).assign((0,n.vec4)((0,n.uintBitsToFloat)(r.bitOr(i.shiftLeft(8)).bitOr(c.shiftLeft(16))),a,o,s)),no=(e,t)=>e.element(Sa(t,ya.MEDIUM_SIGMA_A)).xyz,ro=(e,t,r)=>{let i=e.element(Sa(t,ya.MEDIUM_SIGMA_A)).w.toVar();e.element(Sa(t,ya.MEDIUM_SIGMA_A)).assign((0,n.vec4)(r,i))},io=e=>{let t=(0,n.clamp)(e,(0,n.vec3)(0),(0,n.vec3)(1)).mul(1023).add(.5);return(0,n.uint)(t.x).bitOr((0,n.uint)(t.y).shiftLeft(10)).bitOr((0,n.uint)(t.z).shiftLeft(20))},ao=e=>(0,n.vec3)((0,n.float)(e.bitAnd((0,n.uint)(1023))),(0,n.float)(e.shiftRight(10).bitAnd((0,n.uint)(1023))),(0,n.float)(e.shiftRight(20).bitAnd((0,n.uint)(1023)))).div(1023),oo=(e,t)=>ao((0,n.floatBitsToUint)(e.element(Sa(t,ya.MEDIUM_SIGMA_A)).w)),so=(e,t,r)=>{let i=e.element(Sa(t,ya.MEDIUM_SIGMA_A)).xyz.toVar();e.element(Sa(t,ya.MEDIUM_SIGMA_A)).assign((0,n.vec4)(i,(0,n.uintBitsToFloat)(io(r))))},co=(e,t)=>(0,n.int)((0,n.floatBitsToUint)(e.element(Sa(t,ya.ORIGIN_META)).w).bitAnd(255)),lo=(e,t)=>(0,n.int)((0,n.floatBitsToUint)(e.element(Sa(t,ya.ORIGIN_META)).w).shiftRight(8).bitAnd(255)),uo=(e,t)=>(0,n.int)((0,n.floatBitsToUint)(e.element(Sa(t,ya.ORIGIN_META)).w).shiftRight(16).bitAnd((0,n.uint)(63))),fo=(e,t)=>{let n=e.element(Sa(t,ya.SSS_SIGMA_S));return{sigmaS:n.xyz,g:n.w}},po=(e,t,r,i)=>e.element(Sa(t,ya.SSS_SIGMA_S)).assign((0,n.vec4)(r,i)),mo=6360,ho=6420,go=1.2,_o=.9,vo=.76,yo=1.3,bo=380,xo=25,So=1/32,Co=[1.11776,1.14259,1.01249,1.14716,1.72765,1.73054,1.6887,1.61253,1.91198,2.03474,2.02042,2.02212,1.93377,1.95809,1.91686,1.8298,1.8685,1.8931,1.85149,1.8504,1.8341,1.8345,1.8147,1.78158,1.7533,1.6965,1.68194,1.64654,1.6048,1.52143,1.55622,1.5113,1.474,1.4482,1.41018,1.36775,1.34188,1.31429,1.28303,1.26758,1.2367,1.2082,1.18737,1.14683,1.12362,1.1058,1.07124,1.04992],wo=[118e-29,2182e-31,2818e-31,6636e-31,1527e-30,2763e-30,552e-29,8451e-30,1582e-29,2316e-29,3669e-29,4924e-29,7752e-29,9016e-29,148e-27,1602e-28,2139e-28,2755e-28,3091e-28,35e-26,4266e-28,4672e-28,4398e-28,4701e-28,5019e-28,4305e-28,374e-27,3215e-28,2662e-28,2238e-28,1852e-28,1473e-28,1209e-28,9423e-29,7455e-29,6566e-29,5105e-29,415e-28,4228e-29,3237e-29,2451e-29,2801e-29,2534e-29,1624e-29,1465e-29,2078e-29,1383e-29,7105e-30],To=[1299e-7,3917e-9,6061e-7,2321e-7,6965e-9,.001086,4149e-7,1239e-8,.001946,7416e-7,2202e-8,.003486,.001368,39e-6,.006450001,.002236,64e-6,.01054999,.004243,12e-5,.02005001,.00765,217e-6,.03621,.01431,396e-6,.06785001,.02319,64e-5,.1102,.04351,.00121,.2074,.07763,.00218,.3713,.13438,.004,.6456,.21477,.0073,1.0390501,.2839,.0116,1.3856,.3285,.01684,1.62296,.34828,.023,1.74706,.34806,.0298,1.7826,.3362,.038,1.77211,.3187,.048,1.7441,.2908,.06,1.6692,.2511,.0739,1.5281,.19536,.09098,1.28764,.1421,.1126,1.0419,.09564,.13902,.8129501,.05795001,.1693,.6162,.03201,.20802,.46518,.0147,.2586,.3533,.0049,.323,.272,.0024,.4073,.2123,.0093,.503,.1582,.0291,.6082,.1117,.06327,.71,.07824999,.1096,.7932,.05725001,.1655,.862,.04216,.2257499,.9148501,.02984,.2904,.954,.0203,.3597,.9803,.0134,.4334499,.9949501,.008749999,.5120501,1,.005749999,.5945,.995,.0039,.6784,.9786,.002749999,.7621,.952,.0021,.8425,.9154,.0018,.9163,.87,.001650001,.9786,.8163,.0014,1.0263,.757,.0011,1.0567,.6949,.001,1.0622,.631,8e-4,1.0456,.5668,6e-4,1.0026,.503,34e-5,.9384,.4412,24e-5,.8544499,.381,19e-5,.7514,.321,1e-4,.6424,.265,4999999e-11,.5419,.217,3e-5,.4479,.175,2e-5,.3608,.1382,1e-5,.2835,.107,0,.2187,.0816,0,.1649,.061,0,.1212,.04458,0,.0874,.032,0,.0636,.0232,0,.04677,.017,0,.0329,.01192,0,.0227,.00821,0,.01584,.005723,0,.01135916,.004102,0,.008110916,.002929,0,.005790346,.002091,0,.004109457,.001484,0,.002899327,.001047,0,.00204919,74e-5,0,.001439971,52e-5,0,.0009999493,3611e-7,0,.0006900786,2492e-7,0,.0004760213,1719e-7,0,.0003323011,12e-5,0,.0002348261,848e-7,0,.0001661505,6e-5,0,117413e-9,424e-7,0,8307527e-11,3e-5,0,5870652e-11,212e-7,0,4150994e-11,1499e-8,0,2935326e-11,106e-7,0,2067383e-11,74657e-10,0,1455977e-11,52578e-10,0,1025398e-11,37029e-10,0,7221456e-12,26078e-10,0,5085868e-12,18366e-10,0,3581652e-12,12934e-10,0,2522525e-12,9.1093e-7,0,1776509e-12,6.4153e-7,0,1251141e-12,4.5181e-7,0],Eo=[3.2406,-1.5372,-.4986,-.9689,1.8758,.0415,.0557,-.204,1.057],Do=0xe90f62a5dcb760000;function Oo(e){let t=(e/1e3)**2;return .002152*(1.0455996-341.29061/t-.9023085*t)/(1+.0027059889/t-85.968563*t)}function ko(e,t,n,r,i=1,a=0){let o=e.length/i,s=(r-t)/n;if(s<=0)return e[a];if(s>=o-1)return e[(o-1)*i+a];let c=Math.floor(s),l=s-c;return e[c*i+a]*(1-l)+e[(c+1)*i+a]*l}function Ao(e,t){let n=0,r=bo+e*xo;for(let e=0;e<xo;e++)n+=t(r+e+.5);return n/xo}function jo(e){let t=new Float64Array(16);for(let n=0;n<16;n++)t[n]=Ao(n,e);return t}var Mo=Float64Array.from({length:16},(e,t)=>bo+(t+.5)*xo),No=jo(e=>ko(Co,360,10,e)),Po=jo(e=>Oo(e)/8),Fo=jo(e=>ko(wo,360,10,e)),Io=jo(e=>(e/1e3)**-yo),Lo=(()=>{let e=new Float64Array(48);for(let t=0;t<16;t++)for(let n=0;n<3;n++)e[t*3+n]=Ao(t,e=>ko(To,360,5,e,3,n))*xo;return e})();function Ro(e=1){let t=new Float32Array(48);for(let n=0;n<16;n++){let r=Lo[n*3],i=Lo[n*3+1],a=Lo[n*3+2];for(let o=0;o<3;o++){let s=Eo;t[o*16+n]=(s[o*3]*r+s[o*3+1]*i+s[o*3+2]*a)*e}}return t}function zo(e){let t=0,n=0,r=0;for(let i=0;i<16;i++)t+=e[i]*Lo[i*3],n+=e[i]*Lo[i*3+1],r+=e[i]*Lo[i*3+2];return[t,n,r]}function Bo([e,t,n]){let r=Eo;return[r[0]*e+r[1]*t+r[2]*n,r[3]*e+r[4]*t+r[5]*n,r[6]*e+r[7]*t+r[8]*n]}function Vo(e){return Math.max(0,.0460836582205*e-.04586025928522)}function Ho([e,t,n]){let r=(e,t,n)=>{let r=Math.min(Math.max((n-e)/(t-e),0),1);return r*r*(3-2*r)};return Float64Array.from(Mo,i=>{let a=1-r(470,520,i),o=r(560,610,i);return n*a+e*o+t*(1-a-o)})}function Uo({airDensity:e=1,turbidity:t=2,ozone:n=300,groundAlbedo:r=[.3,.3,.3]}={}){let i=Vo(t)/go,a=n*Do/(15*1e3)*1e3,o=new Float64Array(16),s=new Float64Array(16),c=new Float64Array(16),l=new Float64Array(16);for(let t=0;t<16;t++)o[t]=Po[t]*e,s[t]=Io[t]*i,c[t]=s[t]*_o,l[t]=Fo[t]*a;return{rayleigh:o,mieScattering:c,mieExtinction:s,ozone:l,albedo:Ho(r)}}var Wo=e=>Math.exp(-e/8),Go=e=>Math.exp(-e/go),Ko=e=>Math.max(0,1-Math.abs(e-25)/15);function qo(e){let t=Math.max(e,0);return Math.sqrt(t*(2*mo+t))/(mo+t)}function Jo(e,t,n=1024){let r=Math.max(e,0),i=mo+r,a=i*t,o=r*(2*mo+r);if(t<0&&a*a>=o)return null;let s=-a+Math.sqrt(a*a+(ho-i)*(ho+i)),c=0,l=0,u=0;for(let e=0;e<n;e++){let t=s*(e/n)**2,r=s*((e+1)/n)**2,d=.5*(t+r),f=(o+d*(d+2*a))/(Math.sqrt(i*i+d*(d+2*a))+mo),p=r-t;c+=Wo(f)*p,l+=Go(f)*p,u+=Ko(f)*p}return[c,l,u]}function Yo(e,t){let n=new Float64Array(16);if(!t)return n;let[r,i,a]=t;for(let t=0;t<16;t++)n[t]=Math.exp(-(e.rayleigh[t]*r+e.mieExtinction[t]*i+e.ozone[t]*a));return n}var Xo=[610,550,465].map(e=>-.023+.292/(e/1e3));function Zo(e){let t=Math.sin(e/2);return 4*Math.PI*t*t}function Qo({direction:e,altitude:t,angularDiameter:n,strength:r=1,coefficients:i}){let a=n/2,o=Zo(a),s=qo(t),[c,l,u]=e,d=Math.sin(a),f=new Float64Array(16),p=0,m=e=>{if(e<-s)return;let n=Yo(i,Jo(t,e,512));for(let e=0;e<16;e++)f[e]+=n[e];p++};if(l-d>.1)m(l);else{let e=Math.sqrt(Math.max(0,1-l*l));for(let t=0;t<48;t++){let n=(t+.5)/48,r=-1,i=1;for(let e=0;e<30;e++){let e=.5*(r+i);(Math.asin(e)+e*Math.sqrt(1-e*e)+Math.PI/2)/Math.PI<n?r=e:i=e}m(l+.5*(r+i)*d*e)}}let h=new Float64Array(16),g=l-d>.1?1:48;if(p>0)for(let e=0;e<16;e++)h[e]=No[e]*r/o*f[e]/p;return{radiance:Bo(zo(h)).map(e=>Math.max(0,e*So)),visibleFraction:p/g,solidAngle:o,direction:[c,l,u]}}var $o=e=>3/(16*Math.PI)*(1+e*e);function es(e,t=vo){let n=t*t;return 3/(8*Math.PI)*(1-n)/(2+n)*(1+e*e)/(1+n-2*t*e)**1.5}function ts(e,t,n,r,i=8){let a=n*r,o=e*t,s=new Float32Array(2*o*a);return[$o,e=>es(e)].forEach((c,l)=>{for(let u=0;u<o;u++){let d=-1+2*Math.floor(u/t)/(e-1),f=u%t*Math.PI/(t-1),p=Math.sqrt(Math.max(0,1-d*d)),m=(l*o+u)*a,h=0;for(let e=0;e<a;e++){let t=Math.floor(e/r),a=e%r,o=0;for(let e=0;e<i;e++){let s=-1+2*(t+(e+.5)/i)/n,l=Math.sqrt(Math.max(0,1-s*s));for(let e=0;e<i;e++){let t=Math.PI*(a+(e+.5)/i)/r;o+=c(d*s+p*l*Math.cos(f-t))+c(d*s+p*l*Math.cos(f+t))}}s[m+e]=o,h+=o}for(let e=0;e<a;e++)s[m+e]/=h}}),s}var ns=Math.sqrt(ho*ho-mo*mo),rs=ho-mo,is=Math.PI,as=[0,1,2,3],os=e=>as.map(e);function ss(e){return{r:(0,n.exp)(e.mul(-1/8)),m:(0,n.exp)(e.mul(-1/go)),o:(0,n.max)((0,n.float)(0),(0,n.float)(1).sub((0,n.abs)(e.sub(25)).div(15)))}}function cs(e,t){return os(n=>e.rayleigh[n].mul(t.r).add(e.mieExtinction[n].mul(t.m)).add(e.ozone[n].mul(t.o)))}function ls(e,t){return os(r=>{let i=e[r].mul(t),a=(0,n.exp)(i.negate()),o=(0,n.float)(1).sub(a).div((0,n.max)(i,1e-12));return{weight:(0,n.mix)((0,n.float)(1).sub(i.mul(.5)),o,(0,n.step)(.001,i)).mul(t),transmittance:a}})}function us(e,t,r,i,a,o=1,s=0){let c=(0,n.clamp)(i,0,t-1),l=(0,n.clamp)(a,0,r-1),u=(0,n.floor)(c),d=(0,n.floor)(l),f=c.sub(u),p=l.sub(d),m=(0,n.uint)(u),h=(0,n.uint)(d),g=(0,n.min)(m.add(1),(0,n.uint)(t-1)),_=(0,n.min)(h.add(1),(0,n.uint)(r-1)),v=(n,r)=>e.element(r.mul(t).add(n).mul(o).add(s));return(0,n.mix)((0,n.mix)(v(m,h),v(g,h),f),(0,n.mix)(v(m,_),v(g,_),f),p)}function ds(e,t){let r=e.add(mo),i=(0,n.sqrt)((0,n.max)(e.mul(e.add(2*mo)),0)),a=r.mul(t),o=a.negate().add((0,n.sqrt)((0,n.max)(a.mul(a).add(ns*ns).sub(i.mul(i)),0))),s=(0,n.float)(rs).sub(e),c=i.add(ns);return{x:o.sub(s).div((0,n.max)(c.sub(s),1e-6)).mul(255),y:i.div(ns).mul(63),rho:i,r}}function fs(e,t,r,i,a){let o=ds(r,i),s=us(e,256,64,o.x,o.y).xyz,c=(0,n.smoothstep)(a.negate(),a,i.add(o.rho.div(o.r)));return os(e=>(0,n.exp)(t.rayleigh[e].mul(s.x).add(t.mieExtinction[e].mul(s.y)).add(t.ozone[e].mul(s.z)).negate()).mul(c))}var ps=e=>(0,n.float)(e).div(15).pow(2).mul(rs),ms=e=>(0,n.sqrt)((0,n.clamp)(e.div(rs),0,1)).mul(15),hs=-3*is/180,gs=15*is/180,_s=.5+Math.atan((-is/2-hs)/gs)/is,vs=.5+Math.atan((is/2-hs)/gs)/is,ys=(e,t)=>(0,n.sin)((0,n.clamp)((0,n.tan)((0,n.float)(e).div(t-1).mul(vs-_s).add(_s-.5).mul(is)).mul(gs).add(hs),-is/2,is/2)),bs=(e,t)=>(0,n.atan)((0,n.asin)((0,n.clamp)(e,-1,1)).sub(hs).div(gs)).div(is).add(.5-_s).div(vs-_s).mul(t-1),xs=1e-30,Ss=e=>(0,n.log)((0,n.max)(e,(0,n.vec4)(xs)));function Cs(e,t,r,i,a){let o=[[(0,n.clamp)(bs(r,64),0,63),64],[(0,n.clamp)(ms(t),0,15),16],[(0,n.clamp)(i.add(1).mul(.5*15),0,15),16],[(0,n.clamp)((0,n.acos)((0,n.clamp)(a,-1,1)).mul(7/is),0,7),8]].map(([e,t])=>{let r=(0,n.floor)(e),i=e.sub(r).toVar(),a=(0,n.uint)(r).toVar();return{t:i,i0:a,i1:(0,n.min)(a.add(1),(0,n.uint)(t-1)).toVar()}}),s=[128,8192,8,1],c=[];for(let e=0;e<16;e++){let t=(0,n.uint)(0);o.forEach((n,r)=>{t=t.add((e>>r&1?n.i1:n.i0).mul(s[r]))}),c.push(t.mul(8).toVar())}return Array.from({length:8},(t,r)=>{let i=c.map(t=>e.element(t.add(r)));for(let e=0;e<4;e++){let t=[];for(let r=0;r<i.length;r+=2)t.push((0,n.mix)(i[r],i[r+1],o[e].t));i=t}return(0,n.exp)(i[0])})}function ws(e,t){let r=bs(t,128);return os(t=>(0,n.exp)(us(e,128,1,r,(0,n.float)(0),4,t)))}function Ts(e,t){let r=e.add(mo).toVar(),i=r.mul(t).toVar(),a=e.mul(e.add(2*mo)).toVar(),o=i.mul(i).sub(a),s=t.lessThan(0).and(o.greaterThanEqual(0)).toVar(),c=a.div((0,n.max)(i.negate().add((0,n.sqrt)((0,n.max)(o,0))),1e-9)),l=i.negate().add((0,n.sqrt)((0,n.max)(i.mul(i).add((0,n.float)(ho).sub(r).mul(r.add(ho))),0)));return{r,b:i,cGround:a,hitsGround:s,tMax:s.select(c,l).toVar()}}var Es=(e,t,r)=>e.sub(t.mul(r)).div((0,n.max)((0,n.sqrt)((0,n.float)(1).sub(t.mul(t)).mul((0,n.float)(1).sub(r.mul(r)))),1e-4));function Ds(e,t,r,i){let a=t.mul(t.add(e.b.mul(2))),o=(0,n.sqrt)(e.r.mul(e.r).add(a));return{h:(0,n.max)(e.cGround.add(a).div(o.add(mo)),0),muS:(0,n.clamp)(e.r.mul(r).add(t.mul(i)).div(o),-1,1),mu:(0,n.clamp)(e.b.add(t).div(o),-1,1)}}var Os=e=>e.mul(e).add(1).mul(3/(16*is));function ks(e,t){let r=t*t,i=3/(8*is)*(1-r)/(2+r),a=(0,n.max)((0,n.float)(1+r).sub(e.mul(2*t)),1e-6);return e.mul(e).add(1).mul(i).div(a.mul((0,n.sqrt)(a)))}function As({transmittance:e},t=256){let r=256*64;return(0,n.Fn)(()=>{let i=n.instanceIndex;(0,n.If)(i.greaterThanEqual((0,n.uint)(r)),()=>{(0,n.Return)()});let a=(0,n.float)(i.mod(256)).div(255),o=(0,n.float)(i.div(256)).div(63).mul(ns).toVar(),s=(0,n.sqrt)(o.mul(o).add(mo*mo)).toVar(),c=(0,n.float)(ho).sub(s),l=o.add(ns),u=c.add(a.mul(l.sub(c))).toVar(),d=(0,n.clamp)((0,n.float)(ns*ns).sub(o.mul(o)).sub(u.mul(u)).div((0,n.max)(s.mul(u).mul(2),1e-9)),-1,1).toVar(),f=o.mul(o).toVar(),p=s.mul(d).mul(2).toVar(),m=(0,n.vec3)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(t),type:`int`,condition:`<`},({i:e})=>{let r=(0,n.float)(e).div(t),i=(0,n.float)(e).add(1).div(t),a=u.mul(r.mul(r)),o=u.mul(i.mul(i)),c=a.add(o).mul(.5),l=c.mul(c.add(p)),d=ss((0,n.max)(f.add(l).div((0,n.sqrt)(s.mul(s).add(l)).add(mo)),0));m.addAssign((0,n.vec3)(d.r,d.m,d.o).mul(o.sub(a)))}),e.element(i).assign((0,n.vec4)(m,0))})().compute(r,[64])}var js=4*is/128;function Ms(e,t,r,i){let a=(0,n.float)(e).add((0,n.float)(r.div(i)).add(.5).div(i)).div(16).mul(2).sub(1),o=(0,n.sqrt)((0,n.max)((0,n.float)(1).sub(a.mul(a)),0)),s=(0,n.float)(t).add((0,n.float)(r.mod(i)).add(.5).div(i)).mul(is/8);return(0,n.vec3)(o.mul((0,n.cos)(s)),a,o.mul((0,n.sin)(s)))}function Ns(e,t){let r=bs(t,64);return os(t=>us(e,64,1,r,(0,n.float)(0),4,t))}function Ps(e,{first:t,out:r,cellSamples:i=2,steps:a=20}){let{transmittance:o,transfer:s,multipleScattering:c,groundE:l,coefficients:u,sunSinRadius:d,mieG:f}=e,p=1024*128,m=i*i;return(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(p)),()=>{(0,n.Return)()});let h=e.mod(128),g=e.div(128),_=ys(g.mod(64),64).toVar(),v=(0,n.max)(ps(g.div(64)),.001).toVar(),y=(0,n.vec3)((0,n.sqrt)((0,n.max)((0,n.float)(1).sub(_.mul(_)),0)),_,0).toVar(),b=os(()=>(0,n.vec4)(0).toVar()),x=t?os(()=>(0,n.vec4)(0).toVar()):null;(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(m),type:`int`,condition:`<`,name:`ray`},({ray:e})=>{let r=Ms(h.div(8),h.mod(8),e,i).toVar(),s=(0,n.dot)(r,y).toVar(),p=t?Os(s).toVar():null,m=t?ks(s,f).toVar():null,g=t?null:Array.from({length:8},()=>(0,n.vec4)(0).toVar()),S=Ts(v,r.y),C=os(()=>(0,n.vec4)(1).toVar());(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(a),type:`int`,condition:`<`},({i:e})=>{let r=(0,n.float)(e).div(a),i=(0,n.float)(e).add(1).div(a),l=S.tMax.mul(r.mul(r)),f=S.tMax.mul(i.mul(i)).sub(l),h=Ds(S,l.add(f.mul(.5)),_,s),v=ss(h.h),y=os(e=>u.rayleigh[e].mul(v.r)),w=os(e=>u.mieScattering[e].mul(v.m)),T=ls(cs(u,v),f),E;if(t){let e=fs(o,u,h.h,h.muS,d);E=os(t=>e[t].mul(y[t].mul(p).add(w[t].mul(m))))}else (0,n.If)(e.mod(2).equal(0),()=>{let e=Cs(c,h.h,h.muS,h.mu,Es(s,h.mu,h.muS));for(let t=0;t<8;t++)g[t].assign(e[t])}),E=os(e=>y[e].mul(g[e]).add(w[e].mul(g[4+e])));for(let e of as)b[e].addAssign(C[e].mul(E[e]).mul(T[e].weight)),x&&x[e].addAssign(C[e].mul(y[e].add(w[e])).mul(T[e].weight)),C[e].mulAssign(T[e].transmittance)}),(0,n.If)(S.hitsGround,()=>{let e=(0,n.clamp)(S.r.mul(_).add(S.tMax.mul(s)).div(mo),-1,1),r;if(t){let t=fs(o,u,(0,n.float)(0),e,d);r=os(r=>t[r].mul((0,n.max)(e,0)))}else r=Ns(l,e);for(let e of as)b[e].addAssign(C[e].mul(r[e]).mul(u.albedo[e]).mul(1/is))})});for(let t of as)r.element(e.mul(4).add(t)).assign(b[t].div(m)),x&&s.element(e.mul(4).add(t)).assign(x[t].div(m))})().compute(p,[64])}function Fs(e,{incoming:t,stage:r}){let{transfer:i,phaseCells:a,multipleScattering:o,psiSum:s,groundE:c}=e,l=1024*128,u=r===`last`;return(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(l)),()=>{(0,n.Return)()});let d=e.mod(128),f=e.div(128),p=f.mul(128),m=null;if(u){let e=os(()=>(0,n.vec4)(0).toVar());(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(128),type:`int`,condition:`<`},({i:t})=>{for(let r of as)e[r].addAssign(i.element(p.add((0,n.uint)(t)).mul(4).add(r)))}),m=os(t=>{let r=(0,n.min)(e[t].div(128),.95);return r.div((0,n.float)(1).sub(r)).toVar()})}for(let i=0;i<2;i++){let c=os(()=>(0,n.vec4)(0).toVar());(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(32),type:`int`,condition:`<`},({i:e})=>{let r=a.element((0,n.uint)(i*128).add(d).mul(32).add((0,n.uint)(e))).toVar();for(let i=0;i<4;i++){let a=p.add((0,n.uint)(e).mul(4).add(i)).mul(4),o=r.element((0,n.int)(i));for(let e of as)c[e].addAssign(t.element(a.add(e)).mul(o))}});for(let t of as){let n=e.mul(8).add(i*4+t);r===`first`?(s.element(n).assign(c[t]),o.element(n).assign(Ss(c[t]))):r===`middle`?(s.element(n).addAssign(c[t]),o.element(n).assign(Ss(c[t]))):o.element(n).assign(Ss(s.element(n).add(c[t].mul(m[t].add(1)))))}}u||(0,n.If)(f.lessThan((0,n.uint)(64)).and(d.equal((0,n.uint)(0))),()=>{let e=os(()=>(0,n.vec4)(0).toVar());(0,n.Loop)({start:(0,n.int)(128/2),end:(0,n.int)(128),type:`int`,condition:`<`},({i:r})=>{let i=(0,n.float)((0,n.uint)(r).div(8)).add(.5).div(16).mul(2).sub(1);for(let a of as)e[a].addAssign(t.element(p.add((0,n.uint)(r)).mul(4).add(a)).mul(i))});for(let t of as)c.element(f.mul(4).add(t)).assign(e[t].mul(js))})})().compute(l,[64])}var Is=4;function Ls({transmittance:e,multipleScattering:t,coefficients:r,sunSinRadius:i,mieG:a},o,s,c,l){let u=os(()=>(0,n.vec4)(0).toVar()),d=os(()=>(0,n.vec4)(1).toVar()),f=t?Array.from({length:8},()=>(0,n.vec4)(0).toVar()):null,p=Os(c).toVar(),m=ks(c,a).toVar(),h=o.tMax;return(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(l),type:`int`,condition:`<`},({i:a})=>{let g=(0,n.float)(a).div(l),_=(0,n.float)(a).add(1).div(l),v=h.mul(g.mul(g)),y=h.mul(_.mul(_)).sub(v),b=Ds(o,v.add(y.mul(.5)),s,c),x=ss(b.h),S=os(e=>r.rayleigh[e].mul(x.r)),C=os(e=>r.mieScattering[e].mul(x.m)),w=fs(e,r,b.h,b.muS,i),T=ls(cs(r,x),y);f&&(0,n.If)(a.mod(Is).equal(0),()=>{let e=Cs(t,b.h,b.muS,b.mu,Es(c,b.mu,b.muS));for(let t=0;t<8;t++)f[t].assign(e[t])});for(let e of as){let t=w[e].mul(S[e].mul(p).add(C[e].mul(m)));f&&(t=t.add(S[e].mul(f[e])).add(C[e].mul(f[4+e]))),u[e].addAssign(d[e].mul(t).mul(T[e].weight)),d[e].mulAssign(T[e].transmittance)}}),{L:u,throughput:d}}function Rs(e,{sqrtDirections:t=12,steps:r=32}={}){let{irradiance:i}=e,a=t*t,o=(0,n.float)(.001);return(0,n.Fn)(()=>{let s=n.instanceIndex;(0,n.If)(s.greaterThanEqual((0,n.uint)(128)),()=>{(0,n.Return)()});let c=ys(s,128).toVar(),l=(0,n.vec3)((0,n.sqrt)((0,n.max)((0,n.float)(1).sub(c.mul(c)),0)),c,0).toVar(),u=os(()=>(0,n.vec4)(0).toVar());(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(a),type:`int`,condition:`<`,name:`dirIndex`},({dirIndex:i})=>{let a=(0,n.float)(i.div(t)).add(.5).div(t),s=(0,n.float)(i.mod(t)).add(.5).div(t),d=(0,n.sqrt)(a),f=s.mul(2*is),p=(0,n.vec3)(d.mul((0,n.cos)(f)),(0,n.sqrt)((0,n.max)((0,n.float)(1).sub(a),0)),d.mul((0,n.sin)(f))).toVar(),{L:m}=Ls(e,Ts(o,p.y),c,(0,n.dot)(p,l),r);for(let e of as)u[e].addAssign(m[e])});for(let e of as)i.element(s.mul(4).add(e)).assign(Ss(u[e].mul(is/a)))})().compute(128,[64])}var zs=e=>(0,n.float)(e).div(255).pow(2).mul(is);function Bs(e,{width:t,height:r,steps:i=40,multipleScattering:a=!0}){let{sky:o,skyRows:s,irradiance:c,coefficients:l,rgb:u,sunDirection:d,altitude:f,sunSinRadius:p,transmittance:m}=e,h=a?e:{...e,multipleScattering:null},g=256*r;return[(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(g)),()=>{(0,n.Return)()});let t=(0,n.float)(1).sub((0,n.float)(e.div(256)).add(.5).div(r)).mul(is),a=(0,n.cos)(t).toVar(),o=(0,n.max)(f,.001).toVar(),_=d.y.toVar(),v=(0,n.sin)(t).mul((0,n.cos)(zs(e.mod(256)))).mul((0,n.sqrt)((0,n.max)((0,n.float)(1).sub(_.mul(_)),0))).add(a.mul(_)).toVar(),y=Ts(o,a),{L:b,throughput:x}=Ls(h,y,_,v,i);(0,n.If)(y.hitsGround,()=>{let e=(0,n.clamp)(y.r.mul(_).add(y.tMax.mul(v)).div(mo),-1,1).toVar(),t=fs(m,l,(0,n.float)(0),e,p),r=ws(c,e);for(let i of as)b[i].addAssign(x[i].mul(l.albedo[i]).mul(1/is).mul(t[i].mul((0,n.max)(e,0)).add(r[i])))});let S=os(e=>b[e].mul(l.solar[e])),C=e=>S.reduce((t,r,i)=>t.add((0,n.dot)(r,u[e*4+i])),(0,n.float)(0));s.element(e).assign((0,n.vec4)((0,n.max)((0,n.vec3)(C(0),C(1),C(2)),(0,n.vec3)(0)),1))})().compute(g,[64]),(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(t*r)),()=>{(0,n.Return)()});let i=(0,n.float)(e.mod(t)).add(.5).div(t).sub(.5).mul(2*is).sub((0,n.atan)(d.z,d.x)),a=(0,n.sqrt)((0,n.abs)((0,n.atan)((0,n.sin)(i),(0,n.cos)(i))).div(is)).mul(255).toVar(),c=(0,n.min)((0,n.floor)(a),254).toVar(),l=e.div(t).mul(256).add((0,n.uint)(c)).toVar();o.element(e).assign((0,n.mix)(s.element(l),s.element(l.add(1)),a.sub(c)))})().compute(t*r,[64])]}var Vs=e=>Math.ceil((e+1)*4/256)*64;function Hs(e,t,r){let i=(0,n.int)(0).toVar(),a=(0,n.int)(e-1).toVar();return(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(Math.ceil(Math.log2(e))+1),type:`int`,condition:`<`,name:`step`},()=>{(0,n.If)(i.lessThan(a),()=>{let e=i.add(a).div(2).toVar();(0,n.If)(t(e).lessThan(r),()=>{i.assign(e.add(1))}).Else(()=>{a.assign(e)})})}),i}function Us({pixels:e,rows:t,prefix:r,stats:i,cdf:a,width:o,height:s}){let c=Vs(o),l=e=>(0,n.sin)((0,n.float)(e).add(.5).mul(Math.PI/s)),u=(t,r,i)=>(0,n.dot)(e.element(t.mul(o).add(r)).xyz,zi).mul(i),d=()=>(0,n.If)(n.instanceIndex.greaterThan((0,n.uint)(0)),()=>{(0,n.Return)()});return[(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(s)),()=>{(0,n.Return)()});let r=l(e).toVar(),i=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(o),type:`int`,condition:`<`},({i:t})=>{i.addAssign(u(e,(0,n.uint)(t),r))}),t.element(e).assign((0,n.vec4)(i,0,0,0))})().compute(s,[64]),(0,n.Fn)(()=>{d();let e=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(s),type:`int`,condition:`<`},({i:n})=>{e.addAssign(t.element(n).x)}),i.element(0).assign((0,n.vec4)(e,e.div(o*s),0,0))})().compute(1,[1]),(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(s)),()=>{(0,n.Return)()});let a=l(e).toVar(),c=i.element(0).y.toVar(),d=(0,n.float)(0).toVar(),f=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(o),type:`int`,condition:`<`},({i:t})=>{let i=u(e,(0,n.uint)(t),a).toVar();d.addAssign(i),f.addAssign((0,n.max)(i.sub(c),0)),r.element(e.mul(o).add((0,n.uint)(t))).assign((0,n.vec2)(d,f))}),t.element(e).assign((0,n.vec4)(d,f,0,0))})().compute(s,[64]),(0,n.Fn)(()=>{d();let e=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(s),type:`int`,condition:`<`},({i:n})=>{e.addAssign(t.element(n).y)});let r=e.greaterThan(0).toVar(),l=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(s),type:`int`,condition:`<`},({i:e})=>{let i=t.element(e).toVar();l.addAssign((0,n.select)(r,i.y,i.x)),t.element(e).assign((0,n.vec4)(i.x,i.y,l,0))});let u=i.element(0).toVar();i.element(1).assign((0,n.select)(r,(0,n.vec4)(e,u.y,1,0),(0,n.vec4)(u.x,0,0,0))),(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(s),type:`int`,condition:`<`,name:`row`},({row:e})=>{let r=(0,n.select)(l.greaterThan(0),(0,n.float)(Hs(s,e=>t.element(e).z,(0,n.float)(e).add(1).div(s).mul(l))),(0,n.float)(s-1));a.element((0,n.uint)(e).mul(c).add(o)).assign(r.add(.5).div(s))})})().compute(1,[1]),(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(o*s)),()=>{(0,n.Return)()});let l=e.mod(o),u=e.div(o),d=i.element(1).z.greaterThan(0).toVar(),f=t.element(u).toVar(),p=(0,n.select)(d,f.y,f.x).toVar(),m=u.mul(o).toVar(),h=Hs(o,e=>{let t=r.element(m.add((0,n.uint)(e)));return(0,n.select)(d,t.y,t.x)},(0,n.float)(l).add(1).div(o).mul(p)),g=(0,n.select)(p.greaterThan(0),(0,n.float)(h),(0,n.float)(o-1));a.element(u.mul(c).add(l)).assign(g.add(.5).div(o))})().compute(o*s,[64])]}function Ws(e,t,n){let i=new r.DataTexture(null,e,t,n,r.FloatType);return i.source.dataReady=!1,i.needsUpdate=!0,i._isPhysicalSky=!0,i}var Gs=class{constructor(e=1024,t=512,n={}){this.width=e,this.height=t,this._quality=n,this.lastRenderTime=0,this._texture=Ws(e,t,r.RGBAFormat),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,this._cdfTexture=Ws(e+1,t,r.RedFormat),this._rec709Weights=Ro(So),this._attrs=null,this._kernels=null,this._airKey=null,this._transmittanceBuilt=!1}_init(){let e=e=>Array.from({length:e},()=>(0,n.uniform)(new r.Vector4)),i=e(24);this._uniforms={coefficient:i,rgb:e(12),sunDirection:(0,n.uniform)(new r.Vector3(0,1,0)),altitude:(0,n.uniform)(.05),sunSinRadius:(0,n.uniform)(.0046)};let a=e=>S(e,4);this._attrs={transmittance:a(256*64),incomingA:a(1024*128*4),incomingB:a(1024*128*4),transfer:a(1024*128*4),multipleScattering:a(1024*128*8),psiSum:a(1024*128*8),groundE:a(256),irradiance:a(512),sky:a(this.width*this.height),skyRows:a(256*this.height),cdfRows:a(this.height),cdfPrefix:S(this.width*this.height,2),cdfStats:a(2),cdf:S(Vs(this.width)*this.height,1),phaseCells:new t.StorageInstancedBufferAttribute(ts(16,8,16,8),4)};let o=(e,t=`vec4`)=>(0,n.storage)(this._attrs[e],t,this._attrs[e].count),s=e=>i.slice(e*4,e*4+4),c={transmittance:o(`transmittance`),transfer:o(`transfer`),psiSum:o(`psiSum`),groundE:o(`groundE`),phaseCells:o(`phaseCells`),multipleScattering:o(`multipleScattering`),irradiance:o(`irradiance`),sky:o(`sky`),skyRows:o(`skyRows`),coefficients:{rayleigh:s(0),mieScattering:s(1),mieExtinction:s(2),ozone:s(3),solar:s(4),albedo:s(5)},rgb:this._uniforms.rgb,sunDirection:this._uniforms.sunDirection,altitude:this._uniforms.altitude,sunSinRadius:this._uniforms.sunSinRadius,mieG:vo},l=this._quality,u=o(`incomingA`),d=o(`incomingB`);this._kernels={transmittance:As(c),air:[Ps(c,{first:!0,out:u,...l.incoming}),Fs(c,{incoming:u,stage:`first`}),Ps(c,{first:!1,out:d,...l.incoming}),Fs(c,{incoming:d,stage:`middle`}),Ps(c,{first:!1,out:u,...l.incoming}),Fs(c,{incoming:u,stage:`last`}),Rs(c,l.irradiance)],sky:Bs(c,{width:this.width,height:this.height,...l.sky}),cdf:Us({pixels:c.sky,rows:o(`cdfRows`),prefix:o(`cdfPrefix`,`vec2`),stats:o(`cdfStats`),cdf:o(`cdf`,`float`),width:this.width,height:this.height})},this._setSpectrum(4,No)}_setColorWeights(){let e=this._rec709Weights,t=zr(),n=[0,0,0,0];for(let r=0;r<3;r++)for(let i=0;i<4;i++){for(let a=0;a<4;a++){let o=i*4+a;n[a]=t?t[r*3]*e[o]+t[r*3+1]*e[16+o]+t[r*3+2]*e[32+o]:e[r*16+o]}this._uniforms.rgb[r*4+i].value.fromArray(n)}}_copyToTextures(e){let t=e.backend;e.initTexture(this._texture),e.initTexture(this._cdfTexture);let n=t.device.createCommandEncoder({label:`PhysicalSky`});n.copyBufferToTexture({buffer:t.get(this._attrs.sky).buffer,bytesPerRow:this.width*16,rowsPerImage:this.height},{texture:t.get(this._texture).texture},[this.width,this.height]),n.copyBufferToTexture({buffer:t.get(this._attrs.cdf).buffer,bytesPerRow:Vs(this.width)*4,rowsPerImage:this.height},{texture:t.get(this._cdfTexture).texture},[this.width+1,this.height]),t.device.queue.submit([n.finish()])}_setSpectrum(e,t){for(let n=0;n<4;n++)this._uniforms.coefficient[e*4+n].value.set(t[n*4],t[n*4+1],t[n*4+2],t[n*4+3])}bake(e,t){let n=performance.now();this._kernels||this._init();let r={airDensity:t.airDensity,turbidity:t.turbidity,ozone:t.ozone,groundAlbedo:[...t.groundAlbedo]},i=Uo(r),a=Math.max(t.altitude,1)/1e3,o=t.sunAngularDiameter/2,s=this._uniforms;s.sunDirection.value.fromArray(t.sunDirection).normalize(),s.altitude.value=a,s.sunSinRadius.value=Math.sin(o),this._setColorWeights();let c=[];this._transmittanceBuilt||=(c.push(this._kernels.transmittance),!0);let l=JSON.stringify([r,s.sunSinRadius.value]);l!==this._airKey&&(this._setSpectrum(0,i.rayleigh),this._setSpectrum(1,i.mieScattering),this._setSpectrum(2,i.mieExtinction),this._setSpectrum(3,i.ozone),this._setSpectrum(5,i.albedo),c.push(...this._kernels.air),this._airKey=l),c.push(...this._kernels.sky,...this._kernels.cdf),e.compute(c),this._copyToTextures(e);let u=e.getArrayBufferAsync(this._attrs.cdfStats).then(e=>{let t=new Float32Array(e);return{totalSum:t[4],compensationDelta:t[5]}}),d=Qo({direction:[s.sunDirection.value.x,s.sunDirection.value.y,s.sunDirection.value.z],altitude:a,angularDiameter:t.sunAngularDiameter,strength:t.sunStrength??1,coefficients:i});return d.cosHalfAngle=Math.cos(o),d.sinHalfAngle=Math.sin(o),d.horizonSin=qo(a),this.lastRenderTime=performance.now()-n,{texture:this._texture,cdfTexture:this._cdfTexture,sun:d,stats:u}}async readBack(e){let[t,n,r]=await Promise.all([`sky`,`cdf`,`cdfStats`].map(t=>e.getArrayBufferAsync(this._attrs[t])));return{pixels:new Float32Array(t),cdf:new Float32Array(n),cdfStride:Vs(this.width),stats:new Float32Array(r)}}getLastRenderTime(){return this.lastRenderTime}dispose(e=null){for(let e of Object.values(this._kernels??{}).flat())e.dispose();for(let t of Object.values(this._attrs??{}))Ca(e,t);this._kernels=null,this._attrs=null,this._texture.dispose(),this._cdfTexture.dispose()}},Ks=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()}};function qs(e){let t=String(e??``);return/(hdr|pq|hlg|2100|st2084)/i.test(t)?null:/^display\s*p3\b/i.test(t)?`display-p3`:/^(srgb|rec\.?\s*1886|bt\.?\s*1886|gamma\s*2\.2\s*rec\.?\s*709)\b(?!.*(p3|2020))/i.test(t)?`srgb`:null}function Js(e){if(e){Object.assign(Zs,e);for(let t of Object.keys(e))Qs.add(t)}}function Ys(e){return Qs.has(e)}function Xs(){return{...Zs}}var Zs,Qs,$s=y((()=>{Zs={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`},Qs=new Set}));$s(),jt();var ec=vt(`ocio`);function tc(e){let t=String(e);/\[OpenColorIO Error\]/.test(t)?ec.error(t):/\[OpenColorIO Warning\]/.test(t)?ec.warn(t):ec.debug(t)}var nc=null,rc=null,ic=null,ac=null,oc=null;async function sc(){let{ocioRuntimeFactory:e,ocioRuntimeUrl:t}=Xs();if(typeof e==`function`)return await e();if(typeof t==`string`&&t)return await import(t);throw Error(`OpenColorIO runtime not configured. Call configureAssets({ ocioRuntimeFactory: () => import('@bb-studio/ocio') }) before loading a config.`)}async function cc(){return rc||(nc||=(async()=>{let e=await sc();if(typeof e.createOcioRuntime!=`function`)throw Error(`OCIO module has no createOcioRuntime() — wrong package or version`);let{ocioWasmUrl:t}=Xs();return rc=await e.createOcioRuntime({...t?{wasmUrl:t}:{},moduleOptions:{print:tc,printErr:tc}}),rc})().catch(e=>{throw nc=null,e}),await nc)}async function lc(){return(await cc()).ocio.listBuiltinConfigs()}async function uc({builtin:e,text:t,files:n=[],configPath:r=`config.ocio`,id:i}={}){let a=await cc();if(e)ic=a.loadBuiltinConfig(e),ac=e,oc=gc(a,e);else{let e=n.map(e=>({relativePath:e.relativePath??e.path??e.name,data:e.data instanceof Uint8Array?e.data:new Uint8Array(e.data)}));if(t!==void 0&&e.unshift({relativePath:r,data:new TextEncoder().encode(t)}),!e.some(e=>e.relativePath===r))throw Error(`config package has no "${r}" — pass configPath to name the .ocio file`);ic=a.loadConfigPackage({configRelativePath:r,files:e},i?{id:i}:void 0),ac=i??ic.id;let o=e.find(e=>e.relativePath===r);oc=o?new TextDecoder().decode(o.data):null}return hc()}function dc(){ic=null,ac=null,oc=null}function fc(){return ic!==null}function pc(){return ic?rc:null}function mc(){return ic}function hc(){if(!ic)return null;let e=Object.fromEntries(ic.roles.map(e=>[e.name,e.colorSpace]));return{id:ac,name:oc?.match(/^name:\s*(\S.*?)\s*$/m)?.[1]??null,ocioVersion:ic.ocioVersion,version:ic.version,roles:e,sceneLinear:e.scene_linear??null,colorPicking:e.color_picking??e.texture_paint??null,texturePaint:e.texture_paint??e.color_picking??null,data:e.data??null,compositingLog:e.compositing_log??e.color_timing??null,colorSpaces:ic.colorSpaces.map(e=>({name:e.name,family:e.family,categories:e.categories??[],encoding:e.encoding,isData:e.isData,aliases:e.aliases,description:e.description})),displays:ic.displays.slice(),defaultDisplay:ic.defaultDisplay,views:Object.fromEntries(Object.entries(ic.viewsByDisplay).map(([e,t])=>[e,t.map(e=>({name:e.name,transform:e.transform,colorSpace:e.colorSpace,looks:e.looks,description:e.description}))])),defaultViews:{...ic.defaultViewsByDisplay},looks:ic.looks.map(e=>({name:e.name,processSpace:e.processSpace,description:e.description,forward:e.hasForwardTransform,inverse:e.hasInverseTransform})),namedTransforms:ic.namedTransforms.map(e=>e.name),fileRules:ic.fileRules.map(e=>({index:e.index,name:e.name,colorSpace:e.colorSpace,pattern:e.pattern,extension:e.extension,regex:e.regex})),contextVariables:_c()}}function gc(e,t){try{return e.ocio.getBuiltinConfigYaml(t)}catch{return null}}function _c(){if(!oc)return[];let e=new Map,t=oc.split(/\r?\n/),n=t.findIndex(e=>/^environment:\s*(\{\s*\})?\s*$/.test(e));if(n>=0&&!/\{\s*\}/.test(t[n]))for(let r=n+1;r<t.length;r++){let n=t[r];if(/^\S/.test(n))break;let i=n.match(/^\s+([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*?)\s*$/);i&&e.set(i[1],{name:i[1],default:i[2].replace(/^["']|["']$/g,``)||null,declared:!0})}for(let t of oc.matchAll(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g))e.has(t[1])||e.set(t[1],{name:t[1],default:null,declared:!1});return[...e.values()].sort((e,t)=>e.name.localeCompare(t.name))}function vc(){dc(),rc?.dispose?.(),rc=null,nc=null}var yc=1<<20,bc=new Map,xc=new Map,Sc=4096,Cc=new Map;function wc(e,t,n){return`${e}\u0000${t}\u0000${n?JSON.stringify(n):``}`}function Tc(){for(let e of bc.values())e.dispose?.();bc.clear(),xc.clear(),Cc.clear()}function Ec(e,t,{context:n=null}={}){if(!pc()||e===t)return null;let r=wc(e,t,n),i=bc.get(r);if(i!==void 0)return i;try{i=Ac().createColorSpaceProcessor(e,t,n?{context:n}:void 0),i.isNoOp&&(i.dispose(),i=null)}catch(n){throw Error(`no OCIO transform from "${e}" to "${t}": ${n.message}`)}return bc.set(r,i),i}var Dc=null,Oc=null,kc=!1;function Ac(){let e=pc();if(!e)throw Error(`no OCIO config loaded`);if(e.config)return e.config;let t=mc();if(Dc&&Oc===t.id)return Dc;if(kc&&Dc?.dispose?.(),!t.id?.startsWith(`ocio://`))throw Error(`OCIO runtime exposes no Config handle for this config`);return Dc=e.ocio.createBuiltinConfig(t.id),kc=!0,Oc=t.id,Dc}function jc(){kc&&Dc?.dispose?.(),Dc=null,Oc=null,kc=!1,Tc()}function Mc(e,t,n,{context:r=null}={}){let i=pc();if(!i||t===n)return[e[0],e[1],e[2]];let a=`${wc(t,n,r)}\u0000${e[0]},${e[1]},${e[2]}`,o=xc.get(a);if(o)return o.slice();let s=i.transformRgb(t,n,[e[0],e[1],e[2]],r?{context:r}:void 0);return xc.size>=Sc&&xc.clear(),xc.set(a,s),s.slice()}function Nc(e,t,n,{context:r=null}={}){if(e.length%4!=0)throw Error(`convertPixelsF32 wants 4 floats per pixel`);let i=Ec(t,n,{context:r});if(!i)return e;let a=e.length/4;if(a<=yc)return i.applyRGBAF32(e),e;for(let t=0;t<a;t+=yc){let n=Math.min(yc,a-t);i.applyRGBAF32(e.subarray(t*4,(t+n)*4))}return e}var Pc=.055;function Fc(e){return e<=.04045?e/12.92:((e+Pc)/(1+Pc))**2.4}function Ic(e){return e<=0?0:e<=.0031308?12.92*e:(1+Pc)*e**(1/2.4)-Pc}var Lc=new Float32Array(256);for(let e=0;e<256;e++)Lc[e]=Fc(e/255);var Rc=new Float32Array(256);for(let e=0;e<256;e++)Rc[e]=e/255;function zc(e){return e===`srgb`?Lc:Rc}function Bc(e,t,n,{context:r=null,inputEncoding:i=`raw`,outputEncoding:a=`srgb`}={}){if(e.length%4!=0)throw Error(`convertEncodedRGBA8 wants 4 bytes per pixel`);let o=Ec(t,n,{context:r});if(!o)return e;let s=e.length/4,c=zc(i),l=a===`srgb`?Uc:Wc,u=new Float32Array(Math.min(yc,s)*4);for(let t=0;t<s;t+=yc){let n=Math.min(yc,s-t),r=n*4===u.length?u:u.subarray(0,n*4);for(let i=0;i<n;i++){let n=(t+i)*4,a=i*4;r[a]=c[e[n]],r[a+1]=c[e[n+1]],r[a+2]=c[e[n+2]],r[a+3]=1}o.applyRGBAF32(r);for(let i=0;i<n;i++){let n=(t+i)*4,a=i*4;e[n]=l(r[a]),e[n+1]=l(r[a+1]),e[n+2]=l(r[a+2])}}return e}var Vc=65536,Hc=new Uint8Array(Vc+1);for(let e=0;e<=Vc;e++){let t=e/Vc;Hc[e]=Math.round(Ic(t*t)*255)}function Uc(e){return e>0?e>=1?255:Hc[Math.sqrt(e)*Vc+.5|0]:0}function Wc(e){return e>0?e>=1?255:e*255+.5|0:0}function Gc(e,t,n=`srgb`){if(!t)return e;let r=zc(n),i=n===`srgb`?Uc:Wc,[a,o,s,c,l,u,d,f,p]=t;for(let t=0;t<e.length;t+=4){let n=r[e[t]],m=r[e[t+1]],h=r[e[t+2]];e[t]=i(a*n+o*m+s*h),e[t+1]=i(c*n+l*m+u*h),e[t+2]=i(d*n+f*m+p*h)}return e}function Kc(e,t,{context:n=null,tolerance:r=1e-4}={}){if(!pc())return null;if(e===t)return[1,0,0,0,1,0,0,0,1];let i=wc(e,t,n);if(Cc.has(i))return Cc.get(i);let a=Ec(e,t,{context:n});if(!a)return Cc.set(i,[1,0,0,0,1,0,0,0,1]),Cc.get(i);let o=e=>{let t=new Float32Array([e[0],e[1],e[2],1]);return a.applyRGBAF32(t),[t[0],t[1],t[2]]},s=[o([1,0,0]),o([0,1,0]),o([0,0,1])],c=[s[0][0],s[1][0],s[2][0],s[0][1],s[1][1],s[2][1],s[0][2],s[1][2],s[2][2]],l=e=>[c[0]*e[0]+c[1]*e[1]+c[2]*e[2],c[3]*e[0]+c[4]*e[1]+c[5]*e[2],c[6]*e[0]+c[7]*e[1]+c[8]*e[2]],u=[[.18,.18,.18],[.5,.25,.75],[2,.1,.4],[.02,.9,.3],[8,4,1],[.001,.002,.004]],d=!0;for(let e of u){let t=o(e),n=l(e),i=Math.max(.001,Math.abs(n[0]),Math.abs(n[1]),Math.abs(n[2]));for(let e=0;e<3;e++)Math.abs(t[e]-n[e])>r*i&&(d=!1);if(!d)break}let f=d?c:null;return Cc.set(i,f),f}function qc(e){let t=mc();if(!t)return!1;let n=t.colorSpaces.find(t=>t.name===e||t.aliases?.includes(e));return n?n.isData:!1}function Jc(e){let t=mc();return!t||!e?!1:t.colorSpaces.some(t=>t.name===e||t.aliases?.includes(e))}function Yc(e,t,n,r,i){i[0]=nl(e),i[1]=nl(t),i[2]=nl(n)}function Xc(e,t,n,r,i){i[0]=nl(e*r),i[1]=nl(t*r),i[2]=nl(n*r)}function Zc(e,t,n,r,i){e*=r,t*=r,n*=r,i[0]=nl(e/(e+1)),i[1]=nl(t/(t+1)),i[2]=nl(n/(n+1))}function Qc(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 $c(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]=nl(1.60475*a-.53108*o-.07367*s),i[1]=nl(-.10208*a+1.10813*o-.00605*s),i[2]=nl(-.00327*a-.07276*o+1.07602*s)}function el(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=nl((Math.log2(Math.max(c,1e-10))-d)/f),l=nl((Math.log2(Math.max(l,1e-10))-d)/f),u=nl((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]=nl(1.6605*m-.5876*h-.0728*g),i[1]=nl(-.1246*m+1.1329*h-.0083*g),i[2]=nl(-.0182*m-.1006*h+1.1187*g)}function tl(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 nl,rl,il,al,ol,sl,cl,ll=y((()=>{nl=e=>Math.min(Math.max(e,0),1),rl=`
|
|
302
302
|
fn tm_reinhard( c: vec3<f32> ) -> vec3<f32> {
|
|
303
303
|
return clamp( c / ( c + vec3<f32>( 1.0 ) ), vec3<f32>( 0.0 ), vec3<f32>( 1.0 ) );
|
|
304
304
|
}
|
|
@@ -483,7 +483,7 @@ fn ${e}( c: vec3<f32> ) -> vec3<f32> {
|
|
|
483
483
|
return c000 + ( v1 - c000 ) * w.x + ( v2 - v1 ) * w.y + ( v3 - v2 ) * w.z;
|
|
484
484
|
}
|
|
485
485
|
`}function Ul({sampler:e,apply:t,count:n=4e3,seed:r=31337}){let i=r>>>0,a=()=>(i=i*1664525+1013904223>>>0)/4294967296,o=[];for(let e=0;e<n;e++){let e=.18*2**(-7+a()*13),t=a()**1.2,n=a()*6,r=[0,1,2].map(e=>1-t*Math.min(1,Math.abs((n+e*2)%6-3))),i=Math.max(...r)||1;o.push(r.map(t=>Math.max(t,0)/i*e))}let s=new Float32Array(o.length*4);o.forEach((e,t)=>{s[t*4]=e[0],s[t*4+1]=e[1],s[t*4+2]=e[2],s[t*4+3]=1}),t(s);let c=[0,0,0],l=[];for(let t=0;t<o.length;t++){e(o[t][0],o[t][1],o[t][2],c);for(let e=0;e<3;e++)l.push(Math.abs(c[e]-s[t*4+e])*255)}return l.sort((e,t)=>e-t),{mean:l.reduce((e,t)=>e+t,0)/l.length,p95:l[Math.floor(l.length*.95)],max:l[l.length-1],samples:l.length}}var Wl=-12.47393,Gl=12.5260688117,Kl=65,ql=null,Jl=new Map;function Yl(e){ql=e}function Xl(){let e=pc();if(!e)throw Error(`load an OCIO config first`);if(!e.config)throw Error(`OCIO runtime exposes no Config handle`);return e.config}function Zl({source:e,display:t,view:n,look:r,context:i}){let a=Xl(),o=i?{context:i}:void 0;return r?a.createGroupTransformProcessor([{type:`look`,source:e,destination:e,looks:r},{type:`displayView`,source:e,display:t,view:n}],o):a.createDisplayViewProcessor({source:e,display:t,view:n,...i?{context:i}:{}})}function Ql({texture:e,size:t,minEv:r,maxEv:i}){let a=t-1,o=i-r,s=t=>(0,n.texture3DLoad)(e,(0,n.clamp)(t,(0,n.ivec3)(0),(0,n.ivec3)(a))).rgb;return(0,n.Fn)(([e,i])=>{let c=(0,n.clamp)((0,n.log2)((0,n.max)((0,n.max)(e.mul(i),(0,n.vec3)(0)),(0,n.vec3)(1e-10))).sub((0,n.float)(r)).div((0,n.float)(o)),(0,n.vec3)(0),(0,n.vec3)(1)).mul((0,n.float)(a)).toVar(),l=(0,n.clamp)((0,n.ivec3)((0,n.floor)(c)),(0,n.ivec3)(0),(0,n.ivec3)(t-2)).toVar(),u=(0,n.clamp)(c.sub((0,n.vec3)(l)),(0,n.vec3)(0),(0,n.vec3)(1)).toVar(),d=(0,n.vec3)(0).toVar(),f=(0,n.ivec3)(0).toVar(),p=(0,n.ivec3)(0).toVar(),m=(0,n.ivec3)(1).toVar();(0,n.If)(u.x.greaterThan(u.y),()=>{(0,n.If)(u.y.greaterThan(u.z),()=>{d.assign((0,n.vec3)(u.x,u.y,u.z)),f.assign((0,n.ivec3)(1,0,0)),p.assign((0,n.ivec3)(1,1,0)),m.assign((0,n.ivec3)(1,1,1))}).ElseIf(u.x.greaterThan(u.z),()=>{d.assign((0,n.vec3)(u.x,u.z,u.y)),f.assign((0,n.ivec3)(1,0,0)),p.assign((0,n.ivec3)(1,0,1)),m.assign((0,n.ivec3)(1,1,1))}).Else(()=>{d.assign((0,n.vec3)(u.z,u.x,u.y)),f.assign((0,n.ivec3)(0,0,1)),p.assign((0,n.ivec3)(1,0,1)),m.assign((0,n.ivec3)(1,1,1))})}).Else(()=>{(0,n.If)(u.z.greaterThan(u.y),()=>{d.assign((0,n.vec3)(u.z,u.y,u.x)),f.assign((0,n.ivec3)(0,0,1)),p.assign((0,n.ivec3)(0,1,1)),m.assign((0,n.ivec3)(1,1,1))}).ElseIf(u.z.greaterThan(u.x),()=>{d.assign((0,n.vec3)(u.y,u.z,u.x)),f.assign((0,n.ivec3)(0,1,0)),p.assign((0,n.ivec3)(0,1,1)),m.assign((0,n.ivec3)(1,1,1))}).Else(()=>{d.assign((0,n.vec3)(u.y,u.x,u.z)),f.assign((0,n.ivec3)(0,1,0)),p.assign((0,n.ivec3)(1,1,0)),m.assign((0,n.ivec3)(1,1,1))})});let h=s(l).toVar(),g=s(l.add(f)).toVar(),_=s(l.add(p)).toVar(),v=s(l.add(m)).toVar();return h.add(g.sub(h).mul(d.x)).add(_.sub(g).mul(d.y)).add(v.sub(_).mul(d.z))})}function $l({display:e,view:t,look:n=null,context:r=null,source:i=null,size:a=65,minEv:o=Wl,maxEv:s=Gl,id:c=null,name:l=null}={}){let u=mc();if(!u)throw Error(`load an OCIO config first`);let d=u.roles.find(e=>e.name===`scene_linear`)?.colorSpace,f=i??d;if(!f)throw Error(`config has no scene_linear role — pass an explicit source space`);if(!u.displays.includes(e))throw Error(`config has no display "${e}" — has ${u.displays.join(`, `)}`);let p=(u.viewsByDisplay[e]??[]).map(e=>e.name);if(!p.includes(t))throw Error(`display "${e}" has no view "${t}" — has ${p.join(`, `)}`);if(n&&!u.looks.some(e=>e.name===n))throw Error(`config has no look "${n}" — has ${u.looks.map(e=>e.name).join(`, `)}`);qs(e)===null&&ql?.warn(Y.VIEW_TRANSFORM_DISPLAY_MISMATCH,`"${e}" is not an sRGB-class SDR display, which is all the canvas is configured for — its view will be shown clipped or in the wrong gamut on screen, though a saved buffer is right`,{display:e,view:t});let m=Zl({source:f,display:e,view:t,look:n,context:r}),h=e=>m.applyRGBAF32(e),g,_;try{g=Il(Fl({size:a,minEv:o,maxEv:s,apply:h})),_=Ul({sampler:Vl({data:g,size:a,minEv:o,maxEv:s}),apply:h})}finally{m.dispose()}return tu({id:c,half:g,error:_,name:l??(n?`${t} + ${n} (${e})`:`${t} (${e})`),ocio:{display:e,view:t,look:n,context:r,source:f,configId:u.id,size:a,minEv:o,maxEv:s}})}function eu(e,t=null){let{name:n,data:r,error:i,configId:a,display:o,view:s,look:c,context:l,source:u,size:d,minEv:f,maxEv:p,fingerprint:m,ocioVersion:h}=e;return tu({id:t,name:n,error:i,half:r,ocio:{display:o,view:s,look:c??null,context:l??null,source:u,configId:a,size:d,minEv:f,maxEv:p,baked:{fingerprint:m??null,ocioVersion:h??null}}})}function tu({id:e,name:t,half:n,error:i,ocio:a}){let{size:o,minEv:s,maxEv:c}=a,l=Vl({data:n,size:o,minEv:s,maxEv:c}),u=e??gl(),d=`TM_OCIO_${u}`,f=`tm_ocio_${u}`,p=Jl.get(u),m=p&&p.size===o&&p.minEv===s&&p.maxEv===c,h,g;return m?(h=p.texture,h.image.data=n,h.needsUpdate=!0,g=p.tsl):(p?.texture.dispose(),h=new r.Data3DTexture(n,o,o,o),h.format=r.RGBAFormat,h.type=r.HalfFloatType,h.minFilter=r.NearestFilter,h.magFilter=r.NearestFilter,h.wrapS=h.wrapT=h.wrapR=r.ClampToEdgeWrapping,h.needsUpdate=!0,g=Ql({texture:h,size:o,minEv:s,maxEv:c})),Jl.set(u,{texture:h,tsl:g,size:o,minEv:s,maxEv:c}),{id:u,name:t,wgslConst:d,source:`ocio`,outputEncoded:!0,appliesExposure:!0,cpu:(e,t,n,r,i)=>l(e*r,t*r,n*r,i),wgsl:Hl({fnName:f,texName:`${d.toLowerCase()}_tex`,size:o,minEv:s,maxEv:c}),call:`${f}( c )`,tsl:g,table:{data:n,size:o,texture:h},error:i,ocio:a}}function nu(e){return _l($l(e))}function ru({display:e=null,look:t=null,context:n=null,source:r=null,size:i=65}={}){let a=mc();if(!a)throw Error(`load an OCIO config first`);let o=e??a.defaultDisplay,s=a.viewsByDisplay[o]??[],c=[],l=[];for(let e of s){if(e.colorSpace&&e.colorSpace!==`<USE_DISPLAY_NAME>`&&a.colorSpaces.find(t=>t.name===e.colorSpace)?.isData){l.push({view:e.name,reason:`data view`});continue}try{c.push(nu({display:o,view:e.name,look:t,context:n,source:r,size:i}))}catch(t){l.push({view:e.name,reason:t.message}),ql?.warn(Y.VIEW_TRANSFORM_BAKE_FAILED,`could not bake "${e.name}" (${o}): ${t.message}`,{display:o,view:e.name})}}return{added:c,skipped:l}}function iu(e){let t=Jl.get(e);t&&(t.texture.dispose(),Jl.delete(e))}function au(e=null){for(let t of kl.values())t.source===`ocio`&&!e?.has(t.id)&&t.table?.texture?.dispose?.();for(let[t,n]of Jl)e?.has(t)||(n.texture.dispose(),Jl.delete(t))}var ou=[82,90,86,84],su=`rayzee-baked-view`,cu=15360;async function lu(e,t){return new Uint8Array(await new Response(new Blob([e]).stream().pipeThrough(t)).arrayBuffer())}async function uu(e,t={}){let n=e?.table?.data;if(e?.source!==`ocio`||!(n instanceof Uint16Array))throw Error(`only a baked OCIO view can be saved`);let{size:r,minEv:i,maxEv:a}=e.ocio,o=r*r*r;if(n.length!==o*4)throw Error(`table holds ${n.length} values, expected ${o*4}`);let s=new Uint8Array(o*6);for(let e=0;e<3;e++)for(let t=0;t<o;t++){if(e===0&&n[t*4+3]!==cu)throw Error(`table alpha is not 1`);let i=n[t*4+e]-(t%r?n[(t-1)*4+e]:0)&65535;s[e*o+t]=i>>8,s[3*o+e*o+t]=i&255}let{display:c,view:l,look:u,context:d,source:f,configId:p}=e.ocio,m=new TextEncoder().encode(JSON.stringify({format:su,version:1,name:e.name,configId:p,display:c,view:l,look:u??null,context:d??null,source:f,size:r,minEv:i,maxEv:a,error:e.error??null,...t})),h=new Uint8Array(8+m.length+s.length);return h.set(ou,0),new DataView(h.buffer).setUint32(4,m.length,!0),h.set(m,8),h.set(s,8+m.length),await lu(h,new CompressionStream(`gzip`))}async function du(e){let t=await lu(e,new DecompressionStream(`gzip`));if(t.length<8||ou.some((e,n)=>t[n]!==e))throw Error(`not a baked view file`);let n=new DataView(t.buffer,t.byteOffset).getUint32(4,!0),r=JSON.parse(new TextDecoder().decode(t.subarray(8,8+n)));if(r.format!==su||r.version!==1)throw Error(`unsupported baked view ${r.format} v${r.version}`);let{size:i,minEv:a,maxEv:o}=r;if(!Number.isInteger(i)||i<2||i>129||!(a<o))throw Error(`baked view has a bad table shape`);let s=i*i*i,c=t.subarray(8+n);if(c.length!==s*6)throw Error(`baked view holds ${c.length} bytes of table, expected ${s*6}`);let l=new Uint16Array(s*4);for(let e=0;e<3;e++){let t=0;for(let n=0;n<s;n++)n%i===0&&(t=0),t=t+(c[e*s+n]<<8|c[3*s+e*s+n])&65535,l[n*4+e]=t}for(let e=0;e<s;e++)l[e*4+3]=cu;return{...r,data:l}}async function fu({builtin:e,text:t,files:n=[],configPath:r=`config.ocio`}={}){if(e)return`builtin:${e}`;let i=globalThis.crypto?.subtle;if(!i)return null;let a=e=>Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``),o=async e=>a(await i.digest(`SHA-256`,e)),s=await Promise.all(n.map(async e=>`${e.relativePath??e.path??e.name}:${await o(e.data)}`));return t!==void 0&&s.push(`text:${await o(new TextEncoder().encode(t))}`),s.sort(),s.unshift(`config:${r}`),`sha256:${await o(new TextEncoder().encode(s.join(`
|
|
486
|
-
`)))}`}var pu=[],mu=0;function hu(){return mu}function gu(){mu++}function _u(e,t){pu.unshift({match:e,colorSpace:t}),mu++}function vu(){pu.length!==0&&(pu.length=0,mu++)}function yu(){return pu.map(e=>({match:String(e.match),colorSpace:e.colorSpace}))}function bu(e){if(!e)return null;for(let t of pu)if(t.match instanceof RegExp?t.match.test(e):e.includes(t.match))return t.colorSpace;return null}function xu(){return mc()?.fileRules.map(e=>({index:e.index,name:e.name,colorSpace:e.colorSpace,pattern:e.pattern,extension:e.extension,regex:e.regex}))??[]}function Su(e){let t=mc();if(!t)return null;let n=e=>t.roles.find(t=>t.name===e)?.colorSpace??null;return e===r.NoColorSpace?n(`data`):e===r.SRGBColorSpace?n(`texture_paint`)??n(`color_picking`)??t.colorSpaces.find(e=>/^srgb\b/i.test(e.name)&&!/display/i.test(e.name))?.name??null:e===r.LinearSRGBColorSpace?t.colorSpaces.find(e=>/^lin(ear)?[\s_-]*(rec\.?\s*)?709/i.test(e.name))?.name??t.colorSpaces.find(e=>/^linear.*srgb/i.test(e.name))?.name??n(`scene_linear`):null}function Cu(e,{threeColorSpace:t=null}={}){if(!mc())return null;let n=bu(e);if(n)return{colorSpace:n,via:`override`,rule:null};let r=pc();if(r&&e){let t=r.matchFileRule(e);if(t&&!t.isDefaultRule&&Jc(t.colorSpace))return{colorSpace:t.colorSpace,via:`rule`,rule:{index:t.ruleIndex,name:t.ruleName}}}let i=Su(t);if(i)return{colorSpace:i,via:`three`,rule:null};let a=pc();if(a&&e){let t=a.matchFileRule(e);if(t&&Jc(t.colorSpace))return{colorSpace:t.colorSpace,via:`rule`,rule:{index:t.ruleIndex,name:t.ruleName,isDefault:t.isDefaultRule}}}return null}function wu(e){if(!e)return!1;if(e.colorSpace===r.NoColorSpace)return!0;let t=e.userData?.ocioColorSpace;return!!(t&&qc(t))}function Tu(e,t){return t??e.userData?.sourcePath??(e.name||null)??e.image?.src??null}function Eu(e,t=null){if(!mc()||!e)return null;let n=e.userData?.ocioColorSpace;return n?Jc(n)?{colorSpace:n,via:`tag`,rule:null}:null:wu(e)?null:Cu(Tu(e,t),{threeColorSpace:e.colorSpace})}function Du(e,t=null){return Eu(e,t)?.colorSpace??null}jl();var Ou=`Linear Rec.709 (sRGB)`,ku=null;function Au(){return ku}function ju(e){ku=e,e?._publishWorkingMatrix?.()}function Mu(e){return qs(e)??`srgb`}var Nu=[`Linear Rec.709 (sRGB)`,`lin_rec709_srgb`,`lin_rec709`,`lin_srgb`,`Linear Rec.709`,`Utility - Linear - sRGB`,`Utility - Linear - Rec.709`,`Linear BT.709`,`linrec709`],Pu=/^(lin(ear)?[\s_-]*(rec\.?\s*|bt\.?\s*)?709|linear[\s_-]*\(?srgb\)?$|utility - linear - (srgb|rec\.?709))/i;function Fu(e){if(!e)return null;let t=e.colorSpaces.filter(e=>!e.isData),n=e=>[e.name,...e.aliases??[]];for(let e of Nu){let r=t.find(t=>n(t).some(t=>t.toLowerCase()===e.toLowerCase()));if(r)return r.name}return t.find(e=>n(e).some(e=>Pu.test(e)))?.name??null}var Iu=class{constructor({issues:e=null,renderer:t=null}={}){this._issues=e,this._renderer=t,this._listeners=new Map,this._workingSpace=null,this._activeView=null,this._exportSpace=null,this._context=null,this._lastUsed=new Map,this._useClock=0,this._lastBuiltin=Al,this._fingerprint=null,Yl(e),this._offRegistry=fl(()=>{this._renderer&&bl(this._renderer),this._emit(`transforms`)}),ku===null&&(ku=this)}on(e,t){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(t),()=>this._listeners.get(e)?.delete(t)}_emit(e,t=null){for(let n of this._listeners.get(e)??[])n(t);if(e!==`change`)for(let n of this._listeners.get(`change`)??[])n({event:e,detail:t})}static async listBuiltinConfigs(){return await lc()}async loadConfig({adoptWorkingSpace:e=!1,registerViews:t=!0,display:n=null,lutSize:r,...i}={}){await cc();let a=fu(i).catch(()=>null),o=await this._bakedViewsFrom(i.builtin??i.id??null,a),s;try{s=await uc(i)}catch(e){throw this._issues?.warn(Y.COLOR_CONFIG_LOAD_FAILED,`colour config failed to load; the previous one stays in effect: ${e.message}`,{builtin:i.builtin??null,configPath:i.configPath??null}),e}this._releaseViews(new Set(o.filter(e=>e.ocio.baked.ocioVersion===s.ocioVersion).map(e=>e.id))),this._fingerprint=a,gu(),jc(),this._context=null;let c=this._workingSpace;if(e?this._workingSpace=s.sceneLinear:c&&!Jc(c)&&(this._workingSpace=null),Fu(mc())||this._issues?.warn(Y.COLOR_CONFIG_LOAD_FAILED,`"${s.id}" names no linear Rec.709 space, so until a working space is adopted its views treat the render as ${s.sceneLinear} — colours will be off by that primaries change`,{sceneLinear:s.sceneLinear}),this._publishWorkingMatrix(),this._emit(`config`,s),t){let e=n??s.defaultDisplay,{added:t,skipped:i}=ru({display:e,context:this._context,source:this.workingSpace,...r?{size:r}:{}});if(t.length){let n=s.defaultViews[e],r=t.find(e=>e.ocio.view===n)??t[0];this.setActiveView(r.id)}this._emit(`transforms`,{added:t,skipped:i})}return(this._workingSpace??null)!==(c??null)&&this._emit(`workingSpace`,this.workingSpace),s}unloadConfig(){this.workingSpaceAdopted&&this._issues?.warn(Y.COLOR_CONFIG_LOAD_FAILED,`unloaded while rendering in ${this._workingSpace}; the environment stays converted into it — use app.unloadColorConfig(), which reverts the scene first`,{workingSpace:this._workingSpace}),this._releaseViews(),dc(),jc(),vu(),gu(),this._fingerprint=null,this._workingSpace=null,this._activeView=null,this._exportSpace=null,this._context=null,Rr(null),this._applyRendererOutputColorSpace(),this._emit(`config`,null),this._emit(`workingSpace`,this.workingSpace)}_releaseViews(e=null){au(e),yl(e);for(let t of this._lastUsed.keys())e?.has(t)||this._lastUsed.delete(t);this._renderer&&pl(this._renderer.toneMapping)===null&&(this._renderer.toneMapping=pl(this._lastBuiltin)?this._lastBuiltin:Al,this._activeView=null,this._applyRendererOutputColorSpace())}async _bakedViewsFrom(e,t){let n=[...kl.values()].filter(t=>t.ocio?.baked&&e!==null&&t.ocio.configId===e);if(n.length===0)return[];let r=await t;return r?n.filter(e=>e.ocio.baked.fingerprint===r):[]}async loadBakedView(e,{expect:t=null}={}){let n=await du(e);for(let[e,r]of Object.entries(t??{}))if((n[e]??null)!==(r??null))throw Error(`baked view has ${e} "${n[e]}", expected "${r}"`);let r=hc();if(r&&(r.id!==n.configId||await this._fingerprint!==n.fingerprint))throw Error(`baked view is from "${n.configId}", not the loaded "${r.id}"`);let i=[...kl.values()].find(e=>e.source===`ocio`&&e.ocio.display===n.display&&e.ocio.view===n.view&&(e.ocio.look??null)===(n.look??null));return i||this._makeRoomForTable(),_l(eu(n,i?.id??null))}async saveBakedView(e){let t=pl(e);if(t?.source!==`ocio`)throw Error(`no OCIO view with id ${e}`);let n=hc();return await uu(t,{configId:n?.id??t.ocio.configId,fingerprint:(n?await this._fingerprint:null)??t.ocio.baked?.fingerprint??null,ocioVersion:n?.ocioVersion??t.ocio.baked?.ocioVersion??null})}get hasConfig(){return fc()}describe(){return hc()}get workingSpace(){return this._workingSpace?this._workingSpace:fc()?this.nativeLinearSpace??hc()?.sceneLinear??`Linear Rec.709 (sRGB)`:Ou}get workingSpaceAdopted(){return this._workingSpace!==null}setWorkingSpace(e){if(e!==null){if(!fc())throw Error(`load an OCIO config before choosing a working space`);if(!Jc(e))throw Error(`config has no colour space "${e}"`)}(this._workingSpace??null)!==(e??null)&&(this._workingSpace=e,Tc(),this._publishWorkingMatrix(),this._rebakeViews(),this._emit(`workingSpace`,this.workingSpace))}matrixToWorking(e){return fc()?Kc(e,this.workingSpace,{context:this._context}):null}listViews(){return ml()}get activeView(){return this._activeView}setActiveView(e){let t=pl(e);if(!t)throw Error(`no view transform with id ${e}`);return this._isStale(t)&&(t=this._rebakeView(t)??t),this._activeView=t.source===`ocio`?{...t.ocio,id:t.id,name:t.name}:null,this._lastUsed.set(e,++this._useClock),t.source===`builtin`&&(this._lastBuiltin=e),this._renderer&&(this._renderer.toneMapping=e),this._applyRendererOutputColorSpace(),this._emit(`view`,t),t}setView({display:e,view:t,look:n=null,size:r}={}){if(!fc())throw Error(`load an OCIO config first`);let i=[...kl.values()].find(i=>i.source===`ocio`&&i.ocio.display===e&&i.ocio.view===t&&(i.ocio.look??null)===(n??null)&&(!r||i.ocio.size===r));i||this._makeRoomForTable();let a=i??nu({display:e,view:t,look:n,context:this._context,source:this.workingSpace,...r?{size:r}:{}});return this.setActiveView(a.id),pl(a.id)}_makeRoomForTable(){if(hl()<12)return;let e=this._renderer?.toneMapping??this._activeView?.id??null,t=[...kl.values()].filter(t=>t.source===`ocio`&&t.id!==e).sort((e,t)=>(this._lastUsed.get(e.id)??0)-(this._lastUsed.get(t.id)??0))[0];t&&(iu(t.id),vl(t.id),this._lastUsed.delete(t.id))}setLook(e){if(!this._activeView)throw Error(`no OCIO view is active`);return this.setView({...this._activeView,look:e})}setContext(e){let t=e&&Object.keys(e).length?{...e}:null;JSON.stringify(t)!==JSON.stringify(this._context)&&(this._context=t,fc()&&(this._context&&pc()?.invalidateContext(this._context),Tc(),this._rebakeViews()),this._emit(`context`,this._context))}get context(){return this._context}_isStale(e){return e.source!==`ocio`||!fc()?!1:e.ocio.source!==this.workingSpace||JSON.stringify(e.ocio.context??null)!==JSON.stringify(this._context??null)}_rebakeView(e){try{let t=nu({id:e.id,display:e.ocio.display,view:e.ocio.view,look:e.ocio.look,context:this._context,source:this.workingSpace,size:e.ocio.size,minEv:e.ocio.minEv,maxEv:e.ocio.maxEv}),n=e.table?.texture;return n&&n!==t.table?.texture&&n.dispose?.(),t}catch(t){return this._issues?.warn(Y.VIEW_TRANSFORM_BAKE_FAILED,`could not rebake "${e.name}": ${t.message}`,{id:e.id}),null}}_rebakeViews(){let e=this._renderer?.toneMapping??this._activeView?.id??null,t=e===null?null:pl(e);if(!t||!this._isStale(t))return;let n=this._rebakeView(t);n&&(this._activeView={...n.ocio,id:n.id,name:n.name})}attachRenderer(e){this._renderer=e,pl(e.toneMapping)?.source===`builtin`&&(this._lastBuiltin=e.toneMapping);let t=bl(e);return this._applyRendererOutputColorSpace(),t}_applyRendererOutputColorSpace(){if(!this._renderer)return;let e=pl(this._renderer.toneMapping);this._renderer.outputColorSpace=e?.outputEncoded?r.LinearSRGBColorSpace:r.SRGBColorSpace,this._applyCanvasColorSpace(e?.source===`ocio`?Mu(e.ocio.display):`srgb`)}_applyCanvasColorSpace(e){let t=(this._renderer?.domElement)?.getContext?.(`webgpu`),n=t?.getConfiguration?.();if(n){if(!t.__rayzeeConfigure){let e=t.configure.bind(t);t.__rayzeeConfigure=e,t.configure=n=>e({...n,colorSpace:t.__rayzeeColorSpace??n.colorSpace})}if(t.__rayzeeColorSpace=e,n.colorSpace!==e)try{t.configure({...n,colorSpace:e})}catch(t){this._issues?.warn(Y.VIEW_TRANSFORM_DISPLAY_MISMATCH,`the canvas could not be set to ${e}: ${t.message}`,{colorSpace:e})}}}resolveInput(e,t){return Cu(e,t)}textureSpace(e,t){return Du(e,t)}resolveTexture(e,t){return Eu(e,t)}describeTextureSpace(e){let t=e?.userData??{},n=t.ocioColorSpace??t.__rayzeeColorSpaceChoice??null,i=null,a=t.__rayzeeOriginalColorSpace??e?.colorSpace;return fc()&&(i=Eu({...e,name:e?.name,image:e?.image,colorSpace:a,userData:{}})),i||={colorSpace:a===r.SRGBColorSpace?`sRGB`:`Linear`,via:`three`},{choice:n,auto:i}}get inputKey(){return fc()?`${hc()?.id}|${this.workingSpace}|${hu()}|${JSON.stringify(this._context)}`:`-`}overrideInput(e,t){_u(e,t)}fileRules(){return xu()}toWorkingPixels(e,t){return!fc()||!t?e:Nc(e,t,this.workingSpace,{context:this._context})}get nativeLinearSpace(){return Fu(mc())}_publishWorkingMatrix(){ku!==null&&ku!==this||Rr(fc()?this.primariesMatrixToWorking():null,this.workingSpace)}primariesMatrixToWorking(){if(!fc()||!this.workingSpaceAdopted)return null;let e=this.nativeLinearSpace;if(!e||e===this.workingSpace)return null;let t=Kc(e,this.workingSpace,{context:this._context});return t?[1,0,0,0,1,0,0,0,1].every((e,n)=>Math.abs(t[n]-e)<1e-6)?null:t:null}convertLinearTriple(e){return Vr(e)}convertLinearTriples(e,t,n){return Hr(e,t,n)}convertTexturePixels(e,{space:t=null}={}){if(!fc())return!1;let n=e?.image?.data;if(!n)return!1;let r=this.nativeLinearSpace,i=e.userData?.__rayzeeColorSpace??t??r,a=this.workingSpaceAdopted?this.workingSpace:r;if(!i||!a||i===a)return!1;let o=!1;if(n instanceof Float32Array)Nc(n,i,a,{context:this._context}),o=!0;else if(n instanceof Uint16Array){let e=Ll(n);Nc(e,i,a,{context:this._context}),n.set(Il(e)),o=!0}else if(n instanceof Uint8Array||n instanceof Uint8ClampedArray)Bc(n,i,a,{context:this._context,inputEncoding:`srgb`,outputEncoding:`srgb`}),o=!0;else return this._issues?.warn(Y.VIEW_TRANSFORM_BAKE_FAILED,`texture data is ${n.constructor?.name??typeof n}, which cannot be colour-converted`,{from:i,to:a}),!1;return e.userData=e.userData??{},e.userData.__rayzeeColorSpace=a,e.needsUpdate=!0,o}convertTextureBytes(e,{space:t=null,encoding:n=`srgb`}={}){if(!fc())return!1;if(t)return t===this.workingSpace?!1:(Bc(e,t,this.workingSpace,{context:this._context,inputEncoding:`raw`,outputEncoding:n}),!0);let r=this.primariesMatrixToWorking();return r?(Gc(e,r,n),!0):!1}toWorkingColor(e,t){return!fc()||!t?[e[0],e[1],e[2]]:Mc(e,t,this.workingSpace,{context:this._context})}convert(e,t,n){return Mc(e,t,n,{context:this._context})}get exportSpace(){return this._exportSpace}setExportSpace(e){if(e!=null){if(!fc())throw Error(`load an OCIO config before choosing an export space`);if(!Jc(e))throw Error(`config has no colour space "${e}"`)}this._exportSpace=e??null,this._emit(`export`,this._exportSpace)}exportPixels(e,t=void 0){let n=t===void 0?this._exportSpace:t;return!n||!fc()?{rgba:e,colorSpace:this.workingSpace}:(Nc(e,this.workingSpace,n,{context:this._context}),{rgba:e,colorSpace:n})}status(){let e=hc(),t=this._renderer?pl(this._renderer.toneMapping):null;return{config:e,workingSpace:this.workingSpace,workingSpaceAdopted:this.workingSpaceAdopted,activeTransform:t?{id:t.id,name:t.name,source:t.source}:null,activeView:this._activeView,context:this._context,exportSpace:this._exportSpace,views:ml(),registryVersion:dl(),bakeError:t?.error??null}}dispose(){this._offRegistry?.(),this._listeners.clear(),this._releaseViews(),Yl(null),this._renderer=null,this._issues=null,ku===this&&(Rr(null),ku=null)}static resetAll(){ku=null,Rr(null),au(),Sl(),jc(),vu(),vc()}};function Lu(){return fc()}var Ru=new Map;function zu(e){return Ru.get(e)?.storage??null}$s();var Bu=1;function Vu(e,t){e&&t&&(e.userData.__rayzeeSource=t)}function Hu(e){let t=e?.userData?.__rayzeeSource;if(!t)return null;let{width:n=0,height:r=0}=e.image??{};return`cdf:${Bu}:${t}|${n}x${r}|${e.userData.__rayzeeColorSpace??`native`}`}var Uu=()=>zu(Xs().cacheNamespace)?.area(qn.CDF)??null;async function Wu(e){let t=Hu(e),n=t?await Uu()?.open(t):null;if(!n)return null;try{let[e,t]=await Promise.all([n.file(`marginal.f32`),n.file(`conditional.f32`)]);if(!e||!t)return null;let{totalSum:r,compensationDelta:i,width:a,height:o}=n.extra;return{marginalData:new Float32Array(await e.arrayBuffer()),conditionalData:new Float32Array(await t.arrayBuffer()),totalSum:r,compensationDelta:i,width:a,height:o}}finally{n.release()}}async function Gu(e,{marginalData:t,conditionalData:n,totalSum:r,compensationDelta:i,width:a,height:o}){let s=Hu(e),c=s?Uu():null;if(!c||!t||!n)return!1;let l=await c.create(s,{label:e.name||`environment`,expectedBytes:t.byteLength+n.byteLength});if(!l)return!1;try{return await l.write(`marginal.f32`,t),await l.write(`conditional.f32`,n),await l.commit({totalSum:r,compensationDelta:i,width:a,height:o}),!0}catch{return await l.abort(),!1}}jt();var Ku=vt(`env`),qu=1024,Ju=512,Yu=Math.PI/180,Xu=new r.Matrix4,Zu=4,Qu=class{constructor(e,t,n=null){this.scene=e,this.uniforms=t,this.renderer=n,this.equirectHdrInfo=new pi,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`,gradientZenithColor:new r.Color(V.gradientZenithColor),gradientHorizonColor:new r.Color(V.gradientHorizonColor),gradientGroundColor:new r.Color(V.gradientGroundColor),solidSkyColor:new r.Color(V.solidSkyColor),skySunDirection:this._calculateInitialSunDirection(),skySunStrength:V.skySunStrength,skySunSize:V.skySunSize,skyTurbidity:V.skyTurbidity,skyOzone:V.skyOzone,skyAirDensity:V.skyAirDensity,skyGroundAlbedo:new r.Color(V.skyGroundAlbedo),skyAltitude:V.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===`gradient`?await this.generateGradientTexture():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.onAutoExposureReset?.(),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,gradientZenithColor:e.gradientZenithColor.toArray(),gradientHorizonColor:e.gradientHorizonColor.toArray(),gradientGroundColor:e.gradientGroundColor.toArray(),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=[`gradientZenithColor`,`gradientHorizonColor`,`gradientGroundColor`,`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]);e.mode&&(e.mode!==`hdri`||t.mode!==`hdri`)&&await this.setMode(e.mode)}get params(){return this.envParams}get texture(){return this.environmentTexture}generateGradient(){return this.generateGradientTexture()}generateSolid(){return this.generateSolidColorTexture()}generateProcedural(){return this.generateProceduralSkyTexture()}_initCDFTexture(){this.envCDFTexture=new r.DataTexture(new Float32Array([0]),1,1,r.RedFormat,r.FloatType),this.envCDFTexture.needsUpdate=!0}_updateCDFTexture(){let e=this.equirectHdrInfo.marginalData,t=this.equirectHdrInfo.conditionalData;if(!e||!t)return;let n=this.equirectHdrInfo.width,i=this.equirectHdrInfo.height,a=n+1,o=new Float32Array(a*i);for(let r=0;r<i;r++){let i=r*a;o.set(t.subarray(r*n,r*n+n),i),o[i+n]=e[r]}this.envCDFTexture?._isPhysicalSky||this.envCDFTexture?.dispose?.(),this.envCDFTexture=new r.DataTexture(o,a,i,r.RedFormat,r.FloatType),this.envCDFTexture.needsUpdate=!0}setEnvironmentTexture(e){if(!e)return;let t=Au();if(t?.hasConfig)try{t.convertTexturePixels(e,{space:e.userData?.ocioColorSpace??null})}catch(e){Ku.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),this.uniforms.set(`envCompensationDelta`,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),this.uniforms.set(`envCompensationDelta`,0);return}let r=`${n.uuid}:${n.version}`;if(r===this._cdfSignature)return;let i=await Wu(n).catch(()=>null);i?Object.assign(this.equirectHdrInfo,i):e?await this.equirectHdrInfo.updateFromAsync(n):this.equirectHdrInfo.updateFrom(n),i||Gu(n,this.equirectHdrInfo).catch(()=>{}),this._cdfSignature=r,this.cdfBuildTime=performance.now()-t,this._updateCDFTexture(),this.uniforms.set(`envTotalSum`,this.equirectHdrInfo.totalSum),this.uniforms.set(`envCompensationDelta`,this.equirectHdrInfo.compensationDelta);let{width:a,height:o}=this.equirectHdrInfo;a&&o&&this.uniforms.get(`envResolution`).value.set(a,o),Ku.info(J.list([J.px(this.envTexSize.x,this.envTexSize.y),`CDF ${J.ms(this.cdfBuildTime)}${i?` (stored)`:e?``:` (main thread)`}`]))}catch(e){this._cdfSignature=null,Ku.error(`CDF build failed:`,e),this.uniforms.set(`envTotalSum`,0),this.uniforms.set(`envCompensationDelta`,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),this.uniforms.set(`envCompensationDelta`,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 generateGradientTexture(){this.simpleSkyRenderer||=new Ks(512,256);let e={zenithColor:this.envParams.gradientZenithColor,horizonColor:this.envParams.gradientHorizonColor,groundColor:this.envParams.gradientGroundColor};try{let t=this.simpleSkyRenderer.renderGradient(e);t._isGeneratedProcedural=!0,await this.setEnvironmentMap(t),this.uniforms.set(`hasSun`,0)}catch(e){Ku.error(`gradient sky generation failed:`,e)}}async generateSolidColorTexture(){this.simpleSkyRenderer||=new Ks(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){Ku.error(`solid color sky generation failed:`,e)}}generateProceduralSkyTexture(){return this._skyRequested=!0,this._skyCaughtUp??=new Promise(e=>void(this._resolveSky=e)),this._pumpSky(),this._skyCaughtUp}_pumpSky(){this._skyScheduled||!this._skyRequested||this._skyInFlight>=Zu||(this._skyScheduled=!0,queueMicrotask(()=>{this._skyScheduled=!1,this._skyRequested&&this._skyInFlight<Zu&&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||Ku.warn(`physical sky needs a renderer`),this._skyInFlight===0&&this._settleSky();return}let t=this.physicalSky??=new Gs(qu,Ju),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*Yu,sunStrength:e.skySunStrength});this._sun=s,this._installSky(a,o);let{totalSum:l,compensationDelta:u}=await c;e.mode===`procedural`&&t===this.physicalSky&&r>this._skyStatsBake&&(this._skyStatsBake=r,this.uniforms.set(`envTotalSum`,l),this.uniforms.set(`envCompensationDelta`,u),i()&&this._notifyReset()),i()&&Ku.debug(`physical sky ${J.ms(t.getLastRenderTime())} · sun ${s.radiance.map(e=>e.toPrecision(3)).join(`,`)}`)}catch(e){Ku.error(`physical sky generation failed:`,e)}finally{this._skyInFlight--,i()?this._settleSky():this._pumpSky()}}_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,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(Xu.copy(this.environmentRotationMatrix).transpose());let n=[...e.radiance];Vr(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=V.skySunAzimuth*(Math.PI/180),t=V.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}},$u=1e-6,ed=e=>{let t=e.mul(e);return t.mul(t).mul(e)};(0,n.Fn)(([e,t,r])=>{let i=(0,n.max)((0,n.vec3)((0,n.float)(1).sub(r)),e);return e.add(i.sub(e).mul(ed((0,n.float)(1).sub(t))))});var td=(0,n.Fn)(([e,t])=>{let r=(0,n.clamp)(e,0,1);return t.add((0,n.float)(1).sub(t).mul(ed((0,n.float)(1).sub(r))))}),nd=(0,n.Fn)(([e,t])=>{let r=(0,n.clamp)(e,0,1);return t.add((0,n.vec3)(1).sub(t).mul(ed((0,n.float)(1).sub(r))))}),rd=(0,n.Fn)(([e])=>{let t=(0,n.sqrt)(e);return(0,n.vec3)(1).add(t).div((0,n.max)((0,n.vec3)(1).sub(t),(0,n.vec3)($u)))}),id=(0,n.Fn)(([e,t])=>{let r=e.sub((0,n.vec3)(t)),i=(0,n.max)(e.add((0,n.vec3)(t)),(0,n.vec3)($u)),a=r.div(i);return a.mul(a)}),ad=(0,n.Fn)(([e,t])=>{let r=e.sub(t),i=(0,n.max)(e.add(t),$u),a=r.div(i);return a.mul(a)}),od=e=>(0,n.vec3)(ad(e,(0,n.float)(1))),sd=(0,n.Fn)(([e,t])=>{let r=(0,n.clamp)(e,0,1),i=t.mul(t).sub(1).add(r.mul(r)),a=(0,n.sqrt)((0,n.max)(i,0)),o=a.sub(r).div((0,n.max)(a.add(r),$u)),s=r.mul(a.add(r)).sub(1).div((0,n.max)(r.mul(a.sub(r)).add(1),$u));return(0,n.select)(i.greaterThan(0),(0,n.clamp)(o.mul(o).mul(.5).mul(s.mul(s).add(1)),0,1),(0,n.float)(1))}),cd=(0,n.Fn)(([e,t])=>{let r=ad(t,(0,n.float)(1));return(0,n.clamp)(sd(e,t).sub(r).div((0,n.max)((0,n.float)(1).sub(r),$u)),0,1)}),ld=1e-30,ud=(0,n.Fn)(([e,t])=>{let r=t.mul(t),i=r.mul(r),a=e.mul(e).mul(i.sub(1)).add(1);return i.div((0,n.max)((0,n.float)(Mi).mul(a).mul(a),ld))}),dd=(0,n.Fn)(([e,t])=>{let r=(0,n.max)(t,Ii),i=r.mul(r),a=(0,n.float)(1).div(i.mul(i)),o=e.mul(e).mul(a.sub(1)).add(1);return a.div((0,n.max)((0,n.float)(Mi).mul(o).mul(o),Fi))}),fd=(0,n.Fn)(([e])=>(0,n.float)(1).div((0,n.max)(e,Ii))),pd=(0,n.Fn)(([e,t])=>(0,n.clamp)((0,n.float)(1).div((0,n.max)((0,n.float)(4).mul(t.add(e).sub(t.mul(e))),Fi)),0,1)),md=(0,n.Fn)(([e,t])=>{let r=t.mul(t),i=r.mul(r),a=e.add((0,n.sqrt)(i.add((0,n.float)(1).sub(i).mul(e.mul(e)))));return(0,n.float)(2).mul(e).div((0,n.max)(a,Fi))}),hd=(0,n.Fn)(([e,t,r])=>{let i=r.mul(r),a=i.mul(i),o=t.mul((0,n.sqrt)(a.add((0,n.float)(1).sub(a).mul(e.mul(e))))),s=e.mul((0,n.sqrt)(a.add((0,n.float)(1).sub(a).mul(t.mul(t)))));return(0,n.float)(.5).div((0,n.max)(o.add(s),Fi))}),gd=16,_d=17,vd=.5,yd=_d,bd=new r.DataTexture(new Float32Array([1,.0302,.9039,1,.9712,.0898,.8635,1,.8914,.6742,.6952,1,.9176,1.1716,.5703,1,.9447,1.3763,.4529,1,.9592,1.3948,.3509,1,.9658,1.3111,.269,1,.9679,1.183,.2061,1,.9669,1.0453,.1588,1,.9639,.9156,.1237,1,.9592,.8006,.0978,1,.9533,.7013,.0786,1,.9465,.6167,.0644,1,.9388,.5447,.0537,1,.9304,.4836,.0457,1,.9214,.4314,.0395,1,0,.7915,1,1,0,.745,1,1,0,.5423,1,1,0,.3846,1,1,0,.2656,1,1,0,.1819,1,1,0,.1256,1,1,0,.0882,1,1,0,.0633,1,1,0,.0466,1,1,0,.0352,1,1,0,.0274,1,1,0,.0218,1,1,0,.0178,1,1,0,.0149,1,1,0,.0127,1,1,.7915,.8421,1,1,.745,.798,1,1,.5423,.608,1,1,.3846,.461,1,1,.2656,.34,1,1,.1819,.2471,1,1,.1256,.1797,1,1,.0882,.132,1,1,.0633,.0985,1,1,.0466,.0749,1,1,.0352,.0582,1,1,.0274,.0463,1,1,.0218,.0376,1,1,.0178,.0312,1,1,.0149,.0264,1,1,.0127,.0227,1,1,.8421,.8638,1,1,.798,.821,1,1,.608,.6386,1,1,.461,.4996,1,1,.34,.3803,1,1,.2471,.2847,1,1,.1797,.2128,1,1,.132,.1601,1,1,.0985,.122,1,1,.0749,.0945,1,1,.0582,.0745,1,1,.0463,.06,1,1,.0376,.0493,1,1,.0312,.0413,1,1,.0264,.0352,1,1,.0227,.0305,1,1,.8638,.8754,1,1,.821,.8334,1,1,.6386,.6559,1,1,.4996,.5225,1,1,.3803,.4052,1,1,.2847,.3089,1,1,.2128,.2347,1,1,.1601,.1793,1,1,.122,.1385,1,1,.0945,.1085,1,1,.0745,.0865,1,1,.06,.0702,1,1,.0493,.0581,1,1,.0413,.049,1,1,.0352,.042,1,1,.0305,.0366,1,1,.8754,.8821,1,1,.8334,.8406,1,1,.6559,.6663,1,1,.5225,.5367,1,1,.4052,.4212,1,1,.3089,.3248,1,1,.2347,.2495,1,1,.1793,.1926,1,1,.1385,.1501,1,1,.1085,.1186,1,1,.0865,.0952,1,1,.0702,.0778,1,1,.0581,.0647,1,1,.049,.0547,1,1,.042,.0471,1,1,.0366,.0412,1,1,.8821,.8857,1,1,.8406,.8445,1,1,.6663,.6722,1,1,.5367,.5451,1,1,.4212,.4311,1,1,.3248,.335,1,1,.2495,.2592,1,1,.1926,.2014,1,1,.1501,.158,1,1,.1186,.1255,1,1,.0952,.1013,1,1,.0778,.0831,1,1,.0647,.0694,1,1,.0547,.0589,1,1,.0471,.0508,1,1,.0412,.0445,1,1,.8857,.8872,1,1,.8445,.8462,1,1,.6722,.6749,1,1,.5451,.5494,1,1,.4311,.4364,1,1,.335,.3406,1,1,.2592,.2648,1,1,.2014,.2067,1,1,.158,.1628,1,1,.1255,.1299,1,1,.1013,.1052,1,1,.0831,.0866,1,1,.0694,.0725,1,1,.0589,.0617,1,1,.0508,.0533,1,1,.0445,.0468,1,1,.8872,.887,1,1,.8462,.846,1,1,.6749,.6751,1,1,.5494,.5503,1,1,.4364,.4379,1,1,.3406,.3427,1,1,.2648,.2671,1,1,.2067,.2091,1,1,.1628,.1651,1,1,.1299,.1321,1,1,.1052,.1072,1,1,.0866,.0884,1,1,.0725,.0741,1,1,.0617,.0632,1,1,.0533,.0547,1,1,.0468,.0481,1,1,.887,.8854,1,1,.846,.8443,1,1,.6751,.6732,1,1,.5503,.5483,1,1,.4379,.4363,1,1,.3427,.3415,1,1,.2671,.2665,1,1,.2091,.2088,1,1,.1651,.1651,1,1,.1321,.1322,1,1,.1072,.1075,1,1,.0884,.0888,1,1,.0741,.0745,1,1,.0632,.0636,1,1,.0547,.0551,1,1,.0481,.0485,1,1,.8854,.8824,1,1,.8443,.8412,1,1,.6732,.6692,1,1,.5483,.5436,1,1,.4363,.4317,1,1,.3415,.3375,1,1,.2665,.2631,1,1,.2088,.2061,1,1,.1651,.1631,1,1,.1322,.1306,1,1,.1075,.1062,1,1,.0888,.0878,1,1,.0745,.0737,1,1,.0636,.0629,1,1,.0551,.0546,1,1,.0485,.048,1,1,.8824,.8781,1,1,.8412,.8366,1,1,.6692,.6633,1,1,.5436,.5364,1,1,.4317,.4244,1,1,.3375,.3308,1,1,.2631,.2573,1,1,.2061,.2012,1,1,.1631,.159,1,1,.1306,.1273,1,1,.1062,.1034,1,1,.0878,.0854,1,1,.0737,.0718,1,1,.0629,.0613,1,1,.0546,.0531,1,1,.048,.0467,1,1,.8781,.8723,1,1,.8366,.8306,1,1,.6633,.6555,1,1,.5364,.5267,1,1,.4244,.4142,1,1,.3308,.3213,1,1,.2573,.249,1,1,.2012,.1941,1,1,.159,.153,1,1,.1273,.1223,1,1,.1034,.0992,1,1,.0854,.0819,1,1,.0718,.0687,1,1,.0613,.0586,1,1,.0531,.0508,1,1,.0467,.0447,1,1,.8723,.8651,1,1,.8306,.8229,1,1,.6555,.6454,1,1,.5267,.5142,1,1,.4142,.4012,1,1,.3213,.3091,1,1,.249,.2382,1,1,.1941,.1848,1,1,.153,.1451,1,1,.1223,.1156,1,1,.0992,.0936,1,1,.0819,.0771,1,1,.0687,.0646,1,1,.0586,.0551,1,1,.0508,.0477,1,1,.0447,.0419,1,1,.8651,.856,1,1,.8229,.8134,1,1,.6454,.6331,1,1,.5142,.4988,1,1,.4012,.3852,1,1,.3091,.2941,1,1,.2382,.2248,1,1,.1848,.1733,1,1,.1451,.1353,1,1,.1156,.1073,1,1,.0936,.0866,1,1,.0771,.0711,1,1,.0646,.0594,1,1,.0551,.0505,1,1,.0477,.0437,1,1,.0419,.0383,1,1,.856,.8449,1,1,.8134,.8018,1,1,.6331,.618,1,1,.4988,.4803,1,1,.3852,.3659,1,1,.2941,.276,1,1,.2248,.2087,1,1,.1733,.1595,1,1,.1353,.1236,1,1,.1073,.0973,1,1,.0866,.0781,1,1,.0711,.0638,1,1,.0594,.0532,1,1,.0505,.0451,1,1,.0437,.0389,1,1,.0383,.034,1,1,.8449,.8314,1,1,.8018,.7875,1,1,.618,.5998,1,1,.4803,.458,1,1,.3659,.3429,1,1,.276,.2545,1,1,.2087,.1898,1,1,.1595,.1431,1,1,.1236,.1097,1,1,.0973,.0856,1,1,.0781,.0681,1,1,.0638,.0553,1,1,.0532,.0458,1,1,.0451,.0387,1,1,.0389,.0332,1,1,.034,.029,1,1,1,.0026,.7082,1,.9976,.0086,.7027,1,.9605,.1171,.6408,1,.9009,.4003,.5153,1,.8888,.6973,.4009,1,.9003,.8744,.3086,1,.9117,.9308,.2352,1,.9171,.9098,.1786,1,.9163,.8501,.1361,1,.9105,.7761,.1045,1,.9007,.7008,.0813,1,.8876,.6301,.0641,1,.872,.5661,.0514,1,.8545,.5094,.0418,1,.8354,.4596,.0345,1,.8152,.416,.029,1,0,.4601,1,1,0,.4552,1,1,0,.4022,1,1,0,.2965,1,1,0,.2054,1,1,0,.1411,1,1,0,.0974,1,1,0,.0682,1,1,0,.0486,1,1,0,.0354,1,1,0,.0264,1,1,0,.0202,1,1,0,.0157,1,1,0,.0125,1,1,0,.0102,1,1,0,.0084,1,1,.4601,.5649,1,1,.4552,.5595,1,1,.4022,.5014,1,1,.2965,.3849,1,1,.2054,.2817,1,1,.1411,.2046,1,1,.0974,.1486,1,1,.0682,.1087,1,1,.0486,.0805,1,1,.0354,.0606,1,1,.0264,.0464,1,1,.0202,.0363,1,1,.0157,.0289,1,1,.0125,.0234,1,1,.0102,.0193,1,1,.0084,.0161,1,1,.5649,.6149,1,1,.5595,.6095,1,1,.5014,.5501,1,1,.3849,.4307,1,1,.2817,.3241,1,1,.2046,.2423,1,1,.1486,.1807,1,1,.1087,.1353,1,1,.0805,.1023,1,1,.0606,.0784,1,1,.0464,.061,1,1,.0363,.0483,1,1,.0289,.0389,1,1,.0234,.0318,1,1,.0193,.0265,1,1,.0161,.0223,1,1,.6149,.6434,1,1,.6095,.638,1,1,.5501,.5783,1,1,.4307,.4581,1,1,.3241,.3505,1,1,.2423,.2667,1,1,.1807,.2023,1,1,.1353,.1538,1,1,.1023,.1178,1,1,.0784,.0914,1,1,.061,.0719,1,1,.0483,.0574,1,1,.0389,.0466,1,1,.0318,.0384,1,1,.0265,.0321,1,1,.0223,.0272,1,1,.6434,.6604,1,1,.638,.6551,1,1,.5783,.5954,1,1,.4581,.4752,1,1,.3505,.3675,1,1,.2667,.2829,1,1,.2023,.2169,1,1,.1538,.1666,1,1,.1178,.1289,1,1,.0914,.1008,1,1,.0719,.0798,1,1,.0574,.0642,1,1,.0466,.0524,1,1,.0384,.0433,1,1,.0321,.0364,1,1,.0272,.031,1,1,.6604,.6702,1,1,.6551,.6649,1,1,.5954,.6053,1,1,.4752,.4854,1,1,.3675,.378,1,1,.2829,.2932,1,1,.2169,.2265,1,1,.1666,.1753,1,1,.1289,.1364,1,1,.1008,.1073,1,1,.0798,.0855,1,1,.0642,.069,1,1,.0524,.0565,1,1,.0433,.047,1,1,.0364,.0395,1,1,.031,.0337,1,1,.6702,.6747,1,1,.6649,.6694,1,1,.6053,.6101,1,1,.4854,.4906,1,1,.378,.3837,1,1,.2932,.299,1,1,.2265,.2322,1,1,.1753,.1805,1,1,.1364,.1412,1,1,.1073,.1115,1,1,.0855,.0891,1,1,.069,.0722,1,1,.0565,.0593,1,1,.047,.0494,1,1,.0395,.0417,1,1,.0337,.0356,1,1,.6747,.6751,1,1,.6694,.6699,1,1,.6101,.6108,1,1,.4906,.4918,1,1,.3837,.3854,1,1,.299,.3012,1,1,.2322,.2346,1,1,.1805,.1829,1,1,.1412,.1434,1,1,.1115,.1136,1,1,.0891,.091,1,1,.0722,.0739,1,1,.0593,.0608,1,1,.0494,.0508,1,1,.0417,.0429,1,1,.0356,.0367,1,1,.6751,.672,1,1,.6699,.6668,1,1,.6108,.608,1,1,.4918,.4895,1,1,.3854,.3838,1,1,.3012,.3002,1,1,.2346,.234,1,1,.1829,.1827,1,1,.1434,.1435,1,1,.1136,.1138,1,1,.091,.0914,1,1,.0739,.0743,1,1,.0608,.0612,1,1,.0508,.0512,1,1,.0429,.0433,1,1,.0367,.0371,1,1,.672,.6657,1,1,.6668,.6605,1,1,.608,.6019,1,1,.4895,.4841,1,1,.3838,.379,1,1,.3002,.2962,1,1,.234,.2309,1,1,.1827,.1803,1,1,.1435,.1417,1,1,.1138,.1124,1,1,.0914,.0903,1,1,.0743,.0735,1,1,.0612,.0606,1,1,.0512,.0506,1,1,.0433,.0429,1,1,.0371,.0368,1,1,.6657,.6562,1,1,.6605,.6511,1,1,.6019,.5928,1,1,.4841,.4756,1,1,.379,.3714,1,1,.2962,.2895,1,1,.2309,.2252,1,1,.1803,.1756,1,1,.1417,.1379,1,1,.1124,.1094,1,1,.0903,.0878,1,1,.0735,.0714,1,1,.0606,.0589,1,1,.0506,.0493,1,1,.0429,.0417,1,1,.0368,.0358,1,1,.6562,.6436,1,1,.6511,.6384,1,1,.5928,.5805,1,1,.4756,.4642,1,1,.3714,.3608,1,1,.2895,.2801,1,1,.2252,.2172,1,1,.1756,.1689,1,1,.1379,.1323,1,1,.1094,.1048,1,1,.0878,.084,1,1,.0714,.0683,1,1,.0589,.0563,1,1,.0493,.047,1,1,.0417,.0398,1,1,.0358,.0341,1,1,.6436,.6275,1,1,.6384,.6224,1,1,.5805,.565,1,1,.4642,.4495,1,1,.3608,.3472,1,1,.2801,.2679,1,1,.2172,.2067,1,1,.1689,.16,1,1,.1323,.125,1,1,.1048,.0987,1,1,.084,.079,1,1,.0683,.0641,1,1,.0563,.0527,1,1,.047,.044,1,1,.0398,.0372,1,1,.0341,.0319,1,1,.6275,.6078,1,1,.6224,.6027,1,1,.565,.5458,1,1,.4495,.4316,1,1,.3472,.3305,1,1,.2679,.2529,1,1,.2067,.1937,1,1,.16,.1491,1,1,.125,.1158,1,1,.0987,.0911,1,1,.079,.0726,1,1,.0641,.0588,1,1,.0527,.0483,1,1,.044,.0402,1,1,.0372,.0339,1,1,.0319,.029,1,1,.6078,.5838,1,1,.6027,.5788,1,1,.5458,.5226,1,1,.4316,.4099,1,1,.3305,.3105,1,1,.2529,.235,1,1,.1937,.1781,1,1,.1491,.1359,1,1,.1158,.1048,1,1,.0911,.0819,1,1,.0726,.065,1,1,.0588,.0524,1,1,.0483,.0428,1,1,.0402,.0356,1,1,.0339,.0299,1,1,.029,.0255,1,1,.5838,.5551,1,1,.5788,.5501,1,1,.5226,.4948,1,1,.4099,.384,1,1,.3105,.2867,1,1,.235,.2137,1,1,.1781,.1598,1,1,.1359,.1204,1,1,.1048,.0919,1,1,.0819,.0712,1,1,.065,.056,1,1,.0524,.0448,1,1,.0428,.0365,1,1,.0356,.0301,1,1,.0299,.0253,1,1,.0255,.0215,1,1,1,3e-4,.4889,1,.9994,.002,.4874,1,.9894,.0281,.4696,1,.9511,.1226,.4131,1,.9046,.2856,.3306,1,.8809,.4505,.2533,1,.8752,.5628,.1913,1,.8737,.6152,.1439,1,.8693,.6237,.1084,1,.8596,.6057,.0821,1,.8444,.5742,.0629,1,.8245,.537,.0487,1,.8007,.4985,.0382,1,.7739,.4613,.0303,1,.745,.4264,.0244,1,.7147,.3943,.0199,1,0,.2156,1,1,0,.215,1,1,0,.2064,1,1,0,.177,1,1,0,.1336,1,1,0,.0949,1,1,0,.0665,1,1,0,.0469,1,1,0,.0334,1,1,0,.0243,1,1,0,.018,1,1,0,.0135,1,1,0,.0104,1,1,0,.0081,1,1,0,.0064,1,1,0,.0052,1,1,.2156,.3209,1,1,.215,.3199,1,1,.2064,.3074,1,1,.177,.2667,1,1,.1336,.2071,1,1,.0949,.1529,1,1,.0665,.1116,1,1,.0469,.0817,1,1,.0334,.0603,1,1,.0243,.0451,1,1,.018,.0342,1,1,.0135,.0263,1,1,.0104,.0206,1,1,.0081,.0164,1,1,.0064,.0132,1,1,.0052,.0107,1,1,.3209,.3796,1,1,.3199,.3785,1,1,.3074,.3642,1,1,.2667,.3183,1,1,.2071,.2512,1,1,.1529,.1895,1,1,.1116,.1415,1,1,.0817,.1058,1,1,.0603,.0796,1,1,.0451,.0605,1,1,.0342,.0466,1,1,.0263,.0363,1,1,.0206,.0288,1,1,.0164,.0231,1,1,.0132,.0187,1,1,.0107,.0154,1,1,.3796,.4159,1,1,.3785,.4147,1,1,.3642,.3995,1,1,.3183,.3509,1,1,.2512,.2798,1,1,.1895,.214,1,1,.1415,.1621,1,1,.1058,.1229,1,1,.0796,.0937,1,1,.0605,.072,1,1,.0466,.056,1,1,.0363,.0441,1,1,.0288,.0351,1,1,.0231,.0284,1,1,.0187,.0232,1,1,.0154,.0192,1,1,.4159,.4389,1,1,.4147,.4377,1,1,.3995,.422,1,1,.3509,.372,1,1,.2798,.2987,1,1,.214,.2306,1,1,.1621,.1764,1,1,.1229,.135,1,1,.0937,.1038,1,1,.072,.0805,1,1,.056,.063,1,1,.0441,.0499,1,1,.0351,.04,1,1,.0284,.0325,1,1,.0232,.0266,1,1,.0192,.0221,1,1,.4389,.453,1,1,.4377,.4517,1,1,.422,.4359,1,1,.372,.3851,1,1,.2987,.3107,1,1,.2306,.2414,1,1,.1764,.186,1,1,.135,.1433,1,1,.1038,.1109,1,1,.0805,.0864,1,1,.063,.068,1,1,.0499,.0541,1,1,.04,.0436,1,1,.0325,.0355,1,1,.0266,.0292,1,1,.0221,.0243,1,1,.453,.4604,1,1,.4517,.4591,1,1,.4359,.4432,1,1,.3851,.3922,1,1,.3107,.3174,1,1,.2414,.2477,1,1,.186,.1917,1,1,.1433,.1484,1,1,.1109,.1154,1,1,.0864,.0903,1,1,.068,.0713,1,1,.0541,.057,1,1,.0436,.046,1,1,.0355,.0375,1,1,.0292,.031,1,1,.0243,.0258,1,1,.4604,.4625,1,1,.4591,.4612,1,1,.4432,.4453,1,1,.3922,.3945,1,1,.3174,.3199,1,1,.2477,.2502,1,1,.1917,.1943,1,1,.1484,.1509,1,1,.1154,.1176,1,1,.0903,.0923,1,1,.0713,.0731,1,1,.057,.0585,1,1,.046,.0473,1,1,.0375,.0387,1,1,.031,.032,1,1,.0258,.0267,1,1,.4625,.46,1,1,.4612,.4587,1,1,.4453,.443,1,1,.3945,.3926,1,1,.3199,.3186,1,1,.2502,.2495,1,1,.1943,.194,1,1,.1509,.151,1,1,.1176,.1179,1,1,.0923,.0927,1,1,.0731,.0735,1,1,.0585,.0589,1,1,.0473,.0478,1,1,.0387,.0391,1,1,.032,.0324,1,1,.0267,.0271,1,1,.46,.4533,1,1,.4587,.452,1,1,.443,.4366,1,1,.3926,.3869,1,1,.3186,.3139,1,1,.2495,.2458,1,1,.194,.1912,1,1,.151,.1489,1,1,.1179,.1163,1,1,.0927,.0916,1,1,.0735,.0727,1,1,.0589,.0583,1,1,.0478,.0473,1,1,.0391,.0387,1,1,.0324,.0321,1,1,.0271,.0268,1,1,.4533,.4427,1,1,.452,.4415,1,1,.4366,.4264,1,1,.3869,.3776,1,1,.3139,.306,1,1,.2458,.2394,1,1,.1912,.186,1,1,.1489,.1447,1,1,.1163,.1131,1,1,.0916,.089,1,1,.0727,.0706,1,1,.0583,.0567,1,1,.0473,.0459,1,1,.0387,.0377,1,1,.0321,.0312,1,1,.0268,.0261,1,1,.4427,.4283,1,1,.4415,.4271,1,1,.4264,.4124,1,1,.3776,.3648,1,1,.306,.2951,1,1,.2394,.2302,1,1,.186,.1785,1,1,.1447,.1386,1,1,.1131,.1081,1,1,.089,.085,1,1,.0706,.0674,1,1,.0567,.054,1,1,.0459,.0438,1,1,.0377,.0359,1,1,.0312,.0297,1,1,.0261,.0249,1,1,.4283,.4098,1,1,.4271,.4087,1,1,.4124,.3945,1,1,.3648,.3485,1,1,.2951,.281,1,1,.2302,.2184,1,1,.1785,.1687,1,1,.1386,.1305,1,1,.1081,.1015,1,1,.085,.0796,1,1,.0674,.0631,1,1,.054,.0505,1,1,.0438,.0409,1,1,.0359,.0335,1,1,.0297,.0277,1,1,.0249,.0231,1,1,.4098,.3872,1,1,.4087,.3861,1,1,.3945,.3726,1,1,.3485,.3284,1,1,.281,.2637,1,1,.2184,.2038,1,1,.1687,.1565,1,1,.1305,.1205,1,1,.1015,.0933,1,1,.0796,.0729,1,1,.0631,.0576,1,1,.0505,.046,1,1,.0409,.0372,1,1,.0335,.0304,1,1,.0277,.0251,1,1,.0231,.0209,1,1,.3872,.3601,1,1,.3861,.3591,1,1,.3726,.3462,1,1,.3284,.3044,1,1,.2637,.2429,1,1,.2038,.1863,1,1,.1565,.1419,1,1,.1205,.1085,1,1,.0933,.0835,1,1,.0729,.0649,1,1,.0576,.051,1,1,.046,.0406,1,1,.0372,.0327,1,1,.0304,.0266,1,1,.0251,.0219,1,1,.0209,.0183,1,1,.3601,.328,1,1,.3591,.3271,1,1,.3462,.3151,1,1,.3044,.276,1,1,.2429,.2184,1,1,.1863,.1657,1,1,.1419,.1248,1,1,.1085,.0944,1,1,.0835,.0719,1,1,.0649,.0554,1,1,.051,.0433,1,1,.0406,.0342,1,1,.0327,.0274,1,1,.0266,.0222,1,1,.0219,.0182,1,1,.0183,.0151,1,1,1,0,.3277,1,.9999,7e-4,.3272,1,.9955,.0104,.3205,1,.9751,.0486,.2969,1,.9352,.129,.2521,1,.8955,.2363,.1989,1,.8698,.3371,.1513,1,.8545,.4098,.1136,1,.8416,.4511,.085,1,.8258,.4674,.0639,1,.805,.4664,.0484,1,.7792,.4547,.0369,1,.7489,.437,.0285,1,.7152,.4164,.0223,1,.6791,.3948,.0176,1,.6416,.3732,.014,1,0,.1041,1,1,0,.1041,1,1,0,.1027,1,1,0,.0956,1,1,0,.08,1,1,0,.061,1,1,0,.0444,1,1,0,.0319,1,1,0,.023,1,1,0,.0167,1,1,0,.0124,1,1,0,.0093,1,1,0,.007,1,1,0,.0054,1,1,0,.0042,1,1,0,.0034,1,1,.1041,.1837,1,1,.1041,.1835,1,1,.1027,.1803,1,1,.0956,.1673,1,1,.08,.141,1,1,.061,.1097,1,1,.0444,.082,1,1,.0319,.0606,1,1,.023,.0449,1,1,.0167,.0335,1,1,.0124,.0253,1,1,.0093,.0193,1,1,.007,.015,1,1,.0054,.0117,1,1,.0042,.0093,1,1,.0034,.0074,1,1,.1837,.235,1,1,.1835,.2347,1,1,.1803,.2304,1,1,.1673,.2139,1,1,.141,.1816,1,1,.1097,.143,1,1,.082,.1087,1,1,.0606,.0818,1,1,.0449,.0616,1,1,.0335,.0467,1,1,.0253,.0357,1,1,.0193,.0276,1,1,.015,.0216,1,1,.0117,.0171,1,1,.0093,.0136,1,1,.0074,.011,1,1,.235,.2693,1,1,.2347,.269,1,1,.2304,.264,1,1,.2139,.2454,1,1,.1816,.2093,1,1,.143,.1663,1,1,.1087,.1278,1,1,.0818,.0973,1,1,.0616,.0741,1,1,.0467,.0567,1,1,.0357,.0438,1,1,.0276,.0341,1,1,.0216,.0269,1,1,.0171,.0214,1,1,.0136,.0172,1,1,.011,.014,1,1,.2693,.2924,1,1,.269,.292,1,1,.264,.2866,1,1,.2454,.2667,1,1,.2093,.2283,1,1,.1663,.1825,1,1,.1278,.1413,1,1,.0973,.1085,1,1,.0741,.0833,1,1,.0567,.0642,1,1,.0438,.0499,1,1,.0341,.0392,1,1,.0269,.031,1,1,.0214,.0248,1,1,.0172,.02,1,1,.014,.0163,1,1,.2924,.3072,1,1,.292,.3069,1,1,.2866,.3012,1,1,.2667,.2806,1,1,.2283,.2408,1,1,.1825,.1934,1,1,.1413,.1506,1,1,.1085,.1163,1,1,.0833,.0898,1,1,.0642,.0696,1,1,.0499,.0544,1,1,.0392,.0428,1,1,.031,.034,1,1,.0248,.0273,1,1,.02,.0221,1,1,.0163,.0181,1,1,.3072,.3158,1,1,.3069,.3154,1,1,.3012,.3097,1,1,.2806,.2887,1,1,.2408,.2483,1,1,.1934,.2,1,1,.1506,.1564,1,1,.1163,.1212,1,1,.0898,.094,1,1,.0696,.0732,1,1,.0544,.0574,1,1,.0428,.0453,1,1,.034,.0361,1,1,.0273,.0291,1,1,.0221,.0236,1,1,.0181,.0193,1,1,.3158,.3191,1,1,.3154,.3188,1,1,.3097,.313,1,1,.2887,.292,1,1,.2483,.2514,1,1,.2,.203,1,1,.1564,.1591,1,1,.1212,.1237,1,1,.094,.0962,1,1,.0732,.0751,1,1,.0574,.059,1,1,.0453,.0468,1,1,.0361,.0374,1,1,.0291,.0301,1,1,.0236,.0245,1,1,.0193,.0201,1,1,.3191,.318,1,1,.3188,.3176,1,1,.313,.3119,1,1,.292,.2911,1,1,.2514,.2508,1,1,.203,.2028,1,1,.1591,.1592,1,1,.1237,.124,1,1,.0962,.0967,1,1,.0751,.0756,1,1,.059,.0595,1,1,.0468,.0472,1,1,.0374,.0378,1,1,.0301,.0305,1,1,.0245,.0248,1,1,.0201,.0204,1,1,.318,.3128,1,1,.3176,.3124,1,1,.3119,.3068,1,1,.2911,.2864,1,1,.2508,.2469,1,1,.2028,.1997,1,1,.1592,.1569,1,1,.124,.1223,1,1,.0967,.0954,1,1,.0756,.0747,1,1,.0595,.0589,1,1,.0472,.0467,1,1,.0378,.0374,1,1,.0305,.0302,1,1,.0248,.0246,1,1,.0204,.0202,1,1,.3128,.3038,1,1,.3124,.3034,1,1,.3068,.298,1,1,.2864,.2782,1,1,.2469,.2398,1,1,.1997,.1939,1,1,.1569,.1523,1,1,.1223,.1187,1,1,.0954,.0926,1,1,.0747,.0725,1,1,.0589,.0572,1,1,.0467,.0454,1,1,.0374,.0364,1,1,.0302,.0294,1,1,.0246,.0239,1,1,.0202,.0197,1,1,.3038,.2911,1,1,.3034,.2908,1,1,.298,.2856,1,1,.2782,.2667,1,1,.2398,.2297,1,1,.1939,.1855,1,1,.1523,.1456,1,1,.1187,.1133,1,1,.0926,.0883,1,1,.0725,.0691,1,1,.0572,.0544,1,1,.0454,.0432,1,1,.0364,.0346,1,1,.0294,.028,1,1,.0239,.0228,1,1,.0197,.0187,1,1,.2911,.2747,1,1,.2908,.2744,1,1,.2856,.2696,1,1,.2667,.2517,1,1,.2297,.2166,1,1,.1855,.1745,1,1,.1456,.1366,1,1,.1133,.1061,1,1,.0883,.0825,1,1,.0691,.0645,1,1,.0544,.0507,1,1,.0432,.0402,1,1,.0346,.0322,1,1,.028,.026,1,1,.0228,.0212,1,1,.0187,.0174,1,1,.2747,.2546,1,1,.2744,.2544,1,1,.2696,.2499,1,1,.2517,.2332,1,1,.2166,.2004,1,1,.1745,.161,1,1,.1366,.1256,1,1,.1061,.0972,1,1,.0825,.0753,1,1,.0645,.0587,1,1,.0507,.0461,1,1,.0402,.0365,1,1,.0322,.0291,1,1,.026,.0235,1,1,.0212,.0191,1,1,.0174,.0157,1,1,.2546,.2306,1,1,.2544,.2304,1,1,.2499,.2264,1,1,.2332,.2112,1,1,.2004,.181,1,1,.161,.1448,1,1,.1256,.1123,1,1,.0972,.0864,1,1,.0753,.0667,1,1,.0587,.0517,1,1,.0461,.0404,1,1,.0365,.0319,1,1,.0291,.0254,1,1,.0235,.0204,1,1,.0191,.0166,1,1,.0157,.0136,1,1,.2306,.2025,1,1,.2304,.2023,1,1,.2264,.1988,1,1,.2112,.1853,1,1,.181,.1583,1,1,.1448,.1258,1,1,.1123,.0968,1,1,.0864,.0739,1,1,.0667,.0565,1,1,.0517,.0435,1,1,.0404,.0338,1,1,.0319,.0265,1,1,.0254,.021,1,1,.0204,.0168,1,1,.0166,.0136,1,1,.0136,.0111,1,1,1,0,.2121,1,.9999,0,.2119,1,.9976,.0047,.2095,1,.9854,.0224,.1999,1,.9564,.0638,.1784,1,.9163,.1289,.1472,1,.8792,.2046,.1149,1,.8508,.2736,.0871,1,.8274,.3262,.0653,1,.8038,.3603,.0489,1,.7767,.3787,.0368,1,.745,.3853,.0278,1,.7089,.3836,.0213,1,.6693,.3766,.0164,1,.6275,.3662,.0127,1,.5845,.3541,.01,1,0,.0521,1,1,0,.0521,1,1,0,.052,1,1,0,.0506,1,1,0,.0457,1,1,0,.0376,1,1,0,.0289,1,1,0,.0214,1,1,0,.0157,1,1,0,.0116,1,1,0,.0086,1,1,0,.0064,1,1,0,.0049,1,1,0,.0037,1,1,0,.0029,1,1,0,.0022,1,1,.0521,.106,1,1,.0521,.106,1,1,.052,.1053,1,1,.0506,.1013,1,1,.0457,.091,1,1,.0376,.0753,1,1,.0289,.0586,1,1,.0214,.0443,1,1,.0157,.0332,1,1,.0116,.0249,1,1,.0086,.0188,1,1,.0064,.0143,1,1,.0049,.011,1,1,.0037,.0085,1,1,.0029,.0067,1,1,.0022,.0053,1,1,.106,.1456,1,1,.106,.1456,1,1,.1053,.1443,1,1,.1013,.1385,1,1,.091,.1244,1,1,.0753,.1034,1,1,.0586,.0812,1,1,.0443,.0622,1,1,.0332,.0472,1,1,.0249,.0358,1,1,.0188,.0274,1,1,.0143,.021,1,1,.011,.0163,1,1,.0085,.0128,1,1,.0067,.0101,1,1,.0053,.008,1,1,.1456,.1742,1,1,.1456,.1741,1,1,.1443,.1724,1,1,.1385,.1653,1,1,.1244,.1486,1,1,.1034,.124,1,1,.0812,.0982,1,1,.0622,.0758,1,1,.0472,.058,1,1,.0358,.0445,1,1,.0274,.0342,1,1,.021,.0265,1,1,.0163,.0207,1,1,.0128,.0163,1,1,.0101,.0129,1,1,.008,.0103,1,1,.1742,.1944,1,1,.1741,.1943,1,1,.1724,.1924,1,1,.1653,.1843,1,1,.1486,.1659,1,1,.124,.1389,1,1,.0982,.1105,1,1,.0758,.0859,1,1,.058,.0662,1,1,.0445,.051,1,1,.0342,.0395,1,1,.0265,.0308,1,1,.0207,.0242,1,1,.0163,.0191,1,1,.0129,.0152,1,1,.0103,.0122,1,1,.1944,.2081,1,1,.1943,.208,1,1,.1924,.2059,1,1,.1843,.1973,1,1,.1659,.1778,1,1,.1389,.1492,1,1,.1105,.1192,1,1,.0859,.0931,1,1,.0662,.0721,1,1,.051,.0559,1,1,.0395,.0434,1,1,.0308,.034,1,1,.0242,.0267,1,1,.0191,.0212,1,1,.0152,.017,1,1,.0122,.0137,1,1,.2081,.2166,1,1,.208,.2164,1,1,.2059,.2142,1,1,.1973,.2053,1,1,.1778,.1851,1,1,.1492,.1557,1,1,.1192,.1248,1,1,.0931,.0978,1,1,.0721,.076,1,1,.0559,.0591,1,1,.0434,.0461,1,1,.034,.0362,1,1,.0267,.0286,1,1,.0212,.0227,1,1,.017,.0182,1,1,.0137,.0147,1,1,.2166,.2206,1,1,.2164,.2204,1,1,.2142,.2182,1,1,.2053,.2091,1,1,.1851,.1887,1,1,.1557,.1589,1,1,.1248,.1277,1,1,.0978,.1003,1,1,.076,.0782,1,1,.0591,.0609,1,1,.0461,.0477,1,1,.0362,.0375,1,1,.0286,.0296,1,1,.0227,.0236,1,1,.0182,.019,1,1,.0147,.0153,1,1,.2206,.2206,1,1,.2204,.2205,1,1,.2182,.2182,1,1,.2091,.2092,1,1,.1887,.1889,1,1,.1589,.1593,1,1,.1277,.1281,1,1,.1003,.1008,1,1,.0782,.0787,1,1,.0609,.0615,1,1,.0477,.0482,1,1,.0375,.0379,1,1,.0296,.0301,1,1,.0236,.024,1,1,.019,.0193,1,1,.0153,.0156,1,1,.2206,.2171,1,1,.2205,.2169,1,1,.2182,.2148,1,1,.2092,.206,1,1,.1889,.186,1,1,.1593,.1569,1,1,.1281,.1263,1,1,.1008,.0995,1,1,.0787,.0778,1,1,.0615,.0608,1,1,.0482,.0477,1,1,.0379,.0376,1,1,.0301,.0298,1,1,.024,.0238,1,1,.0193,.0191,1,1,.0156,.0155,1,1,.2171,.2102,1,1,.2169,.2101,1,1,.2148,.208,1,1,.206,.1996,1,1,.186,.1803,1,1,.1569,.1521,1,1,.1263,.1225,1,1,.0995,.0965,1,1,.0778,.0755,1,1,.0608,.059,1,1,.0477,.0463,1,1,.0376,.0365,1,1,.0298,.029,1,1,.0238,.0231,1,1,.0191,.0186,1,1,.0155,.0151,1,1,.2102,.2002,1,1,.2101,.2001,1,1,.208,.1982,1,1,.1996,.1902,1,1,.1803,.1718,1,1,.1521,.145,1,1,.1225,.1167,1,1,.0965,.0918,1,1,.0755,.0718,1,1,.059,.0561,1,1,.0463,.044,1,1,.0365,.0347,1,1,.029,.0276,1,1,.0231,.022,1,1,.0186,.0177,1,1,.0151,.0143,1,1,.2002,.1871,1,1,.2001,.187,1,1,.1982,.1852,1,1,.1902,.1778,1,1,.1718,.1606,1,1,.145,.1355,1,1,.1167,.1089,1,1,.0918,.0856,1,1,.0718,.0668,1,1,.0561,.0522,1,1,.044,.0409,1,1,.0347,.0322,1,1,.0276,.0256,1,1,.022,.0204,1,1,.0177,.0164,1,1,.0143,.0133,1,1,.1871,.1709,1,1,.187,.1708,1,1,.1852,.1692,1,1,.1778,.1625,1,1,.1606,.1468,1,1,.1355,.1236,1,1,.1089,.0992,1,1,.0856,.0778,1,1,.0668,.0606,1,1,.0522,.0472,1,1,.0409,.037,1,1,.0322,.0291,1,1,.0256,.023,1,1,.0204,.0184,1,1,.0164,.0148,1,1,.0133,.0119,1,1,.1709,.1515,1,1,.1708,.1514,1,1,.1692,.1501,1,1,.1625,.1442,1,1,.1468,.1303,1,1,.1236,.1095,1,1,.0992,.0876,1,1,.0778,.0684,1,1,.0606,.0531,1,1,.0472,.0412,1,1,.037,.0322,1,1,.0291,.0252,1,1,.023,.0199,1,1,.0184,.0159,1,1,.0148,.0127,1,1,.0119,.0103,1,1,.1515,.1289,1,1,.1514,.1288,1,1,.1501,.1278,1,1,.1442,.1229,1,1,.1303,.1109,1,1,.1095,.093,1,1,.0876,.074,1,1,.0684,.0575,1,1,.0531,.0443,1,1,.0412,.0342,1,1,.0322,.0265,1,1,.0252,.0207,1,1,.0199,.0163,1,1,.0159,.0129,1,1,.0127,.0103,1,1,.0103,.0083,1,1,1,0,.1317,1,1,0,.1317,1,.9985,.0025,.1311,1,.9904,.0121,.1277,1,.9694,.0356,.1186,1,.9343,.0766,.1026,1,.8935,.1309,.0831,1,.8558,.1889,.0644,1,.8226,.241,.0488,1,.7906,.2821,.0366,1,.7566,.3112,.0275,1,.7188,.3296,.0207,1,.6771,.3395,.0157,1,.6322,.343,.012,1,.5854,.342,.0092,1,.5379,.338,.0071,1,0,.0269,1,1,0,.0269,1,1,0,.0271,1,1,0,.027,1,1,0,.0257,1,1,0,.0226,1,1,0,.0184,1,1,0,.0142,1,1,0,.0107,1,1,0,.008,1,1,0,.006,1,1,0,.0045,1,1,0,.0034,1,1,0,.0026,1,1,0,.002,1,1,0,.0015,1,1,.0269,.0616,1,1,.0269,.0616,1,1,.0271,.0616,1,1,.027,.0606,1,1,.0257,.057,1,1,.0226,.0498,1,1,.0184,.0407,1,1,.0142,.0317,1,1,.0107,.0242,1,1,.008,.0183,1,1,.006,.0139,1,1,.0045,.0106,1,1,.0034,.0081,1,1,.0026,.0062,1,1,.002,.0048,1,1,.0015,.0038,1,1,.0616,.0901,1,1,.0616,.0901,1,1,.0616,.0899,1,1,.0606,.0881,1,1,.057,.0824,1,1,.0498,.072,1,1,.0407,.059,1,1,.0317,.0463,1,1,.0242,.0357,1,1,.0183,.0273,1,1,.0139,.0209,1,1,.0106,.016,1,1,.0081,.0124,1,1,.0062,.0096,1,1,.0048,.0075,1,1,.0038,.0059,1,1,.0901,.1121,1,1,.0901,.1121,1,1,.0899,.1117,1,1,.0881,.1092,1,1,.0824,.1019,1,1,.072,.0891,1,1,.059,.0733,1,1,.0463,.0579,1,1,.0357,.0449,1,1,.0273,.0346,1,1,.0209,.0266,1,1,.016,.0206,1,1,.0124,.016,1,1,.0096,.0125,1,1,.0075,.0098,1,1,.0059,.0078,1,1,.1121,.1286,1,1,.1121,.1285,1,1,.1117,.1279,1,1,.1092,.1249,1,1,.1019,.1165,1,1,.0891,.1019,1,1,.0733,.084,1,1,.0579,.0667,1,1,.0449,.052,1,1,.0346,.0402,1,1,.0266,.0311,1,1,.0206,.0242,1,1,.016,.0188,1,1,.0125,.0148,1,1,.0098,.0117,1,1,.0078,.0093,1,1,.1286,.1402,1,1,.1285,.1402,1,1,.1279,.1395,1,1,.1249,.136,1,1,.1165,.1269,1,1,.1019,.1111,1,1,.084,.0918,1,1,.0667,.0731,1,1,.052,.0572,1,1,.0402,.0444,1,1,.0311,.0345,1,1,.0242,.0269,1,1,.0188,.021,1,1,.0148,.0165,1,1,.0117,.0131,1,1,.0093,.0104,1,1,.1402,.1478,1,1,.1402,.1478,1,1,.1395,.147,1,1,.136,.1433,1,1,.1269,.1336,1,1,.1111,.1171,1,1,.0918,.097,1,1,.0731,.0774,1,1,.0572,.0607,1,1,.0444,.0473,1,1,.0345,.0369,1,1,.0269,.0288,1,1,.021,.0226,1,1,.0165,.0178,1,1,.0131,.0141,1,1,.0104,.0113,1,1,.1478,.1518,1,1,.1478,.1518,1,1,.147,.151,1,1,.1433,.1471,1,1,.1336,.1372,1,1,.1171,.1204,1,1,.097,.0998,1,1,.0774,.0798,1,1,.0607,.0628,1,1,.0473,.049,1,1,.0369,.0383,1,1,.0288,.03,1,1,.0226,.0235,1,1,.0178,.0186,1,1,.0141,.0148,1,1,.0113,.0118,1,1,.1518,.1526,1,1,.1518,.1526,1,1,.151,.1518,1,1,.1471,.1479,1,1,.1372,.138,1,1,.1204,.1211,1,1,.0998,.1005,1,1,.0798,.0805,1,1,.0628,.0634,1,1,.049,.0496,1,1,.0383,.0388,1,1,.03,.0304,1,1,.0235,.0239,1,1,.0186,.0189,1,1,.0148,.015,1,1,.0118,.012,1,1,.1526,.1505,1,1,.1526,.1505,1,1,.1518,.1497,1,1,.1479,.1459,1,1,.138,.1361,1,1,.1211,.1195,1,1,.1005,.0993,1,1,.0805,.0796,1,1,.0634,.0628,1,1,.0496,.0492,1,1,.0388,.0385,1,1,.0304,.0302,1,1,.0239,.0238,1,1,.0189,.0188,1,1,.015,.015,1,1,.012,.012,1,1,.1505,.1457,1,1,.1505,.1456,1,1,.1497,.1449,1,1,.1459,.1412,1,1,.1361,.1319,1,1,.1195,.1158,1,1,.0993,.0962,1,1,.0796,.0772,1,1,.0628,.0609,1,1,.0492,.0477,1,1,.0385,.0374,1,1,.0302,.0293,1,1,.0238,.0231,1,1,.0188,.0183,1,1,.015,.0146,1,1,.012,.0117,1,1,.1457,.1382,1,1,.1456,.1382,1,1,.1449,.1375,1,1,.1412,.1341,1,1,.1319,.1252,1,1,.1158,.11,1,1,.0962,.0914,1,1,.0772,.0733,1,1,.0609,.0579,1,1,.0477,.0453,1,1,.0374,.0355,1,1,.0293,.0279,1,1,.0231,.022,1,1,.0183,.0174,1,1,.0146,.0139,1,1,.0117,.0111,1,1,.1382,.1283,1,1,.1382,.1283,1,1,.1375,.1276,1,1,.1341,.1246,1,1,.1252,.1164,1,1,.11,.1023,1,1,.0914,.0849,1,1,.0733,.0681,1,1,.0579,.0537,1,1,.0453,.0421,1,1,.0355,.0329,1,1,.0279,.0258,1,1,.022,.0204,1,1,.0174,.0161,1,1,.0139,.0128,1,1,.0111,.0103,1,1,.1283,.1159,1,1,.1283,.1159,1,1,.1276,.1153,1,1,.1246,.1126,1,1,.1164,.1053,1,1,.1023,.0925,1,1,.0849,.0768,1,1,.0681,.0615,1,1,.0537,.0484,1,1,.0421,.0379,1,1,.0329,.0296,1,1,.0258,.0232,1,1,.0204,.0183,1,1,.0161,.0144,1,1,.0128,.0115,1,1,.0103,.0092,1,1,.1159,.101,1,1,.1159,.101,1,1,.1153,.1006,1,1,.1126,.0983,1,1,.1053,.092,1,1,.0925,.0808,1,1,.0768,.067,1,1,.0615,.0536,1,1,.0484,.042,1,1,.0379,.0328,1,1,.0296,.0256,1,1,.0232,.02,1,1,.0183,.0157,1,1,.0144,.0124,1,1,.0115,.0099,1,1,.0092,.0079,1,1,.101,.0837,1,1,.101,.0836,1,1,.1006,.0834,1,1,.0983,.0816,1,1,.092,.0765,1,1,.0808,.0672,1,1,.067,.0556,1,1,.0536,.0442,1,1,.042,.0346,1,1,.0328,.0269,1,1,.0256,.0209,1,1,.02,.0163,1,1,.0157,.0127,1,1,.0124,.01,1,1,.0099,.0079,1,1,.0079,.0063,1,1,1,0,.0778,1,1,0,.0778,1,.999,.0015,.0779,1,.9931,.0073,.0773,1,.9774,.022,.0743,1,.9481,.049,.0673,1,.9079,.0883,.0569,1,.8651,.1349,.0456,1,.8239,.182,.0352,1,.7839,.2242,.0267,1,.7427,.2585,.0201,1,.6986,.2844,.0152,1,.6513,.3026,.0114,1,.6014,.3144,.0087,1,.5501,.3212,.0066,1,.4989,.3243,.0051,1,0,.0143,1,1,0,.0143,1,1,0,.0144,1,1,0,.0146,1,1,0,.0144,1,1,0,.0134,1,1,0,.0115,1,1,0,.0093,1,1,0,.0072,1,1,0,.0055,1,1,0,.0041,1,1,0,.0031,1,1,0,.0024,1,1,0,.0018,1,1,0,.0014,1,1,0,.0011,1,1,.0143,.0359,1,1,.0143,.0359,1,1,.0144,.036,1,1,.0146,.0361,1,1,.0144,.035,1,1,.0134,.0321,1,1,.0115,.0275,1,1,.0093,.0223,1,1,.0072,.0174,1,1,.0055,.0134,1,1,.0041,.0102,1,1,.0031,.0078,1,1,.0024,.006,1,1,.0018,.0046,1,1,.0014,.0035,1,1,.0011,.0027,1,1,.0359,.0555,1,1,.0359,.0555,1,1,.036,.0556,1,1,.0361,.0553,1,1,.035,.0533,1,1,.0321,.0486,1,1,.0275,.0416,1,1,.0223,.0338,1,1,.0174,.0266,1,1,.0134,.0206,1,1,.0102,.0158,1,1,.0078,.0121,1,1,.006,.0094,1,1,.0046,.0072,1,1,.0035,.0056,1,1,.0027,.0044,1,1,.0555,.0716,1,1,.0555,.0716,1,1,.0556,.0716,1,1,.0553,.071,1,1,.0533,.0682,1,1,.0486,.0621,1,1,.0416,.0531,1,1,.0338,.0432,1,1,.0266,.0341,1,1,.0206,.0266,1,1,.0158,.0205,1,1,.0121,.0159,1,1,.0094,.0123,1,1,.0072,.0095,1,1,.0056,.0074,1,1,.0044,.0058,1,1,.0716,.0842,1,1,.0716,.0842,1,1,.0716,.0841,1,1,.071,.0832,1,1,.0682,.0797,1,1,.0621,.0725,1,1,.0531,.062,1,1,.0432,.0506,1,1,.0341,.0401,1,1,.0266,.0313,1,1,.0205,.0243,1,1,.0159,.0189,1,1,.0123,.0147,1,1,.0095,.0114,1,1,.0074,.0089,1,1,.0058,.007,1,1,.0842,.0935,1,1,.0842,.0935,1,1,.0841,.0934,1,1,.0832,.0922,1,1,.0797,.0883,1,1,.0725,.0802,1,1,.062,.0687,1,1,.0506,.0562,1,1,.0401,.0446,1,1,.0313,.035,1,1,.0243,.0272,1,1,.0189,.0212,1,1,.0147,.0165,1,1,.0114,.0129,1,1,.0089,.0101,1,1,.007,.008,1,1,.0935,.0998,1,1,.0935,.0998,1,1,.0934,.0997,1,1,.0922,.0983,1,1,.0883,.0941,1,1,.0802,.0854,1,1,.0687,.0732,1,1,.0562,.06,1,1,.0446,.0478,1,1,.035,.0375,1,1,.0272,.0293,1,1,.0212,.0228,1,1,.0165,.0178,1,1,.0129,.014,1,1,.0101,.011,1,1,.008,.0087,1,1,.0998,.1035,1,1,.0998,.1035,1,1,.0997,.1033,1,1,.0983,.1018,1,1,.0941,.0974,1,1,.0854,.0884,1,1,.0732,.0759,1,1,.06,.0622,1,1,.0478,.0496,1,1,.0375,.039,1,1,.0293,.0305,1,1,.0228,.0239,1,1,.0178,.0187,1,1,.014,.0146,1,1,.011,.0115,1,1,.0087,.0091,1,1,.1035,.1047,1,1,.1035,.1047,1,1,.1033,.1045,1,1,.1018,.103,1,1,.0974,.0984,1,1,.0884,.0894,1,1,.0759,.0767,1,1,.0622,.063,1,1,.0496,.0503,1,1,.039,.0396,1,1,.0305,.031,1,1,.0239,.0243,1,1,.0187,.019,1,1,.0146,.0149,1,1,.0115,.0118,1,1,.0091,.0093,1,1,.1047,.1036,1,1,.1047,.1036,1,1,.1045,.1034,1,1,.103,.1019,1,1,.0984,.0974,1,1,.0894,.0885,1,1,.0767,.076,1,1,.063,.0624,1,1,.0503,.0499,1,1,.0396,.0394,1,1,.031,.0309,1,1,.0243,.0242,1,1,.019,.0189,1,1,.0149,.0149,1,1,.0118,.0117,1,1,.0093,.0093,1,1,.1036,.1004,1,1,.1036,.1004,1,1,.1034,.1001,1,1,.1019,.0987,1,1,.0974,.0944,1,1,.0885,.0858,1,1,.076,.0737,1,1,.0624,.0606,1,1,.0499,.0484,1,1,.0394,.0382,1,1,.0309,.03,1,1,.0242,.0235,1,1,.0189,.0184,1,1,.0149,.0145,1,1,.0117,.0114,1,1,.0093,.0091,1,1,.1004,.0951,1,1,.1004,.0951,1,1,.1001,.0949,1,1,.0987,.0936,1,1,.0944,.0895,1,1,.0858,.0814,1,1,.0737,.0699,1,1,.0606,.0575,1,1,.0484,.046,1,1,.0382,.0363,1,1,.03,.0285,1,1,.0235,.0223,1,1,.0184,.0175,1,1,.0145,.0138,1,1,.0114,.0109,1,1,.0091,.0086,1,1,.0951,.0879,1,1,.0951,.0879,1,1,.0949,.0877,1,1,.0936,.0865,1,1,.0895,.0828,1,1,.0814,.0753,1,1,.0699,.0648,1,1,.0575,.0532,1,1,.046,.0426,1,1,.0363,.0336,1,1,.0285,.0263,1,1,.0223,.0206,1,1,.0175,.0162,1,1,.0138,.0127,1,1,.0109,.0101,1,1,.0086,.008,1,1,.0879,.0787,1,1,.0879,.0787,1,1,.0877,.0786,1,1,.0865,.0776,1,1,.0828,.0744,1,1,.0753,.0677,1,1,.0648,.0582,1,1,.0532,.0478,1,1,.0426,.0382,1,1,.0336,.0301,1,1,.0263,.0236,1,1,.0206,.0185,1,1,.0162,.0145,1,1,.0127,.0114,1,1,.0101,.009,1,1,.008,.0071,1,1,.0787,.0677,1,1,.0787,.0677,1,1,.0786,.0677,1,1,.0776,.0669,1,1,.0744,.0642,1,1,.0677,.0585,1,1,.0582,.0503,1,1,.0478,.0413,1,1,.0382,.0329,1,1,.0301,.0259,1,1,.0236,.0203,1,1,.0185,.0158,1,1,.0145,.0124,1,1,.0114,.0097,1,1,.009,.0077,1,1,.0071,.0061,1,1,.0677,.0549,1,1,.0677,.0549,1,1,.0677,.0549,1,1,.0669,.0543,1,1,.0642,.0523,1,1,.0585,.0477,1,1,.0503,.041,1,1,.0413,.0336,1,1,.0329,.0267,1,1,.0259,.021,1,1,.0203,.0164,1,1,.0158,.0127,1,1,.0124,.0099,1,1,.0097,.0078,1,1,.0077,.0061,1,1,.0061,.0048,1,1,1,0,.0432,1,1,0,.0432,1,.9992,.001,.0435,1,.9947,.0048,.044,1,.9826,.0145,.0437,1,.9582,.0333,.0415,1,.9208,.0622,.0368,1,.876,.0993,.0307,1,.8291,.1403,.0244,1,.7818,.1806,.0189,1,.7336,.2168,.0144,1,.6832,.2471,.0109,1,.6303,.2712,.0082,1,.5755,.2895,.0062,1,.5201,.3029,.0047,1,.4656,.3123,.0036,1,0,.0077,1,1,0,.0077,1,1,0,.0078,1,1,0,.008,1,1,0,.0081,1,1,0,.0079,1,1,0,.0071,1,1,0,.006,1,1,0,.0048,1,1,0,.0038,1,1,0,.0029,1,1,0,.0022,1,1,0,.0017,1,1,0,.0013,1,1,0,.001,1,1,0,7e-4,1,1,.0077,.0209,1,1,.0077,.0209,1,1,.0078,.021,1,1,.008,.0213,1,1,.0081,.0212,1,1,.0079,.0202,1,1,.0071,.0181,1,1,.006,.0153,1,1,.0048,.0123,1,1,.0038,.0096,1,1,.0029,.0074,1,1,.0022,.0057,1,1,.0017,.0044,1,1,.0013,.0034,1,1,.001,.0026,1,1,7e-4,.002,1,1,.0209,.0338,1,1,.0209,.0339,1,1,.021,.034,1,1,.0213,.0342,1,1,.0212,.0338,1,1,.0202,.032,1,1,.0181,.0285,1,1,.0153,.024,1,1,.0123,.0194,1,1,.0096,.0152,1,1,.0074,.0118,1,1,.0057,.0091,1,1,.0044,.007,1,1,.0034,.0054,1,1,.0026,.0042,1,1,.002,.0033,1,1,.0338,.0451,1,1,.0339,.0451,1,1,.034,.0453,1,1,.0342,.0453,1,1,.0338,.0446,1,1,.032,.042,1,1,.0285,.0373,1,1,.024,.0314,1,1,.0194,.0254,1,1,.0152,.0201,1,1,.0118,.0157,1,1,.0091,.0121,1,1,.007,.0094,1,1,.0054,.0073,1,1,.0042,.0056,1,1,.0033,.0044,1,1,.0451,.0543,1,1,.0451,.0543,1,1,.0453,.0544,1,1,.0453,.0544,1,1,.0446,.0533,1,1,.042,.05,1,1,.0373,.0445,1,1,.0314,.0374,1,1,.0254,.0304,1,1,.0201,.024,1,1,.0157,.0188,1,1,.0121,.0146,1,1,.0094,.0113,1,1,.0073,.0088,1,1,.0056,.0069,1,1,.0044,.0054,1,1,.0543,.0613,1,1,.0543,.0614,1,1,.0544,.0614,1,1,.0544,.0613,1,1,.0533,.0599,1,1,.05,.0562,1,1,.0445,.0499,1,1,.0374,.042,1,1,.0304,.0341,1,1,.024,.0271,1,1,.0188,.0212,1,1,.0146,.0165,1,1,.0113,.0129,1,1,.0088,.01,1,1,.0069,.0078,1,1,.0054,.0061,1,1,.0613,.0664,1,1,.0614,.0664,1,1,.0614,.0664,1,1,.0613,.0662,1,1,.0599,.0646,1,1,.0562,.0605,1,1,.0499,.0537,1,1,.042,.0453,1,1,.0341,.0368,1,1,.0271,.0293,1,1,.0212,.023,1,1,.0165,.0179,1,1,.0129,.014,1,1,.01,.0109,1,1,.0078,.0085,1,1,.0061,.0067,1,1,.0664,.0695,1,1,.0664,.0695,1,1,.0664,.0695,1,1,.0662,.0692,1,1,.0646,.0675,1,1,.0605,.0632,1,1,.0537,.056,1,1,.0453,.0473,1,1,.0368,.0385,1,1,.0293,.0306,1,1,.023,.0241,1,1,.0179,.0188,1,1,.014,.0147,1,1,.0109,.0115,1,1,.0085,.009,1,1,.0067,.0071,1,1,.0695,.0707,1,1,.0695,.0707,1,1,.0695,.0708,1,1,.0692,.0704,1,1,.0675,.0686,1,1,.0632,.0642,1,1,.056,.057,1,1,.0473,.0481,1,1,.0385,.0392,1,1,.0306,.0312,1,1,.0241,.0246,1,1,.0188,.0192,1,1,.0147,.015,1,1,.0115,.0118,1,1,.009,.0092,1,1,.0071,.0072,1,1,.0707,.0703,1,1,.0707,.0703,1,1,.0708,.0703,1,1,.0704,.0699,1,1,.0686,.0682,1,1,.0642,.0638,1,1,.057,.0566,1,1,.0481,.0478,1,1,.0392,.0389,1,1,.0312,.0311,1,1,.0246,.0245,1,1,.0192,.0192,1,1,.015,.015,1,1,.0118,.0117,1,1,.0092,.0092,1,1,.0072,.0072,1,1,.0703,.0683,1,1,.0703,.0683,1,1,.0703,.0683,1,1,.0699,.0679,1,1,.0682,.0662,1,1,.0638,.0619,1,1,.0566,.0549,1,1,.0478,.0464,1,1,.0389,.0378,1,1,.0311,.0302,1,1,.0245,.0238,1,1,.0192,.0187,1,1,.015,.0146,1,1,.0117,.0114,1,1,.0092,.009,1,1,.0072,.0071,1,1,.0683,.0647,1,1,.0683,.0647,1,1,.0683,.0647,1,1,.0679,.0644,1,1,.0662,.0627,1,1,.0619,.0587,1,1,.0549,.0521,1,1,.0464,.044,1,1,.0378,.0359,1,1,.0302,.0287,1,1,.0238,.0226,1,1,.0187,.0177,1,1,.0146,.0139,1,1,.0114,.0109,1,1,.009,.0085,1,1,.0071,.0067,1,1,.0647,.0596,1,1,.0647,.0596,1,1,.0647,.0597,1,1,.0644,.0594,1,1,.0627,.0579,1,1,.0587,.0542,1,1,.0521,.0481,1,1,.044,.0407,1,1,.0359,.0332,1,1,.0287,.0265,1,1,.0226,.0209,1,1,.0177,.0164,1,1,.0139,.0128,1,1,.0109,.01,1,1,.0085,.0079,1,1,.0067,.0062,1,1,.0596,.0531,1,1,.0596,.0531,1,1,.0597,.0532,1,1,.0594,.053,1,1,.0579,.0517,1,1,.0542,.0484,1,1,.0481,.043,1,1,.0407,.0364,1,1,.0332,.0297,1,1,.0265,.0237,1,1,.0209,.0187,1,1,.0164,.0146,1,1,.0128,.0114,1,1,.01,.009,1,1,.0079,.007,1,1,.0062,.0055,1,1,.0531,.0452,1,1,.0531,.0453,1,1,.0532,.0453,1,1,.053,.0452,1,1,.0517,.0442,1,1,.0484,.0415,1,1,.043,.0369,1,1,.0364,.0312,1,1,.0297,.0254,1,1,.0237,.0202,1,1,.0187,.0159,1,1,.0146,.0125,1,1,.0114,.0098,1,1,.009,.0076,1,1,.007,.006,1,1,.0055,.0047,1,1,.0452,.036,1,1,.0453,.036,1,1,.0453,.0361,1,1,.0452,.036,1,1,.0442,.0353,1,1,.0415,.0333,1,1,.0369,.0296,1,1,.0312,.025,1,1,.0254,.0204,1,1,.0202,.0162,1,1,.0159,.0127,1,1,.0125,.0099,1,1,.0098,.0078,1,1,.0076,.0061,1,1,.006,.0047,1,1,.0047,.0037,1,1,1,0,.0221,1,1,0,.0222,1,.9995,7e-4,.0225,1,.9958,.0033,.0232,1,.986,.0102,.0239,1,.9656,.0237,.0238,1,.9316,.0454,.0224,1,.8869,.075,.0196,1,.8363,.1101,.0162,1,.7831,.1473,.0128,1,.7282,.1833,.0099,1,.6715,.216,.0076,1,.613,.2442,.0057,1,.5535,.2676,.0043,1,.4942,.2866,.0033,1,.4368,.3017,.0025,1,0,.0042,1,1,0,.0042,1,1,0,.0042,1,1,0,.0044,1,1,0,.0045,1,1,0,.0046,1,1,0,.0043,1,1,0,.0038,1,1,0,.0032,1,1,0,.0025,1,1,0,.002,1,1,0,.0015,1,1,0,.0012,1,1,0,9e-4,1,1,0,7e-4,1,1,0,5e-4,1,1,.0042,.012,1,1,.0042,.012,1,1,.0042,.0122,1,1,.0044,.0124,1,1,.0045,.0126,1,1,.0046,.0125,1,1,.0043,.0116,1,1,.0038,.0102,1,1,.0032,.0085,1,1,.0025,.0068,1,1,.002,.0054,1,1,.0015,.0041,1,1,.0012,.0032,1,1,9e-4,.0025,1,1,7e-4,.0019,1,1,5e-4,.0015,1,1,.012,.0203,1,1,.012,.0203,1,1,.0122,.0205,1,1,.0124,.0208,1,1,.0126,.0209,1,1,.0125,.0205,1,1,.0116,.019,1,1,.0102,.0166,1,1,.0085,.0138,1,1,.0068,.0111,1,1,.0054,.0087,1,1,.0041,.0068,1,1,.0032,.0053,1,1,.0025,.0041,1,1,.0019,.0031,1,1,.0015,.0024,1,1,.0203,.0279,1,1,.0203,.0279,1,1,.0205,.028,1,1,.0208,.0283,1,1,.0209,.0284,1,1,.0205,.0276,1,1,.019,.0255,1,1,.0166,.0222,1,1,.0138,.0185,1,1,.0111,.0149,1,1,.0087,.0118,1,1,.0068,.0092,1,1,.0053,.0071,1,1,.0041,.0055,1,1,.0031,.0043,1,1,.0024,.0033,1,1,.0279,.0342,1,1,.0279,.0343,1,1,.028,.0344,1,1,.0283,.0347,1,1,.0284,.0346,1,1,.0276,.0335,1,1,.0255,.0309,1,1,.0222,.0269,1,1,.0185,.0224,1,1,.0149,.0181,1,1,.0118,.0143,1,1,.0092,.0112,1,1,.0071,.0087,1,1,.0055,.0067,1,1,.0043,.0052,1,1,.0033,.0041,1,1,.0342,.0393,1,1,.0343,.0394,1,1,.0344,.0395,1,1,.0347,.0397,1,1,.0346,.0396,1,1,.0335,.0382,1,1,.0309,.0351,1,1,.0269,.0306,1,1,.0224,.0255,1,1,.0181,.0206,1,1,.0143,.0163,1,1,.0112,.0128,1,1,.0087,.0099,1,1,.0067,.0077,1,1,.0052,.006,1,1,.0041,.0047,1,1,.0393,.0431,1,1,.0394,.0431,1,1,.0395,.0433,1,1,.0397,.0434,1,1,.0396,.0432,1,1,.0382,.0416,1,1,.0351,.0381,1,1,.0306,.0332,1,1,.0255,.0277,1,1,.0206,.0224,1,1,.0163,.0178,1,1,.0128,.0139,1,1,.0099,.0109,1,1,.0077,.0085,1,1,.006,.0066,1,1,.0047,.0051,1,1,.0431,.0455,1,1,.0431,.0455,1,1,.0433,.0457,1,1,.0434,.0458,1,1,.0432,.0455,1,1,.0416,.0437,1,1,.0381,.0401,1,1,.0332,.0349,1,1,.0277,.0291,1,1,.0224,.0236,1,1,.0178,.0187,1,1,.0139,.0147,1,1,.0109,.0115,1,1,.0085,.009,1,1,.0066,.007,1,1,.0051,.0055,1,1,.0455,.0467,1,1,.0455,.0467,1,1,.0457,.0468,1,1,.0458,.047,1,1,.0455,.0465,1,1,.0437,.0447,1,1,.0401,.041,1,1,.0349,.0357,1,1,.0291,.0298,1,1,.0236,.0241,1,1,.0187,.0192,1,1,.0147,.0151,1,1,.0115,.0118,1,1,.009,.0092,1,1,.007,.0072,1,1,.0055,.0056,1,1,.0467,.0466,1,1,.0467,.0467,1,1,.0468,.0468,1,1,.047,.0469,1,1,.0465,.0464,1,1,.0447,.0446,1,1,.041,.0409,1,1,.0357,.0356,1,1,.0298,.0297,1,1,.0241,.024,1,1,.0192,.0191,1,1,.0151,.015,1,1,.0118,.0118,1,1,.0092,.0092,1,1,.0072,.0072,1,1,.0056,.0056,1,1,.0466,.0454,1,1,.0467,.0454,1,1,.0468,.0456,1,1,.0469,.0456,1,1,.0464,.0452,1,1,.0446,.0434,1,1,.0409,.0398,1,1,.0356,.0346,1,1,.0297,.0289,1,1,.024,.0234,1,1,.0191,.0186,1,1,.015,.0147,1,1,.0118,.0115,1,1,.0092,.009,1,1,.0072,.007,1,1,.0056,.0055,1,1,.0454,.0431,1,1,.0454,.0431,1,1,.0456,.0432,1,1,.0456,.0433,1,1,.0452,.0429,1,1,.0434,.0412,1,1,.0398,.0377,1,1,.0346,.0329,1,1,.0289,.0274,1,1,.0234,.0222,1,1,.0186,.0177,1,1,.0147,.0139,1,1,.0115,.0109,1,1,.009,.0085,1,1,.007,.0067,1,1,.0055,.0052,1,1,.0431,.0397,1,1,.0431,.0397,1,1,.0432,.0398,1,1,.0433,.0399,1,1,.0429,.0395,1,1,.0412,.038,1,1,.0377,.0348,1,1,.0329,.0303,1,1,.0274,.0253,1,1,.0222,.0205,1,1,.0177,.0163,1,1,.0139,.0129,1,1,.0109,.0101,1,1,.0085,.0079,1,1,.0067,.0062,1,1,.0052,.0048,1,1,.0397,.0352,1,1,.0397,.0353,1,1,.0398,.0354,1,1,.0399,.0355,1,1,.0395,.0352,1,1,.038,.0338,1,1,.0348,.031,1,1,.0303,.027,1,1,.0253,.0226,1,1,.0205,.0183,1,1,.0163,.0146,1,1,.0129,.0115,1,1,.0101,.009,1,1,.0079,.007,1,1,.0062,.0055,1,1,.0048,.0043,1,1,.0352,.0298,1,1,.0353,.0298,1,1,.0354,.0299,1,1,.0355,.03,1,1,.0352,.0298,1,1,.0338,.0287,1,1,.031,.0264,1,1,.027,.023,1,1,.0226,.0192,1,1,.0183,.0156,1,1,.0146,.0124,1,1,.0115,.0097,1,1,.009,.0076,1,1,.007,.006,1,1,.0055,.0046,1,1,.0043,.0036,1,1,.0298,.0234,1,1,.0298,.0234,1,1,.0299,.0235,1,1,.03,.0236,1,1,.0298,.0235,1,1,.0287,.0227,1,1,.0264,.0209,1,1,.023,.0183,1,1,.0192,.0152,1,1,.0156,.0123,1,1,.0124,.0098,1,1,.0097,.0077,1,1,.0076,.006,1,1,.006,.0047,1,1,.0046,.0037,1,1,.0036,.0029,1,1,1,0,.0102,1,1,0,.0103,1,.9998,4e-4,.0105,1,.9965,.0024,.0111,1,.9884,.0074,.012,1,.971,.0175,.0127,1,.9404,.0342,.0126,1,.8971,.058,.0117,1,.8446,.0879,.0101,1,.7867,.1215,.0083,1,.7258,.1562,.0066,1,.6629,.1898,.0051,1,.5988,.2207,.0039,1,.5345,.2482,.003,1,.4716,.2719,.0022,1,.4115,.2922,.0017,1,0,.0022,1,1,0,.0022,1,1,0,.0023,1,1,0,.0024,1,1,0,.0025,1,1,0,.0026,1,1,0,.0026,1,1,0,.0024,1,1,0,.002,1,1,0,.0017,1,1,0,.0013,1,1,0,.0011,1,1,0,8e-4,1,1,0,6e-4,1,1,0,5e-4,1,1,0,4e-4,1,1,.0022,.0068,1,1,.0022,.0068,1,1,.0023,.0069,1,1,.0024,.0071,1,1,.0025,.0073,1,1,.0026,.0075,1,1,.0026,.0073,1,1,.0024,.0066,1,1,.002,.0057,1,1,.0017,.0047,1,1,.0013,.0038,1,1,.0011,.003,1,1,8e-4,.0023,1,1,6e-4,.0018,1,1,5e-4,.0014,1,1,4e-4,.0011,1,1,.0068,.0118,1,1,.0068,.0119,1,1,.0069,.012,1,1,.0071,.0123,1,1,.0073,.0126,1,1,.0075,.0127,1,1,.0073,.0122,1,1,.0066,.0111,1,1,.0057,.0096,1,1,.0047,.0079,1,1,.0038,.0063,1,1,.003,.005,1,1,.0023,.0039,1,1,.0018,.003,1,1,.0014,.0023,1,1,.0011,.0018,1,1,.0118,.0167,1,1,.0119,.0167,1,1,.012,.0169,1,1,.0123,.0172,1,1,.0126,.0175,1,1,.0127,.0175,1,1,.0122,.0168,1,1,.0111,.0152,1,1,.0096,.0131,1,1,.0079,.0108,1,1,.0063,.0087,1,1,.005,.0068,1,1,.0039,.0053,1,1,.003,.0041,1,1,.0023,.0032,1,1,.0018,.0025,1,1,.0167,.0209,1,1,.0167,.0209,1,1,.0169,.0211,1,1,.0172,.0214,1,1,.0175,.0218,1,1,.0175,.0217,1,1,.0168,.0207,1,1,.0152,.0187,1,1,.0131,.0161,1,1,.0108,.0133,1,1,.0087,.0107,1,1,.0068,.0084,1,1,.0053,.0066,1,1,.0041,.0051,1,1,.0032,.004,1,1,.0025,.0031,1,1,.0209,.0244,1,1,.0209,.0244,1,1,.0211,.0246,1,1,.0214,.0249,1,1,.0218,.0252,1,1,.0217,.025,1,1,.0207,.0238,1,1,.0187,.0215,1,1,.0161,.0184,1,1,.0133,.0152,1,1,.0107,.0123,1,1,.0084,.0097,1,1,.0066,.0076,1,1,.0051,.0059,1,1,.004,.0046,1,1,.0031,.0036,1,1,.0244,.027,1,1,.0244,.027,1,1,.0246,.0273,1,1,.0249,.0276,1,1,.0252,.0278,1,1,.025,.0275,1,1,.0238,.0261,1,1,.0215,.0235,1,1,.0184,.0202,1,1,.0152,.0167,1,1,.0123,.0134,1,1,.0097,.0106,1,1,.0076,.0083,1,1,.0059,.0065,1,1,.0046,.0051,1,1,.0036,.0039,1,1,.027,.0288,1,1,.027,.0288,1,1,.0273,.029,1,1,.0276,.0293,1,1,.0278,.0296,1,1,.0275,.0292,1,1,.0261,.0277,1,1,.0235,.0249,1,1,.0202,.0214,1,1,.0167,.0177,1,1,.0134,.0142,1,1,.0106,.0113,1,1,.0083,.0089,1,1,.0065,.0069,1,1,.0051,.0054,1,1,.0039,.0042,1,1,.0288,.0298,1,1,.0288,.0298,1,1,.029,.03,1,1,.0293,.0303,1,1,.0296,.0305,1,1,.0292,.0301,1,1,.0277,.0284,1,1,.0249,.0256,1,1,.0214,.022,1,1,.0177,.0182,1,1,.0142,.0146,1,1,.0113,.0116,1,1,.0089,.0091,1,1,.0069,.0071,1,1,.0054,.0055,1,1,.0042,.0043,1,1,.0298,.0299,1,1,.0298,.0299,1,1,.03,.0301,1,1,.0303,.0304,1,1,.0305,.0306,1,1,.0301,.0301,1,1,.0284,.0285,1,1,.0256,.0256,1,1,.022,.022,1,1,.0182,.0182,1,1,.0146,.0147,1,1,.0116,.0116,1,1,.0091,.0091,1,1,.0071,.0071,1,1,.0055,.0056,1,1,.0043,.0043,1,1,.0299,.0293,1,1,.0299,.0293,1,1,.0301,.0294,1,1,.0304,.0297,1,1,.0306,.0299,1,1,.0301,.0294,1,1,.0285,.0278,1,1,.0256,.025,1,1,.022,.0214,1,1,.0182,.0177,1,1,.0147,.0143,1,1,.0116,.0114,1,1,.0091,.0089,1,1,.0071,.007,1,1,.0056,.0054,1,1,.0043,.0042,1,1,.0293,.0278,1,1,.0293,.0278,1,1,.0294,.028,1,1,.0297,.0282,1,1,.0299,.0284,1,1,.0294,.0279,1,1,.0278,.0264,1,1,.025,.0237,1,1,.0214,.0204,1,1,.0177,.0169,1,1,.0143,.0136,1,1,.0114,.0108,1,1,.0089,.0085,1,1,.007,.0066,1,1,.0054,.0052,1,1,.0042,.004,1,1,.0278,.0256,1,1,.0278,.0256,1,1,.028,.0258,1,1,.0282,.026,1,1,.0284,.0262,1,1,.0279,.0257,1,1,.0264,.0243,1,1,.0237,.0219,1,1,.0204,.0188,1,1,.0169,.0155,1,1,.0136,.0125,1,1,.0108,.01,1,1,.0085,.0078,1,1,.0066,.0061,1,1,.0052,.0048,1,1,.004,.0037,1,1,.0256,.0227,1,1,.0256,.0227,1,1,.0258,.0229,1,1,.026,.0231,1,1,.0262,.0232,1,1,.0257,.0229,1,1,.0243,.0216,1,1,.0219,.0195,1,1,.0188,.0167,1,1,.0155,.0138,1,1,.0125,.0112,1,1,.01,.0089,1,1,.0078,.007,1,1,.0061,.0054,1,1,.0048,.0042,1,1,.0037,.0033,1,1,.0227,.0191,1,1,.0227,.0191,1,1,.0229,.0193,1,1,.0231,.0194,1,1,.0232,.0196,1,1,.0229,.0193,1,1,.0216,.0183,1,1,.0195,.0165,1,1,.0167,.0142,1,1,.0138,.0117,1,1,.0112,.0095,1,1,.0089,.0075,1,1,.007,.0059,1,1,.0054,.0046,1,1,.0042,.0036,1,1,.0033,.0028,1,1,.0191,.0148,1,1,.0191,.0149,1,1,.0193,.015,1,1,.0194,.0151,1,1,.0196,.0153,1,1,.0193,.0151,1,1,.0183,.0144,1,1,.0165,.013,1,1,.0142,.0111,1,1,.0117,.0092,1,1,.0095,.0074,1,1,.0075,.0059,1,1,.0059,.0046,1,1,.0046,.0036,1,1,.0036,.0028,1,1,.0028,.0022,1,1,1,0,.0041,1,1,0,.0041,1,.9999,3e-4,.0043,1,.997,.0018,.0047,1,.9901,.0056,.0054,1,.9751,.0133,.0061,1,.9476,.0265,.0065,1,.9063,.0458,.0065,1,.8531,.0712,.0059,1,.7918,.1013,.0051,1,.7256,.1341,.0041,1,.6568,.1676,.0033,1,.5871,.2002,.0025,1,.5182,.2308,.0019,1,.4517,.2586,.0015,1,.3891,.2836,.0011,1,0,.0012,1,1,0,.0012,1,1,0,.0012,1,1,0,.0013,1,1,0,.0013,1,1,0,.0014,1,1,0,.0015,1,1,0,.0014,1,1,0,.0013,1,1,0,.0011,1,1,0,9e-4,1,1,0,7e-4,1,1,0,6e-4,1,1,0,4e-4,1,1,0,3e-4,1,1,0,3e-4,1,1,.0012,.0037,1,1,.0012,.0037,1,1,.0012,.0038,1,1,.0013,.0039,1,1,.0013,.0041,1,1,.0014,.0043,1,1,.0015,.0044,1,1,.0014,.0042,1,1,.0013,.0037,1,1,.0011,.0032,1,1,9e-4,.0026,1,1,7e-4,.0021,1,1,6e-4,.0016,1,1,4e-4,.0013,1,1,3e-4,.001,1,1,3e-4,8e-4,1,1,.0037,.0066,1,1,.0037,.0066,1,1,.0038,.0067,1,1,.0039,.0069,1,1,.0041,.0073,1,1,.0043,.0076,1,1,.0044,.0076,1,1,.0042,.0072,1,1,.0037,.0064,1,1,.0032,.0054,1,1,.0026,.0045,1,1,.0021,.0036,1,1,.0016,.0028,1,1,.0013,.0022,1,1,.001,.0017,1,1,8e-4,.0013,1,1,.0066,.0095,1,1,.0066,.0095,1,1,.0067,.0097,1,1,.0069,.0099,1,1,.0073,.0103,1,1,.0076,.0107,1,1,.0076,.0106,1,1,.0072,.01,1,1,.0064,.0089,1,1,.0054,.0076,1,1,.0045,.0062,1,1,.0036,.005,1,1,.0028,.0039,1,1,.0022,.0031,1,1,.0017,.0024,1,1,.0013,.0018,1,1,.0095,.0122,1,1,.0095,.0122,1,1,.0097,.0123,1,1,.0099,.0126,1,1,.0103,.0131,1,1,.0107,.0134,1,1,.0106,.0132,1,1,.01,.0124,1,1,.0089,.0111,1,1,.0076,.0094,1,1,.0062,.0077,1,1,.005,.0062,1,1,.0039,.0049,1,1,.0031,.0038,1,1,.0024,.003,1,1,.0018,.0023,1,1,.0122,.0144,1,1,.0122,.0144,1,1,.0123,.0146,1,1,.0126,.0149,1,1,.0131,.0154,1,1,.0134,.0157,1,1,.0132,.0154,1,1,.0124,.0145,1,1,.0111,.0129,1,1,.0094,.0109,1,1,.0077,.009,1,1,.0062,.0072,1,1,.0049,.0057,1,1,.0038,.0044,1,1,.003,.0035,1,1,.0023,.0027,1,1,.0144,.0161,1,1,.0144,.0162,1,1,.0146,.0163,1,1,.0149,.0166,1,1,.0154,.0171,1,1,.0157,.0174,1,1,.0154,.0171,1,1,.0145,.016,1,1,.0129,.0142,1,1,.0109,.0121,1,1,.009,.0099,1,1,.0072,.008,1,1,.0057,.0063,1,1,.0044,.0049,1,1,.0035,.0038,1,1,.0027,.003,1,1,.0161,.0174,1,1,.0162,.0174,1,1,.0163,.0176,1,1,.0166,.0179,1,1,.0171,.0184,1,1,.0174,.0186,1,1,.0171,.0183,1,1,.016,.0171,1,1,.0142,.0151,1,1,.0121,.0128,1,1,.0099,.0106,1,1,.008,.0085,1,1,.0063,.0067,1,1,.0049,.0053,1,1,.0038,.0041,1,1,.003,.0032,1,1,.0174,.0181,1,1,.0174,.0181,1,1,.0176,.0183,1,1,.0179,.0186,1,1,.0184,.019,1,1,.0186,.0193,1,1,.0183,.0189,1,1,.0171,.0176,1,1,.0151,.0156,1,1,.0128,.0133,1,1,.0106,.0109,1,1,.0085,.0087,1,1,.0067,.0069,1,1,.0053,.0054,1,1,.0041,.0042,1,1,.0032,.0033,1,1,.0181,.0183,1,1,.0181,.0183,1,1,.0183,.0184,1,1,.0186,.0188,1,1,.019,.0192,1,1,.0193,.0194,1,1,.0189,.019,1,1,.0176,.0177,1,1,.0156,.0157,1,1,.0133,.0133,1,1,.0109,.0109,1,1,.0087,.0088,1,1,.0069,.007,1,1,.0054,.0055,1,1,.0042,.0043,1,1,.0033,.0033,1,1,.0183,.0179,1,1,.0183,.0179,1,1,.0184,.0181,1,1,.0188,.0184,1,1,.0192,.0188,1,1,.0194,.019,1,1,.019,.0186,1,1,.0177,.0173,1,1,.0157,.0153,1,1,.0133,.013,1,1,.0109,.0107,1,1,.0088,.0086,1,1,.007,.0068,1,1,.0055,.0053,1,1,.0043,.0042,1,1,.0033,.0032,1,1,.0179,.0171,1,1,.0179,.0171,1,1,.0181,.0173,1,1,.0184,.0175,1,1,.0188,.0179,1,1,.019,.0181,1,1,.0186,.0177,1,1,.0173,.0165,1,1,.0153,.0146,1,1,.013,.0124,1,1,.0107,.0102,1,1,.0086,.0082,1,1,.0068,.0065,1,1,.0053,.0051,1,1,.0042,.004,1,1,.0032,.0031,1,1,.0171,.0158,1,1,.0171,.0158,1,1,.0173,.0159,1,1,.0175,.0162,1,1,.0179,.0165,1,1,.0181,.0167,1,1,.0177,.0163,1,1,.0165,.0152,1,1,.0146,.0135,1,1,.0124,.0114,1,1,.0102,.0094,1,1,.0082,.0075,1,1,.0065,.006,1,1,.0051,.0047,1,1,.004,.0037,1,1,.0031,.0029,1,1,.0158,.014,1,1,.0158,.014,1,1,.0159,.0141,1,1,.0162,.0143,1,1,.0165,.0147,1,1,.0167,.0148,1,1,.0163,.0145,1,1,.0152,.0135,1,1,.0135,.012,1,1,.0114,.0101,1,1,.0094,.0083,1,1,.0075,.0067,1,1,.006,.0053,1,1,.0047,.0042,1,1,.0037,.0033,1,1,.0029,.0025,1,1,.014,.0117,1,1,.014,.0117,1,1,.0141,.0118,1,1,.0143,.012,1,1,.0147,.0123,1,1,.0148,.0125,1,1,.0145,.0122,1,1,.0135,.0114,1,1,.012,.0101,1,1,.0101,.0086,1,1,.0083,.007,1,1,.0067,.0057,1,1,.0053,.0045,1,1,.0042,.0035,1,1,.0033,.0027,1,1,.0025,.0021,1,1,.0117,.009,1,1,.0117,.009,1,1,.0118,.0091,1,1,.012,.0093,1,1,.0123,.0095,1,1,.0125,.0097,1,1,.0122,.0095,1,1,.0114,.0089,1,1,.0101,.0079,1,1,.0086,.0067,1,1,.007,.0055,1,1,.0057,.0044,1,1,.0045,.0035,1,1,.0035,.0027,1,1,.0027,.0021,1,1,.0021,.0017,1,1,1,0,.0013,1,1,0,.0014,1,.9999,2e-4,.0014,1,.9974,.0014,.0017,1,.9913,.0043,.0021,1,.9783,.0104,.0026,1,.9534,.021,.003,1,.9143,.0369,.0033,1,.8615,.0585,.0032,1,.7979,.0852,.0029,1,.7271,.1159,.0024,1,.6528,.1487,.002,1,.5776,.1822,.0016,1,.504,.2151,.0012,1,.4339,.2465,9e-4,1,.3692,.2758,7e-4,1,0,6e-4,1,1,0,6e-4,1,1,0,6e-4,1,1,0,6e-4,1,1,0,7e-4,1,1,0,8e-4,1,1,0,8e-4,1,1,0,8e-4,1,1,0,8e-4,1,1,0,7e-4,1,1,0,6e-4,1,1,0,5e-4,1,1,0,4e-4,1,1,0,3e-4,1,1,0,2e-4,1,1,0,2e-4,1,1,6e-4,.0019,1,1,6e-4,.0019,1,1,6e-4,.0019,1,1,6e-4,.002,1,1,7e-4,.0022,1,1,8e-4,.0024,1,1,8e-4,.0025,1,1,8e-4,.0025,1,1,8e-4,.0023,1,1,7e-4,.0021,1,1,6e-4,.0017,1,1,5e-4,.0014,1,1,4e-4,.0011,1,1,3e-4,9e-4,1,1,2e-4,7e-4,1,1,2e-4,5e-4,1,1,.0019,.0035,1,1,.0019,.0035,1,1,.0019,.0035,1,1,.002,.0037,1,1,.0022,.0039,1,1,.0024,.0042,1,1,.0025,.0044,1,1,.0025,.0044,1,1,.0023,.0041,1,1,.0021,.0036,1,1,.0017,.003,1,1,.0014,.0025,1,1,.0011,.002,1,1,9e-4,.0016,1,1,7e-4,.0012,1,1,5e-4,9e-4,1,1,.0035,.0051,1,1,.0035,.0051,1,1,.0035,.0052,1,1,.0037,.0054,1,1,.0039,.0057,1,1,.0042,.0061,1,1,.0044,.0063,1,1,.0044,.0062,1,1,.0041,.0058,1,1,.0036,.0051,1,1,.003,.0043,1,1,.0025,.0035,1,1,.002,.0028,1,1,.0016,.0022,1,1,.0012,.0017,1,1,9e-4,.0013,1,1,.0051,.0066,1,1,.0051,.0066,1,1,.0052,.0067,1,1,.0054,.0069,1,1,.0057,.0073,1,1,.0061,.0078,1,1,.0063,.008,1,1,.0062,.0079,1,1,.0058,.0073,1,1,.0051,.0064,1,1,.0043,.0054,1,1,.0035,.0044,1,1,.0028,.0035,1,1,.0022,.0028,1,1,.0017,.0022,1,1,.0013,.0017,1,1,.0066,.0079,1,1,.0066,.0079,1,1,.0067,.008,1,1,.0069,.0083,1,1,.0073,.0087,1,1,.0078,.0092,1,1,.008,.0094,1,1,.0079,.0092,1,1,.0073,.0086,1,1,.0064,.0075,1,1,.0054,.0063,1,1,.0044,.0052,1,1,.0035,.0042,1,1,.0028,.0033,1,1,.0022,.0026,1,1,.0017,.002,1,1,.0079,.0089,1,1,.0079,.0089,1,1,.008,.0091,1,1,.0083,.0094,1,1,.0087,.0098,1,1,.0092,.0103,1,1,.0094,.0106,1,1,.0092,.0103,1,1,.0086,.0095,1,1,.0075,.0084,1,1,.0063,.0071,1,1,.0052,.0058,1,1,.0042,.0046,1,1,.0033,.0036,1,1,.0026,.0029,1,1,.002,.0022,1,1,.0089,.0097,1,1,.0089,.0097,1,1,.0091,.0098,1,1,.0094,.0101,1,1,.0098,.0106,1,1,.0103,.0111,1,1,.0106,.0114,1,1,.0103,.0111,1,1,.0095,.0102,1,1,.0084,.009,1,1,.0071,.0076,1,1,.0058,.0062,1,1,.0046,.0049,1,1,.0036,.0039,1,1,.0029,.0031,1,1,.0022,.0024,1,1,.0097,.0102,1,1,.0097,.0102,1,1,.0098,.0103,1,1,.0101,.0106,1,1,.0106,.0111,1,1,.0111,.0116,1,1,.0114,.0118,1,1,.0111,.0115,1,1,.0102,.0106,1,1,.009,.0093,1,1,.0076,.0078,1,1,.0062,.0064,1,1,.0049,.0051,1,1,.0039,.0041,1,1,.0031,.0032,1,1,.0024,.0025,1,1,.0102,.0103,1,1,.0102,.0103,1,1,.0103,.0105,1,1,.0106,.0108,1,1,.0111,.0113,1,1,.0116,.0117,1,1,.0118,.0119,1,1,.0115,.0116,1,1,.0106,.0107,1,1,.0093,.0094,1,1,.0078,.0079,1,1,.0064,.0065,1,1,.0051,.0052,1,1,.0041,.0041,1,1,.0032,.0032,1,1,.0025,.0025,1,1,.0103,.0102,1,1,.0103,.0102,1,1,.0105,.0103,1,1,.0108,.0106,1,1,.0113,.0111,1,1,.0117,.0115,1,1,.0119,.0117,1,1,.0116,.0114,1,1,.0107,.0105,1,1,.0094,.0092,1,1,.0079,.0077,1,1,.0065,.0063,1,1,.0052,.0051,1,1,.0041,.004,1,1,.0032,.0031,1,1,.0025,.0025,1,1,.0102,.0097,1,1,.0102,.0098,1,1,.0103,.0099,1,1,.0106,.0101,1,1,.0111,.0106,1,1,.0115,.011,1,1,.0117,.0112,1,1,.0114,.0108,1,1,.0105,.01,1,1,.0092,.0087,1,1,.0077,.0074,1,1,.0063,.006,1,1,.0051,.0048,1,1,.004,.0038,1,1,.0031,.003,1,1,.0025,.0023,1,1,.0097,.009,1,1,.0098,.009,1,1,.0099,.0091,1,1,.0101,.0094,1,1,.0106,.0098,1,1,.011,.0102,1,1,.0112,.0103,1,1,.0108,.01,1,1,.01,.0092,1,1,.0087,.0081,1,1,.0074,.0068,1,1,.006,.0056,1,1,.0048,.0045,1,1,.0038,.0035,1,1,.003,.0028,1,1,.0023,.0022,1,1,.009,.008,1,1,.009,.008,1,1,.0091,.0081,1,1,.0094,.0083,1,1,.0098,.0087,1,1,.0102,.009,1,1,.0103,.0091,1,1,.01,.0089,1,1,.0092,.0082,1,1,.0081,.0072,1,1,.0068,.006,1,1,.0056,.0049,1,1,.0045,.004,1,1,.0035,.0031,1,1,.0028,.0025,1,1,.0022,.0019,1,1,.008,.0067,1,1,.008,.0067,1,1,.0081,.0068,1,1,.0083,.007,1,1,.0087,.0073,1,1,.009,.0076,1,1,.0091,.0077,1,1,.0089,.0075,1,1,.0082,.0069,1,1,.0072,.006,1,1,.006,.0051,1,1,.0049,.0042,1,1,.004,.0033,1,1,.0031,.0026,1,1,.0025,.0021,1,1,.0019,.0016,1,1,.0067,.0051,1,1,.0067,.0051,1,1,.0068,.0052,1,1,.007,.0054,1,1,.0073,.0056,1,1,.0076,.0059,1,1,.0077,.0059,1,1,.0075,.0058,1,1,.0069,.0053,1,1,.006,.0047,1,1,.0051,.0039,1,1,.0042,.0032,1,1,.0033,.0026,1,1,.0026,.002,1,1,.0021,.0016,1,1,.0016,.0013,1,1,1,0,3e-4,1,1,0,3e-4,1,1,1e-4,4e-4,1,.9977,.001,5e-4,1,.9923,.0034,7e-4,1,.9807,.0083,.001,1,.9581,.0169,.0012,1,.9214,.0301,.0015,1,.8695,.0486,.0015,1,.8044,.0724,.0015,1,.7299,.1007,.0013,1,.6504,.1325,.0011,1,.5699,.1663,9e-4,1,.4916,.201,7e-4,1,.4181,.2353,6e-4,1,.3513,.2686,4e-4,1,0,3e-4,1,1,0,3e-4,1,1,0,3e-4,1,1,0,3e-4,1,1,0,3e-4,1,1,0,4e-4,1,1,0,4e-4,1,1,0,4e-4,1,1,0,4e-4,1,1,0,4e-4,1,1,0,4e-4,1,1,0,3e-4,1,1,0,2e-4,1,1,0,2e-4,1,1,0,2e-4,1,1,0,1e-4,1,1,3e-4,9e-4,1,1,3e-4,9e-4,1,1,3e-4,9e-4,1,1,3e-4,9e-4,1,1,3e-4,.001,1,1,4e-4,.0012,1,1,4e-4,.0013,1,1,4e-4,.0014,1,1,4e-4,.0014,1,1,4e-4,.0013,1,1,4e-4,.0011,1,1,3e-4,9e-4,1,1,2e-4,8e-4,1,1,2e-4,6e-4,1,1,2e-4,5e-4,1,1,1e-4,4e-4,1,1,9e-4,.0016,1,1,9e-4,.0016,1,1,9e-4,.0016,1,1,9e-4,.0018,1,1,.001,.0019,1,1,.0012,.0022,1,1,.0013,.0024,1,1,.0014,.0025,1,1,.0014,.0024,1,1,.0013,.0023,1,1,.0011,.002,1,1,9e-4,.0017,1,1,8e-4,.0014,1,1,6e-4,.0011,1,1,5e-4,9e-4,1,1,4e-4,7e-4,1,1,.0016,.0024,1,1,.0016,.0024,1,1,.0016,.0025,1,1,.0018,.0026,1,1,.0019,.0029,1,1,.0022,.0032,1,1,.0024,.0035,1,1,.0025,.0036,1,1,.0024,.0035,1,1,.0023,.0032,1,1,.002,.0028,1,1,.0017,.0024,1,1,.0014,.0019,1,1,.0011,.0016,1,1,9e-4,.0012,1,1,7e-4,.001,1,1,.0024,.0032,1,1,.0024,.0032,1,1,.0025,.0032,1,1,.0026,.0034,1,1,.0029,.0037,1,1,.0032,.0041,1,1,.0035,.0045,1,1,.0036,.0046,1,1,.0035,.0045,1,1,.0032,.0041,1,1,.0028,.0036,1,1,.0024,.003,1,1,.0019,.0025,1,1,.0016,.002,1,1,.0012,.0016,1,1,.001,.0012,1,1,.0032,.0038,1,1,.0032,.0038,1,1,.0032,.0039,1,1,.0034,.0041,1,1,.0037,.0045,1,1,.0041,.0049,1,1,.0045,.0053,1,1,.0046,.0055,1,1,.0045,.0053,1,1,.0041,.0049,1,1,.0036,.0043,1,1,.003,.0036,1,1,.0025,.0029,1,1,.002,.0023,1,1,.0016,.0019,1,1,.0012,.0015,1,1,.0038,.0044,1,1,.0038,.0044,1,1,.0039,.0045,1,1,.0041,.0047,1,1,.0045,.0051,1,1,.0049,.0056,1,1,.0053,.006,1,1,.0055,.0062,1,1,.0053,.006,1,1,.0049,.0055,1,1,.0043,.0048,1,1,.0036,.004,1,1,.0029,.0033,1,1,.0023,.0026,1,1,.0019,.0021,1,1,.0015,.0016,1,1,.0044,.0048,1,1,.0044,.0048,1,1,.0045,.0049,1,1,.0047,.0051,1,1,.0051,.0055,1,1,.0056,.0061,1,1,.006,.0065,1,1,.0062,.0066,1,1,.006,.0064,1,1,.0055,.0059,1,1,.0048,.0051,1,1,.004,.0043,1,1,.0033,.0035,1,1,.0026,.0028,1,1,.0021,.0022,1,1,.0016,.0018,1,1,.0048,.0051,1,1,.0048,.0051,1,1,.0049,.0052,1,1,.0051,.0054,1,1,.0055,.0058,1,1,.0061,.0064,1,1,.0065,.0068,1,1,.0066,.0069,1,1,.0064,.0067,1,1,.0059,.0061,1,1,.0051,.0054,1,1,.0043,.0045,1,1,.0035,.0037,1,1,.0028,.0029,1,1,.0022,.0023,1,1,.0018,.0018,1,1,.0051,.0052,1,1,.0051,.0052,1,1,.0052,.0053,1,1,.0054,.0055,1,1,.0058,.0059,1,1,.0064,.0065,1,1,.0068,.0069,1,1,.0069,.007,1,1,.0067,.0068,1,1,.0061,.0062,1,1,.0054,.0054,1,1,.0045,.0045,1,1,.0037,.0037,1,1,.0029,.003,1,1,.0023,.0024,1,1,.0018,.0018,1,1,.0052,.0051,1,1,.0052,.0051,1,1,.0053,.0052,1,1,.0055,.0055,1,1,.0059,.0059,1,1,.0065,.0064,1,1,.0069,.0068,1,1,.007,.0069,1,1,.0068,.0067,1,1,.0062,.0061,1,1,.0054,.0053,1,1,.0045,.0045,1,1,.0037,.0036,1,1,.003,.0029,1,1,.0024,.0023,1,1,.0018,.0018,1,1,.0051,.0049,1,1,.0051,.0049,1,1,.0052,.005,1,1,.0055,.0052,1,1,.0059,.0056,1,1,.0064,.0061,1,1,.0068,.0065,1,1,.0069,.0066,1,1,.0067,.0064,1,1,.0061,.0058,1,1,.0053,.0051,1,1,.0045,.0043,1,1,.0036,.0035,1,1,.0029,.0028,1,1,.0023,.0022,1,1,.0018,.0017,1,1,.0049,.0046,1,1,.0049,.0046,1,1,.005,.0046,1,1,.0052,.0049,1,1,.0056,.0052,1,1,.0061,.0056,1,1,.0065,.006,1,1,.0066,.0061,1,1,.0064,.0059,1,1,.0058,.0054,1,1,.0051,.0047,1,1,.0043,.0039,1,1,.0035,.0032,1,1,.0028,.0026,1,1,.0022,.002,1,1,.0017,.0016,1,1,.0046,.004,1,1,.0046,.0041,1,1,.0046,.0041,1,1,.0049,.0043,1,1,.0052,.0046,1,1,.0056,.005,1,1,.006,.0053,1,1,.0061,.0054,1,1,.0059,.0052,1,1,.0054,.0048,1,1,.0047,.0042,1,1,.0039,.0035,1,1,.0032,.0029,1,1,.0026,.0023,1,1,.002,.0018,1,1,.0016,.0014,1,1,.004,.0034,1,1,.0041,.0034,1,1,.0041,.0035,1,1,.0043,.0036,1,1,.0046,.0039,1,1,.005,.0042,1,1,.0053,.0045,1,1,.0054,.0045,1,1,.0052,.0044,1,1,.0048,.004,1,1,.0042,.0035,1,1,.0035,.0029,1,1,.0029,.0024,1,1,.0023,.0019,1,1,.0018,.0015,1,1,.0014,.0012,1,1,.0034,.0026,1,1,.0034,.0026,1,1,.0035,.0026,1,1,.0036,.0028,1,1,.0039,.003,1,1,.0042,.0032,1,1,.0045,.0034,1,1,.0045,.0035,1,1,.0044,.0034,1,1,.004,.0031,1,1,.0035,.0027,1,1,.0029,.0023,1,1,.0024,.0019,1,1,.0019,.0015,1,1,.0015,.0012,1,1,.0012,9e-4,1,1,1,0,0,1,1,0,0,1,1,0,1e-4,1,.9979,8e-4,1e-4,1,.993,.0028,2e-4,1,.9826,.0068,3e-4,1,.9619,.0139,4e-4,1,.9274,.025,6e-4,1,.8769,.0409,6e-4,1,.8112,.062,7e-4,1,.7337,.0881,6e-4,1,.6495,.1185,5e-4,1,.5637,.1522,5e-4,1,.4808,.1881,4e-4,1,.4039,.225,3e-4,1,.335,.2619,2e-4,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,2e-4,1,1,0,2e-4,1,1,0,2e-4,1,1,0,2e-4,1,1,0,2e-4,1,1,0,2e-4,1,1,0,2e-4,1,1,0,2e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,1e-4,3e-4,1,1,1e-4,3e-4,1,1,1e-4,3e-4,1,1,1e-4,4e-4,1,1,1e-4,4e-4,1,1,2e-4,5e-4,1,1,2e-4,6e-4,1,1,2e-4,7e-4,1,1,2e-4,7e-4,1,1,2e-4,7e-4,1,1,2e-4,7e-4,1,1,2e-4,6e-4,1,1,2e-4,5e-4,1,1,1e-4,4e-4,1,1,1e-4,3e-4,1,1,1e-4,3e-4,1,1,3e-4,6e-4,1,1,3e-4,6e-4,1,1,3e-4,6e-4,1,1,4e-4,7e-4,1,1,4e-4,8e-4,1,1,5e-4,.001,1,1,6e-4,.0011,1,1,7e-4,.0013,1,1,7e-4,.0013,1,1,7e-4,.0013,1,1,7e-4,.0012,1,1,6e-4,.001,1,1,5e-4,9e-4,1,1,4e-4,7e-4,1,1,3e-4,6e-4,1,1,3e-4,5e-4,1,1,6e-4,9e-4,1,1,6e-4,9e-4,1,1,6e-4,9e-4,1,1,7e-4,.001,1,1,8e-4,.0012,1,1,.001,.0014,1,1,.0011,.0017,1,1,.0013,.0019,1,1,.0013,.0019,1,1,.0013,.0019,1,1,.0012,.0017,1,1,.001,.0015,1,1,9e-4,.0013,1,1,7e-4,.001,1,1,6e-4,8e-4,1,1,5e-4,7e-4,1,1,9e-4,.0012,1,1,9e-4,.0012,1,1,9e-4,.0012,1,1,.001,.0014,1,1,.0012,.0016,1,1,.0014,.0019,1,1,.0017,.0022,1,1,.0019,.0024,1,1,.0019,.0025,1,1,.0019,.0024,1,1,.0017,.0022,1,1,.0015,.002,1,1,.0013,.0016,1,1,.001,.0013,1,1,8e-4,.0011,1,1,7e-4,9e-4,1,1,.0012,.0015,1,1,.0012,.0015,1,1,.0012,.0015,1,1,.0014,.0017,1,1,.0016,.0019,1,1,.0019,.0023,1,1,.0022,.0026,1,1,.0024,.0029,1,1,.0025,.003,1,1,.0024,.0029,1,1,.0022,.0027,1,1,.002,.0023,1,1,.0016,.002,1,1,.0013,.0016,1,1,.0011,.0013,1,1,9e-4,.001,1,1,.0015,.0017,1,1,.0015,.0017,1,1,.0015,.0018,1,1,.0017,.0019,1,1,.0019,.0022,1,1,.0023,.0026,1,1,.0026,.003,1,1,.0029,.0033,1,1,.003,.0034,1,1,.0029,.0033,1,1,.0027,.003,1,1,.0023,.0026,1,1,.002,.0022,1,1,.0016,.0018,1,1,.0013,.0015,1,1,.001,.0012,1,1,.0017,.0019,1,1,.0017,.0019,1,1,.0018,.0019,1,1,.0019,.0021,1,1,.0022,.0024,1,1,.0026,.0028,1,1,.003,.0032,1,1,.0033,.0036,1,1,.0034,.0037,1,1,.0033,.0036,1,1,.003,.0033,1,1,.0026,.0028,1,1,.0022,.0024,1,1,.0018,.002,1,1,.0015,.0016,1,1,.0012,.0012,1,1,.0019,.002,1,1,.0019,.002,1,1,.0019,.0021,1,1,.0021,.0022,1,1,.0024,.0025,1,1,.0028,.003,1,1,.0032,.0034,1,1,.0036,.0037,1,1,.0037,.0038,1,1,.0036,.0037,1,1,.0033,.0034,1,1,.0028,.003,1,1,.0024,.0025,1,1,.002,.002,1,1,.0016,.0016,1,1,.0012,.0013,1,1,.002,.002,1,1,.002,.0021,1,1,.0021,.0021,1,1,.0022,.0023,1,1,.0025,.0026,1,1,.003,.003,1,1,.0034,.0035,1,1,.0037,.0038,1,1,.0038,.0039,1,1,.0037,.0038,1,1,.0034,.0035,1,1,.003,.003,1,1,.0025,.0025,1,1,.002,.0021,1,1,.0016,.0017,1,1,.0013,.0013,1,1,.002,.002,1,1,.0021,.002,1,1,.0021,.0021,1,1,.0023,.0023,1,1,.0026,.0026,1,1,.003,.003,1,1,.0035,.0034,1,1,.0038,.0037,1,1,.0039,.0039,1,1,.0038,.0037,1,1,.0035,.0034,1,1,.003,.003,1,1,.0025,.0025,1,1,.0021,.002,1,1,.0017,.0016,1,1,.0013,.0013,1,1,.002,.002,1,1,.002,.002,1,1,.0021,.002,1,1,.0023,.0022,1,1,.0026,.0025,1,1,.003,.0029,1,1,.0034,.0033,1,1,.0037,.0036,1,1,.0039,.0037,1,1,.0037,.0036,1,1,.0034,.0033,1,1,.003,.0028,1,1,.0025,.0024,1,1,.002,.002,1,1,.0016,.0016,1,1,.0013,.0013,1,1,.002,.0018,1,1,.002,.0018,1,1,.002,.0019,1,1,.0022,.002,1,1,.0025,.0023,1,1,.0029,.0027,1,1,.0033,.003,1,1,.0036,.0033,1,1,.0037,.0034,1,1,.0036,.0033,1,1,.0033,.003,1,1,.0028,.0026,1,1,.0024,.0022,1,1,.002,.0018,1,1,.0016,.0015,1,1,.0013,.0012,1,1,.0018,.0016,1,1,.0018,.0016,1,1,.0019,.0017,1,1,.002,.0018,1,1,.0023,.002,1,1,.0027,.0024,1,1,.003,.0027,1,1,.0033,.0029,1,1,.0034,.003,1,1,.0033,.0029,1,1,.003,.0027,1,1,.0026,.0023,1,1,.0022,.002,1,1,.0018,.0016,1,1,.0015,.0013,1,1,.0012,.001,1,1,.0016,.0014,1,1,.0016,.0014,1,1,.0017,.0014,1,1,.0018,.0015,1,1,.002,.0017,1,1,.0024,.002,1,1,.0027,.0023,1,1,.0029,.0025,1,1,.003,.0025,1,1,.0029,.0025,1,1,.0027,.0022,1,1,.0023,.002,1,1,.002,.0016,1,1,.0016,.0013,1,1,.0013,.0011,1,1,.001,9e-4,1,1,.0014,.001,1,1,.0014,.001,1,1,.0014,.0011,1,1,.0015,.0012,1,1,.0017,.0013,1,1,.002,.0015,1,1,.0023,.0017,1,1,.0025,.0019,1,1,.0025,.002,1,1,.0025,.0019,1,1,.0022,.0017,1,1,.002,.0015,1,1,.0016,.0013,1,1,.0013,.001,1,1,.0011,8e-4,1,1,9e-4,7e-4,1,1,1,0,0,1,1,0,0,1,1,0,0,1,.998,6e-4,0,1,.9936,.0023,0,1,.9841,.0056,1e-4,1,.9651,.0115,1e-4,1,.9327,.021,2e-4,1,.8837,.0348,2e-4,1,.8179,.0535,2e-4,1,.7381,.0775,2e-4,1,.6497,.1064,2e-4,1,.5589,.1396,2e-4,1,.4713,.1763,2e-4,1,.3911,.2154,1e-4,1,.3203,.2557,1e-4,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,0,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,1e-4,2e-4,1,1,1e-4,2e-4,1,1,1e-4,3e-4,1,1,1e-4,3e-4,1,1,1e-4,3e-4,1,1,1e-4,3e-4,1,1,1e-4,3e-4,1,1,1e-4,3e-4,1,1,1e-4,2e-4,1,1,1e-4,2e-4,1,1,0,2e-4,1,1,1e-4,1e-4,1,1,1e-4,1e-4,1,1,1e-4,1e-4,1,1,1e-4,2e-4,1,1,1e-4,2e-4,1,1,2e-4,3e-4,1,1,2e-4,4e-4,1,1,3e-4,5e-4,1,1,3e-4,6e-4,1,1,3e-4,6e-4,1,1,3e-4,6e-4,1,1,3e-4,6e-4,1,1,3e-4,5e-4,1,1,2e-4,4e-4,1,1,2e-4,4e-4,1,1,2e-4,3e-4,1,1,1e-4,2e-4,1,1,1e-4,2e-4,1,1,1e-4,2e-4,1,1,2e-4,2e-4,1,1,2e-4,3e-4,1,1,3e-4,5e-4,1,1,4e-4,6e-4,1,1,5e-4,8e-4,1,1,6e-4,9e-4,1,1,6e-4,.001,1,1,6e-4,9e-4,1,1,6e-4,9e-4,1,1,5e-4,8e-4,1,1,4e-4,7e-4,1,1,4e-4,5e-4,1,1,3e-4,4e-4,1,1,2e-4,3e-4,1,1,2e-4,3e-4,1,1,2e-4,3e-4,1,1,2e-4,3e-4,1,1,3e-4,5e-4,1,1,5e-4,6e-4,1,1,6e-4,8e-4,1,1,8e-4,.001,1,1,9e-4,.0012,1,1,.001,.0012,1,1,9e-4,.0012,1,1,9e-4,.0011,1,1,8e-4,.001,1,1,7e-4,8e-4,1,1,5e-4,7e-4,1,1,4e-4,6e-4,1,1,3e-4,3e-4,1,1,3e-4,3e-4,1,1,3e-4,3e-4,1,1,3e-4,4e-4,1,1,5e-4,6e-4,1,1,6e-4,8e-4,1,1,8e-4,.001,1,1,.001,.0012,1,1,.0012,.0014,1,1,.0012,.0015,1,1,.0012,.0015,1,1,.0011,.0014,1,1,.001,.0012,1,1,8e-4,.001,1,1,7e-4,8e-4,1,1,6e-4,7e-4,1,1,3e-4,4e-4,1,1,3e-4,4e-4,1,1,3e-4,4e-4,1,1,4e-4,5e-4,1,1,6e-4,6e-4,1,1,8e-4,9e-4,1,1,.001,.0012,1,1,.0012,.0014,1,1,.0014,.0016,1,1,.0015,.0017,1,1,.0015,.0017,1,1,.0014,.0015,1,1,.0012,.0014,1,1,.001,.0012,1,1,8e-4,.001,1,1,7e-4,8e-4,1,1,4e-4,4e-4,1,1,4e-4,4e-4,1,1,4e-4,4e-4,1,1,5e-4,5e-4,1,1,6e-4,7e-4,1,1,9e-4,.001,1,1,.0012,.0013,1,1,.0014,.0016,1,1,.0016,.0018,1,1,.0017,.0019,1,1,.0017,.0018,1,1,.0015,.0017,1,1,.0014,.0015,1,1,.0012,.0013,1,1,.001,.001,1,1,8e-4,8e-4,1,1,4e-4,4e-4,1,1,4e-4,4e-4,1,1,4e-4,5e-4,1,1,5e-4,6e-4,1,1,7e-4,7e-4,1,1,.001,.001,1,1,.0013,.0013,1,1,.0016,.0016,1,1,.0018,.0019,1,1,.0019,.002,1,1,.0018,.0019,1,1,.0017,.0018,1,1,.0015,.0016,1,1,.0013,.0013,1,1,.001,.0011,1,1,8e-4,9e-4,1,1,4e-4,5e-4,1,1,4e-4,5e-4,1,1,5e-4,5e-4,1,1,6e-4,6e-4,1,1,7e-4,8e-4,1,1,.001,.001,1,1,.0013,.0014,1,1,.0016,.0017,1,1,.0019,.0019,1,1,.002,.002,1,1,.0019,.002,1,1,.0018,.0018,1,1,.0016,.0016,1,1,.0013,.0013,1,1,.0011,.0011,1,1,9e-4,9e-4,1,1,5e-4,5e-4,1,1,5e-4,5e-4,1,1,5e-4,5e-4,1,1,6e-4,6e-4,1,1,8e-4,8e-4,1,1,.001,.001,1,1,.0014,.0014,1,1,.0017,.0017,1,1,.0019,.0019,1,1,.002,.002,1,1,.002,.0019,1,1,.0018,.0018,1,1,.0016,.0016,1,1,.0013,.0013,1,1,.0011,.0011,1,1,9e-4,9e-4,1,1,5e-4,4e-4,1,1,5e-4,4e-4,1,1,5e-4,5e-4,1,1,6e-4,6e-4,1,1,8e-4,7e-4,1,1,.001,.001,1,1,.0014,.0013,1,1,.0017,.0016,1,1,.0019,.0018,1,1,.002,.0019,1,1,.0019,.0019,1,1,.0018,.0017,1,1,.0016,.0015,1,1,.0013,.0013,1,1,.0011,.0011,1,1,9e-4,9e-4,1,1,4e-4,4e-4,1,1,4e-4,4e-4,1,1,5e-4,4e-4,1,1,6e-4,5e-4,1,1,7e-4,7e-4,1,1,.001,9e-4,1,1,.0013,.0012,1,1,.0016,.0015,1,1,.0018,.0017,1,1,.0019,.0018,1,1,.0019,.0017,1,1,.0017,.0016,1,1,.0015,.0014,1,1,.0013,.0012,1,1,.0011,.001,1,1,9e-4,8e-4,1,1,4e-4,4e-4,1,1,4e-4,4e-4,1,1,4e-4,4e-4,1,1,5e-4,5e-4,1,1,7e-4,6e-4,1,1,9e-4,8e-4,1,1,.0012,.0011,1,1,.0015,.0013,1,1,.0017,.0015,1,1,.0018,.0016,1,1,.0017,.0015,1,1,.0016,.0014,1,1,.0014,.0012,1,1,.0012,.0011,1,1,.001,9e-4,1,1,8e-4,7e-4,1,1,4e-4,3e-4,1,1,4e-4,3e-4,1,1,4e-4,3e-4,1,1,5e-4,4e-4,1,1,6e-4,5e-4,1,1,8e-4,7e-4,1,1,.0011,9e-4,1,1,.0013,.0011,1,1,.0015,.0012,1,1,.0016,.0013,1,1,.0015,.0013,1,1,.0014,.0012,1,1,.0012,.001,1,1,.0011,9e-4,1,1,9e-4,7e-4,1,1,7e-4,6e-4,1,1,3e-4,2e-4,1,1,3e-4,2e-4,1,1,3e-4,3e-4,1,1,4e-4,3e-4,1,1,5e-4,4e-4,1,1,7e-4,5e-4,1,1,9e-4,7e-4,1,1,.0011,8e-4,1,1,.0012,.001,1,1,.0013,.001,1,1,.0013,.001,1,1,.0012,9e-4,1,1,.001,8e-4,1,1,9e-4,7e-4,1,1,7e-4,6e-4,1,1,6e-4,5e-4,1,1,1,0,0,1,1,0,0,1,1,0,0,1,.998,5e-4,0,1,.9939,.0019,0,1,.9854,.0047,0,1,.9677,.0097,0,1,.9372,.0178,0,1,.8899,.0298,0,1,.8245,.0466,0,1,.743,.0685,0,1,.6508,.0959,0,1,.5552,.1284,0,1,.4631,.1656,0,1,.3794,.2065,0,1,.3069,.25,0,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,1e-4,1,1,0,1e-4,1,1,1e-4,1e-4,1,1,1e-4,2e-4,1,1,1e-4,2e-4,1,1,1e-4,3e-4,1,1,1e-4,3e-4,1,1,1e-4,3e-4,1,1,1e-4,2e-4,1,1,1e-4,2e-4,1,1,1e-4,2e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1e-4,1e-4,1,1,1e-4,1e-4,1,1,1e-4,2e-4,1,1,2e-4,3e-4,1,1,2e-4,4e-4,1,1,3e-4,4e-4,1,1,3e-4,4e-4,1,1,3e-4,4e-4,1,1,2e-4,4e-4,1,1,2e-4,3e-4,1,1,2e-4,3e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1e-4,1e-4,1,1,1e-4,2e-4,1,1,2e-4,3e-4,1,1,3e-4,4e-4,1,1,4e-4,5e-4,1,1,4e-4,5e-4,1,1,4e-4,5e-4,1,1,4e-4,5e-4,1,1,4e-4,5e-4,1,1,3e-4,4e-4,1,1,3e-4,3e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,1e-4,1,1,1e-4,1e-4,1,1,2e-4,2e-4,1,1,3e-4,3e-4,1,1,4e-4,5e-4,1,1,5e-4,6e-4,1,1,5e-4,6e-4,1,1,5e-4,6e-4,1,1,5e-4,6e-4,1,1,5e-4,6e-4,1,1,4e-4,5e-4,1,1,3e-4,4e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1e-4,1e-4,1,1,1e-4,1e-4,1,1,2e-4,3e-4,1,1,3e-4,4e-4,1,1,5e-4,5e-4,1,1,6e-4,7e-4,1,1,6e-4,7e-4,1,1,6e-4,7e-4,1,1,6e-4,7e-4,1,1,6e-4,7e-4,1,1,5e-4,6e-4,1,1,4e-4,5e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1e-4,1e-4,1,1,1e-4,2e-4,1,1,3e-4,3e-4,1,1,4e-4,4e-4,1,1,5e-4,6e-4,1,1,7e-4,7e-4,1,1,7e-4,8e-4,1,1,7e-4,8e-4,1,1,7e-4,8e-4,1,1,7e-4,7e-4,1,1,6e-4,6e-4,1,1,5e-4,5e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1e-4,1e-4,1,1,2e-4,2e-4,1,1,3e-4,3e-4,1,1,4e-4,5e-4,1,1,6e-4,6e-4,1,1,7e-4,8e-4,1,1,8e-4,8e-4,1,1,8e-4,9e-4,1,1,8e-4,8e-4,1,1,7e-4,8e-4,1,1,6e-4,7e-4,1,1,5e-4,6e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1e-4,1e-4,1,1,2e-4,2e-4,1,1,3e-4,3e-4,1,1,5e-4,5e-4,1,1,6e-4,6e-4,1,1,8e-4,8e-4,1,1,8e-4,9e-4,1,1,9e-4,9e-4,1,1,8e-4,8e-4,1,1,8e-4,8e-4,1,1,7e-4,7e-4,1,1,6e-4,6e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1e-4,1e-4,1,1,2e-4,2e-4,1,1,3e-4,3e-4,1,1,5e-4,5e-4,1,1,6e-4,6e-4,1,1,8e-4,8e-4,1,1,9e-4,9e-4,1,1,9e-4,9e-4,1,1,8e-4,8e-4,1,1,8e-4,8e-4,1,1,7e-4,7e-4,1,1,6e-4,6e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1e-4,1e-4,1,1,2e-4,2e-4,1,1,3e-4,3e-4,1,1,5e-4,5e-4,1,1,6e-4,6e-4,1,1,8e-4,7e-4,1,1,9e-4,8e-4,1,1,9e-4,8e-4,1,1,8e-4,8e-4,1,1,8e-4,7e-4,1,1,7e-4,6e-4,1,1,6e-4,5e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1e-4,1e-4,1,1,2e-4,2e-4,1,1,3e-4,3e-4,1,1,5e-4,4e-4,1,1,6e-4,6e-4,1,1,7e-4,7e-4,1,1,8e-4,8e-4,1,1,8e-4,8e-4,1,1,8e-4,8e-4,1,1,7e-4,7e-4,1,1,6e-4,6e-4,1,1,5e-4,5e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1e-4,1e-4,1,1,2e-4,1e-4,1,1,3e-4,2e-4,1,1,4e-4,4e-4,1,1,6e-4,5e-4,1,1,7e-4,6e-4,1,1,8e-4,7e-4,1,1,8e-4,7e-4,1,1,8e-4,7e-4,1,1,7e-4,6e-4,1,1,6e-4,5e-4,1,1,5e-4,4e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1e-4,0,1,1,1e-4,1e-4,1,1,2e-4,2e-4,1,1,4e-4,3e-4,1,1,5e-4,4e-4,1,1,6e-4,5e-4,1,1,7e-4,6e-4,1,1,7e-4,6e-4,1,1,7e-4,6e-4,1,1,6e-4,5e-4,1,1,5e-4,4e-4,1,1,4e-4,4e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1e-4,1e-4,1,1,2e-4,2e-4,1,1,3e-4,2e-4,1,1,4e-4,3e-4,1,1,5e-4,4e-4,1,1,6e-4,4e-4,1,1,6e-4,4e-4,1,1,6e-4,4e-4,1,1,5e-4,4e-4,1,1,4e-4,3e-4,1,1,4e-4,3e-4,1,1]),gd*yd,gd,r.RGBAFormat,r.FloatType);bd.minFilter=r.LinearFilter,bd.magFilter=r.LinearFilter,bd.wrapS=r.ClampToEdgeWrapping,bd.wrapT=r.ClampToEdgeWrapping,bd.generateMipmaps=!1,bd.needsUpdate=!0;var xd=(0,n.texture)(bd);xd.setUpdateMatrix(!1);var Sd=(e,t,r=0)=>(0,n.vec2)((0,n.clamp)(e,0,1).mul(gd-1).add(.5).add((0,n.float)(r).mul(gd)).div(gd*yd),(0,n.clamp)(t,0,1).mul((gd-1)/gd).add(.5/gd)),Cd=(0,n.Fn)(([e,t])=>(0,n.clamp)(xd.sample(Sd(t,e)).g,0,1)),wd=(0,n.Fn)(([e,t,r,i,a,o,s,c,l,u])=>{let d=xd.sample(Sd(u,l)).toVar(),f=(0,n.clamp)(r.sub(1).div(r.add(1)).div(vd),0,1).mul(_d-1).toVar(),p=(0,n.min)((0,n.floor)(f),(0,n.float)(_d-2)).toVar(),m=xd.sample(Sd(u,l,p.add(1))).toVar(),h=(0,n.clamp)((0,n.mix)(m.r,m.g,f.sub(p)),0,1),g=(0,n.max)(d.r,.05).toVar(),_=(0,n.clamp)(d.b,0,1).toVar(),v=e.mul(g.sub(h)).add((0,n.vec3)(t.mul(h))),y=i.mul(g.sub(_)).add((0,n.vec3)(_)),b=o.mul(g.sub(_)).add((0,n.vec3)(_)),x=(0,n.max)((0,n.mix)((0,n.mix)(v,y,a),b,s),(0,n.vec3)(0)),S=(0,n.vec3)(1).add(c.mul((0,n.float)(1).div(g).sub(1)));return wi({compensation:S,E_total:(0,n.clamp)(x.mul(S),(0,n.vec3)(0),(0,n.vec3)(1))})}),Td=(0,n.Fn)(([e,t])=>{let r=(0,n.min)(od(e.ior).mul(e.specularColor),(0,n.vec3)(1)).mul(e.specularIntensity),i=(0,n.clamp)(t.mul(e.specularIntensity),(0,n.vec3)(0),(0,n.vec3)(1));return Ti({f0:r,f90:e.specularIntensity,eta:(0,n.max)(e.ior,1),F0m:i,F0:(0,n.clamp)((0,n.mix)(r,i,e.metalness),(0,n.vec3)(0),(0,n.vec3)(1))})}),Ed=(0,n.Fn)(([e,t,r])=>{let i=ud(e,r),a=md(t,r);return i.mul(a).div((0,n.max)(t.mul(4),Fi))}),Dd=(0,n.Fn)(([e,t])=>{let r=(0,n.max)(e.mul(e),1e-4).toVar();return(0,n.vec2)((0,n.max)((0,n.mix)(r,(0,n.float)(1),t.mul(t)),1e-4),r)}),Od=(0,n.Fn)(([e,t,r,i,a])=>{let o=e.mul(t),s=(0,n.vec3)(t.mul(i),e.mul(a),o.mul(r)),c=(0,n.max)((0,n.dot)(s,s),ld),l=o.div(c);return o.mul(l.mul(l)).div(Mi)}),kd=(0,n.Fn)(([e,t,r,i,a,o,s,c])=>{let l=c.mul((0,n.vec3)(e.mul(r),t.mul(i),s).length()),u=s.mul((0,n.vec3)(e.mul(a),t.mul(o),c).length());return(0,n.float)(.5).div((0,n.max)(l.add(u),Fi))}),Ad=(0,n.Fn)(([e,t,r,i,a])=>{let o=e.mul(r),s=t.mul(i),c=o.mul(o).add(s.mul(s)),l=(0,n.max)(a.mul(a),Fi),u=(0,n.sqrt)((0,n.float)(1).add(c.div(l))).sub(1).mul(.5);return(0,n.float)(1).div(u.add(1))}),jd=(0,n.Fn)(([e,t,r,i,a,o,s,c])=>{let l=Od(e,t,r,i,a),u=Ad(e,t,s,c,o);return l.mul(u).div((0,n.max)(o.mul(4),Fi))}),Md=(0,n.Fn)(([e,t])=>{let r=(0,n.float)(Pi).mul(e).mul(1e-9),i=(0,n.vec3)(54856e-17,44201e-17,52481e-17),a=(0,n.vec3)(1681e3,1795300,2208400),o=(0,n.vec3)(43278e5,93046e5,66121e5),s=i.mul((0,n.sqrt)((0,n.float)(Pi).mul(o))).mul((0,n.cos)(a.mul(r).add(t))).mul((0,n.exp)(Gi({x:r}).negate().mul(o))).toVar();return s.x.addAssign((0,n.float)(9747e-17).mul((0,n.sqrt)((0,n.float)(Pi).mul(45282e5))).mul((0,n.cos)((0,n.float)(2239900).mul(r).add(t.x))).mul((0,n.exp)((0,n.float)(-45282e5).mul(Gi({x:r}))))),Wi.mul(s.div(1.0685e-7))}),Nd=(0,n.Fn)(([e,t,r,i,a])=>{let o=(0,n.mix)(e,t,(0,n.smoothstep)(0,.03,i)).toVar(),s=Gi({x:e.div(o)}).mul((0,n.float)(1).sub(Gi({x:r}))),c=(0,n.float)(1).sub(s).toVar(),l=(0,n.vec3)(0).toVar();return(0,n.If)(c.lessThan(0),()=>{l.assign((0,n.vec3)(1))}).Else(()=>{let t=(0,n.sqrt)(c).toVar(),s=td(r,ad(o,e)).toVar(),u=(0,n.float)(1).sub(s).toVar(),d=o.lessThan(e).select((0,n.float)(Mi),(0,n.float)(0)),f=(0,n.float)(Mi).sub(d),p=rd((0,n.clamp)(a,0,.9999)).toVar(),m=id(p,o).toVar(),h=(0,n.vec3)(td(t,m.x),td(t,m.y),td(t,m.z)).toVar(),g=(0,n.vec3)(p.x.lessThan(o).select((0,n.float)(Mi),(0,n.float)(0)),p.y.lessThan(o).select((0,n.float)(Mi),(0,n.float)(0)),p.z.lessThan(o).select((0,n.float)(Mi),(0,n.float)(0))),_=(0,n.float)(2).mul(o).mul(i).mul(t).toVar(),v=(0,n.vec3)(f).add(g).toVar(),y=(0,n.clamp)((0,n.vec3)(s).mul(h),1e-5,.9999).toVar(),b=(0,n.sqrt)(y).toVar(),x=(0,n.vec3)(u.mul(u)).mul(h).div((0,n.vec3)(1).sub(y)).toVar(),S=(0,n.vec3)(s).add(x).toVar().toVar(),C=x.sub((0,n.vec3)(u)).toVar();C.mulAssign(b),S.addAssign(C.mul((0,n.float)(2).mul(Md((0,n.float)(1).mul(_),(0,n.float)(1).mul(v))))),C.mulAssign(b),S.addAssign(C.mul((0,n.float)(2).mul(Md((0,n.float)(2).mul(_),(0,n.float)(2).mul(v))))),l.assign((0,n.max)(S,(0,n.vec3)(0)))}),l}),Pd=(0,n.Fn)(([e,t,r])=>{let i=r.invRoughness,a=r.metalFactor,o=(0,n.float)(0).toVar();(0,n.If)(t.isMetallic,()=>{o.assign((0,n.max)(i.mul(a),.7))}).ElseIf(t.isSmooth,()=>{o.assign(i.mul(a).mul(1.2))}).Else(()=>{o.assign((0,n.max)(i.mul(a),e.metalness.mul(.1)))});let s=o.mul(e.specularIntensity).toVar(),c=(0,n.float)(1).sub(o).mul((0,n.float)(1).sub(e.metalness)).mul((0,n.float)(1).sub(e.transmission)).toVar(),l=e.sheen.mul(r.maxSheenColor).toVar(),u=(0,n.float)(0).toVar();(0,n.If)(t.hasClearcoat,()=>{u.assign(e.clearcoat.mul(i).mul(.4))}).Else(()=>{u.assign(e.clearcoat.mul(i).mul(.35))});let d=(0,n.float)(0).toVar();(0,n.If)(t.isTransmissive,()=>{let t=r.iorFactor.mul(i).mul(.8);d.assign(e.transmission.mul(t).mul((0,n.float)(.6).add((0,n.float)(.4).mul(e.ior.div(2)))).mul((0,n.float)(1).add(e.dispersion.mul(.6))))}).Else(()=>{let t=r.iorFactor.mul(i).mul(.7);d.assign(e.transmission.mul(t).mul((0,n.float)(.5).add((0,n.float)(.5).mul(e.ior.div(2)))).mul((0,n.float)(1).add(e.dispersion.mul(.5))))});let f=i.mul(t.isSmooth.select((0,n.float)(.6),(0,n.float)(.5))),p=(0,n.min)(e.iridescence.mul(f).mul((0,n.float)(.5).add((0,n.float)(.5).mul(e.iridescenceThicknessRange.y.sub(e.iridescenceThicknessRange.x).div(1e3)))).mul((0,n.float)(.5).add((0,n.float)(.5).mul(e.iridescenceIOR.div(2)))),c);s.addAssign(p),c.subAssign(p);let m=s.add(c).add(l).add(u).add(d),h=(0,n.float)(1).div((0,n.max)(m,.001));return xi({specular:s.mul(h),diffuse:c.mul(h),sheen:l.mul(h),clearcoat:u.mul(h),transmission:d.mul(h),iridescence:(0,n.float)(0)})}),Fd=(0,n.Fn)(([e,t,r])=>{let i=(0,n.float)(0).toVar();return(0,n.If)(r.NoL.greaterThan(0),()=>{i.addAssign(t.diffuse.mul(r.NoL).mul(Ni));let a=(0,n.float)(0).toVar();(0,n.If)(e.anisotropy.greaterThan(0),()=>{let t=Dd(e.roughness,e.anisotropy);a.assign(jd(t.x,t.y,r.NoH,r.ToH,r.BoH,r.NoV,r.ToV,r.BoV))}).Else(()=>{a.assign(Ed(r.NoH,r.NoV,e.roughness))}),i.addAssign(t.specular.mul(a)),(0,n.If)(t.sheen.greaterThan(0),()=>{let a=dd(r.NoH,e.sheenRoughness).mul(r.NoH).div((0,n.max)((0,n.float)(4).mul(r.VoH),Fi));i.addAssign(t.sheen.mul(a))}),(0,n.If)(t.clearcoat.greaterThan(0),()=>{let a=(0,n.clamp)(e.clearcoatRoughness,Li,1);i.addAssign(t.clearcoat.mul(Ed(r.NoH,r.NoV,a)))})}),i}),Id=(0,n.Fn)(([e])=>Pd(e,Di.wrap(ta(e.metalness,e.roughness,e.transmission,e.clearcoat,e.emissive,e.subsurface)),ki({invRoughness:(0,n.float)(1).sub(e.roughness),metalFactor:(0,n.float)(.5).add((0,n.float)(.5).mul(e.metalness)),iorFactor:(0,n.min)((0,n.float)(2).div(e.ior),1),maxSheenColor:(0,n.max)(e.sheenColor.x,(0,n.max)(e.sheenColor.y,e.sheenColor.z))}))),Ld=(0,n.Fn)(([e,t])=>Fd(e,xi.wrap(Id(e)),t)),Rd=(0,n.wgslFn)(`
|
|
486
|
+
`)))}`}var pu=[],mu=0;function hu(){return mu}function gu(){mu++}function _u(e,t){pu.unshift({match:e,colorSpace:t}),mu++}function vu(){pu.length!==0&&(pu.length=0,mu++)}function yu(){return pu.map(e=>({match:String(e.match),colorSpace:e.colorSpace}))}function bu(e){if(!e)return null;for(let t of pu)if(t.match instanceof RegExp?t.match.test(e):e.includes(t.match))return t.colorSpace;return null}function xu(){return mc()?.fileRules.map(e=>({index:e.index,name:e.name,colorSpace:e.colorSpace,pattern:e.pattern,extension:e.extension,regex:e.regex}))??[]}function Su(e){let t=mc();if(!t)return null;let n=e=>t.roles.find(t=>t.name===e)?.colorSpace??null;return e===r.NoColorSpace?n(`data`):e===r.SRGBColorSpace?n(`texture_paint`)??n(`color_picking`)??t.colorSpaces.find(e=>/^srgb\b/i.test(e.name)&&!/display/i.test(e.name))?.name??null:e===r.LinearSRGBColorSpace?t.colorSpaces.find(e=>/^lin(ear)?[\s_-]*(rec\.?\s*)?709/i.test(e.name))?.name??t.colorSpaces.find(e=>/^linear.*srgb/i.test(e.name))?.name??n(`scene_linear`):null}function Cu(e,{threeColorSpace:t=null}={}){if(!mc())return null;let n=bu(e);if(n)return{colorSpace:n,via:`override`,rule:null};let r=pc();if(r&&e){let t=r.matchFileRule(e);if(t&&!t.isDefaultRule&&Jc(t.colorSpace))return{colorSpace:t.colorSpace,via:`rule`,rule:{index:t.ruleIndex,name:t.ruleName}}}let i=Su(t);if(i)return{colorSpace:i,via:`three`,rule:null};let a=pc();if(a&&e){let t=a.matchFileRule(e);if(t&&Jc(t.colorSpace))return{colorSpace:t.colorSpace,via:`rule`,rule:{index:t.ruleIndex,name:t.ruleName,isDefault:t.isDefaultRule}}}return null}function wu(e){if(!e)return!1;if(e.colorSpace===r.NoColorSpace)return!0;let t=e.userData?.ocioColorSpace;return!!(t&&qc(t))}function Tu(e,t){return t??e.userData?.sourcePath??(e.name||null)??e.image?.src??null}function Eu(e,t=null){if(!mc()||!e)return null;let n=e.userData?.ocioColorSpace;return n?Jc(n)?{colorSpace:n,via:`tag`,rule:null}:null:wu(e)?null:Cu(Tu(e,t),{threeColorSpace:e.colorSpace})}function Du(e,t=null){return Eu(e,t)?.colorSpace??null}jl();var Ou=`Linear Rec.709 (sRGB)`,ku=null;function Au(){return ku}function ju(e){ku=e,e?._publishWorkingMatrix?.()}function Mu(e){return qs(e)??`srgb`}var Nu=[`Linear Rec.709 (sRGB)`,`lin_rec709_srgb`,`lin_rec709`,`lin_srgb`,`Linear Rec.709`,`Utility - Linear - sRGB`,`Utility - Linear - Rec.709`,`Linear BT.709`,`linrec709`],Pu=/^(lin(ear)?[\s_-]*(rec\.?\s*|bt\.?\s*)?709|linear[\s_-]*\(?srgb\)?$|utility - linear - (srgb|rec\.?709))/i;function Fu(e){if(!e)return null;let t=e.colorSpaces.filter(e=>!e.isData),n=e=>[e.name,...e.aliases??[]];for(let e of Nu){let r=t.find(t=>n(t).some(t=>t.toLowerCase()===e.toLowerCase()));if(r)return r.name}return t.find(e=>n(e).some(e=>Pu.test(e)))?.name??null}var Iu=class{constructor({issues:e=null,renderer:t=null}={}){this._issues=e,this._renderer=t,this._listeners=new Map,this._workingSpace=null,this._activeView=null,this._exportSpace=null,this._context=null,this._lastUsed=new Map,this._useClock=0,this._lastBuiltin=Al,this._fingerprint=null,Yl(e),this._offRegistry=fl(()=>{this._renderer&&bl(this._renderer),this._emit(`transforms`)}),ku===null&&(ku=this)}on(e,t){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(t),()=>this._listeners.get(e)?.delete(t)}_emit(e,t=null){for(let n of this._listeners.get(e)??[])n(t);if(e!==`change`)for(let n of this._listeners.get(`change`)??[])n({event:e,detail:t})}static async listBuiltinConfigs(){return await lc()}async loadConfig({adoptWorkingSpace:e=!1,registerViews:t=!0,display:n=null,lutSize:r,...i}={}){await cc();let a=fu(i).catch(()=>null),o=await this._bakedViewsFrom(i.builtin??i.id??null,a),s;try{s=await uc(i)}catch(e){throw this._issues?.warn(Y.COLOR_CONFIG_LOAD_FAILED,`colour config failed to load; the previous one stays in effect: ${e.message}`,{builtin:i.builtin??null,configPath:i.configPath??null}),e}this._releaseViews(new Set(o.filter(e=>e.ocio.baked.ocioVersion===s.ocioVersion).map(e=>e.id))),this._fingerprint=a,gu(),jc(),this._context=null;let c=this._workingSpace;if(e?this._workingSpace=s.sceneLinear:c&&!Jc(c)&&(this._workingSpace=null),Fu(mc())||this._issues?.warn(Y.COLOR_CONFIG_LOAD_FAILED,`"${s.id}" names no linear Rec.709 space, so until a working space is adopted its views treat the render as ${s.sceneLinear} — colours will be off by that primaries change`,{sceneLinear:s.sceneLinear}),this._publishWorkingMatrix(),this._emit(`config`,s),t){let e=n??s.defaultDisplay,{added:t,skipped:i}=ru({display:e,context:this._context,source:this.workingSpace,...r?{size:r}:{}});if(t.length){let n=s.defaultViews[e],r=t.find(e=>e.ocio.view===n)??t[0];this.setActiveView(r.id)}this._emit(`transforms`,{added:t,skipped:i})}return(this._workingSpace??null)!==(c??null)&&this._emit(`workingSpace`,this.workingSpace),s}unloadConfig(){this.workingSpaceAdopted&&this._issues?.warn(Y.COLOR_CONFIG_LOAD_FAILED,`unloaded while rendering in ${this._workingSpace}; the environment stays converted into it — use app.unloadColorConfig(), which reverts the scene first`,{workingSpace:this._workingSpace}),this._releaseViews(),dc(),jc(),vu(),gu(),this._fingerprint=null,this._workingSpace=null,this._activeView=null,this._exportSpace=null,this._context=null,Rr(null),this._applyRendererOutputColorSpace(),this._emit(`config`,null),this._emit(`workingSpace`,this.workingSpace)}_releaseViews(e=null){au(e),yl(e);for(let t of this._lastUsed.keys())e?.has(t)||this._lastUsed.delete(t);this._renderer&&pl(this._renderer.toneMapping)===null&&(this._renderer.toneMapping=pl(this._lastBuiltin)?this._lastBuiltin:Al,this._activeView=null,this._applyRendererOutputColorSpace())}async _bakedViewsFrom(e,t){let n=[...kl.values()].filter(t=>t.ocio?.baked&&e!==null&&t.ocio.configId===e);if(n.length===0)return[];let r=await t;return r?n.filter(e=>e.ocio.baked.fingerprint===r):[]}async loadBakedView(e,{expect:t=null}={}){let n=await du(e);for(let[e,r]of Object.entries(t??{}))if((n[e]??null)!==(r??null))throw Error(`baked view has ${e} "${n[e]}", expected "${r}"`);let r=hc();if(r&&(r.id!==n.configId||await this._fingerprint!==n.fingerprint))throw Error(`baked view is from "${n.configId}", not the loaded "${r.id}"`);let i=[...kl.values()].find(e=>e.source===`ocio`&&e.ocio.display===n.display&&e.ocio.view===n.view&&(e.ocio.look??null)===(n.look??null));return i||this._makeRoomForTable(),_l(eu(n,i?.id??null))}async saveBakedView(e){let t=pl(e);if(t?.source!==`ocio`)throw Error(`no OCIO view with id ${e}`);let n=hc();return await uu(t,{configId:n?.id??t.ocio.configId,fingerprint:(n?await this._fingerprint:null)??t.ocio.baked?.fingerprint??null,ocioVersion:n?.ocioVersion??t.ocio.baked?.ocioVersion??null})}get hasConfig(){return fc()}describe(){return hc()}get workingSpace(){return this._workingSpace?this._workingSpace:fc()?this.nativeLinearSpace??hc()?.sceneLinear??`Linear Rec.709 (sRGB)`:Ou}get workingSpaceAdopted(){return this._workingSpace!==null}setWorkingSpace(e){if(e!==null){if(!fc())throw Error(`load an OCIO config before choosing a working space`);if(!Jc(e))throw Error(`config has no colour space "${e}"`)}(this._workingSpace??null)!==(e??null)&&(this._workingSpace=e,Tc(),this._publishWorkingMatrix(),this._rebakeViews(),this._emit(`workingSpace`,this.workingSpace))}matrixToWorking(e){return fc()?Kc(e,this.workingSpace,{context:this._context}):null}listViews(){return ml()}get activeView(){return this._activeView}setActiveView(e){let t=pl(e);if(!t)throw Error(`no view transform with id ${e}`);return this._isStale(t)&&(t=this._rebakeView(t)??t),this._activeView=t.source===`ocio`?{...t.ocio,id:t.id,name:t.name}:null,this._lastUsed.set(e,++this._useClock),t.source===`builtin`&&(this._lastBuiltin=e),this._renderer&&(this._renderer.toneMapping=e),this._applyRendererOutputColorSpace(),this._emit(`view`,t),t}setView({display:e,view:t,look:n=null,size:r}={}){if(!fc())throw Error(`load an OCIO config first`);let i=[...kl.values()].find(i=>i.source===`ocio`&&i.ocio.display===e&&i.ocio.view===t&&(i.ocio.look??null)===(n??null)&&(!r||i.ocio.size===r));i||this._makeRoomForTable();let a=i??nu({display:e,view:t,look:n,context:this._context,source:this.workingSpace,...r?{size:r}:{}});return this.setActiveView(a.id),pl(a.id)}_makeRoomForTable(){if(hl()<12)return;let e=this._renderer?.toneMapping??this._activeView?.id??null,t=[...kl.values()].filter(t=>t.source===`ocio`&&t.id!==e).sort((e,t)=>(this._lastUsed.get(e.id)??0)-(this._lastUsed.get(t.id)??0))[0];t&&(iu(t.id),vl(t.id),this._lastUsed.delete(t.id))}setLook(e){if(!this._activeView)throw Error(`no OCIO view is active`);return this.setView({...this._activeView,look:e})}setContext(e){let t=e&&Object.keys(e).length?{...e}:null;JSON.stringify(t)!==JSON.stringify(this._context)&&(this._context=t,fc()&&(this._context&&pc()?.invalidateContext(this._context),Tc(),this._rebakeViews()),this._emit(`context`,this._context))}get context(){return this._context}_isStale(e){return e.source!==`ocio`||!fc()?!1:e.ocio.source!==this.workingSpace||JSON.stringify(e.ocio.context??null)!==JSON.stringify(this._context??null)}_rebakeView(e){try{let t=nu({id:e.id,display:e.ocio.display,view:e.ocio.view,look:e.ocio.look,context:this._context,source:this.workingSpace,size:e.ocio.size,minEv:e.ocio.minEv,maxEv:e.ocio.maxEv}),n=e.table?.texture;return n&&n!==t.table?.texture&&n.dispose?.(),t}catch(t){return this._issues?.warn(Y.VIEW_TRANSFORM_BAKE_FAILED,`could not rebake "${e.name}": ${t.message}`,{id:e.id}),null}}_rebakeViews(){let e=this._renderer?.toneMapping??this._activeView?.id??null,t=e===null?null:pl(e);if(!t||!this._isStale(t))return;let n=this._rebakeView(t);n&&(this._activeView={...n.ocio,id:n.id,name:n.name})}attachRenderer(e){this._renderer=e,pl(e.toneMapping)?.source===`builtin`&&(this._lastBuiltin=e.toneMapping);let t=bl(e);return this._applyRendererOutputColorSpace(),t}_applyRendererOutputColorSpace(){if(!this._renderer)return;let e=pl(this._renderer.toneMapping);this._renderer.outputColorSpace=e?.outputEncoded?r.LinearSRGBColorSpace:r.SRGBColorSpace,this._applyCanvasColorSpace(e?.source===`ocio`?Mu(e.ocio.display):`srgb`)}_applyCanvasColorSpace(e){let t=(this._renderer?.domElement)?.getContext?.(`webgpu`),n=t?.getConfiguration?.();if(n){if(!t.__rayzeeConfigure){let e=t.configure.bind(t);t.__rayzeeConfigure=e,t.configure=n=>e({...n,colorSpace:t.__rayzeeColorSpace??n.colorSpace})}if(t.__rayzeeColorSpace=e,n.colorSpace!==e)try{t.configure({...n,colorSpace:e})}catch(t){this._issues?.warn(Y.VIEW_TRANSFORM_DISPLAY_MISMATCH,`the canvas could not be set to ${e}: ${t.message}`,{colorSpace:e})}}}resolveInput(e,t){return Cu(e,t)}textureSpace(e,t){return Du(e,t)}resolveTexture(e,t){return Eu(e,t)}describeTextureSpace(e){let t=e?.userData??{},n=t.ocioColorSpace??t.__rayzeeColorSpaceChoice??null,i=null,a=t.__rayzeeOriginalColorSpace??e?.colorSpace;return fc()&&(i=Eu({...e,name:e?.name,image:e?.image,colorSpace:a,userData:{}})),i||={colorSpace:a===r.SRGBColorSpace?`sRGB`:`Linear`,via:`three`},{choice:n,auto:i}}get inputKey(){return fc()?`${hc()?.id}|${this.workingSpace}|${hu()}|${JSON.stringify(this._context)}`:`-`}overrideInput(e,t){_u(e,t)}fileRules(){return xu()}toWorkingPixels(e,t){return!fc()||!t?e:Nc(e,t,this.workingSpace,{context:this._context})}get nativeLinearSpace(){return Fu(mc())}_publishWorkingMatrix(){ku!==null&&ku!==this||Rr(fc()?this.primariesMatrixToWorking():null,this.workingSpace)}primariesMatrixToWorking(){if(!fc()||!this.workingSpaceAdopted)return null;let e=this.nativeLinearSpace;if(!e||e===this.workingSpace)return null;let t=Kc(e,this.workingSpace,{context:this._context});return t?[1,0,0,0,1,0,0,0,1].every((e,n)=>Math.abs(t[n]-e)<1e-6)?null:t:null}convertLinearTriple(e){return Vr(e)}convertLinearTriples(e,t,n){return Hr(e,t,n)}convertTexturePixels(e,{space:t=null}={}){if(!fc())return!1;let n=e?.image?.data;if(!n)return!1;let r=this.nativeLinearSpace,i=e.userData?.__rayzeeColorSpace??t??r,a=this.workingSpaceAdopted?this.workingSpace:r;if(!i||!a||i===a)return!1;let o=!1;if(n instanceof Float32Array)Nc(n,i,a,{context:this._context}),o=!0;else if(n instanceof Uint16Array){let e=Ll(n);Nc(e,i,a,{context:this._context}),n.set(Il(e)),o=!0}else if(n instanceof Uint8Array||n instanceof Uint8ClampedArray)Bc(n,i,a,{context:this._context,inputEncoding:`srgb`,outputEncoding:`srgb`}),o=!0;else return this._issues?.warn(Y.VIEW_TRANSFORM_BAKE_FAILED,`texture data is ${n.constructor?.name??typeof n}, which cannot be colour-converted`,{from:i,to:a}),!1;return e.userData=e.userData??{},e.userData.__rayzeeColorSpace=a,e.needsUpdate=!0,o}convertTextureBytes(e,{space:t=null,encoding:n=`srgb`}={}){if(!fc())return!1;if(t)return t===this.workingSpace?!1:(Bc(e,t,this.workingSpace,{context:this._context,inputEncoding:`raw`,outputEncoding:n}),!0);let r=this.primariesMatrixToWorking();return r?(Gc(e,r,n),!0):!1}toWorkingColor(e,t){return!fc()||!t?[e[0],e[1],e[2]]:Mc(e,t,this.workingSpace,{context:this._context})}convert(e,t,n){return Mc(e,t,n,{context:this._context})}get exportSpace(){return this._exportSpace}setExportSpace(e){if(e!=null){if(!fc())throw Error(`load an OCIO config before choosing an export space`);if(!Jc(e))throw Error(`config has no colour space "${e}"`)}this._exportSpace=e??null,this._emit(`export`,this._exportSpace)}exportPixels(e,t=void 0){let n=t===void 0?this._exportSpace:t;return!n||!fc()?{rgba:e,colorSpace:this.workingSpace}:(Nc(e,this.workingSpace,n,{context:this._context}),{rgba:e,colorSpace:n})}status(){let e=hc(),t=this._renderer?pl(this._renderer.toneMapping):null;return{config:e,workingSpace:this.workingSpace,workingSpaceAdopted:this.workingSpaceAdopted,activeTransform:t?{id:t.id,name:t.name,source:t.source}:null,activeView:this._activeView,context:this._context,exportSpace:this._exportSpace,views:ml(),registryVersion:dl(),bakeError:t?.error??null}}dispose(){this._offRegistry?.(),this._listeners.clear(),this._releaseViews(),Yl(null),this._renderer=null,this._issues=null,ku===this&&(Rr(null),ku=null)}static resetAll(){ku=null,Rr(null),au(),Sl(),jc(),vu(),vc()}};function Lu(){return fc()}var Ru=new Map;function zu(e){return Ru.get(e)?.storage??null}$s();var Bu=1;function Vu(e,t){e&&t&&(e.userData.__rayzeeSource=t)}function Hu(e){let t=e?.userData?.__rayzeeSource;if(!t)return null;let{width:n=0,height:r=0}=e.image??{};return`cdf:${Bu}:${t}|${n}x${r}|${e.userData.__rayzeeColorSpace??`native`}`}var Uu=()=>zu(Xs().cacheNamespace)?.area(qn.CDF)??null;async function Wu(e){let t=Hu(e),n=t?await Uu()?.open(t):null;if(!n)return null;try{let[e,t]=await Promise.all([n.file(`marginal.f32`),n.file(`conditional.f32`)]);if(!e||!t)return null;let{totalSum:r,compensationDelta:i,width:a,height:o}=n.extra;return{marginalData:new Float32Array(await e.arrayBuffer()),conditionalData:new Float32Array(await t.arrayBuffer()),totalSum:r,compensationDelta:i,width:a,height:o}}finally{n.release()}}async function Gu(e,{marginalData:t,conditionalData:n,totalSum:r,compensationDelta:i,width:a,height:o}){let s=Hu(e),c=s?Uu():null;if(!c||!t||!n)return!1;let l=await c.create(s,{label:e.name||`environment`,expectedBytes:t.byteLength+n.byteLength});if(!l)return!1;try{return await l.write(`marginal.f32`,t),await l.write(`conditional.f32`,n),await l.commit({totalSum:r,compensationDelta:i,width:a,height:o}),!0}catch{return await l.abort(),!1}}jt();var Ku=vt(`env`),qu=1024,Ju=512,Yu=Math.PI/180,Xu=new r.Matrix4,Zu=4,Qu=class{constructor(e,t,n=null){this.scene=e,this.uniforms=t,this.renderer=n,this.equirectHdrInfo=new pi,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(V.solidSkyColor),skySunDirection:this._calculateInitialSunDirection(),skySunStrength:V.skySunStrength,skySunSize:V.skySunSize,skyTurbidity:V.skyTurbidity,skyOzone:V.skyOzone,skyAirDensity:V.skyAirDensity,skyGroundAlbedo:new r.Color(V.skyGroundAlbedo),skyAltitude:V.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.onAutoExposureReset?.(),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([0]),1,1,r.RedFormat,r.FloatType),this.envCDFTexture.needsUpdate=!0}_updateCDFTexture(){let e=this.equirectHdrInfo.marginalData,t=this.equirectHdrInfo.conditionalData;if(!e||!t)return;let n=this.equirectHdrInfo.width,i=this.equirectHdrInfo.height,a=n+1,o=new Float32Array(a*i);for(let r=0;r<i;r++){let i=r*a;o.set(t.subarray(r*n,r*n+n),i),o[i+n]=e[r]}this.envCDFTexture?._isPhysicalSky||this.envCDFTexture?.dispose?.(),this.envCDFTexture=new r.DataTexture(o,a,i,r.RedFormat,r.FloatType),this.envCDFTexture.needsUpdate=!0}setEnvironmentTexture(e){if(!e)return;let t=Au();if(t?.hasConfig)try{t.convertTexturePixels(e,{space:e.userData?.ocioColorSpace??null})}catch(e){Ku.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),this.uniforms.set(`envCompensationDelta`,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),this.uniforms.set(`envCompensationDelta`,0);return}let r=`${n.uuid}:${n.version}`;if(r===this._cdfSignature)return;let i=await Wu(n).catch(()=>null);i?Object.assign(this.equirectHdrInfo,i):e?await this.equirectHdrInfo.updateFromAsync(n):this.equirectHdrInfo.updateFrom(n),i||Gu(n,this.equirectHdrInfo).catch(()=>{}),this._cdfSignature=r,this.cdfBuildTime=performance.now()-t,this._updateCDFTexture(),this.uniforms.set(`envTotalSum`,this.equirectHdrInfo.totalSum),this.uniforms.set(`envCompensationDelta`,this.equirectHdrInfo.compensationDelta);let{width:a,height:o}=this.equirectHdrInfo;a&&o&&this.uniforms.get(`envResolution`).value.set(a,o),Ku.info(J.list([J.px(this.envTexSize.x,this.envTexSize.y),`CDF ${J.ms(this.cdfBuildTime)}${i?` (stored)`:e?``:` (main thread)`}`]))}catch(e){this._cdfSignature=null,Ku.error(`CDF build failed:`,e),this.uniforms.set(`envTotalSum`,0),this.uniforms.set(`envCompensationDelta`,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),this.uniforms.set(`envCompensationDelta`,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 Ks(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){Ku.error(`solid color sky generation failed:`,e)}}generateProceduralSkyTexture(){return this._skyRequested=!0,this._skyCaughtUp??=new Promise(e=>void(this._resolveSky=e)),this._pumpSky(),this._skyCaughtUp}_pumpSky(){this._skyScheduled||!this._skyRequested||this._skyInFlight>=Zu||(this._skyScheduled=!0,queueMicrotask(()=>{this._skyScheduled=!1,this._skyRequested&&this._skyInFlight<Zu&&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||Ku.warn(`physical sky needs a renderer`),this._skyInFlight===0&&this._settleSky();return}let t=this.physicalSky??=new Gs(qu,Ju),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*Yu,sunStrength:e.skySunStrength});this._sun=s,this._installSky(a,o);let{totalSum:l,compensationDelta:u}=await c;e.mode===`procedural`&&t===this.physicalSky&&r>this._skyStatsBake&&(this._skyStatsBake=r,this.uniforms.set(`envTotalSum`,l),this.uniforms.set(`envCompensationDelta`,u),i()&&this._notifyReset()),i()&&Ku.debug(`physical sky ${J.ms(t.getLastRenderTime())} · sun ${s.radiance.map(e=>e.toPrecision(3)).join(`,`)}`)}catch(e){Ku.error(`physical sky generation failed:`,e)}finally{this._skyInFlight--,i()?this._settleSky():this._pumpSky()}}_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,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(Xu.copy(this.environmentRotationMatrix).transpose());let n=[...e.radiance];Vr(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=V.skySunAzimuth*(Math.PI/180),t=V.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}},$u=1e-6,ed=e=>{let t=e.mul(e);return t.mul(t).mul(e)};(0,n.Fn)(([e,t,r])=>{let i=(0,n.max)((0,n.vec3)((0,n.float)(1).sub(r)),e);return e.add(i.sub(e).mul(ed((0,n.float)(1).sub(t))))});var td=(0,n.Fn)(([e,t])=>{let r=(0,n.clamp)(e,0,1);return t.add((0,n.float)(1).sub(t).mul(ed((0,n.float)(1).sub(r))))}),nd=(0,n.Fn)(([e,t])=>{let r=(0,n.clamp)(e,0,1);return t.add((0,n.vec3)(1).sub(t).mul(ed((0,n.float)(1).sub(r))))}),rd=(0,n.Fn)(([e])=>{let t=(0,n.sqrt)(e);return(0,n.vec3)(1).add(t).div((0,n.max)((0,n.vec3)(1).sub(t),(0,n.vec3)($u)))}),id=(0,n.Fn)(([e,t])=>{let r=e.sub((0,n.vec3)(t)),i=(0,n.max)(e.add((0,n.vec3)(t)),(0,n.vec3)($u)),a=r.div(i);return a.mul(a)}),ad=(0,n.Fn)(([e,t])=>{let r=e.sub(t),i=(0,n.max)(e.add(t),$u),a=r.div(i);return a.mul(a)}),od=e=>(0,n.vec3)(ad(e,(0,n.float)(1))),sd=(0,n.Fn)(([e,t])=>{let r=(0,n.clamp)(e,0,1),i=t.mul(t).sub(1).add(r.mul(r)),a=(0,n.sqrt)((0,n.max)(i,0)),o=a.sub(r).div((0,n.max)(a.add(r),$u)),s=r.mul(a.add(r)).sub(1).div((0,n.max)(r.mul(a.sub(r)).add(1),$u));return(0,n.select)(i.greaterThan(0),(0,n.clamp)(o.mul(o).mul(.5).mul(s.mul(s).add(1)),0,1),(0,n.float)(1))}),cd=(0,n.Fn)(([e,t])=>{let r=ad(t,(0,n.float)(1));return(0,n.clamp)(sd(e,t).sub(r).div((0,n.max)((0,n.float)(1).sub(r),$u)),0,1)}),ld=1e-30,ud=(0,n.Fn)(([e,t])=>{let r=t.mul(t),i=r.mul(r),a=e.mul(e).mul(i.sub(1)).add(1);return i.div((0,n.max)((0,n.float)(Mi).mul(a).mul(a),ld))}),dd=(0,n.Fn)(([e,t])=>{let r=(0,n.max)(t,Ii),i=r.mul(r),a=(0,n.float)(1).div(i.mul(i)),o=e.mul(e).mul(a.sub(1)).add(1);return a.div((0,n.max)((0,n.float)(Mi).mul(o).mul(o),Fi))}),fd=(0,n.Fn)(([e])=>(0,n.float)(1).div((0,n.max)(e,Ii))),pd=(0,n.Fn)(([e,t])=>(0,n.clamp)((0,n.float)(1).div((0,n.max)((0,n.float)(4).mul(t.add(e).sub(t.mul(e))),Fi)),0,1)),md=(0,n.Fn)(([e,t])=>{let r=t.mul(t),i=r.mul(r),a=e.add((0,n.sqrt)(i.add((0,n.float)(1).sub(i).mul(e.mul(e)))));return(0,n.float)(2).mul(e).div((0,n.max)(a,Fi))}),hd=(0,n.Fn)(([e,t,r])=>{let i=r.mul(r),a=i.mul(i),o=t.mul((0,n.sqrt)(a.add((0,n.float)(1).sub(a).mul(e.mul(e))))),s=e.mul((0,n.sqrt)(a.add((0,n.float)(1).sub(a).mul(t.mul(t)))));return(0,n.float)(.5).div((0,n.max)(o.add(s),Fi))}),gd=16,_d=17,vd=.5,yd=_d,bd=new r.DataTexture(new Float32Array([1,.0302,.9039,1,.9712,.0898,.8635,1,.8914,.6742,.6952,1,.9176,1.1716,.5703,1,.9447,1.3763,.4529,1,.9592,1.3948,.3509,1,.9658,1.3111,.269,1,.9679,1.183,.2061,1,.9669,1.0453,.1588,1,.9639,.9156,.1237,1,.9592,.8006,.0978,1,.9533,.7013,.0786,1,.9465,.6167,.0644,1,.9388,.5447,.0537,1,.9304,.4836,.0457,1,.9214,.4314,.0395,1,0,.7915,1,1,0,.745,1,1,0,.5423,1,1,0,.3846,1,1,0,.2656,1,1,0,.1819,1,1,0,.1256,1,1,0,.0882,1,1,0,.0633,1,1,0,.0466,1,1,0,.0352,1,1,0,.0274,1,1,0,.0218,1,1,0,.0178,1,1,0,.0149,1,1,0,.0127,1,1,.7915,.8421,1,1,.745,.798,1,1,.5423,.608,1,1,.3846,.461,1,1,.2656,.34,1,1,.1819,.2471,1,1,.1256,.1797,1,1,.0882,.132,1,1,.0633,.0985,1,1,.0466,.0749,1,1,.0352,.0582,1,1,.0274,.0463,1,1,.0218,.0376,1,1,.0178,.0312,1,1,.0149,.0264,1,1,.0127,.0227,1,1,.8421,.8638,1,1,.798,.821,1,1,.608,.6386,1,1,.461,.4996,1,1,.34,.3803,1,1,.2471,.2847,1,1,.1797,.2128,1,1,.132,.1601,1,1,.0985,.122,1,1,.0749,.0945,1,1,.0582,.0745,1,1,.0463,.06,1,1,.0376,.0493,1,1,.0312,.0413,1,1,.0264,.0352,1,1,.0227,.0305,1,1,.8638,.8754,1,1,.821,.8334,1,1,.6386,.6559,1,1,.4996,.5225,1,1,.3803,.4052,1,1,.2847,.3089,1,1,.2128,.2347,1,1,.1601,.1793,1,1,.122,.1385,1,1,.0945,.1085,1,1,.0745,.0865,1,1,.06,.0702,1,1,.0493,.0581,1,1,.0413,.049,1,1,.0352,.042,1,1,.0305,.0366,1,1,.8754,.8821,1,1,.8334,.8406,1,1,.6559,.6663,1,1,.5225,.5367,1,1,.4052,.4212,1,1,.3089,.3248,1,1,.2347,.2495,1,1,.1793,.1926,1,1,.1385,.1501,1,1,.1085,.1186,1,1,.0865,.0952,1,1,.0702,.0778,1,1,.0581,.0647,1,1,.049,.0547,1,1,.042,.0471,1,1,.0366,.0412,1,1,.8821,.8857,1,1,.8406,.8445,1,1,.6663,.6722,1,1,.5367,.5451,1,1,.4212,.4311,1,1,.3248,.335,1,1,.2495,.2592,1,1,.1926,.2014,1,1,.1501,.158,1,1,.1186,.1255,1,1,.0952,.1013,1,1,.0778,.0831,1,1,.0647,.0694,1,1,.0547,.0589,1,1,.0471,.0508,1,1,.0412,.0445,1,1,.8857,.8872,1,1,.8445,.8462,1,1,.6722,.6749,1,1,.5451,.5494,1,1,.4311,.4364,1,1,.335,.3406,1,1,.2592,.2648,1,1,.2014,.2067,1,1,.158,.1628,1,1,.1255,.1299,1,1,.1013,.1052,1,1,.0831,.0866,1,1,.0694,.0725,1,1,.0589,.0617,1,1,.0508,.0533,1,1,.0445,.0468,1,1,.8872,.887,1,1,.8462,.846,1,1,.6749,.6751,1,1,.5494,.5503,1,1,.4364,.4379,1,1,.3406,.3427,1,1,.2648,.2671,1,1,.2067,.2091,1,1,.1628,.1651,1,1,.1299,.1321,1,1,.1052,.1072,1,1,.0866,.0884,1,1,.0725,.0741,1,1,.0617,.0632,1,1,.0533,.0547,1,1,.0468,.0481,1,1,.887,.8854,1,1,.846,.8443,1,1,.6751,.6732,1,1,.5503,.5483,1,1,.4379,.4363,1,1,.3427,.3415,1,1,.2671,.2665,1,1,.2091,.2088,1,1,.1651,.1651,1,1,.1321,.1322,1,1,.1072,.1075,1,1,.0884,.0888,1,1,.0741,.0745,1,1,.0632,.0636,1,1,.0547,.0551,1,1,.0481,.0485,1,1,.8854,.8824,1,1,.8443,.8412,1,1,.6732,.6692,1,1,.5483,.5436,1,1,.4363,.4317,1,1,.3415,.3375,1,1,.2665,.2631,1,1,.2088,.2061,1,1,.1651,.1631,1,1,.1322,.1306,1,1,.1075,.1062,1,1,.0888,.0878,1,1,.0745,.0737,1,1,.0636,.0629,1,1,.0551,.0546,1,1,.0485,.048,1,1,.8824,.8781,1,1,.8412,.8366,1,1,.6692,.6633,1,1,.5436,.5364,1,1,.4317,.4244,1,1,.3375,.3308,1,1,.2631,.2573,1,1,.2061,.2012,1,1,.1631,.159,1,1,.1306,.1273,1,1,.1062,.1034,1,1,.0878,.0854,1,1,.0737,.0718,1,1,.0629,.0613,1,1,.0546,.0531,1,1,.048,.0467,1,1,.8781,.8723,1,1,.8366,.8306,1,1,.6633,.6555,1,1,.5364,.5267,1,1,.4244,.4142,1,1,.3308,.3213,1,1,.2573,.249,1,1,.2012,.1941,1,1,.159,.153,1,1,.1273,.1223,1,1,.1034,.0992,1,1,.0854,.0819,1,1,.0718,.0687,1,1,.0613,.0586,1,1,.0531,.0508,1,1,.0467,.0447,1,1,.8723,.8651,1,1,.8306,.8229,1,1,.6555,.6454,1,1,.5267,.5142,1,1,.4142,.4012,1,1,.3213,.3091,1,1,.249,.2382,1,1,.1941,.1848,1,1,.153,.1451,1,1,.1223,.1156,1,1,.0992,.0936,1,1,.0819,.0771,1,1,.0687,.0646,1,1,.0586,.0551,1,1,.0508,.0477,1,1,.0447,.0419,1,1,.8651,.856,1,1,.8229,.8134,1,1,.6454,.6331,1,1,.5142,.4988,1,1,.4012,.3852,1,1,.3091,.2941,1,1,.2382,.2248,1,1,.1848,.1733,1,1,.1451,.1353,1,1,.1156,.1073,1,1,.0936,.0866,1,1,.0771,.0711,1,1,.0646,.0594,1,1,.0551,.0505,1,1,.0477,.0437,1,1,.0419,.0383,1,1,.856,.8449,1,1,.8134,.8018,1,1,.6331,.618,1,1,.4988,.4803,1,1,.3852,.3659,1,1,.2941,.276,1,1,.2248,.2087,1,1,.1733,.1595,1,1,.1353,.1236,1,1,.1073,.0973,1,1,.0866,.0781,1,1,.0711,.0638,1,1,.0594,.0532,1,1,.0505,.0451,1,1,.0437,.0389,1,1,.0383,.034,1,1,.8449,.8314,1,1,.8018,.7875,1,1,.618,.5998,1,1,.4803,.458,1,1,.3659,.3429,1,1,.276,.2545,1,1,.2087,.1898,1,1,.1595,.1431,1,1,.1236,.1097,1,1,.0973,.0856,1,1,.0781,.0681,1,1,.0638,.0553,1,1,.0532,.0458,1,1,.0451,.0387,1,1,.0389,.0332,1,1,.034,.029,1,1,1,.0026,.7082,1,.9976,.0086,.7027,1,.9605,.1171,.6408,1,.9009,.4003,.5153,1,.8888,.6973,.4009,1,.9003,.8744,.3086,1,.9117,.9308,.2352,1,.9171,.9098,.1786,1,.9163,.8501,.1361,1,.9105,.7761,.1045,1,.9007,.7008,.0813,1,.8876,.6301,.0641,1,.872,.5661,.0514,1,.8545,.5094,.0418,1,.8354,.4596,.0345,1,.8152,.416,.029,1,0,.4601,1,1,0,.4552,1,1,0,.4022,1,1,0,.2965,1,1,0,.2054,1,1,0,.1411,1,1,0,.0974,1,1,0,.0682,1,1,0,.0486,1,1,0,.0354,1,1,0,.0264,1,1,0,.0202,1,1,0,.0157,1,1,0,.0125,1,1,0,.0102,1,1,0,.0084,1,1,.4601,.5649,1,1,.4552,.5595,1,1,.4022,.5014,1,1,.2965,.3849,1,1,.2054,.2817,1,1,.1411,.2046,1,1,.0974,.1486,1,1,.0682,.1087,1,1,.0486,.0805,1,1,.0354,.0606,1,1,.0264,.0464,1,1,.0202,.0363,1,1,.0157,.0289,1,1,.0125,.0234,1,1,.0102,.0193,1,1,.0084,.0161,1,1,.5649,.6149,1,1,.5595,.6095,1,1,.5014,.5501,1,1,.3849,.4307,1,1,.2817,.3241,1,1,.2046,.2423,1,1,.1486,.1807,1,1,.1087,.1353,1,1,.0805,.1023,1,1,.0606,.0784,1,1,.0464,.061,1,1,.0363,.0483,1,1,.0289,.0389,1,1,.0234,.0318,1,1,.0193,.0265,1,1,.0161,.0223,1,1,.6149,.6434,1,1,.6095,.638,1,1,.5501,.5783,1,1,.4307,.4581,1,1,.3241,.3505,1,1,.2423,.2667,1,1,.1807,.2023,1,1,.1353,.1538,1,1,.1023,.1178,1,1,.0784,.0914,1,1,.061,.0719,1,1,.0483,.0574,1,1,.0389,.0466,1,1,.0318,.0384,1,1,.0265,.0321,1,1,.0223,.0272,1,1,.6434,.6604,1,1,.638,.6551,1,1,.5783,.5954,1,1,.4581,.4752,1,1,.3505,.3675,1,1,.2667,.2829,1,1,.2023,.2169,1,1,.1538,.1666,1,1,.1178,.1289,1,1,.0914,.1008,1,1,.0719,.0798,1,1,.0574,.0642,1,1,.0466,.0524,1,1,.0384,.0433,1,1,.0321,.0364,1,1,.0272,.031,1,1,.6604,.6702,1,1,.6551,.6649,1,1,.5954,.6053,1,1,.4752,.4854,1,1,.3675,.378,1,1,.2829,.2932,1,1,.2169,.2265,1,1,.1666,.1753,1,1,.1289,.1364,1,1,.1008,.1073,1,1,.0798,.0855,1,1,.0642,.069,1,1,.0524,.0565,1,1,.0433,.047,1,1,.0364,.0395,1,1,.031,.0337,1,1,.6702,.6747,1,1,.6649,.6694,1,1,.6053,.6101,1,1,.4854,.4906,1,1,.378,.3837,1,1,.2932,.299,1,1,.2265,.2322,1,1,.1753,.1805,1,1,.1364,.1412,1,1,.1073,.1115,1,1,.0855,.0891,1,1,.069,.0722,1,1,.0565,.0593,1,1,.047,.0494,1,1,.0395,.0417,1,1,.0337,.0356,1,1,.6747,.6751,1,1,.6694,.6699,1,1,.6101,.6108,1,1,.4906,.4918,1,1,.3837,.3854,1,1,.299,.3012,1,1,.2322,.2346,1,1,.1805,.1829,1,1,.1412,.1434,1,1,.1115,.1136,1,1,.0891,.091,1,1,.0722,.0739,1,1,.0593,.0608,1,1,.0494,.0508,1,1,.0417,.0429,1,1,.0356,.0367,1,1,.6751,.672,1,1,.6699,.6668,1,1,.6108,.608,1,1,.4918,.4895,1,1,.3854,.3838,1,1,.3012,.3002,1,1,.2346,.234,1,1,.1829,.1827,1,1,.1434,.1435,1,1,.1136,.1138,1,1,.091,.0914,1,1,.0739,.0743,1,1,.0608,.0612,1,1,.0508,.0512,1,1,.0429,.0433,1,1,.0367,.0371,1,1,.672,.6657,1,1,.6668,.6605,1,1,.608,.6019,1,1,.4895,.4841,1,1,.3838,.379,1,1,.3002,.2962,1,1,.234,.2309,1,1,.1827,.1803,1,1,.1435,.1417,1,1,.1138,.1124,1,1,.0914,.0903,1,1,.0743,.0735,1,1,.0612,.0606,1,1,.0512,.0506,1,1,.0433,.0429,1,1,.0371,.0368,1,1,.6657,.6562,1,1,.6605,.6511,1,1,.6019,.5928,1,1,.4841,.4756,1,1,.379,.3714,1,1,.2962,.2895,1,1,.2309,.2252,1,1,.1803,.1756,1,1,.1417,.1379,1,1,.1124,.1094,1,1,.0903,.0878,1,1,.0735,.0714,1,1,.0606,.0589,1,1,.0506,.0493,1,1,.0429,.0417,1,1,.0368,.0358,1,1,.6562,.6436,1,1,.6511,.6384,1,1,.5928,.5805,1,1,.4756,.4642,1,1,.3714,.3608,1,1,.2895,.2801,1,1,.2252,.2172,1,1,.1756,.1689,1,1,.1379,.1323,1,1,.1094,.1048,1,1,.0878,.084,1,1,.0714,.0683,1,1,.0589,.0563,1,1,.0493,.047,1,1,.0417,.0398,1,1,.0358,.0341,1,1,.6436,.6275,1,1,.6384,.6224,1,1,.5805,.565,1,1,.4642,.4495,1,1,.3608,.3472,1,1,.2801,.2679,1,1,.2172,.2067,1,1,.1689,.16,1,1,.1323,.125,1,1,.1048,.0987,1,1,.084,.079,1,1,.0683,.0641,1,1,.0563,.0527,1,1,.047,.044,1,1,.0398,.0372,1,1,.0341,.0319,1,1,.6275,.6078,1,1,.6224,.6027,1,1,.565,.5458,1,1,.4495,.4316,1,1,.3472,.3305,1,1,.2679,.2529,1,1,.2067,.1937,1,1,.16,.1491,1,1,.125,.1158,1,1,.0987,.0911,1,1,.079,.0726,1,1,.0641,.0588,1,1,.0527,.0483,1,1,.044,.0402,1,1,.0372,.0339,1,1,.0319,.029,1,1,.6078,.5838,1,1,.6027,.5788,1,1,.5458,.5226,1,1,.4316,.4099,1,1,.3305,.3105,1,1,.2529,.235,1,1,.1937,.1781,1,1,.1491,.1359,1,1,.1158,.1048,1,1,.0911,.0819,1,1,.0726,.065,1,1,.0588,.0524,1,1,.0483,.0428,1,1,.0402,.0356,1,1,.0339,.0299,1,1,.029,.0255,1,1,.5838,.5551,1,1,.5788,.5501,1,1,.5226,.4948,1,1,.4099,.384,1,1,.3105,.2867,1,1,.235,.2137,1,1,.1781,.1598,1,1,.1359,.1204,1,1,.1048,.0919,1,1,.0819,.0712,1,1,.065,.056,1,1,.0524,.0448,1,1,.0428,.0365,1,1,.0356,.0301,1,1,.0299,.0253,1,1,.0255,.0215,1,1,1,3e-4,.4889,1,.9994,.002,.4874,1,.9894,.0281,.4696,1,.9511,.1226,.4131,1,.9046,.2856,.3306,1,.8809,.4505,.2533,1,.8752,.5628,.1913,1,.8737,.6152,.1439,1,.8693,.6237,.1084,1,.8596,.6057,.0821,1,.8444,.5742,.0629,1,.8245,.537,.0487,1,.8007,.4985,.0382,1,.7739,.4613,.0303,1,.745,.4264,.0244,1,.7147,.3943,.0199,1,0,.2156,1,1,0,.215,1,1,0,.2064,1,1,0,.177,1,1,0,.1336,1,1,0,.0949,1,1,0,.0665,1,1,0,.0469,1,1,0,.0334,1,1,0,.0243,1,1,0,.018,1,1,0,.0135,1,1,0,.0104,1,1,0,.0081,1,1,0,.0064,1,1,0,.0052,1,1,.2156,.3209,1,1,.215,.3199,1,1,.2064,.3074,1,1,.177,.2667,1,1,.1336,.2071,1,1,.0949,.1529,1,1,.0665,.1116,1,1,.0469,.0817,1,1,.0334,.0603,1,1,.0243,.0451,1,1,.018,.0342,1,1,.0135,.0263,1,1,.0104,.0206,1,1,.0081,.0164,1,1,.0064,.0132,1,1,.0052,.0107,1,1,.3209,.3796,1,1,.3199,.3785,1,1,.3074,.3642,1,1,.2667,.3183,1,1,.2071,.2512,1,1,.1529,.1895,1,1,.1116,.1415,1,1,.0817,.1058,1,1,.0603,.0796,1,1,.0451,.0605,1,1,.0342,.0466,1,1,.0263,.0363,1,1,.0206,.0288,1,1,.0164,.0231,1,1,.0132,.0187,1,1,.0107,.0154,1,1,.3796,.4159,1,1,.3785,.4147,1,1,.3642,.3995,1,1,.3183,.3509,1,1,.2512,.2798,1,1,.1895,.214,1,1,.1415,.1621,1,1,.1058,.1229,1,1,.0796,.0937,1,1,.0605,.072,1,1,.0466,.056,1,1,.0363,.0441,1,1,.0288,.0351,1,1,.0231,.0284,1,1,.0187,.0232,1,1,.0154,.0192,1,1,.4159,.4389,1,1,.4147,.4377,1,1,.3995,.422,1,1,.3509,.372,1,1,.2798,.2987,1,1,.214,.2306,1,1,.1621,.1764,1,1,.1229,.135,1,1,.0937,.1038,1,1,.072,.0805,1,1,.056,.063,1,1,.0441,.0499,1,1,.0351,.04,1,1,.0284,.0325,1,1,.0232,.0266,1,1,.0192,.0221,1,1,.4389,.453,1,1,.4377,.4517,1,1,.422,.4359,1,1,.372,.3851,1,1,.2987,.3107,1,1,.2306,.2414,1,1,.1764,.186,1,1,.135,.1433,1,1,.1038,.1109,1,1,.0805,.0864,1,1,.063,.068,1,1,.0499,.0541,1,1,.04,.0436,1,1,.0325,.0355,1,1,.0266,.0292,1,1,.0221,.0243,1,1,.453,.4604,1,1,.4517,.4591,1,1,.4359,.4432,1,1,.3851,.3922,1,1,.3107,.3174,1,1,.2414,.2477,1,1,.186,.1917,1,1,.1433,.1484,1,1,.1109,.1154,1,1,.0864,.0903,1,1,.068,.0713,1,1,.0541,.057,1,1,.0436,.046,1,1,.0355,.0375,1,1,.0292,.031,1,1,.0243,.0258,1,1,.4604,.4625,1,1,.4591,.4612,1,1,.4432,.4453,1,1,.3922,.3945,1,1,.3174,.3199,1,1,.2477,.2502,1,1,.1917,.1943,1,1,.1484,.1509,1,1,.1154,.1176,1,1,.0903,.0923,1,1,.0713,.0731,1,1,.057,.0585,1,1,.046,.0473,1,1,.0375,.0387,1,1,.031,.032,1,1,.0258,.0267,1,1,.4625,.46,1,1,.4612,.4587,1,1,.4453,.443,1,1,.3945,.3926,1,1,.3199,.3186,1,1,.2502,.2495,1,1,.1943,.194,1,1,.1509,.151,1,1,.1176,.1179,1,1,.0923,.0927,1,1,.0731,.0735,1,1,.0585,.0589,1,1,.0473,.0478,1,1,.0387,.0391,1,1,.032,.0324,1,1,.0267,.0271,1,1,.46,.4533,1,1,.4587,.452,1,1,.443,.4366,1,1,.3926,.3869,1,1,.3186,.3139,1,1,.2495,.2458,1,1,.194,.1912,1,1,.151,.1489,1,1,.1179,.1163,1,1,.0927,.0916,1,1,.0735,.0727,1,1,.0589,.0583,1,1,.0478,.0473,1,1,.0391,.0387,1,1,.0324,.0321,1,1,.0271,.0268,1,1,.4533,.4427,1,1,.452,.4415,1,1,.4366,.4264,1,1,.3869,.3776,1,1,.3139,.306,1,1,.2458,.2394,1,1,.1912,.186,1,1,.1489,.1447,1,1,.1163,.1131,1,1,.0916,.089,1,1,.0727,.0706,1,1,.0583,.0567,1,1,.0473,.0459,1,1,.0387,.0377,1,1,.0321,.0312,1,1,.0268,.0261,1,1,.4427,.4283,1,1,.4415,.4271,1,1,.4264,.4124,1,1,.3776,.3648,1,1,.306,.2951,1,1,.2394,.2302,1,1,.186,.1785,1,1,.1447,.1386,1,1,.1131,.1081,1,1,.089,.085,1,1,.0706,.0674,1,1,.0567,.054,1,1,.0459,.0438,1,1,.0377,.0359,1,1,.0312,.0297,1,1,.0261,.0249,1,1,.4283,.4098,1,1,.4271,.4087,1,1,.4124,.3945,1,1,.3648,.3485,1,1,.2951,.281,1,1,.2302,.2184,1,1,.1785,.1687,1,1,.1386,.1305,1,1,.1081,.1015,1,1,.085,.0796,1,1,.0674,.0631,1,1,.054,.0505,1,1,.0438,.0409,1,1,.0359,.0335,1,1,.0297,.0277,1,1,.0249,.0231,1,1,.4098,.3872,1,1,.4087,.3861,1,1,.3945,.3726,1,1,.3485,.3284,1,1,.281,.2637,1,1,.2184,.2038,1,1,.1687,.1565,1,1,.1305,.1205,1,1,.1015,.0933,1,1,.0796,.0729,1,1,.0631,.0576,1,1,.0505,.046,1,1,.0409,.0372,1,1,.0335,.0304,1,1,.0277,.0251,1,1,.0231,.0209,1,1,.3872,.3601,1,1,.3861,.3591,1,1,.3726,.3462,1,1,.3284,.3044,1,1,.2637,.2429,1,1,.2038,.1863,1,1,.1565,.1419,1,1,.1205,.1085,1,1,.0933,.0835,1,1,.0729,.0649,1,1,.0576,.051,1,1,.046,.0406,1,1,.0372,.0327,1,1,.0304,.0266,1,1,.0251,.0219,1,1,.0209,.0183,1,1,.3601,.328,1,1,.3591,.3271,1,1,.3462,.3151,1,1,.3044,.276,1,1,.2429,.2184,1,1,.1863,.1657,1,1,.1419,.1248,1,1,.1085,.0944,1,1,.0835,.0719,1,1,.0649,.0554,1,1,.051,.0433,1,1,.0406,.0342,1,1,.0327,.0274,1,1,.0266,.0222,1,1,.0219,.0182,1,1,.0183,.0151,1,1,1,0,.3277,1,.9999,7e-4,.3272,1,.9955,.0104,.3205,1,.9751,.0486,.2969,1,.9352,.129,.2521,1,.8955,.2363,.1989,1,.8698,.3371,.1513,1,.8545,.4098,.1136,1,.8416,.4511,.085,1,.8258,.4674,.0639,1,.805,.4664,.0484,1,.7792,.4547,.0369,1,.7489,.437,.0285,1,.7152,.4164,.0223,1,.6791,.3948,.0176,1,.6416,.3732,.014,1,0,.1041,1,1,0,.1041,1,1,0,.1027,1,1,0,.0956,1,1,0,.08,1,1,0,.061,1,1,0,.0444,1,1,0,.0319,1,1,0,.023,1,1,0,.0167,1,1,0,.0124,1,1,0,.0093,1,1,0,.007,1,1,0,.0054,1,1,0,.0042,1,1,0,.0034,1,1,.1041,.1837,1,1,.1041,.1835,1,1,.1027,.1803,1,1,.0956,.1673,1,1,.08,.141,1,1,.061,.1097,1,1,.0444,.082,1,1,.0319,.0606,1,1,.023,.0449,1,1,.0167,.0335,1,1,.0124,.0253,1,1,.0093,.0193,1,1,.007,.015,1,1,.0054,.0117,1,1,.0042,.0093,1,1,.0034,.0074,1,1,.1837,.235,1,1,.1835,.2347,1,1,.1803,.2304,1,1,.1673,.2139,1,1,.141,.1816,1,1,.1097,.143,1,1,.082,.1087,1,1,.0606,.0818,1,1,.0449,.0616,1,1,.0335,.0467,1,1,.0253,.0357,1,1,.0193,.0276,1,1,.015,.0216,1,1,.0117,.0171,1,1,.0093,.0136,1,1,.0074,.011,1,1,.235,.2693,1,1,.2347,.269,1,1,.2304,.264,1,1,.2139,.2454,1,1,.1816,.2093,1,1,.143,.1663,1,1,.1087,.1278,1,1,.0818,.0973,1,1,.0616,.0741,1,1,.0467,.0567,1,1,.0357,.0438,1,1,.0276,.0341,1,1,.0216,.0269,1,1,.0171,.0214,1,1,.0136,.0172,1,1,.011,.014,1,1,.2693,.2924,1,1,.269,.292,1,1,.264,.2866,1,1,.2454,.2667,1,1,.2093,.2283,1,1,.1663,.1825,1,1,.1278,.1413,1,1,.0973,.1085,1,1,.0741,.0833,1,1,.0567,.0642,1,1,.0438,.0499,1,1,.0341,.0392,1,1,.0269,.031,1,1,.0214,.0248,1,1,.0172,.02,1,1,.014,.0163,1,1,.2924,.3072,1,1,.292,.3069,1,1,.2866,.3012,1,1,.2667,.2806,1,1,.2283,.2408,1,1,.1825,.1934,1,1,.1413,.1506,1,1,.1085,.1163,1,1,.0833,.0898,1,1,.0642,.0696,1,1,.0499,.0544,1,1,.0392,.0428,1,1,.031,.034,1,1,.0248,.0273,1,1,.02,.0221,1,1,.0163,.0181,1,1,.3072,.3158,1,1,.3069,.3154,1,1,.3012,.3097,1,1,.2806,.2887,1,1,.2408,.2483,1,1,.1934,.2,1,1,.1506,.1564,1,1,.1163,.1212,1,1,.0898,.094,1,1,.0696,.0732,1,1,.0544,.0574,1,1,.0428,.0453,1,1,.034,.0361,1,1,.0273,.0291,1,1,.0221,.0236,1,1,.0181,.0193,1,1,.3158,.3191,1,1,.3154,.3188,1,1,.3097,.313,1,1,.2887,.292,1,1,.2483,.2514,1,1,.2,.203,1,1,.1564,.1591,1,1,.1212,.1237,1,1,.094,.0962,1,1,.0732,.0751,1,1,.0574,.059,1,1,.0453,.0468,1,1,.0361,.0374,1,1,.0291,.0301,1,1,.0236,.0245,1,1,.0193,.0201,1,1,.3191,.318,1,1,.3188,.3176,1,1,.313,.3119,1,1,.292,.2911,1,1,.2514,.2508,1,1,.203,.2028,1,1,.1591,.1592,1,1,.1237,.124,1,1,.0962,.0967,1,1,.0751,.0756,1,1,.059,.0595,1,1,.0468,.0472,1,1,.0374,.0378,1,1,.0301,.0305,1,1,.0245,.0248,1,1,.0201,.0204,1,1,.318,.3128,1,1,.3176,.3124,1,1,.3119,.3068,1,1,.2911,.2864,1,1,.2508,.2469,1,1,.2028,.1997,1,1,.1592,.1569,1,1,.124,.1223,1,1,.0967,.0954,1,1,.0756,.0747,1,1,.0595,.0589,1,1,.0472,.0467,1,1,.0378,.0374,1,1,.0305,.0302,1,1,.0248,.0246,1,1,.0204,.0202,1,1,.3128,.3038,1,1,.3124,.3034,1,1,.3068,.298,1,1,.2864,.2782,1,1,.2469,.2398,1,1,.1997,.1939,1,1,.1569,.1523,1,1,.1223,.1187,1,1,.0954,.0926,1,1,.0747,.0725,1,1,.0589,.0572,1,1,.0467,.0454,1,1,.0374,.0364,1,1,.0302,.0294,1,1,.0246,.0239,1,1,.0202,.0197,1,1,.3038,.2911,1,1,.3034,.2908,1,1,.298,.2856,1,1,.2782,.2667,1,1,.2398,.2297,1,1,.1939,.1855,1,1,.1523,.1456,1,1,.1187,.1133,1,1,.0926,.0883,1,1,.0725,.0691,1,1,.0572,.0544,1,1,.0454,.0432,1,1,.0364,.0346,1,1,.0294,.028,1,1,.0239,.0228,1,1,.0197,.0187,1,1,.2911,.2747,1,1,.2908,.2744,1,1,.2856,.2696,1,1,.2667,.2517,1,1,.2297,.2166,1,1,.1855,.1745,1,1,.1456,.1366,1,1,.1133,.1061,1,1,.0883,.0825,1,1,.0691,.0645,1,1,.0544,.0507,1,1,.0432,.0402,1,1,.0346,.0322,1,1,.028,.026,1,1,.0228,.0212,1,1,.0187,.0174,1,1,.2747,.2546,1,1,.2744,.2544,1,1,.2696,.2499,1,1,.2517,.2332,1,1,.2166,.2004,1,1,.1745,.161,1,1,.1366,.1256,1,1,.1061,.0972,1,1,.0825,.0753,1,1,.0645,.0587,1,1,.0507,.0461,1,1,.0402,.0365,1,1,.0322,.0291,1,1,.026,.0235,1,1,.0212,.0191,1,1,.0174,.0157,1,1,.2546,.2306,1,1,.2544,.2304,1,1,.2499,.2264,1,1,.2332,.2112,1,1,.2004,.181,1,1,.161,.1448,1,1,.1256,.1123,1,1,.0972,.0864,1,1,.0753,.0667,1,1,.0587,.0517,1,1,.0461,.0404,1,1,.0365,.0319,1,1,.0291,.0254,1,1,.0235,.0204,1,1,.0191,.0166,1,1,.0157,.0136,1,1,.2306,.2025,1,1,.2304,.2023,1,1,.2264,.1988,1,1,.2112,.1853,1,1,.181,.1583,1,1,.1448,.1258,1,1,.1123,.0968,1,1,.0864,.0739,1,1,.0667,.0565,1,1,.0517,.0435,1,1,.0404,.0338,1,1,.0319,.0265,1,1,.0254,.021,1,1,.0204,.0168,1,1,.0166,.0136,1,1,.0136,.0111,1,1,1,0,.2121,1,.9999,0,.2119,1,.9976,.0047,.2095,1,.9854,.0224,.1999,1,.9564,.0638,.1784,1,.9163,.1289,.1472,1,.8792,.2046,.1149,1,.8508,.2736,.0871,1,.8274,.3262,.0653,1,.8038,.3603,.0489,1,.7767,.3787,.0368,1,.745,.3853,.0278,1,.7089,.3836,.0213,1,.6693,.3766,.0164,1,.6275,.3662,.0127,1,.5845,.3541,.01,1,0,.0521,1,1,0,.0521,1,1,0,.052,1,1,0,.0506,1,1,0,.0457,1,1,0,.0376,1,1,0,.0289,1,1,0,.0214,1,1,0,.0157,1,1,0,.0116,1,1,0,.0086,1,1,0,.0064,1,1,0,.0049,1,1,0,.0037,1,1,0,.0029,1,1,0,.0022,1,1,.0521,.106,1,1,.0521,.106,1,1,.052,.1053,1,1,.0506,.1013,1,1,.0457,.091,1,1,.0376,.0753,1,1,.0289,.0586,1,1,.0214,.0443,1,1,.0157,.0332,1,1,.0116,.0249,1,1,.0086,.0188,1,1,.0064,.0143,1,1,.0049,.011,1,1,.0037,.0085,1,1,.0029,.0067,1,1,.0022,.0053,1,1,.106,.1456,1,1,.106,.1456,1,1,.1053,.1443,1,1,.1013,.1385,1,1,.091,.1244,1,1,.0753,.1034,1,1,.0586,.0812,1,1,.0443,.0622,1,1,.0332,.0472,1,1,.0249,.0358,1,1,.0188,.0274,1,1,.0143,.021,1,1,.011,.0163,1,1,.0085,.0128,1,1,.0067,.0101,1,1,.0053,.008,1,1,.1456,.1742,1,1,.1456,.1741,1,1,.1443,.1724,1,1,.1385,.1653,1,1,.1244,.1486,1,1,.1034,.124,1,1,.0812,.0982,1,1,.0622,.0758,1,1,.0472,.058,1,1,.0358,.0445,1,1,.0274,.0342,1,1,.021,.0265,1,1,.0163,.0207,1,1,.0128,.0163,1,1,.0101,.0129,1,1,.008,.0103,1,1,.1742,.1944,1,1,.1741,.1943,1,1,.1724,.1924,1,1,.1653,.1843,1,1,.1486,.1659,1,1,.124,.1389,1,1,.0982,.1105,1,1,.0758,.0859,1,1,.058,.0662,1,1,.0445,.051,1,1,.0342,.0395,1,1,.0265,.0308,1,1,.0207,.0242,1,1,.0163,.0191,1,1,.0129,.0152,1,1,.0103,.0122,1,1,.1944,.2081,1,1,.1943,.208,1,1,.1924,.2059,1,1,.1843,.1973,1,1,.1659,.1778,1,1,.1389,.1492,1,1,.1105,.1192,1,1,.0859,.0931,1,1,.0662,.0721,1,1,.051,.0559,1,1,.0395,.0434,1,1,.0308,.034,1,1,.0242,.0267,1,1,.0191,.0212,1,1,.0152,.017,1,1,.0122,.0137,1,1,.2081,.2166,1,1,.208,.2164,1,1,.2059,.2142,1,1,.1973,.2053,1,1,.1778,.1851,1,1,.1492,.1557,1,1,.1192,.1248,1,1,.0931,.0978,1,1,.0721,.076,1,1,.0559,.0591,1,1,.0434,.0461,1,1,.034,.0362,1,1,.0267,.0286,1,1,.0212,.0227,1,1,.017,.0182,1,1,.0137,.0147,1,1,.2166,.2206,1,1,.2164,.2204,1,1,.2142,.2182,1,1,.2053,.2091,1,1,.1851,.1887,1,1,.1557,.1589,1,1,.1248,.1277,1,1,.0978,.1003,1,1,.076,.0782,1,1,.0591,.0609,1,1,.0461,.0477,1,1,.0362,.0375,1,1,.0286,.0296,1,1,.0227,.0236,1,1,.0182,.019,1,1,.0147,.0153,1,1,.2206,.2206,1,1,.2204,.2205,1,1,.2182,.2182,1,1,.2091,.2092,1,1,.1887,.1889,1,1,.1589,.1593,1,1,.1277,.1281,1,1,.1003,.1008,1,1,.0782,.0787,1,1,.0609,.0615,1,1,.0477,.0482,1,1,.0375,.0379,1,1,.0296,.0301,1,1,.0236,.024,1,1,.019,.0193,1,1,.0153,.0156,1,1,.2206,.2171,1,1,.2205,.2169,1,1,.2182,.2148,1,1,.2092,.206,1,1,.1889,.186,1,1,.1593,.1569,1,1,.1281,.1263,1,1,.1008,.0995,1,1,.0787,.0778,1,1,.0615,.0608,1,1,.0482,.0477,1,1,.0379,.0376,1,1,.0301,.0298,1,1,.024,.0238,1,1,.0193,.0191,1,1,.0156,.0155,1,1,.2171,.2102,1,1,.2169,.2101,1,1,.2148,.208,1,1,.206,.1996,1,1,.186,.1803,1,1,.1569,.1521,1,1,.1263,.1225,1,1,.0995,.0965,1,1,.0778,.0755,1,1,.0608,.059,1,1,.0477,.0463,1,1,.0376,.0365,1,1,.0298,.029,1,1,.0238,.0231,1,1,.0191,.0186,1,1,.0155,.0151,1,1,.2102,.2002,1,1,.2101,.2001,1,1,.208,.1982,1,1,.1996,.1902,1,1,.1803,.1718,1,1,.1521,.145,1,1,.1225,.1167,1,1,.0965,.0918,1,1,.0755,.0718,1,1,.059,.0561,1,1,.0463,.044,1,1,.0365,.0347,1,1,.029,.0276,1,1,.0231,.022,1,1,.0186,.0177,1,1,.0151,.0143,1,1,.2002,.1871,1,1,.2001,.187,1,1,.1982,.1852,1,1,.1902,.1778,1,1,.1718,.1606,1,1,.145,.1355,1,1,.1167,.1089,1,1,.0918,.0856,1,1,.0718,.0668,1,1,.0561,.0522,1,1,.044,.0409,1,1,.0347,.0322,1,1,.0276,.0256,1,1,.022,.0204,1,1,.0177,.0164,1,1,.0143,.0133,1,1,.1871,.1709,1,1,.187,.1708,1,1,.1852,.1692,1,1,.1778,.1625,1,1,.1606,.1468,1,1,.1355,.1236,1,1,.1089,.0992,1,1,.0856,.0778,1,1,.0668,.0606,1,1,.0522,.0472,1,1,.0409,.037,1,1,.0322,.0291,1,1,.0256,.023,1,1,.0204,.0184,1,1,.0164,.0148,1,1,.0133,.0119,1,1,.1709,.1515,1,1,.1708,.1514,1,1,.1692,.1501,1,1,.1625,.1442,1,1,.1468,.1303,1,1,.1236,.1095,1,1,.0992,.0876,1,1,.0778,.0684,1,1,.0606,.0531,1,1,.0472,.0412,1,1,.037,.0322,1,1,.0291,.0252,1,1,.023,.0199,1,1,.0184,.0159,1,1,.0148,.0127,1,1,.0119,.0103,1,1,.1515,.1289,1,1,.1514,.1288,1,1,.1501,.1278,1,1,.1442,.1229,1,1,.1303,.1109,1,1,.1095,.093,1,1,.0876,.074,1,1,.0684,.0575,1,1,.0531,.0443,1,1,.0412,.0342,1,1,.0322,.0265,1,1,.0252,.0207,1,1,.0199,.0163,1,1,.0159,.0129,1,1,.0127,.0103,1,1,.0103,.0083,1,1,1,0,.1317,1,1,0,.1317,1,.9985,.0025,.1311,1,.9904,.0121,.1277,1,.9694,.0356,.1186,1,.9343,.0766,.1026,1,.8935,.1309,.0831,1,.8558,.1889,.0644,1,.8226,.241,.0488,1,.7906,.2821,.0366,1,.7566,.3112,.0275,1,.7188,.3296,.0207,1,.6771,.3395,.0157,1,.6322,.343,.012,1,.5854,.342,.0092,1,.5379,.338,.0071,1,0,.0269,1,1,0,.0269,1,1,0,.0271,1,1,0,.027,1,1,0,.0257,1,1,0,.0226,1,1,0,.0184,1,1,0,.0142,1,1,0,.0107,1,1,0,.008,1,1,0,.006,1,1,0,.0045,1,1,0,.0034,1,1,0,.0026,1,1,0,.002,1,1,0,.0015,1,1,.0269,.0616,1,1,.0269,.0616,1,1,.0271,.0616,1,1,.027,.0606,1,1,.0257,.057,1,1,.0226,.0498,1,1,.0184,.0407,1,1,.0142,.0317,1,1,.0107,.0242,1,1,.008,.0183,1,1,.006,.0139,1,1,.0045,.0106,1,1,.0034,.0081,1,1,.0026,.0062,1,1,.002,.0048,1,1,.0015,.0038,1,1,.0616,.0901,1,1,.0616,.0901,1,1,.0616,.0899,1,1,.0606,.0881,1,1,.057,.0824,1,1,.0498,.072,1,1,.0407,.059,1,1,.0317,.0463,1,1,.0242,.0357,1,1,.0183,.0273,1,1,.0139,.0209,1,1,.0106,.016,1,1,.0081,.0124,1,1,.0062,.0096,1,1,.0048,.0075,1,1,.0038,.0059,1,1,.0901,.1121,1,1,.0901,.1121,1,1,.0899,.1117,1,1,.0881,.1092,1,1,.0824,.1019,1,1,.072,.0891,1,1,.059,.0733,1,1,.0463,.0579,1,1,.0357,.0449,1,1,.0273,.0346,1,1,.0209,.0266,1,1,.016,.0206,1,1,.0124,.016,1,1,.0096,.0125,1,1,.0075,.0098,1,1,.0059,.0078,1,1,.1121,.1286,1,1,.1121,.1285,1,1,.1117,.1279,1,1,.1092,.1249,1,1,.1019,.1165,1,1,.0891,.1019,1,1,.0733,.084,1,1,.0579,.0667,1,1,.0449,.052,1,1,.0346,.0402,1,1,.0266,.0311,1,1,.0206,.0242,1,1,.016,.0188,1,1,.0125,.0148,1,1,.0098,.0117,1,1,.0078,.0093,1,1,.1286,.1402,1,1,.1285,.1402,1,1,.1279,.1395,1,1,.1249,.136,1,1,.1165,.1269,1,1,.1019,.1111,1,1,.084,.0918,1,1,.0667,.0731,1,1,.052,.0572,1,1,.0402,.0444,1,1,.0311,.0345,1,1,.0242,.0269,1,1,.0188,.021,1,1,.0148,.0165,1,1,.0117,.0131,1,1,.0093,.0104,1,1,.1402,.1478,1,1,.1402,.1478,1,1,.1395,.147,1,1,.136,.1433,1,1,.1269,.1336,1,1,.1111,.1171,1,1,.0918,.097,1,1,.0731,.0774,1,1,.0572,.0607,1,1,.0444,.0473,1,1,.0345,.0369,1,1,.0269,.0288,1,1,.021,.0226,1,1,.0165,.0178,1,1,.0131,.0141,1,1,.0104,.0113,1,1,.1478,.1518,1,1,.1478,.1518,1,1,.147,.151,1,1,.1433,.1471,1,1,.1336,.1372,1,1,.1171,.1204,1,1,.097,.0998,1,1,.0774,.0798,1,1,.0607,.0628,1,1,.0473,.049,1,1,.0369,.0383,1,1,.0288,.03,1,1,.0226,.0235,1,1,.0178,.0186,1,1,.0141,.0148,1,1,.0113,.0118,1,1,.1518,.1526,1,1,.1518,.1526,1,1,.151,.1518,1,1,.1471,.1479,1,1,.1372,.138,1,1,.1204,.1211,1,1,.0998,.1005,1,1,.0798,.0805,1,1,.0628,.0634,1,1,.049,.0496,1,1,.0383,.0388,1,1,.03,.0304,1,1,.0235,.0239,1,1,.0186,.0189,1,1,.0148,.015,1,1,.0118,.012,1,1,.1526,.1505,1,1,.1526,.1505,1,1,.1518,.1497,1,1,.1479,.1459,1,1,.138,.1361,1,1,.1211,.1195,1,1,.1005,.0993,1,1,.0805,.0796,1,1,.0634,.0628,1,1,.0496,.0492,1,1,.0388,.0385,1,1,.0304,.0302,1,1,.0239,.0238,1,1,.0189,.0188,1,1,.015,.015,1,1,.012,.012,1,1,.1505,.1457,1,1,.1505,.1456,1,1,.1497,.1449,1,1,.1459,.1412,1,1,.1361,.1319,1,1,.1195,.1158,1,1,.0993,.0962,1,1,.0796,.0772,1,1,.0628,.0609,1,1,.0492,.0477,1,1,.0385,.0374,1,1,.0302,.0293,1,1,.0238,.0231,1,1,.0188,.0183,1,1,.015,.0146,1,1,.012,.0117,1,1,.1457,.1382,1,1,.1456,.1382,1,1,.1449,.1375,1,1,.1412,.1341,1,1,.1319,.1252,1,1,.1158,.11,1,1,.0962,.0914,1,1,.0772,.0733,1,1,.0609,.0579,1,1,.0477,.0453,1,1,.0374,.0355,1,1,.0293,.0279,1,1,.0231,.022,1,1,.0183,.0174,1,1,.0146,.0139,1,1,.0117,.0111,1,1,.1382,.1283,1,1,.1382,.1283,1,1,.1375,.1276,1,1,.1341,.1246,1,1,.1252,.1164,1,1,.11,.1023,1,1,.0914,.0849,1,1,.0733,.0681,1,1,.0579,.0537,1,1,.0453,.0421,1,1,.0355,.0329,1,1,.0279,.0258,1,1,.022,.0204,1,1,.0174,.0161,1,1,.0139,.0128,1,1,.0111,.0103,1,1,.1283,.1159,1,1,.1283,.1159,1,1,.1276,.1153,1,1,.1246,.1126,1,1,.1164,.1053,1,1,.1023,.0925,1,1,.0849,.0768,1,1,.0681,.0615,1,1,.0537,.0484,1,1,.0421,.0379,1,1,.0329,.0296,1,1,.0258,.0232,1,1,.0204,.0183,1,1,.0161,.0144,1,1,.0128,.0115,1,1,.0103,.0092,1,1,.1159,.101,1,1,.1159,.101,1,1,.1153,.1006,1,1,.1126,.0983,1,1,.1053,.092,1,1,.0925,.0808,1,1,.0768,.067,1,1,.0615,.0536,1,1,.0484,.042,1,1,.0379,.0328,1,1,.0296,.0256,1,1,.0232,.02,1,1,.0183,.0157,1,1,.0144,.0124,1,1,.0115,.0099,1,1,.0092,.0079,1,1,.101,.0837,1,1,.101,.0836,1,1,.1006,.0834,1,1,.0983,.0816,1,1,.092,.0765,1,1,.0808,.0672,1,1,.067,.0556,1,1,.0536,.0442,1,1,.042,.0346,1,1,.0328,.0269,1,1,.0256,.0209,1,1,.02,.0163,1,1,.0157,.0127,1,1,.0124,.01,1,1,.0099,.0079,1,1,.0079,.0063,1,1,1,0,.0778,1,1,0,.0778,1,.999,.0015,.0779,1,.9931,.0073,.0773,1,.9774,.022,.0743,1,.9481,.049,.0673,1,.9079,.0883,.0569,1,.8651,.1349,.0456,1,.8239,.182,.0352,1,.7839,.2242,.0267,1,.7427,.2585,.0201,1,.6986,.2844,.0152,1,.6513,.3026,.0114,1,.6014,.3144,.0087,1,.5501,.3212,.0066,1,.4989,.3243,.0051,1,0,.0143,1,1,0,.0143,1,1,0,.0144,1,1,0,.0146,1,1,0,.0144,1,1,0,.0134,1,1,0,.0115,1,1,0,.0093,1,1,0,.0072,1,1,0,.0055,1,1,0,.0041,1,1,0,.0031,1,1,0,.0024,1,1,0,.0018,1,1,0,.0014,1,1,0,.0011,1,1,.0143,.0359,1,1,.0143,.0359,1,1,.0144,.036,1,1,.0146,.0361,1,1,.0144,.035,1,1,.0134,.0321,1,1,.0115,.0275,1,1,.0093,.0223,1,1,.0072,.0174,1,1,.0055,.0134,1,1,.0041,.0102,1,1,.0031,.0078,1,1,.0024,.006,1,1,.0018,.0046,1,1,.0014,.0035,1,1,.0011,.0027,1,1,.0359,.0555,1,1,.0359,.0555,1,1,.036,.0556,1,1,.0361,.0553,1,1,.035,.0533,1,1,.0321,.0486,1,1,.0275,.0416,1,1,.0223,.0338,1,1,.0174,.0266,1,1,.0134,.0206,1,1,.0102,.0158,1,1,.0078,.0121,1,1,.006,.0094,1,1,.0046,.0072,1,1,.0035,.0056,1,1,.0027,.0044,1,1,.0555,.0716,1,1,.0555,.0716,1,1,.0556,.0716,1,1,.0553,.071,1,1,.0533,.0682,1,1,.0486,.0621,1,1,.0416,.0531,1,1,.0338,.0432,1,1,.0266,.0341,1,1,.0206,.0266,1,1,.0158,.0205,1,1,.0121,.0159,1,1,.0094,.0123,1,1,.0072,.0095,1,1,.0056,.0074,1,1,.0044,.0058,1,1,.0716,.0842,1,1,.0716,.0842,1,1,.0716,.0841,1,1,.071,.0832,1,1,.0682,.0797,1,1,.0621,.0725,1,1,.0531,.062,1,1,.0432,.0506,1,1,.0341,.0401,1,1,.0266,.0313,1,1,.0205,.0243,1,1,.0159,.0189,1,1,.0123,.0147,1,1,.0095,.0114,1,1,.0074,.0089,1,1,.0058,.007,1,1,.0842,.0935,1,1,.0842,.0935,1,1,.0841,.0934,1,1,.0832,.0922,1,1,.0797,.0883,1,1,.0725,.0802,1,1,.062,.0687,1,1,.0506,.0562,1,1,.0401,.0446,1,1,.0313,.035,1,1,.0243,.0272,1,1,.0189,.0212,1,1,.0147,.0165,1,1,.0114,.0129,1,1,.0089,.0101,1,1,.007,.008,1,1,.0935,.0998,1,1,.0935,.0998,1,1,.0934,.0997,1,1,.0922,.0983,1,1,.0883,.0941,1,1,.0802,.0854,1,1,.0687,.0732,1,1,.0562,.06,1,1,.0446,.0478,1,1,.035,.0375,1,1,.0272,.0293,1,1,.0212,.0228,1,1,.0165,.0178,1,1,.0129,.014,1,1,.0101,.011,1,1,.008,.0087,1,1,.0998,.1035,1,1,.0998,.1035,1,1,.0997,.1033,1,1,.0983,.1018,1,1,.0941,.0974,1,1,.0854,.0884,1,1,.0732,.0759,1,1,.06,.0622,1,1,.0478,.0496,1,1,.0375,.039,1,1,.0293,.0305,1,1,.0228,.0239,1,1,.0178,.0187,1,1,.014,.0146,1,1,.011,.0115,1,1,.0087,.0091,1,1,.1035,.1047,1,1,.1035,.1047,1,1,.1033,.1045,1,1,.1018,.103,1,1,.0974,.0984,1,1,.0884,.0894,1,1,.0759,.0767,1,1,.0622,.063,1,1,.0496,.0503,1,1,.039,.0396,1,1,.0305,.031,1,1,.0239,.0243,1,1,.0187,.019,1,1,.0146,.0149,1,1,.0115,.0118,1,1,.0091,.0093,1,1,.1047,.1036,1,1,.1047,.1036,1,1,.1045,.1034,1,1,.103,.1019,1,1,.0984,.0974,1,1,.0894,.0885,1,1,.0767,.076,1,1,.063,.0624,1,1,.0503,.0499,1,1,.0396,.0394,1,1,.031,.0309,1,1,.0243,.0242,1,1,.019,.0189,1,1,.0149,.0149,1,1,.0118,.0117,1,1,.0093,.0093,1,1,.1036,.1004,1,1,.1036,.1004,1,1,.1034,.1001,1,1,.1019,.0987,1,1,.0974,.0944,1,1,.0885,.0858,1,1,.076,.0737,1,1,.0624,.0606,1,1,.0499,.0484,1,1,.0394,.0382,1,1,.0309,.03,1,1,.0242,.0235,1,1,.0189,.0184,1,1,.0149,.0145,1,1,.0117,.0114,1,1,.0093,.0091,1,1,.1004,.0951,1,1,.1004,.0951,1,1,.1001,.0949,1,1,.0987,.0936,1,1,.0944,.0895,1,1,.0858,.0814,1,1,.0737,.0699,1,1,.0606,.0575,1,1,.0484,.046,1,1,.0382,.0363,1,1,.03,.0285,1,1,.0235,.0223,1,1,.0184,.0175,1,1,.0145,.0138,1,1,.0114,.0109,1,1,.0091,.0086,1,1,.0951,.0879,1,1,.0951,.0879,1,1,.0949,.0877,1,1,.0936,.0865,1,1,.0895,.0828,1,1,.0814,.0753,1,1,.0699,.0648,1,1,.0575,.0532,1,1,.046,.0426,1,1,.0363,.0336,1,1,.0285,.0263,1,1,.0223,.0206,1,1,.0175,.0162,1,1,.0138,.0127,1,1,.0109,.0101,1,1,.0086,.008,1,1,.0879,.0787,1,1,.0879,.0787,1,1,.0877,.0786,1,1,.0865,.0776,1,1,.0828,.0744,1,1,.0753,.0677,1,1,.0648,.0582,1,1,.0532,.0478,1,1,.0426,.0382,1,1,.0336,.0301,1,1,.0263,.0236,1,1,.0206,.0185,1,1,.0162,.0145,1,1,.0127,.0114,1,1,.0101,.009,1,1,.008,.0071,1,1,.0787,.0677,1,1,.0787,.0677,1,1,.0786,.0677,1,1,.0776,.0669,1,1,.0744,.0642,1,1,.0677,.0585,1,1,.0582,.0503,1,1,.0478,.0413,1,1,.0382,.0329,1,1,.0301,.0259,1,1,.0236,.0203,1,1,.0185,.0158,1,1,.0145,.0124,1,1,.0114,.0097,1,1,.009,.0077,1,1,.0071,.0061,1,1,.0677,.0549,1,1,.0677,.0549,1,1,.0677,.0549,1,1,.0669,.0543,1,1,.0642,.0523,1,1,.0585,.0477,1,1,.0503,.041,1,1,.0413,.0336,1,1,.0329,.0267,1,1,.0259,.021,1,1,.0203,.0164,1,1,.0158,.0127,1,1,.0124,.0099,1,1,.0097,.0078,1,1,.0077,.0061,1,1,.0061,.0048,1,1,1,0,.0432,1,1,0,.0432,1,.9992,.001,.0435,1,.9947,.0048,.044,1,.9826,.0145,.0437,1,.9582,.0333,.0415,1,.9208,.0622,.0368,1,.876,.0993,.0307,1,.8291,.1403,.0244,1,.7818,.1806,.0189,1,.7336,.2168,.0144,1,.6832,.2471,.0109,1,.6303,.2712,.0082,1,.5755,.2895,.0062,1,.5201,.3029,.0047,1,.4656,.3123,.0036,1,0,.0077,1,1,0,.0077,1,1,0,.0078,1,1,0,.008,1,1,0,.0081,1,1,0,.0079,1,1,0,.0071,1,1,0,.006,1,1,0,.0048,1,1,0,.0038,1,1,0,.0029,1,1,0,.0022,1,1,0,.0017,1,1,0,.0013,1,1,0,.001,1,1,0,7e-4,1,1,.0077,.0209,1,1,.0077,.0209,1,1,.0078,.021,1,1,.008,.0213,1,1,.0081,.0212,1,1,.0079,.0202,1,1,.0071,.0181,1,1,.006,.0153,1,1,.0048,.0123,1,1,.0038,.0096,1,1,.0029,.0074,1,1,.0022,.0057,1,1,.0017,.0044,1,1,.0013,.0034,1,1,.001,.0026,1,1,7e-4,.002,1,1,.0209,.0338,1,1,.0209,.0339,1,1,.021,.034,1,1,.0213,.0342,1,1,.0212,.0338,1,1,.0202,.032,1,1,.0181,.0285,1,1,.0153,.024,1,1,.0123,.0194,1,1,.0096,.0152,1,1,.0074,.0118,1,1,.0057,.0091,1,1,.0044,.007,1,1,.0034,.0054,1,1,.0026,.0042,1,1,.002,.0033,1,1,.0338,.0451,1,1,.0339,.0451,1,1,.034,.0453,1,1,.0342,.0453,1,1,.0338,.0446,1,1,.032,.042,1,1,.0285,.0373,1,1,.024,.0314,1,1,.0194,.0254,1,1,.0152,.0201,1,1,.0118,.0157,1,1,.0091,.0121,1,1,.007,.0094,1,1,.0054,.0073,1,1,.0042,.0056,1,1,.0033,.0044,1,1,.0451,.0543,1,1,.0451,.0543,1,1,.0453,.0544,1,1,.0453,.0544,1,1,.0446,.0533,1,1,.042,.05,1,1,.0373,.0445,1,1,.0314,.0374,1,1,.0254,.0304,1,1,.0201,.024,1,1,.0157,.0188,1,1,.0121,.0146,1,1,.0094,.0113,1,1,.0073,.0088,1,1,.0056,.0069,1,1,.0044,.0054,1,1,.0543,.0613,1,1,.0543,.0614,1,1,.0544,.0614,1,1,.0544,.0613,1,1,.0533,.0599,1,1,.05,.0562,1,1,.0445,.0499,1,1,.0374,.042,1,1,.0304,.0341,1,1,.024,.0271,1,1,.0188,.0212,1,1,.0146,.0165,1,1,.0113,.0129,1,1,.0088,.01,1,1,.0069,.0078,1,1,.0054,.0061,1,1,.0613,.0664,1,1,.0614,.0664,1,1,.0614,.0664,1,1,.0613,.0662,1,1,.0599,.0646,1,1,.0562,.0605,1,1,.0499,.0537,1,1,.042,.0453,1,1,.0341,.0368,1,1,.0271,.0293,1,1,.0212,.023,1,1,.0165,.0179,1,1,.0129,.014,1,1,.01,.0109,1,1,.0078,.0085,1,1,.0061,.0067,1,1,.0664,.0695,1,1,.0664,.0695,1,1,.0664,.0695,1,1,.0662,.0692,1,1,.0646,.0675,1,1,.0605,.0632,1,1,.0537,.056,1,1,.0453,.0473,1,1,.0368,.0385,1,1,.0293,.0306,1,1,.023,.0241,1,1,.0179,.0188,1,1,.014,.0147,1,1,.0109,.0115,1,1,.0085,.009,1,1,.0067,.0071,1,1,.0695,.0707,1,1,.0695,.0707,1,1,.0695,.0708,1,1,.0692,.0704,1,1,.0675,.0686,1,1,.0632,.0642,1,1,.056,.057,1,1,.0473,.0481,1,1,.0385,.0392,1,1,.0306,.0312,1,1,.0241,.0246,1,1,.0188,.0192,1,1,.0147,.015,1,1,.0115,.0118,1,1,.009,.0092,1,1,.0071,.0072,1,1,.0707,.0703,1,1,.0707,.0703,1,1,.0708,.0703,1,1,.0704,.0699,1,1,.0686,.0682,1,1,.0642,.0638,1,1,.057,.0566,1,1,.0481,.0478,1,1,.0392,.0389,1,1,.0312,.0311,1,1,.0246,.0245,1,1,.0192,.0192,1,1,.015,.015,1,1,.0118,.0117,1,1,.0092,.0092,1,1,.0072,.0072,1,1,.0703,.0683,1,1,.0703,.0683,1,1,.0703,.0683,1,1,.0699,.0679,1,1,.0682,.0662,1,1,.0638,.0619,1,1,.0566,.0549,1,1,.0478,.0464,1,1,.0389,.0378,1,1,.0311,.0302,1,1,.0245,.0238,1,1,.0192,.0187,1,1,.015,.0146,1,1,.0117,.0114,1,1,.0092,.009,1,1,.0072,.0071,1,1,.0683,.0647,1,1,.0683,.0647,1,1,.0683,.0647,1,1,.0679,.0644,1,1,.0662,.0627,1,1,.0619,.0587,1,1,.0549,.0521,1,1,.0464,.044,1,1,.0378,.0359,1,1,.0302,.0287,1,1,.0238,.0226,1,1,.0187,.0177,1,1,.0146,.0139,1,1,.0114,.0109,1,1,.009,.0085,1,1,.0071,.0067,1,1,.0647,.0596,1,1,.0647,.0596,1,1,.0647,.0597,1,1,.0644,.0594,1,1,.0627,.0579,1,1,.0587,.0542,1,1,.0521,.0481,1,1,.044,.0407,1,1,.0359,.0332,1,1,.0287,.0265,1,1,.0226,.0209,1,1,.0177,.0164,1,1,.0139,.0128,1,1,.0109,.01,1,1,.0085,.0079,1,1,.0067,.0062,1,1,.0596,.0531,1,1,.0596,.0531,1,1,.0597,.0532,1,1,.0594,.053,1,1,.0579,.0517,1,1,.0542,.0484,1,1,.0481,.043,1,1,.0407,.0364,1,1,.0332,.0297,1,1,.0265,.0237,1,1,.0209,.0187,1,1,.0164,.0146,1,1,.0128,.0114,1,1,.01,.009,1,1,.0079,.007,1,1,.0062,.0055,1,1,.0531,.0452,1,1,.0531,.0453,1,1,.0532,.0453,1,1,.053,.0452,1,1,.0517,.0442,1,1,.0484,.0415,1,1,.043,.0369,1,1,.0364,.0312,1,1,.0297,.0254,1,1,.0237,.0202,1,1,.0187,.0159,1,1,.0146,.0125,1,1,.0114,.0098,1,1,.009,.0076,1,1,.007,.006,1,1,.0055,.0047,1,1,.0452,.036,1,1,.0453,.036,1,1,.0453,.0361,1,1,.0452,.036,1,1,.0442,.0353,1,1,.0415,.0333,1,1,.0369,.0296,1,1,.0312,.025,1,1,.0254,.0204,1,1,.0202,.0162,1,1,.0159,.0127,1,1,.0125,.0099,1,1,.0098,.0078,1,1,.0076,.0061,1,1,.006,.0047,1,1,.0047,.0037,1,1,1,0,.0221,1,1,0,.0222,1,.9995,7e-4,.0225,1,.9958,.0033,.0232,1,.986,.0102,.0239,1,.9656,.0237,.0238,1,.9316,.0454,.0224,1,.8869,.075,.0196,1,.8363,.1101,.0162,1,.7831,.1473,.0128,1,.7282,.1833,.0099,1,.6715,.216,.0076,1,.613,.2442,.0057,1,.5535,.2676,.0043,1,.4942,.2866,.0033,1,.4368,.3017,.0025,1,0,.0042,1,1,0,.0042,1,1,0,.0042,1,1,0,.0044,1,1,0,.0045,1,1,0,.0046,1,1,0,.0043,1,1,0,.0038,1,1,0,.0032,1,1,0,.0025,1,1,0,.002,1,1,0,.0015,1,1,0,.0012,1,1,0,9e-4,1,1,0,7e-4,1,1,0,5e-4,1,1,.0042,.012,1,1,.0042,.012,1,1,.0042,.0122,1,1,.0044,.0124,1,1,.0045,.0126,1,1,.0046,.0125,1,1,.0043,.0116,1,1,.0038,.0102,1,1,.0032,.0085,1,1,.0025,.0068,1,1,.002,.0054,1,1,.0015,.0041,1,1,.0012,.0032,1,1,9e-4,.0025,1,1,7e-4,.0019,1,1,5e-4,.0015,1,1,.012,.0203,1,1,.012,.0203,1,1,.0122,.0205,1,1,.0124,.0208,1,1,.0126,.0209,1,1,.0125,.0205,1,1,.0116,.019,1,1,.0102,.0166,1,1,.0085,.0138,1,1,.0068,.0111,1,1,.0054,.0087,1,1,.0041,.0068,1,1,.0032,.0053,1,1,.0025,.0041,1,1,.0019,.0031,1,1,.0015,.0024,1,1,.0203,.0279,1,1,.0203,.0279,1,1,.0205,.028,1,1,.0208,.0283,1,1,.0209,.0284,1,1,.0205,.0276,1,1,.019,.0255,1,1,.0166,.0222,1,1,.0138,.0185,1,1,.0111,.0149,1,1,.0087,.0118,1,1,.0068,.0092,1,1,.0053,.0071,1,1,.0041,.0055,1,1,.0031,.0043,1,1,.0024,.0033,1,1,.0279,.0342,1,1,.0279,.0343,1,1,.028,.0344,1,1,.0283,.0347,1,1,.0284,.0346,1,1,.0276,.0335,1,1,.0255,.0309,1,1,.0222,.0269,1,1,.0185,.0224,1,1,.0149,.0181,1,1,.0118,.0143,1,1,.0092,.0112,1,1,.0071,.0087,1,1,.0055,.0067,1,1,.0043,.0052,1,1,.0033,.0041,1,1,.0342,.0393,1,1,.0343,.0394,1,1,.0344,.0395,1,1,.0347,.0397,1,1,.0346,.0396,1,1,.0335,.0382,1,1,.0309,.0351,1,1,.0269,.0306,1,1,.0224,.0255,1,1,.0181,.0206,1,1,.0143,.0163,1,1,.0112,.0128,1,1,.0087,.0099,1,1,.0067,.0077,1,1,.0052,.006,1,1,.0041,.0047,1,1,.0393,.0431,1,1,.0394,.0431,1,1,.0395,.0433,1,1,.0397,.0434,1,1,.0396,.0432,1,1,.0382,.0416,1,1,.0351,.0381,1,1,.0306,.0332,1,1,.0255,.0277,1,1,.0206,.0224,1,1,.0163,.0178,1,1,.0128,.0139,1,1,.0099,.0109,1,1,.0077,.0085,1,1,.006,.0066,1,1,.0047,.0051,1,1,.0431,.0455,1,1,.0431,.0455,1,1,.0433,.0457,1,1,.0434,.0458,1,1,.0432,.0455,1,1,.0416,.0437,1,1,.0381,.0401,1,1,.0332,.0349,1,1,.0277,.0291,1,1,.0224,.0236,1,1,.0178,.0187,1,1,.0139,.0147,1,1,.0109,.0115,1,1,.0085,.009,1,1,.0066,.007,1,1,.0051,.0055,1,1,.0455,.0467,1,1,.0455,.0467,1,1,.0457,.0468,1,1,.0458,.047,1,1,.0455,.0465,1,1,.0437,.0447,1,1,.0401,.041,1,1,.0349,.0357,1,1,.0291,.0298,1,1,.0236,.0241,1,1,.0187,.0192,1,1,.0147,.0151,1,1,.0115,.0118,1,1,.009,.0092,1,1,.007,.0072,1,1,.0055,.0056,1,1,.0467,.0466,1,1,.0467,.0467,1,1,.0468,.0468,1,1,.047,.0469,1,1,.0465,.0464,1,1,.0447,.0446,1,1,.041,.0409,1,1,.0357,.0356,1,1,.0298,.0297,1,1,.0241,.024,1,1,.0192,.0191,1,1,.0151,.015,1,1,.0118,.0118,1,1,.0092,.0092,1,1,.0072,.0072,1,1,.0056,.0056,1,1,.0466,.0454,1,1,.0467,.0454,1,1,.0468,.0456,1,1,.0469,.0456,1,1,.0464,.0452,1,1,.0446,.0434,1,1,.0409,.0398,1,1,.0356,.0346,1,1,.0297,.0289,1,1,.024,.0234,1,1,.0191,.0186,1,1,.015,.0147,1,1,.0118,.0115,1,1,.0092,.009,1,1,.0072,.007,1,1,.0056,.0055,1,1,.0454,.0431,1,1,.0454,.0431,1,1,.0456,.0432,1,1,.0456,.0433,1,1,.0452,.0429,1,1,.0434,.0412,1,1,.0398,.0377,1,1,.0346,.0329,1,1,.0289,.0274,1,1,.0234,.0222,1,1,.0186,.0177,1,1,.0147,.0139,1,1,.0115,.0109,1,1,.009,.0085,1,1,.007,.0067,1,1,.0055,.0052,1,1,.0431,.0397,1,1,.0431,.0397,1,1,.0432,.0398,1,1,.0433,.0399,1,1,.0429,.0395,1,1,.0412,.038,1,1,.0377,.0348,1,1,.0329,.0303,1,1,.0274,.0253,1,1,.0222,.0205,1,1,.0177,.0163,1,1,.0139,.0129,1,1,.0109,.0101,1,1,.0085,.0079,1,1,.0067,.0062,1,1,.0052,.0048,1,1,.0397,.0352,1,1,.0397,.0353,1,1,.0398,.0354,1,1,.0399,.0355,1,1,.0395,.0352,1,1,.038,.0338,1,1,.0348,.031,1,1,.0303,.027,1,1,.0253,.0226,1,1,.0205,.0183,1,1,.0163,.0146,1,1,.0129,.0115,1,1,.0101,.009,1,1,.0079,.007,1,1,.0062,.0055,1,1,.0048,.0043,1,1,.0352,.0298,1,1,.0353,.0298,1,1,.0354,.0299,1,1,.0355,.03,1,1,.0352,.0298,1,1,.0338,.0287,1,1,.031,.0264,1,1,.027,.023,1,1,.0226,.0192,1,1,.0183,.0156,1,1,.0146,.0124,1,1,.0115,.0097,1,1,.009,.0076,1,1,.007,.006,1,1,.0055,.0046,1,1,.0043,.0036,1,1,.0298,.0234,1,1,.0298,.0234,1,1,.0299,.0235,1,1,.03,.0236,1,1,.0298,.0235,1,1,.0287,.0227,1,1,.0264,.0209,1,1,.023,.0183,1,1,.0192,.0152,1,1,.0156,.0123,1,1,.0124,.0098,1,1,.0097,.0077,1,1,.0076,.006,1,1,.006,.0047,1,1,.0046,.0037,1,1,.0036,.0029,1,1,1,0,.0102,1,1,0,.0103,1,.9998,4e-4,.0105,1,.9965,.0024,.0111,1,.9884,.0074,.012,1,.971,.0175,.0127,1,.9404,.0342,.0126,1,.8971,.058,.0117,1,.8446,.0879,.0101,1,.7867,.1215,.0083,1,.7258,.1562,.0066,1,.6629,.1898,.0051,1,.5988,.2207,.0039,1,.5345,.2482,.003,1,.4716,.2719,.0022,1,.4115,.2922,.0017,1,0,.0022,1,1,0,.0022,1,1,0,.0023,1,1,0,.0024,1,1,0,.0025,1,1,0,.0026,1,1,0,.0026,1,1,0,.0024,1,1,0,.002,1,1,0,.0017,1,1,0,.0013,1,1,0,.0011,1,1,0,8e-4,1,1,0,6e-4,1,1,0,5e-4,1,1,0,4e-4,1,1,.0022,.0068,1,1,.0022,.0068,1,1,.0023,.0069,1,1,.0024,.0071,1,1,.0025,.0073,1,1,.0026,.0075,1,1,.0026,.0073,1,1,.0024,.0066,1,1,.002,.0057,1,1,.0017,.0047,1,1,.0013,.0038,1,1,.0011,.003,1,1,8e-4,.0023,1,1,6e-4,.0018,1,1,5e-4,.0014,1,1,4e-4,.0011,1,1,.0068,.0118,1,1,.0068,.0119,1,1,.0069,.012,1,1,.0071,.0123,1,1,.0073,.0126,1,1,.0075,.0127,1,1,.0073,.0122,1,1,.0066,.0111,1,1,.0057,.0096,1,1,.0047,.0079,1,1,.0038,.0063,1,1,.003,.005,1,1,.0023,.0039,1,1,.0018,.003,1,1,.0014,.0023,1,1,.0011,.0018,1,1,.0118,.0167,1,1,.0119,.0167,1,1,.012,.0169,1,1,.0123,.0172,1,1,.0126,.0175,1,1,.0127,.0175,1,1,.0122,.0168,1,1,.0111,.0152,1,1,.0096,.0131,1,1,.0079,.0108,1,1,.0063,.0087,1,1,.005,.0068,1,1,.0039,.0053,1,1,.003,.0041,1,1,.0023,.0032,1,1,.0018,.0025,1,1,.0167,.0209,1,1,.0167,.0209,1,1,.0169,.0211,1,1,.0172,.0214,1,1,.0175,.0218,1,1,.0175,.0217,1,1,.0168,.0207,1,1,.0152,.0187,1,1,.0131,.0161,1,1,.0108,.0133,1,1,.0087,.0107,1,1,.0068,.0084,1,1,.0053,.0066,1,1,.0041,.0051,1,1,.0032,.004,1,1,.0025,.0031,1,1,.0209,.0244,1,1,.0209,.0244,1,1,.0211,.0246,1,1,.0214,.0249,1,1,.0218,.0252,1,1,.0217,.025,1,1,.0207,.0238,1,1,.0187,.0215,1,1,.0161,.0184,1,1,.0133,.0152,1,1,.0107,.0123,1,1,.0084,.0097,1,1,.0066,.0076,1,1,.0051,.0059,1,1,.004,.0046,1,1,.0031,.0036,1,1,.0244,.027,1,1,.0244,.027,1,1,.0246,.0273,1,1,.0249,.0276,1,1,.0252,.0278,1,1,.025,.0275,1,1,.0238,.0261,1,1,.0215,.0235,1,1,.0184,.0202,1,1,.0152,.0167,1,1,.0123,.0134,1,1,.0097,.0106,1,1,.0076,.0083,1,1,.0059,.0065,1,1,.0046,.0051,1,1,.0036,.0039,1,1,.027,.0288,1,1,.027,.0288,1,1,.0273,.029,1,1,.0276,.0293,1,1,.0278,.0296,1,1,.0275,.0292,1,1,.0261,.0277,1,1,.0235,.0249,1,1,.0202,.0214,1,1,.0167,.0177,1,1,.0134,.0142,1,1,.0106,.0113,1,1,.0083,.0089,1,1,.0065,.0069,1,1,.0051,.0054,1,1,.0039,.0042,1,1,.0288,.0298,1,1,.0288,.0298,1,1,.029,.03,1,1,.0293,.0303,1,1,.0296,.0305,1,1,.0292,.0301,1,1,.0277,.0284,1,1,.0249,.0256,1,1,.0214,.022,1,1,.0177,.0182,1,1,.0142,.0146,1,1,.0113,.0116,1,1,.0089,.0091,1,1,.0069,.0071,1,1,.0054,.0055,1,1,.0042,.0043,1,1,.0298,.0299,1,1,.0298,.0299,1,1,.03,.0301,1,1,.0303,.0304,1,1,.0305,.0306,1,1,.0301,.0301,1,1,.0284,.0285,1,1,.0256,.0256,1,1,.022,.022,1,1,.0182,.0182,1,1,.0146,.0147,1,1,.0116,.0116,1,1,.0091,.0091,1,1,.0071,.0071,1,1,.0055,.0056,1,1,.0043,.0043,1,1,.0299,.0293,1,1,.0299,.0293,1,1,.0301,.0294,1,1,.0304,.0297,1,1,.0306,.0299,1,1,.0301,.0294,1,1,.0285,.0278,1,1,.0256,.025,1,1,.022,.0214,1,1,.0182,.0177,1,1,.0147,.0143,1,1,.0116,.0114,1,1,.0091,.0089,1,1,.0071,.007,1,1,.0056,.0054,1,1,.0043,.0042,1,1,.0293,.0278,1,1,.0293,.0278,1,1,.0294,.028,1,1,.0297,.0282,1,1,.0299,.0284,1,1,.0294,.0279,1,1,.0278,.0264,1,1,.025,.0237,1,1,.0214,.0204,1,1,.0177,.0169,1,1,.0143,.0136,1,1,.0114,.0108,1,1,.0089,.0085,1,1,.007,.0066,1,1,.0054,.0052,1,1,.0042,.004,1,1,.0278,.0256,1,1,.0278,.0256,1,1,.028,.0258,1,1,.0282,.026,1,1,.0284,.0262,1,1,.0279,.0257,1,1,.0264,.0243,1,1,.0237,.0219,1,1,.0204,.0188,1,1,.0169,.0155,1,1,.0136,.0125,1,1,.0108,.01,1,1,.0085,.0078,1,1,.0066,.0061,1,1,.0052,.0048,1,1,.004,.0037,1,1,.0256,.0227,1,1,.0256,.0227,1,1,.0258,.0229,1,1,.026,.0231,1,1,.0262,.0232,1,1,.0257,.0229,1,1,.0243,.0216,1,1,.0219,.0195,1,1,.0188,.0167,1,1,.0155,.0138,1,1,.0125,.0112,1,1,.01,.0089,1,1,.0078,.007,1,1,.0061,.0054,1,1,.0048,.0042,1,1,.0037,.0033,1,1,.0227,.0191,1,1,.0227,.0191,1,1,.0229,.0193,1,1,.0231,.0194,1,1,.0232,.0196,1,1,.0229,.0193,1,1,.0216,.0183,1,1,.0195,.0165,1,1,.0167,.0142,1,1,.0138,.0117,1,1,.0112,.0095,1,1,.0089,.0075,1,1,.007,.0059,1,1,.0054,.0046,1,1,.0042,.0036,1,1,.0033,.0028,1,1,.0191,.0148,1,1,.0191,.0149,1,1,.0193,.015,1,1,.0194,.0151,1,1,.0196,.0153,1,1,.0193,.0151,1,1,.0183,.0144,1,1,.0165,.013,1,1,.0142,.0111,1,1,.0117,.0092,1,1,.0095,.0074,1,1,.0075,.0059,1,1,.0059,.0046,1,1,.0046,.0036,1,1,.0036,.0028,1,1,.0028,.0022,1,1,1,0,.0041,1,1,0,.0041,1,.9999,3e-4,.0043,1,.997,.0018,.0047,1,.9901,.0056,.0054,1,.9751,.0133,.0061,1,.9476,.0265,.0065,1,.9063,.0458,.0065,1,.8531,.0712,.0059,1,.7918,.1013,.0051,1,.7256,.1341,.0041,1,.6568,.1676,.0033,1,.5871,.2002,.0025,1,.5182,.2308,.0019,1,.4517,.2586,.0015,1,.3891,.2836,.0011,1,0,.0012,1,1,0,.0012,1,1,0,.0012,1,1,0,.0013,1,1,0,.0013,1,1,0,.0014,1,1,0,.0015,1,1,0,.0014,1,1,0,.0013,1,1,0,.0011,1,1,0,9e-4,1,1,0,7e-4,1,1,0,6e-4,1,1,0,4e-4,1,1,0,3e-4,1,1,0,3e-4,1,1,.0012,.0037,1,1,.0012,.0037,1,1,.0012,.0038,1,1,.0013,.0039,1,1,.0013,.0041,1,1,.0014,.0043,1,1,.0015,.0044,1,1,.0014,.0042,1,1,.0013,.0037,1,1,.0011,.0032,1,1,9e-4,.0026,1,1,7e-4,.0021,1,1,6e-4,.0016,1,1,4e-4,.0013,1,1,3e-4,.001,1,1,3e-4,8e-4,1,1,.0037,.0066,1,1,.0037,.0066,1,1,.0038,.0067,1,1,.0039,.0069,1,1,.0041,.0073,1,1,.0043,.0076,1,1,.0044,.0076,1,1,.0042,.0072,1,1,.0037,.0064,1,1,.0032,.0054,1,1,.0026,.0045,1,1,.0021,.0036,1,1,.0016,.0028,1,1,.0013,.0022,1,1,.001,.0017,1,1,8e-4,.0013,1,1,.0066,.0095,1,1,.0066,.0095,1,1,.0067,.0097,1,1,.0069,.0099,1,1,.0073,.0103,1,1,.0076,.0107,1,1,.0076,.0106,1,1,.0072,.01,1,1,.0064,.0089,1,1,.0054,.0076,1,1,.0045,.0062,1,1,.0036,.005,1,1,.0028,.0039,1,1,.0022,.0031,1,1,.0017,.0024,1,1,.0013,.0018,1,1,.0095,.0122,1,1,.0095,.0122,1,1,.0097,.0123,1,1,.0099,.0126,1,1,.0103,.0131,1,1,.0107,.0134,1,1,.0106,.0132,1,1,.01,.0124,1,1,.0089,.0111,1,1,.0076,.0094,1,1,.0062,.0077,1,1,.005,.0062,1,1,.0039,.0049,1,1,.0031,.0038,1,1,.0024,.003,1,1,.0018,.0023,1,1,.0122,.0144,1,1,.0122,.0144,1,1,.0123,.0146,1,1,.0126,.0149,1,1,.0131,.0154,1,1,.0134,.0157,1,1,.0132,.0154,1,1,.0124,.0145,1,1,.0111,.0129,1,1,.0094,.0109,1,1,.0077,.009,1,1,.0062,.0072,1,1,.0049,.0057,1,1,.0038,.0044,1,1,.003,.0035,1,1,.0023,.0027,1,1,.0144,.0161,1,1,.0144,.0162,1,1,.0146,.0163,1,1,.0149,.0166,1,1,.0154,.0171,1,1,.0157,.0174,1,1,.0154,.0171,1,1,.0145,.016,1,1,.0129,.0142,1,1,.0109,.0121,1,1,.009,.0099,1,1,.0072,.008,1,1,.0057,.0063,1,1,.0044,.0049,1,1,.0035,.0038,1,1,.0027,.003,1,1,.0161,.0174,1,1,.0162,.0174,1,1,.0163,.0176,1,1,.0166,.0179,1,1,.0171,.0184,1,1,.0174,.0186,1,1,.0171,.0183,1,1,.016,.0171,1,1,.0142,.0151,1,1,.0121,.0128,1,1,.0099,.0106,1,1,.008,.0085,1,1,.0063,.0067,1,1,.0049,.0053,1,1,.0038,.0041,1,1,.003,.0032,1,1,.0174,.0181,1,1,.0174,.0181,1,1,.0176,.0183,1,1,.0179,.0186,1,1,.0184,.019,1,1,.0186,.0193,1,1,.0183,.0189,1,1,.0171,.0176,1,1,.0151,.0156,1,1,.0128,.0133,1,1,.0106,.0109,1,1,.0085,.0087,1,1,.0067,.0069,1,1,.0053,.0054,1,1,.0041,.0042,1,1,.0032,.0033,1,1,.0181,.0183,1,1,.0181,.0183,1,1,.0183,.0184,1,1,.0186,.0188,1,1,.019,.0192,1,1,.0193,.0194,1,1,.0189,.019,1,1,.0176,.0177,1,1,.0156,.0157,1,1,.0133,.0133,1,1,.0109,.0109,1,1,.0087,.0088,1,1,.0069,.007,1,1,.0054,.0055,1,1,.0042,.0043,1,1,.0033,.0033,1,1,.0183,.0179,1,1,.0183,.0179,1,1,.0184,.0181,1,1,.0188,.0184,1,1,.0192,.0188,1,1,.0194,.019,1,1,.019,.0186,1,1,.0177,.0173,1,1,.0157,.0153,1,1,.0133,.013,1,1,.0109,.0107,1,1,.0088,.0086,1,1,.007,.0068,1,1,.0055,.0053,1,1,.0043,.0042,1,1,.0033,.0032,1,1,.0179,.0171,1,1,.0179,.0171,1,1,.0181,.0173,1,1,.0184,.0175,1,1,.0188,.0179,1,1,.019,.0181,1,1,.0186,.0177,1,1,.0173,.0165,1,1,.0153,.0146,1,1,.013,.0124,1,1,.0107,.0102,1,1,.0086,.0082,1,1,.0068,.0065,1,1,.0053,.0051,1,1,.0042,.004,1,1,.0032,.0031,1,1,.0171,.0158,1,1,.0171,.0158,1,1,.0173,.0159,1,1,.0175,.0162,1,1,.0179,.0165,1,1,.0181,.0167,1,1,.0177,.0163,1,1,.0165,.0152,1,1,.0146,.0135,1,1,.0124,.0114,1,1,.0102,.0094,1,1,.0082,.0075,1,1,.0065,.006,1,1,.0051,.0047,1,1,.004,.0037,1,1,.0031,.0029,1,1,.0158,.014,1,1,.0158,.014,1,1,.0159,.0141,1,1,.0162,.0143,1,1,.0165,.0147,1,1,.0167,.0148,1,1,.0163,.0145,1,1,.0152,.0135,1,1,.0135,.012,1,1,.0114,.0101,1,1,.0094,.0083,1,1,.0075,.0067,1,1,.006,.0053,1,1,.0047,.0042,1,1,.0037,.0033,1,1,.0029,.0025,1,1,.014,.0117,1,1,.014,.0117,1,1,.0141,.0118,1,1,.0143,.012,1,1,.0147,.0123,1,1,.0148,.0125,1,1,.0145,.0122,1,1,.0135,.0114,1,1,.012,.0101,1,1,.0101,.0086,1,1,.0083,.007,1,1,.0067,.0057,1,1,.0053,.0045,1,1,.0042,.0035,1,1,.0033,.0027,1,1,.0025,.0021,1,1,.0117,.009,1,1,.0117,.009,1,1,.0118,.0091,1,1,.012,.0093,1,1,.0123,.0095,1,1,.0125,.0097,1,1,.0122,.0095,1,1,.0114,.0089,1,1,.0101,.0079,1,1,.0086,.0067,1,1,.007,.0055,1,1,.0057,.0044,1,1,.0045,.0035,1,1,.0035,.0027,1,1,.0027,.0021,1,1,.0021,.0017,1,1,1,0,.0013,1,1,0,.0014,1,.9999,2e-4,.0014,1,.9974,.0014,.0017,1,.9913,.0043,.0021,1,.9783,.0104,.0026,1,.9534,.021,.003,1,.9143,.0369,.0033,1,.8615,.0585,.0032,1,.7979,.0852,.0029,1,.7271,.1159,.0024,1,.6528,.1487,.002,1,.5776,.1822,.0016,1,.504,.2151,.0012,1,.4339,.2465,9e-4,1,.3692,.2758,7e-4,1,0,6e-4,1,1,0,6e-4,1,1,0,6e-4,1,1,0,6e-4,1,1,0,7e-4,1,1,0,8e-4,1,1,0,8e-4,1,1,0,8e-4,1,1,0,8e-4,1,1,0,7e-4,1,1,0,6e-4,1,1,0,5e-4,1,1,0,4e-4,1,1,0,3e-4,1,1,0,2e-4,1,1,0,2e-4,1,1,6e-4,.0019,1,1,6e-4,.0019,1,1,6e-4,.0019,1,1,6e-4,.002,1,1,7e-4,.0022,1,1,8e-4,.0024,1,1,8e-4,.0025,1,1,8e-4,.0025,1,1,8e-4,.0023,1,1,7e-4,.0021,1,1,6e-4,.0017,1,1,5e-4,.0014,1,1,4e-4,.0011,1,1,3e-4,9e-4,1,1,2e-4,7e-4,1,1,2e-4,5e-4,1,1,.0019,.0035,1,1,.0019,.0035,1,1,.0019,.0035,1,1,.002,.0037,1,1,.0022,.0039,1,1,.0024,.0042,1,1,.0025,.0044,1,1,.0025,.0044,1,1,.0023,.0041,1,1,.0021,.0036,1,1,.0017,.003,1,1,.0014,.0025,1,1,.0011,.002,1,1,9e-4,.0016,1,1,7e-4,.0012,1,1,5e-4,9e-4,1,1,.0035,.0051,1,1,.0035,.0051,1,1,.0035,.0052,1,1,.0037,.0054,1,1,.0039,.0057,1,1,.0042,.0061,1,1,.0044,.0063,1,1,.0044,.0062,1,1,.0041,.0058,1,1,.0036,.0051,1,1,.003,.0043,1,1,.0025,.0035,1,1,.002,.0028,1,1,.0016,.0022,1,1,.0012,.0017,1,1,9e-4,.0013,1,1,.0051,.0066,1,1,.0051,.0066,1,1,.0052,.0067,1,1,.0054,.0069,1,1,.0057,.0073,1,1,.0061,.0078,1,1,.0063,.008,1,1,.0062,.0079,1,1,.0058,.0073,1,1,.0051,.0064,1,1,.0043,.0054,1,1,.0035,.0044,1,1,.0028,.0035,1,1,.0022,.0028,1,1,.0017,.0022,1,1,.0013,.0017,1,1,.0066,.0079,1,1,.0066,.0079,1,1,.0067,.008,1,1,.0069,.0083,1,1,.0073,.0087,1,1,.0078,.0092,1,1,.008,.0094,1,1,.0079,.0092,1,1,.0073,.0086,1,1,.0064,.0075,1,1,.0054,.0063,1,1,.0044,.0052,1,1,.0035,.0042,1,1,.0028,.0033,1,1,.0022,.0026,1,1,.0017,.002,1,1,.0079,.0089,1,1,.0079,.0089,1,1,.008,.0091,1,1,.0083,.0094,1,1,.0087,.0098,1,1,.0092,.0103,1,1,.0094,.0106,1,1,.0092,.0103,1,1,.0086,.0095,1,1,.0075,.0084,1,1,.0063,.0071,1,1,.0052,.0058,1,1,.0042,.0046,1,1,.0033,.0036,1,1,.0026,.0029,1,1,.002,.0022,1,1,.0089,.0097,1,1,.0089,.0097,1,1,.0091,.0098,1,1,.0094,.0101,1,1,.0098,.0106,1,1,.0103,.0111,1,1,.0106,.0114,1,1,.0103,.0111,1,1,.0095,.0102,1,1,.0084,.009,1,1,.0071,.0076,1,1,.0058,.0062,1,1,.0046,.0049,1,1,.0036,.0039,1,1,.0029,.0031,1,1,.0022,.0024,1,1,.0097,.0102,1,1,.0097,.0102,1,1,.0098,.0103,1,1,.0101,.0106,1,1,.0106,.0111,1,1,.0111,.0116,1,1,.0114,.0118,1,1,.0111,.0115,1,1,.0102,.0106,1,1,.009,.0093,1,1,.0076,.0078,1,1,.0062,.0064,1,1,.0049,.0051,1,1,.0039,.0041,1,1,.0031,.0032,1,1,.0024,.0025,1,1,.0102,.0103,1,1,.0102,.0103,1,1,.0103,.0105,1,1,.0106,.0108,1,1,.0111,.0113,1,1,.0116,.0117,1,1,.0118,.0119,1,1,.0115,.0116,1,1,.0106,.0107,1,1,.0093,.0094,1,1,.0078,.0079,1,1,.0064,.0065,1,1,.0051,.0052,1,1,.0041,.0041,1,1,.0032,.0032,1,1,.0025,.0025,1,1,.0103,.0102,1,1,.0103,.0102,1,1,.0105,.0103,1,1,.0108,.0106,1,1,.0113,.0111,1,1,.0117,.0115,1,1,.0119,.0117,1,1,.0116,.0114,1,1,.0107,.0105,1,1,.0094,.0092,1,1,.0079,.0077,1,1,.0065,.0063,1,1,.0052,.0051,1,1,.0041,.004,1,1,.0032,.0031,1,1,.0025,.0025,1,1,.0102,.0097,1,1,.0102,.0098,1,1,.0103,.0099,1,1,.0106,.0101,1,1,.0111,.0106,1,1,.0115,.011,1,1,.0117,.0112,1,1,.0114,.0108,1,1,.0105,.01,1,1,.0092,.0087,1,1,.0077,.0074,1,1,.0063,.006,1,1,.0051,.0048,1,1,.004,.0038,1,1,.0031,.003,1,1,.0025,.0023,1,1,.0097,.009,1,1,.0098,.009,1,1,.0099,.0091,1,1,.0101,.0094,1,1,.0106,.0098,1,1,.011,.0102,1,1,.0112,.0103,1,1,.0108,.01,1,1,.01,.0092,1,1,.0087,.0081,1,1,.0074,.0068,1,1,.006,.0056,1,1,.0048,.0045,1,1,.0038,.0035,1,1,.003,.0028,1,1,.0023,.0022,1,1,.009,.008,1,1,.009,.008,1,1,.0091,.0081,1,1,.0094,.0083,1,1,.0098,.0087,1,1,.0102,.009,1,1,.0103,.0091,1,1,.01,.0089,1,1,.0092,.0082,1,1,.0081,.0072,1,1,.0068,.006,1,1,.0056,.0049,1,1,.0045,.004,1,1,.0035,.0031,1,1,.0028,.0025,1,1,.0022,.0019,1,1,.008,.0067,1,1,.008,.0067,1,1,.0081,.0068,1,1,.0083,.007,1,1,.0087,.0073,1,1,.009,.0076,1,1,.0091,.0077,1,1,.0089,.0075,1,1,.0082,.0069,1,1,.0072,.006,1,1,.006,.0051,1,1,.0049,.0042,1,1,.004,.0033,1,1,.0031,.0026,1,1,.0025,.0021,1,1,.0019,.0016,1,1,.0067,.0051,1,1,.0067,.0051,1,1,.0068,.0052,1,1,.007,.0054,1,1,.0073,.0056,1,1,.0076,.0059,1,1,.0077,.0059,1,1,.0075,.0058,1,1,.0069,.0053,1,1,.006,.0047,1,1,.0051,.0039,1,1,.0042,.0032,1,1,.0033,.0026,1,1,.0026,.002,1,1,.0021,.0016,1,1,.0016,.0013,1,1,1,0,3e-4,1,1,0,3e-4,1,1,1e-4,4e-4,1,.9977,.001,5e-4,1,.9923,.0034,7e-4,1,.9807,.0083,.001,1,.9581,.0169,.0012,1,.9214,.0301,.0015,1,.8695,.0486,.0015,1,.8044,.0724,.0015,1,.7299,.1007,.0013,1,.6504,.1325,.0011,1,.5699,.1663,9e-4,1,.4916,.201,7e-4,1,.4181,.2353,6e-4,1,.3513,.2686,4e-4,1,0,3e-4,1,1,0,3e-4,1,1,0,3e-4,1,1,0,3e-4,1,1,0,3e-4,1,1,0,4e-4,1,1,0,4e-4,1,1,0,4e-4,1,1,0,4e-4,1,1,0,4e-4,1,1,0,4e-4,1,1,0,3e-4,1,1,0,2e-4,1,1,0,2e-4,1,1,0,2e-4,1,1,0,1e-4,1,1,3e-4,9e-4,1,1,3e-4,9e-4,1,1,3e-4,9e-4,1,1,3e-4,9e-4,1,1,3e-4,.001,1,1,4e-4,.0012,1,1,4e-4,.0013,1,1,4e-4,.0014,1,1,4e-4,.0014,1,1,4e-4,.0013,1,1,4e-4,.0011,1,1,3e-4,9e-4,1,1,2e-4,8e-4,1,1,2e-4,6e-4,1,1,2e-4,5e-4,1,1,1e-4,4e-4,1,1,9e-4,.0016,1,1,9e-4,.0016,1,1,9e-4,.0016,1,1,9e-4,.0018,1,1,.001,.0019,1,1,.0012,.0022,1,1,.0013,.0024,1,1,.0014,.0025,1,1,.0014,.0024,1,1,.0013,.0023,1,1,.0011,.002,1,1,9e-4,.0017,1,1,8e-4,.0014,1,1,6e-4,.0011,1,1,5e-4,9e-4,1,1,4e-4,7e-4,1,1,.0016,.0024,1,1,.0016,.0024,1,1,.0016,.0025,1,1,.0018,.0026,1,1,.0019,.0029,1,1,.0022,.0032,1,1,.0024,.0035,1,1,.0025,.0036,1,1,.0024,.0035,1,1,.0023,.0032,1,1,.002,.0028,1,1,.0017,.0024,1,1,.0014,.0019,1,1,.0011,.0016,1,1,9e-4,.0012,1,1,7e-4,.001,1,1,.0024,.0032,1,1,.0024,.0032,1,1,.0025,.0032,1,1,.0026,.0034,1,1,.0029,.0037,1,1,.0032,.0041,1,1,.0035,.0045,1,1,.0036,.0046,1,1,.0035,.0045,1,1,.0032,.0041,1,1,.0028,.0036,1,1,.0024,.003,1,1,.0019,.0025,1,1,.0016,.002,1,1,.0012,.0016,1,1,.001,.0012,1,1,.0032,.0038,1,1,.0032,.0038,1,1,.0032,.0039,1,1,.0034,.0041,1,1,.0037,.0045,1,1,.0041,.0049,1,1,.0045,.0053,1,1,.0046,.0055,1,1,.0045,.0053,1,1,.0041,.0049,1,1,.0036,.0043,1,1,.003,.0036,1,1,.0025,.0029,1,1,.002,.0023,1,1,.0016,.0019,1,1,.0012,.0015,1,1,.0038,.0044,1,1,.0038,.0044,1,1,.0039,.0045,1,1,.0041,.0047,1,1,.0045,.0051,1,1,.0049,.0056,1,1,.0053,.006,1,1,.0055,.0062,1,1,.0053,.006,1,1,.0049,.0055,1,1,.0043,.0048,1,1,.0036,.004,1,1,.0029,.0033,1,1,.0023,.0026,1,1,.0019,.0021,1,1,.0015,.0016,1,1,.0044,.0048,1,1,.0044,.0048,1,1,.0045,.0049,1,1,.0047,.0051,1,1,.0051,.0055,1,1,.0056,.0061,1,1,.006,.0065,1,1,.0062,.0066,1,1,.006,.0064,1,1,.0055,.0059,1,1,.0048,.0051,1,1,.004,.0043,1,1,.0033,.0035,1,1,.0026,.0028,1,1,.0021,.0022,1,1,.0016,.0018,1,1,.0048,.0051,1,1,.0048,.0051,1,1,.0049,.0052,1,1,.0051,.0054,1,1,.0055,.0058,1,1,.0061,.0064,1,1,.0065,.0068,1,1,.0066,.0069,1,1,.0064,.0067,1,1,.0059,.0061,1,1,.0051,.0054,1,1,.0043,.0045,1,1,.0035,.0037,1,1,.0028,.0029,1,1,.0022,.0023,1,1,.0018,.0018,1,1,.0051,.0052,1,1,.0051,.0052,1,1,.0052,.0053,1,1,.0054,.0055,1,1,.0058,.0059,1,1,.0064,.0065,1,1,.0068,.0069,1,1,.0069,.007,1,1,.0067,.0068,1,1,.0061,.0062,1,1,.0054,.0054,1,1,.0045,.0045,1,1,.0037,.0037,1,1,.0029,.003,1,1,.0023,.0024,1,1,.0018,.0018,1,1,.0052,.0051,1,1,.0052,.0051,1,1,.0053,.0052,1,1,.0055,.0055,1,1,.0059,.0059,1,1,.0065,.0064,1,1,.0069,.0068,1,1,.007,.0069,1,1,.0068,.0067,1,1,.0062,.0061,1,1,.0054,.0053,1,1,.0045,.0045,1,1,.0037,.0036,1,1,.003,.0029,1,1,.0024,.0023,1,1,.0018,.0018,1,1,.0051,.0049,1,1,.0051,.0049,1,1,.0052,.005,1,1,.0055,.0052,1,1,.0059,.0056,1,1,.0064,.0061,1,1,.0068,.0065,1,1,.0069,.0066,1,1,.0067,.0064,1,1,.0061,.0058,1,1,.0053,.0051,1,1,.0045,.0043,1,1,.0036,.0035,1,1,.0029,.0028,1,1,.0023,.0022,1,1,.0018,.0017,1,1,.0049,.0046,1,1,.0049,.0046,1,1,.005,.0046,1,1,.0052,.0049,1,1,.0056,.0052,1,1,.0061,.0056,1,1,.0065,.006,1,1,.0066,.0061,1,1,.0064,.0059,1,1,.0058,.0054,1,1,.0051,.0047,1,1,.0043,.0039,1,1,.0035,.0032,1,1,.0028,.0026,1,1,.0022,.002,1,1,.0017,.0016,1,1,.0046,.004,1,1,.0046,.0041,1,1,.0046,.0041,1,1,.0049,.0043,1,1,.0052,.0046,1,1,.0056,.005,1,1,.006,.0053,1,1,.0061,.0054,1,1,.0059,.0052,1,1,.0054,.0048,1,1,.0047,.0042,1,1,.0039,.0035,1,1,.0032,.0029,1,1,.0026,.0023,1,1,.002,.0018,1,1,.0016,.0014,1,1,.004,.0034,1,1,.0041,.0034,1,1,.0041,.0035,1,1,.0043,.0036,1,1,.0046,.0039,1,1,.005,.0042,1,1,.0053,.0045,1,1,.0054,.0045,1,1,.0052,.0044,1,1,.0048,.004,1,1,.0042,.0035,1,1,.0035,.0029,1,1,.0029,.0024,1,1,.0023,.0019,1,1,.0018,.0015,1,1,.0014,.0012,1,1,.0034,.0026,1,1,.0034,.0026,1,1,.0035,.0026,1,1,.0036,.0028,1,1,.0039,.003,1,1,.0042,.0032,1,1,.0045,.0034,1,1,.0045,.0035,1,1,.0044,.0034,1,1,.004,.0031,1,1,.0035,.0027,1,1,.0029,.0023,1,1,.0024,.0019,1,1,.0019,.0015,1,1,.0015,.0012,1,1,.0012,9e-4,1,1,1,0,0,1,1,0,0,1,1,0,1e-4,1,.9979,8e-4,1e-4,1,.993,.0028,2e-4,1,.9826,.0068,3e-4,1,.9619,.0139,4e-4,1,.9274,.025,6e-4,1,.8769,.0409,6e-4,1,.8112,.062,7e-4,1,.7337,.0881,6e-4,1,.6495,.1185,5e-4,1,.5637,.1522,5e-4,1,.4808,.1881,4e-4,1,.4039,.225,3e-4,1,.335,.2619,2e-4,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,2e-4,1,1,0,2e-4,1,1,0,2e-4,1,1,0,2e-4,1,1,0,2e-4,1,1,0,2e-4,1,1,0,2e-4,1,1,0,2e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,1e-4,3e-4,1,1,1e-4,3e-4,1,1,1e-4,3e-4,1,1,1e-4,4e-4,1,1,1e-4,4e-4,1,1,2e-4,5e-4,1,1,2e-4,6e-4,1,1,2e-4,7e-4,1,1,2e-4,7e-4,1,1,2e-4,7e-4,1,1,2e-4,7e-4,1,1,2e-4,6e-4,1,1,2e-4,5e-4,1,1,1e-4,4e-4,1,1,1e-4,3e-4,1,1,1e-4,3e-4,1,1,3e-4,6e-4,1,1,3e-4,6e-4,1,1,3e-4,6e-4,1,1,4e-4,7e-4,1,1,4e-4,8e-4,1,1,5e-4,.001,1,1,6e-4,.0011,1,1,7e-4,.0013,1,1,7e-4,.0013,1,1,7e-4,.0013,1,1,7e-4,.0012,1,1,6e-4,.001,1,1,5e-4,9e-4,1,1,4e-4,7e-4,1,1,3e-4,6e-4,1,1,3e-4,5e-4,1,1,6e-4,9e-4,1,1,6e-4,9e-4,1,1,6e-4,9e-4,1,1,7e-4,.001,1,1,8e-4,.0012,1,1,.001,.0014,1,1,.0011,.0017,1,1,.0013,.0019,1,1,.0013,.0019,1,1,.0013,.0019,1,1,.0012,.0017,1,1,.001,.0015,1,1,9e-4,.0013,1,1,7e-4,.001,1,1,6e-4,8e-4,1,1,5e-4,7e-4,1,1,9e-4,.0012,1,1,9e-4,.0012,1,1,9e-4,.0012,1,1,.001,.0014,1,1,.0012,.0016,1,1,.0014,.0019,1,1,.0017,.0022,1,1,.0019,.0024,1,1,.0019,.0025,1,1,.0019,.0024,1,1,.0017,.0022,1,1,.0015,.002,1,1,.0013,.0016,1,1,.001,.0013,1,1,8e-4,.0011,1,1,7e-4,9e-4,1,1,.0012,.0015,1,1,.0012,.0015,1,1,.0012,.0015,1,1,.0014,.0017,1,1,.0016,.0019,1,1,.0019,.0023,1,1,.0022,.0026,1,1,.0024,.0029,1,1,.0025,.003,1,1,.0024,.0029,1,1,.0022,.0027,1,1,.002,.0023,1,1,.0016,.002,1,1,.0013,.0016,1,1,.0011,.0013,1,1,9e-4,.001,1,1,.0015,.0017,1,1,.0015,.0017,1,1,.0015,.0018,1,1,.0017,.0019,1,1,.0019,.0022,1,1,.0023,.0026,1,1,.0026,.003,1,1,.0029,.0033,1,1,.003,.0034,1,1,.0029,.0033,1,1,.0027,.003,1,1,.0023,.0026,1,1,.002,.0022,1,1,.0016,.0018,1,1,.0013,.0015,1,1,.001,.0012,1,1,.0017,.0019,1,1,.0017,.0019,1,1,.0018,.0019,1,1,.0019,.0021,1,1,.0022,.0024,1,1,.0026,.0028,1,1,.003,.0032,1,1,.0033,.0036,1,1,.0034,.0037,1,1,.0033,.0036,1,1,.003,.0033,1,1,.0026,.0028,1,1,.0022,.0024,1,1,.0018,.002,1,1,.0015,.0016,1,1,.0012,.0012,1,1,.0019,.002,1,1,.0019,.002,1,1,.0019,.0021,1,1,.0021,.0022,1,1,.0024,.0025,1,1,.0028,.003,1,1,.0032,.0034,1,1,.0036,.0037,1,1,.0037,.0038,1,1,.0036,.0037,1,1,.0033,.0034,1,1,.0028,.003,1,1,.0024,.0025,1,1,.002,.002,1,1,.0016,.0016,1,1,.0012,.0013,1,1,.002,.002,1,1,.002,.0021,1,1,.0021,.0021,1,1,.0022,.0023,1,1,.0025,.0026,1,1,.003,.003,1,1,.0034,.0035,1,1,.0037,.0038,1,1,.0038,.0039,1,1,.0037,.0038,1,1,.0034,.0035,1,1,.003,.003,1,1,.0025,.0025,1,1,.002,.0021,1,1,.0016,.0017,1,1,.0013,.0013,1,1,.002,.002,1,1,.0021,.002,1,1,.0021,.0021,1,1,.0023,.0023,1,1,.0026,.0026,1,1,.003,.003,1,1,.0035,.0034,1,1,.0038,.0037,1,1,.0039,.0039,1,1,.0038,.0037,1,1,.0035,.0034,1,1,.003,.003,1,1,.0025,.0025,1,1,.0021,.002,1,1,.0017,.0016,1,1,.0013,.0013,1,1,.002,.002,1,1,.002,.002,1,1,.0021,.002,1,1,.0023,.0022,1,1,.0026,.0025,1,1,.003,.0029,1,1,.0034,.0033,1,1,.0037,.0036,1,1,.0039,.0037,1,1,.0037,.0036,1,1,.0034,.0033,1,1,.003,.0028,1,1,.0025,.0024,1,1,.002,.002,1,1,.0016,.0016,1,1,.0013,.0013,1,1,.002,.0018,1,1,.002,.0018,1,1,.002,.0019,1,1,.0022,.002,1,1,.0025,.0023,1,1,.0029,.0027,1,1,.0033,.003,1,1,.0036,.0033,1,1,.0037,.0034,1,1,.0036,.0033,1,1,.0033,.003,1,1,.0028,.0026,1,1,.0024,.0022,1,1,.002,.0018,1,1,.0016,.0015,1,1,.0013,.0012,1,1,.0018,.0016,1,1,.0018,.0016,1,1,.0019,.0017,1,1,.002,.0018,1,1,.0023,.002,1,1,.0027,.0024,1,1,.003,.0027,1,1,.0033,.0029,1,1,.0034,.003,1,1,.0033,.0029,1,1,.003,.0027,1,1,.0026,.0023,1,1,.0022,.002,1,1,.0018,.0016,1,1,.0015,.0013,1,1,.0012,.001,1,1,.0016,.0014,1,1,.0016,.0014,1,1,.0017,.0014,1,1,.0018,.0015,1,1,.002,.0017,1,1,.0024,.002,1,1,.0027,.0023,1,1,.0029,.0025,1,1,.003,.0025,1,1,.0029,.0025,1,1,.0027,.0022,1,1,.0023,.002,1,1,.002,.0016,1,1,.0016,.0013,1,1,.0013,.0011,1,1,.001,9e-4,1,1,.0014,.001,1,1,.0014,.001,1,1,.0014,.0011,1,1,.0015,.0012,1,1,.0017,.0013,1,1,.002,.0015,1,1,.0023,.0017,1,1,.0025,.0019,1,1,.0025,.002,1,1,.0025,.0019,1,1,.0022,.0017,1,1,.002,.0015,1,1,.0016,.0013,1,1,.0013,.001,1,1,.0011,8e-4,1,1,9e-4,7e-4,1,1,1,0,0,1,1,0,0,1,1,0,0,1,.998,6e-4,0,1,.9936,.0023,0,1,.9841,.0056,1e-4,1,.9651,.0115,1e-4,1,.9327,.021,2e-4,1,.8837,.0348,2e-4,1,.8179,.0535,2e-4,1,.7381,.0775,2e-4,1,.6497,.1064,2e-4,1,.5589,.1396,2e-4,1,.4713,.1763,2e-4,1,.3911,.2154,1e-4,1,.3203,.2557,1e-4,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,0,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,1e-4,2e-4,1,1,1e-4,2e-4,1,1,1e-4,3e-4,1,1,1e-4,3e-4,1,1,1e-4,3e-4,1,1,1e-4,3e-4,1,1,1e-4,3e-4,1,1,1e-4,3e-4,1,1,1e-4,2e-4,1,1,1e-4,2e-4,1,1,0,2e-4,1,1,1e-4,1e-4,1,1,1e-4,1e-4,1,1,1e-4,1e-4,1,1,1e-4,2e-4,1,1,1e-4,2e-4,1,1,2e-4,3e-4,1,1,2e-4,4e-4,1,1,3e-4,5e-4,1,1,3e-4,6e-4,1,1,3e-4,6e-4,1,1,3e-4,6e-4,1,1,3e-4,6e-4,1,1,3e-4,5e-4,1,1,2e-4,4e-4,1,1,2e-4,4e-4,1,1,2e-4,3e-4,1,1,1e-4,2e-4,1,1,1e-4,2e-4,1,1,1e-4,2e-4,1,1,2e-4,2e-4,1,1,2e-4,3e-4,1,1,3e-4,5e-4,1,1,4e-4,6e-4,1,1,5e-4,8e-4,1,1,6e-4,9e-4,1,1,6e-4,.001,1,1,6e-4,9e-4,1,1,6e-4,9e-4,1,1,5e-4,8e-4,1,1,4e-4,7e-4,1,1,4e-4,5e-4,1,1,3e-4,4e-4,1,1,2e-4,3e-4,1,1,2e-4,3e-4,1,1,2e-4,3e-4,1,1,2e-4,3e-4,1,1,3e-4,5e-4,1,1,5e-4,6e-4,1,1,6e-4,8e-4,1,1,8e-4,.001,1,1,9e-4,.0012,1,1,.001,.0012,1,1,9e-4,.0012,1,1,9e-4,.0011,1,1,8e-4,.001,1,1,7e-4,8e-4,1,1,5e-4,7e-4,1,1,4e-4,6e-4,1,1,3e-4,3e-4,1,1,3e-4,3e-4,1,1,3e-4,3e-4,1,1,3e-4,4e-4,1,1,5e-4,6e-4,1,1,6e-4,8e-4,1,1,8e-4,.001,1,1,.001,.0012,1,1,.0012,.0014,1,1,.0012,.0015,1,1,.0012,.0015,1,1,.0011,.0014,1,1,.001,.0012,1,1,8e-4,.001,1,1,7e-4,8e-4,1,1,6e-4,7e-4,1,1,3e-4,4e-4,1,1,3e-4,4e-4,1,1,3e-4,4e-4,1,1,4e-4,5e-4,1,1,6e-4,6e-4,1,1,8e-4,9e-4,1,1,.001,.0012,1,1,.0012,.0014,1,1,.0014,.0016,1,1,.0015,.0017,1,1,.0015,.0017,1,1,.0014,.0015,1,1,.0012,.0014,1,1,.001,.0012,1,1,8e-4,.001,1,1,7e-4,8e-4,1,1,4e-4,4e-4,1,1,4e-4,4e-4,1,1,4e-4,4e-4,1,1,5e-4,5e-4,1,1,6e-4,7e-4,1,1,9e-4,.001,1,1,.0012,.0013,1,1,.0014,.0016,1,1,.0016,.0018,1,1,.0017,.0019,1,1,.0017,.0018,1,1,.0015,.0017,1,1,.0014,.0015,1,1,.0012,.0013,1,1,.001,.001,1,1,8e-4,8e-4,1,1,4e-4,4e-4,1,1,4e-4,4e-4,1,1,4e-4,5e-4,1,1,5e-4,6e-4,1,1,7e-4,7e-4,1,1,.001,.001,1,1,.0013,.0013,1,1,.0016,.0016,1,1,.0018,.0019,1,1,.0019,.002,1,1,.0018,.0019,1,1,.0017,.0018,1,1,.0015,.0016,1,1,.0013,.0013,1,1,.001,.0011,1,1,8e-4,9e-4,1,1,4e-4,5e-4,1,1,4e-4,5e-4,1,1,5e-4,5e-4,1,1,6e-4,6e-4,1,1,7e-4,8e-4,1,1,.001,.001,1,1,.0013,.0014,1,1,.0016,.0017,1,1,.0019,.0019,1,1,.002,.002,1,1,.0019,.002,1,1,.0018,.0018,1,1,.0016,.0016,1,1,.0013,.0013,1,1,.0011,.0011,1,1,9e-4,9e-4,1,1,5e-4,5e-4,1,1,5e-4,5e-4,1,1,5e-4,5e-4,1,1,6e-4,6e-4,1,1,8e-4,8e-4,1,1,.001,.001,1,1,.0014,.0014,1,1,.0017,.0017,1,1,.0019,.0019,1,1,.002,.002,1,1,.002,.0019,1,1,.0018,.0018,1,1,.0016,.0016,1,1,.0013,.0013,1,1,.0011,.0011,1,1,9e-4,9e-4,1,1,5e-4,4e-4,1,1,5e-4,4e-4,1,1,5e-4,5e-4,1,1,6e-4,6e-4,1,1,8e-4,7e-4,1,1,.001,.001,1,1,.0014,.0013,1,1,.0017,.0016,1,1,.0019,.0018,1,1,.002,.0019,1,1,.0019,.0019,1,1,.0018,.0017,1,1,.0016,.0015,1,1,.0013,.0013,1,1,.0011,.0011,1,1,9e-4,9e-4,1,1,4e-4,4e-4,1,1,4e-4,4e-4,1,1,5e-4,4e-4,1,1,6e-4,5e-4,1,1,7e-4,7e-4,1,1,.001,9e-4,1,1,.0013,.0012,1,1,.0016,.0015,1,1,.0018,.0017,1,1,.0019,.0018,1,1,.0019,.0017,1,1,.0017,.0016,1,1,.0015,.0014,1,1,.0013,.0012,1,1,.0011,.001,1,1,9e-4,8e-4,1,1,4e-4,4e-4,1,1,4e-4,4e-4,1,1,4e-4,4e-4,1,1,5e-4,5e-4,1,1,7e-4,6e-4,1,1,9e-4,8e-4,1,1,.0012,.0011,1,1,.0015,.0013,1,1,.0017,.0015,1,1,.0018,.0016,1,1,.0017,.0015,1,1,.0016,.0014,1,1,.0014,.0012,1,1,.0012,.0011,1,1,.001,9e-4,1,1,8e-4,7e-4,1,1,4e-4,3e-4,1,1,4e-4,3e-4,1,1,4e-4,3e-4,1,1,5e-4,4e-4,1,1,6e-4,5e-4,1,1,8e-4,7e-4,1,1,.0011,9e-4,1,1,.0013,.0011,1,1,.0015,.0012,1,1,.0016,.0013,1,1,.0015,.0013,1,1,.0014,.0012,1,1,.0012,.001,1,1,.0011,9e-4,1,1,9e-4,7e-4,1,1,7e-4,6e-4,1,1,3e-4,2e-4,1,1,3e-4,2e-4,1,1,3e-4,3e-4,1,1,4e-4,3e-4,1,1,5e-4,4e-4,1,1,7e-4,5e-4,1,1,9e-4,7e-4,1,1,.0011,8e-4,1,1,.0012,.001,1,1,.0013,.001,1,1,.0013,.001,1,1,.0012,9e-4,1,1,.001,8e-4,1,1,9e-4,7e-4,1,1,7e-4,6e-4,1,1,6e-4,5e-4,1,1,1,0,0,1,1,0,0,1,1,0,0,1,.998,5e-4,0,1,.9939,.0019,0,1,.9854,.0047,0,1,.9677,.0097,0,1,.9372,.0178,0,1,.8899,.0298,0,1,.8245,.0466,0,1,.743,.0685,0,1,.6508,.0959,0,1,.5552,.1284,0,1,.4631,.1656,0,1,.3794,.2065,0,1,.3069,.25,0,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,1e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,1e-4,1,1,0,1e-4,1,1,1e-4,1e-4,1,1,1e-4,2e-4,1,1,1e-4,2e-4,1,1,1e-4,3e-4,1,1,1e-4,3e-4,1,1,1e-4,3e-4,1,1,1e-4,2e-4,1,1,1e-4,2e-4,1,1,1e-4,2e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1e-4,1e-4,1,1,1e-4,1e-4,1,1,1e-4,2e-4,1,1,2e-4,3e-4,1,1,2e-4,4e-4,1,1,3e-4,4e-4,1,1,3e-4,4e-4,1,1,3e-4,4e-4,1,1,2e-4,4e-4,1,1,2e-4,3e-4,1,1,2e-4,3e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1e-4,1e-4,1,1,1e-4,2e-4,1,1,2e-4,3e-4,1,1,3e-4,4e-4,1,1,4e-4,5e-4,1,1,4e-4,5e-4,1,1,4e-4,5e-4,1,1,4e-4,5e-4,1,1,4e-4,5e-4,1,1,3e-4,4e-4,1,1,3e-4,3e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,1e-4,1,1,1e-4,1e-4,1,1,2e-4,2e-4,1,1,3e-4,3e-4,1,1,4e-4,5e-4,1,1,5e-4,6e-4,1,1,5e-4,6e-4,1,1,5e-4,6e-4,1,1,5e-4,6e-4,1,1,5e-4,6e-4,1,1,4e-4,5e-4,1,1,3e-4,4e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1e-4,1e-4,1,1,1e-4,1e-4,1,1,2e-4,3e-4,1,1,3e-4,4e-4,1,1,5e-4,5e-4,1,1,6e-4,7e-4,1,1,6e-4,7e-4,1,1,6e-4,7e-4,1,1,6e-4,7e-4,1,1,6e-4,7e-4,1,1,5e-4,6e-4,1,1,4e-4,5e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1e-4,1e-4,1,1,1e-4,2e-4,1,1,3e-4,3e-4,1,1,4e-4,4e-4,1,1,5e-4,6e-4,1,1,7e-4,7e-4,1,1,7e-4,8e-4,1,1,7e-4,8e-4,1,1,7e-4,8e-4,1,1,7e-4,7e-4,1,1,6e-4,6e-4,1,1,5e-4,5e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1e-4,1e-4,1,1,2e-4,2e-4,1,1,3e-4,3e-4,1,1,4e-4,5e-4,1,1,6e-4,6e-4,1,1,7e-4,8e-4,1,1,8e-4,8e-4,1,1,8e-4,9e-4,1,1,8e-4,8e-4,1,1,7e-4,8e-4,1,1,6e-4,7e-4,1,1,5e-4,6e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1e-4,1e-4,1,1,2e-4,2e-4,1,1,3e-4,3e-4,1,1,5e-4,5e-4,1,1,6e-4,6e-4,1,1,8e-4,8e-4,1,1,8e-4,9e-4,1,1,9e-4,9e-4,1,1,8e-4,8e-4,1,1,8e-4,8e-4,1,1,7e-4,7e-4,1,1,6e-4,6e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1e-4,1e-4,1,1,2e-4,2e-4,1,1,3e-4,3e-4,1,1,5e-4,5e-4,1,1,6e-4,6e-4,1,1,8e-4,8e-4,1,1,9e-4,9e-4,1,1,9e-4,9e-4,1,1,8e-4,8e-4,1,1,8e-4,8e-4,1,1,7e-4,7e-4,1,1,6e-4,6e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1e-4,1e-4,1,1,2e-4,2e-4,1,1,3e-4,3e-4,1,1,5e-4,5e-4,1,1,6e-4,6e-4,1,1,8e-4,7e-4,1,1,9e-4,8e-4,1,1,9e-4,8e-4,1,1,8e-4,8e-4,1,1,8e-4,7e-4,1,1,7e-4,6e-4,1,1,6e-4,5e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1e-4,1e-4,1,1,2e-4,2e-4,1,1,3e-4,3e-4,1,1,5e-4,4e-4,1,1,6e-4,6e-4,1,1,7e-4,7e-4,1,1,8e-4,8e-4,1,1,8e-4,8e-4,1,1,8e-4,8e-4,1,1,7e-4,7e-4,1,1,6e-4,6e-4,1,1,5e-4,5e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1e-4,1e-4,1,1,2e-4,1e-4,1,1,3e-4,2e-4,1,1,4e-4,4e-4,1,1,6e-4,5e-4,1,1,7e-4,6e-4,1,1,8e-4,7e-4,1,1,8e-4,7e-4,1,1,8e-4,7e-4,1,1,7e-4,6e-4,1,1,6e-4,5e-4,1,1,5e-4,4e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1e-4,0,1,1,1e-4,1e-4,1,1,2e-4,2e-4,1,1,4e-4,3e-4,1,1,5e-4,4e-4,1,1,6e-4,5e-4,1,1,7e-4,6e-4,1,1,7e-4,6e-4,1,1,7e-4,6e-4,1,1,6e-4,5e-4,1,1,5e-4,4e-4,1,1,4e-4,4e-4,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1e-4,1e-4,1,1,2e-4,2e-4,1,1,3e-4,2e-4,1,1,4e-4,3e-4,1,1,5e-4,4e-4,1,1,6e-4,4e-4,1,1,6e-4,4e-4,1,1,6e-4,4e-4,1,1,5e-4,4e-4,1,1,4e-4,3e-4,1,1,4e-4,3e-4,1,1]),gd*yd,gd,r.RGBAFormat,r.FloatType);bd.minFilter=r.LinearFilter,bd.magFilter=r.LinearFilter,bd.wrapS=r.ClampToEdgeWrapping,bd.wrapT=r.ClampToEdgeWrapping,bd.generateMipmaps=!1,bd.needsUpdate=!0;var xd=(0,n.texture)(bd);xd.setUpdateMatrix(!1);var Sd=(e,t,r=0)=>(0,n.vec2)((0,n.clamp)(e,0,1).mul(gd-1).add(.5).add((0,n.float)(r).mul(gd)).div(gd*yd),(0,n.clamp)(t,0,1).mul((gd-1)/gd).add(.5/gd)),Cd=(0,n.Fn)(([e,t])=>(0,n.clamp)(xd.sample(Sd(t,e)).g,0,1)),wd=(0,n.Fn)(([e,t,r,i,a,o,s,c,l,u])=>{let d=xd.sample(Sd(u,l)).toVar(),f=(0,n.clamp)(r.sub(1).div(r.add(1)).div(vd),0,1).mul(_d-1).toVar(),p=(0,n.min)((0,n.floor)(f),(0,n.float)(_d-2)).toVar(),m=xd.sample(Sd(u,l,p.add(1))).toVar(),h=(0,n.clamp)((0,n.mix)(m.r,m.g,f.sub(p)),0,1),g=(0,n.max)(d.r,.05).toVar(),_=(0,n.clamp)(d.b,0,1).toVar(),v=e.mul(g.sub(h)).add((0,n.vec3)(t.mul(h))),y=i.mul(g.sub(_)).add((0,n.vec3)(_)),b=o.mul(g.sub(_)).add((0,n.vec3)(_)),x=(0,n.max)((0,n.mix)((0,n.mix)(v,y,a),b,s),(0,n.vec3)(0)),S=(0,n.vec3)(1).add(c.mul((0,n.float)(1).div(g).sub(1)));return wi({compensation:S,E_total:(0,n.clamp)(x.mul(S),(0,n.vec3)(0),(0,n.vec3)(1))})}),Td=(0,n.Fn)(([e,t])=>{let r=(0,n.min)(od(e.ior).mul(e.specularColor),(0,n.vec3)(1)).mul(e.specularIntensity),i=(0,n.clamp)(t.mul(e.specularIntensity),(0,n.vec3)(0),(0,n.vec3)(1));return Ti({f0:r,f90:e.specularIntensity,eta:(0,n.max)(e.ior,1),F0m:i,F0:(0,n.clamp)((0,n.mix)(r,i,e.metalness),(0,n.vec3)(0),(0,n.vec3)(1))})}),Ed=(0,n.Fn)(([e,t,r])=>{let i=ud(e,r),a=md(t,r);return i.mul(a).div((0,n.max)(t.mul(4),Fi))}),Dd=(0,n.Fn)(([e,t])=>{let r=(0,n.max)(e.mul(e),1e-4).toVar();return(0,n.vec2)((0,n.max)((0,n.mix)(r,(0,n.float)(1),t.mul(t)),1e-4),r)}),Od=(0,n.Fn)(([e,t,r,i,a])=>{let o=e.mul(t),s=(0,n.vec3)(t.mul(i),e.mul(a),o.mul(r)),c=(0,n.max)((0,n.dot)(s,s),ld),l=o.div(c);return o.mul(l.mul(l)).div(Mi)}),kd=(0,n.Fn)(([e,t,r,i,a,o,s,c])=>{let l=c.mul((0,n.vec3)(e.mul(r),t.mul(i),s).length()),u=s.mul((0,n.vec3)(e.mul(a),t.mul(o),c).length());return(0,n.float)(.5).div((0,n.max)(l.add(u),Fi))}),Ad=(0,n.Fn)(([e,t,r,i,a])=>{let o=e.mul(r),s=t.mul(i),c=o.mul(o).add(s.mul(s)),l=(0,n.max)(a.mul(a),Fi),u=(0,n.sqrt)((0,n.float)(1).add(c.div(l))).sub(1).mul(.5);return(0,n.float)(1).div(u.add(1))}),jd=(0,n.Fn)(([e,t,r,i,a,o,s,c])=>{let l=Od(e,t,r,i,a),u=Ad(e,t,s,c,o);return l.mul(u).div((0,n.max)(o.mul(4),Fi))}),Md=(0,n.Fn)(([e,t])=>{let r=(0,n.float)(Pi).mul(e).mul(1e-9),i=(0,n.vec3)(54856e-17,44201e-17,52481e-17),a=(0,n.vec3)(1681e3,1795300,2208400),o=(0,n.vec3)(43278e5,93046e5,66121e5),s=i.mul((0,n.sqrt)((0,n.float)(Pi).mul(o))).mul((0,n.cos)(a.mul(r).add(t))).mul((0,n.exp)(Gi({x:r}).negate().mul(o))).toVar();return s.x.addAssign((0,n.float)(9747e-17).mul((0,n.sqrt)((0,n.float)(Pi).mul(45282e5))).mul((0,n.cos)((0,n.float)(2239900).mul(r).add(t.x))).mul((0,n.exp)((0,n.float)(-45282e5).mul(Gi({x:r}))))),Wi.mul(s.div(1.0685e-7))}),Nd=(0,n.Fn)(([e,t,r,i,a])=>{let o=(0,n.mix)(e,t,(0,n.smoothstep)(0,.03,i)).toVar(),s=Gi({x:e.div(o)}).mul((0,n.float)(1).sub(Gi({x:r}))),c=(0,n.float)(1).sub(s).toVar(),l=(0,n.vec3)(0).toVar();return(0,n.If)(c.lessThan(0),()=>{l.assign((0,n.vec3)(1))}).Else(()=>{let t=(0,n.sqrt)(c).toVar(),s=td(r,ad(o,e)).toVar(),u=(0,n.float)(1).sub(s).toVar(),d=o.lessThan(e).select((0,n.float)(Mi),(0,n.float)(0)),f=(0,n.float)(Mi).sub(d),p=rd((0,n.clamp)(a,0,.9999)).toVar(),m=id(p,o).toVar(),h=(0,n.vec3)(td(t,m.x),td(t,m.y),td(t,m.z)).toVar(),g=(0,n.vec3)(p.x.lessThan(o).select((0,n.float)(Mi),(0,n.float)(0)),p.y.lessThan(o).select((0,n.float)(Mi),(0,n.float)(0)),p.z.lessThan(o).select((0,n.float)(Mi),(0,n.float)(0))),_=(0,n.float)(2).mul(o).mul(i).mul(t).toVar(),v=(0,n.vec3)(f).add(g).toVar(),y=(0,n.clamp)((0,n.vec3)(s).mul(h),1e-5,.9999).toVar(),b=(0,n.sqrt)(y).toVar(),x=(0,n.vec3)(u.mul(u)).mul(h).div((0,n.vec3)(1).sub(y)).toVar(),S=(0,n.vec3)(s).add(x).toVar().toVar(),C=x.sub((0,n.vec3)(u)).toVar();C.mulAssign(b),S.addAssign(C.mul((0,n.float)(2).mul(Md((0,n.float)(1).mul(_),(0,n.float)(1).mul(v))))),C.mulAssign(b),S.addAssign(C.mul((0,n.float)(2).mul(Md((0,n.float)(2).mul(_),(0,n.float)(2).mul(v))))),l.assign((0,n.max)(S,(0,n.vec3)(0)))}),l}),Pd=(0,n.Fn)(([e,t,r])=>{let i=r.invRoughness,a=r.metalFactor,o=(0,n.float)(0).toVar();(0,n.If)(t.isMetallic,()=>{o.assign((0,n.max)(i.mul(a),.7))}).ElseIf(t.isSmooth,()=>{o.assign(i.mul(a).mul(1.2))}).Else(()=>{o.assign((0,n.max)(i.mul(a),e.metalness.mul(.1)))});let s=o.mul(e.specularIntensity).toVar(),c=(0,n.float)(1).sub(o).mul((0,n.float)(1).sub(e.metalness)).mul((0,n.float)(1).sub(e.transmission)).toVar(),l=e.sheen.mul(r.maxSheenColor).toVar(),u=(0,n.float)(0).toVar();(0,n.If)(t.hasClearcoat,()=>{u.assign(e.clearcoat.mul(i).mul(.4))}).Else(()=>{u.assign(e.clearcoat.mul(i).mul(.35))});let d=(0,n.float)(0).toVar();(0,n.If)(t.isTransmissive,()=>{let t=r.iorFactor.mul(i).mul(.8);d.assign(e.transmission.mul(t).mul((0,n.float)(.6).add((0,n.float)(.4).mul(e.ior.div(2)))).mul((0,n.float)(1).add(e.dispersion.mul(.6))))}).Else(()=>{let t=r.iorFactor.mul(i).mul(.7);d.assign(e.transmission.mul(t).mul((0,n.float)(.5).add((0,n.float)(.5).mul(e.ior.div(2)))).mul((0,n.float)(1).add(e.dispersion.mul(.5))))});let f=i.mul(t.isSmooth.select((0,n.float)(.6),(0,n.float)(.5))),p=(0,n.min)(e.iridescence.mul(f).mul((0,n.float)(.5).add((0,n.float)(.5).mul(e.iridescenceThicknessRange.y.sub(e.iridescenceThicknessRange.x).div(1e3)))).mul((0,n.float)(.5).add((0,n.float)(.5).mul(e.iridescenceIOR.div(2)))),c);s.addAssign(p),c.subAssign(p);let m=s.add(c).add(l).add(u).add(d),h=(0,n.float)(1).div((0,n.max)(m,.001));return xi({specular:s.mul(h),diffuse:c.mul(h),sheen:l.mul(h),clearcoat:u.mul(h),transmission:d.mul(h),iridescence:(0,n.float)(0)})}),Fd=(0,n.Fn)(([e,t,r])=>{let i=(0,n.float)(0).toVar();return(0,n.If)(r.NoL.greaterThan(0),()=>{i.addAssign(t.diffuse.mul(r.NoL).mul(Ni));let a=(0,n.float)(0).toVar();(0,n.If)(e.anisotropy.greaterThan(0),()=>{let t=Dd(e.roughness,e.anisotropy);a.assign(jd(t.x,t.y,r.NoH,r.ToH,r.BoH,r.NoV,r.ToV,r.BoV))}).Else(()=>{a.assign(Ed(r.NoH,r.NoV,e.roughness))}),i.addAssign(t.specular.mul(a)),(0,n.If)(t.sheen.greaterThan(0),()=>{let a=dd(r.NoH,e.sheenRoughness).mul(r.NoH).div((0,n.max)((0,n.float)(4).mul(r.VoH),Fi));i.addAssign(t.sheen.mul(a))}),(0,n.If)(t.clearcoat.greaterThan(0),()=>{let a=(0,n.clamp)(e.clearcoatRoughness,Li,1);i.addAssign(t.clearcoat.mul(Ed(r.NoH,r.NoV,a)))})}),i}),Id=(0,n.Fn)(([e])=>Pd(e,Di.wrap(ta(e.metalness,e.roughness,e.transmission,e.clearcoat,e.emissive,e.subsurface)),ki({invRoughness:(0,n.float)(1).sub(e.roughness),metalFactor:(0,n.float)(.5).add((0,n.float)(.5).mul(e.metalness)),iorFactor:(0,n.min)((0,n.float)(2).div(e.ior),1),maxSheenColor:(0,n.max)(e.sheenColor.x,(0,n.max)(e.sheenColor.y,e.sheenColor.z))}))),Ld=(0,n.Fn)(([e,t])=>Fd(e,xi.wrap(Id(e)),t)),Rd=(0,n.wgslFn)(`
|
|
487
487
|
fn ImportanceSampleGGX( N: vec3f, roughness: f32, Xi: vec2f ) -> vec3f {
|
|
488
488
|
let alpha = roughness * roughness;
|
|
489
489
|
let phi = 6.28318530717958647692f * Xi.x;
|
|
@@ -712,7 +712,7 @@ fn ${e}( c: vec3<f32> ) -> vec3<f32> {
|
|
|
712
712
|
let p = o + xu * x + yv * y + z0 * z;
|
|
713
713
|
return vec4f( p, 1.0f / S );
|
|
714
714
|
}
|
|
715
|
-
`);jt();var pp=vt(`shader`),mp=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),pp.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;ua(e.uniforms.get(`enableAlphaShadows`));let 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=e.goboMaps?(0,n.texture)(e.goboMaps):u();rp(d);let f=e.iesProfiles?(0,n.texture)(e.iesProfiles):u();sp(f);let p={triStorage:i,bvhStorage:a,matStorage:o,lightBufferStorage:s,envTex:c,goboMapsTex:d,iesProfilesTex:f};return this._sceneTextureNodes=p,p}dispose(){this.prevColorTexNode=null,this.prevAlbedoTexNode=null,this.prevNormalDepthTexNode=null,this._sceneTextureNodes=null}},hp=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.maxTreeletLeaves=7,this.minImprovement=.02,this.topologyCache=new Map;for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.set(e,this.generateTopologies(e));this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0}}generateTopologies(e){if(e===1)return[0];if(e===2)return[[0,1]];let t=[];for(let n=1;n<e;n++){let r=this.generateTopologies(n),i=this.generateTopologies(e-n);for(let e of r)for(let r of i)t.push([e,this.offsetTopology(r,n)])}return t}offsetTopology(e,t){return typeof e==`number`?e+t:[this.offsetTopology(e[0],t),this.offsetTopology(e[1],t)]}optimizeBVH(e){let t=performance.now();this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0};let n=this.identifyTreeletRoots(e);for(let e=0;e<n.length;e++){if(performance.now()-t>3e4){console.warn(`TreeletOptimizer: timeout after ${e}/${n.length} treelets`);break}this.optimizeTreelet(n[e])}return this.stats.optimizationTime=performance.now()-t,this.stats.averageSAHImprovement=this.stats.treeletsProcessed>0?this.stats.totalSAHImprovement/this.stats.treeletsProcessed:0,e}identifyTreeletRoots(e){let t=[],n=new Set,r=[{node:e,visited:!1}];for(;r.length>0;){let e=r[r.length-1];if(e.visited){r.pop();let i=e.node;if(i.triangleCount>0||n.has(i))continue;let a=this.countLeaves(i);a>=3&&a<=this.maxTreeletLeaves&&(t.push(i),this.markSubtree(i,n))}else{e.visited=!0;let t=e.node;if(t.triangleCount>0)continue;t.rightChild&&r.push({node:t.rightChild,visited:!1}),t.leftChild&&r.push({node:t.leftChild,visited:!1})}}return t}countLeaves(e){return e?e.triangleCount>0?1:this.countLeaves(e.leftChild)+this.countLeaves(e.rightChild):0}markSubtree(e,t){e&&(t.add(e),!(e.triangleCount>0)&&(this.markSubtree(e.leftChild,t),this.markSubtree(e.rightChild,t)))}optimizeTreelet(e){let t=[];this.extractLeaves(e,t);let n=t.length;if(n<3||n>this.maxTreeletLeaves)return;this.stats.treeletsProcessed++;let r=this.evaluateSubtreeSAH(e),i=this.topologyCache.get(n);if(!i||i.length===0)return;let a=r,o=null,s=null;if(n<=5){let e=this.generatePermutations(n);for(let n of i)for(let r of e){let e=this.evaluateTopology(n,t,r);e<a&&(a=e,o=n,s=r)}}else{let e=Array.from({length:n},(e,t)=>t);for(let n of i){let r=this.evaluateTopology(n,t,e);r<a&&(a=r,o=n,s=e);let i=this.greedySwapOptimize(n,t,e,r);i.cost<a&&(a=i.cost,o=n,s=i.perm)}}let c=(r-a)/r;o&&c>this.minImprovement&&(this.reconstructTreelet(e,o,t,s),this.stats.treeletsImproved++,this.stats.totalSAHImprovement+=c)}extractLeaves(e,t){if(e){if(e.triangleCount>0){t.push({minX:e.minX,minY:e.minY,minZ:e.minZ,maxX:e.maxX,maxY:e.maxY,maxZ:e.maxZ,triangleOffset:e.triangleOffset,triangleCount:e.triangleCount});return}this.extractLeaves(e.leftChild,t),this.extractLeaves(e.rightChild,t)}}evaluateSubtreeSAH(e){if(!e)return 0;if(e.triangleCount>0)return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*e.triangleCount*this.intersectionCost;let t=this.evaluateSubtreeSAH(e.leftChild),n=this.evaluateSubtreeSAH(e.rightChild);return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*this.traversalCost+t+n}evaluateTopology(e,t,n){return this.evalTopoRecursive(e,t,n).cost}evalTopoRecursive(e,t,n){if(typeof e==`number`){let r=t[n[e]];return{cost:this.surfaceAreaFlat(r.minX,r.minY,r.minZ,r.maxX,r.maxY,r.maxZ)*r.triangleCount*this.intersectionCost,minX:r.minX,minY:r.minY,minZ:r.minZ,maxX:r.maxX,maxY:r.maxY,maxZ:r.maxZ}}let r=this.evalTopoRecursive(e[0],t,n),i=this.evalTopoRecursive(e[1],t,n),a=Math.min(r.minX,i.minX),o=Math.min(r.minY,i.minY),s=Math.min(r.minZ,i.minZ),c=Math.max(r.maxX,i.maxX),l=Math.max(r.maxY,i.maxY),u=Math.max(r.maxZ,i.maxZ);return{cost:this.surfaceAreaFlat(a,o,s,c,l,u)*this.traversalCost+r.cost+i.cost,minX:a,minY:o,minZ:s,maxX:c,maxY:l,maxZ:u}}surfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}generatePermutations(e){let t=[],n=Array.from({length:e},(e,t)=>t),r=i=>{if(i===e){t.push([...n]);return}for(let t=i;t<e;t++)[n[i],n[t]]=[n[t],n[i]],r(i+1),[n[i],n[t]]=[n[t],n[i]]};return r(0),t}greedySwapOptimize(e,t,n,r){let i=[...n],a=r,o=!0;for(;o;){o=!1;for(let n=0;n<i.length-1;n++)for(let r=n+1;r<i.length;r++){[i[n],i[r]]=[i[r],i[n]];let s=this.evaluateTopology(e,t,i);s<a?(a=s,o=!0):[i[n],i[r]]=[i[r],i[n]]}}return{perm:i,cost:a}}reconstructTreelet(e,t,n,r){let i=this.buildSubtree(t,n,r);e.minX=i.minX,e.minY=i.minY,e.minZ=i.minZ,e.maxX=i.maxX,e.maxY=i.maxY,e.maxZ=i.maxZ,e.leftChild=i.leftChild,e.rightChild=i.rightChild,e.triangleOffset=i.triangleOffset,e.triangleCount=i.triangleCount}buildSubtree(e,t,n){if(typeof e==`number`){let r=t[n[e]],i=new gp;return i.minX=r.minX,i.minY=r.minY,i.minZ=r.minZ,i.maxX=r.maxX,i.maxY=r.maxY,i.maxZ=r.maxZ,i.triangleOffset=r.triangleOffset,i.triangleCount=r.triangleCount,i}let r=this.buildSubtree(e[0],t,n),i=this.buildSubtree(e[1],t,n),a=new gp;return a.leftChild=r,a.rightChild=i,a.minX=Math.min(r.minX,i.minX),a.minY=Math.min(r.minY,i.minY),a.minZ=Math.min(r.minZ,i.minZ),a.maxX=Math.max(r.maxX,i.maxX),a.maxY=Math.max(r.maxY,i.maxY),a.maxZ=Math.max(r.maxZ,i.maxZ),a}setTreeletSize(e){this.maxTreeletLeaves=Math.max(3,Math.min(7,e));for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.has(e)||this.topologyCache.set(e,this.generateTopologies(e))}setMinImprovement(e){this.minImprovement=Math.max(.001,e)}getStatistics(){return{...this.stats}}},gp=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}},_p=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}},vp=1073741824,yp=1073741824,bp=15,xp=16,Sp=2147483648,Cp=(e,t)=>~(e<<4|t)>>>0,wp=e=>e>=Sp,Tp=e=>~e>>>0>>>4,Ep=e=>~e&15;function Dp(e){let t=new Uint32Array(e.buffer,e.byteOffset,e.length),n=e.length/xp,r=e=>{let n=e*xp;return t[n+3]===vp&&t[n+1]>0&&t[n+1]<=bp},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*xp;t[n+3]>=yp||(r(t[n+7])||s.push(t[n+7]),r(t[n+3])||s.push(t[n+3]))}let c=new Float32Array(o*xp),l=new Uint32Array(c.buffer);for(let n=0;n<o;n++){let o=a[n]*xp,s=n*xp;c.set(e.subarray(o,o+xp),s),!(t[o+3]>=yp)&&(l[s+3]=Op(t,t[o+3],r,i),l[s+7]=Op(t,t[o+7],r,i))}return c}function Op(e,t,n,r){let i=t*xp;return n(t)?Cp(e[i],e[i+1]):r[t]}var kp=(e,t,n)=>e>=Sp?Cp(Tp(e)+n,Ep(e)):e+t;function Ap(e,t,n,r=0,i=e.length){for(let a=r;a<i;a+=xp){if(e[a+3]===vp){e[a]+=n;continue}e[a+3]=kp(e[a+3],t,n),e[a+7]=kp(e[a+7],t,n)}}jt();var jp=vt(`bvh`),Mp=1073741824,Np=1073741826,Pp=e=>new Uint32Array(e.buffer,e.byteOffset,e.length),Fp=1073741824;function Ip(e,t){if(e>=Fp)throw RangeError(`${t} is ${e}, at or past the BVH index limit of ${Fp}`);return e}var Lp=null;function Rp(e){Lp=e}var zp={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8},Bp=zp.FLOATS_PER_TRIANGLE,Vp=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),Hp=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}},Up=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,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0},this.enableTreeletOptimization=!1,this.treeletSize=5,this.treeletOptimizationPasses=1,this.treeletMinImprovement=.02,this.treeletComplexityThreshold=5e4,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)}setTreeletConfig(e){e.enabled!==void 0&&(this.enableTreeletOptimization=e.enabled),e.size!==void 0&&(this.treeletSize=Math.max(3,Math.min(12,e.size))),e.passes!==void 0&&(this.treeletOptimizationPasses=Math.max(1,Math.min(3,e.passes))),e.minImprovement!==void 0&&(this.treeletMinImprovement=Math.max(.001,e.minImprovement)),e.complexityThreshold!==void 0&&(this.treeletComplexityThreshold=e.complexityThreshold)}disableTreeletOptimization(){this.enableTreeletOptimization=!1}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=Vp(this.triangles),n=zp.POSITION_A_OFFSET,r=zp.POSITION_B_OFFSET,i=zp.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*Bp,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/(Bp*4),this.processedTriangles=0,this.lastProgressUpdate=performance.now(),this.useWorker&&Lp&&si()?new Promise((r,i)=>{let a=a=>{let o=this.totalTriangles,s=typeof SharedArrayBuffer<`u`;jp.debug(`SharedArrayBuffer ${s?`enabled`:`unavailable (using transfer fallback)`}`);let c=s?new SharedArrayBuffer(o*Bp*4):null;a.onmessage=e=>{let{bvhData:t,triangles:o,originalToBvh:s,error:l,progress:u,treeletStats: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,treeletOptimization:{enabled:this.enableTreeletOptimization,size:this.treeletSize,passes:this.treeletOptimizationPasses,minImprovement:this.treeletMinImprovement},reinsertionOptimization:{enabled:this.enableReinsertionOptimization,batchSizeRatio:this.reinsertionBatchSizeRatio,maxIterations:this.reinsertionMaxIterations}};a.postMessage(u,[l])};try{a(Lp())}catch(i){jp.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?Dp(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/(Bp*4),this.lastProgressUpdate=performance.now(),this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement: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.enableTreeletOptimization&&this.totalTriangles>1e3){let e=this.totalTriangles>this.treeletComplexityThreshold?3:this.treeletSize,t=new hp(this.traversalCost,this.intersectionCost);t.setTreeletSize(e),t.setMinImprovement(this.treeletMinImprovement);let r=performance.now();for(let e=0;e<this.treeletOptimizationPasses;e++){let i=n?t=>{n(`Treelet optimization pass ${e+1}/${this.treeletOptimizationPasses}: ${t}`)}:null;try{t.optimizeBVH(c,i)}catch(t){jp.error(`treelet optimizer failed in pass ${e+1}:`,t);break}let a=t.getStatistics(),o=performance.now()-r;if(a.treeletsImproved===0&&e>0||o>15e3)break}let i=performance.now()-r;this.splitStats.treeletOptimizationTime=i;let a=t.getStatistics();this.splitStats.treeletsProcessed=a.treeletsProcessed,this.splitStats.treeletsImproved=a.treeletsImproved,this.splitStats.averageSAHImprovement=a.averageSAHImprovement}if(this.enableReinsertionOptimization&&this.totalTriangles>1e3){let e=new _p(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){jp.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*Bp);for(let e=0;e<a;e++){let t=this.indices[e]*Bp,n=e*Bp;f.set(d.subarray(t,t+Bp),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 jp.debug(`${J.n(a)} tris → ${J.n(this.totalNodes)} nodes in ${J.ms(m)} | SAH ${h.sahSplits} objMed ${h.objectMedianSplits} spatMed ${h.spatialMedianSplits} failed ${h.failedSplits}`+(h.treeletsProcessed?` | treelets ${h.treeletsImproved}/${h.treeletsProcessed} improved`:``)+(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 Hp;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 Hp;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)}Ip(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=Pp(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]=Mp}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)}Ip(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=[],a=Pp(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]=Np,i.push({taskId:t,flatIndex:e})}else a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+3]=Mp}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;Ip(a,`assembled BLAS node count`);let o=new Float32Array(a*16),s=Pp(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]<Mp&&(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)}},Wp={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},Gp=Wp.FLOATS_PER_TRIANGLE,Kp=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),qp=e=>e instanceof Uint32Array?e:new Uint32Array(e.buffer,e.byteOffset,e.length),Jp=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:e,idx:t?e.viewAs(Uint32Array):qp(e)}},Yp=(e,t)=>e.chunked?e.f.chunkFor(t):e.f,Xp=(e,t)=>e.chunked?e.idx.chunkFor(t):e.idx,Zp=(e,t)=>e.chunked?e.chunked.baseOf(t):t*em,Qp=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:t?t.viewAs(Float32Array):Kp(e),u:t?e:qp(e)}};function $p(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}var em=16,tm=1073741824,nm=1073741825,rm=1e-12;function im(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)<=rm*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,ee=-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>ee&&(ee=c)}i[a]=P,i[a+1]=F,i[a+2]=I,i[a+3]=L,i[a+4]=R,i[a+5]=ee}function am(e,t,n,r,i){let a=Wp.POSITION_A_OFFSET,o=Wp.POSITION_B_OFFSET,s=Wp.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*Gp;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 om=new Float32Array(12);function sm(e,t,n,r){let i=Yp(e,t),a=Xp(e,t),o=Zp(e,t);if(a[o+3]===tm){am(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 cm(e,t,n,r,i){let a=Yp(e,t),o=Xp(e,t),s=Zp(e,t),c=(t-i)*6,l=o[s+3];if(l===tm){am(n,o[s],o[s+1],r,c);return}if(l===nm){im(a,s,r,(o[s]-i)*6,r,c);return}let u=o[s+7],d=r,f=(l-i)*6;wp(l)&&(am(n,Tp(l),Ep(l),om,0),d=om,f=0);let p=r,m=(u-i)*6;wp(u)&&(am(n,Tp(u),Ep(u),om,6),p=om,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 lm=class{constructor(){this._bounds=null,this._boundsNodeCount=0,this._tlasBounds=null,this._rootBox=null}updateTrianglePositions(e,t,n){let r=n.length,i=Qp(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*Gp,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+Wp.POSITION_A_OFFSET]=l,a[s+Wp.POSITION_A_OFFSET+1]=u,a[s+Wp.POSITION_A_OFFSET+2]=d,a[s+Wp.POSITION_B_OFFSET]=f,a[s+Wp.POSITION_B_OFFSET+1]=p,a[s+Wp.POSITION_B_OFFSET+2]=m,a[s+Wp.POSITION_C_OFFSET]=h,a[s+Wp.POSITION_C_OFFSET+1]=g,a[s+Wp.POSITION_C_OFFSET+2]=_;let v=f-l,y=p-u,b=m-d,x=h-l,S=g-u,C=_-d,w=$p(y*C-b*S,b*x-v*C,v*S-y*x);o[s+Wp.NORMAL_A_PACKED_OFFSET]=w,o[s+Wp.NORMAL_B_PACKED_OFFSET]=w,o[s+Wp.NORMAL_C_PACKED_OFFSET]=w}}refitRange(e,t,n,r){let i=Qp(t);r>this._boundsNodeCount&&(this._bounds=new Float32Array(r*6),this._boundsNodeCount=r);let a=Jp(e);for(let e=n+r-1;e>=n;e--)cm(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=Qp(t),a=Jp(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=Xp(a,e),n=Zp(a,e);t[n+3]===nm?(sm(a,t[n],i,s),im(Yp(a,e),n,s,0,o,e*6)):cm(a,e,i,o,0)}}refit(e,t,n){let r=Qp(t);n!==this._boundsNodeCount&&(this._bounds=new Float32Array(n*6),this._boundsNodeCount=n);let i=Jp(e);for(let e=n-1;e>=0;e--)cm(i,e,r,this._bounds,0)}},um="var e=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.maxTreeletLeaves=7,this.minImprovement=.02,this.topologyCache=new Map;for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.set(e,this.generateTopologies(e));this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0}}generateTopologies(e){if(e===1)return[0];if(e===2)return[[0,1]];let t=[];for(let n=1;n<e;n++){let r=this.generateTopologies(n),i=this.generateTopologies(e-n);for(let e of r)for(let r of i)t.push([e,this.offsetTopology(r,n)])}return t}offsetTopology(e,t){return typeof e==`number`?e+t:[this.offsetTopology(e[0],t),this.offsetTopology(e[1],t)]}optimizeBVH(e){let t=performance.now();this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0};let n=this.identifyTreeletRoots(e);for(let e=0;e<n.length;e++){if(performance.now()-t>3e4){console.warn(`TreeletOptimizer: timeout after ${e}/${n.length} treelets`);break}this.optimizeTreelet(n[e])}return this.stats.optimizationTime=performance.now()-t,this.stats.averageSAHImprovement=this.stats.treeletsProcessed>0?this.stats.totalSAHImprovement/this.stats.treeletsProcessed:0,e}identifyTreeletRoots(e){let t=[],n=new Set,r=[{node:e,visited:!1}];for(;r.length>0;){let e=r[r.length-1];if(e.visited){r.pop();let i=e.node;if(i.triangleCount>0||n.has(i))continue;let a=this.countLeaves(i);a>=3&&a<=this.maxTreeletLeaves&&(t.push(i),this.markSubtree(i,n))}else{e.visited=!0;let t=e.node;if(t.triangleCount>0)continue;t.rightChild&&r.push({node:t.rightChild,visited:!1}),t.leftChild&&r.push({node:t.leftChild,visited:!1})}}return t}countLeaves(e){return e?e.triangleCount>0?1:this.countLeaves(e.leftChild)+this.countLeaves(e.rightChild):0}markSubtree(e,t){e&&(t.add(e),!(e.triangleCount>0)&&(this.markSubtree(e.leftChild,t),this.markSubtree(e.rightChild,t)))}optimizeTreelet(e){let t=[];this.extractLeaves(e,t);let n=t.length;if(n<3||n>this.maxTreeletLeaves)return;this.stats.treeletsProcessed++;let r=this.evaluateSubtreeSAH(e),i=this.topologyCache.get(n);if(!i||i.length===0)return;let a=r,o=null,s=null;if(n<=5){let e=this.generatePermutations(n);for(let n of i)for(let r of e){let e=this.evaluateTopology(n,t,r);e<a&&(a=e,o=n,s=r)}}else{let e=Array.from({length:n},(e,t)=>t);for(let n of i){let r=this.evaluateTopology(n,t,e);r<a&&(a=r,o=n,s=e);let i=this.greedySwapOptimize(n,t,e,r);i.cost<a&&(a=i.cost,o=n,s=i.perm)}}let c=(r-a)/r;o&&c>this.minImprovement&&(this.reconstructTreelet(e,o,t,s),this.stats.treeletsImproved++,this.stats.totalSAHImprovement+=c)}extractLeaves(e,t){if(e){if(e.triangleCount>0){t.push({minX:e.minX,minY:e.minY,minZ:e.minZ,maxX:e.maxX,maxY:e.maxY,maxZ:e.maxZ,triangleOffset:e.triangleOffset,triangleCount:e.triangleCount});return}this.extractLeaves(e.leftChild,t),this.extractLeaves(e.rightChild,t)}}evaluateSubtreeSAH(e){if(!e)return 0;if(e.triangleCount>0)return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*e.triangleCount*this.intersectionCost;let t=this.evaluateSubtreeSAH(e.leftChild),n=this.evaluateSubtreeSAH(e.rightChild);return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*this.traversalCost+t+n}evaluateTopology(e,t,n){return this.evalTopoRecursive(e,t,n).cost}evalTopoRecursive(e,t,n){if(typeof e==`number`){let r=t[n[e]];return{cost:this.surfaceAreaFlat(r.minX,r.minY,r.minZ,r.maxX,r.maxY,r.maxZ)*r.triangleCount*this.intersectionCost,minX:r.minX,minY:r.minY,minZ:r.minZ,maxX:r.maxX,maxY:r.maxY,maxZ:r.maxZ}}let r=this.evalTopoRecursive(e[0],t,n),i=this.evalTopoRecursive(e[1],t,n),a=Math.min(r.minX,i.minX),o=Math.min(r.minY,i.minY),s=Math.min(r.minZ,i.minZ),c=Math.max(r.maxX,i.maxX),l=Math.max(r.maxY,i.maxY),u=Math.max(r.maxZ,i.maxZ);return{cost:this.surfaceAreaFlat(a,o,s,c,l,u)*this.traversalCost+r.cost+i.cost,minX:a,minY:o,minZ:s,maxX:c,maxY:l,maxZ:u}}surfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}generatePermutations(e){let t=[],n=Array.from({length:e},(e,t)=>t),r=i=>{if(i===e){t.push([...n]);return}for(let t=i;t<e;t++)[n[i],n[t]]=[n[t],n[i]],r(i+1),[n[i],n[t]]=[n[t],n[i]]};return r(0),t}greedySwapOptimize(e,t,n,r){let i=[...n],a=r,o=!0;for(;o;){o=!1;for(let n=0;n<i.length-1;n++)for(let r=n+1;r<i.length;r++){[i[n],i[r]]=[i[r],i[n]];let s=this.evaluateTopology(e,t,i);s<a?(a=s,o=!0):[i[n],i[r]]=[i[r],i[n]]}}return{perm:i,cost:a}}reconstructTreelet(e,t,n,r){let i=this.buildSubtree(t,n,r);e.minX=i.minX,e.minY=i.minY,e.minZ=i.minZ,e.maxX=i.maxX,e.maxY=i.maxY,e.maxZ=i.maxZ,e.leftChild=i.leftChild,e.rightChild=i.rightChild,e.triangleOffset=i.triangleOffset,e.triangleCount=i.triangleCount}buildSubtree(e,n,r){if(typeof e==`number`){let i=n[r[e]],a=new t;return a.minX=i.minX,a.minY=i.minY,a.minZ=i.minZ,a.maxX=i.maxX,a.maxY=i.maxY,a.maxZ=i.maxZ,a.triangleOffset=i.triangleOffset,a.triangleCount=i.triangleCount,a}let i=this.buildSubtree(e[0],n,r),a=this.buildSubtree(e[1],n,r),o=new t;return o.leftChild=i,o.rightChild=a,o.minX=Math.min(i.minX,a.minX),o.minY=Math.min(i.minY,a.minY),o.minZ=Math.min(i.minZ,a.minZ),o.maxX=Math.max(i.maxX,a.maxX),o.maxY=Math.max(i.maxY,a.maxY),o.maxZ=Math.max(i.maxZ,a.maxZ),o}setTreeletSize(e){this.maxTreeletLeaves=Math.max(3,Math.min(7,e));for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.has(e)||this.topologyCache.set(e,this.generateTopologies(e))}setMinImprovement(e){this.minImprovement=Math.max(.001,e)}getStatistics(){return{...this.stats}}},t=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(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 r={silent:0,error:1,warn:2,info:3,debug:4},i=`info`,a=`rayzeeLogLevel`,o=`rayzeeLogNamespaces`,s=`color:#7c8494`,c=`color:inherit`;let l=null,u=null;function d(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function f(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function p(){if(l!==null)return l;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in r?(l=r[e],l):(l=r[d(a)]??r[i],l)}function m(){if(u!==null)return u;let e=globalThis.__RAYZEE_LOG_NS__??d(o);return u=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],u}function h(e,t){if(t<r.debug)return!0;let n=m();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function g(e,t,n){if(e>p()||!h(t,e))return;let i=e===r.error?console.error:e===r.warn?console.warn:console.log,a=`[${t}]`;typeof n[0]==`string`?i(`%c${a}%c ${n[0]}`,s,c,...n.slice(1)):i(`%c${a}`,s,...n)}const _={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`)=>`${_.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},v={levels:r,setLevel(e){return e in r?(globalThis.__RAYZEE_LOG_LEVEL__=e,l=r[e],f(a,e===i?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(r).join(`, `)}`),this.getLevel())},getLevel(){let e=p();return Object.keys(r).find(t=>r[t]===e)},isEnabled(e){return(r[e]??r.debug)<=p()},only(...e){let t=e.flat().filter(Boolean);return u=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),f(o,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return l=null,u=null,this.getLevel()}};function y(e){return{namespace:e,error:(...t)=>g(r.error,e,t),warn:(...t)=>g(r.warn,e,t),info:(...t)=>g(r.info,e,t),debug:(...t)=>g(r.debug,e,t),isEnabled:e=>v.isEnabled(e),summary(t,n=[]){let i=n.filter(Boolean);if(i.length===0||!console.groupCollapsed){g(r.info,e,[t]),i.forEach(t=>g(r.debug,e,[t]));return}r.info>p()||((p()>=r.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,s,c),i.forEach(e=>console.log(e)),console.groupEnd())}}}function b(e){e&&e in r&&(globalThis.__RAYZEE_LOG_LEVEL__=e,l=r[e])}const x=1073741824,S=(e,t)=>~(e<<4|t)>>>0;function C(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]===1073741824&&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]>=x||(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]>=x)&&(l[s+3]=w(t,t[o+3],r,i),l[s+7]=w(t,t[o+7],r,i))}return c}function w(e,t,n,r){let i=t*16;return n(t)?S(e[i],e[i+1]):r[t]}const T=y(`bvh`),E=1073741824,D=e=>new Uint32Array(e.buffer,e.byteOffset,e.length),O=1073741824;function k(e,t){if(e>=O)throw RangeError(`${t} is ${e}, at or past the BVH index limit of ${O}`);return e}const A={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8},j=A.FLOATS_PER_TRIANGLE,M=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length);var N=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}},P=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,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0},this.enableTreeletOptimization=!1,this.treeletSize=5,this.treeletOptimizationPasses=1,this.treeletMinImprovement=.02,this.treeletComplexityThreshold=5e4,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)}setTreeletConfig(e){e.enabled!==void 0&&(this.enableTreeletOptimization=e.enabled),e.size!==void 0&&(this.treeletSize=Math.max(3,Math.min(12,e.size))),e.passes!==void 0&&(this.treeletOptimizationPasses=Math.max(1,Math.min(3,e.passes))),e.minImprovement!==void 0&&(this.treeletMinImprovement=Math.max(.001,e.minImprovement)),e.complexityThreshold!==void 0&&(this.treeletComplexityThreshold=e.complexityThreshold)}disableTreeletOptimization(){this.enableTreeletOptimization=!1}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=M(this.triangles),n=A.POSITION_A_OFFSET,r=A.POSITION_B_OFFSET,i=A.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*j,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/(j*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?C(i):i,bvhRoot:!0,reorderedTriangles:this.reorderedTriangleData||null,originalToBvh:this.originalToBvhMap||null}}buildSync(t,r=30,i=null,a=null){let o=performance.now();this.totalNodes=0,this.processedTriangles=0,this.triangles=t,this.totalTriangles=t.byteLength/(j*4),this.lastProgressUpdate=performance.now(),this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0,saOrderTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let s=this.totalTriangles,c=performance.now();this.centroids=new Float32Array(s*3),this.bMin=new Float32Array(s*3),this.bMax=new Float32Array(s*3),this.indices=new Uint32Array(s),this.mortonCodes=new Uint32Array(s),this.initializeTriangleArrays(),this.splitStats.initTime=performance.now()-c,this.sortTrianglesByMortonCode();let l=performance.now(),u=this.buildNodeRecursive(0,s,r,i);if(this.splitStats.sahBuildTime=performance.now()-l,this.enableTreeletOptimization&&this.totalTriangles>1e3){let t=this.totalTriangles>this.treeletComplexityThreshold?3:this.treeletSize,n=new e(this.traversalCost,this.intersectionCost);n.setTreeletSize(t),n.setMinImprovement(this.treeletMinImprovement);let r=performance.now();for(let e=0;e<this.treeletOptimizationPasses;e++){let t=i?t=>{i(`Treelet optimization pass ${e+1}/${this.treeletOptimizationPasses}: ${t}`)}:null;try{n.optimizeBVH(u,t)}catch(t){T.error(`treelet optimizer failed in pass ${e+1}:`,t);break}let a=n.getStatistics(),o=performance.now()-r;if(a.treeletsImproved===0&&e>0||o>15e3)break}let a=performance.now()-r;this.splitStats.treeletOptimizationTime=a;let o=n.getStatistics();this.splitStats.treeletsProcessed=o.treeletsProcessed,this.splitStats.treeletsImproved=o.treeletsImproved,this.splitStats.averageSAHImprovement=o.averageSAHImprovement}if(this.enableReinsertionOptimization&&this.totalTriangles>1e3){let e=new n(this.traversalCost,this.intersectionCost);e.setBatchSizeRatio(this.reinsertionBatchSizeRatio),e.setMaxIterations(this.reinsertionMaxIterations);let t=i?e=>{i(e)}:null;try{e.optimizeBVH(u,t)}catch(e){T.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 d=performance.now();this.applySAOrdering(u),this.splitStats.saOrderTime=performance.now()-d;let f=performance.now(),p=this.triangles,m=a||new p.constructor(s*j);for(let e=0;e<s;e++){let t=this.indices[e]*j,n=e*j;m.set(p.subarray(t,t+j),n)}this.reorderedTriangleData=m;let h=new Uint32Array(s);for(let e=0;e<s;e++)h[this.indices[e]]=e;this.originalToBvhMap=h,this.splitStats.reorderTime=performance.now()-f,this.splitStats.totalBuildTime=performance.now()-o;let g=this.splitStats.totalBuildTime,v=this.splitStats;return T.debug(`${_.n(s)} tris → ${_.n(this.totalNodes)} nodes in ${_.ms(g)} | SAH ${v.sahSplits} objMed ${v.objectMedianSplits} spatMed ${v.spatialMedianSplits} failed ${v.failedSplits}`+(v.treeletsProcessed?` | treelets ${v.treeletsImproved}/${v.treeletsProcessed} improved`:``)+(v.reinsertionsApplied?` | reinsertions ${v.reinsertionsApplied}`:``)),i&&i(100),this.centroids=null,this.bMin=null,this.bMax=null,this.mortonCodes=null,u}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 N;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 N;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)}k(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=D(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]=E}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)}k(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=[],a=D(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]=1073741826,i.push({taskId:t,flatIndex:e})}else a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+3]=E}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;k(a,`assembled BLAS node count`);let o=new Float32Array(a*16),s=D(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]<E&&(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 F=y(`bvh`);self.onmessage=function(e){let t=e.data,n=t.type;b(t.logLevel),n===`buildPhase1`?I(t):n===`assemble`?L(t):R(t)};function I(e){let{sharedTriangleData:t,sharedCentroids:n,sharedBMin:r,sharedBMax:i,sharedIndices:a,sharedMortonCodes:o,triangleCount:s,depth:c,parallelDepth:l,reportProgress:u,treeletOptimization:d}=e;try{let e=new P;d&&e.setTreeletConfig(d);let f=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,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,initTime:0,sahBuildTime:0,reorderTime:0};let p=performance.now(),m=performance.now();e.initializeTriangleArrays(),e.splitStats.initTime=performance.now()-m,e.sortTrianglesByMortonCode(),e.frontierTasks=[];let h=performance.now(),g=e.buildNodeRecursiveToDepth(0,s,c,l,f);e.splitStats.sahBuildTime=performance.now()-h,e.applySAOrdering(g);let v=performance.now(),{flatData:y,frontierMap:b,nodeCount:x}=e.flattenBVHWithFrontier(g),S=performance.now()-v,C=performance.now()-p;F.debug(`phase 1 ${_.ms(C)} (init ${_.ms(e.splitStats.initTime)} · morton ${_.ms(e.splitStats.mortonSortTime)} · SAH ${_.ms(e.splitStats.sahBuildTime)} · flatten ${_.ms(S)}) · ${e.frontierTasks.length} frontier tasks`),self.postMessage({type:`phase1Result`,topFlatData:y,topNodeCount:x,frontierTasks:e.frontierTasks,frontierMap:b,splitStats:e.splitStats},[y.buffer])}catch(e){F.error(`phase 1 failed:`,e),self.postMessage({type:`error`,error:e.message})}}function L(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 P().assembleParallelBVH(t,n,r,i),d=l?C(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;F.debug(`phase 3 assemble + reorder ${_.ms(m)} (${_.mb(d.byteLength)} BVH)`),self.postMessage({type:`assembleResult`,bvhData:d,originalToBvh:p,triangleCount:c},[d.buffer,p.buffer])}catch(e){F.error(`assembly failed:`,e),self.postMessage({type:`error`,error:e.message})}}function R(e){let{triangleData:t,triangleByteOffset:n,triangleByteLength:r,depth:i,reportProgress:a,treeletOptimization:o,reinsertionOptimization:s,sharedReorderBuffer:c,maxLeafSize:l,numBins:u,maxBins:d,minBins:f,foldLeaves:p}=e,m=new P;l!==void 0&&(m.maxLeafSize=l),u!==void 0&&(m.numBins=u),d!==void 0&&(m.maxBins=d),f!==void 0&&(m.minBins=f);try{o&&m.setTreeletConfig(o),s&&m.setReinsertionConfig(s);let e=a?e=>{self.postMessage({progress:e})}:null,l=n===void 0?new Uint32Array(t):new Uint32Array(t,n,r/4),u=c?new Uint32Array(c):null,d=m.buildSync(l,i,e,u),f=performance.now(),h=m.flattenBVH(d),g=p?C(h):h,v=performance.now()-f;F.debug(`flatten ${_.ms(v)} (${_.mb(g.byteLength)})`);let y=m.originalToBvhMap||null;if(c){let e=[g.buffer];y&&e.push(y.buffer),self.postMessage({bvhData:g,originalToBvh:y,triangleCount:l.length/20,treeletStats:m.splitStats},e)}else{let e=m.reorderedTriangleData,t=e.byteLength/80,n=[g.buffer,e.buffer];y&&n.push(y.buffer),self.postMessage({bvhData:g,triangles:e,originalToBvh:y,triangleCount:t,treeletStats:m.splitStats},n)}}catch(e){F.error(`build failed:`,e),self.postMessage({error:e.message})}}",dm=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,um],{type:`text/javascript;charset=utf-8`});function fm(e){let t;try{if(t=dm&&(self.URL||self.webkitURL).createObjectURL(dm),!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(um),{type:`module`,name:e?.name})}}var pm="var e=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.maxTreeletLeaves=7,this.minImprovement=.02,this.topologyCache=new Map;for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.set(e,this.generateTopologies(e));this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0}}generateTopologies(e){if(e===1)return[0];if(e===2)return[[0,1]];let t=[];for(let n=1;n<e;n++){let r=this.generateTopologies(n),i=this.generateTopologies(e-n);for(let e of r)for(let r of i)t.push([e,this.offsetTopology(r,n)])}return t}offsetTopology(e,t){return typeof e==`number`?e+t:[this.offsetTopology(e[0],t),this.offsetTopology(e[1],t)]}optimizeBVH(e){let t=performance.now();this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0};let n=this.identifyTreeletRoots(e);for(let e=0;e<n.length;e++){if(performance.now()-t>3e4){console.warn(`TreeletOptimizer: timeout after ${e}/${n.length} treelets`);break}this.optimizeTreelet(n[e])}return this.stats.optimizationTime=performance.now()-t,this.stats.averageSAHImprovement=this.stats.treeletsProcessed>0?this.stats.totalSAHImprovement/this.stats.treeletsProcessed:0,e}identifyTreeletRoots(e){let t=[],n=new Set,r=[{node:e,visited:!1}];for(;r.length>0;){let e=r[r.length-1];if(e.visited){r.pop();let i=e.node;if(i.triangleCount>0||n.has(i))continue;let a=this.countLeaves(i);a>=3&&a<=this.maxTreeletLeaves&&(t.push(i),this.markSubtree(i,n))}else{e.visited=!0;let t=e.node;if(t.triangleCount>0)continue;t.rightChild&&r.push({node:t.rightChild,visited:!1}),t.leftChild&&r.push({node:t.leftChild,visited:!1})}}return t}countLeaves(e){return e?e.triangleCount>0?1:this.countLeaves(e.leftChild)+this.countLeaves(e.rightChild):0}markSubtree(e,t){e&&(t.add(e),!(e.triangleCount>0)&&(this.markSubtree(e.leftChild,t),this.markSubtree(e.rightChild,t)))}optimizeTreelet(e){let t=[];this.extractLeaves(e,t);let n=t.length;if(n<3||n>this.maxTreeletLeaves)return;this.stats.treeletsProcessed++;let r=this.evaluateSubtreeSAH(e),i=this.topologyCache.get(n);if(!i||i.length===0)return;let a=r,o=null,s=null;if(n<=5){let e=this.generatePermutations(n);for(let n of i)for(let r of e){let e=this.evaluateTopology(n,t,r);e<a&&(a=e,o=n,s=r)}}else{let e=Array.from({length:n},(e,t)=>t);for(let n of i){let r=this.evaluateTopology(n,t,e);r<a&&(a=r,o=n,s=e);let i=this.greedySwapOptimize(n,t,e,r);i.cost<a&&(a=i.cost,o=n,s=i.perm)}}let c=(r-a)/r;o&&c>this.minImprovement&&(this.reconstructTreelet(e,o,t,s),this.stats.treeletsImproved++,this.stats.totalSAHImprovement+=c)}extractLeaves(e,t){if(e){if(e.triangleCount>0){t.push({minX:e.minX,minY:e.minY,minZ:e.minZ,maxX:e.maxX,maxY:e.maxY,maxZ:e.maxZ,triangleOffset:e.triangleOffset,triangleCount:e.triangleCount});return}this.extractLeaves(e.leftChild,t),this.extractLeaves(e.rightChild,t)}}evaluateSubtreeSAH(e){if(!e)return 0;if(e.triangleCount>0)return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*e.triangleCount*this.intersectionCost;let t=this.evaluateSubtreeSAH(e.leftChild),n=this.evaluateSubtreeSAH(e.rightChild);return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*this.traversalCost+t+n}evaluateTopology(e,t,n){return this.evalTopoRecursive(e,t,n).cost}evalTopoRecursive(e,t,n){if(typeof e==`number`){let r=t[n[e]];return{cost:this.surfaceAreaFlat(r.minX,r.minY,r.minZ,r.maxX,r.maxY,r.maxZ)*r.triangleCount*this.intersectionCost,minX:r.minX,minY:r.minY,minZ:r.minZ,maxX:r.maxX,maxY:r.maxY,maxZ:r.maxZ}}let r=this.evalTopoRecursive(e[0],t,n),i=this.evalTopoRecursive(e[1],t,n),a=Math.min(r.minX,i.minX),o=Math.min(r.minY,i.minY),s=Math.min(r.minZ,i.minZ),c=Math.max(r.maxX,i.maxX),l=Math.max(r.maxY,i.maxY),u=Math.max(r.maxZ,i.maxZ);return{cost:this.surfaceAreaFlat(a,o,s,c,l,u)*this.traversalCost+r.cost+i.cost,minX:a,minY:o,minZ:s,maxX:c,maxY:l,maxZ:u}}surfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}generatePermutations(e){let t=[],n=Array.from({length:e},(e,t)=>t),r=i=>{if(i===e){t.push([...n]);return}for(let t=i;t<e;t++)[n[i],n[t]]=[n[t],n[i]],r(i+1),[n[i],n[t]]=[n[t],n[i]]};return r(0),t}greedySwapOptimize(e,t,n,r){let i=[...n],a=r,o=!0;for(;o;){o=!1;for(let n=0;n<i.length-1;n++)for(let r=n+1;r<i.length;r++){[i[n],i[r]]=[i[r],i[n]];let s=this.evaluateTopology(e,t,i);s<a?(a=s,o=!0):[i[n],i[r]]=[i[r],i[n]]}}return{perm:i,cost:a}}reconstructTreelet(e,t,n,r){let i=this.buildSubtree(t,n,r);e.minX=i.minX,e.minY=i.minY,e.minZ=i.minZ,e.maxX=i.maxX,e.maxY=i.maxY,e.maxZ=i.maxZ,e.leftChild=i.leftChild,e.rightChild=i.rightChild,e.triangleOffset=i.triangleOffset,e.triangleCount=i.triangleCount}buildSubtree(e,n,r){if(typeof e==`number`){let i=n[r[e]],a=new t;return a.minX=i.minX,a.minY=i.minY,a.minZ=i.minZ,a.maxX=i.maxX,a.maxY=i.maxY,a.maxZ=i.maxZ,a.triangleOffset=i.triangleOffset,a.triangleCount=i.triangleCount,a}let i=this.buildSubtree(e[0],n,r),a=this.buildSubtree(e[1],n,r),o=new t;return o.leftChild=i,o.rightChild=a,o.minX=Math.min(i.minX,a.minX),o.minY=Math.min(i.minY,a.minY),o.minZ=Math.min(i.minZ,a.minZ),o.maxX=Math.max(i.maxX,a.maxX),o.maxY=Math.max(i.maxY,a.maxY),o.maxZ=Math.max(i.maxZ,a.maxZ),o}setTreeletSize(e){this.maxTreeletLeaves=Math.max(3,Math.min(7,e));for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.has(e)||this.topologyCache.set(e,this.generateTopologies(e))}setMinImprovement(e){this.minImprovement=Math.max(.001,e)}getStatistics(){return{...this.stats}}},t=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(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 r={silent:0,error:1,warn:2,info:3,debug:4},i=`info`,a=`rayzeeLogLevel`,o=`rayzeeLogNamespaces`,s=`color:#7c8494`,c=`color:inherit`;let l=null,u=null;function d(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function f(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function p(){if(l!==null)return l;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in r?(l=r[e],l):(l=r[d(a)]??r[i],l)}function m(){if(u!==null)return u;let e=globalThis.__RAYZEE_LOG_NS__??d(o);return u=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],u}function h(e,t){if(t<r.debug)return!0;let n=m();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function g(e,t,n){if(e>p()||!h(t,e))return;let i=e===r.error?console.error:e===r.warn?console.warn:console.log,a=`[${t}]`;typeof n[0]==`string`?i(`%c${a}%c ${n[0]}`,s,c,...n.slice(1)):i(`%c${a}`,s,...n)}const _={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`)=>`${_.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},v={levels:r,setLevel(e){return e in r?(globalThis.__RAYZEE_LOG_LEVEL__=e,l=r[e],f(a,e===i?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(r).join(`, `)}`),this.getLevel())},getLevel(){let e=p();return Object.keys(r).find(t=>r[t]===e)},isEnabled(e){return(r[e]??r.debug)<=p()},only(...e){let t=e.flat().filter(Boolean);return u=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),f(o,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return l=null,u=null,this.getLevel()}};function y(e){return{namespace:e,error:(...t)=>g(r.error,e,t),warn:(...t)=>g(r.warn,e,t),info:(...t)=>g(r.info,e,t),debug:(...t)=>g(r.debug,e,t),isEnabled:e=>v.isEnabled(e),summary(t,n=[]){let i=n.filter(Boolean);if(i.length===0||!console.groupCollapsed){g(r.info,e,[t]),i.forEach(t=>g(r.debug,e,[t]));return}r.info>p()||((p()>=r.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,s,c),i.forEach(e=>console.log(e)),console.groupEnd())}}}const b=1073741824,x=(e,t)=>~(e<<4|t)>>>0;function S(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]===1073741824&&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]>=b||(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]>=b)&&(l[s+3]=C(t,t[o+3],r,i),l[s+7]=C(t,t[o+7],r,i))}return c}function C(e,t,n,r){let i=t*16;return n(t)?x(e[i],e[i+1]):r[t]}const w=y(`bvh`),T=1073741824,E=e=>new Uint32Array(e.buffer,e.byteOffset,e.length),D=1073741824;function O(e,t){if(e>=D)throw RangeError(`${t} is ${e}, at or past the BVH index limit of ${D}`);return e}const k={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8},A=k.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,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0},this.enableTreeletOptimization=!1,this.treeletSize=5,this.treeletOptimizationPasses=1,this.treeletMinImprovement=.02,this.treeletComplexityThreshold=5e4,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)}setTreeletConfig(e){e.enabled!==void 0&&(this.enableTreeletOptimization=e.enabled),e.size!==void 0&&(this.treeletSize=Math.max(3,Math.min(12,e.size))),e.passes!==void 0&&(this.treeletOptimizationPasses=Math.max(1,Math.min(3,e.passes))),e.minImprovement!==void 0&&(this.treeletMinImprovement=Math.max(.001,e.minImprovement)),e.complexityThreshold!==void 0&&(this.treeletComplexityThreshold=e.complexityThreshold)}disableTreeletOptimization(){this.enableTreeletOptimization=!1}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=k.POSITION_A_OFFSET,r=k.POSITION_B_OFFSET,i=k.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?S(i):i,bvhRoot:!0,reorderedTriangles:this.reorderedTriangleData||null,originalToBvh:this.originalToBvhMap||null}}buildSync(t,r=30,i=null,a=null){let o=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,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0,saOrderTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let s=this.totalTriangles,c=performance.now();this.centroids=new Float32Array(s*3),this.bMin=new Float32Array(s*3),this.bMax=new Float32Array(s*3),this.indices=new Uint32Array(s),this.mortonCodes=new Uint32Array(s),this.initializeTriangleArrays(),this.splitStats.initTime=performance.now()-c,this.sortTrianglesByMortonCode();let l=performance.now(),u=this.buildNodeRecursive(0,s,r,i);if(this.splitStats.sahBuildTime=performance.now()-l,this.enableTreeletOptimization&&this.totalTriangles>1e3){let t=this.totalTriangles>this.treeletComplexityThreshold?3:this.treeletSize,n=new e(this.traversalCost,this.intersectionCost);n.setTreeletSize(t),n.setMinImprovement(this.treeletMinImprovement);let r=performance.now();for(let e=0;e<this.treeletOptimizationPasses;e++){let t=i?t=>{i(`Treelet optimization pass ${e+1}/${this.treeletOptimizationPasses}: ${t}`)}:null;try{n.optimizeBVH(u,t)}catch(t){w.error(`treelet optimizer failed in pass ${e+1}:`,t);break}let a=n.getStatistics(),o=performance.now()-r;if(a.treeletsImproved===0&&e>0||o>15e3)break}let a=performance.now()-r;this.splitStats.treeletOptimizationTime=a;let o=n.getStatistics();this.splitStats.treeletsProcessed=o.treeletsProcessed,this.splitStats.treeletsImproved=o.treeletsImproved,this.splitStats.averageSAHImprovement=o.averageSAHImprovement}if(this.enableReinsertionOptimization&&this.totalTriangles>1e3){let e=new n(this.traversalCost,this.intersectionCost);e.setBatchSizeRatio(this.reinsertionBatchSizeRatio),e.setMaxIterations(this.reinsertionMaxIterations);let t=i?e=>{i(e)}:null;try{e.optimizeBVH(u,t)}catch(e){w.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 d=performance.now();this.applySAOrdering(u),this.splitStats.saOrderTime=performance.now()-d;let f=performance.now(),p=this.triangles,m=a||new p.constructor(s*A);for(let e=0;e<s;e++){let t=this.indices[e]*A,n=e*A;m.set(p.subarray(t,t+A),n)}this.reorderedTriangleData=m;let h=new Uint32Array(s);for(let e=0;e<s;e++)h[this.indices[e]]=e;this.originalToBvhMap=h,this.splitStats.reorderTime=performance.now()-f,this.splitStats.totalBuildTime=performance.now()-o;let g=this.splitStats.totalBuildTime,v=this.splitStats;return w.debug(`${_.n(s)} tris → ${_.n(this.totalNodes)} nodes in ${_.ms(g)} | SAH ${v.sahSplits} objMed ${v.objectMedianSplits} spatMed ${v.spatialMedianSplits} failed ${v.failedSplits}`+(v.treeletsProcessed?` | treelets ${v.treeletsImproved}/${v.treeletsProcessed} improved`:``)+(v.reinsertionsApplied?` | reinsertions ${v.reinsertionsApplied}`:``)),i&&i(100),this.centroids=null,this.bMin=null,this.bMax=null,this.mortonCodes=null,u}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)}O(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=E(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]=T}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)}O(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=[],a=E(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]=1073741826,i.push({taskId:t,flatIndex:e})}else a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+3]=T}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;O(a,`assembled BLAS node count`);let o=new Float32Array(a*16),s=E(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]<T&&(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:r,sharedTriangleData:i,sharedCentroids:a,sharedBMin:o,sharedBMax:s,sharedIndices:c,triangleCount:l,maxLeafSize:u,numBins:d,maxBins:f,minBins:p,treeletConfig:m,reinsertionConfig:h,reportProgress:g}=t.data;for(let t=0;t<r.length;t++){let _=r[t];try{let t=new N;t.maxLeafSize=u,t.numBins=d,t.maxBins=f,t.minBins=p,t.triangles=new Float32Array(i),t.centroids=new Float32Array(a),t.bMin=new Float32Array(o),t.bMax=new Float32Array(s),t.indices=new Uint32Array(c),t.totalTriangles=l,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,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,initTime:0,sahBuildTime:0,reorderTime:0};let r=g?e=>{self.postMessage({type:`progress`,taskId:_.taskId,progress:e})}:null,v=performance.now(),y=t.buildNodeRecursive(_.start,_.end,_.depth,r,_.preMinX,_.preMinY,_.preMinZ,_.preMaxX,_.preMaxY,_.preMaxZ);if(m&&m.enabled&&_.end-_.start>1e3){let n=_.end-_.start>5e4,r=n?3:m.size||5,i=n?10:20,a=new e(t.traversalCost,t.intersectionCost);a.setTreeletSize(r),a.setMinImprovement(m.minImprovement||.02),a.setMaxTreelets(i);let o=m.passes||1;for(let e=0;e<o;e++)try{a.optimizeBVH(y,null)}catch(t){console.error(`[BVHSubtreeWorker] Treelet pass ${e+1} error:`,t);break}}if(h&&h.enabled&&_.end-_.start>1e3){let e=new n(t.traversalCost,t.intersectionCost);h.batchSizeRatio&&e.setBatchSizeRatio(h.batchSizeRatio),h.maxIterations&&e.setMaxIterations(h.maxIterations);try{e.optimizeBVH(y,null)}catch(e){console.error(`[BVHSubtreeWorker] Reinsertion error:`,e)}}t.applySAOrdering(y);let b=t.flattenBVH(y),x=b.length/16,S=performance.now()-v;console.log(`[BVHSubtreeWorker] Task ${_.taskId}: ${(_.end-_.start).toLocaleString()} triangles, ${x} nodes, ${Math.round(S)}ms`),self.postMessage({type:`subtreeResult`,taskId:_.taskId,flatData:b,nodeCount:x},[b.buffer])}catch(e){console.error(`[BVHSubtreeWorker] Task ${_.taskId} error:`,e),self.postMessage({type:`error`,taskId:_.taskId,error:e.message})}}};",mm=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,pm],{type:`text/javascript;charset=utf-8`});function hm(e){let t;try{if(t=mm&&(self.URL||self.webkitURL).createObjectURL(mm),!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(pm),{type:`module`,name:e?.name})}}jt(),Rp(()=>ci(fm));var gm=vt(`bvh`),_m=20,vm=5e4,ym=8;function bm(e,t,n,r){let i=e.byteLength/(_m*4),a=Math.min(oi(),ym),o=Math.ceil(Math.log2(a*2.5+1));return gm.debug(`parallel build ${J.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=ci(fm),_=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,gm.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(Sm(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,xm(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,treeletOptimization:r.treeletOptimization})})().catch(e=>{gm.warn(`parallel build setup failed:`,e),c(e)})})}async function xm(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){gm.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}gm.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=ci(hm);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,treeletConfig:g.treeletOptimization,reinsertionConfig:g.reinsertionOptimization,reportProgress:!!l})}}function Sm(e,t,n,r){return new Promise((i,a)=>{(async()=>{let o=ci(fm),s=e.byteLength/(_m*4),c=typeof SharedArrayBuffer<`u`?new SharedArrayBuffer(s*_m*4):null;o.onmessage=e=>{let{bvhData:t,triangles:r,originalToBvh:s,error:l,progress:u,treeletStats: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,treeletOptimization:r.treeletOptimization,reinsertionOptimization:r.reinsertionOptimization,foldLeaves:r.foldLeaves},[l])})().catch(e=>{gm.warn(`single worker fallback failed:`,e),a(e)})})}function Cm(e){return si()&&typeof SharedArrayBuffer<`u`&&e>=vm}var wm=Float64Array.from([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Tm(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 Em(e,t,n){let r=Tm(e,t);if(!Number.isFinite(r)||Math.abs(r)<1e-20)return n.set(wm),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 Dm(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 Om(e){for(let t=0;t<16;t++)if(e[t]!==wm[t])return!1;return!0}function km(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 Am(e,t){for(let n=0;n<16;n++)if(e[t+n]!==wm[n])return!1;return!0}var jm=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(wm,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]=+(Tm(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 Em(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}km(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}km(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||Je(e)[3]===Ke.TRIANGLE_LEAF){Mm(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){Mm(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,Ye(t,`combined TLAS + BLAS node count`)}get totalNodeCount(){return this.tlasNodeCount+this.totalBLASNodes}clear(){this.allocate(0),this.totalBLASNodes=0,this.tlasNodeCount=0}};function Mm(e,t,n,r,i){let a=W.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}var Nm=16,Pm=32,Fm=e=>e<Pm?e:Pm,Im=8,Lm=64,Rm=new Float64Array(16),zm=class e{constructor(){this._flatBuffer=null,this._flatBufferCapacity=0,this._binCounts=new Int32Array(Pm*3),this._binBounds=new Float64Array(Pm*6*3),this._binSuffix=new Float64Array(Pm),this._binSuffixCount=new Int32Array(Pm),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};Ye(r,`TLAS node count`);let i=r*Nm;i>this._flatBufferCapacity&&(this._flatBuffer=new Float32Array(i),this._flatBufferCapacity=i);let a=this._flatBuffer,o=Je(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(Lm);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*Nm;o[e]=0,o[e+1]=s[u],a[e+2]=0,o[e+3]=Ke.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*Nm;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=Je(t);for(let r=0;r<n;r++){let n=r*Nm;if(l[n+3]!==Ke.BLAS_POINTER_LEAF)continue;let u=l[n+1]&Ge;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=Rm;Em(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|(Am(r,i*16)?We: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<=Im)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=Fm(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)}},Bm=W.FLOATS_PER_TRIANGLE*4,Vm=64,Hm=.9,Um=64,Wm=4,Gm=7040*1024*1024,Km=9216*1024*1024;function qm(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}}var Jm=1.15,Ym=12*1024*1024*1024;function Xm({triangles:e,placements:t,geometryBytes:n=0}){let r={triangles:e*Bm,bvh:Math.ceil(e*Hm)*Vm,geometry:n,placements:t*Um,orderMaps:e*Wm};return r.total=r.triangles+r.bvh+r.geometry+r.placements+r.orderMaps,r}function Zm(e,{chunkBytes:t=vn,shared:n=!1,allocate:r=null}={}){let i=Math.min(e,Ym),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 Qm=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()}}},$m="let e,t;const n={MAX_TEXTURE_DIMENSION:8192,CHUNK_SIZE:8,ADAPTIVE_CHUNK_SIZE:!0,MEMORY_SAFETY_FACTOR:.8};let r=null;function i(e){if(e.stream===`begin`){let{width:t,height:n,depth:i}=e;r={width:t,height:n,depth:i,context:new OffscreenCanvas(t,n).getContext(`2d`,{willReadFrequently:!0,alpha:!0,desynchronized:!0}),data:new Uint8Array(t*n*i*4)};return}let{width:t,height:n,depth:i,context:a,data:o}=r;if(e.stream===`layer`){a.clearRect(0,0,t,n),a.drawImage(e.bitmap,0,0),e.bitmap.close(),o.set(a.getImageData(0,0,t,n).data,t*n*4*e.index),self.postMessage({stream:`ack`,index:e.index});return}r=null,self.postMessage({data:o.buffer,width:t,height:n,depth:i},[o.buffer])}async function a({shared:n,width:r,height:i,layers:a}){(e.width!==r||e.height!==i)&&(e.width=r,e.height=i),t.imageSmoothingEnabled=!0,t.imageSmoothingQuality=`high`;let o=new Uint8Array(n),s=r*i*4;for(let{index:e,texture:t}of a)try{await d(t,o,e*s,r,i)}catch(t){console.warn(`Failed to process texture ${e}:`,t),o.fill(0,e*s,(e+1)*s)}}self.onmessage=async function(t){if(t.data.shared){try{e||o(t.data.maxTextureSize),await a(t.data),self.postMessage({done:!0})}catch(e){self.postMessage({error:e.message})}return}if(t.data.stream){try{i(t.data)}catch(e){self.postMessage({error:e.message})}return}let{textures:n,maxTextureSize:r,method:c=`direct-transfer`}=t.data;try{e||o(r);let t=await s(n,r,c);self.postMessage(t,[t.data])}catch(e){console.error(`Worker processing failed:`,e),self.postMessage({error:e.message})}};function o(r){let i=Math.min(r,n.MAX_TEXTURE_DIMENSION);e=new OffscreenCanvas(i,i),t=e.getContext(`2d`,{willReadFrequently:!0,alpha:!0,desynchronized:!0})}async function s(e,t,n){switch(n){case`direct-transfer`:return await m(e,t);case`offscreen-optimized`:return await g(e,t);case`imageBitmap-batch`:return await _(e,t);default:return await m(e,t)}}async function c(e,t,n){let{maxWidth:r,maxHeight:i}=v(e,t),a=e.length,o=l(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 h(e,y(e,t),n)}let d=r*i*o*4,f;try{f=new Uint8Array(d)}catch{return console.warn(`Failed to allocate chunk buffer, reducing dimensions`),await h(e,y(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 u(e.slice(n,s),r,i,f.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 l(e,t,r){if(!n.ADAPTIVE_CHUNK_SIZE)return Math.min(n.CHUNK_SIZE,r);let i=e*t*4/(1024*1024),a;return a=i<=1?16:i<=4?8:i<=16?4:2,Math.min(a,r,n.CHUNK_SIZE*2)}async function u(n,r,i,a){(e.width!==r||e.height!==i)&&(e.width=r,e.height=i);let o=r*i*4;t.imageSmoothingEnabled=!0,t.imageSmoothingQuality=`high`;for(let e=0;e<n.length;e++){let t=n[e];try{await d(t,a,e*o,r,i)}catch(t){console.warn(`Failed to process texture ${e}:`,t);let n=e*o;a.fill(0,n,n+o)}}return{data:a.buffer,width:r,height:i,depth:n.length}}async function d(e,n,r,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`);t.clearRect(0,0,i,a),t.drawImage(o,0,0,i,a);let s=t.getImageData(0,0,i,a);n.set(s.data,r),(e.isImageData||e.isBlob)&&o.close()}async function f(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 f(e,i,a)}return await u(e,t,n,r)}async function p(e,t,n,r,i){await d(e,n,r*i*4*t,r,i)}async function m(n,r){let{maxWidth:i,maxHeight:a}=v(n,r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a);let o=n.length,s;try{s=new Uint8Array(i*a*o*4)}catch(e){return console.error(`Failed to allocate texture array:`,e),await c(n,r,`direct-transfer`)}t.imageSmoothingEnabled=!0,t.imageSmoothingQuality=`high`;for(let e=0;e<n.length;e++){let t=n[e];try{await p(t,e,s,i,a)}catch(t){console.warn(`Failed to process texture ${e}:`,t);let n=i*a*4*e;s.fill(0,n,n+i*a*4)}}return{data:s.buffer,width:i,height:a,depth:o}}async function h(e,t,n){let{maxWidth:r,maxHeight:i}=t;return console.log(`Using reduced dimensions: ${r}x${i}`),await f(e,r,i,n)}async function g(n,r){let{maxWidth:i,maxHeight:a}=v(n,r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a);let o=n.length,s;try{s=new Uint8Array(i*a*o*4)}catch(e){return console.error(`Failed to allocate texture array:`,e),await c(n,r,`offscreen-optimized`)}t.imageSmoothingEnabled=!0,t.imageSmoothingQuality=`high`;for(let e=0;e<n.length;e++){let r=n[e];try{let n;if(r.isBlob){let e=new Blob([r.data]);n=await createImageBitmap(e,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}else{let e=new ImageData(new Uint8ClampedArray(r.data),r.width,r.height);n=await createImageBitmap(e,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}t.clearRect(0,0,i,a),t.drawImage(n,0,0);let o=t.getImageData(0,0,i,a),c=i*a*4*e;s.set(o.data,c),n.close()}catch(t){console.warn(`Failed to process texture ${e}:`,t);let n=i*a*4*e;s.fill(0,n,n+i*a*4)}}return{data:s.buffer,width:i,height:a,depth:o}}async function _(n,r){let{maxWidth:i,maxHeight:a}=v(n,r),o=n.length,s;try{s=new Uint8Array(i*a*o*4)}catch(e){return console.error(`Failed to allocate texture array:`,e),await c(n,r,`imageBitmap-batch`)}let u=Math.min(l(i,a,n.length),n.length);for(let r=0;r<n.length;r+=u){let o=Math.min(r+u,n.length),c=[];for(let e=r;e<o;e++){let t=n[e],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`})}c.push(r.then(t=>({bitmap:t,index:e})))}let l=await Promise.all(c);e.width=i,e.height=a,t.imageSmoothingEnabled=!1;for(let{bitmap:e,index:n}of l){t.clearRect(0,0,i,a),t.drawImage(e,0,0);let r=t.getImageData(0,0,i,a),o=i*a*4*n;s.set(r.data,o),e.close()}}return{data:s.buffer,width:i,height:a,depth:o}}function v(e,t){let r=0,i=0;for(let t of e)r=Math.max(r,t.width||0),i=Math.max(i,t.height||0);let a=Math.min(t,n.MAX_TEXTURE_DIMENSION),o=Math.max(r,i);if(o>a){let e=a/o;r=Math.round(r*e),i=Math.round(i*e)}return r=Math.min(a,Math.max(4,Math.ceil(Math.max(1,r)/64)*64)),{maxWidth:r,maxHeight:Math.max(1,i)}}function y(e,t){let n=v(e,t);return{maxWidth:Math.max(64,Math.ceil(n.maxWidth/128)*64),maxHeight:Math.max(1,Math.floor(n.maxHeight/2))}}",eh=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,$m],{type:`text/javascript;charset=utf-8`});function th(e){let t;try{if(t=eh&&(self.URL||self.webkitURL).createObjectURL(eh),!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($m),{type:`module`,name:e?.name})}}var nh=`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})}};`,rh=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,nh],{type:`text/javascript;charset=utf-8`});function ih(e){let t;try{if(t=rh&&(self.URL||self.webkitURL).createObjectURL(rh),!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(nh),{type:`module`,name:e?.name})}}function ah({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)}}jl();var oh=e=>(t,n,r,i,a)=>e(t>0?t:0,n>0?n:0,r>0?r:0,i,a),sh=new Map;function ch(){sh.clear();for(let e of kl.values())sh.set(e.id,oh(e.cpu))}ch(),fl(ch);function lh(e){return pl(e)?.outputEncoded===!0}function uh(e){return e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055}function dh(e,t){let n=pl(t);return n?n.appliesExposure?e:1:t===r.NoToneMapping?1:e}var fh=.2126,ph=.7152,mh=.0722;function hh(e,t){if(t===1)return;let n=e[0]*fh+e[1]*ph+e[2]*mh;e[0]=n+(e[0]-n)*t,e[1]=n+(e[1]-n)*t,e[2]=n+(e[2]-n)*t}function gh(e,{exposure:t,toneMapping:n,saturation:i=1,preserveAlpha:a=!1}){let o=sh.get(n)??sh.get(r.NoToneMapping),s=dh(t,n),c=lh(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,hh(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]=uh(u[0])*255+.5,l[t+1]=uh(u[1])*255+.5,l[t+2]=uh(u[2])*255+.5),l[t+3]=a?e[t+3]*255+.5:255;return l}jt();var _h=vt(`textures`),vh=8*2**20,yh=16,bh=4,xh=8192*8192,Sh={busy:0,waiting:[]};async function Ch(){return Sh.busy<Math.max(1,oi()-1)?Sh.busy++:await new Promise(e=>Sh.waiting.push(e)),()=>{let e=Sh.waiting.shift();e?e():Sh.busy--}}var wh={toSRGB:null,toLinear:null};function Th(e){if(!wh[e]){let t=new Uint8Array(256);for(let n=0;n<256;n++){let r=n/255,i=e===`toSRGB`?uh(r):r<=.04045?r/12.92:((r+.055)/1.055)**2.4;t[n]=Math.max(0,Math.min(255,Math.round(i*255)))}wh[e]=t}return wh[e]}var Eh=class{constructor(){this.canvasContextPairs=[],this.maxPoolSize=Xe.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=[]}},Dh=class{constructor(e={}){this.pools=new Map,this.memoryUsage=0,this.maxMemoryUsage=e.maxMemory||dt.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*dt.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<Xe.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`}},Oh=class{constructor(e=Xe.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=[]}},kh=class{constructor(e={}){this.useWorkers=typeof Worker<`u`,this.maxConcurrentWorkers=Xe.MAX_CONCURRENT_WORKERS,this.activeWorkers=0,this._issues=e.issues??null,this.maxTextureSize=this._clampTextureSize(e.maxTextureSize??Xe.DEFAULT_MAX_TEXTURE_SIZE),this.canvasPool=new Eh,this.bufferPool=new Dh({maxMemory:e.maxBufferMemory||dt.MAX_BUFFER_MEMORY,sizeStrategy:e.bufferSizeStrategy||`adaptive`}),this.textureCache=new Oh,this.capabilities=this.detectCapabilities(),this.optimalMethod=this.selectOptimalMethod()}_reportTextureFailure(e,t){if(t instanceof gn)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)||Xe.DEFAULT_MAX_TEXTURE_SIZE);return Math.max(Xe.MIN_TEXTURE_WIDTH,Math.min(t,Xe.MAX_TEXTURE_SIZE))}setMaxTextureSize(e){let t=this._clampTextureSize(e);return t===this.maxTextureSize?t:(this.maxTextureSize=t,this.textureCache?.dispose(),this.textureCache=new Oh,this.maxTextureSize)}detectCapabilities(){return{offscreenCanvas:typeof OffscreenCanvas<`u`,imageBitmap:typeof createImageBitmap<`u`,workers:typeof Worker<`u`,hardwareConcurrency:oi()}}selectOptimalMethod(){return this.capabilities.workers&&this.capabilities.offscreenCanvas?`worker-offscreen`:this.capabilities.imageBitmap?`imageBitmap`:`canvas`}_applyColorManagement(e,t,n,i=new Set){let a=Au();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){_h.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,_h.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=Th(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?_h.info(`re-encoded ${l.length}/${o.length} linear-declared colour map(s) to sRGB so the GPU decode round-trips: ${u}`):_h.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=Au()?.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 gn)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>dt.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 th;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)<xh)return 0;let t=this.maxConcurrentWorkers-this.activeWorkers;return Math.max(0,Math.min(e.length,bh,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=ci(th);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=ci(th);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>=dt.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>yh&&(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=si()&&i*t.length>=vh?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)=>ah(e,o,t*i,n,r)),this.createDataArrayTextureFromBuffer(o,n,r,t.length)}async _packInWorker(e,t,n){let r=await Ch(),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=ci(ih),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%dt.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=G.FLOATS_PER_MATERIAL,n=new Float32Array(e.length*t);for(let r=0;r<e.length;r++)mn(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=Xe.VEC4_PER_BVH_NODE*Xe.FLOATS_PER_VEC4;Ye(t.length,`BVH node count`);let i=t.length*r,a=new Float32Array(i),o=Je(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]=Ke.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 Oh;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:Qe(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:Ah(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:Ah(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 Ah(e,t,n){let r=new Uint8ClampedArray(e.buffer,e.byteOffset,e.byteLength);return createImageBitmap(new ImageData(r,t,n))}var jh=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=Nh(E,Mh(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=Nh(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 Mh(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 Nh(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)}}jt();var Ph=Object.freeze({r:0,g:0,b:0});function Fh(e){if(!e)return Ph;if(!zr())return e;let t=[e.r,e.g,e.b];return Vr(t),{r:t[0],g:t[1],b:t[2]}}var Ih=vt(`emissive`),Lh=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=W.FLOATS_PER_TRIANGLE,a=W.MATERIAL_FLAGS_OFFSET,o=W.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]&Le,h=n[p+o],g=t[m];if(!g)continue;let _=d.get(g);_===void 0&&(_=Fh(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),R=(O-T)*(M-E)-(k-E)*(j-T),ee=Math.sqrt(I*I+L*L+R*R)||1,te=g.side===1?-1:1;I=I/ee*te,L=L/ee*te,R=R/ee*te;let ne=g.side===2,z=(T+O+j)/3,B=(E+k+M)/3,re=(D+A+N)/3,ie=Math.min(T,O,j),ae=Math.min(E,k,M),oe=Math.min(D,A,N),se=Math.max(T,O,j),ce=Math.max(E,k,M),le=Math.max(D,A,N);this.emissiveTriangles.push({triangleIndex:e,materialIndex:m,meshIndex:h,sideSign:te,instanceLeaf:n?r.tlasLeafIndex[t]:-1,power:F,area:P,emissive:{r:_.r,g:_.g,b:_.b},emissiveIntensity:v,cx:z,cy:B,cz:re,bMinX:ie,bMinY:ae,bMinZ:oe,bMaxX:se,bMaxY:ce,bMaxZ:le,nx:I,ny:L,nz:R,twoSided:ne}),this.totalEmissivePower+=F}}return this.emissiveCount=this.emissiveTriangles.length,this.emissiveCount>0&&Ih.debug(`${J.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=W.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,Ih.debug(`emissive texture ${J.px(t,n)} · ${J.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 Ih.debug(`emissive raw data ${J.n(this.emissiveCount)} entries (${J.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=Fh(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 jh().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,Ih.debug(`rebuilt sorted emissive data · ${J.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}};jt();var Rh=class{constructor(e=`Build`,{namespace:t=`build`,level:n=`debug`}={}){this.label=e,this.level=n,this.logger=vt(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=J.list([this.label,...e,J.ms(t)]);return this.level===`info`?this.logger.summary(r,n):this.logger.debug(J.list([r,n.join(` · `)])),{steps:Object.fromEntries(this.order.map(e=>[e,Math.round(this.entries.get(e)?.duration??0)])),total:Math.round(t)}}},zh=1<<20,Bh=1<<21,Vh=()=>new Promise(e=>setTimeout(e,0)),Hh=[0,1,2,4,5,6,8,9,10];function Uh(e,t,n,r=Hh){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 Wh(e,t){let n=[],r=0;for(let{triOffset:i,triCount:a}of t)n.push(Uh(e,i,a)),r+=a,r>=Bh&&(r=0,await Vh());return n}async function Gh(e,t){let n=await e?.area(qn.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 Kh(e,t,{index:n,bvh:r,orders:i,isStale:a,label:o=``}){let s=e?.area(qn.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,zh),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+=zh*4)await u.write(`order.u32`,e.subarray(t,Math.min(e.length,t+zh*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 qh(e,t,n,r){for(let i=0;i<r;i+=zh){let a=Math.min(zh,r-i),o=await e.slice(i*64,(i+a)*64).arrayBuffer();t.setRecords(n+i,new Float32Array(o))}}async function Jh(e,t,n){return new Uint32Array(await e.slice(t*4,(t+n)*4).arrayBuffer())}var Yh=16,Xh=W.POSITION_A_OFFSET,Zh=W.POSITION_B_OFFSET,Qh=W.POSITION_C_OFFSET;async function $h(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+Xh]+o[n+Zh]+o[n+Qh],c[r]=o[n+Xh+1]+o[n+Zh+1]+o[n+Qh+1],l[r]=o[n+Xh+2]+o[n+Zh+2]+o[n+Qh+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 tg(u,o,eg(o,e,t),e,t,n),{left:f(e,n),right:f(n,t)}},p=f(0,n);return await i?.(),await ng(e,t,n,u,i),{order:u,pieces:d,tree:p}}function eg(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 tg(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 ng(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 rg(e,t,n,r){let i=t.length-1,a=[],o=i;for(let{bvhData:e}of n)a.push(o),o+=e.length/Yh;let s=new Float32Array(i*Yh),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];Ap(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*Yh;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 ig=`9.4.1`,ag=1e4,og=15e5;function sg(e,t,n=ag){return e>=n&&t/og<e/3}var cg="const e=e=>e>=2147483648,t=e=>~e>>>0>>>4,n=e=>~e&15,r={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},i=r.FLOATS_PER_TRIANGLE,a=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),o=e=>e instanceof Uint32Array?e:new Uint32Array(e.buffer,e.byteOffset,e.length),s=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:e,idx:t?e.viewAs(Uint32Array):o(e)}},c=(e,t)=>e.chunked?e.f.chunkFor(t):e.f,l=(e,t)=>e.chunked?e.idx.chunkFor(t):e.idx,u=(e,t)=>e.chunked?e.chunked.baseOf(t):t*p,d=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:t?t.viewAs(Float32Array):a(e),u:t?e:o(e)}};function f(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 p=16,m=1073741824,h=1073741825;function g(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 _(e,t,n,a,o){let s=r.POSITION_A_OFFSET,c=r.POSITION_B_OFFSET,l=r.POSITION_C_OFFSET,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0;for(let r=0;r<n;r++){let n=t+r,a=e.chunked?e.f.chunkFor(n):e.f,o=e.chunked?e.chunked.baseOf(n):n*i;u=Math.min(u,a[o+s],a[o+c],a[o+l]),d=Math.min(d,a[o+s+1],a[o+c+1],a[o+l+1]),f=Math.min(f,a[o+s+2],a[o+c+2],a[o+l+2]),p=Math.max(p,a[o+s],a[o+c],a[o+l]),m=Math.max(m,a[o+s+1],a[o+c+1],a[o+l+1]),h=Math.max(h,a[o+s+2],a[o+c+2],a[o+l+2])}a[o]=u,a[o+1]=d,a[o+2]=f,a[o+3]=p,a[o+4]=m,a[o+5]=h}const v=new Float32Array(12);function y(e,t,n,r){let i=c(e,t),a=l(e,t),o=u(e,t);if(a[o+3]===m){_(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 b(r,i,a,o,s){let d=c(r,i),f=l(r,i),p=u(r,i),y=(i-s)*6,b=f[p+3];if(b===m){_(a,f[p],f[p+1],o,y);return}if(b===h){g(d,p,o,(f[p]-s)*6,o,y);return}let x=f[p+7],S=o,C=(b-s)*6;e(b)&&(_(a,t(b),n(b),v,0),S=v,C=0);let w=o,T=(x-s)*6;e(x)&&(_(a,t(x),n(x),v,6),w=v,T=6),d[p]=S[C],d[p+1]=S[C+1],d[p+2]=S[C+2],d[p+4]=S[C+3],d[p+5]=S[C+4],d[p+6]=S[C+5],d[p+8]=w[T],d[p+9]=w[T+1],d[p+10]=w[T+2],d[p+12]=w[T+3],d[p+13]=w[T+4],d[p+14]=w[T+5];for(let e=0;e<3;e++)o[y+e]=Math.min(S[C+e],w[T+e]),o[y+3+e]=Math.max(S[C+3+e],w[T+3+e])}var x=class{constructor(){this._bounds=null,this._boundsNodeCount=0,this._tlasBounds=null,this._rootBox=null}updateTrianglePositions(e,t,n){let a=n.length,o=d(e);for(let e=0;e<a;e++){let a=n[e],s=o.chunked?o.f.chunkFor(e):o.f,c=o.chunked?o.u.chunkFor(e):o.u,l=o.chunked?o.chunked.baseOf(e):e*i,u=a*9,d=t[u],p=t[u+1],m=t[u+2],h=t[u+3],g=t[u+4],_=t[u+5],v=t[u+6],y=t[u+7],b=t[u+8];s[l+r.POSITION_A_OFFSET]=d,s[l+r.POSITION_A_OFFSET+1]=p,s[l+r.POSITION_A_OFFSET+2]=m,s[l+r.POSITION_B_OFFSET]=h,s[l+r.POSITION_B_OFFSET+1]=g,s[l+r.POSITION_B_OFFSET+2]=_,s[l+r.POSITION_C_OFFSET]=v,s[l+r.POSITION_C_OFFSET+1]=y,s[l+r.POSITION_C_OFFSET+2]=b;let x=h-d,S=g-p,C=_-m,w=v-d,T=y-p,E=b-m,D=f(S*E-C*T,C*w-x*E,x*T-S*w);c[l+r.NORMAL_A_PACKED_OFFSET]=D,c[l+r.NORMAL_B_PACKED_OFFSET]=D,c[l+r.NORMAL_C_PACKED_OFFSET]=D}}refitRange(e,t,n,r){let i=d(t);r>this._boundsNodeCount&&(this._bounds=new Float32Array(r*6),this._boundsNodeCount=r);let a=s(e);for(let e=n+r-1;e>=n;e--)b(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=d(t),a=s(e);(!this._tlasBounds||this._tlasBounds.length<r*6)&&(this._tlasBounds=new Float32Array(r*6));let o=this._tlasBounds,f=this._rootBox||=new Float32Array(6);for(let e=r-1;e>=0;e--){let t=l(a,e),n=u(a,e);t[n+3]===h?(y(a,t[n],i,f),g(c(a,e),n,f,0,o,e*6)):b(a,e,i,o,0)}}refit(e,t,n){let r=d(t);n!==this._boundsNodeCount&&(this._bounds=new Float32Array(n*6),this._boundsNodeCount=n);let i=s(e);for(let e=n-1;e>=0;e--)b(i,e,r,this._bounds,0)}};const S=64*1024*1024;function C(e,t,n){return n?new e(new SharedArrayBuffer(t*e.BYTES_PER_ELEMENT)):new e(t)}var w=class e{constructor(e,t,n,r=S,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(C(n,e*t,i)),s-=e}this.chunks.length===0&&this.chunks.push(C(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=S,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]=C(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=C(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=C(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 T=new x;let E=null,D=null,O=0;self.onmessage=function(e){let{type:t}=e.data;if(t===`init`){E=w.adopt(e.data.sharedBvhBufs.map(e=>new Float32Array(e)),e.data.bvhRecordCount,16,e.data.bvhRecordsPerChunk),D=w.adopt(e.data.sharedTriBufs.map(e=>new Uint32Array(e)),e.data.triRecordCount,e.data.triLanesPerRecord,e.data.triRecordsPerChunk),O=E.recordCount;return}if(t===`refit`)try{let t=performance.now(),{blasRanges:n,tlasNodeCount:r}=e.data;n?T.refitPartial(E,D,n,r):T.refit(E,D,O),self.postMessage({type:`refitComplete`,refitTimeMs:performance.now()-t})}catch(e){console.error(`[BVHRefitWorker] Refit error:`,e),self.postMessage({type:`error`,error:e.message})}};",lg=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,cg],{type:`text/javascript;charset=utf-8`});function ug(e){let t;try{if(t=lg&&(self.URL||self.webkitURL).createObjectURL(lg),!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(cg),{type:`module`,name:e?.name})}}var dg="const e=Math.PI/180;function t(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 n({hours:n,dayOfYear:r,latitude:i}){let a=t(r),o=(n-12)*15*e,s=i*e,c=Math.sin(s)*Math.sin(a)+Math.cos(s)*Math.cos(a)*Math.cos(o),l=Math.asin(Math.min(1,Math.max(-1,c)))/e;return{azimuth:(Math.atan2(Math.sin(o),Math.cos(o)*Math.sin(s)-Math.tan(a)*Math.cos(s))/e+540)%360,elevation:l}}const r=e=>[0,31,59,90,120,151,181,212,243,273,304,334][e-1]+21,i=Object.freeze({time:10,month:3,latitude:40}),a=n({hours:i.time,dayOfYear:r(i.month),latitude:i.latitude}),o=Object.freeze({viewer:Object.freeze({areaLightIntensityScale:.1,environmentRotation:0,toneMapping:6,saturation:1,dofMode:`look`}),physical:Object.freeze({areaLightIntensityScale:1,environmentRotation:0,toneMapping:6,saturation:1,dofMode:`physical`})}),s={resolution:512,canvasWidth:512,canvasHeight:512,maxTextureSize:4096,toneMapping:o.viewer.toneMapping,exposure:1,saturation:o.viewer.saturation,enableEnvironment:!0,showBackground:!0,transparentBackground:!1,environmentIntensity:1,backgroundIntensity:1,backgroundColor:`#000000`,backgroundBlurriness:0,backgroundBlurSamples:8,environmentRotation:o.viewer.environmentRotation,groundProjectionEnabled:!1,groundProjectionRadius:100,groundProjectionHeight:15,groundProjectionLevel:0,enableGroundCatcher:!1,groundCatcherHeight:0,globalIlluminationIntensity:1,environmentMode:`hdri`,gradientZenithColor:`#0077BE`,gradientHorizonColor:`#87CEEB`,gradientGroundColor:`#654321`,solidSkyColor:`#87CEEB`,skySunAzimuth:180-a.azimuth,skySunElevation:a.elevation,skySunStrength:1,skySunSize:.53,skyTurbidity:2,skyOzone:300,skyAirDensity:1,skyGroundAlbedo:`#959595`,skyAltitude:50,skyPreset:`clearDay`,cameraProjection:`perspective`,panoramaLonRange:[-180,180],panoramaLatRange:[-90,90],panoramaLevelHorizon:!0,enableDOF:!1,fov:55,focusDistance:.8,aperture:5.6,focalLength:50,apertureScale:1,anamorphicRatio:1,unitsPerMetre:1,dofMode:o.viewer.dofMode,dofBlur:.05,autoFocusMode:`auto`,afScreenPoint:{x:.5,y:.5},afSmoothingFactor:.15,enablePathTracer:!0,enableAccumulation:!0,pauseRendering:!1,maxSamples:60,bounces:3,transmissiveBounces:5,maxSubsurfaceSteps:8,maxTransparentBounces:32,useAdaptiveSampling:!0,noiseThreshold:.1,adaptiveMinSamples:8,adaptiveStopFraction:.9,usePixelFreeze:!0,pixelFreezeThreshold:.02,pixelFreezeStability:8,convergenceOverlay:!1,samplingTechnique:2,enableEmissiveTriangleSampling:!1,emissiveBoost:1,fireflyThreshold:3,shadowTerminatorOffset:.1,wavefrontSortMaterials:!0,renderLimitMode:`frames`,renderTimeLimit:30,renderMode:0,enableAlphaShadows:!1,tilesHelper:!0,showLightHelper:!1,directionalLightIntensity:0,directionalLightColor:`#ffffff`,directionalLightPosition:[1,1,1],directionalLightAngle:0,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,debugMode:0,debugThreshold:100,debugModel:0,enableBloom:!1,bloomStrength:.2,bloomRadius:.15,bloomThreshold:.85,interactionModeEnabled:!0,interactionRenderScale:.5,debugVisScale:100,denoiserStrategy:`none`,enableASVGF:!1,asvgfTemporalAlpha:.1,asvgfAtrousIterations:8,asvgfPhiColor:10,asvgfPhiNormal:128,asvgfPhiDepth:1,asvgfVarianceBoost:1,asvgfMaxAccumFrames:32,asvgfGradientStrength:1,asvgfGradientSigmaScale:2,asvgfGradientNoiseFloor:0,asvgfDebugMode:0,asvgfQualityPreset:`medium`,showAsvgfHeatmap:!1,nrdQualityPreset:`medium`,nrdDebugMode:0,autoExposure:!1,autoExposureKeyValue:.18,autoExposureMinExposure:.1,autoExposureMaxExposure:20,autoExposureAdaptSpeedBright:3,autoExposureAdaptSpeedDark:.5};Object.freeze({perspective:0,equirectangular:1,orthographic:2}),s.fov,s.focusDistance,s.aperture,s.focalLength,180-a.azimuth,a.elevation,c({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});function c(e){for(let t of Object.values(e))typeof t==`object`&&Object.freeze(t);return Object.freeze(e)}const l={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826};function u(e){return new Uint32Array(e.buffer,e.byteOffset,e.length)}function d(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}Math.min(typeof navigator<`u`&&navigator.hardwareConcurrency||4,6),s.maxSamples,s.bounces,s.renderMode,s.enableAlphaShadows,s.maxSubsurfaceSteps;const f=Float64Array.from([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function p(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 m(e,t,n){let r=p(e,t);if(!Number.isFinite(r)||Math.abs(r)<1e-20)return n.set(f),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 h(e,t){for(let n=0;n<16;n++)if(e[t+n]!==f[n])return!1;return!0}const g=e=>e<32?e:32,_=new Float64Array(16);var v=class e{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(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};d(r,`TLAS node count`);let i=r*16;i>this._flatBufferCapacity&&(this._flatBuffer=new Float32Array(i),this._flatBufferCapacity=i);let a=this._flatBuffer,o=u(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(64);let c=0,f=0,p=0,m=n,h=this._bounds;this._rangeBounds(t,s,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 e=f*16;o[e]=0,o[e+1]=s[p],a[e+2]=0,o[e+3]=l.BLAS_POINTER_LEAF}else{let e=this._partition(t,s,p,m,g,_,v,y,b,x),n=e-p,r=f+1,i=r+(n*2-1),l=f*16;a[l]=h[0],a[l+1]=h[1],a[l+2]=h[2],o[l+3]=r,a[l+4]=h[3],a[l+5]=h[4],a[l+6]=h[5],o[l+7]=i,a[l+8]=h[6],a[l+9]=h[7],a[l+10]=h[8],a[l+11]=0,a[l+12]=h[9],a[l+13]=h[10],a[l+14]=h[11],a[l+15]=0;let u=n<=m-e,d=u?0:6,S=u?6:0;c=this._push(c,u?i:r,u?e:p,u?m:e,h,S),f=u?r:i,u?m=e:p=e,g=h[d],_=h[d+1],v=h[d+2],y=h[d+3],b=h[d+4],x=h[d+5];continue}if(c===0)break;c--;let e=c*3,n=c*6;f=this._stackI[e],p=this._stackI[e+1],m=this._stackI[e+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: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,d=u(t);for(let r=0;r<n;r++){let n=r*16;if(d[n+3]!==l.BLAS_POINTER_LEAF)continue;let u=d[n+1]&1073741823;d[n]=o[a[u]],t[n+2]=+!!s[u],e.writeLeafMatrix(t,d,n,i,u),c[u]=r}}static writeLeafMatrix(e,t,n,r,i){let a=_;m(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|(h(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,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,_=-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>_&&(_=o)}let v=this._extent,y=this._cMin;v[0]=m-d,v[1]=h-f,v[2]=_-p,y[0]=d,y[1]=f,y[2]=p;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=g(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,d=0;for(let e=O-1;e>=1;e--){let u=(t+e)*6;w[u]<i&&(i=w[u]),w[u+1]<a&&(a=w[u+1]),w[u+2]<o&&(o=w[u+2]),w[u+3]>s&&(s=w[u+3]),w[u+4]>c&&(c=w[u+4]),w[u+5]>l&&(l=w[u+5]),d+=C[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,_=-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])/u;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 y={silent:0,error:1,warn:2,info:3,debug:4},b=`info`,x=`rayzeeLogLevel`,S=`rayzeeLogNamespaces`,C=`color:#7c8494`,w=`color:inherit`;let T=null,E=null;function D(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function O(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function k(){if(T!==null)return T;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in y?(T=y[e],T):(T=y[D(x)]??y[b],T)}function A(){if(E!==null)return E;let e=globalThis.__RAYZEE_LOG_NS__??D(S);return E=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],E}function j(e,t){if(t<y.debug)return!0;let n=A();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function M(e,t,n){if(e>k()||!j(t,e))return;let r=e===y.error?console.error:e===y.warn?console.warn:console.log,i=`[${t}]`;typeof n[0]==`string`?r(`%c${i}%c ${n[0]}`,C,w,...n.slice(1)):r(`%c${i}`,C,...n)}const N={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`)=>`${N.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},P={levels:y,setLevel(e){return e in y?(globalThis.__RAYZEE_LOG_LEVEL__=e,T=y[e],O(x,e===b?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(y).join(`, `)}`),this.getLevel())},getLevel(){let e=k();return Object.keys(y).find(t=>y[t]===e)},isEnabled(e){return(y[e]??y.debug)<=k()},only(...e){let t=e.flat().filter(Boolean);return E=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),O(S,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return T=null,E=null,this.getLevel()}};function F(e){return{namespace:e,error:(...t)=>M(y.error,e,t),warn:(...t)=>M(y.warn,e,t),info:(...t)=>M(y.info,e,t),debug:(...t)=>M(y.debug,e,t),isEnabled:e=>P.isEnabled(e),summary(t,n=[]){let r=n.filter(Boolean);if(r.length===0||!console.groupCollapsed){M(y.info,e,[t]),r.forEach(t=>M(y.debug,e,[t]));return}y.info>k()||((k()>=y.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,C,w),r.forEach(e=>console.log(e)),console.groupEnd())}}}function I(e){e&&e in y&&(globalThis.__RAYZEE_LOG_LEVEL__=e,T=y[e])}const L=F(`bvh`);self.onmessage=function(e){let{aabbs:t,count:n,logLevel:r}=e.data;I(r);try{let e=performance.now(),{data:r,nodeCount:i}=new v().buildStructure(new Float64Array(t),n);L.debug(`TLAS ${N.n(i)} nodes in ${N.ms(performance.now()-e)}`),self.postMessage({tlasData:r,nodeCount:i},[r.buffer])}catch(e){L.error(`TLAS build failed:`,e),self.postMessage({error:e.message})}};",fg=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,dg],{type:`text/javascript;charset=utf-8`});function pg(e){let t;try{if(t=fg&&(self.URL||self.webkitURL).createObjectURL(fg),!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(dg),{type:`module`,name:e?.name})}}jt(),$s();var mg=5e4,hg=2e5,gg=2e6,_g=1<<19,vg=4e7,yg=1.5*1024**3,bg=256*1024*1024,xg=vt(`scene`),Sg=e=>Array.isArray(e)?e:[e],Cg=e=>Sg(e).reduce((e,t)=>e+t.byteLength,0),wg=64*1024*1024;async function Tg(e,t,n){for(let r of Sg(n))await e.writeAt(t,r),t+=r.byteLength}function Eg(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 Dg=class{constructor(e={}){this.config={useWorkers:!0,bvhDepth:30,maxLeafSize:4,verbose:!1,useFloat32Array:!0,textureQuality:`adaptive`,maxTextureSize:Xe.DEFAULT_MAX_TEXTURE_SIZE,enableTextureCache:!0,maxConcurrentTextureTasks:Math.min(oi(),6),maxSceneBytes:Km,enableTreeletOptimization:!1,treeletSize:7,treeletOptimizationPasses:1,treeletMinImprovement:.01,treeletComplexityThreshold:5e4,sceneCache:!0,sceneCacheMinBuildMs:ag,...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.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 Qm,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 Fr({issues:this.config.issues}),this.bvhBuilder=new Up,this.bvhBuilder.maxLeafSize=this.config.maxLeafSize,this.bvhBuilder.setTreeletConfig({enabled:this.config.enableTreeletOptimization,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold}),this.textureCreator=new kh({maxTextureSize:this.config.maxTextureSize,issues:this.config.issues}),this.emissiveTriangleBuilder=new Lh,this.tlasBuilder=new zm,this._tlasWorker=null,this._tlasWorkerFailed=!1}_log(e,t){t===void 0?xg.debug(e):xg.debug(e,t)}_preflightMemory(e){let t=this.config.maxSceneBytes??9663676416,n=this.geometryExtractor.surveyScene(e),r=Xm(n);if(this._progressive&&(r.total-=r.bvh),this._streaming){let t=yg+Eg(e)*(W.FLOATS_PER_TRIANGLE*4+44);r.total-=Math.max(0,r.triangles-t)}let i={...n,estimate:r,safeBytes:Gm,maxBytes:t,fits:r.total<=Gm};if(this.memoryPreflight=i,r.total<1610612736)return i;if(xg.debug(J.list([`memory preflight: ${J.mb(r.total)} estimated`,`triangles ${J.mb(r.triangles)} · bvh ${J.mb(r.bvh)} · geometry ${J.mb(r.geometry)}`,`${J.n(n.triangles)} tris · ${J.n(n.placements)} placements`])),r.total>t){let e=`Scene needs about ${J.mb(r.total)} of CPU memory, past the ${J.mb(t)} a browser tab can hold — loading it would crash the tab rather than fail. Reduce the scene (it has ${J.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 ${J.mb(r.total)} of CPU memory, above the ${J.mb(Gm)} 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:Gm}),i}_checkAssemblyHeadroom(e){let t=e*64;if(t<1610612736)return!0;let n=Zm(Math.ceil(t*Jm),{shared:yn});return this.memoryPreflight&&(this.memoryPreflight.assemblyProbed=n.placed),n.exhausted&&this.config.issues?.warn(Y.SCENE_MEMORY_BUDGET,`BVH assembly needs ${J.mb(t)} but only ${J.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?Cg(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} ${J.mb(n[e].allocated)}`),i=this.memoryPreflight?.estimate?.total;xg.debug(J.list([`memory: peak live ${J.mb(t)}`,`allocated ${J.mb(e)}`,i?`predicted ${J.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,xn(e=>this.memory.alloc(e));let r=new Rh(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/(W.FLOATS_PER_TRIANGLE*4)),this._foldLeaves=i>vg,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=kr(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=>xg.debug(`storing BLASes failed:`,e))),this}catch(e){throw this.processingStage=`error`,xg.error(`processing failed:`,e),z({status:`Error: ${e.message}`,failed:!0,progress:100}),e}finally{this._disposeGeometrySpill(),xn(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 xg.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=Cn.lazy(o,W.FLOATS_PER_TRIANGLE,Uint32Array),c=s.recordsPerChunk*s.lanesPerRecord*4,l=await mr.create(r,`${a}:tri`,c,{label:`Triangle records`,expectedBytes:o*c/s.recordsPerChunk}),u=l&&await mr.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 br.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);jm.rootAABB(Sg(r)[0],v,t.start,t.count,i,0),p.set(e,{result:n,aabb:i});let a=f.blasBytes;f.blasBytes+=Cg(r),f.blasAt.set(e,a),n.nodeCount=Cg(r)/64,n.bvhData=null,this._queueSpill(f,()=>Tg(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>bg&&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>yg&&(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),xg.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=Ye(e.triangleCount,`triangle count`),this._foldLeaves&&this.triangleCount>134217728)throw RangeError(`${this.triangleCount.toLocaleString()} triangles is past the ${qe.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.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 jm,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(_,zm.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,treeletsImproved:0,treeletsProcessed: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,T.treeletsImproved+=i.treeletsImproved??0,T.treeletsProcessed+=i.treeletsProcessed??0,this.performanceMetrics.blasWorkerTime+=i.totalBuildTime??0),this.instanceTable.setEntry({meshIndex:e,blasNodeCount:r.nodeCount??Cg(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(zm.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(Cn.lazy(O,16,Float32Array,void 0,yn));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 qh(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 Sg(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;xg.debug(J.list([`${J.n(D.setCount)} BLASes + TLAS`,`${J.n(this.bvh.recordCount)} nodes`,`SAH ${J.n(T.sah)} · objMed ${T.objMed} · spatMed ${T.spatMed} · failed ${T.failed}`,T.treeletsProcessed?`treelets ${T.treeletsImproved}/${T.treeletsProcessed} improved`:null,J.ms(N)])),z({status:`BVH construction complete`,progress:75})}catch(e){throw xg.error(`BVH build failed:`,e),z({status:`BVH error: ${e.message}`,failed:!0,progress:75}),e}}_blasWorkerOpts(){return{depth:this.config.bvhDepth,treeletOptimization:{enabled:this.config.enableTreeletOptimization!==!1,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold},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:bt()}}_isLargeMesh(e){return e.count>=hg&&Cm(e.count)}async _buildLargeBLAS(e,t){if(e.count>gg)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 bm(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 $h(n,e.start,e.count,_g,{pause:()=>new Promise(e=>setTimeout(e,0))}),o=this._blasPool(t,null,null,Math.min(oi(),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),jm.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{...rg(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:${ig}:${JSON.stringify(t)}:${n}:${this._sceneKey}`}async _restoreBLASes(e,t,n){if(!this._sceneKey||this.config.sceneCache===!1)return null;let r=zu(Xs().cacheNamespace);if(!r)return null;this._blasKey=this._blasCacheKey(n);let i=await Gh(r,this._blasKey);if(!i)return null;let a=e=>(xg.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 Wh(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 Jh(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},xg.debug(`restored ${J.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=zu(Xs().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 Wh(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 Kh(t,r,{index:{v:2,tlasNodeCount:n.tlasNodeCount,totalNodes:n.totalNodeCount,templates:d},bvh:this.bvh,orders:u,isStale:a,label:e});return f&&xg.debug(`stored ${J.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 mr.create(t,`${i}:tri`,a,{label:`Triangle records`,expectedBytes:r.byteLength}),s=o&&await mr.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(Sg(a)[0],t,this.triangles,i.tplObjectAABB,t*6);let o=e.blasBytes;e.blasBytes+=Cg(a),e.blasAt.set(t,o),r.nodeCount=Cg(a)/64,r.bvhData=null,this._queueSpill(e,()=>Tg(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=W.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+=wg)i.push(new Float32Array(await e.blasStore.readAt(n+t,Math.min(wg,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 mr.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);Ap(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,o=i<=500?{...e.treeletOptimization,enabled:!1}:e.treeletOptimization;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,treeletOptimization:o,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.treeletStats||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=ci(fm);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 xg.error(`texture creation failed:`,e),e}}_bucketTextures(){let e=this.config.maxTextureSize,t=Xe.MATERIAL_BUCKET_COUNT,n=Xe.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],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],o=it(r(i),e,t),s=it(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=at(e.image.width,e.image.height,a),s=e.source?.uuid??e.uuid,c=r[o].get(s);if(c!==void 0)return ot(o,c);if(t[o].length>=n)return xg.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=ot(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)}}}_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)}_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.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){xg.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 xg.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.bvhBuilder.setTreeletConfig({enabled:this.config.enableTreeletOptimization,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold})),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=Cn.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||=ci(ug),!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=W.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 lm;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?(Dm(s,c,e*16,r),n.setPlacementMatrix(t,r)):l?(Dm(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||zm.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=W.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)):xg.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):(xg.error(`failed to get BVH data`),!1)):(xg.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 mr.create(e,`${a}:tri`,o(t),{label:`Triangle records`,expectedBytes:t.byteLength}),c=s&&await mr.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 xg.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=kr(e),xg.info(`read ${J.mb(r)} of scene geometry back from disk in ${J.ms(performance.now()-n)}`),t.error&&xg.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>=mg&&!this._tlasWorkerFailed)try{let n=new Float64Array(t*6);e.writeWorldAABBs(n);let{tlasData:r,nodeCount:i}=await this._runTLASWorker(n,t);return zm.fillLeaves(r,i,e),r}catch(e){this._tlasWorkerFailed=!0,xg.warn(`TLAS worker unavailable (${e.message}); building on the main thread`)}return this.tlasBuilder.build(e).data}_runTLASWorker(e,t){this._tlasWorker||=ci(pg);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:bt()},[e.buffer])})}_setBVHData(e){this._tlasLeafBoxesOf=null;let t=e?e instanceof Cn?e:Cn.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=W.FLOATS_PER_TRIANGLE,n=e?e instanceof Cn?e:Cn.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=W.POSITION_A_OFFSET,r=W.POSITION_B_OFFSET,i=W.POSITION_C_OFFSET,a=W.NORMAL_A_PACKED_OFFSET,o=W.NORMAL_B_PACKED_OFFSET,s=W.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=Om(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=Be(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=W.NORMAL_A_PACKED_OFFSET,o=W.NORMAL_B_PACKED_OFFSET,s=W.NORMAL_C_PACKED_OFFSET,c=r,l=!c||Om(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]]=Be(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===Ke.BLAS_POINTER_LEAF){let a=t[o+1]&Ge;a<n.count&&!(r&&!e[a])&&n.writeWorldAABB(a,this._tlasBounds,i*6)}else if(s<Ke.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){xg.error(`background BLAS rebuild failed (mesh ${e}):`,o.error);return}n===this._rebuildGeneration&&this._swapBLAS(e,r,o,t)},i.onerror=t=>{xg.error(`background BLAS rebuild worker failed (mesh ${e}):`,t),i.terminate(),this._pendingRebuilds.delete(e)};let o=r.triCount>500;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,treeletOptimization:{enabled:o,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold},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,ci(fm))}}_swapBLAS(e,t,n,r){this._geometryVersion=(this._geometryVersion??0)+1;let i=n.bvhData,a=i.length/16;if(a>t.blasNodeCount){xg.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}},Og=[[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]],kg=[[-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]],Ag=[[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 jg(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=Og[i],o=kg[i],s=Ag[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)]}var Mg=1/(4*Math.PI);function Ng(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]=jg(t.temperature??6500);i[0]*=e,i[1]*=n,i[2]*=r}return Vr(i),{r:i[0],g:i[1],b:i[2],intensity:r}}var Pg=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=Ng(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=Ng(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=Ng(e);this.pointLightCache.push({data:[t.x,t.y,t.z,i.r,i.g,i.b,i.intensity*Mg,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=Ng(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*Mg,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}))}}};jt();var Fg=1<<18,Ig=vt(`pathtracer`),Lg=100,Rg=4,zg=class extends P{constructor(e,t,n,i={}){super(`PathTracer`,{...i,executionMode:N.ALWAYS});let a=i.width||1920,o=i.height||1080;this.camera=n,this.width=a,this.height=o,this.renderer=e,this.scene=t,this.sdfs=new Dg,this.lightSerializer=new Pg,this.accumulationEnabled=!0,this.isComplete=!1,this.cameras=[],this.performanceMonitor=fe(),this.completionThreshold=0,this.renderLimitMode=`frames`,this._initDataTextures(),this.storageTextures=new Ft(0,0),this.uniforms=new on(a,o),this._defineUniformGetters(),this.materialData=new $r(this.sdfs),this.materialData.callbacks.onReset=()=>this.reset(),this.materialData.callbacks.getTriangleData=()=>({array:this._triangleFlat,records:this._triangleRecords,count:this.triangleCount}),this.materialData.callbacks.onTriangleDataChanged=()=>{this.triangleShadeAttr&&this._uploadTriangles(0,this._triangleRecordCount,{geo:!1})},this.environment=new Qu(this.scene,this.uniforms,this.renderer),this.environment.callbacks.onReset=()=>this.reset(),this.environment.callbacks.getSceneTextureNodes=()=>this.shaderBuilder.getSceneTextureNodes(),this.shaderBuilder=new mp,this._initRenderingState(),this.tempVector2=new r.Vector2,this.lastCameraMatrix=new r.Matrix4,this.lastProjectionMatrix=new r.Matrix4,this._seedTick=0,this._pinSeedToFrame=!1,this.tracedFrames=0,this.resetCount=0,this.lastRenderMode=-1,this.renderModeChangeTimeout=null,this.renderModeChangeDelay=50,this.pendingRenderMode=null,this.lastInteractionModeState=!1,this.cameraChanged=!1,this._lastViewChangeAt=-1/0,this.updateCompletionThreshold()}_initDataTextures(){this.triangleGeoAttr=null,this.triangleShadeAttr=null,this._triangleRecords=null,this._triangleFlat=null,this._triangleRecordCount=0,this.triangleStorageNode=null,this.triangleCount=0,this.bvhStorageAttr=null,this._bvhRecords=null,this.bvhStorageNode=null,this.bvhNodeCount=0,this.directionalLightsData=null,this.pointLightsData=null,this.spotLightsData=null,this.areaLightsData=null,this.goboMaps=null,this.iesProfiles=null,this.blueNoiseReady=Promise.resolve(),this.lightStorageAttr=new t.StorageInstancedBufferAttribute(new Float32Array(16),4),this.lightStorageNode=(0,n.storage)(this.lightStorageAttr,`vec4`,1).toReadOnly(),this._lightBufferRealloc=!1,this._lbvhDataCache=null,this._emissiveDataCache=null,this._bitTrailMapCache=null,this._bitTrailOffset=0,this._bitTrailLength=0,this._instanceTable=null,this.spheres=[]}_defineUniformGetters(){let e=this.uniforms;for(let t of e.keys())Object.defineProperty(this,t,{get:()=>e.get(t),configurable:!0});let t=e.getLightBufferNodes();for(let[e,n]of Object.entries(t))Object.defineProperty(this,`${e}LightsBufferNode`,{get:()=>n,configurable:!0})}_initRenderingState(){this.isReady=!1,this.frameCount=0}_initCameraOptimizer(){let e=this;this.cameraOptimizer=new F(this.renderer,{uniforms:{enableAccumulation:{get value(){return e.enableAccumulation.value},set value(t){e.enableAccumulation.value=t}},fireflyThreshold:{get value(){return e.fireflyThreshold.value},set value(t){e.fireflyThreshold.value=t}},cameraIsMoving:{get value(){return e.cameraIsMoving.value},set value(t){e.cameraIsMoving.value=t}}}},{enabled:V.interactionModeEnabled,qualitySettings:{enableAccumulation:!1,fireflyThreshold:e=>e*8},onEnter:()=>this.emit(`pathtracer:interactionStart`),onExit:()=>this.emit(`pathtracer:interactionEnd`),onReset:()=>{this.reset(),this.emit(`pathtracer:viewpointChanged`)}})}setupEventListeners(){this.on(`pipeline:reset`,()=>{this.reset()}),this.on(`pipeline:resize`,e=>{e&&e.width&&e.height&&this.setSize(e.width,e.height)}),this.on(`pathtracer:setCompletionThreshold`,e=>{e&&e.threshold!==void 0&&(this.completionThreshold=e.threshold)})}async build(e){this.dispose(),this.scene=e,await this.sdfs.buildBVH(e),this.cameras=this.sdfs.cameras,this.updateSceneUniforms(),this.updateLights(),this._initCameraOptimizer(),this.setupMaterial()}updateSceneUniforms(){this.setTriangleData(this.sdfs.triangleData,this.sdfs.triangleCount),this.setBVHData(this.sdfs.bvhData),this.setInstanceTable(this.sdfs.instanceTable),this.materialData.setMaterialData(this.sdfs.materialData,this.sdfs.materials?.map(e=>e.sources)),this.materialData.loadTexturesFromSdfs(),this.sdfs.emissiveTriangleData?this.setEmissiveTriangleData(this.sdfs.emissiveTriangleData,this.sdfs.emissiveTriangleCount||0):this.emissiveTriangleCount.value=0,this.sdfs.lightBVHNodeData?this.setLightBVHData(this.sdfs.lightBVHNodeData,this.sdfs.lightBVHNodeCount||0):this.lightBVHNodeCount.value=0,this._meshRefs=this._collectMeshRefs(this.scene),this.setMeshVisibilityData(this._meshRefs),this.spheres=this.sdfs.spheres||[]}updateLights(){let e={uniforms:{directionalLights:{value:null},pointLights:{value:null},spotLights:{value:null},areaLights:{value:null}},defines:{}};this.lightSerializer.processSceneLights(this.scene,e),this.directionalLightsData=e.uniforms.directionalLights.value,this.pointLightsData=e.uniforms.pointLights.value,this.spotLightsData=e.uniforms.spotLights.value,this.areaLightsData=e.uniforms.areaLights.value,this._updateLightBufferNodes()}_updateLightBufferNodes(){this._writeLightList(`directional`,this.directionalLightsData,this.numDirectionalLights),this._writeLightList(`area`,this.areaLightsData,this.numAreaLights),this._writeLightList(`point`,this.pointLightsData,this.numPointLights),this._writeLightList(`spot`,this.spotLightsData,this.numSpotLights)}_writeLightList(e,t,n){let r=nn[e],i=this[`${e}LightsBufferNode`],a=t?Math.floor(t.length/r):0,o=a*r;o>i.array.length&&(i.array=new Float32Array(an(e,a)*r),this._lightBufferRealloc=!0),o>0&&i.array.set(t.subarray(0,o)),i.array.fill(0,o),n.value=a}reset(){this.resetCount++,this.frameCount=0,this.frame.value=0,this.hasPreviousAccumulated.value=0,this.storageTextures.currentTarget=0,this.updateCompletionThreshold(),this.isComplete=!1,this.performanceMonitor?.reset(),this.lastInteractionModeState=!1,(this._pinSeedToFrame||this._lockstep)&&(this._seedTick=0),this._accumulationLockstep=!!this._lockstep}setSize(e,t){this.width=e,this.height=t,this.resolution.value.set(e,t),this.createStorageTextures(e,t)}setAccumulationEnabled(e){this.accumulationEnabled=e,this.enableAccumulation.value=+!!e}enterInteractionMode(){this.cameraOptimizer?.enterInteractionMode()}setInteractionModeEnabled(e){this.cameraOptimizer?.setInteractionModeEnabled(e)}get interactionMode(){return this.cameraOptimizer?.isInInteractionMode()??!1}get viewIsChanging(){return this.interactionMode||performance.now()-this._lastViewChangeAt<Lg}noteViewChanged(){this._lastViewChangeAt=performance.now()}setTriangleData(e,t){if(!e)return;let r=e.chunks&&e.chunks.length>1?e:null,i=r?null:e.chunks?e.chunks[0]:e,a=r?r.recordCount:Math.ceil(i.length/W.FLOATS_PER_TRIANGLE),o=r?._gpuUpload?.triangles?r._gpuUpload:null,{geo:s,shade:c}=o??this._allocateTriangleBuffers(a);this.triangleStorageNode?(this.triangleStorageNode.geo.value=s,this.triangleStorageNode.geo.bufferCount=s.count,this.triangleStorageNode.shade.value=c,this.triangleStorageNode.shade.bufferCount=c.count):this.triangleStorageNode={geo:(0,n.storage)(s,`uvec4`,s.count).toReadOnly(),shade:(0,n.storage)(c,`uvec4`,c.count).toReadOnly()},this.triangleGeoAttr=s,this.triangleShadeAttr=c,this._triangleRecords=r,this._triangleFlat=i,this._triangleRecordCount=a,this.triangleCount=t,this._uploadTriangles(0,a,{skipChunks:o?.uploaded}),Ig.debug(`${J.n(this.triangleCount)} triangles (storage buffer)`)}_allocateTriangleBuffers(e){let t=Math.max(1,e);this._assertFitsGPU(t*3*16);let n=S(t*3,4,Uint32Array),r=S(t*2,4,Uint32Array);return this.renderer.backend.createStorageAttribute(n),this.renderer.backend.createStorageAttribute(r),{geo:n,shade:r}}_uploadTriangles(e,t,{geo:n=!0,shade:r=!0,skipChunks:i=null,source:a=null,sourceStart:o=0,geoAttr:s=this.triangleGeoAttr,shadeAttr:c=this.triangleShadeAttr}={}){if(t<=0||!s)return;let l=this.renderer.backend,u=l.get(s).buffer,d=l.get(c).buffer,f=W.FLOATS_PER_TRIANGLE,p=this._triangleRecords,m=a?t:p?p.recordsPerChunk:this._triangleRecordCount,h=Fg;this._triangleStaging??={geo:new Uint32Array(h*12),shade:new Uint32Array(h*8)};let g=this._triangleStaging.geo,_=this._triangleStaging.shade;for(let s=e,c=e+t;s<c;){let t=a?0:Math.floor(s/m),v=a?e:t*m,y=Math.min(c,v+m);if(i?.has(t)){s=y;continue}let b=a??(p?p.chunks[t]:this._triangleFlat);if(!b)throw Error(`triangle chunk ${t} is on disk and was never uploaded`);let x=Math.min(h,y-s),S=(a?s-e+o:s-v)*f;for(let e=0,t=0,i=0;e<x;e++,S+=f){if(n)for(let e=0;e<12;e++)g[t++]=b[S+e];if(r)for(let e=12;e<f;e++)_[i++]=b[S+e]}n&&l.device.queue.writeBuffer(u,s*12*4,g,0,x*12),r&&l.device.queue.writeBuffer(d,s*8*4,_,0,x*8),s+=x}}createChunkUploader(e){this._assertFitsGPU(e.recordCount*e.lanesPerRecord*e.LaneType.BYTES_PER_ELEMENT);let t=S(e.recordCount*e.lanesPerRecord/4,4,e.LaneType),n=this.renderer.backend;n.createStorageAttribute(t);let r=n.get(t).buffer,i=e.recordsPerChunk*e.lanesPerRecord*e.LaneType.BYTES_PER_ELEMENT,a=new Set;return e._gpuUpload={attr:t,uploaded:a},t=>{let o=e.chunks[t];n.device.queue.writeBuffer(r,t*i,o,0,o.length),a.add(t)}}createTriangleChunkUploader(e){let{geo:t,shade:n}=this._allocateTriangleBuffers(e.recordCount),r=new Set;e._gpuUpload={triangles:!0,geo:t,shade:n,uploaded:r};let i=e.recordsPerChunk;return a=>{let o=a*i,s=Math.min(i,e.recordCount-o);this._uploadTriangles(o,s,{source:e.chunks[a],geoAttr:t,shadeAttr:n}),r.add(a)}}_assertFitsGPU(e){let t=this.renderer?.backend?.device?.limits,n=Math.min(t?.maxBufferSize??1/0,t?.maxStorageBufferBindingSize??1/0);if(e>n)throw Error(`the scene needs a ${J.mb(e)} GPU buffer, past the ${J.mb(n)} this GPU allows for one — load fewer triangles`)}_uploadChunked(e,t){let n=t._gpuUpload;if(!n||n.attr!==e){w(this.renderer,e,t.chunks);return}let r=this.renderer.backend.get(e).buffer,i=t.recordsPerChunk*t.lanesPerRecord*t.LaneType.BYTES_PER_ELEMENT;for(let e=0;e<t.chunks.length;e++){if(n.uploaded.has(e))continue;let a=t.chunks[e];if(!a)throw Error(`chunk ${e} is on disk and was never uploaded`);this.renderer.backend.device.queue.writeBuffer(r,e*i,a,0,a.length),n.uploaded.add(e)}}setBVHData(e){if(!e)return;let r=e.chunks&&e.chunks.length>1?e:null,i=r?null:e.chunks?e.chunks[0]:e,a=r?r.recordCount*r.lanesPerRecord:i.length,o=a/4;this._assertFitsGPU(a*4);let s=()=>r?r._gpuUpload?.attr??S(o,4,Float32Array):new t.StorageInstancedBufferAttribute(i,4);this.bvhStorageNode?(this.bvhStorageAttr=s(),this.bvhStorageNode.value=this.bvhStorageAttr,this.bvhStorageNode.bufferCount=o):(this.bvhStorageAttr=s(),this.bvhStorageNode=(0,n.storage)(this.bvhStorageAttr,`vec4`,o).toReadOnly()),this.bvhStorageAttr.foldedLeaves=e.foldedLeaves===!0,this._bvhRecords=r,r&&this._uploadChunked(this.bvhStorageAttr,r),this.bvhNodeCount=Math.floor(o/Rg),Ig.debug(`${J.n(this.bvhNodeCount)} BVH nodes (storage buffer)`)}setInstanceTable(e){this._instanceTable=e}setMeshVisibilityData(e){!e||e.length===0||!this._instanceTable||(this._patchVisibilityFromMeshes(e),this._flushBVHEdits())}_patchVisibilityFromMeshes(e){let t=this._instanceTable,n=new Map;for(let r=0;r<t.count;r++){if(!t.isSet[r])continue;let i=t.sourceMesh[r],a=n.get(i);a===void 0&&n.set(i,a=this._isWorldVisible(e[i])),this._patchTLASLeafVisibility(r,a)}}updateMeshVisibility(e,t){this._patchTLASLeafVisibility(e,t)&&this._flushBVHEdits()}updateAllMeshVisibility(){!this._meshRefs||!this._instanceTable||(this._patchVisibilityFromMeshes(this._meshRefs),this._flushBVHEdits())}_patchTLASLeafVisibility(e,t){let n=this._instanceTable;if(!n||!n.isSet?.[e]||!this.bvhStorageAttr)return!1;let r=n.tlasLeafIndex[e];return r<0?!1:(n.visible[e]=+!!t,this._bvhRecords?this._bvhRecords.chunkFor(r)[this._bvhRecords.baseOf(r)+2]=+!!t:this.bvhStorageAttr.array[r*16+2]=+!!t,this._dirtyBVHLeaves??=new Set,this._dirtyBVHLeaves.add(r),!0)}_flushBVHEdits(){if(this.bvhStorageAttr){if(!this._bvhRecords){let e=1/0,t=-1;for(let n of this._dirtyBVHLeaves??[])n<e&&(e=n),n>t&&(t=n);t>=0&&(this.bvhStorageAttr.addUpdateRange(e*16,(t-e+1)*16),this.bvhStorageAttr.version++),this._dirtyBVHLeaves?.clear();return}for(let e of this._dirtyBVHLeaves??[])T(this.renderer,this.bvhStorageAttr,this._bvhRecords,e*16,16);this._dirtyBVHLeaves?.clear()}}_collectMeshRefs(e){if(!e)return[];let t=[];return e.traverse(e=>{e.isMesh&&e.userData.meshIndex!==void 0&&(t[e.userData.meshIndex]=e)}),t}_isWorldVisible(e){for(;e;){if(!e.visible)return!1;e=e.parent}return!0}_updateStorageBuffer(e,t){e&&(e.array.set(t),e.clearUpdateRanges(),e.needsUpdate=!0)}updateTriangleData(e,t){e?.chunks?.length>1?this._triangleRecords=e:e&&(this._triangleFlat=e.chunks?e.chunks[0]:e),t?this.updateBufferRanges(t,[]):this._uploadTriangles(0,this._triangleRecordCount)}updateBVHData(e,t){if(this._bvhRecords){e?.chunks?.length>1&&(this._bvhRecords=e),t?this.updateBufferRanges([],t):w(this.renderer,this.bvhStorageAttr,this._bvhRecords.chunks);return}let n=e?.chunks?e.chunks[0]:e;if(!t){this._updateStorageBuffer(this.bvhStorageAttr,n);return}let r=this.bvhStorageAttr?.array;if(n&&r&&n!==r)for(let e of t)r.set(n.subarray(e.offset,e.offset+e.count),e.offset);this.updateBufferRanges([],t)}updateBufferRanges(e,t){if(this.triangleGeoAttr&&e.length>0){let t=W.FLOATS_PER_TRIANGLE;for(let n of e){let e=Math.floor(n.offset/t);this._uploadTriangles(e,Math.ceil((n.offset+n.count)/t)-e)}}if(this.bvhStorageAttr&&t.length>0)if(this._bvhRecords)for(let e of t)T(this.renderer,this.bvhStorageAttr,this._bvhRecords,e.offset,e.count);else{this.bvhStorageAttr.clearUpdateRanges();for(let e of t)this.bvhStorageAttr.addUpdateRange(e.offset,e.count);this.bvhStorageAttr.version++}}createStorageTextures(e,t){this.storageTextures.writeColor?this.storageTextures.setSize(e,t):this.storageTextures.create(e,t),this.resolution.value.set(e,t)}setupMaterial(){if(this.cameraOptimizer||this._initCameraOptimizer(),!this.triangleStorageNode){Ig.error(`triangle data required`);return}if(!this.bvhStorageNode){Ig.error(`BVH data required`);return}if(this.isReady&&this.shaderBuilder.getSceneTextureNodes()){this.shaderBuilder.updateSceneTextures(this);return}this._ensureStorageTextures(),this.shaderBuilder.createSceneTextureNodes(this,this.storageTextures),this.isReady=!0}_ensureStorageTextures(){let e=this.renderer.domElement,t=Math.max(1,e.width||this.width),n=Math.max(1,e.height||this.height);this.storageTextures.ensureSize(t,n)&&this.resolution.value.set(t,n)}_handleResize(){let{width:e,height:t}=this.renderer.domElement;(e!==this.storageTextures.renderWidth||t!==this.storageTextures.renderHeight)&&(this.createStorageTextures(e,t),this.frameCount=0,this._accumulationLockstep=!1),this.resolution.value.set(e,t)}_matricesApproxEqual(e,t,n=1e-10){let r=e.elements,i=t.elements;for(let e=0;e<16;e++)if(Math.abs(r[e]-i[e])>n)return!1;return!0}_updateCameraUniforms(){return!this._matricesApproxEqual(this.lastCameraMatrix,this.camera.matrixWorld)||!this._matricesApproxEqual(this.lastProjectionMatrix,this.camera.projectionMatrixInverse)?(this.cameraWorldMatrix.value.copy(this.camera.matrixWorld),this.cameraViewMatrix.value.copy(this.camera.matrixWorldInverse),this.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix),this.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse),this.lastCameraMatrix.copy(this.camera.matrixWorld),this.lastProjectionMatrix.copy(this.camera.projectionMatrixInverse),!0):!1}_updateAccumulationUniforms(e){let t=this.cameraOptimizer?.isInInteractionMode()??!1;this.lastInteractionModeState=t,this.accumulationEnabled?t?(this.accumulationAlpha.value=1,this.hasPreviousAccumulated.value=0):(this.accumulationAlpha.value=de(e),this.hasPreviousAccumulated.value=+(e>0)):(this.accumulationAlpha.value=1,this.hasPreviousAccumulated.value=0)}_publishTexturesToContext(e,t){e.setTexture(`pathtracer:color`,t.color),e.setTexture(`pathtracer:normalDepth`,t.normalDepth),e.setTexture(`pathtracer:albedo`,t.albedo),e.setState(`pathtracer:samples`,this.frameCount),e.setState(`interactionMode`,this.cameraOptimizer?.isInInteractionMode()??!1),e.setState(`renderMode`,this.renderMode.value)}_emitStateEvents(){this.emit(`pathtracer:frameComplete`,{frame:this.frameCount,isComplete:this.isComplete}),this.cameraChanged&&=(this.emit(`camera:moved`),!1)}updateCompletionThreshold(){this.completionThreshold=ue(this.renderMode.value,this.maxSamples.value)}setRenderLimitMode(e){this.renderLimitMode=e,this.updateCompletionThreshold()}manageASVGFForRenderMode(e){e!==this.lastRenderMode&&(this.renderModeChangeTimeout&&clearTimeout(this.renderModeChangeTimeout),this.pendingRenderMode=e,this.renderModeChangeTimeout=setTimeout(()=>{this.pendingRenderMode!==null&&this.pendingRenderMode!==this.lastRenderMode&&(this.lastRenderMode=this.pendingRenderMode,this.emit(`asvgf:reset`),this.emit(`denoiser:reset`)),this.renderModeChangeTimeout=null,this.pendingRenderMode=null},this.renderModeChangeDelay))}setUniform(e,t){this.uniforms.set(e,t)}setBlueNoiseTexture(){}_rebuildLightBuffer(){let e=this._lbvhDataCache,n=this._emissiveDataCache,r=this.lightStorageAttr?.array,i=this._bitTrailMapCache??(r&&this._bitTrailLength?r.slice(this._bitTrailOffset,this._bitTrailOffset+this._bitTrailLength):null);this._bitTrailMapCache=null;let a=e?e.length:0,o=n?n.length:0,s=i?Math.ceil(i.length/4)*4:0,c=Math.max(a+o+s,4);if(this.lightStorageAttr&&c<=this.lightStorageAttr.array.length){let t=this.lightStorageAttr.array;e&&t.set(e,0),n&&t.set(n,a),i&&t.set(i,a+o),this.lightStorageAttr.needsUpdate=!0}else{let r=new Float32Array(c);e&&r.set(e,0),n&&r.set(n,a),i&&r.set(i,a+o),this.lightStorageAttr=new t.StorageInstancedBufferAttribute(r,4),this.lightStorageNode.value=this.lightStorageAttr,this.lightStorageNode.bufferCount=r.length/4,this._lightBufferRealloc=!0}this.emissiveVec4Offset.value=(this.lightBVHNodeCount.value||0)*4,this.reverseMapVec4Offset.value=(a+o)/4,this._bitTrailOffset=a+o,this._bitTrailLength=i?i.length:0}setEmissiveTriangleData(e,t,n=0,r=null){e&&(this._emissiveDataCache=e,r&&(this._bitTrailMapCache=r),this.emissiveTriangleCount.value=t,this.emissiveTotalPower.value=n,this._rebuildLightBuffer(),Ig.debug(`${J.n(t)} emissive triangles · totalPower ${n.toFixed(4)} (storage buffer)`))}setLightBVHData(e,t){e&&(this._lbvhDataCache=e,this.lightBVHNodeCount.value=t,this._rebuildLightBuffer(),Ig.debug(`light BVH ${J.n(t)} nodes`))}updateUniforms(e){let t=!1;for(let[n,r]of Object.entries(e))this[n]&&this[n].value!==void 0&&this[n].value!==r&&(this[n].value=r,t=!0);t&&this.reset()}async rebuildMaterials(e){if(!this.sdfs)throw Error(`Scene not built yet. Call build() first.`);try{Ig.debug(`material rebuild started`),await this.sdfs.rebuildMaterials(e),this.materialData.setMaterialData(this.sdfs.materialData,this.sdfs.materials?.map(e=>e.sources)),this.materialData.loadTexturesFromSdfs(),this.shaderBuilder.updateSceneTextures(this),this.updateLights(),this.reset(),Ig.debug(`material rebuild complete`)}catch(e){Ig.error(`material rebuild failed:`,e);try{Ig.warn(`attempting recovery by resetting the path tracer`),this.reset()}catch(e){Ig.error(`recovery failed:`,e)}throw e}}dispose(){this.renderModeChangeTimeout&&=(clearTimeout(this.renderModeChangeTimeout),null),this.cameraOptimizer?.dispose(),this.materialData?.dispose(),this.environment?.dispose(),this.shaderBuilder?.dispose(),this.uniforms?.dispose(),this.storageTextures?.dispose(),this.placeholderTexture?.dispose(),this.triangleGeoAttr=null,this.triangleShadeAttr=null,this._triangleStaging=null,this._triangleRecords=null,this._triangleFlat=null,this._triangleRecordCount=0,this.triangleStorageNode=null,this.bvhStorageAttr=null,this._bvhRecords=null,this.bvhStorageNode=null,this.placeholderTexture=null,this.isReady=!1}};jt();var Bg=vt(`gpu`),$={ACTIVE_RAY_COUNT:0,ENTERING_COUNT:1,CONVERGED_COUNT:2,RESERVED_3:3,ACTIVE_PIXEL_COUNT:4,GEOMETRY_COUNT:5,CONVERGED_GEOMETRY_COUNT:6,ACTIVE_ENERGY:7,COUNT:8},Vg=65535,Hg={BOUNCE_MASK:255,ACTIVE:256,SPECULAR:512,INSIDE_MEDIUM:1024,RAY_TYPE_SHIFT:11,RAY_TYPE_MASK:63488,HAS_HIT_OPAQUE:65536,AUX_LOCKED:1<<17,REDIRECTED:1<<18,SUN_NEE:1<<19,UNDER_SURFACE:1<<20},Ug=class{constructor(e=0,t=null){this._renderer=t,this.capacity=0,this.counters=null,this.activeIndices=null,this.activeIndicesRO=null,this.sortedIndices=null,this.sortedIndicesRO=null,this.sortGlobalHistogram=null,this.pingPong=0,e>0&&this.allocate(e)}allocate(e){this.dispose(),this.capacity=e,this._countersAttr=new t.StorageInstancedBufferAttribute(new Uint32Array($.COUNT),1),this.counters=(0,n.storage)(this._countersAttr,`uint`).toAtomic(),this.MAX_BOUNCE_SNAPSHOTS=32,this._bounceCountsAttr=new t.StorageInstancedBufferAttribute(new Uint32Array(2*this.MAX_BOUNCE_SNAPSHOTS),1),this.bounceCounts=(0,n.storage)(this._bounceCountsAttr,`uint`);let r=S(e,1,Uint32Array),i=S(e,1,Uint32Array);this._attrA=r,this._attrB=i,this.activeIndices={a:(0,n.storage)(r,`uint`),b:(0,n.storage)(i,`uint`)},this.activeIndicesRO={a:(0,n.storage)(r,`uint`).toReadOnly(),b:(0,n.storage)(i,`uint`).toReadOnly()};let a=S(e,1,Uint32Array);this._sortAttr=a,this.sortedIndices=(0,n.storage)(a,`uint`),this.sortedIndicesRO=(0,n.storage)(a,`uint`).toReadOnly(),this._sortGlobalHistAttr=new t.StorageInstancedBufferAttribute(new Uint32Array(256),1),this.sortGlobalHistogram=(0,n.storage)(this._sortGlobalHistAttr,`uint`).toAtomic(),this.pingPong=0,this.totalBytes=$.COUNT*4+e*4*3,Bg.debug(`queues capacity ${J.n(e)} · ${J.mb(this.totalBytes)}`)}resize(e){return e<=this.capacity&&this.capacity>0?!1:(this.allocate(e),!0)}getCounters(){return this.counters}getActiveReadRO(){return this.pingPong===0?this.activeIndicesRO.a:this.activeIndicesRO.b}getActiveRead(){return this.pingPong===0?this.activeIndices.a:this.activeIndices.b}getActiveWrite(){return this.pingPong===0?this.activeIndices.b:this.activeIndices.a}getSortedRW(){return this.sortedIndices}getSortedRO(){return this.sortedIndicesRO}getSortGlobalHistogram(){return this.sortGlobalHistogram}getCountersAttribute(){return this._countersAttr}getBounceCounts(){return this.bounceCounts}getBounceCountsAttribute(){return this._bounceCountsAttr}swap(){this.pingPong=1-this.pingPong}resetPingPong(){this.pingPong=0}dispose(){Ca(this._renderer,this._countersAttr),Ca(this._renderer,this._bounceCountsAttr),Ca(this._renderer,this._attrA),Ca(this._renderer,this._attrB),Ca(this._renderer,this._sortAttr),Ca(this._renderer,this._sortGlobalHistAttr),this._countersAttr=this._bounceCountsAttr=null,this._attrA=this._attrB=this._sortAttr=this._sortGlobalHistAttr=null,this.counters=null,this.activeIndices=null,this.activeIndicesRO=null,this.sortedIndices=null,this.sortedIndicesRO=null,this.sortGlobalHistogram=null,this.capacity=0}},Wg={[r.RGBAFormat]:4,[r.RGBFormat]:3,[r.RGFormat]:2,[r.RedFormat]:1},Gg={[r.FloatType]:4,[r.HalfFloatType]:2,[r.UnsignedByteType]:1,[r.ByteType]:1,[r.UnsignedShortType]:2,[r.ShortType]:2,[r.UnsignedIntType]:4,[r.IntType]:4};function Kg(e){return(Wg[e.format]??4)*(Gg[e.type]??4)}function qg(e){return e?.gpuByteLength??e?.array?.byteLength??0}function Jg(e){if(!e)return 0;if(e.isRenderTarget){let t=e.textures?.length?e.textures:[e.texture],n=e.width||0,r=e.height||0,i=e.depth||1,a=0;for(let e of t)e&&(a+=n*r*i*Kg(e));return a}let t=e.image||{},n=t.width??e.width??0,r=t.height??e.height??0,i=t.depth??1;return n*r*i*Kg(e)}var Yg=class{constructor(e=null){this._providers=[],this._renderer=e,this.current=0,this.peak=0,this.byCategory={}}setRenderer(e){this._renderer=e}register(e,t){this._providers.push({category:e,fn:t})}measure(){let e=new WeakSet,t={},n=0;for(let{category:r,fn:i}of this._providers){let a;try{a=i()}catch{a=null}if(!a)continue;let o=0;for(let t of Array.isArray(a)?a:[a])o+=this._resourceBytes(t,e);t[r]=(t[r]||0)+o,n+=o}return this.byCategory=t,this.current=n,n>this.peak&&(this.peak=n),{current:n,peak:this.peak,byCategory:t}}_resourceBytes(e,t){return e?typeof e.bytes==`number`&&!e.isTexture&&!e.isRenderTarget?e.bytes:e.gpuByteLength==null?e.array&&e.array.byteLength!=null?t.has(e.array)?0:(t.add(e.array),e.array.byteLength):e.isRenderTarget||e.isTexture?t.has(e)?0:(t.add(e),this._residentTextureBytes(e)):0:t.has(e)?0:(t.add(e),e.gpuByteLength):0}_isResident(e){let t=this._renderer?.backend;if(!t||typeof t.get!=`function`)return!0;if(typeof t.has==`function`&&!t.has(e))return!1;let n=t.get(e);return!!(n&&(n.texture||n.gpuTexture))}_residentTextureBytes(e){if(e.isRenderTarget){let t=e.textures?.length?e.textures:[e.texture],n=e.width||0,r=e.height||0,i=e.depth||1,a=0;for(let e of t)e&&this._isResident(e)&&(a+=n*r*i*Kg(e));return a}return this._isResident(e)?Jg(e):0}resetPeak(){this.peak=this.current}getReport(){let e=e=>(e/1048576).toFixed(1),t=Object.entries(this.byCategory).map(([t,n])=>`${t}=${e(n)}`);return`VRAM current=${e(this.current)}MB peak=${e(this.peak)}MB [${t.join(` `)}]`}};jt();var Xg=vt(`wavefront`),Zg=class{constructor(e){this.renderer=e,this.kernels=new Map,this.timing=new Map,this.profiling=!1,this.profile=new Map,this._firstDispatches=[],this._firstDispatchFlush=null}_recordFirstDispatch(e,t){this._firstDispatches.push({name:e,ms:t}),clearTimeout(this._firstDispatchFlush),this._firstDispatchFlush=setTimeout(()=>this._flushFirstDispatches(),0)}_flushFirstDispatches(){let e=this._firstDispatches;if(this._firstDispatches=[],this._firstDispatchFlush=null,e.length===0)return;let t=e.reduce((e,t)=>e+t.ms,0),n=[...e].sort((e,t)=>t.ms-e.ms);Xg.info(J.list([`${e.length} kernel${e.length===1?``:`s`} compiled in ${J.ms(t)}`,`slowest ${n.slice(0,2).map(e=>`${e.name} ${J.ms(e.ms)}`).join(`, `)}`])),e.forEach(e=>Xg.debug(`kernel '${e.name}' first dispatch (incl. compilation) ${J.ms(e.ms)}`))}register(e,t){this.kernels.set(e,t),this.timing.set(e,{compiledOnce:!1,lastDispatchMs:0})}dispatch(e){let t=this.kernels.get(e);if(!t)throw Error(`KernelManager: Unknown kernel '${e}'`);let n=this.timing.get(e);if(n&&!n.compiledOnce){let r=performance.now();this.renderer.compute(t);let i=performance.now();n.compiledOnce=!0,n.lastDispatchMs=i-r,this._recordFirstDispatch(e,i-r)}else if(this.profiling){let n=performance.now();this.renderer.compute(t);let r=performance.now(),i=this.profile.get(e);i||(i={calls:0,totalMs:0},this.profile.set(e,i)),i.calls++,i.totalMs+=r-n}else this.renderer.compute(t)}setDispatchForCount(e,t){let n=this.kernels.get(e);if(!n)return;let r=Math.ceil(t/n.workgroupSize[0]),i=this.renderer?.backend?.device?.limits.maxComputeWorkgroupsPerDimension??65535;n.dispatchSize=r>i?[i,Math.ceil(r/i),1]:[r,1,1]}setDispatchForGrid(e,t,n){let r=this.kernels.get(e);if(!r)return;let i=r.workgroupSize;r.dispatchSize=[Math.ceil(t/i[0]),Math.ceil(n/i[1]),1]}has(e){return this.kernels.has(e)}get(e){return this.kernels.get(e)}getTimingReport(){let e={};for(let[t,n]of this.timing)e[t]={...n};return e}enableProfiling(e){this.profiling=e,e&&this.profile.clear()}getProfileReport(){let e=[],t=0;for(let[n,{calls:r,totalMs:i}]of this.profile)t+=i,e.push({name:n,calls:r,totalMs:+i.toFixed(2),avgMs:+(i/r).toFixed(3)});return e.sort((e,t)=>t.totalMs-e.totalMs),e.push({name:`TOTAL`,calls:e.reduce((e,t)=>e+t.calls,0),totalMs:+t.toFixed(2),avgMs:null}),e}dispose(){clearTimeout(this._firstDispatchFlush),this._firstDispatchFlush=null,this._firstDispatches=[],this.kernels.clear(),this.timing.clear(),this.profile.clear()}},Qg=(0,n.int)(Se.equirectangular),$g=(0,n.int)(Se.orthographic),e_=e=>e.equal($g);function t_(){let e={cameraProjection:(0,n.uniform)(0,`int`),panoLonRange:(0,n.uniform)(new r.Vector2,`vec2`),panoLatRange:(0,n.uniform)(new r.Vector2,`vec2`),panoLevelHorizon:(0,n.uniform)(1,`int`),sync(t){e.cameraProjection.value=t.get(`cameraProjection`).value,e.panoLonRange.value.copy(t.get(`panoLonRange`).value),e.panoLatRange.value.copy(t.get(`panoLatRange`).value),e.panoLevelHorizon.value=t.get(`panoLevelHorizon`).value}};return e}var n_=(e,t,n,r)=>({origin:i_(e,t,n,r.cameraProjection),direction:a_(e,t,n,r.cameraProjection,r.panoLonRange,r.panoLatRange,r.panoLevelHorizon)}),r_=(e,t,n,r,i)=>{let{origin:a,direction:o}=n_(e,n,r,i);return a.add(o.mul(t))},i_=(0,n.Fn)(([e,t,r,i])=>{let a=(0,n.vec3)(t[3]).toVar();return(0,n.If)(e_(i),()=>{let i=r.mul((0,n.vec4)(e.x.mul(2).sub(1),(0,n.float)(1).sub(e.y.mul(2)),0,1));a.assign(t.mul((0,n.vec4)(i.xy,0,1)).xyz)}),a}),a_=(0,n.Fn)(([e,t,r,i,a,o,s])=>{let c=(0,n.vec3)(0).toVar();return(0,n.If)(i.equal(Qg),()=>{let r=(0,n.mix)(a.x,a.y,e.x).toVar(),i=(0,n.mix)(o.y,o.x,e.y).toVar(),l=(0,n.cos)(i).toVar(),u=(0,n.vec3)(0).toVar(),d=(0,n.vec3)(0).toVar(),f=(0,n.vec3)(0).toVar();(0,n.If)(s.equal((0,n.int)(1)),()=>{let e=(0,n.vec3)(t[2].x,0,t[2].z).toVar();(0,n.If)((0,n.dot)(e,e).lessThan((0,n.float)(1e-8)),()=>{e.assign((0,n.vec3)(t[1].x,0,t[1].z))}),f.assign((0,n.normalize)(e)),d.assign((0,n.vec3)(0,1,0)),u.assign((0,n.cross)(d,f))}).Else(()=>{u.assign((0,n.normalize)((0,n.vec3)(t[0]))),d.assign((0,n.normalize)((0,n.vec3)(t[1]))),f.assign((0,n.normalize)((0,n.vec3)(t[2])))}),c.assign((0,n.normalize)(u.mul((0,n.sin)(r).mul(l)).add(d.mul((0,n.sin)(i))).sub(f.mul((0,n.cos)(r).mul(l)))))}).ElseIf(e_(i),()=>{c.assign((0,n.normalize)((0,n.vec3)(t[2])).negate())}).Else(()=>{let i=(0,n.vec3)(e.x.mul(2).sub(1),(0,n.float)(1).sub(e.y.mul(2)),1),a=r.mul((0,n.vec4)(i,1));c.assign((0,n.normalize)((0,n.mat3)(t[0].xyz,t[1].xyz,t[2].xyz).mul(a.xyz.div(a.w))))}),c}),o_=(0,n.Fn)(([e,t,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_])=>{let v=i_(e,r,i,a).toVar(),y=a_(e,r,i,a,o,s,c).toVar(),b=v.toVar(),x=y.toVar(),S=g.equal((0,n.int)(1)),C=S.and(_.greaterThan(0)).or(S.not().and(u.greaterThan(0)).and(d.lessThan(64)));return(0,n.If)(l.and(C).and(f.greaterThan(.001)),()=>{let e=(0,n.select)(a.equal(Qg),s.y.sub(s.x).mul(.5),(0,n.select)(e_(a),(0,n.float)(1),i[1].y)),o=(0,n.select)(S,_.mul(f).mul(e),u.div(d.mul(2)).mul(.001).mul(p).mul(m)),c=Ht(t),l=c.x.mul(h.max(.01)),g=c.y,C=(0,n.vec3)(0).toVar(),w=f.toVar();(0,n.If)(a.equal(Qg),()=>{C.assign(Yi({N:y}).mul((0,n.vec3)(l,g,0)))}).Else(()=>{let e=(0,n.normalize)((0,n.vec3)(r[0])),t=(0,n.normalize)((0,n.vec3)(r[1]));C.assign(e.mul(l).add(t.mul(g))),w.assign(f.div((0,n.dot)(y,(0,n.normalize)((0,n.vec3)(r[2]))).negate()))}),b.assign(v.add(C.mul(o))),x.assign((0,n.normalize)(v.add(y.mul(w)).sub(b)))}),mi({origin:b,direction:x})});function s_(e){let{rayBufferRW:t,hitBufferRW:r,gBufferRW:i,resolution:a,frame:o,cameraWorldMatrix:s,cameraProjectionMatrixInverse:c,cameraProjection:l,panoLonRange:u,panoLatRange:d,panoLevelHorizon:f,enableDOF:p,focalLength:m,aperture:h,focusDistance:g,unitsPerMetre:_,apertureScale:v,anamorphicRatio:y,dofMode:b,dofBlur:x,renderWidth:S,chunkRowBase:C,chunkRows:w,transmissiveBounces:T,auxGBufferEnabled:E,listDriven:D=!1,activeIndicesRO:O=null,counters:k=null}=e,A=E.greaterThan((0,n.uint)(0)),j=(e,S,C)=>{let w=(0,n.vec2)((0,n.float)(e).add(.5),(0,n.float)(S).add(.5)),E=Rt({state:en({pixelCoord:w,rayIndex:(0,n.int)(0),frame:o}).toVar()}).toVar(),D=$t(w,(0,n.int)(1),E,a,o).toVar().sub(.5),O=(0,n.vec2)(w.x.add(D.x),w.y.sub(D.y)).div(a),k=mi.wrap(o_(O,E,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x));Ba(t,C,k.origin,(0,n.int)(0),(0,n.int)(0)),Va(t,C,k.direction,(0,n.uint)(Hg.ACTIVE)),Ha(t,C,(0,n.vec4)(1,1,1,0).xyz,(0,n.float)(0)),Ua(t,C,(0,n.vec4)((0,n.vec3)(0),(0,n.float)(1))),(0,n.If)(A,()=>{Ma(i,C,(0,n.vec3)(0,0,1),(0,n.float)(1),(0,n.vec3)(0),(0,n.float)(0)),so(t,C,(0,n.vec3)(1))}),to(t,C,(0,n.uint)(0),(0,n.uint)(T),(0,n.float)(1),(0,n.float)(1),(0,n.float)(1)),Qa(r,C,E)};return(0,n.Fn)(()=>{if(D){let e=n.instanceIndex;(0,n.If)(e.lessThan((0,n.atomicLoad)(k.element((0,n.uint)($.ENTERING_COUNT)))),()=>{let t=(0,n.int)(O.element(e)),r=t.add(C.mul(S));j(r.mod(S),r.div(S),(0,n.uint)(t))})}else{let e=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),t=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(e.lessThan(S).and(t.lessThan(w)),()=>{j(e,t.add(C),(0,n.uint)(t.mul(S).add(e)))})}})}var c_=32,l_=4096,u_=4,d_=1e8,f_=()=>(0,n.array)(`int`,c_).toVar(),p_=e=>(0,n.int)((0,n.uint)(e.bitNot()).shiftRight((0,n.uint)(4))),m_=e=>(0,n.int)((0,n.uint)(e.bitNot()).bitAnd((0,n.uint)(15))),h_=e=>e?e=>e.shiftRight((0,n.uint)(30)).equal((0,n.uint)(1)):e=>e.greaterThanEqual((0,n.uint)(Ue)),g_=e=>{let t=(0,n.mix)((0,n.vec3)(1),(0,n.sign)(e),(0,n.notEqual)(e,(0,n.vec3)(0)));return(0,n.mix)((0,n.vec3)(1).div(e),(0,n.vec3)(d_).mul(t),(0,n.lessThan)((0,n.abs)(e),(0,n.vec3)(1e-8)))},__=(e,t)=>(0,n.vec3)(e[0].xyz.dot(t).add(e[0].w),e[1].xyz.dot(t).add(e[1].w),e[2].xyz.dot(t).add(e[2].w)),v_=(e,t)=>(0,n.vec3)(e[0].xyz.dot(t),e[1].xyz.dot(t),e[2].xyz.dot(t)),y_=(0,n.wgslFn)(`
|
|
715
|
+
`);jt();var pp=vt(`shader`),mp=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),pp.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;ua(e.uniforms.get(`enableAlphaShadows`));let 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=e.goboMaps?(0,n.texture)(e.goboMaps):u();rp(d);let f=e.iesProfiles?(0,n.texture)(e.iesProfiles):u();sp(f);let p={triStorage:i,bvhStorage:a,matStorage:o,lightBufferStorage:s,envTex:c,goboMapsTex:d,iesProfilesTex:f};return this._sceneTextureNodes=p,p}dispose(){this.prevColorTexNode=null,this.prevAlbedoTexNode=null,this.prevNormalDepthTexNode=null,this._sceneTextureNodes=null}},hp=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.maxTreeletLeaves=7,this.minImprovement=.02,this.topologyCache=new Map;for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.set(e,this.generateTopologies(e));this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0}}generateTopologies(e){if(e===1)return[0];if(e===2)return[[0,1]];let t=[];for(let n=1;n<e;n++){let r=this.generateTopologies(n),i=this.generateTopologies(e-n);for(let e of r)for(let r of i)t.push([e,this.offsetTopology(r,n)])}return t}offsetTopology(e,t){return typeof e==`number`?e+t:[this.offsetTopology(e[0],t),this.offsetTopology(e[1],t)]}optimizeBVH(e){let t=performance.now();this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0};let n=this.identifyTreeletRoots(e);for(let e=0;e<n.length;e++){if(performance.now()-t>3e4){console.warn(`TreeletOptimizer: timeout after ${e}/${n.length} treelets`);break}this.optimizeTreelet(n[e])}return this.stats.optimizationTime=performance.now()-t,this.stats.averageSAHImprovement=this.stats.treeletsProcessed>0?this.stats.totalSAHImprovement/this.stats.treeletsProcessed:0,e}identifyTreeletRoots(e){let t=[],n=new Set,r=[{node:e,visited:!1}];for(;r.length>0;){let e=r[r.length-1];if(e.visited){r.pop();let i=e.node;if(i.triangleCount>0||n.has(i))continue;let a=this.countLeaves(i);a>=3&&a<=this.maxTreeletLeaves&&(t.push(i),this.markSubtree(i,n))}else{e.visited=!0;let t=e.node;if(t.triangleCount>0)continue;t.rightChild&&r.push({node:t.rightChild,visited:!1}),t.leftChild&&r.push({node:t.leftChild,visited:!1})}}return t}countLeaves(e){return e?e.triangleCount>0?1:this.countLeaves(e.leftChild)+this.countLeaves(e.rightChild):0}markSubtree(e,t){e&&(t.add(e),!(e.triangleCount>0)&&(this.markSubtree(e.leftChild,t),this.markSubtree(e.rightChild,t)))}optimizeTreelet(e){let t=[];this.extractLeaves(e,t);let n=t.length;if(n<3||n>this.maxTreeletLeaves)return;this.stats.treeletsProcessed++;let r=this.evaluateSubtreeSAH(e),i=this.topologyCache.get(n);if(!i||i.length===0)return;let a=r,o=null,s=null;if(n<=5){let e=this.generatePermutations(n);for(let n of i)for(let r of e){let e=this.evaluateTopology(n,t,r);e<a&&(a=e,o=n,s=r)}}else{let e=Array.from({length:n},(e,t)=>t);for(let n of i){let r=this.evaluateTopology(n,t,e);r<a&&(a=r,o=n,s=e);let i=this.greedySwapOptimize(n,t,e,r);i.cost<a&&(a=i.cost,o=n,s=i.perm)}}let c=(r-a)/r;o&&c>this.minImprovement&&(this.reconstructTreelet(e,o,t,s),this.stats.treeletsImproved++,this.stats.totalSAHImprovement+=c)}extractLeaves(e,t){if(e){if(e.triangleCount>0){t.push({minX:e.minX,minY:e.minY,minZ:e.minZ,maxX:e.maxX,maxY:e.maxY,maxZ:e.maxZ,triangleOffset:e.triangleOffset,triangleCount:e.triangleCount});return}this.extractLeaves(e.leftChild,t),this.extractLeaves(e.rightChild,t)}}evaluateSubtreeSAH(e){if(!e)return 0;if(e.triangleCount>0)return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*e.triangleCount*this.intersectionCost;let t=this.evaluateSubtreeSAH(e.leftChild),n=this.evaluateSubtreeSAH(e.rightChild);return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*this.traversalCost+t+n}evaluateTopology(e,t,n){return this.evalTopoRecursive(e,t,n).cost}evalTopoRecursive(e,t,n){if(typeof e==`number`){let r=t[n[e]];return{cost:this.surfaceAreaFlat(r.minX,r.minY,r.minZ,r.maxX,r.maxY,r.maxZ)*r.triangleCount*this.intersectionCost,minX:r.minX,minY:r.minY,minZ:r.minZ,maxX:r.maxX,maxY:r.maxY,maxZ:r.maxZ}}let r=this.evalTopoRecursive(e[0],t,n),i=this.evalTopoRecursive(e[1],t,n),a=Math.min(r.minX,i.minX),o=Math.min(r.minY,i.minY),s=Math.min(r.minZ,i.minZ),c=Math.max(r.maxX,i.maxX),l=Math.max(r.maxY,i.maxY),u=Math.max(r.maxZ,i.maxZ);return{cost:this.surfaceAreaFlat(a,o,s,c,l,u)*this.traversalCost+r.cost+i.cost,minX:a,minY:o,minZ:s,maxX:c,maxY:l,maxZ:u}}surfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}generatePermutations(e){let t=[],n=Array.from({length:e},(e,t)=>t),r=i=>{if(i===e){t.push([...n]);return}for(let t=i;t<e;t++)[n[i],n[t]]=[n[t],n[i]],r(i+1),[n[i],n[t]]=[n[t],n[i]]};return r(0),t}greedySwapOptimize(e,t,n,r){let i=[...n],a=r,o=!0;for(;o;){o=!1;for(let n=0;n<i.length-1;n++)for(let r=n+1;r<i.length;r++){[i[n],i[r]]=[i[r],i[n]];let s=this.evaluateTopology(e,t,i);s<a?(a=s,o=!0):[i[n],i[r]]=[i[r],i[n]]}}return{perm:i,cost:a}}reconstructTreelet(e,t,n,r){let i=this.buildSubtree(t,n,r);e.minX=i.minX,e.minY=i.minY,e.minZ=i.minZ,e.maxX=i.maxX,e.maxY=i.maxY,e.maxZ=i.maxZ,e.leftChild=i.leftChild,e.rightChild=i.rightChild,e.triangleOffset=i.triangleOffset,e.triangleCount=i.triangleCount}buildSubtree(e,t,n){if(typeof e==`number`){let r=t[n[e]],i=new gp;return i.minX=r.minX,i.minY=r.minY,i.minZ=r.minZ,i.maxX=r.maxX,i.maxY=r.maxY,i.maxZ=r.maxZ,i.triangleOffset=r.triangleOffset,i.triangleCount=r.triangleCount,i}let r=this.buildSubtree(e[0],t,n),i=this.buildSubtree(e[1],t,n),a=new gp;return a.leftChild=r,a.rightChild=i,a.minX=Math.min(r.minX,i.minX),a.minY=Math.min(r.minY,i.minY),a.minZ=Math.min(r.minZ,i.minZ),a.maxX=Math.max(r.maxX,i.maxX),a.maxY=Math.max(r.maxY,i.maxY),a.maxZ=Math.max(r.maxZ,i.maxZ),a}setTreeletSize(e){this.maxTreeletLeaves=Math.max(3,Math.min(7,e));for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.has(e)||this.topologyCache.set(e,this.generateTopologies(e))}setMinImprovement(e){this.minImprovement=Math.max(.001,e)}getStatistics(){return{...this.stats}}},gp=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}},_p=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}},vp=1073741824,yp=1073741824,bp=15,xp=16,Sp=2147483648,Cp=(e,t)=>~(e<<4|t)>>>0,wp=e=>e>=Sp,Tp=e=>~e>>>0>>>4,Ep=e=>~e&15;function Dp(e){let t=new Uint32Array(e.buffer,e.byteOffset,e.length),n=e.length/xp,r=e=>{let n=e*xp;return t[n+3]===vp&&t[n+1]>0&&t[n+1]<=bp},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*xp;t[n+3]>=yp||(r(t[n+7])||s.push(t[n+7]),r(t[n+3])||s.push(t[n+3]))}let c=new Float32Array(o*xp),l=new Uint32Array(c.buffer);for(let n=0;n<o;n++){let o=a[n]*xp,s=n*xp;c.set(e.subarray(o,o+xp),s),!(t[o+3]>=yp)&&(l[s+3]=Op(t,t[o+3],r,i),l[s+7]=Op(t,t[o+7],r,i))}return c}function Op(e,t,n,r){let i=t*xp;return n(t)?Cp(e[i],e[i+1]):r[t]}var kp=(e,t,n)=>e>=Sp?Cp(Tp(e)+n,Ep(e)):e+t;function Ap(e,t,n,r=0,i=e.length){for(let a=r;a<i;a+=xp){if(e[a+3]===vp){e[a]+=n;continue}e[a+3]=kp(e[a+3],t,n),e[a+7]=kp(e[a+7],t,n)}}jt();var jp=vt(`bvh`),Mp=1073741824,Np=1073741826,Pp=e=>new Uint32Array(e.buffer,e.byteOffset,e.length),Fp=1073741824;function Ip(e,t){if(e>=Fp)throw RangeError(`${t} is ${e}, at or past the BVH index limit of ${Fp}`);return e}var Lp=null;function Rp(e){Lp=e}var zp={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8},Bp=zp.FLOATS_PER_TRIANGLE,Vp=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),Hp=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}},Up=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,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0},this.enableTreeletOptimization=!1,this.treeletSize=5,this.treeletOptimizationPasses=1,this.treeletMinImprovement=.02,this.treeletComplexityThreshold=5e4,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)}setTreeletConfig(e){e.enabled!==void 0&&(this.enableTreeletOptimization=e.enabled),e.size!==void 0&&(this.treeletSize=Math.max(3,Math.min(12,e.size))),e.passes!==void 0&&(this.treeletOptimizationPasses=Math.max(1,Math.min(3,e.passes))),e.minImprovement!==void 0&&(this.treeletMinImprovement=Math.max(.001,e.minImprovement)),e.complexityThreshold!==void 0&&(this.treeletComplexityThreshold=e.complexityThreshold)}disableTreeletOptimization(){this.enableTreeletOptimization=!1}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=Vp(this.triangles),n=zp.POSITION_A_OFFSET,r=zp.POSITION_B_OFFSET,i=zp.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*Bp,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/(Bp*4),this.processedTriangles=0,this.lastProgressUpdate=performance.now(),this.useWorker&&Lp&&si()?new Promise((r,i)=>{let a=a=>{let o=this.totalTriangles,s=typeof SharedArrayBuffer<`u`;jp.debug(`SharedArrayBuffer ${s?`enabled`:`unavailable (using transfer fallback)`}`);let c=s?new SharedArrayBuffer(o*Bp*4):null;a.onmessage=e=>{let{bvhData:t,triangles:o,originalToBvh:s,error:l,progress:u,treeletStats: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,treeletOptimization:{enabled:this.enableTreeletOptimization,size:this.treeletSize,passes:this.treeletOptimizationPasses,minImprovement:this.treeletMinImprovement},reinsertionOptimization:{enabled:this.enableReinsertionOptimization,batchSizeRatio:this.reinsertionBatchSizeRatio,maxIterations:this.reinsertionMaxIterations}};a.postMessage(u,[l])};try{a(Lp())}catch(i){jp.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?Dp(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/(Bp*4),this.lastProgressUpdate=performance.now(),this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement: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.enableTreeletOptimization&&this.totalTriangles>1e3){let e=this.totalTriangles>this.treeletComplexityThreshold?3:this.treeletSize,t=new hp(this.traversalCost,this.intersectionCost);t.setTreeletSize(e),t.setMinImprovement(this.treeletMinImprovement);let r=performance.now();for(let e=0;e<this.treeletOptimizationPasses;e++){let i=n?t=>{n(`Treelet optimization pass ${e+1}/${this.treeletOptimizationPasses}: ${t}`)}:null;try{t.optimizeBVH(c,i)}catch(t){jp.error(`treelet optimizer failed in pass ${e+1}:`,t);break}let a=t.getStatistics(),o=performance.now()-r;if(a.treeletsImproved===0&&e>0||o>15e3)break}let i=performance.now()-r;this.splitStats.treeletOptimizationTime=i;let a=t.getStatistics();this.splitStats.treeletsProcessed=a.treeletsProcessed,this.splitStats.treeletsImproved=a.treeletsImproved,this.splitStats.averageSAHImprovement=a.averageSAHImprovement}if(this.enableReinsertionOptimization&&this.totalTriangles>1e3){let e=new _p(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){jp.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*Bp);for(let e=0;e<a;e++){let t=this.indices[e]*Bp,n=e*Bp;f.set(d.subarray(t,t+Bp),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 jp.debug(`${J.n(a)} tris → ${J.n(this.totalNodes)} nodes in ${J.ms(m)} | SAH ${h.sahSplits} objMed ${h.objectMedianSplits} spatMed ${h.spatialMedianSplits} failed ${h.failedSplits}`+(h.treeletsProcessed?` | treelets ${h.treeletsImproved}/${h.treeletsProcessed} improved`:``)+(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 Hp;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 Hp;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)}Ip(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=Pp(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]=Mp}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)}Ip(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=[],a=Pp(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]=Np,i.push({taskId:t,flatIndex:e})}else a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+3]=Mp}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;Ip(a,`assembled BLAS node count`);let o=new Float32Array(a*16),s=Pp(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]<Mp&&(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)}},Wp={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},Gp=Wp.FLOATS_PER_TRIANGLE,Kp=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),qp=e=>e instanceof Uint32Array?e:new Uint32Array(e.buffer,e.byteOffset,e.length),Jp=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:e,idx:t?e.viewAs(Uint32Array):qp(e)}},Yp=(e,t)=>e.chunked?e.f.chunkFor(t):e.f,Xp=(e,t)=>e.chunked?e.idx.chunkFor(t):e.idx,Zp=(e,t)=>e.chunked?e.chunked.baseOf(t):t*em,Qp=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:t?t.viewAs(Float32Array):Kp(e),u:t?e:qp(e)}};function $p(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}var em=16,tm=1073741824,nm=1073741825,rm=1e-12;function im(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)<=rm*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,ee=-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>ee&&(ee=c)}i[a]=P,i[a+1]=F,i[a+2]=I,i[a+3]=L,i[a+4]=R,i[a+5]=ee}function am(e,t,n,r,i){let a=Wp.POSITION_A_OFFSET,o=Wp.POSITION_B_OFFSET,s=Wp.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*Gp;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 om=new Float32Array(12);function sm(e,t,n,r){let i=Yp(e,t),a=Xp(e,t),o=Zp(e,t);if(a[o+3]===tm){am(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 cm(e,t,n,r,i){let a=Yp(e,t),o=Xp(e,t),s=Zp(e,t),c=(t-i)*6,l=o[s+3];if(l===tm){am(n,o[s],o[s+1],r,c);return}if(l===nm){im(a,s,r,(o[s]-i)*6,r,c);return}let u=o[s+7],d=r,f=(l-i)*6;wp(l)&&(am(n,Tp(l),Ep(l),om,0),d=om,f=0);let p=r,m=(u-i)*6;wp(u)&&(am(n,Tp(u),Ep(u),om,6),p=om,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 lm=class{constructor(){this._bounds=null,this._boundsNodeCount=0,this._tlasBounds=null,this._rootBox=null}updateTrianglePositions(e,t,n){let r=n.length,i=Qp(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*Gp,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+Wp.POSITION_A_OFFSET]=l,a[s+Wp.POSITION_A_OFFSET+1]=u,a[s+Wp.POSITION_A_OFFSET+2]=d,a[s+Wp.POSITION_B_OFFSET]=f,a[s+Wp.POSITION_B_OFFSET+1]=p,a[s+Wp.POSITION_B_OFFSET+2]=m,a[s+Wp.POSITION_C_OFFSET]=h,a[s+Wp.POSITION_C_OFFSET+1]=g,a[s+Wp.POSITION_C_OFFSET+2]=_;let v=f-l,y=p-u,b=m-d,x=h-l,S=g-u,C=_-d,w=$p(y*C-b*S,b*x-v*C,v*S-y*x);o[s+Wp.NORMAL_A_PACKED_OFFSET]=w,o[s+Wp.NORMAL_B_PACKED_OFFSET]=w,o[s+Wp.NORMAL_C_PACKED_OFFSET]=w}}refitRange(e,t,n,r){let i=Qp(t);r>this._boundsNodeCount&&(this._bounds=new Float32Array(r*6),this._boundsNodeCount=r);let a=Jp(e);for(let e=n+r-1;e>=n;e--)cm(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=Qp(t),a=Jp(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=Xp(a,e),n=Zp(a,e);t[n+3]===nm?(sm(a,t[n],i,s),im(Yp(a,e),n,s,0,o,e*6)):cm(a,e,i,o,0)}}refit(e,t,n){let r=Qp(t);n!==this._boundsNodeCount&&(this._bounds=new Float32Array(n*6),this._boundsNodeCount=n);let i=Jp(e);for(let e=n-1;e>=0;e--)cm(i,e,r,this._bounds,0)}},um="var e=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.maxTreeletLeaves=7,this.minImprovement=.02,this.topologyCache=new Map;for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.set(e,this.generateTopologies(e));this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0}}generateTopologies(e){if(e===1)return[0];if(e===2)return[[0,1]];let t=[];for(let n=1;n<e;n++){let r=this.generateTopologies(n),i=this.generateTopologies(e-n);for(let e of r)for(let r of i)t.push([e,this.offsetTopology(r,n)])}return t}offsetTopology(e,t){return typeof e==`number`?e+t:[this.offsetTopology(e[0],t),this.offsetTopology(e[1],t)]}optimizeBVH(e){let t=performance.now();this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0};let n=this.identifyTreeletRoots(e);for(let e=0;e<n.length;e++){if(performance.now()-t>3e4){console.warn(`TreeletOptimizer: timeout after ${e}/${n.length} treelets`);break}this.optimizeTreelet(n[e])}return this.stats.optimizationTime=performance.now()-t,this.stats.averageSAHImprovement=this.stats.treeletsProcessed>0?this.stats.totalSAHImprovement/this.stats.treeletsProcessed:0,e}identifyTreeletRoots(e){let t=[],n=new Set,r=[{node:e,visited:!1}];for(;r.length>0;){let e=r[r.length-1];if(e.visited){r.pop();let i=e.node;if(i.triangleCount>0||n.has(i))continue;let a=this.countLeaves(i);a>=3&&a<=this.maxTreeletLeaves&&(t.push(i),this.markSubtree(i,n))}else{e.visited=!0;let t=e.node;if(t.triangleCount>0)continue;t.rightChild&&r.push({node:t.rightChild,visited:!1}),t.leftChild&&r.push({node:t.leftChild,visited:!1})}}return t}countLeaves(e){return e?e.triangleCount>0?1:this.countLeaves(e.leftChild)+this.countLeaves(e.rightChild):0}markSubtree(e,t){e&&(t.add(e),!(e.triangleCount>0)&&(this.markSubtree(e.leftChild,t),this.markSubtree(e.rightChild,t)))}optimizeTreelet(e){let t=[];this.extractLeaves(e,t);let n=t.length;if(n<3||n>this.maxTreeletLeaves)return;this.stats.treeletsProcessed++;let r=this.evaluateSubtreeSAH(e),i=this.topologyCache.get(n);if(!i||i.length===0)return;let a=r,o=null,s=null;if(n<=5){let e=this.generatePermutations(n);for(let n of i)for(let r of e){let e=this.evaluateTopology(n,t,r);e<a&&(a=e,o=n,s=r)}}else{let e=Array.from({length:n},(e,t)=>t);for(let n of i){let r=this.evaluateTopology(n,t,e);r<a&&(a=r,o=n,s=e);let i=this.greedySwapOptimize(n,t,e,r);i.cost<a&&(a=i.cost,o=n,s=i.perm)}}let c=(r-a)/r;o&&c>this.minImprovement&&(this.reconstructTreelet(e,o,t,s),this.stats.treeletsImproved++,this.stats.totalSAHImprovement+=c)}extractLeaves(e,t){if(e){if(e.triangleCount>0){t.push({minX:e.minX,minY:e.minY,minZ:e.minZ,maxX:e.maxX,maxY:e.maxY,maxZ:e.maxZ,triangleOffset:e.triangleOffset,triangleCount:e.triangleCount});return}this.extractLeaves(e.leftChild,t),this.extractLeaves(e.rightChild,t)}}evaluateSubtreeSAH(e){if(!e)return 0;if(e.triangleCount>0)return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*e.triangleCount*this.intersectionCost;let t=this.evaluateSubtreeSAH(e.leftChild),n=this.evaluateSubtreeSAH(e.rightChild);return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*this.traversalCost+t+n}evaluateTopology(e,t,n){return this.evalTopoRecursive(e,t,n).cost}evalTopoRecursive(e,t,n){if(typeof e==`number`){let r=t[n[e]];return{cost:this.surfaceAreaFlat(r.minX,r.minY,r.minZ,r.maxX,r.maxY,r.maxZ)*r.triangleCount*this.intersectionCost,minX:r.minX,minY:r.minY,minZ:r.minZ,maxX:r.maxX,maxY:r.maxY,maxZ:r.maxZ}}let r=this.evalTopoRecursive(e[0],t,n),i=this.evalTopoRecursive(e[1],t,n),a=Math.min(r.minX,i.minX),o=Math.min(r.minY,i.minY),s=Math.min(r.minZ,i.minZ),c=Math.max(r.maxX,i.maxX),l=Math.max(r.maxY,i.maxY),u=Math.max(r.maxZ,i.maxZ);return{cost:this.surfaceAreaFlat(a,o,s,c,l,u)*this.traversalCost+r.cost+i.cost,minX:a,minY:o,minZ:s,maxX:c,maxY:l,maxZ:u}}surfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}generatePermutations(e){let t=[],n=Array.from({length:e},(e,t)=>t),r=i=>{if(i===e){t.push([...n]);return}for(let t=i;t<e;t++)[n[i],n[t]]=[n[t],n[i]],r(i+1),[n[i],n[t]]=[n[t],n[i]]};return r(0),t}greedySwapOptimize(e,t,n,r){let i=[...n],a=r,o=!0;for(;o;){o=!1;for(let n=0;n<i.length-1;n++)for(let r=n+1;r<i.length;r++){[i[n],i[r]]=[i[r],i[n]];let s=this.evaluateTopology(e,t,i);s<a?(a=s,o=!0):[i[n],i[r]]=[i[r],i[n]]}}return{perm:i,cost:a}}reconstructTreelet(e,t,n,r){let i=this.buildSubtree(t,n,r);e.minX=i.minX,e.minY=i.minY,e.minZ=i.minZ,e.maxX=i.maxX,e.maxY=i.maxY,e.maxZ=i.maxZ,e.leftChild=i.leftChild,e.rightChild=i.rightChild,e.triangleOffset=i.triangleOffset,e.triangleCount=i.triangleCount}buildSubtree(e,n,r){if(typeof e==`number`){let i=n[r[e]],a=new t;return a.minX=i.minX,a.minY=i.minY,a.minZ=i.minZ,a.maxX=i.maxX,a.maxY=i.maxY,a.maxZ=i.maxZ,a.triangleOffset=i.triangleOffset,a.triangleCount=i.triangleCount,a}let i=this.buildSubtree(e[0],n,r),a=this.buildSubtree(e[1],n,r),o=new t;return o.leftChild=i,o.rightChild=a,o.minX=Math.min(i.minX,a.minX),o.minY=Math.min(i.minY,a.minY),o.minZ=Math.min(i.minZ,a.minZ),o.maxX=Math.max(i.maxX,a.maxX),o.maxY=Math.max(i.maxY,a.maxY),o.maxZ=Math.max(i.maxZ,a.maxZ),o}setTreeletSize(e){this.maxTreeletLeaves=Math.max(3,Math.min(7,e));for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.has(e)||this.topologyCache.set(e,this.generateTopologies(e))}setMinImprovement(e){this.minImprovement=Math.max(.001,e)}getStatistics(){return{...this.stats}}},t=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(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 r={silent:0,error:1,warn:2,info:3,debug:4},i=`info`,a=`rayzeeLogLevel`,o=`rayzeeLogNamespaces`,s=`color:#7c8494`,c=`color:inherit`;let l=null,u=null;function d(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function f(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function p(){if(l!==null)return l;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in r?(l=r[e],l):(l=r[d(a)]??r[i],l)}function m(){if(u!==null)return u;let e=globalThis.__RAYZEE_LOG_NS__??d(o);return u=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],u}function h(e,t){if(t<r.debug)return!0;let n=m();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function g(e,t,n){if(e>p()||!h(t,e))return;let i=e===r.error?console.error:e===r.warn?console.warn:console.log,a=`[${t}]`;typeof n[0]==`string`?i(`%c${a}%c ${n[0]}`,s,c,...n.slice(1)):i(`%c${a}`,s,...n)}const _={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`)=>`${_.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},v={levels:r,setLevel(e){return e in r?(globalThis.__RAYZEE_LOG_LEVEL__=e,l=r[e],f(a,e===i?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(r).join(`, `)}`),this.getLevel())},getLevel(){let e=p();return Object.keys(r).find(t=>r[t]===e)},isEnabled(e){return(r[e]??r.debug)<=p()},only(...e){let t=e.flat().filter(Boolean);return u=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),f(o,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return l=null,u=null,this.getLevel()}};function y(e){return{namespace:e,error:(...t)=>g(r.error,e,t),warn:(...t)=>g(r.warn,e,t),info:(...t)=>g(r.info,e,t),debug:(...t)=>g(r.debug,e,t),isEnabled:e=>v.isEnabled(e),summary(t,n=[]){let i=n.filter(Boolean);if(i.length===0||!console.groupCollapsed){g(r.info,e,[t]),i.forEach(t=>g(r.debug,e,[t]));return}r.info>p()||((p()>=r.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,s,c),i.forEach(e=>console.log(e)),console.groupEnd())}}}function b(e){e&&e in r&&(globalThis.__RAYZEE_LOG_LEVEL__=e,l=r[e])}const x=1073741824,S=(e,t)=>~(e<<4|t)>>>0;function C(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]===1073741824&&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]>=x||(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]>=x)&&(l[s+3]=w(t,t[o+3],r,i),l[s+7]=w(t,t[o+7],r,i))}return c}function w(e,t,n,r){let i=t*16;return n(t)?S(e[i],e[i+1]):r[t]}const T=y(`bvh`),E=1073741824,D=e=>new Uint32Array(e.buffer,e.byteOffset,e.length),O=1073741824;function k(e,t){if(e>=O)throw RangeError(`${t} is ${e}, at or past the BVH index limit of ${O}`);return e}const A={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8},j=A.FLOATS_PER_TRIANGLE,M=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length);var N=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}},P=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,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0},this.enableTreeletOptimization=!1,this.treeletSize=5,this.treeletOptimizationPasses=1,this.treeletMinImprovement=.02,this.treeletComplexityThreshold=5e4,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)}setTreeletConfig(e){e.enabled!==void 0&&(this.enableTreeletOptimization=e.enabled),e.size!==void 0&&(this.treeletSize=Math.max(3,Math.min(12,e.size))),e.passes!==void 0&&(this.treeletOptimizationPasses=Math.max(1,Math.min(3,e.passes))),e.minImprovement!==void 0&&(this.treeletMinImprovement=Math.max(.001,e.minImprovement)),e.complexityThreshold!==void 0&&(this.treeletComplexityThreshold=e.complexityThreshold)}disableTreeletOptimization(){this.enableTreeletOptimization=!1}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=M(this.triangles),n=A.POSITION_A_OFFSET,r=A.POSITION_B_OFFSET,i=A.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*j,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/(j*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?C(i):i,bvhRoot:!0,reorderedTriangles:this.reorderedTriangleData||null,originalToBvh:this.originalToBvhMap||null}}buildSync(t,r=30,i=null,a=null){let o=performance.now();this.totalNodes=0,this.processedTriangles=0,this.triangles=t,this.totalTriangles=t.byteLength/(j*4),this.lastProgressUpdate=performance.now(),this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0,saOrderTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let s=this.totalTriangles,c=performance.now();this.centroids=new Float32Array(s*3),this.bMin=new Float32Array(s*3),this.bMax=new Float32Array(s*3),this.indices=new Uint32Array(s),this.mortonCodes=new Uint32Array(s),this.initializeTriangleArrays(),this.splitStats.initTime=performance.now()-c,this.sortTrianglesByMortonCode();let l=performance.now(),u=this.buildNodeRecursive(0,s,r,i);if(this.splitStats.sahBuildTime=performance.now()-l,this.enableTreeletOptimization&&this.totalTriangles>1e3){let t=this.totalTriangles>this.treeletComplexityThreshold?3:this.treeletSize,n=new e(this.traversalCost,this.intersectionCost);n.setTreeletSize(t),n.setMinImprovement(this.treeletMinImprovement);let r=performance.now();for(let e=0;e<this.treeletOptimizationPasses;e++){let t=i?t=>{i(`Treelet optimization pass ${e+1}/${this.treeletOptimizationPasses}: ${t}`)}:null;try{n.optimizeBVH(u,t)}catch(t){T.error(`treelet optimizer failed in pass ${e+1}:`,t);break}let a=n.getStatistics(),o=performance.now()-r;if(a.treeletsImproved===0&&e>0||o>15e3)break}let a=performance.now()-r;this.splitStats.treeletOptimizationTime=a;let o=n.getStatistics();this.splitStats.treeletsProcessed=o.treeletsProcessed,this.splitStats.treeletsImproved=o.treeletsImproved,this.splitStats.averageSAHImprovement=o.averageSAHImprovement}if(this.enableReinsertionOptimization&&this.totalTriangles>1e3){let e=new n(this.traversalCost,this.intersectionCost);e.setBatchSizeRatio(this.reinsertionBatchSizeRatio),e.setMaxIterations(this.reinsertionMaxIterations);let t=i?e=>{i(e)}:null;try{e.optimizeBVH(u,t)}catch(e){T.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 d=performance.now();this.applySAOrdering(u),this.splitStats.saOrderTime=performance.now()-d;let f=performance.now(),p=this.triangles,m=a||new p.constructor(s*j);for(let e=0;e<s;e++){let t=this.indices[e]*j,n=e*j;m.set(p.subarray(t,t+j),n)}this.reorderedTriangleData=m;let h=new Uint32Array(s);for(let e=0;e<s;e++)h[this.indices[e]]=e;this.originalToBvhMap=h,this.splitStats.reorderTime=performance.now()-f,this.splitStats.totalBuildTime=performance.now()-o;let g=this.splitStats.totalBuildTime,v=this.splitStats;return T.debug(`${_.n(s)} tris → ${_.n(this.totalNodes)} nodes in ${_.ms(g)} | SAH ${v.sahSplits} objMed ${v.objectMedianSplits} spatMed ${v.spatialMedianSplits} failed ${v.failedSplits}`+(v.treeletsProcessed?` | treelets ${v.treeletsImproved}/${v.treeletsProcessed} improved`:``)+(v.reinsertionsApplied?` | reinsertions ${v.reinsertionsApplied}`:``)),i&&i(100),this.centroids=null,this.bMin=null,this.bMax=null,this.mortonCodes=null,u}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 N;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 N;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)}k(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=D(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]=E}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)}k(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=[],a=D(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]=1073741826,i.push({taskId:t,flatIndex:e})}else a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+3]=E}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;k(a,`assembled BLAS node count`);let o=new Float32Array(a*16),s=D(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]<E&&(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 F=y(`bvh`);self.onmessage=function(e){let t=e.data,n=t.type;b(t.logLevel),n===`buildPhase1`?I(t):n===`assemble`?L(t):R(t)};function I(e){let{sharedTriangleData:t,sharedCentroids:n,sharedBMin:r,sharedBMax:i,sharedIndices:a,sharedMortonCodes:o,triangleCount:s,depth:c,parallelDepth:l,reportProgress:u,treeletOptimization:d}=e;try{let e=new P;d&&e.setTreeletConfig(d);let f=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,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,initTime:0,sahBuildTime:0,reorderTime:0};let p=performance.now(),m=performance.now();e.initializeTriangleArrays(),e.splitStats.initTime=performance.now()-m,e.sortTrianglesByMortonCode(),e.frontierTasks=[];let h=performance.now(),g=e.buildNodeRecursiveToDepth(0,s,c,l,f);e.splitStats.sahBuildTime=performance.now()-h,e.applySAOrdering(g);let v=performance.now(),{flatData:y,frontierMap:b,nodeCount:x}=e.flattenBVHWithFrontier(g),S=performance.now()-v,C=performance.now()-p;F.debug(`phase 1 ${_.ms(C)} (init ${_.ms(e.splitStats.initTime)} · morton ${_.ms(e.splitStats.mortonSortTime)} · SAH ${_.ms(e.splitStats.sahBuildTime)} · flatten ${_.ms(S)}) · ${e.frontierTasks.length} frontier tasks`),self.postMessage({type:`phase1Result`,topFlatData:y,topNodeCount:x,frontierTasks:e.frontierTasks,frontierMap:b,splitStats:e.splitStats},[y.buffer])}catch(e){F.error(`phase 1 failed:`,e),self.postMessage({type:`error`,error:e.message})}}function L(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 P().assembleParallelBVH(t,n,r,i),d=l?C(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;F.debug(`phase 3 assemble + reorder ${_.ms(m)} (${_.mb(d.byteLength)} BVH)`),self.postMessage({type:`assembleResult`,bvhData:d,originalToBvh:p,triangleCount:c},[d.buffer,p.buffer])}catch(e){F.error(`assembly failed:`,e),self.postMessage({type:`error`,error:e.message})}}function R(e){let{triangleData:t,triangleByteOffset:n,triangleByteLength:r,depth:i,reportProgress:a,treeletOptimization:o,reinsertionOptimization:s,sharedReorderBuffer:c,maxLeafSize:l,numBins:u,maxBins:d,minBins:f,foldLeaves:p}=e,m=new P;l!==void 0&&(m.maxLeafSize=l),u!==void 0&&(m.numBins=u),d!==void 0&&(m.maxBins=d),f!==void 0&&(m.minBins=f);try{o&&m.setTreeletConfig(o),s&&m.setReinsertionConfig(s);let e=a?e=>{self.postMessage({progress:e})}:null,l=n===void 0?new Uint32Array(t):new Uint32Array(t,n,r/4),u=c?new Uint32Array(c):null,d=m.buildSync(l,i,e,u),f=performance.now(),h=m.flattenBVH(d),g=p?C(h):h,v=performance.now()-f;F.debug(`flatten ${_.ms(v)} (${_.mb(g.byteLength)})`);let y=m.originalToBvhMap||null;if(c){let e=[g.buffer];y&&e.push(y.buffer),self.postMessage({bvhData:g,originalToBvh:y,triangleCount:l.length/20,treeletStats:m.splitStats},e)}else{let e=m.reorderedTriangleData,t=e.byteLength/80,n=[g.buffer,e.buffer];y&&n.push(y.buffer),self.postMessage({bvhData:g,triangles:e,originalToBvh:y,triangleCount:t,treeletStats:m.splitStats},n)}}catch(e){F.error(`build failed:`,e),self.postMessage({error:e.message})}}",dm=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,um],{type:`text/javascript;charset=utf-8`});function fm(e){let t;try{if(t=dm&&(self.URL||self.webkitURL).createObjectURL(dm),!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(um),{type:`module`,name:e?.name})}}var pm="var e=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.maxTreeletLeaves=7,this.minImprovement=.02,this.topologyCache=new Map;for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.set(e,this.generateTopologies(e));this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0}}generateTopologies(e){if(e===1)return[0];if(e===2)return[[0,1]];let t=[];for(let n=1;n<e;n++){let r=this.generateTopologies(n),i=this.generateTopologies(e-n);for(let e of r)for(let r of i)t.push([e,this.offsetTopology(r,n)])}return t}offsetTopology(e,t){return typeof e==`number`?e+t:[this.offsetTopology(e[0],t),this.offsetTopology(e[1],t)]}optimizeBVH(e){let t=performance.now();this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0};let n=this.identifyTreeletRoots(e);for(let e=0;e<n.length;e++){if(performance.now()-t>3e4){console.warn(`TreeletOptimizer: timeout after ${e}/${n.length} treelets`);break}this.optimizeTreelet(n[e])}return this.stats.optimizationTime=performance.now()-t,this.stats.averageSAHImprovement=this.stats.treeletsProcessed>0?this.stats.totalSAHImprovement/this.stats.treeletsProcessed:0,e}identifyTreeletRoots(e){let t=[],n=new Set,r=[{node:e,visited:!1}];for(;r.length>0;){let e=r[r.length-1];if(e.visited){r.pop();let i=e.node;if(i.triangleCount>0||n.has(i))continue;let a=this.countLeaves(i);a>=3&&a<=this.maxTreeletLeaves&&(t.push(i),this.markSubtree(i,n))}else{e.visited=!0;let t=e.node;if(t.triangleCount>0)continue;t.rightChild&&r.push({node:t.rightChild,visited:!1}),t.leftChild&&r.push({node:t.leftChild,visited:!1})}}return t}countLeaves(e){return e?e.triangleCount>0?1:this.countLeaves(e.leftChild)+this.countLeaves(e.rightChild):0}markSubtree(e,t){e&&(t.add(e),!(e.triangleCount>0)&&(this.markSubtree(e.leftChild,t),this.markSubtree(e.rightChild,t)))}optimizeTreelet(e){let t=[];this.extractLeaves(e,t);let n=t.length;if(n<3||n>this.maxTreeletLeaves)return;this.stats.treeletsProcessed++;let r=this.evaluateSubtreeSAH(e),i=this.topologyCache.get(n);if(!i||i.length===0)return;let a=r,o=null,s=null;if(n<=5){let e=this.generatePermutations(n);for(let n of i)for(let r of e){let e=this.evaluateTopology(n,t,r);e<a&&(a=e,o=n,s=r)}}else{let e=Array.from({length:n},(e,t)=>t);for(let n of i){let r=this.evaluateTopology(n,t,e);r<a&&(a=r,o=n,s=e);let i=this.greedySwapOptimize(n,t,e,r);i.cost<a&&(a=i.cost,o=n,s=i.perm)}}let c=(r-a)/r;o&&c>this.minImprovement&&(this.reconstructTreelet(e,o,t,s),this.stats.treeletsImproved++,this.stats.totalSAHImprovement+=c)}extractLeaves(e,t){if(e){if(e.triangleCount>0){t.push({minX:e.minX,minY:e.minY,minZ:e.minZ,maxX:e.maxX,maxY:e.maxY,maxZ:e.maxZ,triangleOffset:e.triangleOffset,triangleCount:e.triangleCount});return}this.extractLeaves(e.leftChild,t),this.extractLeaves(e.rightChild,t)}}evaluateSubtreeSAH(e){if(!e)return 0;if(e.triangleCount>0)return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*e.triangleCount*this.intersectionCost;let t=this.evaluateSubtreeSAH(e.leftChild),n=this.evaluateSubtreeSAH(e.rightChild);return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*this.traversalCost+t+n}evaluateTopology(e,t,n){return this.evalTopoRecursive(e,t,n).cost}evalTopoRecursive(e,t,n){if(typeof e==`number`){let r=t[n[e]];return{cost:this.surfaceAreaFlat(r.minX,r.minY,r.minZ,r.maxX,r.maxY,r.maxZ)*r.triangleCount*this.intersectionCost,minX:r.minX,minY:r.minY,minZ:r.minZ,maxX:r.maxX,maxY:r.maxY,maxZ:r.maxZ}}let r=this.evalTopoRecursive(e[0],t,n),i=this.evalTopoRecursive(e[1],t,n),a=Math.min(r.minX,i.minX),o=Math.min(r.minY,i.minY),s=Math.min(r.minZ,i.minZ),c=Math.max(r.maxX,i.maxX),l=Math.max(r.maxY,i.maxY),u=Math.max(r.maxZ,i.maxZ);return{cost:this.surfaceAreaFlat(a,o,s,c,l,u)*this.traversalCost+r.cost+i.cost,minX:a,minY:o,minZ:s,maxX:c,maxY:l,maxZ:u}}surfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}generatePermutations(e){let t=[],n=Array.from({length:e},(e,t)=>t),r=i=>{if(i===e){t.push([...n]);return}for(let t=i;t<e;t++)[n[i],n[t]]=[n[t],n[i]],r(i+1),[n[i],n[t]]=[n[t],n[i]]};return r(0),t}greedySwapOptimize(e,t,n,r){let i=[...n],a=r,o=!0;for(;o;){o=!1;for(let n=0;n<i.length-1;n++)for(let r=n+1;r<i.length;r++){[i[n],i[r]]=[i[r],i[n]];let s=this.evaluateTopology(e,t,i);s<a?(a=s,o=!0):[i[n],i[r]]=[i[r],i[n]]}}return{perm:i,cost:a}}reconstructTreelet(e,t,n,r){let i=this.buildSubtree(t,n,r);e.minX=i.minX,e.minY=i.minY,e.minZ=i.minZ,e.maxX=i.maxX,e.maxY=i.maxY,e.maxZ=i.maxZ,e.leftChild=i.leftChild,e.rightChild=i.rightChild,e.triangleOffset=i.triangleOffset,e.triangleCount=i.triangleCount}buildSubtree(e,n,r){if(typeof e==`number`){let i=n[r[e]],a=new t;return a.minX=i.minX,a.minY=i.minY,a.minZ=i.minZ,a.maxX=i.maxX,a.maxY=i.maxY,a.maxZ=i.maxZ,a.triangleOffset=i.triangleOffset,a.triangleCount=i.triangleCount,a}let i=this.buildSubtree(e[0],n,r),a=this.buildSubtree(e[1],n,r),o=new t;return o.leftChild=i,o.rightChild=a,o.minX=Math.min(i.minX,a.minX),o.minY=Math.min(i.minY,a.minY),o.minZ=Math.min(i.minZ,a.minZ),o.maxX=Math.max(i.maxX,a.maxX),o.maxY=Math.max(i.maxY,a.maxY),o.maxZ=Math.max(i.maxZ,a.maxZ),o}setTreeletSize(e){this.maxTreeletLeaves=Math.max(3,Math.min(7,e));for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.has(e)||this.topologyCache.set(e,this.generateTopologies(e))}setMinImprovement(e){this.minImprovement=Math.max(.001,e)}getStatistics(){return{...this.stats}}},t=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(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 r={silent:0,error:1,warn:2,info:3,debug:4},i=`info`,a=`rayzeeLogLevel`,o=`rayzeeLogNamespaces`,s=`color:#7c8494`,c=`color:inherit`;let l=null,u=null;function d(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function f(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function p(){if(l!==null)return l;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in r?(l=r[e],l):(l=r[d(a)]??r[i],l)}function m(){if(u!==null)return u;let e=globalThis.__RAYZEE_LOG_NS__??d(o);return u=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],u}function h(e,t){if(t<r.debug)return!0;let n=m();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function g(e,t,n){if(e>p()||!h(t,e))return;let i=e===r.error?console.error:e===r.warn?console.warn:console.log,a=`[${t}]`;typeof n[0]==`string`?i(`%c${a}%c ${n[0]}`,s,c,...n.slice(1)):i(`%c${a}`,s,...n)}const _={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`)=>`${_.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},v={levels:r,setLevel(e){return e in r?(globalThis.__RAYZEE_LOG_LEVEL__=e,l=r[e],f(a,e===i?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(r).join(`, `)}`),this.getLevel())},getLevel(){let e=p();return Object.keys(r).find(t=>r[t]===e)},isEnabled(e){return(r[e]??r.debug)<=p()},only(...e){let t=e.flat().filter(Boolean);return u=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),f(o,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return l=null,u=null,this.getLevel()}};function y(e){return{namespace:e,error:(...t)=>g(r.error,e,t),warn:(...t)=>g(r.warn,e,t),info:(...t)=>g(r.info,e,t),debug:(...t)=>g(r.debug,e,t),isEnabled:e=>v.isEnabled(e),summary(t,n=[]){let i=n.filter(Boolean);if(i.length===0||!console.groupCollapsed){g(r.info,e,[t]),i.forEach(t=>g(r.debug,e,[t]));return}r.info>p()||((p()>=r.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,s,c),i.forEach(e=>console.log(e)),console.groupEnd())}}}const b=1073741824,x=(e,t)=>~(e<<4|t)>>>0;function S(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]===1073741824&&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]>=b||(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]>=b)&&(l[s+3]=C(t,t[o+3],r,i),l[s+7]=C(t,t[o+7],r,i))}return c}function C(e,t,n,r){let i=t*16;return n(t)?x(e[i],e[i+1]):r[t]}const w=y(`bvh`),T=1073741824,E=e=>new Uint32Array(e.buffer,e.byteOffset,e.length),D=1073741824;function O(e,t){if(e>=D)throw RangeError(`${t} is ${e}, at or past the BVH index limit of ${D}`);return e}const k={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8},A=k.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,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0},this.enableTreeletOptimization=!1,this.treeletSize=5,this.treeletOptimizationPasses=1,this.treeletMinImprovement=.02,this.treeletComplexityThreshold=5e4,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)}setTreeletConfig(e){e.enabled!==void 0&&(this.enableTreeletOptimization=e.enabled),e.size!==void 0&&(this.treeletSize=Math.max(3,Math.min(12,e.size))),e.passes!==void 0&&(this.treeletOptimizationPasses=Math.max(1,Math.min(3,e.passes))),e.minImprovement!==void 0&&(this.treeletMinImprovement=Math.max(.001,e.minImprovement)),e.complexityThreshold!==void 0&&(this.treeletComplexityThreshold=e.complexityThreshold)}disableTreeletOptimization(){this.enableTreeletOptimization=!1}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=k.POSITION_A_OFFSET,r=k.POSITION_B_OFFSET,i=k.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?S(i):i,bvhRoot:!0,reorderedTriangles:this.reorderedTriangleData||null,originalToBvh:this.originalToBvhMap||null}}buildSync(t,r=30,i=null,a=null){let o=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,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0,saOrderTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let s=this.totalTriangles,c=performance.now();this.centroids=new Float32Array(s*3),this.bMin=new Float32Array(s*3),this.bMax=new Float32Array(s*3),this.indices=new Uint32Array(s),this.mortonCodes=new Uint32Array(s),this.initializeTriangleArrays(),this.splitStats.initTime=performance.now()-c,this.sortTrianglesByMortonCode();let l=performance.now(),u=this.buildNodeRecursive(0,s,r,i);if(this.splitStats.sahBuildTime=performance.now()-l,this.enableTreeletOptimization&&this.totalTriangles>1e3){let t=this.totalTriangles>this.treeletComplexityThreshold?3:this.treeletSize,n=new e(this.traversalCost,this.intersectionCost);n.setTreeletSize(t),n.setMinImprovement(this.treeletMinImprovement);let r=performance.now();for(let e=0;e<this.treeletOptimizationPasses;e++){let t=i?t=>{i(`Treelet optimization pass ${e+1}/${this.treeletOptimizationPasses}: ${t}`)}:null;try{n.optimizeBVH(u,t)}catch(t){w.error(`treelet optimizer failed in pass ${e+1}:`,t);break}let a=n.getStatistics(),o=performance.now()-r;if(a.treeletsImproved===0&&e>0||o>15e3)break}let a=performance.now()-r;this.splitStats.treeletOptimizationTime=a;let o=n.getStatistics();this.splitStats.treeletsProcessed=o.treeletsProcessed,this.splitStats.treeletsImproved=o.treeletsImproved,this.splitStats.averageSAHImprovement=o.averageSAHImprovement}if(this.enableReinsertionOptimization&&this.totalTriangles>1e3){let e=new n(this.traversalCost,this.intersectionCost);e.setBatchSizeRatio(this.reinsertionBatchSizeRatio),e.setMaxIterations(this.reinsertionMaxIterations);let t=i?e=>{i(e)}:null;try{e.optimizeBVH(u,t)}catch(e){w.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 d=performance.now();this.applySAOrdering(u),this.splitStats.saOrderTime=performance.now()-d;let f=performance.now(),p=this.triangles,m=a||new p.constructor(s*A);for(let e=0;e<s;e++){let t=this.indices[e]*A,n=e*A;m.set(p.subarray(t,t+A),n)}this.reorderedTriangleData=m;let h=new Uint32Array(s);for(let e=0;e<s;e++)h[this.indices[e]]=e;this.originalToBvhMap=h,this.splitStats.reorderTime=performance.now()-f,this.splitStats.totalBuildTime=performance.now()-o;let g=this.splitStats.totalBuildTime,v=this.splitStats;return w.debug(`${_.n(s)} tris → ${_.n(this.totalNodes)} nodes in ${_.ms(g)} | SAH ${v.sahSplits} objMed ${v.objectMedianSplits} spatMed ${v.spatialMedianSplits} failed ${v.failedSplits}`+(v.treeletsProcessed?` | treelets ${v.treeletsImproved}/${v.treeletsProcessed} improved`:``)+(v.reinsertionsApplied?` | reinsertions ${v.reinsertionsApplied}`:``)),i&&i(100),this.centroids=null,this.bMin=null,this.bMax=null,this.mortonCodes=null,u}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)}O(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=E(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]=T}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)}O(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=[],a=E(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]=1073741826,i.push({taskId:t,flatIndex:e})}else a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+3]=T}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;O(a,`assembled BLAS node count`);let o=new Float32Array(a*16),s=E(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]<T&&(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:r,sharedTriangleData:i,sharedCentroids:a,sharedBMin:o,sharedBMax:s,sharedIndices:c,triangleCount:l,maxLeafSize:u,numBins:d,maxBins:f,minBins:p,treeletConfig:m,reinsertionConfig:h,reportProgress:g}=t.data;for(let t=0;t<r.length;t++){let _=r[t];try{let t=new N;t.maxLeafSize=u,t.numBins=d,t.maxBins=f,t.minBins=p,t.triangles=new Float32Array(i),t.centroids=new Float32Array(a),t.bMin=new Float32Array(o),t.bMax=new Float32Array(s),t.indices=new Uint32Array(c),t.totalTriangles=l,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,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,initTime:0,sahBuildTime:0,reorderTime:0};let r=g?e=>{self.postMessage({type:`progress`,taskId:_.taskId,progress:e})}:null,v=performance.now(),y=t.buildNodeRecursive(_.start,_.end,_.depth,r,_.preMinX,_.preMinY,_.preMinZ,_.preMaxX,_.preMaxY,_.preMaxZ);if(m&&m.enabled&&_.end-_.start>1e3){let n=_.end-_.start>5e4,r=n?3:m.size||5,i=n?10:20,a=new e(t.traversalCost,t.intersectionCost);a.setTreeletSize(r),a.setMinImprovement(m.minImprovement||.02),a.setMaxTreelets(i);let o=m.passes||1;for(let e=0;e<o;e++)try{a.optimizeBVH(y,null)}catch(t){console.error(`[BVHSubtreeWorker] Treelet pass ${e+1} error:`,t);break}}if(h&&h.enabled&&_.end-_.start>1e3){let e=new n(t.traversalCost,t.intersectionCost);h.batchSizeRatio&&e.setBatchSizeRatio(h.batchSizeRatio),h.maxIterations&&e.setMaxIterations(h.maxIterations);try{e.optimizeBVH(y,null)}catch(e){console.error(`[BVHSubtreeWorker] Reinsertion error:`,e)}}t.applySAOrdering(y);let b=t.flattenBVH(y),x=b.length/16,S=performance.now()-v;console.log(`[BVHSubtreeWorker] Task ${_.taskId}: ${(_.end-_.start).toLocaleString()} triangles, ${x} nodes, ${Math.round(S)}ms`),self.postMessage({type:`subtreeResult`,taskId:_.taskId,flatData:b,nodeCount:x},[b.buffer])}catch(e){console.error(`[BVHSubtreeWorker] Task ${_.taskId} error:`,e),self.postMessage({type:`error`,taskId:_.taskId,error:e.message})}}};",mm=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,pm],{type:`text/javascript;charset=utf-8`});function hm(e){let t;try{if(t=mm&&(self.URL||self.webkitURL).createObjectURL(mm),!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(pm),{type:`module`,name:e?.name})}}jt(),Rp(()=>ci(fm));var gm=vt(`bvh`),_m=20,vm=5e4,ym=8;function bm(e,t,n,r){let i=e.byteLength/(_m*4),a=Math.min(oi(),ym),o=Math.ceil(Math.log2(a*2.5+1));return gm.debug(`parallel build ${J.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=ci(fm),_=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,gm.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(Sm(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,xm(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,treeletOptimization:r.treeletOptimization})})().catch(e=>{gm.warn(`parallel build setup failed:`,e),c(e)})})}async function xm(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){gm.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}gm.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=ci(hm);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,treeletConfig:g.treeletOptimization,reinsertionConfig:g.reinsertionOptimization,reportProgress:!!l})}}function Sm(e,t,n,r){return new Promise((i,a)=>{(async()=>{let o=ci(fm),s=e.byteLength/(_m*4),c=typeof SharedArrayBuffer<`u`?new SharedArrayBuffer(s*_m*4):null;o.onmessage=e=>{let{bvhData:t,triangles:r,originalToBvh:s,error:l,progress:u,treeletStats: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,treeletOptimization:r.treeletOptimization,reinsertionOptimization:r.reinsertionOptimization,foldLeaves:r.foldLeaves},[l])})().catch(e=>{gm.warn(`single worker fallback failed:`,e),a(e)})})}function Cm(e){return si()&&typeof SharedArrayBuffer<`u`&&e>=vm}var wm=Float64Array.from([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Tm(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 Em(e,t,n){let r=Tm(e,t);if(!Number.isFinite(r)||Math.abs(r)<1e-20)return n.set(wm),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 Dm(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 Om(e){for(let t=0;t<16;t++)if(e[t]!==wm[t])return!1;return!0}function km(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 Am(e,t){for(let n=0;n<16;n++)if(e[t+n]!==wm[n])return!1;return!0}var jm=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(wm,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]=+(Tm(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 Em(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}km(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}km(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||Je(e)[3]===Ke.TRIANGLE_LEAF){Mm(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){Mm(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,Ye(t,`combined TLAS + BLAS node count`)}get totalNodeCount(){return this.tlasNodeCount+this.totalBLASNodes}clear(){this.allocate(0),this.totalBLASNodes=0,this.tlasNodeCount=0}};function Mm(e,t,n,r,i){let a=W.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}var Nm=16,Pm=32,Fm=e=>e<Pm?e:Pm,Im=8,Lm=64,Rm=new Float64Array(16),zm=class e{constructor(){this._flatBuffer=null,this._flatBufferCapacity=0,this._binCounts=new Int32Array(Pm*3),this._binBounds=new Float64Array(Pm*6*3),this._binSuffix=new Float64Array(Pm),this._binSuffixCount=new Int32Array(Pm),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};Ye(r,`TLAS node count`);let i=r*Nm;i>this._flatBufferCapacity&&(this._flatBuffer=new Float32Array(i),this._flatBufferCapacity=i);let a=this._flatBuffer,o=Je(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(Lm);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*Nm;o[e]=0,o[e+1]=s[u],a[e+2]=0,o[e+3]=Ke.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*Nm;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=Je(t);for(let r=0;r<n;r++){let n=r*Nm;if(l[n+3]!==Ke.BLAS_POINTER_LEAF)continue;let u=l[n+1]&Ge;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=Rm;Em(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|(Am(r,i*16)?We: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<=Im)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=Fm(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)}},Bm=W.FLOATS_PER_TRIANGLE*4,Vm=64,Hm=.9,Um=64,Wm=4,Gm=7040*1024*1024,Km=9216*1024*1024;function qm(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}}var Jm=1.15,Ym=12*1024*1024*1024;function Xm({triangles:e,placements:t,geometryBytes:n=0}){let r={triangles:e*Bm,bvh:Math.ceil(e*Hm)*Vm,geometry:n,placements:t*Um,orderMaps:e*Wm};return r.total=r.triangles+r.bvh+r.geometry+r.placements+r.orderMaps,r}function Zm(e,{chunkBytes:t=vn,shared:n=!1,allocate:r=null}={}){let i=Math.min(e,Ym),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 Qm=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()}}},$m="let e,t;const n={MAX_TEXTURE_DIMENSION:8192,CHUNK_SIZE:8,ADAPTIVE_CHUNK_SIZE:!0,MEMORY_SAFETY_FACTOR:.8};let r=null;function i(e){if(e.stream===`begin`){let{width:t,height:n,depth:i}=e;r={width:t,height:n,depth:i,context:new OffscreenCanvas(t,n).getContext(`2d`,{willReadFrequently:!0,alpha:!0,desynchronized:!0}),data:new Uint8Array(t*n*i*4)};return}let{width:t,height:n,depth:i,context:a,data:o}=r;if(e.stream===`layer`){a.clearRect(0,0,t,n),a.drawImage(e.bitmap,0,0),e.bitmap.close(),o.set(a.getImageData(0,0,t,n).data,t*n*4*e.index),self.postMessage({stream:`ack`,index:e.index});return}r=null,self.postMessage({data:o.buffer,width:t,height:n,depth:i},[o.buffer])}async function a({shared:n,width:r,height:i,layers:a}){(e.width!==r||e.height!==i)&&(e.width=r,e.height=i),t.imageSmoothingEnabled=!0,t.imageSmoothingQuality=`high`;let o=new Uint8Array(n),s=r*i*4;for(let{index:e,texture:t}of a)try{await d(t,o,e*s,r,i)}catch(t){console.warn(`Failed to process texture ${e}:`,t),o.fill(0,e*s,(e+1)*s)}}self.onmessage=async function(t){if(t.data.shared){try{e||o(t.data.maxTextureSize),await a(t.data),self.postMessage({done:!0})}catch(e){self.postMessage({error:e.message})}return}if(t.data.stream){try{i(t.data)}catch(e){self.postMessage({error:e.message})}return}let{textures:n,maxTextureSize:r,method:c=`direct-transfer`}=t.data;try{e||o(r);let t=await s(n,r,c);self.postMessage(t,[t.data])}catch(e){console.error(`Worker processing failed:`,e),self.postMessage({error:e.message})}};function o(r){let i=Math.min(r,n.MAX_TEXTURE_DIMENSION);e=new OffscreenCanvas(i,i),t=e.getContext(`2d`,{willReadFrequently:!0,alpha:!0,desynchronized:!0})}async function s(e,t,n){switch(n){case`direct-transfer`:return await m(e,t);case`offscreen-optimized`:return await g(e,t);case`imageBitmap-batch`:return await _(e,t);default:return await m(e,t)}}async function c(e,t,n){let{maxWidth:r,maxHeight:i}=v(e,t),a=e.length,o=l(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 h(e,y(e,t),n)}let d=r*i*o*4,f;try{f=new Uint8Array(d)}catch{return console.warn(`Failed to allocate chunk buffer, reducing dimensions`),await h(e,y(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 u(e.slice(n,s),r,i,f.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 l(e,t,r){if(!n.ADAPTIVE_CHUNK_SIZE)return Math.min(n.CHUNK_SIZE,r);let i=e*t*4/(1024*1024),a;return a=i<=1?16:i<=4?8:i<=16?4:2,Math.min(a,r,n.CHUNK_SIZE*2)}async function u(n,r,i,a){(e.width!==r||e.height!==i)&&(e.width=r,e.height=i);let o=r*i*4;t.imageSmoothingEnabled=!0,t.imageSmoothingQuality=`high`;for(let e=0;e<n.length;e++){let t=n[e];try{await d(t,a,e*o,r,i)}catch(t){console.warn(`Failed to process texture ${e}:`,t);let n=e*o;a.fill(0,n,n+o)}}return{data:a.buffer,width:r,height:i,depth:n.length}}async function d(e,n,r,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`);t.clearRect(0,0,i,a),t.drawImage(o,0,0,i,a);let s=t.getImageData(0,0,i,a);n.set(s.data,r),(e.isImageData||e.isBlob)&&o.close()}async function f(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 f(e,i,a)}return await u(e,t,n,r)}async function p(e,t,n,r,i){await d(e,n,r*i*4*t,r,i)}async function m(n,r){let{maxWidth:i,maxHeight:a}=v(n,r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a);let o=n.length,s;try{s=new Uint8Array(i*a*o*4)}catch(e){return console.error(`Failed to allocate texture array:`,e),await c(n,r,`direct-transfer`)}t.imageSmoothingEnabled=!0,t.imageSmoothingQuality=`high`;for(let e=0;e<n.length;e++){let t=n[e];try{await p(t,e,s,i,a)}catch(t){console.warn(`Failed to process texture ${e}:`,t);let n=i*a*4*e;s.fill(0,n,n+i*a*4)}}return{data:s.buffer,width:i,height:a,depth:o}}async function h(e,t,n){let{maxWidth:r,maxHeight:i}=t;return console.log(`Using reduced dimensions: ${r}x${i}`),await f(e,r,i,n)}async function g(n,r){let{maxWidth:i,maxHeight:a}=v(n,r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a);let o=n.length,s;try{s=new Uint8Array(i*a*o*4)}catch(e){return console.error(`Failed to allocate texture array:`,e),await c(n,r,`offscreen-optimized`)}t.imageSmoothingEnabled=!0,t.imageSmoothingQuality=`high`;for(let e=0;e<n.length;e++){let r=n[e];try{let n;if(r.isBlob){let e=new Blob([r.data]);n=await createImageBitmap(e,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}else{let e=new ImageData(new Uint8ClampedArray(r.data),r.width,r.height);n=await createImageBitmap(e,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}t.clearRect(0,0,i,a),t.drawImage(n,0,0);let o=t.getImageData(0,0,i,a),c=i*a*4*e;s.set(o.data,c),n.close()}catch(t){console.warn(`Failed to process texture ${e}:`,t);let n=i*a*4*e;s.fill(0,n,n+i*a*4)}}return{data:s.buffer,width:i,height:a,depth:o}}async function _(n,r){let{maxWidth:i,maxHeight:a}=v(n,r),o=n.length,s;try{s=new Uint8Array(i*a*o*4)}catch(e){return console.error(`Failed to allocate texture array:`,e),await c(n,r,`imageBitmap-batch`)}let u=Math.min(l(i,a,n.length),n.length);for(let r=0;r<n.length;r+=u){let o=Math.min(r+u,n.length),c=[];for(let e=r;e<o;e++){let t=n[e],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`})}c.push(r.then(t=>({bitmap:t,index:e})))}let l=await Promise.all(c);e.width=i,e.height=a,t.imageSmoothingEnabled=!1;for(let{bitmap:e,index:n}of l){t.clearRect(0,0,i,a),t.drawImage(e,0,0);let r=t.getImageData(0,0,i,a),o=i*a*4*n;s.set(r.data,o),e.close()}}return{data:s.buffer,width:i,height:a,depth:o}}function v(e,t){let r=0,i=0;for(let t of e)r=Math.max(r,t.width||0),i=Math.max(i,t.height||0);let a=Math.min(t,n.MAX_TEXTURE_DIMENSION),o=Math.max(r,i);if(o>a){let e=a/o;r=Math.round(r*e),i=Math.round(i*e)}return r=Math.min(a,Math.max(4,Math.ceil(Math.max(1,r)/64)*64)),{maxWidth:r,maxHeight:Math.max(1,i)}}function y(e,t){let n=v(e,t);return{maxWidth:Math.max(64,Math.ceil(n.maxWidth/128)*64),maxHeight:Math.max(1,Math.floor(n.maxHeight/2))}}",eh=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,$m],{type:`text/javascript;charset=utf-8`});function th(e){let t;try{if(t=eh&&(self.URL||self.webkitURL).createObjectURL(eh),!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($m),{type:`module`,name:e?.name})}}var nh=`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})}};`,rh=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,nh],{type:`text/javascript;charset=utf-8`});function ih(e){let t;try{if(t=rh&&(self.URL||self.webkitURL).createObjectURL(rh),!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(nh),{type:`module`,name:e?.name})}}function ah({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)}}jl();var oh=e=>(t,n,r,i,a)=>e(t>0?t:0,n>0?n:0,r>0?r:0,i,a),sh=new Map;function ch(){sh.clear();for(let e of kl.values())sh.set(e.id,oh(e.cpu))}ch(),fl(ch);function lh(e){return pl(e)?.outputEncoded===!0}function uh(e){return e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055}function dh(e,t){let n=pl(t);return n?n.appliesExposure?e:1:t===r.NoToneMapping?1:e}var fh=.2126,ph=.7152,mh=.0722;function hh(e,t){if(t===1)return;let n=e[0]*fh+e[1]*ph+e[2]*mh;e[0]=n+(e[0]-n)*t,e[1]=n+(e[1]-n)*t,e[2]=n+(e[2]-n)*t}function gh(e,{exposure:t,toneMapping:n,saturation:i=1,preserveAlpha:a=!1}){let o=sh.get(n)??sh.get(r.NoToneMapping),s=dh(t,n),c=lh(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,hh(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]=uh(u[0])*255+.5,l[t+1]=uh(u[1])*255+.5,l[t+2]=uh(u[2])*255+.5),l[t+3]=a?e[t+3]*255+.5:255;return l}jt();var _h=vt(`textures`),vh=8*2**20,yh=16,bh=4,xh=8192*8192,Sh={busy:0,waiting:[]};async function Ch(){return Sh.busy<Math.max(1,oi()-1)?Sh.busy++:await new Promise(e=>Sh.waiting.push(e)),()=>{let e=Sh.waiting.shift();e?e():Sh.busy--}}var wh={toSRGB:null,toLinear:null};function Th(e){if(!wh[e]){let t=new Uint8Array(256);for(let n=0;n<256;n++){let r=n/255,i=e===`toSRGB`?uh(r):r<=.04045?r/12.92:((r+.055)/1.055)**2.4;t[n]=Math.max(0,Math.min(255,Math.round(i*255)))}wh[e]=t}return wh[e]}var Eh=class{constructor(){this.canvasContextPairs=[],this.maxPoolSize=Xe.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=[]}},Dh=class{constructor(e={}){this.pools=new Map,this.memoryUsage=0,this.maxMemoryUsage=e.maxMemory||dt.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*dt.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<Xe.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`}},Oh=class{constructor(e=Xe.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=[]}},kh=class{constructor(e={}){this.useWorkers=typeof Worker<`u`,this.maxConcurrentWorkers=Xe.MAX_CONCURRENT_WORKERS,this.activeWorkers=0,this._issues=e.issues??null,this.maxTextureSize=this._clampTextureSize(e.maxTextureSize??Xe.DEFAULT_MAX_TEXTURE_SIZE),this.canvasPool=new Eh,this.bufferPool=new Dh({maxMemory:e.maxBufferMemory||dt.MAX_BUFFER_MEMORY,sizeStrategy:e.bufferSizeStrategy||`adaptive`}),this.textureCache=new Oh,this.capabilities=this.detectCapabilities(),this.optimalMethod=this.selectOptimalMethod()}_reportTextureFailure(e,t){if(t instanceof gn)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)||Xe.DEFAULT_MAX_TEXTURE_SIZE);return Math.max(Xe.MIN_TEXTURE_WIDTH,Math.min(t,Xe.MAX_TEXTURE_SIZE))}setMaxTextureSize(e){let t=this._clampTextureSize(e);return t===this.maxTextureSize?t:(this.maxTextureSize=t,this.textureCache?.dispose(),this.textureCache=new Oh,this.maxTextureSize)}detectCapabilities(){return{offscreenCanvas:typeof OffscreenCanvas<`u`,imageBitmap:typeof createImageBitmap<`u`,workers:typeof Worker<`u`,hardwareConcurrency:oi()}}selectOptimalMethod(){return this.capabilities.workers&&this.capabilities.offscreenCanvas?`worker-offscreen`:this.capabilities.imageBitmap?`imageBitmap`:`canvas`}_applyColorManagement(e,t,n,i=new Set){let a=Au();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){_h.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,_h.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=Th(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?_h.info(`re-encoded ${l.length}/${o.length} linear-declared colour map(s) to sRGB so the GPU decode round-trips: ${u}`):_h.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=Au()?.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 gn)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>dt.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 th;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)<xh)return 0;let t=this.maxConcurrentWorkers-this.activeWorkers;return Math.max(0,Math.min(e.length,bh,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=ci(th);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=ci(th);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>=dt.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>yh&&(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=si()&&i*t.length>=vh?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)=>ah(e,o,t*i,n,r)),this.createDataArrayTextureFromBuffer(o,n,r,t.length)}async _packInWorker(e,t,n){let r=await Ch(),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=ci(ih),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%dt.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=G.FLOATS_PER_MATERIAL,n=new Float32Array(e.length*t);for(let r=0;r<e.length;r++)mn(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=Xe.VEC4_PER_BVH_NODE*Xe.FLOATS_PER_VEC4;Ye(t.length,`BVH node count`);let i=t.length*r,a=new Float32Array(i),o=Je(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]=Ke.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 Oh;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:Qe(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:Ah(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:Ah(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 Ah(e,t,n){let r=new Uint8ClampedArray(e.buffer,e.byteOffset,e.byteLength);return createImageBitmap(new ImageData(r,t,n))}var jh=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=Nh(E,Mh(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=Nh(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 Mh(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 Nh(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)}}jt();var Ph=Object.freeze({r:0,g:0,b:0});function Fh(e){if(!e)return Ph;if(!zr())return e;let t=[e.r,e.g,e.b];return Vr(t),{r:t[0],g:t[1],b:t[2]}}var Ih=vt(`emissive`),Lh=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=W.FLOATS_PER_TRIANGLE,a=W.MATERIAL_FLAGS_OFFSET,o=W.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]&Le,h=n[p+o],g=t[m];if(!g)continue;let _=d.get(g);_===void 0&&(_=Fh(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),R=(O-T)*(M-E)-(k-E)*(j-T),ee=Math.sqrt(I*I+L*L+R*R)||1,te=g.side===1?-1:1;I=I/ee*te,L=L/ee*te,R=R/ee*te;let ne=g.side===2,z=(T+O+j)/3,B=(E+k+M)/3,re=(D+A+N)/3,ie=Math.min(T,O,j),ae=Math.min(E,k,M),oe=Math.min(D,A,N),se=Math.max(T,O,j),ce=Math.max(E,k,M),le=Math.max(D,A,N);this.emissiveTriangles.push({triangleIndex:e,materialIndex:m,meshIndex:h,sideSign:te,instanceLeaf:n?r.tlasLeafIndex[t]:-1,power:F,area:P,emissive:{r:_.r,g:_.g,b:_.b},emissiveIntensity:v,cx:z,cy:B,cz:re,bMinX:ie,bMinY:ae,bMinZ:oe,bMaxX:se,bMaxY:ce,bMaxZ:le,nx:I,ny:L,nz:R,twoSided:ne}),this.totalEmissivePower+=F}}return this.emissiveCount=this.emissiveTriangles.length,this.emissiveCount>0&&Ih.debug(`${J.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=W.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,Ih.debug(`emissive texture ${J.px(t,n)} · ${J.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 Ih.debug(`emissive raw data ${J.n(this.emissiveCount)} entries (${J.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=Fh(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 jh().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,Ih.debug(`rebuilt sorted emissive data · ${J.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}};jt();var Rh=class{constructor(e=`Build`,{namespace:t=`build`,level:n=`debug`}={}){this.label=e,this.level=n,this.logger=vt(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=J.list([this.label,...e,J.ms(t)]);return this.level===`info`?this.logger.summary(r,n):this.logger.debug(J.list([r,n.join(` · `)])),{steps:Object.fromEntries(this.order.map(e=>[e,Math.round(this.entries.get(e)?.duration??0)])),total:Math.round(t)}}},zh=1<<20,Bh=1<<21,Vh=()=>new Promise(e=>setTimeout(e,0)),Hh=[0,1,2,4,5,6,8,9,10];function Uh(e,t,n,r=Hh){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 Wh(e,t){let n=[],r=0;for(let{triOffset:i,triCount:a}of t)n.push(Uh(e,i,a)),r+=a,r>=Bh&&(r=0,await Vh());return n}async function Gh(e,t){let n=await e?.area(qn.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 Kh(e,t,{index:n,bvh:r,orders:i,isStale:a,label:o=``}){let s=e?.area(qn.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,zh),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+=zh*4)await u.write(`order.u32`,e.subarray(t,Math.min(e.length,t+zh*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 qh(e,t,n,r){for(let i=0;i<r;i+=zh){let a=Math.min(zh,r-i),o=await e.slice(i*64,(i+a)*64).arrayBuffer();t.setRecords(n+i,new Float32Array(o))}}async function Jh(e,t,n){return new Uint32Array(await e.slice(t*4,(t+n)*4).arrayBuffer())}var Yh=16,Xh=W.POSITION_A_OFFSET,Zh=W.POSITION_B_OFFSET,Qh=W.POSITION_C_OFFSET;async function $h(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+Xh]+o[n+Zh]+o[n+Qh],c[r]=o[n+Xh+1]+o[n+Zh+1]+o[n+Qh+1],l[r]=o[n+Xh+2]+o[n+Zh+2]+o[n+Qh+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 tg(u,o,eg(o,e,t),e,t,n),{left:f(e,n),right:f(n,t)}},p=f(0,n);return await i?.(),await ng(e,t,n,u,i),{order:u,pieces:d,tree:p}}function eg(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 tg(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 ng(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 rg(e,t,n,r){let i=t.length-1,a=[],o=i;for(let{bvhData:e}of n)a.push(o),o+=e.length/Yh;let s=new Float32Array(i*Yh),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];Ap(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*Yh;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 ig=`9.4.2`,ag=1e4,og=15e5;function sg(e,t,n=ag){return e>=n&&t/og<e/3}var cg="const e=e=>e>=2147483648,t=e=>~e>>>0>>>4,n=e=>~e&15,r={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},i=r.FLOATS_PER_TRIANGLE,a=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),o=e=>e instanceof Uint32Array?e:new Uint32Array(e.buffer,e.byteOffset,e.length),s=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:e,idx:t?e.viewAs(Uint32Array):o(e)}},c=(e,t)=>e.chunked?e.f.chunkFor(t):e.f,l=(e,t)=>e.chunked?e.idx.chunkFor(t):e.idx,u=(e,t)=>e.chunked?e.chunked.baseOf(t):t*p,d=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:t?t.viewAs(Float32Array):a(e),u:t?e:o(e)}};function f(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 p=16,m=1073741824,h=1073741825;function g(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 _(e,t,n,a,o){let s=r.POSITION_A_OFFSET,c=r.POSITION_B_OFFSET,l=r.POSITION_C_OFFSET,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0;for(let r=0;r<n;r++){let n=t+r,a=e.chunked?e.f.chunkFor(n):e.f,o=e.chunked?e.chunked.baseOf(n):n*i;u=Math.min(u,a[o+s],a[o+c],a[o+l]),d=Math.min(d,a[o+s+1],a[o+c+1],a[o+l+1]),f=Math.min(f,a[o+s+2],a[o+c+2],a[o+l+2]),p=Math.max(p,a[o+s],a[o+c],a[o+l]),m=Math.max(m,a[o+s+1],a[o+c+1],a[o+l+1]),h=Math.max(h,a[o+s+2],a[o+c+2],a[o+l+2])}a[o]=u,a[o+1]=d,a[o+2]=f,a[o+3]=p,a[o+4]=m,a[o+5]=h}const v=new Float32Array(12);function y(e,t,n,r){let i=c(e,t),a=l(e,t),o=u(e,t);if(a[o+3]===m){_(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 b(r,i,a,o,s){let d=c(r,i),f=l(r,i),p=u(r,i),y=(i-s)*6,b=f[p+3];if(b===m){_(a,f[p],f[p+1],o,y);return}if(b===h){g(d,p,o,(f[p]-s)*6,o,y);return}let x=f[p+7],S=o,C=(b-s)*6;e(b)&&(_(a,t(b),n(b),v,0),S=v,C=0);let w=o,T=(x-s)*6;e(x)&&(_(a,t(x),n(x),v,6),w=v,T=6),d[p]=S[C],d[p+1]=S[C+1],d[p+2]=S[C+2],d[p+4]=S[C+3],d[p+5]=S[C+4],d[p+6]=S[C+5],d[p+8]=w[T],d[p+9]=w[T+1],d[p+10]=w[T+2],d[p+12]=w[T+3],d[p+13]=w[T+4],d[p+14]=w[T+5];for(let e=0;e<3;e++)o[y+e]=Math.min(S[C+e],w[T+e]),o[y+3+e]=Math.max(S[C+3+e],w[T+3+e])}var x=class{constructor(){this._bounds=null,this._boundsNodeCount=0,this._tlasBounds=null,this._rootBox=null}updateTrianglePositions(e,t,n){let a=n.length,o=d(e);for(let e=0;e<a;e++){let a=n[e],s=o.chunked?o.f.chunkFor(e):o.f,c=o.chunked?o.u.chunkFor(e):o.u,l=o.chunked?o.chunked.baseOf(e):e*i,u=a*9,d=t[u],p=t[u+1],m=t[u+2],h=t[u+3],g=t[u+4],_=t[u+5],v=t[u+6],y=t[u+7],b=t[u+8];s[l+r.POSITION_A_OFFSET]=d,s[l+r.POSITION_A_OFFSET+1]=p,s[l+r.POSITION_A_OFFSET+2]=m,s[l+r.POSITION_B_OFFSET]=h,s[l+r.POSITION_B_OFFSET+1]=g,s[l+r.POSITION_B_OFFSET+2]=_,s[l+r.POSITION_C_OFFSET]=v,s[l+r.POSITION_C_OFFSET+1]=y,s[l+r.POSITION_C_OFFSET+2]=b;let x=h-d,S=g-p,C=_-m,w=v-d,T=y-p,E=b-m,D=f(S*E-C*T,C*w-x*E,x*T-S*w);c[l+r.NORMAL_A_PACKED_OFFSET]=D,c[l+r.NORMAL_B_PACKED_OFFSET]=D,c[l+r.NORMAL_C_PACKED_OFFSET]=D}}refitRange(e,t,n,r){let i=d(t);r>this._boundsNodeCount&&(this._bounds=new Float32Array(r*6),this._boundsNodeCount=r);let a=s(e);for(let e=n+r-1;e>=n;e--)b(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=d(t),a=s(e);(!this._tlasBounds||this._tlasBounds.length<r*6)&&(this._tlasBounds=new Float32Array(r*6));let o=this._tlasBounds,f=this._rootBox||=new Float32Array(6);for(let e=r-1;e>=0;e--){let t=l(a,e),n=u(a,e);t[n+3]===h?(y(a,t[n],i,f),g(c(a,e),n,f,0,o,e*6)):b(a,e,i,o,0)}}refit(e,t,n){let r=d(t);n!==this._boundsNodeCount&&(this._bounds=new Float32Array(n*6),this._boundsNodeCount=n);let i=s(e);for(let e=n-1;e>=0;e--)b(i,e,r,this._bounds,0)}};const S=64*1024*1024;function C(e,t,n){return n?new e(new SharedArrayBuffer(t*e.BYTES_PER_ELEMENT)):new e(t)}var w=class e{constructor(e,t,n,r=S,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(C(n,e*t,i)),s-=e}this.chunks.length===0&&this.chunks.push(C(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=S,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]=C(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=C(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=C(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 T=new x;let E=null,D=null,O=0;self.onmessage=function(e){let{type:t}=e.data;if(t===`init`){E=w.adopt(e.data.sharedBvhBufs.map(e=>new Float32Array(e)),e.data.bvhRecordCount,16,e.data.bvhRecordsPerChunk),D=w.adopt(e.data.sharedTriBufs.map(e=>new Uint32Array(e)),e.data.triRecordCount,e.data.triLanesPerRecord,e.data.triRecordsPerChunk),O=E.recordCount;return}if(t===`refit`)try{let t=performance.now(),{blasRanges:n,tlasNodeCount:r}=e.data;n?T.refitPartial(E,D,n,r):T.refit(E,D,O),self.postMessage({type:`refitComplete`,refitTimeMs:performance.now()-t})}catch(e){console.error(`[BVHRefitWorker] Refit error:`,e),self.postMessage({type:`error`,error:e.message})}};",lg=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,cg],{type:`text/javascript;charset=utf-8`});function ug(e){let t;try{if(t=lg&&(self.URL||self.webkitURL).createObjectURL(lg),!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(cg),{type:`module`,name:e?.name})}}var dg="const e=Math.PI/180;function t(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 n({hours:n,dayOfYear:r,latitude:i}){let a=t(r),o=(n-12)*15*e,s=i*e,c=Math.sin(s)*Math.sin(a)+Math.cos(s)*Math.cos(a)*Math.cos(o),l=Math.asin(Math.min(1,Math.max(-1,c)))/e;return{azimuth:(Math.atan2(Math.sin(o),Math.cos(o)*Math.sin(s)-Math.tan(a)*Math.cos(s))/e+540)%360,elevation:l}}const r=e=>[0,31,59,90,120,151,181,212,243,273,304,334][e-1]+21,i=Object.freeze({time:10,month:3,latitude:40}),a=n({hours:i.time,dayOfYear:r(i.month),latitude:i.latitude}),o=Object.freeze({viewer:Object.freeze({areaLightIntensityScale:.1,environmentRotation:0,toneMapping:6,saturation:1,dofMode:`look`}),physical:Object.freeze({areaLightIntensityScale:1,environmentRotation:0,toneMapping:6,saturation:1,dofMode:`physical`})}),s={resolution:512,canvasWidth:512,canvasHeight:512,maxTextureSize:4096,toneMapping:o.viewer.toneMapping,exposure:1,saturation:o.viewer.saturation,enableEnvironment:!0,showBackground:!0,transparentBackground:!1,environmentIntensity:1,backgroundIntensity:1,backgroundColor:`#000000`,backgroundBlurriness:0,backgroundBlurSamples:8,environmentRotation:o.viewer.environmentRotation,groundProjectionEnabled:!1,groundProjectionRadius:100,groundProjectionHeight:15,groundProjectionLevel:0,enableGroundCatcher:!1,groundCatcherHeight:0,globalIlluminationIntensity:1,environmentMode:`hdri`,solidSkyColor:`#87CEEB`,skySunAzimuth:180-a.azimuth,skySunElevation:a.elevation,skySunStrength:1,skySunSize:.53,skyTurbidity:2,skyOzone:300,skyAirDensity:1,skyGroundAlbedo:`#959595`,skyAltitude:50,skyPreset:`clearDay`,cameraProjection:`perspective`,panoramaLonRange:[-180,180],panoramaLatRange:[-90,90],panoramaLevelHorizon:!0,enableDOF:!1,fov:55,focusDistance:.8,aperture:5.6,focalLength:50,apertureScale:1,anamorphicRatio:1,unitsPerMetre:1,dofMode:o.viewer.dofMode,dofBlur:.05,autoFocusMode:`auto`,afScreenPoint:{x:.5,y:.5},afSmoothingFactor:.15,enablePathTracer:!0,enableAccumulation:!0,pauseRendering:!1,maxSamples:60,bounces:3,transmissiveBounces:5,maxSubsurfaceSteps:8,maxTransparentBounces:32,useAdaptiveSampling:!0,noiseThreshold:.1,adaptiveMinSamples:8,adaptiveStopFraction:.9,usePixelFreeze:!0,pixelFreezeThreshold:.02,pixelFreezeStability:8,convergenceOverlay:!1,samplingTechnique:2,enableEmissiveTriangleSampling:!1,emissiveBoost:1,fireflyThreshold:3,shadowTerminatorOffset:.1,wavefrontSortMaterials:!0,renderLimitMode:`frames`,renderTimeLimit:30,renderMode:0,enableAlphaShadows:!1,tilesHelper:!0,showLightHelper:!1,directionalLightIntensity:0,directionalLightColor:`#ffffff`,directionalLightPosition:[1,1,1],directionalLightAngle:0,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,debugMode:0,debugThreshold:100,debugModel:0,enableBloom:!1,bloomStrength:.2,bloomRadius:.15,bloomThreshold:.85,interactionModeEnabled:!0,interactionRenderScale:.5,debugVisScale:100,denoiserStrategy:`none`,enableASVGF:!1,asvgfTemporalAlpha:.1,asvgfAtrousIterations:8,asvgfPhiColor:10,asvgfPhiNormal:128,asvgfPhiDepth:1,asvgfVarianceBoost:1,asvgfMaxAccumFrames:32,asvgfGradientStrength:1,asvgfGradientSigmaScale:2,asvgfGradientNoiseFloor:0,asvgfDebugMode:0,asvgfQualityPreset:`medium`,showAsvgfHeatmap:!1,nrdQualityPreset:`medium`,nrdDebugMode:0,autoExposure:!1,autoExposureKeyValue:.18,autoExposureMinExposure:.1,autoExposureMaxExposure:20,autoExposureAdaptSpeedBright:3,autoExposureAdaptSpeedDark:.5};Object.freeze({perspective:0,equirectangular:1,orthographic:2}),s.fov,s.focusDistance,s.aperture,s.focalLength,180-a.azimuth,a.elevation,c({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});function c(e){for(let t of Object.values(e))typeof t==`object`&&Object.freeze(t);return Object.freeze(e)}const l={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826};function u(e){return new Uint32Array(e.buffer,e.byteOffset,e.length)}function d(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}Math.min(typeof navigator<`u`&&navigator.hardwareConcurrency||4,6),s.maxSamples,s.bounces,s.renderMode,s.enableAlphaShadows,s.maxSubsurfaceSteps;const f=Float64Array.from([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function p(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 m(e,t,n){let r=p(e,t);if(!Number.isFinite(r)||Math.abs(r)<1e-20)return n.set(f),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 h(e,t){for(let n=0;n<16;n++)if(e[t+n]!==f[n])return!1;return!0}const g=e=>e<32?e:32,_=new Float64Array(16);var v=class e{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(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};d(r,`TLAS node count`);let i=r*16;i>this._flatBufferCapacity&&(this._flatBuffer=new Float32Array(i),this._flatBufferCapacity=i);let a=this._flatBuffer,o=u(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(64);let c=0,f=0,p=0,m=n,h=this._bounds;this._rangeBounds(t,s,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 e=f*16;o[e]=0,o[e+1]=s[p],a[e+2]=0,o[e+3]=l.BLAS_POINTER_LEAF}else{let e=this._partition(t,s,p,m,g,_,v,y,b,x),n=e-p,r=f+1,i=r+(n*2-1),l=f*16;a[l]=h[0],a[l+1]=h[1],a[l+2]=h[2],o[l+3]=r,a[l+4]=h[3],a[l+5]=h[4],a[l+6]=h[5],o[l+7]=i,a[l+8]=h[6],a[l+9]=h[7],a[l+10]=h[8],a[l+11]=0,a[l+12]=h[9],a[l+13]=h[10],a[l+14]=h[11],a[l+15]=0;let u=n<=m-e,d=u?0:6,S=u?6:0;c=this._push(c,u?i:r,u?e:p,u?m:e,h,S),f=u?r:i,u?m=e:p=e,g=h[d],_=h[d+1],v=h[d+2],y=h[d+3],b=h[d+4],x=h[d+5];continue}if(c===0)break;c--;let e=c*3,n=c*6;f=this._stackI[e],p=this._stackI[e+1],m=this._stackI[e+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: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,d=u(t);for(let r=0;r<n;r++){let n=r*16;if(d[n+3]!==l.BLAS_POINTER_LEAF)continue;let u=d[n+1]&1073741823;d[n]=o[a[u]],t[n+2]=+!!s[u],e.writeLeafMatrix(t,d,n,i,u),c[u]=r}}static writeLeafMatrix(e,t,n,r,i){let a=_;m(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|(h(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,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,_=-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>_&&(_=o)}let v=this._extent,y=this._cMin;v[0]=m-d,v[1]=h-f,v[2]=_-p,y[0]=d,y[1]=f,y[2]=p;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=g(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,d=0;for(let e=O-1;e>=1;e--){let u=(t+e)*6;w[u]<i&&(i=w[u]),w[u+1]<a&&(a=w[u+1]),w[u+2]<o&&(o=w[u+2]),w[u+3]>s&&(s=w[u+3]),w[u+4]>c&&(c=w[u+4]),w[u+5]>l&&(l=w[u+5]),d+=C[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,_=-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])/u;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 y={silent:0,error:1,warn:2,info:3,debug:4},b=`info`,x=`rayzeeLogLevel`,S=`rayzeeLogNamespaces`,C=`color:#7c8494`,w=`color:inherit`;let T=null,E=null;function D(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function O(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function k(){if(T!==null)return T;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in y?(T=y[e],T):(T=y[D(x)]??y[b],T)}function A(){if(E!==null)return E;let e=globalThis.__RAYZEE_LOG_NS__??D(S);return E=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],E}function j(e,t){if(t<y.debug)return!0;let n=A();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function M(e,t,n){if(e>k()||!j(t,e))return;let r=e===y.error?console.error:e===y.warn?console.warn:console.log,i=`[${t}]`;typeof n[0]==`string`?r(`%c${i}%c ${n[0]}`,C,w,...n.slice(1)):r(`%c${i}`,C,...n)}const N={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`)=>`${N.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},P={levels:y,setLevel(e){return e in y?(globalThis.__RAYZEE_LOG_LEVEL__=e,T=y[e],O(x,e===b?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(y).join(`, `)}`),this.getLevel())},getLevel(){let e=k();return Object.keys(y).find(t=>y[t]===e)},isEnabled(e){return(y[e]??y.debug)<=k()},only(...e){let t=e.flat().filter(Boolean);return E=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),O(S,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return T=null,E=null,this.getLevel()}};function F(e){return{namespace:e,error:(...t)=>M(y.error,e,t),warn:(...t)=>M(y.warn,e,t),info:(...t)=>M(y.info,e,t),debug:(...t)=>M(y.debug,e,t),isEnabled:e=>P.isEnabled(e),summary(t,n=[]){let r=n.filter(Boolean);if(r.length===0||!console.groupCollapsed){M(y.info,e,[t]),r.forEach(t=>M(y.debug,e,[t]));return}y.info>k()||((k()>=y.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,C,w),r.forEach(e=>console.log(e)),console.groupEnd())}}}function I(e){e&&e in y&&(globalThis.__RAYZEE_LOG_LEVEL__=e,T=y[e])}const L=F(`bvh`);self.onmessage=function(e){let{aabbs:t,count:n,logLevel:r}=e.data;I(r);try{let e=performance.now(),{data:r,nodeCount:i}=new v().buildStructure(new Float64Array(t),n);L.debug(`TLAS ${N.n(i)} nodes in ${N.ms(performance.now()-e)}`),self.postMessage({tlasData:r,nodeCount:i},[r.buffer])}catch(e){L.error(`TLAS build failed:`,e),self.postMessage({error:e.message})}};",fg=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,dg],{type:`text/javascript;charset=utf-8`});function pg(e){let t;try{if(t=fg&&(self.URL||self.webkitURL).createObjectURL(fg),!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(dg),{type:`module`,name:e?.name})}}jt(),$s();var mg=5e4,hg=2e5,gg=2e6,_g=1<<19,vg=4e7,yg=1.5*1024**3,bg=256*1024*1024,xg=vt(`scene`),Sg=e=>Array.isArray(e)?e:[e],Cg=e=>Sg(e).reduce((e,t)=>e+t.byteLength,0),wg=64*1024*1024;async function Tg(e,t,n){for(let r of Sg(n))await e.writeAt(t,r),t+=r.byteLength}function Eg(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 Dg=class{constructor(e={}){this.config={useWorkers:!0,bvhDepth:30,maxLeafSize:4,verbose:!1,useFloat32Array:!0,textureQuality:`adaptive`,maxTextureSize:Xe.DEFAULT_MAX_TEXTURE_SIZE,enableTextureCache:!0,maxConcurrentTextureTasks:Math.min(oi(),6),maxSceneBytes:Km,enableTreeletOptimization:!1,treeletSize:7,treeletOptimizationPasses:1,treeletMinImprovement:.01,treeletComplexityThreshold:5e4,sceneCache:!0,sceneCacheMinBuildMs:ag,...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.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 Qm,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 Fr({issues:this.config.issues}),this.bvhBuilder=new Up,this.bvhBuilder.maxLeafSize=this.config.maxLeafSize,this.bvhBuilder.setTreeletConfig({enabled:this.config.enableTreeletOptimization,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold}),this.textureCreator=new kh({maxTextureSize:this.config.maxTextureSize,issues:this.config.issues}),this.emissiveTriangleBuilder=new Lh,this.tlasBuilder=new zm,this._tlasWorker=null,this._tlasWorkerFailed=!1}_log(e,t){t===void 0?xg.debug(e):xg.debug(e,t)}_preflightMemory(e){let t=this.config.maxSceneBytes??9663676416,n=this.geometryExtractor.surveyScene(e),r=Xm(n);if(this._progressive&&(r.total-=r.bvh),this._streaming){let t=yg+Eg(e)*(W.FLOATS_PER_TRIANGLE*4+44);r.total-=Math.max(0,r.triangles-t)}let i={...n,estimate:r,safeBytes:Gm,maxBytes:t,fits:r.total<=Gm};if(this.memoryPreflight=i,r.total<1610612736)return i;if(xg.debug(J.list([`memory preflight: ${J.mb(r.total)} estimated`,`triangles ${J.mb(r.triangles)} · bvh ${J.mb(r.bvh)} · geometry ${J.mb(r.geometry)}`,`${J.n(n.triangles)} tris · ${J.n(n.placements)} placements`])),r.total>t){let e=`Scene needs about ${J.mb(r.total)} of CPU memory, past the ${J.mb(t)} a browser tab can hold — loading it would crash the tab rather than fail. Reduce the scene (it has ${J.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 ${J.mb(r.total)} of CPU memory, above the ${J.mb(Gm)} 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:Gm}),i}_checkAssemblyHeadroom(e){let t=e*64;if(t<1610612736)return!0;let n=Zm(Math.ceil(t*Jm),{shared:yn});return this.memoryPreflight&&(this.memoryPreflight.assemblyProbed=n.placed),n.exhausted&&this.config.issues?.warn(Y.SCENE_MEMORY_BUDGET,`BVH assembly needs ${J.mb(t)} but only ${J.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?Cg(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} ${J.mb(n[e].allocated)}`),i=this.memoryPreflight?.estimate?.total;xg.debug(J.list([`memory: peak live ${J.mb(t)}`,`allocated ${J.mb(e)}`,i?`predicted ${J.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,xn(e=>this.memory.alloc(e));let r=new Rh(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/(W.FLOATS_PER_TRIANGLE*4)),this._foldLeaves=i>vg,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=kr(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=>xg.debug(`storing BLASes failed:`,e))),this}catch(e){throw this.processingStage=`error`,xg.error(`processing failed:`,e),z({status:`Error: ${e.message}`,failed:!0,progress:100}),e}finally{this._disposeGeometrySpill(),xn(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 xg.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=Cn.lazy(o,W.FLOATS_PER_TRIANGLE,Uint32Array),c=s.recordsPerChunk*s.lanesPerRecord*4,l=await mr.create(r,`${a}:tri`,c,{label:`Triangle records`,expectedBytes:o*c/s.recordsPerChunk}),u=l&&await mr.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 br.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);jm.rootAABB(Sg(r)[0],v,t.start,t.count,i,0),p.set(e,{result:n,aabb:i});let a=f.blasBytes;f.blasBytes+=Cg(r),f.blasAt.set(e,a),n.nodeCount=Cg(r)/64,n.bvhData=null,this._queueSpill(f,()=>Tg(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>bg&&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>yg&&(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),xg.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=Ye(e.triangleCount,`triangle count`),this._foldLeaves&&this.triangleCount>134217728)throw RangeError(`${this.triangleCount.toLocaleString()} triangles is past the ${qe.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.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 jm,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(_,zm.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,treeletsImproved:0,treeletsProcessed: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,T.treeletsImproved+=i.treeletsImproved??0,T.treeletsProcessed+=i.treeletsProcessed??0,this.performanceMetrics.blasWorkerTime+=i.totalBuildTime??0),this.instanceTable.setEntry({meshIndex:e,blasNodeCount:r.nodeCount??Cg(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(zm.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(Cn.lazy(O,16,Float32Array,void 0,yn));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 qh(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 Sg(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;xg.debug(J.list([`${J.n(D.setCount)} BLASes + TLAS`,`${J.n(this.bvh.recordCount)} nodes`,`SAH ${J.n(T.sah)} · objMed ${T.objMed} · spatMed ${T.spatMed} · failed ${T.failed}`,T.treeletsProcessed?`treelets ${T.treeletsImproved}/${T.treeletsProcessed} improved`:null,J.ms(N)])),z({status:`BVH construction complete`,progress:75})}catch(e){throw xg.error(`BVH build failed:`,e),z({status:`BVH error: ${e.message}`,failed:!0,progress:75}),e}}_blasWorkerOpts(){return{depth:this.config.bvhDepth,treeletOptimization:{enabled:this.config.enableTreeletOptimization!==!1,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold},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:bt()}}_isLargeMesh(e){return e.count>=hg&&Cm(e.count)}async _buildLargeBLAS(e,t){if(e.count>gg)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 bm(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 $h(n,e.start,e.count,_g,{pause:()=>new Promise(e=>setTimeout(e,0))}),o=this._blasPool(t,null,null,Math.min(oi(),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),jm.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{...rg(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:${ig}:${JSON.stringify(t)}:${n}:${this._sceneKey}`}async _restoreBLASes(e,t,n){if(!this._sceneKey||this.config.sceneCache===!1)return null;let r=zu(Xs().cacheNamespace);if(!r)return null;this._blasKey=this._blasCacheKey(n);let i=await Gh(r,this._blasKey);if(!i)return null;let a=e=>(xg.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 Wh(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 Jh(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},xg.debug(`restored ${J.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=zu(Xs().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 Wh(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 Kh(t,r,{index:{v:2,tlasNodeCount:n.tlasNodeCount,totalNodes:n.totalNodeCount,templates:d},bvh:this.bvh,orders:u,isStale:a,label:e});return f&&xg.debug(`stored ${J.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 mr.create(t,`${i}:tri`,a,{label:`Triangle records`,expectedBytes:r.byteLength}),s=o&&await mr.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(Sg(a)[0],t,this.triangles,i.tplObjectAABB,t*6);let o=e.blasBytes;e.blasBytes+=Cg(a),e.blasAt.set(t,o),r.nodeCount=Cg(a)/64,r.bvhData=null,this._queueSpill(e,()=>Tg(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=W.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+=wg)i.push(new Float32Array(await e.blasStore.readAt(n+t,Math.min(wg,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 mr.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);Ap(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,o=i<=500?{...e.treeletOptimization,enabled:!1}:e.treeletOptimization;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,treeletOptimization:o,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.treeletStats||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=ci(fm);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 xg.error(`texture creation failed:`,e),e}}_bucketTextures(){let e=this.config.maxTextureSize,t=Xe.MATERIAL_BUCKET_COUNT,n=Xe.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],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],o=it(r(i),e,t),s=it(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=at(e.image.width,e.image.height,a),s=e.source?.uuid??e.uuid,c=r[o].get(s);if(c!==void 0)return ot(o,c);if(t[o].length>=n)return xg.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=ot(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)}}}_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)}_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.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){xg.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 xg.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.bvhBuilder.setTreeletConfig({enabled:this.config.enableTreeletOptimization,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold})),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=Cn.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||=ci(ug),!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=W.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 lm;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?(Dm(s,c,e*16,r),n.setPlacementMatrix(t,r)):l?(Dm(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||zm.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=W.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)):xg.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):(xg.error(`failed to get BVH data`),!1)):(xg.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 mr.create(e,`${a}:tri`,o(t),{label:`Triangle records`,expectedBytes:t.byteLength}),c=s&&await mr.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 xg.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=kr(e),xg.info(`read ${J.mb(r)} of scene geometry back from disk in ${J.ms(performance.now()-n)}`),t.error&&xg.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>=mg&&!this._tlasWorkerFailed)try{let n=new Float64Array(t*6);e.writeWorldAABBs(n);let{tlasData:r,nodeCount:i}=await this._runTLASWorker(n,t);return zm.fillLeaves(r,i,e),r}catch(e){this._tlasWorkerFailed=!0,xg.warn(`TLAS worker unavailable (${e.message}); building on the main thread`)}return this.tlasBuilder.build(e).data}_runTLASWorker(e,t){this._tlasWorker||=ci(pg);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:bt()},[e.buffer])})}_setBVHData(e){this._tlasLeafBoxesOf=null;let t=e?e instanceof Cn?e:Cn.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=W.FLOATS_PER_TRIANGLE,n=e?e instanceof Cn?e:Cn.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=W.POSITION_A_OFFSET,r=W.POSITION_B_OFFSET,i=W.POSITION_C_OFFSET,a=W.NORMAL_A_PACKED_OFFSET,o=W.NORMAL_B_PACKED_OFFSET,s=W.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=Om(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=Be(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=W.NORMAL_A_PACKED_OFFSET,o=W.NORMAL_B_PACKED_OFFSET,s=W.NORMAL_C_PACKED_OFFSET,c=r,l=!c||Om(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]]=Be(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===Ke.BLAS_POINTER_LEAF){let a=t[o+1]&Ge;a<n.count&&!(r&&!e[a])&&n.writeWorldAABB(a,this._tlasBounds,i*6)}else if(s<Ke.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){xg.error(`background BLAS rebuild failed (mesh ${e}):`,o.error);return}n===this._rebuildGeneration&&this._swapBLAS(e,r,o,t)},i.onerror=t=>{xg.error(`background BLAS rebuild worker failed (mesh ${e}):`,t),i.terminate(),this._pendingRebuilds.delete(e)};let o=r.triCount>500;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,treeletOptimization:{enabled:o,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold},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,ci(fm))}}_swapBLAS(e,t,n,r){this._geometryVersion=(this._geometryVersion??0)+1;let i=n.bvhData,a=i.length/16;if(a>t.blasNodeCount){xg.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}},Og=[[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]],kg=[[-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]],Ag=[[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 jg(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=Og[i],o=kg[i],s=Ag[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)]}var Mg=1/(4*Math.PI);function Ng(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]=jg(t.temperature??6500);i[0]*=e,i[1]*=n,i[2]*=r}return Vr(i),{r:i[0],g:i[1],b:i[2],intensity:r}}var Pg=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=Ng(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=Ng(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=Ng(e);this.pointLightCache.push({data:[t.x,t.y,t.z,i.r,i.g,i.b,i.intensity*Mg,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=Ng(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*Mg,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}))}}};jt();var Fg=1<<18,Ig=vt(`pathtracer`),Lg=100,Rg=4,zg=class extends P{constructor(e,t,n,i={}){super(`PathTracer`,{...i,executionMode:N.ALWAYS});let a=i.width||1920,o=i.height||1080;this.camera=n,this.width=a,this.height=o,this.renderer=e,this.scene=t,this.sdfs=new Dg,this.lightSerializer=new Pg,this.accumulationEnabled=!0,this.isComplete=!1,this.cameras=[],this.performanceMonitor=fe(),this.completionThreshold=0,this.renderLimitMode=`frames`,this._initDataTextures(),this.storageTextures=new Ft(0,0),this.uniforms=new on(a,o),this._defineUniformGetters(),this.materialData=new $r(this.sdfs),this.materialData.callbacks.onReset=()=>this.reset(),this.materialData.callbacks.getTriangleData=()=>({array:this._triangleFlat,records:this._triangleRecords,count:this.triangleCount}),this.materialData.callbacks.onTriangleDataChanged=()=>{this.triangleShadeAttr&&this._uploadTriangles(0,this._triangleRecordCount,{geo:!1})},this.environment=new Qu(this.scene,this.uniforms,this.renderer),this.environment.callbacks.onReset=()=>this.reset(),this.environment.callbacks.getSceneTextureNodes=()=>this.shaderBuilder.getSceneTextureNodes(),this.shaderBuilder=new mp,this._initRenderingState(),this.tempVector2=new r.Vector2,this.lastCameraMatrix=new r.Matrix4,this.lastProjectionMatrix=new r.Matrix4,this._seedTick=0,this._pinSeedToFrame=!1,this.tracedFrames=0,this.resetCount=0,this.lastRenderMode=-1,this.renderModeChangeTimeout=null,this.renderModeChangeDelay=50,this.pendingRenderMode=null,this.lastInteractionModeState=!1,this.cameraChanged=!1,this._lastViewChangeAt=-1/0,this.updateCompletionThreshold()}_initDataTextures(){this.triangleGeoAttr=null,this.triangleShadeAttr=null,this._triangleRecords=null,this._triangleFlat=null,this._triangleRecordCount=0,this.triangleStorageNode=null,this.triangleCount=0,this.bvhStorageAttr=null,this._bvhRecords=null,this.bvhStorageNode=null,this.bvhNodeCount=0,this.directionalLightsData=null,this.pointLightsData=null,this.spotLightsData=null,this.areaLightsData=null,this.goboMaps=null,this.iesProfiles=null,this.blueNoiseReady=Promise.resolve(),this.lightStorageAttr=new t.StorageInstancedBufferAttribute(new Float32Array(16),4),this.lightStorageNode=(0,n.storage)(this.lightStorageAttr,`vec4`,1).toReadOnly(),this._lightBufferRealloc=!1,this._lbvhDataCache=null,this._emissiveDataCache=null,this._bitTrailMapCache=null,this._bitTrailOffset=0,this._bitTrailLength=0,this._instanceTable=null,this.spheres=[]}_defineUniformGetters(){let e=this.uniforms;for(let t of e.keys())Object.defineProperty(this,t,{get:()=>e.get(t),configurable:!0});let t=e.getLightBufferNodes();for(let[e,n]of Object.entries(t))Object.defineProperty(this,`${e}LightsBufferNode`,{get:()=>n,configurable:!0})}_initRenderingState(){this.isReady=!1,this.frameCount=0}_initCameraOptimizer(){let e=this;this.cameraOptimizer=new F(this.renderer,{uniforms:{enableAccumulation:{get value(){return e.enableAccumulation.value},set value(t){e.enableAccumulation.value=t}},fireflyThreshold:{get value(){return e.fireflyThreshold.value},set value(t){e.fireflyThreshold.value=t}},cameraIsMoving:{get value(){return e.cameraIsMoving.value},set value(t){e.cameraIsMoving.value=t}}}},{enabled:V.interactionModeEnabled,qualitySettings:{enableAccumulation:!1,fireflyThreshold:e=>e*8},onEnter:()=>this.emit(`pathtracer:interactionStart`),onExit:()=>this.emit(`pathtracer:interactionEnd`),onReset:()=>{this.reset(),this.emit(`pathtracer:viewpointChanged`)}})}setupEventListeners(){this.on(`pipeline:reset`,()=>{this.reset()}),this.on(`pipeline:resize`,e=>{e&&e.width&&e.height&&this.setSize(e.width,e.height)}),this.on(`pathtracer:setCompletionThreshold`,e=>{e&&e.threshold!==void 0&&(this.completionThreshold=e.threshold)})}async build(e){this.dispose(),this.scene=e,await this.sdfs.buildBVH(e),this.cameras=this.sdfs.cameras,this.updateSceneUniforms(),this.updateLights(),this._initCameraOptimizer(),this.setupMaterial()}updateSceneUniforms(){this.setTriangleData(this.sdfs.triangleData,this.sdfs.triangleCount),this.setBVHData(this.sdfs.bvhData),this.setInstanceTable(this.sdfs.instanceTable),this.materialData.setMaterialData(this.sdfs.materialData,this.sdfs.materials?.map(e=>e.sources)),this.materialData.loadTexturesFromSdfs(),this.sdfs.emissiveTriangleData?this.setEmissiveTriangleData(this.sdfs.emissiveTriangleData,this.sdfs.emissiveTriangleCount||0):this.emissiveTriangleCount.value=0,this.sdfs.lightBVHNodeData?this.setLightBVHData(this.sdfs.lightBVHNodeData,this.sdfs.lightBVHNodeCount||0):this.lightBVHNodeCount.value=0,this._meshRefs=this._collectMeshRefs(this.scene),this.setMeshVisibilityData(this._meshRefs),this.spheres=this.sdfs.spheres||[]}updateLights(){let e={uniforms:{directionalLights:{value:null},pointLights:{value:null},spotLights:{value:null},areaLights:{value:null}},defines:{}};this.lightSerializer.processSceneLights(this.scene,e),this.directionalLightsData=e.uniforms.directionalLights.value,this.pointLightsData=e.uniforms.pointLights.value,this.spotLightsData=e.uniforms.spotLights.value,this.areaLightsData=e.uniforms.areaLights.value,this._updateLightBufferNodes()}_updateLightBufferNodes(){this._writeLightList(`directional`,this.directionalLightsData,this.numDirectionalLights),this._writeLightList(`area`,this.areaLightsData,this.numAreaLights),this._writeLightList(`point`,this.pointLightsData,this.numPointLights),this._writeLightList(`spot`,this.spotLightsData,this.numSpotLights)}_writeLightList(e,t,n){let r=nn[e],i=this[`${e}LightsBufferNode`],a=t?Math.floor(t.length/r):0,o=a*r;o>i.array.length&&(i.array=new Float32Array(an(e,a)*r),this._lightBufferRealloc=!0),o>0&&i.array.set(t.subarray(0,o)),i.array.fill(0,o),n.value=a}reset(){this.resetCount++,this.frameCount=0,this.frame.value=0,this.hasPreviousAccumulated.value=0,this.storageTextures.currentTarget=0,this.updateCompletionThreshold(),this.isComplete=!1,this.performanceMonitor?.reset(),this.lastInteractionModeState=!1,(this._pinSeedToFrame||this._lockstep)&&(this._seedTick=0),this._accumulationLockstep=!!this._lockstep}setSize(e,t){this.width=e,this.height=t,this.resolution.value.set(e,t),this.createStorageTextures(e,t)}setAccumulationEnabled(e){this.accumulationEnabled=e,this.enableAccumulation.value=+!!e}enterInteractionMode(){this.cameraOptimizer?.enterInteractionMode()}setInteractionModeEnabled(e){this.cameraOptimizer?.setInteractionModeEnabled(e)}get interactionMode(){return this.cameraOptimizer?.isInInteractionMode()??!1}get viewIsChanging(){return this.interactionMode||performance.now()-this._lastViewChangeAt<Lg}noteViewChanged(){this._lastViewChangeAt=performance.now()}setTriangleData(e,t){if(!e)return;let r=e.chunks&&e.chunks.length>1?e:null,i=r?null:e.chunks?e.chunks[0]:e,a=r?r.recordCount:Math.ceil(i.length/W.FLOATS_PER_TRIANGLE),o=r?._gpuUpload?.triangles?r._gpuUpload:null,{geo:s,shade:c}=o??this._allocateTriangleBuffers(a);this.triangleStorageNode?(this.triangleStorageNode.geo.value=s,this.triangleStorageNode.geo.bufferCount=s.count,this.triangleStorageNode.shade.value=c,this.triangleStorageNode.shade.bufferCount=c.count):this.triangleStorageNode={geo:(0,n.storage)(s,`uvec4`,s.count).toReadOnly(),shade:(0,n.storage)(c,`uvec4`,c.count).toReadOnly()},this.triangleGeoAttr=s,this.triangleShadeAttr=c,this._triangleRecords=r,this._triangleFlat=i,this._triangleRecordCount=a,this.triangleCount=t,this._uploadTriangles(0,a,{skipChunks:o?.uploaded}),Ig.debug(`${J.n(this.triangleCount)} triangles (storage buffer)`)}_allocateTriangleBuffers(e){let t=Math.max(1,e);this._assertFitsGPU(t*3*16);let n=S(t*3,4,Uint32Array),r=S(t*2,4,Uint32Array);return this.renderer.backend.createStorageAttribute(n),this.renderer.backend.createStorageAttribute(r),{geo:n,shade:r}}_uploadTriangles(e,t,{geo:n=!0,shade:r=!0,skipChunks:i=null,source:a=null,sourceStart:o=0,geoAttr:s=this.triangleGeoAttr,shadeAttr:c=this.triangleShadeAttr}={}){if(t<=0||!s)return;let l=this.renderer.backend,u=l.get(s).buffer,d=l.get(c).buffer,f=W.FLOATS_PER_TRIANGLE,p=this._triangleRecords,m=a?t:p?p.recordsPerChunk:this._triangleRecordCount,h=Fg;this._triangleStaging??={geo:new Uint32Array(h*12),shade:new Uint32Array(h*8)};let g=this._triangleStaging.geo,_=this._triangleStaging.shade;for(let s=e,c=e+t;s<c;){let t=a?0:Math.floor(s/m),v=a?e:t*m,y=Math.min(c,v+m);if(i?.has(t)){s=y;continue}let b=a??(p?p.chunks[t]:this._triangleFlat);if(!b)throw Error(`triangle chunk ${t} is on disk and was never uploaded`);let x=Math.min(h,y-s),S=(a?s-e+o:s-v)*f;for(let e=0,t=0,i=0;e<x;e++,S+=f){if(n)for(let e=0;e<12;e++)g[t++]=b[S+e];if(r)for(let e=12;e<f;e++)_[i++]=b[S+e]}n&&l.device.queue.writeBuffer(u,s*12*4,g,0,x*12),r&&l.device.queue.writeBuffer(d,s*8*4,_,0,x*8),s+=x}}createChunkUploader(e){this._assertFitsGPU(e.recordCount*e.lanesPerRecord*e.LaneType.BYTES_PER_ELEMENT);let t=S(e.recordCount*e.lanesPerRecord/4,4,e.LaneType),n=this.renderer.backend;n.createStorageAttribute(t);let r=n.get(t).buffer,i=e.recordsPerChunk*e.lanesPerRecord*e.LaneType.BYTES_PER_ELEMENT,a=new Set;return e._gpuUpload={attr:t,uploaded:a},t=>{let o=e.chunks[t];n.device.queue.writeBuffer(r,t*i,o,0,o.length),a.add(t)}}createTriangleChunkUploader(e){let{geo:t,shade:n}=this._allocateTriangleBuffers(e.recordCount),r=new Set;e._gpuUpload={triangles:!0,geo:t,shade:n,uploaded:r};let i=e.recordsPerChunk;return a=>{let o=a*i,s=Math.min(i,e.recordCount-o);this._uploadTriangles(o,s,{source:e.chunks[a],geoAttr:t,shadeAttr:n}),r.add(a)}}_assertFitsGPU(e){let t=this.renderer?.backend?.device?.limits,n=Math.min(t?.maxBufferSize??1/0,t?.maxStorageBufferBindingSize??1/0);if(e>n)throw Error(`the scene needs a ${J.mb(e)} GPU buffer, past the ${J.mb(n)} this GPU allows for one — load fewer triangles`)}_uploadChunked(e,t){let n=t._gpuUpload;if(!n||n.attr!==e){w(this.renderer,e,t.chunks);return}let r=this.renderer.backend.get(e).buffer,i=t.recordsPerChunk*t.lanesPerRecord*t.LaneType.BYTES_PER_ELEMENT;for(let e=0;e<t.chunks.length;e++){if(n.uploaded.has(e))continue;let a=t.chunks[e];if(!a)throw Error(`chunk ${e} is on disk and was never uploaded`);this.renderer.backend.device.queue.writeBuffer(r,e*i,a,0,a.length),n.uploaded.add(e)}}setBVHData(e){if(!e)return;let r=e.chunks&&e.chunks.length>1?e:null,i=r?null:e.chunks?e.chunks[0]:e,a=r?r.recordCount*r.lanesPerRecord:i.length,o=a/4;this._assertFitsGPU(a*4);let s=()=>r?r._gpuUpload?.attr??S(o,4,Float32Array):new t.StorageInstancedBufferAttribute(i,4);this.bvhStorageNode?(this.bvhStorageAttr=s(),this.bvhStorageNode.value=this.bvhStorageAttr,this.bvhStorageNode.bufferCount=o):(this.bvhStorageAttr=s(),this.bvhStorageNode=(0,n.storage)(this.bvhStorageAttr,`vec4`,o).toReadOnly()),this.bvhStorageAttr.foldedLeaves=e.foldedLeaves===!0,this._bvhRecords=r,r&&this._uploadChunked(this.bvhStorageAttr,r),this.bvhNodeCount=Math.floor(o/Rg),Ig.debug(`${J.n(this.bvhNodeCount)} BVH nodes (storage buffer)`)}setInstanceTable(e){this._instanceTable=e}setMeshVisibilityData(e){!e||e.length===0||!this._instanceTable||(this._patchVisibilityFromMeshes(e),this._flushBVHEdits())}_patchVisibilityFromMeshes(e){let t=this._instanceTable,n=new Map;for(let r=0;r<t.count;r++){if(!t.isSet[r])continue;let i=t.sourceMesh[r],a=n.get(i);a===void 0&&n.set(i,a=this._isWorldVisible(e[i])),this._patchTLASLeafVisibility(r,a)}}updateMeshVisibility(e,t){this._patchTLASLeafVisibility(e,t)&&this._flushBVHEdits()}updateAllMeshVisibility(){!this._meshRefs||!this._instanceTable||(this._patchVisibilityFromMeshes(this._meshRefs),this._flushBVHEdits())}_patchTLASLeafVisibility(e,t){let n=this._instanceTable;if(!n||!n.isSet?.[e]||!this.bvhStorageAttr)return!1;let r=n.tlasLeafIndex[e];return r<0?!1:(n.visible[e]=+!!t,this._bvhRecords?this._bvhRecords.chunkFor(r)[this._bvhRecords.baseOf(r)+2]=+!!t:this.bvhStorageAttr.array[r*16+2]=+!!t,this._dirtyBVHLeaves??=new Set,this._dirtyBVHLeaves.add(r),!0)}_flushBVHEdits(){if(this.bvhStorageAttr){if(!this._bvhRecords){let e=1/0,t=-1;for(let n of this._dirtyBVHLeaves??[])n<e&&(e=n),n>t&&(t=n);t>=0&&(this.bvhStorageAttr.addUpdateRange(e*16,(t-e+1)*16),this.bvhStorageAttr.version++),this._dirtyBVHLeaves?.clear();return}for(let e of this._dirtyBVHLeaves??[])T(this.renderer,this.bvhStorageAttr,this._bvhRecords,e*16,16);this._dirtyBVHLeaves?.clear()}}_collectMeshRefs(e){if(!e)return[];let t=[];return e.traverse(e=>{e.isMesh&&e.userData.meshIndex!==void 0&&(t[e.userData.meshIndex]=e)}),t}_isWorldVisible(e){for(;e;){if(!e.visible)return!1;e=e.parent}return!0}_updateStorageBuffer(e,t){e&&(e.array.set(t),e.clearUpdateRanges(),e.needsUpdate=!0)}updateTriangleData(e,t){e?.chunks?.length>1?this._triangleRecords=e:e&&(this._triangleFlat=e.chunks?e.chunks[0]:e),t?this.updateBufferRanges(t,[]):this._uploadTriangles(0,this._triangleRecordCount)}updateBVHData(e,t){if(this._bvhRecords){e?.chunks?.length>1&&(this._bvhRecords=e),t?this.updateBufferRanges([],t):w(this.renderer,this.bvhStorageAttr,this._bvhRecords.chunks);return}let n=e?.chunks?e.chunks[0]:e;if(!t){this._updateStorageBuffer(this.bvhStorageAttr,n);return}let r=this.bvhStorageAttr?.array;if(n&&r&&n!==r)for(let e of t)r.set(n.subarray(e.offset,e.offset+e.count),e.offset);this.updateBufferRanges([],t)}updateBufferRanges(e,t){if(this.triangleGeoAttr&&e.length>0){let t=W.FLOATS_PER_TRIANGLE;for(let n of e){let e=Math.floor(n.offset/t);this._uploadTriangles(e,Math.ceil((n.offset+n.count)/t)-e)}}if(this.bvhStorageAttr&&t.length>0)if(this._bvhRecords)for(let e of t)T(this.renderer,this.bvhStorageAttr,this._bvhRecords,e.offset,e.count);else{this.bvhStorageAttr.clearUpdateRanges();for(let e of t)this.bvhStorageAttr.addUpdateRange(e.offset,e.count);this.bvhStorageAttr.version++}}createStorageTextures(e,t){this.storageTextures.writeColor?this.storageTextures.setSize(e,t):this.storageTextures.create(e,t),this.resolution.value.set(e,t)}setupMaterial(){if(this.cameraOptimizer||this._initCameraOptimizer(),!this.triangleStorageNode){Ig.error(`triangle data required`);return}if(!this.bvhStorageNode){Ig.error(`BVH data required`);return}if(this.isReady&&this.shaderBuilder.getSceneTextureNodes()){this.shaderBuilder.updateSceneTextures(this);return}this._ensureStorageTextures(),this.shaderBuilder.createSceneTextureNodes(this,this.storageTextures),this.isReady=!0}_ensureStorageTextures(){let e=this.renderer.domElement,t=Math.max(1,e.width||this.width),n=Math.max(1,e.height||this.height);this.storageTextures.ensureSize(t,n)&&this.resolution.value.set(t,n)}_handleResize(){let{width:e,height:t}=this.renderer.domElement;(e!==this.storageTextures.renderWidth||t!==this.storageTextures.renderHeight)&&(this.createStorageTextures(e,t),this.frameCount=0,this._accumulationLockstep=!1),this.resolution.value.set(e,t)}_matricesApproxEqual(e,t,n=1e-10){let r=e.elements,i=t.elements;for(let e=0;e<16;e++)if(Math.abs(r[e]-i[e])>n)return!1;return!0}_updateCameraUniforms(){return!this._matricesApproxEqual(this.lastCameraMatrix,this.camera.matrixWorld)||!this._matricesApproxEqual(this.lastProjectionMatrix,this.camera.projectionMatrixInverse)?(this.cameraWorldMatrix.value.copy(this.camera.matrixWorld),this.cameraViewMatrix.value.copy(this.camera.matrixWorldInverse),this.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix),this.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse),this.lastCameraMatrix.copy(this.camera.matrixWorld),this.lastProjectionMatrix.copy(this.camera.projectionMatrixInverse),!0):!1}_updateAccumulationUniforms(e){let t=this.cameraOptimizer?.isInInteractionMode()??!1;this.lastInteractionModeState=t,this.accumulationEnabled?t?(this.accumulationAlpha.value=1,this.hasPreviousAccumulated.value=0):(this.accumulationAlpha.value=de(e),this.hasPreviousAccumulated.value=+(e>0)):(this.accumulationAlpha.value=1,this.hasPreviousAccumulated.value=0)}_publishTexturesToContext(e,t){e.setTexture(`pathtracer:color`,t.color),e.setTexture(`pathtracer:normalDepth`,t.normalDepth),e.setTexture(`pathtracer:albedo`,t.albedo),e.setState(`pathtracer:samples`,this.frameCount),e.setState(`interactionMode`,this.cameraOptimizer?.isInInteractionMode()??!1),e.setState(`renderMode`,this.renderMode.value)}_emitStateEvents(){this.emit(`pathtracer:frameComplete`,{frame:this.frameCount,isComplete:this.isComplete}),this.cameraChanged&&=(this.emit(`camera:moved`),!1)}updateCompletionThreshold(){this.completionThreshold=ue(this.renderMode.value,this.maxSamples.value)}setRenderLimitMode(e){this.renderLimitMode=e,this.updateCompletionThreshold()}manageASVGFForRenderMode(e){e!==this.lastRenderMode&&(this.renderModeChangeTimeout&&clearTimeout(this.renderModeChangeTimeout),this.pendingRenderMode=e,this.renderModeChangeTimeout=setTimeout(()=>{this.pendingRenderMode!==null&&this.pendingRenderMode!==this.lastRenderMode&&(this.lastRenderMode=this.pendingRenderMode,this.emit(`asvgf:reset`),this.emit(`denoiser:reset`)),this.renderModeChangeTimeout=null,this.pendingRenderMode=null},this.renderModeChangeDelay))}setUniform(e,t){this.uniforms.set(e,t)}setBlueNoiseTexture(){}_rebuildLightBuffer(){let e=this._lbvhDataCache,n=this._emissiveDataCache,r=this.lightStorageAttr?.array,i=this._bitTrailMapCache??(r&&this._bitTrailLength?r.slice(this._bitTrailOffset,this._bitTrailOffset+this._bitTrailLength):null);this._bitTrailMapCache=null;let a=e?e.length:0,o=n?n.length:0,s=i?Math.ceil(i.length/4)*4:0,c=Math.max(a+o+s,4);if(this.lightStorageAttr&&c<=this.lightStorageAttr.array.length){let t=this.lightStorageAttr.array;e&&t.set(e,0),n&&t.set(n,a),i&&t.set(i,a+o),this.lightStorageAttr.needsUpdate=!0}else{let r=new Float32Array(c);e&&r.set(e,0),n&&r.set(n,a),i&&r.set(i,a+o),this.lightStorageAttr=new t.StorageInstancedBufferAttribute(r,4),this.lightStorageNode.value=this.lightStorageAttr,this.lightStorageNode.bufferCount=r.length/4,this._lightBufferRealloc=!0}this.emissiveVec4Offset.value=(this.lightBVHNodeCount.value||0)*4,this.reverseMapVec4Offset.value=(a+o)/4,this._bitTrailOffset=a+o,this._bitTrailLength=i?i.length:0}setEmissiveTriangleData(e,t,n=0,r=null){e&&(this._emissiveDataCache=e,r&&(this._bitTrailMapCache=r),this.emissiveTriangleCount.value=t,this.emissiveTotalPower.value=n,this._rebuildLightBuffer(),Ig.debug(`${J.n(t)} emissive triangles · totalPower ${n.toFixed(4)} (storage buffer)`))}setLightBVHData(e,t){e&&(this._lbvhDataCache=e,this.lightBVHNodeCount.value=t,this._rebuildLightBuffer(),Ig.debug(`light BVH ${J.n(t)} nodes`))}updateUniforms(e){let t=!1;for(let[n,r]of Object.entries(e))this[n]&&this[n].value!==void 0&&this[n].value!==r&&(this[n].value=r,t=!0);t&&this.reset()}async rebuildMaterials(e){if(!this.sdfs)throw Error(`Scene not built yet. Call build() first.`);try{Ig.debug(`material rebuild started`),await this.sdfs.rebuildMaterials(e),this.materialData.setMaterialData(this.sdfs.materialData,this.sdfs.materials?.map(e=>e.sources)),this.materialData.loadTexturesFromSdfs(),this.shaderBuilder.updateSceneTextures(this),this.updateLights(),this.reset(),Ig.debug(`material rebuild complete`)}catch(e){Ig.error(`material rebuild failed:`,e);try{Ig.warn(`attempting recovery by resetting the path tracer`),this.reset()}catch(e){Ig.error(`recovery failed:`,e)}throw e}}dispose(){this.renderModeChangeTimeout&&=(clearTimeout(this.renderModeChangeTimeout),null),this.cameraOptimizer?.dispose(),this.materialData?.dispose(),this.environment?.dispose(),this.shaderBuilder?.dispose(),this.uniforms?.dispose(),this.storageTextures?.dispose(),this.placeholderTexture?.dispose(),this.triangleGeoAttr=null,this.triangleShadeAttr=null,this._triangleStaging=null,this._triangleRecords=null,this._triangleFlat=null,this._triangleRecordCount=0,this.triangleStorageNode=null,this.bvhStorageAttr=null,this._bvhRecords=null,this.bvhStorageNode=null,this.placeholderTexture=null,this.isReady=!1}};jt();var Bg=vt(`gpu`),$={ACTIVE_RAY_COUNT:0,ENTERING_COUNT:1,CONVERGED_COUNT:2,RESERVED_3:3,ACTIVE_PIXEL_COUNT:4,GEOMETRY_COUNT:5,CONVERGED_GEOMETRY_COUNT:6,ACTIVE_ENERGY:7,COUNT:8},Vg=65535,Hg={BOUNCE_MASK:255,ACTIVE:256,SPECULAR:512,INSIDE_MEDIUM:1024,RAY_TYPE_SHIFT:11,RAY_TYPE_MASK:63488,HAS_HIT_OPAQUE:65536,AUX_LOCKED:1<<17,REDIRECTED:1<<18,SUN_NEE:1<<19,UNDER_SURFACE:1<<20},Ug=class{constructor(e=0,t=null){this._renderer=t,this.capacity=0,this.counters=null,this.activeIndices=null,this.activeIndicesRO=null,this.sortedIndices=null,this.sortedIndicesRO=null,this.sortGlobalHistogram=null,this.pingPong=0,e>0&&this.allocate(e)}allocate(e){this.dispose(),this.capacity=e,this._countersAttr=new t.StorageInstancedBufferAttribute(new Uint32Array($.COUNT),1),this.counters=(0,n.storage)(this._countersAttr,`uint`).toAtomic(),this.MAX_BOUNCE_SNAPSHOTS=32,this._bounceCountsAttr=new t.StorageInstancedBufferAttribute(new Uint32Array(2*this.MAX_BOUNCE_SNAPSHOTS),1),this.bounceCounts=(0,n.storage)(this._bounceCountsAttr,`uint`);let r=S(e,1,Uint32Array),i=S(e,1,Uint32Array);this._attrA=r,this._attrB=i,this.activeIndices={a:(0,n.storage)(r,`uint`),b:(0,n.storage)(i,`uint`)},this.activeIndicesRO={a:(0,n.storage)(r,`uint`).toReadOnly(),b:(0,n.storage)(i,`uint`).toReadOnly()};let a=S(e,1,Uint32Array);this._sortAttr=a,this.sortedIndices=(0,n.storage)(a,`uint`),this.sortedIndicesRO=(0,n.storage)(a,`uint`).toReadOnly(),this._sortGlobalHistAttr=new t.StorageInstancedBufferAttribute(new Uint32Array(256),1),this.sortGlobalHistogram=(0,n.storage)(this._sortGlobalHistAttr,`uint`).toAtomic(),this.pingPong=0,this.totalBytes=$.COUNT*4+e*4*3,Bg.debug(`queues capacity ${J.n(e)} · ${J.mb(this.totalBytes)}`)}resize(e){return e<=this.capacity&&this.capacity>0?!1:(this.allocate(e),!0)}getCounters(){return this.counters}getActiveReadRO(){return this.pingPong===0?this.activeIndicesRO.a:this.activeIndicesRO.b}getActiveRead(){return this.pingPong===0?this.activeIndices.a:this.activeIndices.b}getActiveWrite(){return this.pingPong===0?this.activeIndices.b:this.activeIndices.a}getSortedRW(){return this.sortedIndices}getSortedRO(){return this.sortedIndicesRO}getSortGlobalHistogram(){return this.sortGlobalHistogram}getCountersAttribute(){return this._countersAttr}getBounceCounts(){return this.bounceCounts}getBounceCountsAttribute(){return this._bounceCountsAttr}swap(){this.pingPong=1-this.pingPong}resetPingPong(){this.pingPong=0}dispose(){Ca(this._renderer,this._countersAttr),Ca(this._renderer,this._bounceCountsAttr),Ca(this._renderer,this._attrA),Ca(this._renderer,this._attrB),Ca(this._renderer,this._sortAttr),Ca(this._renderer,this._sortGlobalHistAttr),this._countersAttr=this._bounceCountsAttr=null,this._attrA=this._attrB=this._sortAttr=this._sortGlobalHistAttr=null,this.counters=null,this.activeIndices=null,this.activeIndicesRO=null,this.sortedIndices=null,this.sortedIndicesRO=null,this.sortGlobalHistogram=null,this.capacity=0}},Wg={[r.RGBAFormat]:4,[r.RGBFormat]:3,[r.RGFormat]:2,[r.RedFormat]:1},Gg={[r.FloatType]:4,[r.HalfFloatType]:2,[r.UnsignedByteType]:1,[r.ByteType]:1,[r.UnsignedShortType]:2,[r.ShortType]:2,[r.UnsignedIntType]:4,[r.IntType]:4};function Kg(e){return(Wg[e.format]??4)*(Gg[e.type]??4)}function qg(e){return e?.gpuByteLength??e?.array?.byteLength??0}function Jg(e){if(!e)return 0;if(e.isRenderTarget){let t=e.textures?.length?e.textures:[e.texture],n=e.width||0,r=e.height||0,i=e.depth||1,a=0;for(let e of t)e&&(a+=n*r*i*Kg(e));return a}let t=e.image||{},n=t.width??e.width??0,r=t.height??e.height??0,i=t.depth??1;return n*r*i*Kg(e)}var Yg=class{constructor(e=null){this._providers=[],this._renderer=e,this.current=0,this.peak=0,this.byCategory={}}setRenderer(e){this._renderer=e}register(e,t){this._providers.push({category:e,fn:t})}measure(){let e=new WeakSet,t={},n=0;for(let{category:r,fn:i}of this._providers){let a;try{a=i()}catch{a=null}if(!a)continue;let o=0;for(let t of Array.isArray(a)?a:[a])o+=this._resourceBytes(t,e);t[r]=(t[r]||0)+o,n+=o}return this.byCategory=t,this.current=n,n>this.peak&&(this.peak=n),{current:n,peak:this.peak,byCategory:t}}_resourceBytes(e,t){return e?typeof e.bytes==`number`&&!e.isTexture&&!e.isRenderTarget?e.bytes:e.gpuByteLength==null?e.array&&e.array.byteLength!=null?t.has(e.array)?0:(t.add(e.array),e.array.byteLength):e.isRenderTarget||e.isTexture?t.has(e)?0:(t.add(e),this._residentTextureBytes(e)):0:t.has(e)?0:(t.add(e),e.gpuByteLength):0}_isResident(e){let t=this._renderer?.backend;if(!t||typeof t.get!=`function`)return!0;if(typeof t.has==`function`&&!t.has(e))return!1;let n=t.get(e);return!!(n&&(n.texture||n.gpuTexture))}_residentTextureBytes(e){if(e.isRenderTarget){let t=e.textures?.length?e.textures:[e.texture],n=e.width||0,r=e.height||0,i=e.depth||1,a=0;for(let e of t)e&&this._isResident(e)&&(a+=n*r*i*Kg(e));return a}return this._isResident(e)?Jg(e):0}resetPeak(){this.peak=this.current}getReport(){let e=e=>(e/1048576).toFixed(1),t=Object.entries(this.byCategory).map(([t,n])=>`${t}=${e(n)}`);return`VRAM current=${e(this.current)}MB peak=${e(this.peak)}MB [${t.join(` `)}]`}};jt();var Xg=vt(`wavefront`),Zg=class{constructor(e){this.renderer=e,this.kernels=new Map,this.timing=new Map,this.profiling=!1,this.profile=new Map,this._firstDispatches=[],this._firstDispatchFlush=null}_recordFirstDispatch(e,t){this._firstDispatches.push({name:e,ms:t}),clearTimeout(this._firstDispatchFlush),this._firstDispatchFlush=setTimeout(()=>this._flushFirstDispatches(),0)}_flushFirstDispatches(){let e=this._firstDispatches;if(this._firstDispatches=[],this._firstDispatchFlush=null,e.length===0)return;let t=e.reduce((e,t)=>e+t.ms,0),n=[...e].sort((e,t)=>t.ms-e.ms);Xg.info(J.list([`${e.length} kernel${e.length===1?``:`s`} compiled in ${J.ms(t)}`,`slowest ${n.slice(0,2).map(e=>`${e.name} ${J.ms(e.ms)}`).join(`, `)}`])),e.forEach(e=>Xg.debug(`kernel '${e.name}' first dispatch (incl. compilation) ${J.ms(e.ms)}`))}register(e,t){this.kernels.set(e,t),this.timing.set(e,{compiledOnce:!1,lastDispatchMs:0})}dispatch(e){let t=this.kernels.get(e);if(!t)throw Error(`KernelManager: Unknown kernel '${e}'`);let n=this.timing.get(e);if(n&&!n.compiledOnce){let r=performance.now();this.renderer.compute(t);let i=performance.now();n.compiledOnce=!0,n.lastDispatchMs=i-r,this._recordFirstDispatch(e,i-r)}else if(this.profiling){let n=performance.now();this.renderer.compute(t);let r=performance.now(),i=this.profile.get(e);i||(i={calls:0,totalMs:0},this.profile.set(e,i)),i.calls++,i.totalMs+=r-n}else this.renderer.compute(t)}setDispatchForCount(e,t){let n=this.kernels.get(e);if(!n)return;let r=Math.ceil(t/n.workgroupSize[0]),i=this.renderer?.backend?.device?.limits.maxComputeWorkgroupsPerDimension??65535;n.dispatchSize=r>i?[i,Math.ceil(r/i),1]:[r,1,1]}setDispatchForGrid(e,t,n){let r=this.kernels.get(e);if(!r)return;let i=r.workgroupSize;r.dispatchSize=[Math.ceil(t/i[0]),Math.ceil(n/i[1]),1]}has(e){return this.kernels.has(e)}get(e){return this.kernels.get(e)}getTimingReport(){let e={};for(let[t,n]of this.timing)e[t]={...n};return e}enableProfiling(e){this.profiling=e,e&&this.profile.clear()}getProfileReport(){let e=[],t=0;for(let[n,{calls:r,totalMs:i}]of this.profile)t+=i,e.push({name:n,calls:r,totalMs:+i.toFixed(2),avgMs:+(i/r).toFixed(3)});return e.sort((e,t)=>t.totalMs-e.totalMs),e.push({name:`TOTAL`,calls:e.reduce((e,t)=>e+t.calls,0),totalMs:+t.toFixed(2),avgMs:null}),e}dispose(){clearTimeout(this._firstDispatchFlush),this._firstDispatchFlush=null,this._firstDispatches=[],this.kernels.clear(),this.timing.clear(),this.profile.clear()}},Qg=(0,n.int)(Se.equirectangular),$g=(0,n.int)(Se.orthographic),e_=e=>e.equal($g);function t_(){let e={cameraProjection:(0,n.uniform)(0,`int`),panoLonRange:(0,n.uniform)(new r.Vector2,`vec2`),panoLatRange:(0,n.uniform)(new r.Vector2,`vec2`),panoLevelHorizon:(0,n.uniform)(1,`int`),sync(t){e.cameraProjection.value=t.get(`cameraProjection`).value,e.panoLonRange.value.copy(t.get(`panoLonRange`).value),e.panoLatRange.value.copy(t.get(`panoLatRange`).value),e.panoLevelHorizon.value=t.get(`panoLevelHorizon`).value}};return e}var n_=(e,t,n,r)=>({origin:i_(e,t,n,r.cameraProjection),direction:a_(e,t,n,r.cameraProjection,r.panoLonRange,r.panoLatRange,r.panoLevelHorizon)}),r_=(e,t,n,r,i)=>{let{origin:a,direction:o}=n_(e,n,r,i);return a.add(o.mul(t))},i_=(0,n.Fn)(([e,t,r,i])=>{let a=(0,n.vec3)(t[3]).toVar();return(0,n.If)(e_(i),()=>{let i=r.mul((0,n.vec4)(e.x.mul(2).sub(1),(0,n.float)(1).sub(e.y.mul(2)),0,1));a.assign(t.mul((0,n.vec4)(i.xy,0,1)).xyz)}),a}),a_=(0,n.Fn)(([e,t,r,i,a,o,s])=>{let c=(0,n.vec3)(0).toVar();return(0,n.If)(i.equal(Qg),()=>{let r=(0,n.mix)(a.x,a.y,e.x).toVar(),i=(0,n.mix)(o.y,o.x,e.y).toVar(),l=(0,n.cos)(i).toVar(),u=(0,n.vec3)(0).toVar(),d=(0,n.vec3)(0).toVar(),f=(0,n.vec3)(0).toVar();(0,n.If)(s.equal((0,n.int)(1)),()=>{let e=(0,n.vec3)(t[2].x,0,t[2].z).toVar();(0,n.If)((0,n.dot)(e,e).lessThan((0,n.float)(1e-8)),()=>{e.assign((0,n.vec3)(t[1].x,0,t[1].z))}),f.assign((0,n.normalize)(e)),d.assign((0,n.vec3)(0,1,0)),u.assign((0,n.cross)(d,f))}).Else(()=>{u.assign((0,n.normalize)((0,n.vec3)(t[0]))),d.assign((0,n.normalize)((0,n.vec3)(t[1]))),f.assign((0,n.normalize)((0,n.vec3)(t[2])))}),c.assign((0,n.normalize)(u.mul((0,n.sin)(r).mul(l)).add(d.mul((0,n.sin)(i))).sub(f.mul((0,n.cos)(r).mul(l)))))}).ElseIf(e_(i),()=>{c.assign((0,n.normalize)((0,n.vec3)(t[2])).negate())}).Else(()=>{let i=(0,n.vec3)(e.x.mul(2).sub(1),(0,n.float)(1).sub(e.y.mul(2)),1),a=r.mul((0,n.vec4)(i,1));c.assign((0,n.normalize)((0,n.mat3)(t[0].xyz,t[1].xyz,t[2].xyz).mul(a.xyz.div(a.w))))}),c}),o_=(0,n.Fn)(([e,t,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_])=>{let v=i_(e,r,i,a).toVar(),y=a_(e,r,i,a,o,s,c).toVar(),b=v.toVar(),x=y.toVar(),S=g.equal((0,n.int)(1)),C=S.and(_.greaterThan(0)).or(S.not().and(u.greaterThan(0)).and(d.lessThan(64)));return(0,n.If)(l.and(C).and(f.greaterThan(.001)),()=>{let e=(0,n.select)(a.equal(Qg),s.y.sub(s.x).mul(.5),(0,n.select)(e_(a),(0,n.float)(1),i[1].y)),o=(0,n.select)(S,_.mul(f).mul(e),u.div(d.mul(2)).mul(.001).mul(p).mul(m)),c=Ht(t),l=c.x.mul(h.max(.01)),g=c.y,C=(0,n.vec3)(0).toVar(),w=f.toVar();(0,n.If)(a.equal(Qg),()=>{C.assign(Yi({N:y}).mul((0,n.vec3)(l,g,0)))}).Else(()=>{let e=(0,n.normalize)((0,n.vec3)(r[0])),t=(0,n.normalize)((0,n.vec3)(r[1]));C.assign(e.mul(l).add(t.mul(g))),w.assign(f.div((0,n.dot)(y,(0,n.normalize)((0,n.vec3)(r[2]))).negate()))}),b.assign(v.add(C.mul(o))),x.assign((0,n.normalize)(v.add(y.mul(w)).sub(b)))}),mi({origin:b,direction:x})});function s_(e){let{rayBufferRW:t,hitBufferRW:r,gBufferRW:i,resolution:a,frame:o,cameraWorldMatrix:s,cameraProjectionMatrixInverse:c,cameraProjection:l,panoLonRange:u,panoLatRange:d,panoLevelHorizon:f,enableDOF:p,focalLength:m,aperture:h,focusDistance:g,unitsPerMetre:_,apertureScale:v,anamorphicRatio:y,dofMode:b,dofBlur:x,renderWidth:S,chunkRowBase:C,chunkRows:w,transmissiveBounces:T,auxGBufferEnabled:E,listDriven:D=!1,activeIndicesRO:O=null,counters:k=null}=e,A=E.greaterThan((0,n.uint)(0)),j=(e,S,C)=>{let w=(0,n.vec2)((0,n.float)(e).add(.5),(0,n.float)(S).add(.5)),E=Rt({state:en({pixelCoord:w,rayIndex:(0,n.int)(0),frame:o}).toVar()}).toVar(),D=$t(w,(0,n.int)(1),E,a,o).toVar().sub(.5),O=(0,n.vec2)(w.x.add(D.x),w.y.sub(D.y)).div(a),k=mi.wrap(o_(O,E,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x));Ba(t,C,k.origin,(0,n.int)(0),(0,n.int)(0)),Va(t,C,k.direction,(0,n.uint)(Hg.ACTIVE)),Ha(t,C,(0,n.vec4)(1,1,1,0).xyz,(0,n.float)(0)),Ua(t,C,(0,n.vec4)((0,n.vec3)(0),(0,n.float)(1))),(0,n.If)(A,()=>{Ma(i,C,(0,n.vec3)(0,0,1),(0,n.float)(1),(0,n.vec3)(0),(0,n.float)(0)),so(t,C,(0,n.vec3)(1))}),to(t,C,(0,n.uint)(0),(0,n.uint)(T),(0,n.float)(1),(0,n.float)(1),(0,n.float)(1)),Qa(r,C,E)};return(0,n.Fn)(()=>{if(D){let e=n.instanceIndex;(0,n.If)(e.lessThan((0,n.atomicLoad)(k.element((0,n.uint)($.ENTERING_COUNT)))),()=>{let t=(0,n.int)(O.element(e)),r=t.add(C.mul(S));j(r.mod(S),r.div(S),(0,n.uint)(t))})}else{let e=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),t=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(e.lessThan(S).and(t.lessThan(w)),()=>{j(e,t.add(C),(0,n.uint)(t.mul(S).add(e)))})}})}var c_=32,l_=4096,u_=4,d_=1e8,f_=()=>(0,n.array)(`int`,c_).toVar(),p_=e=>(0,n.int)((0,n.uint)(e.bitNot()).shiftRight((0,n.uint)(4))),m_=e=>(0,n.int)((0,n.uint)(e.bitNot()).bitAnd((0,n.uint)(15))),h_=e=>e?e=>e.shiftRight((0,n.uint)(30)).equal((0,n.uint)(1)):e=>e.greaterThanEqual((0,n.uint)(Ue)),g_=e=>{let t=(0,n.mix)((0,n.vec3)(1),(0,n.sign)(e),(0,n.notEqual)(e,(0,n.vec3)(0)));return(0,n.mix)((0,n.vec3)(1).div(e),(0,n.vec3)(d_).mul(t),(0,n.lessThan)((0,n.abs)(e),(0,n.vec3)(1e-8)))},__=(e,t)=>(0,n.vec3)(e[0].xyz.dot(t).add(e[0].w),e[1].xyz.dot(t).add(e[1].w),e[2].xyz.dot(t).add(e[2].w)),v_=(e,t)=>(0,n.vec3)(e[0].xyz.dot(t),e[1].xyz.dot(t),e[2].xyz.dot(t)),y_=(0,n.wgslFn)(`
|
|
716
716
|
fn RayTriangleGeometry( rayOrigin: vec3f, rayDir: vec3f, pA: vec3f, pB: vec3f, pC: vec3f, closestHitDst: f32, woopParams: vec4f ) -> vec4f {
|
|
717
717
|
|
|
718
718
|
// Returns vec4(t, u, v, hit) where hit > 0.5 means intersection.
|