softbox 4.2.1 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,11 @@
1
+ "use strict";var Go=Object.create;var zi=Object.defineProperty;var Wo=Object.getOwnPropertyDescriptor;var Zo=Object.getOwnPropertyNames;var Ko=Object.getPrototypeOf,Xo=Object.prototype.hasOwnProperty;var Yo=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Zo(e))!Xo.call(i,s)&&s!==t&&zi(i,s,{get:()=>e[s],enumerable:!(n=Wo(e,s))||n.enumerable});return i};var Rs=(i,e,t)=>(t=i!=null?Go(Ko(i)):{},Yo(e||!i||!i.__esModule?zi(t,"default",{value:i,enumerable:!0}):t,i));const me=require("react/jsx-runtime"),re=require("react"),p=require("three");function qo(i){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const t in i)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(i,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>i[t]})}}return e.default=i,Object.freeze(e)}const S=qo(p);class K extends Error{constructor(e,t,n){super(e),this.code=t,this.context=n,this.name="ThreeViewerError",this.timestamp=new Date,Error.captureStackTrace&&Error.captureStackTrace(this,K)}static fromError(e,t,n){if(e instanceof K)return e;const s=e instanceof Error?e.message:String(e),r={...n,originalError:e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:e};return new K(s,t,r)}}var Y=(i=>(i.SCENE_INIT_FAILED="SCENE_INIT_FAILED",i.RENDERER_INIT_FAILED="RENDERER_INIT_FAILED",i.RENDERER_NOT_INITIALIZED="RENDERER_NOT_INITIALIZED",i.CAMERA_INIT_FAILED="CAMERA_INIT_FAILED",i.WEBGL_NOT_SUPPORTED="WEBGL_NOT_SUPPORTED",i.INITIALIZATION_FAILED="INITIALIZATION_FAILED",i.PATH_TRACING_INIT_FAILED="PATH_TRACING_INIT_FAILED",i.MODEL_LOAD_FAILED="MODEL_LOAD_FAILED",i.TEXTURE_LOAD_FAILED="TEXTURE_LOAD_FAILED",i.RESOURCE_NOT_FOUND="RESOURCE_NOT_FOUND",i.UNSUPPORTED_FORMAT="UNSUPPORTED_FORMAT",i.INVALID_CONFIGURATION="INVALID_CONFIGURATION",i.RENDER_ERROR="RENDER_ERROR",i.RENDER_FAILED="RENDER_FAILED",i.SCENE_OPERATION_FAILED="SCENE_OPERATION_FAILED",i.COMPONENT_NOT_MOUNTED="COMPONENT_NOT_MOUNTED",i.INVALID_STATE="INVALID_STATE",i.INVALID_PARAMETER="INVALID_PARAMETER",i.OPERATION_FAILED="OPERATION_FAILED",i.UNKNOWN="UNKNOWN",i))(Y||{});const F={ok(i){return{ok:!0,value:i}},err(i){return{ok:!1,error:i}},wrap(i){try{return F.ok(i())}catch(e){return F.err(e instanceof K?e:new K(String(e),Y.UNKNOWN,{originalError:e}))}}};class ws{constructor(){this.listeners=new Map}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);const n=this.listeners.get(e);return n&&n.add(t),()=>{var s;(s=this.listeners.get(e))==null||s.delete(t)}}emit(e,t){var n;(n=this.listeners.get(e))==null||n.forEach(s=>{try{s(t)}catch(r){console.error(`Error in event listener for ${String(e)}:`,r)}})}once(e,t){const n=this.on(e,s=>{n(),t(s)});return n}removeAllListeners(e){e?this.listeners.delete(e):this.listeners.clear()}listenerCount(e){var t;return((t=this.listeners.get(e))==null?void 0:t.size)||0}off(e,t){var n;(n=this.listeners.get(e))==null||n.delete(t)}removeListener(e,t){this.off(e,t)}}const $s=300,vs={meters:1,centimeters:.01,millimeters:.001,feet:.3048,inches:.0254},$o="softbox-units-scale";function Mr(i){const e=i??"meters";if(!Object.prototype.hasOwnProperty.call(vs,e))throw new K(`Unknown units '${String(e)}'. Valid values: ${Object.keys(vs).join(", ")}`,Y.INVALID_PARAMETER);return vs[e]}const Ui="#1a1a1f";class Qo{configureScene(e,t,n){var a,c,u;if(n.helpers){const d={grid:n.helpers.grid,axes:n.helpers.axes,gridColor:"#AAAAAA"},h=t.addHelpers(e,d);h.ok||console.warn("Failed to add helpers:",h.error)}const s=n.lighting;if(s){const d={ambient:s.ambientLight?{color:String(s.ambientLight.color),intensity:s.ambientLight.intensity}:void 0,hemisphere:s.hemisphereLight?{skyColor:String(s.hemisphereLight.skyColor),groundColor:String(s.hemisphereLight.groundColor),intensity:s.hemisphereLight.intensity}:void 0,directional:s.directionalLight?{color:String(s.directionalLight.color),intensity:s.directionalLight.intensity,position:Array.isArray(s.directionalLight.position)?s.directionalLight.position:void 0,castShadow:s.directionalLight.castShadow,shadow:s.directionalLight.shadow}:void 0},h=t.addLighting(e,d);h.ok||console.warn("Failed to add lighting:",h.error)}const r=(a=n.environment)==null?void 0:a.url,o=(((c=n.helpers)==null?void 0:c.studioEnvironment)??!1)&&(((u=n.helpers)==null?void 0:u.darkStudioMode)??!1);if(n.backgroundColor&&!r&&!o){const d=String(n.backgroundColor),h=t.createGradientBackground(e,{topColor:d,bottomColor:d});h.ok||console.warn("Failed to set background:",h.error)}}async configureEnvironment(e,t,n,s,r,o){var d,h,f,m,E,b;const a=await t.initialize({renderer:s,autoDispose:!0});if(o())return;a.ok||console.warn("Failed to initialize environment service:",a.error);const c={backgroundBlurriness:(d=r.environment)==null?void 0:d.backgroundBlurriness,backgroundIntensity:(h=r.environment)==null?void 0:h.backgroundIntensity,environmentIntensity:(f=r.environment)==null?void 0:f.environmentIntensity},u=(m=r.environment)==null?void 0:m.url;if(u){const T=await t.loadEnvironmentMap(u);if(o())return;T.ok?t.applyToScene(e,T.value,c):console.warn("Failed to load environment map:",T.error)}else if((E=r.helpers)!=null&&E.studioEnvironment){const T=t.createStudioEnvironment();if(T.ok){if(t.applyToScene(e,T.value,{...c,setBackground:!1}),(b=r.helpers)!=null&&b.darkStudioMode&&n){const A=n.createGradientBackground(e,{topColor:Ui,bottomColor:Ui});A.ok||console.warn("Failed to set dark studio background:",A.error)}}else console.warn("Failed to create studio environment:",T.error)}}}class Jo{constructor(e={}){this.animationFrameId=null,this.lastRenderTime=0,this.idleTimeout=null,this.isIdle=!1,this.needsRender=!0,this.continuousRenderingEnabled=!1,this.continuousReasons=new Set,this.alwaysRender=!1,this.enableIdleDetection=e.enableIdleDetection??!0,this.idleDelay=e.idleDelay??1e3,this.targetFPS=e.targetFPS??60,this.frameInterval=1e3/this.targetFPS,this.enableFrameRateLimiting=e.enableFrameRateLimiting??!0,this.alwaysRender=e.alwaysRender??!1,this.lastRenderTime=performance.now()}requestRender(){this.needsRender=!0,this.wakeUp()}requireContinuous(e){this.continuousReasons.add(e),this.continuousRenderingEnabled=!0,this.wakeUp()}releaseContinuous(e){this.continuousReasons.delete(e),this.continuousRenderingEnabled=this.continuousReasons.size>0}hasContinuousDemand(){return this.continuousReasons.size>0}setAlwaysRender(e){this.alwaysRender=e,e&&this.wakeUp()}wakeUp(){this.idleTimeout!==null&&(clearTimeout(this.idleTimeout),this.idleTimeout=null),this.isIdle=!1}start(e){if(this.animationFrameId!==null)return;const t=n=>{if(this.animationFrameId===null)return;const s=n-this.lastRenderTime;if(this.enableFrameRateLimiting&&s<this.frameInterval){this.animationFrameId=requestAnimationFrame(t);return}(this.alwaysRender||this.needsRender||this.continuousRenderingEnabled)&&(e(s),this.lastRenderTime=n,this.needsRender=!1),this.enableIdleDetection&&!this.alwaysRender&&(this.continuousRenderingEnabled||this.needsRender?this.wakeUp():this.idleTimeout===null&&!this.isIdle&&(this.idleTimeout=window.setTimeout(()=>{this.isIdle=!0},this.idleDelay))),this.alwaysRender||!this.enableIdleDetection||!this.isIdle||this.continuousRenderingEnabled||this.needsRender?this.animationFrameId=requestAnimationFrame(t):this.animationFrameId=null};this.animationFrameId=requestAnimationFrame(t)}stop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.idleTimeout!==null&&(clearTimeout(this.idleTimeout),this.idleTimeout=null),this.isIdle=!1,this.needsRender=!1,this.continuousRenderingEnabled=!1,this.continuousReasons.clear(),this.alwaysRender=!1}isRunning(){return this.animationFrameId!==null}getIsIdle(){return this.isIdle}getNeedsRender(){return this.needsRender||this.continuousRenderingEnabled||this.alwaysRender}}function Hn(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function ps(i,e){if(!Hn(i)||!Hn(e))return e===void 0?i:e;const t=e,n={...i};for(const s of Object.keys(t)){const r=t[s];if(r===void 0)continue;const o=n[s];n[s]=Hn(o)&&Hn(r)?ps(o,r):r}return n}class Rr{static serialize(e,t,n,s){const r=t.position,o=n.target||{x:0,y:0,z:0};return{modelUrl:e,cameraPosition:{x:r.x,y:r.y,z:r.z},cameraTarget:{x:o.x,y:o.y,z:o.z},controlsTarget:{x:o.x,y:o.y,z:o.z},rendererSize:{width:s.clientWidth,height:s.clientHeight}}}static async restore(e,t,n,s){t.position.set(e.cameraPosition.x,e.cameraPosition.y,e.cameraPosition.z),t.lookAt({x:e.cameraTarget.x,y:e.cameraTarget.y,z:e.cameraTarget.z,set:()=>{},copy:()=>{},add:()=>{},multiply:()=>{},normalize:()=>{},length:()=>0}),n.target&&n.target.set(e.controlsTarget.x,e.controlsTarget.y,e.controlsTarget.z),n.update&&n.update(),e.modelUrl&&s&&await s(e.modelUrl)}}function Qs(i,e){i.type==="perspective"&&"aspect"in i&&(i.aspect=e),i.updateProjectionMatrix()}class gt{constructor(e={}){this.data=Object.freeze({status:"idle",currentModel:null,error:null,isInitialized:!1,loadProgress:0,renderInfo:{frameCount:0,fps:0,lastRenderTime:0,averageRenderTime:0},...e})}get status(){return this.data.status}get currentModel(){return this.data.currentModel}get error(){return this.data.error}get isInitialized(){return this.data.isInitialized}get loadProgress(){return this.data.loadProgress}get renderInfo(){return this.data.renderInfo}setInitialized(){return new gt({...this.data,isInitialized:!0,status:"idle"})}startLoading(){return new gt({...this.data,status:"loading",loadProgress:0,error:null})}updateLoadProgress(e){return new gt({...this.data,loadProgress:Math.min(Math.max(0,e),1)})}setLoaded(e){return new gt({...this.data,status:"loaded",currentModel:e,loadProgress:1,error:null})}setError(e){return new gt({...this.data,status:"error",error:e,loadProgress:0})}startRendering(){return new gt({...this.data,status:"rendering"})}updateRenderInfo(e){return new gt({...this.data,renderInfo:{...this.data.renderInfo,...e}})}dispose(){return new gt({...this.data,status:"disposed",currentModel:null})}canLoad(){return this.data.isInitialized&&(this.data.status==="idle"||this.data.status==="loaded"||this.data.status==="error"||this.data.status==="rendering")}canRender(){return this.data.isInitialized&&this.data.status==="loaded"&&this.data.currentModel!==null}isLoading(){return this.data.status==="loading"}hasError(){return this.data.status==="error"&&this.data.error!==null}toJSON(){return{...this.data}}}class ea{constructor(){this.state=new gt,this.stateChangeCallbacks=new Set}getState(){return this.state}setInitialized(){this.updateState(this.state.setInitialized())}startLoading(){this.updateState(this.state.startLoading())}setLoaded(e){this.updateState(this.state.setLoaded(e))}setError(e){this.updateState(this.state.setError(e))}startRendering(){this.updateState(this.state.startRendering())}updateRenderInfo(e){this.updateState(this.state.updateRenderInfo(e))}setDisposed(){this.updateState(this.state.dispose())}canLoad(){return this.state.canLoad()}isInitialized(){return this.state.isInitialized}getStatus(){return this.state.status}getCurrentModel(){return this.state.currentModel}onStateChange(e){return this.stateChangeCallbacks.add(e),()=>{this.stateChangeCallbacks.delete(e)}}clearCallbacks(){this.stateChangeCallbacks.clear()}updateState(e){this.state=e,this.stateChangeCallbacks.forEach(t=>{try{t(e)}catch(n){console.error("Error in state change callback:",n)}})}}function vr(i){const e=i.toDataURL("image/png");return!e||e==="data:,"?null:e}class ta{constructor(e){this.screenshotElement=null,this.isShowingScreenshot=!1,this.renderer=e.renderer,this.onRestore=e.onRestore}isActive(){return this.isShowingScreenshot}captureAndReplace(e,t,n,s){if(this.isShowingScreenshot)return;const r=this.renderer.getDomElement(),o=vr(r);if(!o){console.warn("[ScreenshotManager] Screenshot capture produced no image, keeping live scene");return}const a=document.createElement("img");a.src=o,a.style.position="absolute",a.style.top="0",a.style.left="0",a.style.width="100%",a.style.height="100%",a.style.pointerEvents="auto",a.style.cursor="grab";const c=r.parentElement;if(c){this.serializedSceneState=Rr.serialize(n,e,t,r),r.style.display="none",c.appendChild(a),this.screenshotElement=a,this.isShowingScreenshot=!0;const u=()=>{this.restore()};a.addEventListener("mousedown",u),a.addEventListener("touchstart",u);const d=()=>{this.isShowingScreenshot&&this.restore()};window.addEventListener("resize",d),this.screenshotResizeHandler=d,s==null||s()}}async restore(){if(!this.isShowingScreenshot||!this.screenshotElement)return;const e=this.renderer.getDomElement(),t=this.screenshotElement.parentElement;t&&(this.screenshotResizeHandler&&(window.removeEventListener("resize",this.screenshotResizeHandler),this.screenshotResizeHandler=void 0),t.removeChild(this.screenshotElement),e.style.display="",this.screenshotElement=null,this.isShowingScreenshot=!1,this.onRestore&&await this.onRestore())}getSerializedState(){return this.serializedSceneState}dispose(){this.screenshotResizeHandler&&(window.removeEventListener("resize",this.screenshotResizeHandler),this.screenshotResizeHandler=void 0),this.screenshotElement&&this.screenshotElement.parentElement&&this.screenshotElement.parentElement.removeChild(this.screenshotElement),this.isShowingScreenshot&&(this.renderer.getDomElement().style.display=""),this.screenshotElement=null,this.isShowingScreenshot=!1,this.serializedSceneState=void 0}}class na{constructor(e){this.currentModel=null,this.modelLoader=e.modelLoader,this.scene=e.scene,this.camera=e.camera,this.controls=e.controls,this.floorAlignmentService=e.floorAlignmentService,this.sceneSetupService=e.sceneSetupService,this.renderer=e.renderer,this.autoFitToObject=e.autoFitToObject??!1,this.unitsScaleToMeters=e.unitsScaleToMeters??1}getCurrentModel(){return this.currentModel}getLastModelUrl(){return this.lastModelUrl}async loadModel(e,t){const n=performance.now();try{let s;if(typeof e=="string"){this.lastModelUrl=e,t.emit("model:loading",{url:e});const a=await this.modelLoader.load(e,(c,u)=>{t.emit("model:progress",{url:e,loaded:c,total:u})});if(!a.ok)throw a.error;s=a.value.scene}else s=e;if(this.unitsScaleToMeters!==1){if(!this.sceneSetupService)throw new K("A units conversion is configured but no scene setup service is available to apply it",Y.INVALID_PARAMETER);const a=this.sceneSetupService.wrapInUnitsScaleGroup(s,this.unitsScaleToMeters);if(!a.ok)throw a.error;s=a.value}this.currentModel&&(this.scene.remove(this.currentModel),this.disposeObject(this.currentModel));const r=this.scene.add(s);if(!r.ok)throw r.error;if(this.floorAlignmentService){const a=this.floorAlignmentService.alignToFloor(s);a.ok||console.warn("Failed to align model to floor:",a.error)}if(s.traverse(a=>{"castShadow"in a&&"receiveShadow"in a&&(a.castShadow=!0,a.receiveShadow=!0)}),this.currentModel=s,this.sceneSetupService){const a=this.sceneSetupService.addDynamicGrid(this.scene,s,2);a.ok||console.warn("Failed to add dynamic grid:",a.error);const c=this.sceneSetupService.snapObjectToFloor(this.scene,s);c.ok||console.warn("Failed to snap object to floor:",c.error);const u=this.sceneSetupService.fitShadowCameraToObject(this.scene,s);if(u.ok||console.warn("Failed to fit shadow camera to object:",u.error),this.renderer){const d=this.sceneSetupService.bakeContactShadow(this.scene,s,this.renderer);d.ok||console.warn("Failed to bake contact shadow:",d.error)}}if(this.autoFitToObject&&this.sceneSetupService){const a=this.sceneSetupService.fitCameraToObject(s,this.camera,this.controls);a.ok||console.warn("Failed to fit camera to object:",a.error)}const o=performance.now()-n;return t.emit("model:loaded",{model:s,loadTime:o}),F.ok(s)}catch(s){const r=s instanceof K?s:new K("Failed to load model",Y.MODEL_LOAD_FAILED,{originalError:s,source:e});return t.emit("model:error",{error:r,url:typeof e=="string"?e:void 0}),F.err(r)}}disposeCurrentModel(){this.currentModel&&(this.scene.remove(this.currentModel),this.disposeObject(this.currentModel),this.currentModel=null)}disposeObject(e){e.dispose()}dispose(){var e,t;this.disposeCurrentModel(),(t=(e=this.modelLoader).dispose)==null||t.call(e),this.lastModelUrl=void 0}}class sa{constructor(e){this.scene=e.scene,this.pathTracingService=e.pathTracingService,this.environmentService=e.environmentService}updateServices(e){e.pathTracingService&&(this.pathTracingService=e.pathTracingService),e.environmentService&&(this.environmentService=e.environmentService)}disposeSceneResources(e=!1){this.scene.disposeContents({keepBackgrounds:!0}),this.triggerGarbageCollection()}disposeServices(){this.pathTracingService&&(this.pathTracingService.dispose(),this.pathTracingService=void 0),this.environmentService&&(this.environmentService.dispose(),this.environmentService=void 0)}dispose(){this.disposeServices(),this.scene.disposeContents(),this.triggerGarbageCollection()}triggerGarbageCollection(){var e;globalThis.gc&&((e=globalThis.gc)==null||e.call(globalThis))}}function Cr(i){return typeof i=="object"&&i!==null&&"getInternalRenderer"in i&&typeof i.getInternalRenderer=="function"}class ia{constructor(e){this.completeHandled=!1,this.selfPauseListeners=new Set,this.deps=e}isEnabled(){var e;return!!(this.deps.service&&(((e=this.deps.getOptions().pathTracing)==null?void 0:e.enabled)??!1))}getMaxSamples(){var e;return((e=this.deps.getOptions().pathTracing)==null?void 0:e.maxSamples)??$s}isCompleteHandled(){return this.completeHandled}isAccumulating(){var e;return!!((e=this.deps.service)!=null&&e.isEnabled())}onSelfPause(e){return this.selfPauseListeners.add(e),()=>this.selfPauseListeners.delete(e)}async initialize(){var u;const{service:e,getOptions:t,isDisposed:n,renderer:s,renderLoopManager:r,schedule:o}=this.deps;if(!e||!(((u=t().pathTracing)==null?void 0:u.enabled)??!1))return;const a=await e.initialize({enabled:!0,renderer:s});if(n())return;if(!a.ok){console.warn("Failed to initialize path tracing:",a.error);return}const c=t().pathTracing;c&&e.updateSettings({samples:c.maxSamples??$s,bounces:c.bounces,transmissiveBounces:c.transmissiveBounces,renderScale:c.renderScale,lowResScale:c.lowResScale,dynamicLowRes:c.dynamicLowRes,enablePathTracing:c.enabled??!0}),e.events.on("pathtracing:paused",({reason:d})=>{r.releaseContinuous("path-tracing"),t().staticScene||r.setAlwaysRender(!1),o(()=>{r.hasContinuousDemand()||r.stop()},100),d==="gave-up"&&this.selfPauseListeners.forEach(h=>h())})}resetAccumulation(e=!1){this.deps.service&&this.isEnabled()&&(this.deps.service.reset(e),this.completeHandled=!1)}getSampleCount(){var e;return((e=this.deps.service)==null?void 0:e.getSampleCount())||0}beforeFrame(){var e;return{wasActive:((e=this.deps.service)==null?void 0:e.isEnabled())||!1,samples:this.getSampleCount()}}render(e,t){const n=this.deps.service;if(!n||n.isPathTracerDisposed())return null;const s=n.getSampleCount(),r=s>=this.getMaxSamples()&&s>0;return!n.isEnabled()&&!r?null:(s===0&&(this.startTime=performance.now()),n.render(e,t))}detectCompletion(e,t){const n=this.deps.service;if(!n)return;(n.getSampleCount()||0)>=this.getMaxSamples()&&!this.completeHandled&&e.wasActive&&this.handleComplete(e.samples,t)}handleComplete(e,t){const{events:n,renderLoopManager:s,getOptions:r,schedule:o,replaceWithScreenshot:a,renderer:c}=this.deps;this.completeHandled=!0,s.releaseContinuous("path-tracing"),r().staticScene||s.setAlwaysRender(!1),n.emit("pathtracing:complete",{samples:e,totalTime:t-(this.startTime||0)});const u=()=>{s.hasContinuousDemand()||s.stop()};if(r().replaceWithScreenshotOnComplete){o(()=>{a(),o(u,200)},100);return}if(s.requestRender(),o(u,100),Cr(c)){const d=c.getInternalRenderer();d&&(d.autoClear=!1)}}onResizeStart(){var t;const e=((t=this.deps.service)==null?void 0:t.isEnabled())??!1;return this.deps.service&&this.completeHandled&&(this.deps.service.reset(),this.completeHandled=!1),e}onResizeEnd(e){e&&this.deps.service&&this.deps.service.setEnabled(!0)}}function Ir(){const i="0123456789abcdef";return Array.from("xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx",t=>t==="x"?i[Math.floor(Math.random()*16)]:t==="y"?(Math.floor(Math.random()*16)&3|8).toString(16):t).join("")}const ra=i=>[i,"video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"].filter(t=>!!t).find(t=>MediaRecorder.isTypeSupported(t));class oa{constructor(e){this.pendingSettlers=new Set,this.pathTracedWaitSettlers=new Set,this.deps=e}async captureStill(e={}){return this.deps.isDisposed()?F.err(new K("Cannot capture a still from a disposed viewer",Y.INVALID_STATE)):(await this.deps.awaitModelLoads().catch(()=>{}),this.deps.isDisposed()?F.err(new K("Viewer was disposed while a model load finished",Y.INVALID_STATE)):this.deps.isScreenshotActive()?F.err(new K("Cannot capture a still while a screenshot is replacing the canvas",Y.INVALID_STATE)):this.deps.pathTracing.isEnabled()?this.capturePathTracedStill(e):this.captureRasterStill(e))}settleOnDispose(){[...this.pendingSettlers].forEach(e=>e("disposed"))}notifyTurntableEnabled(){[...this.pathTracedWaitSettlers].forEach(e=>e("turntable"))}async captureVideo(e={}){var d;if(this.deps.isDisposed())return F.err(new K("Cannot capture video from a disposed viewer",Y.INVALID_STATE));if(await this.deps.awaitModelLoads().catch(()=>{}),this.deps.isDisposed())return F.err(new K("Viewer was disposed while a model load finished",Y.INVALID_STATE));if(this.deps.isScreenshotActive())return F.err(new K("Cannot capture video while a screenshot is replacing the canvas",Y.INVALID_STATE));const t=e.duration??3;if(!(t>0))return F.err(new K("Video duration must be a positive number of seconds",Y.INVALID_PARAMETER));const n=this.deps.renderer.getDomElement();if(typeof MediaRecorder>"u"||typeof n.captureStream!="function")return F.err(new K("Video capture needs MediaRecorder and canvas.captureStream support",Y.UNSUPPORTED_FORMAT));const s=n.captureStream(e.fps??30);let r;try{r=new MediaRecorder(s,{mimeType:ra(e.mimeType),videoBitsPerSecond:e.videoBitsPerSecond})}catch(h){return s.getTracks().forEach(f=>f.stop()),F.err(new K("Failed to start the video recorder",Y.OPERATION_FAILED,{originalError:h}))}const o=s.getVideoTracks()[0],a=(d=o==null?void 0:o.requestFrame)==null?void 0:d.bind(o),c=a?this.deps.events.on("render:complete",()=>a()):()=>{},u=`video-capture:${Ir()}`;return this.deps.renderLoopManager.requireContinuous(u),this.deps.reviveRenderLoop(),this.deps.renderLoopManager.requestRender(),new Promise(h=>{const f=[];let m=null,E=!1;const b=A=>{E||(E=!0,this.pendingSettlers.delete(T),c(),m!==null&&clearTimeout(m),this.deps.renderLoopManager.releaseContinuous(u),s.getTracks().forEach(w=>w.stop()),h(A))},T=()=>{b(F.err(new K("Viewer was disposed during video capture",Y.INVALID_STATE)));try{r.stop()}catch{}};this.pendingSettlers.add(T),r.ondataavailable=A=>{A.data.size>0&&f.push(A.data)},r.onstop=()=>{b(F.ok(new Blob(f,{type:r.mimeType||"video/webm"})))},r.onerror=()=>{b(F.err(new K("Video recording failed",Y.OPERATION_FAILED)))},r.start(250),m=setTimeout(()=>{r.state!=="inactive"&&r.stop()},t*1e3)})}async capturePathTracedStill(e){if(e.width!==void 0||e.height!==void 0)return F.err(new K("Path-traced stills are captured at the canvas resolution; omit width/height",Y.INVALID_PARAMETER));if(this.deps.isAutoRotating())return F.err(new K("Cannot capture a path-traced still while the turntable is spinning — pause autoRotate first",Y.INVALID_STATE));const t=this.deps.pathTracing.isAccumulating()&&this.deps.getStatus()!=="error";if(!this.deps.pathTracing.isCompleteHandled()&&t){const n=await this.waitForPathTracingOutcome();if(n==="disposed")return F.err(new K("Viewer was disposed while waiting for the path tracer",Y.INVALID_STATE));if(n==="error")return F.err(new K("Model failed while waiting for the path tracer",Y.RENDER_FAILED));if(n==="turntable")return F.err(new K("Cannot capture a path-traced still while the turntable is spinning — pause autoRotate first",Y.INVALID_STATE))}return this.readCanvasPng()}waitForPathTracingOutcome(){return new Promise(e=>{let t=()=>{},n=()=>{},s=()=>{},r=()=>{};const o=a=>{this.pendingSettlers.delete(o),this.pathTracedWaitSettlers.delete(o),t(),n(),s(),r(),e(a)};this.pendingSettlers.add(o),this.pathTracedWaitSettlers.add(o),t=this.deps.events.once("pathtracing:complete",()=>o("complete")),n=this.deps.events.once("model:error",()=>o("error")),s=this.deps.pathTracing.onSelfPause(()=>o("complete")),r=this.deps.events.on("controls:change",()=>{this.deps.isAutoRotating()&&o("turntable")})})}captureRasterStill(e){const{renderer:t,scene:n,camera:s,renderLoopManager:r}=this.deps,o=t.getDomElement(),a=t.getPixelRatio(),c=o.clientWidth>0&&o.clientHeight>0,u=c?o.clientWidth:Math.round(o.width/a),d=c?o.clientHeight:Math.round(o.height/a);if(u<=0||d<=0)return F.err(new K("Cannot capture: the canvas has no size",Y.INVALID_STATE));const h=u/d,f=Math.round(e.width??(e.height!==void 0?e.height*h:u*a)),m=Math.round(e.height??(e.width!==void 0?e.width/h:d*a)),E=t.capabilities.maxTextureSize;if(!Number.isFinite(f)||!Number.isFinite(m)||f<=0||m<=0||f>E||m>E)return F.err(new K(`Requested still size ${f}x${m} is outside 1..${E}`,Y.INVALID_PARAMETER));t.setPixelRatio(1),t.setSize(f,m),Qs(s,f/m);const b=t.render(n,s),T=b.ok?this.readCanvasPng():F.err(b.error);return t.setSize(u,d),t.setPixelRatio(a),Qs(s,h),t.render(n,s),r.requestRender(),T}readCanvasPng(){const e=vr(this.deps.renderer.getDomElement());return e?F.ok(e):F.err(new K("Canvas produced an empty image",Y.RENDER_FAILED))}}class aa{constructor(e){var r;this.frameCount=0,this.disposed=!1,this.pendingTimers=new Set,this.modelLoadChain=Promise.resolve(),this.renderer=e.renderer,this.scene=e.scene,this.camera=e.camera,this.controls=e.controls,this.options=e.options,this.rendererOptions=e.rendererOptions,this.sceneSetupService=e.sceneSetupService,this.environmentService=e.environmentService,this.selectionService=e.selectionService,this.anchorProjectionService=e.anchorProjectionService,this.animationService=e.animationService,this.stateManager=new ea,this.screenshotManager=new ta({renderer:this.renderer,onRestore:async()=>{await this.restoreFromScreenshot()}});const t=Mr(this.options.units);this.modelManager=new na({modelLoader:e.modelLoader,scene:this.scene,camera:this.camera,controls:this.controls,floorAlignmentService:e.floorAlignmentService,sceneSetupService:this.sceneSetupService,renderer:this.renderer,autoFitToObject:(r=this.options.camera)==null?void 0:r.autoFitToObject,unitsScaleToMeters:t}),this.resourceManager=new sa({scene:this.scene,pathTracingService:e.pathTracingService,environmentService:this.environmentService}),this.sceneConfigurator=new Qo,this.events=new ws;const n=this.options.rendering||{},s=this.options.staticScene!==!1;this.renderLoopManager=new Jo({enableIdleDetection:n.enableIdleDetection??s,idleDelay:n.idleDelay,targetFPS:n.targetFPS,enableFrameRateLimiting:n.enableFrameRateLimiting,alwaysRender:!1}),this.pathTracing=new ia({service:e.pathTracingService,events:this.events,renderLoopManager:this.renderLoopManager,renderer:this.renderer,getOptions:()=>this.options,isDisposed:()=>this.disposed,schedule:(o,a)=>this.schedule(o,a),replaceWithScreenshot:()=>this.replaceWithScreenshot()}),this.capture=new oa({renderer:this.renderer,scene:this.scene,camera:this.camera,events:this.events,renderLoopManager:this.renderLoopManager,pathTracing:this.pathTracing,getStatus:()=>this.stateManager.getStatus(),isDisposed:()=>this.disposed,awaitModelLoads:()=>this.modelLoadChain,reviveRenderLoop:()=>this.reviveRenderLoop(),isAutoRotating:()=>this.controls.autoRotate,isScreenshotActive:()=>this.screenshotManager.isActive()})}async initialize(){var e,t;try{const n=this.renderer.initialize(this.rendererOptions||{});return n.ok?(this.sceneSetupService&&this.sceneConfigurator.configureScene(this.scene,this.sceneSetupService,this.options),this.environmentService&&(await this.sceneConfigurator.configureEnvironment(this.scene,this.environmentService,this.sceneSetupService,this.renderer,this.options,()=>this.disposed),this.disposed)||(await this.pathTracing.initialize(),this.disposed)||(this.selectionService&&this.selectionService.initialize({canvas:this.renderer.getDomElement(),camera:this.camera,getPickRoot:()=>this.modelManager.getCurrentModel(),bvh:(e=this.options.selection)==null?void 0:e.bvh,onPick:s=>{s&&!this.disposed&&this.events.emit("object:selected",s)}}),this.stateManager.setInitialized(),this.startRenderLoop(),this.options.staticScene?this.pathTracing.isEnabled()&&this.renderLoopManager.requireContinuous("path-tracing"):this.renderLoopManager.setAlwaysRender(!0),(t=this.options.controls)!=null&&t.autoRotate&&this.renderLoopManager.requireContinuous("turntable"),this.renderLoopManager.requestRender()),F.ok(void 0)):n}catch(n){const s=new K("Failed to initialize viewer",Y.INITIALIZATION_FAILED,{originalError:n});return this.stateManager.setError(s),this.events.emit("error",{error:s}),F.err(s)}}loadModel(e){const t=this.modelLoadChain.then(()=>this.runLoadModel(e));return this.modelLoadChain=t.then(()=>{},()=>{}),t}async runLoadModel(e){if(this.disposed)return F.err(new K("Cannot load model after dispose",Y.INVALID_STATE));if(!this.stateManager.canLoad())return F.err(new K("Cannot load model in current state",Y.INVALID_STATE,{currentState:this.stateManager.getStatus(),isInitialized:this.stateManager.isInitialized()}));try{this.stateManager.startLoading();const t=await this.modelManager.loadModel(e,this.events);return this.disposed?(t.ok&&this.modelManager.disposeCurrentModel(),F.err(new K("Viewer was disposed while the model was loading",Y.INVALID_STATE))):t.ok?(this.stateManager.setLoaded(t.value),this.attachAnimations(t.value),this.renderLoopManager.requestRender(),this.pathTracing.resetAccumulation(!0),F.ok(void 0)):(this.stateManager.setError(t.error),t)}catch(t){const n=t instanceof K?t:new K("Failed to load model",Y.MODEL_LOAD_FAILED,{originalError:t,source:e});return this.stateManager.setError(n),F.err(n)}}startRenderLoop(){this.renderLoopManager.start(e=>{var o;if(this.disposed){this.renderLoopManager.stop();return}if(!this.stateManager.isInitialized()||this.stateManager.getStatus()==="error")return;if(!this.renderer||this.renderer.isDisposed()){this.renderLoopManager.stop();return}const t=performance.now(),n=e>0?1e3/e:0;this.controls.update()&&(this.events.emit("controls:change",{controls:this.controls}),this.pathTracing.resetAccumulation(),this.renderLoopManager.requestRender()),(o=this.animationService)!=null&&o.isPlaying()&&this.animationService.update(e/1e3);const r=this.pathTracing.beforeFrame();this.renderFrame().catch(a=>{console.error("[ViewerCore] Render frame error:",a)}),this.pathTracing.detectCompletion(r,t),this.frameCount++,this.stateManager.updateRenderInfo({frameCount:this.frameCount,fps:Math.round(n),lastRenderTime:performance.now()-t})})}stopRenderLoop(){this.renderLoopManager.stop()}schedule(e,t){const n=setTimeout(()=>{this.pendingTimers.delete(n),!this.disposed&&e()},t);this.pendingTimers.add(n)}async renderFrame(){const e=performance.now();if(!this.renderer||!this.scene||!this.camera){console.warn("[ViewerCore] Cannot render - components not initialized");return}if(this.screenshotManager.isActive())return;this.stateManager.startRendering();const t=await(this.pathTracing.render(this.scene,this.camera)??Promise.resolve(this.renderer.render(this.scene,this.camera)));if(!t.ok){console.error("[ViewerCore] Render failed:",t.error),this.events.emit("error",{error:t.error});return}this.events.emit("render:complete",{frame:this.frameCount,renderTime:performance.now()-e,samples:this.pathTracing.getSampleCount()})}updateOptions(e){var h,f,m,E,b,T,A,w,x;if(this.disposed)return;const t=(h=this.options.animations)==null?void 0:h.autoplay,n=(f=this.options.controls)==null?void 0:f.autoRotate;this.options=ps(this.options,e);let s=!1;e.backgroundColor!==void 0&&this.applyBackgroundColor(e.backgroundColor);const r=(m=e.renderer)==null?void 0:m.toneMappingExposure;r!==void 0&&(this.renderer.setToneMappingExposure(r),s=!0);const o=(E=e.environment)==null?void 0:E.environmentIntensity;o!==void 0&&(this.scene.setEnvironmentIntensity(o),s=!0);const a=(b=e.controls)==null?void 0:b.autoRotate;a!==void 0&&a!==n&&(this.controls.autoRotate=a,a?(this.renderLoopManager.requireContinuous("turntable"),this.capture.notifyTurntableEnabled()):this.renderLoopManager.releaseContinuous("turntable"),s=!0);const c=(T=e.controls)==null?void 0:T.autoRotateSpeed;c!==void 0&&(this.controls.autoRotateSpeed=c,s=!0);const u=(A=e.animations)==null?void 0:A.autoplay;u!==void 0&&u!==t&&(u?this.modelManager.getCurrentModel()&&this.autoplayFromOptions(u):this.pauseAnimations(),s=!0);const d=(w=e.animations)==null?void 0:w.speed;d!==void 0&&((x=this.animationService)==null||x.setSpeed(d),s=!0),s&&(this.reviveRenderLoop(),this.renderLoopManager.requestRender())}applyBackgroundColor(e){var n;if((n=this.options.environment)!=null&&n.url||!this.sceneSetupService)return;const t=this.sceneSetupService.createGradientBackground(this.scene,{topColor:String(e),bottomColor:String(e)});if(!t.ok){console.warn("Failed to update background color:",t.error);return}this.renderLoopManager.requestRender()}resize(e,t){if(this.disposed)return;const n=this.renderer.getDomElement();if(n.width===e&&n.height===t)return;const s=this.pathTracing.onResizeStart();Qs(this.camera,e/t),this.renderer.setSize(e,t);try{this.renderer.render(this.scene,this.camera)}catch{}this.pathTracing.onResizeEnd(s),this.renderLoopManager.requestRender()}getState(){return this.stateManager.getState()}onStateChange(e){return this.stateManager.onStateChange(e)}getEvents(){return this.events}getDomElement(){return this.renderer.getDomElement()}getRenderer(){return this.renderer}getScene(){return this.scene}getCamera(){return this.camera}getControls(){return this.controls}getModel(){return this.modelManager.getCurrentModel()}requestRender(){this.renderLoopManager.requestRender()}reviveRenderLoop(){this.stateManager.isInitialized()&&!this.renderLoopManager.isRunning()&&this.startRenderLoop()}getAnimationNames(){var e;return((e=this.animationService)==null?void 0:e.getClipNames())??[]}playAnimations(e){var n;if(!this.animationService)return e!==void 0?F.err(new K(`Cannot play animation clip '${e}': the viewer was assembled without an animation service`,Y.INVALID_STATE)):F.ok(void 0);const t=this.animationService.play(e);return t.ok?(this.animationService.isPlaying()&&((n=this.sceneSetupService)==null||n.setContactShadowMode(this.scene,"live"),this.renderLoopManager.requireContinuous("animations"),this.reviveRenderLoop(),this.renderLoopManager.requestRender()),F.ok(void 0)):t}autoplayFromOptions(e){const t=this.playAnimations(typeof e=="string"?e:void 0);t.ok||console.error("animations.autoplay failed:",t.error.message)}pauseAnimations(){var e;(e=this.animationService)==null||e.pause(),this.renderLoopManager.releaseContinuous("animations"),this.rebakeContactShadowForCurrentPose(),this.renderLoopManager.requestRender()}rebakeContactShadowForCurrentPose(){const e=this.modelManager.getCurrentModel();if(!e||!this.sceneSetupService)return;const t=this.sceneSetupService.bakeContactShadow(this.scene,e,this.renderer);t.ok||console.warn("Failed to re-bake contact shadow after pausing animations:",t.error)}attachAnimations(e){if(!this.animationService)return;this.renderLoopManager.releaseContinuous("animations"),this.animationService.attach(e);const t=this.options.animations;(t==null?void 0:t.speed)!==void 0&&this.animationService.setSpeed(t.speed);const n=t==null?void 0:t.autoplay;n&&this.autoplayFromOptions(n)}createAnchorProjector(){return this.anchorProjectionService?this.anchorProjectionService.createProjector({camera:this.camera,getCanvas:()=>this.renderer.getDomElement(),getModel:()=>this.getModel()}):null}captureStill(e={}){return this.capture.captureStill(e)}captureVideo(e={}){return this.capture.captureVideo(e)}replaceWithScreenshot(){const e=this.modelManager.getLastModelUrl();this.screenshotManager.captureAndReplace(this.camera,this.controls,e,()=>{this.modelManager.disposeCurrentModel(),this.resourceManager.disposeSceneResources(!0)})}async restoreFromScreenshot(){const e=this.screenshotManager.getSerializedState();e&&await Rr.restore(e,this.camera,this.controls,async t=>{const n=await this.loadModel(t);n.ok||console.error("[ViewerCore] Failed to reload model:",n.error)}),this.renderLoopManager.isRunning()||this.startRenderLoop(),this.renderLoopManager.requestRender()}dispose(){var e,t;this.disposed=!0,this.pendingTimers.forEach(n=>clearTimeout(n)),this.pendingTimers.clear(),this.stopRenderLoop(),(e=this.selectionService)==null||e.dispose(),(t=this.animationService)==null||t.detach(),this.modelManager.dispose(),this.resourceManager.dispose(),this.screenshotManager.dispose(),this.controls.dispose(),this.renderer.dispose(),this.stateManager.setDisposed(),this.capture.settleOnDispose(),this.events.removeAllListeners(),this.stateManager.clearCallbacks()}}class Pt{constructor(e){this.vector=e}get x(){return this.vector.x}set x(e){this.vector.x=e}get y(){return this.vector.y}set y(e){this.vector.y=e}get z(){return this.vector.z}set z(e){this.vector.z=e}set(e,t,n){this.vector.set(e,t,n)}copy(e){this.vector.set(e.x,e.y,e.z)}add(e){this.vector.x+=e.x,this.vector.y+=e.y,this.vector.z+=e.z}multiply(e){this.vector.x*=e.x,this.vector.y*=e.y,this.vector.z*=e.z}normalize(){this.vector.normalize()}length(){return this.vector.length()}getThreeVector(){return this.vector}static fromThreeVector(e){return new Pt(e)}static create(e=0,t=0,n=0){return new Pt(new S.Vector3(e,t,n))}}const Lr=0,ca=1,Pr=2,Hi=2,Cs=1.25,Vi=1,He=32,De=He/4,Ei=65535,la=Ei<<16,us=Math.pow(2,-24),wi=Symbol("SKIP_GENERATION"),Or={strategy:Lr,maxDepth:40,maxLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[wi]:!1};function xe(i,e,t){return t.min.x=e[i],t.min.y=e[i+1],t.min.z=e[i+2],t.max.x=e[i+3],t.max.y=e[i+4],t.max.z=e[i+5],t}function ji(i){let e=-1,t=-1/0;for(let n=0;n<3;n++){const s=i[n+3]-i[n];s>t&&(t=s,e=n)}return e}function Gi(i,e){e.set(i)}function Wi(i,e,t){let n,s;for(let r=0;r<3;r++){const o=r+3;n=i[r],s=e[r],t[r]=n<s?n:s,n=i[o],s=e[o],t[o]=n>s?n:s}}function Vn(i,e,t){for(let n=0;n<3;n++){const s=e[i+2*n],r=e[i+2*n+1],o=s-r,a=s+r;o<t[n]&&(t[n]=o),a>t[n+3]&&(t[n+3]=a)}}function hn(i){const e=i[3]-i[0],t=i[4]-i[1],n=i[5]-i[2];return 2*(e*t+t*n+n*e)}function Ce(i,e){return e[i+15]===Ei}function Ve(i,e){return e[i+6]}function Xe(i,e){return e[i+14]}function Fe(i){return i+De}function Be(i,e){const t=e[i+6];return i+t*De}function Ts(i,e){return e[i+7]}function ha(i){return i}function Is(i,e,t,n,s){let r=1/0,o=1/0,a=1/0,c=-1/0,u=-1/0,d=-1/0,h=1/0,f=1/0,m=1/0,E=-1/0,b=-1/0,T=-1/0;const A=i.offset||0;for(let w=(e-A)*6,x=(e+t-A)*6;w<x;w+=6){const _=i[w+0],M=i[w+1],P=_-M,I=_+M;P<r&&(r=P),I>c&&(c=I),_<h&&(h=_),_>E&&(E=_);const C=i[w+2],D=i[w+3],L=C-D,k=C+D;L<o&&(o=L),k>u&&(u=k),C<f&&(f=C),C>b&&(b=C);const N=i[w+4],V=i[w+5],G=N-V,$=N+V;G<a&&(a=G),$>d&&(d=$),N<m&&(m=N),N>T&&(T=N)}n[0]=r,n[1]=o,n[2]=a,n[3]=c,n[4]=u,n[5]=d,s[0]=h,s[1]=f,s[2]=m,s[3]=E,s[4]=b,s[5]=T}const wt=32,ua=(i,e)=>i.candidate-e.candidate,Mt=new Array(wt).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),jn=new Float32Array(6);function da(i,e,t,n,s,r){let o=-1,a=0;if(r===Lr)o=ji(e),o!==-1&&(a=(e[o]+e[o+3])/2);else if(r===ca)o=ji(i),o!==-1&&(a=fa(t,n,s,o));else if(r===Pr){const c=hn(i);let u=Cs*s;const d=t.offset||0,h=(n-d)*6,f=(n+s-d)*6;for(let m=0;m<3;m++){const E=e[m],A=(e[m+3]-E)/wt;if(s<wt/4){const w=[...Mt];w.length=s;let x=0;for(let M=h;M<f;M+=6,x++){const P=w[x];P.candidate=t[M+2*m],P.count=0;const{bounds:I,leftCacheBounds:C,rightCacheBounds:D}=P;for(let L=0;L<3;L++)D[L]=1/0,D[L+3]=-1/0,C[L]=1/0,C[L+3]=-1/0,I[L]=1/0,I[L+3]=-1/0;Vn(M,t,I)}w.sort(ua);let _=s;for(let M=0;M<_;M++){const P=w[M];for(;M+1<_&&w[M+1].candidate===P.candidate;)w.splice(M+1,1),_--}for(let M=h;M<f;M+=6){const P=t[M+2*m];for(let I=0;I<_;I++){const C=w[I];P>=C.candidate?Vn(M,t,C.rightCacheBounds):(Vn(M,t,C.leftCacheBounds),C.count++)}}for(let M=0;M<_;M++){const P=w[M],I=P.count,C=s-P.count,D=P.leftCacheBounds,L=P.rightCacheBounds;let k=0;I!==0&&(k=hn(D)/c);let N=0;C!==0&&(N=hn(L)/c);const V=Vi+Cs*(k*I+N*C);V<u&&(o=m,u=V,a=P.candidate)}}else{for(let _=0;_<wt;_++){const M=Mt[_];M.count=0,M.candidate=E+A+_*A;const P=M.bounds;for(let I=0;I<3;I++)P[I]=1/0,P[I+3]=-1/0}for(let _=h;_<f;_+=6){let I=~~((t[_+2*m]-E)/A);I>=wt&&(I=wt-1);const C=Mt[I];C.count++,Vn(_,t,C.bounds)}const w=Mt[wt-1];Gi(w.bounds,w.rightCacheBounds);for(let _=wt-2;_>=0;_--){const M=Mt[_],P=Mt[_+1];Wi(M.bounds,P.rightCacheBounds,M.rightCacheBounds)}let x=0;for(let _=0;_<wt-1;_++){const M=Mt[_],P=M.count,I=M.bounds,D=Mt[_+1].rightCacheBounds;P!==0&&(x===0?Gi(I,jn):Wi(I,jn,jn)),x+=P;let L=0,k=0;x!==0&&(L=hn(jn)/c);const N=s-x;N!==0&&(k=hn(D)/c);const V=Vi+Cs*(L*x+k*N);V<u&&(o=m,u=V,a=M.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${r} used.`);return{axis:o,pos:a}}function fa(i,e,t,n){let s=0;const r=i.offset;for(let o=e,a=e+t;o<a;o++)s+=i[(o-r)*6+n*2];return s/t}class Ls{constructor(){this.boundingData=new Float32Array(6)}}function pa(i,e,t,n,s,r){let o=n,a=n+s-1;const c=r.pos,u=r.axis*2,d=t.offset||0;for(;;){for(;o<=a&&t[(o-d)*6+u]<c;)o++;for(;o<=a&&t[(a-d)*6+u]>=c;)a--;if(o<a){for(let h=0;h<e;h++){let f=i[o*e+h];i[o*e+h]=i[a*e+h],i[a*e+h]=f}for(let h=0;h<6;h++){const f=o-d,m=a-d,E=t[f*6+h];t[f*6+h]=t[m*6+h],t[m*6+h]=E}o++,a--}else return o}}let Dr,ds,Js,Nr;const ma=Math.pow(2,32);function ei(i){return"count"in i?1:1+ei(i.left)+ei(i.right)}function ga(i,e,t){return Dr=new Float32Array(t),ds=new Uint32Array(t),Js=new Uint16Array(t),Nr=new Uint8Array(t),ti(i,e)}function ti(i,e){const t=i/4,n=i/2,s="count"in e,r=e.boundingData;for(let o=0;o<6;o++)Dr[t+o]=r[o];if(s)return e.buffer?(Nr.set(new Uint8Array(e.buffer),i),i+e.buffer.byteLength):(ds[t+6]=e.offset,Js[n+14]=e.count,Js[n+15]=Ei,i+He);{const{left:o,right:a,splitAxis:c}=e,u=i+He;let d=ti(u,o);const h=i/He,m=d/He-h;if(m>ma)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return ds[t+6]=m,ds[t+7]=c,ti(d,a)}}function ya(i,e,t,n,s,r){const{maxDepth:o,verbose:a,maxLeafSize:c,strategy:u,onProgress:d}=s,h=i.primitiveBuffer,f=i.primitiveBufferStride,m=new Float32Array(6);let E=!1;const b=new Ls;return Is(e,t,n,b.boundingData,m),A(b,t,n,m),b;function T(w){d&&d((w-r.offset)/r.count)}function A(w,x,_,M=null,P=0){if(!E&&P>=o&&(E=!0,a&&console.warn(`BVH: Max depth of ${o} reached when generating BVH. Consider increasing maxDepth.`)),_<=c||P>=o)return T(x+_),w.offset=x,w.count=_,w;const I=da(w.boundingData,M,e,x,_,u);if(I.axis===-1)return T(x+_),w.offset=x,w.count=_,w;const C=pa(h,f,e,x,_,I);if(C===x||C===x+_)T(x+_),w.offset=x,w.count=_;else{w.splitAxis=I.axis;const D=new Ls,L=x,k=C-x;w.left=D,Is(e,L,k,D.boundingData,m),A(D,L,k,m,P+1);const N=new Ls,V=C,G=_-k;w.right=N,Is(e,V,G,N.boundingData,m),A(N,V,G,m,P+1)}return w}}function Ea(i,e){const t=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=i.getRootRanges(e.range),s=n[0],r=n[n.length-1],o={offset:s.offset,count:r.offset+r.count-s.offset},a=new Float32Array(6*o.count);a.offset=o.offset,i.computePrimitiveBounds(o.offset,o.count,a),i._roots=n.map(c=>{const u=ya(i,a,c.offset,c.count,e,o),d=ei(u),h=new t(He*d);return ga(0,u,h),h})}class Ti{constructor(e){this._getNewPrimitive=e,this._primitives=[]}getPrimitive(){const e=this._primitives;return e.length===0?this._getNewPrimitive():e.pop()}releasePrimitive(e){this._primitives.push(e)}}class wa{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const e=[];let t=null;this.setBuffer=n=>{t&&e.push(t),t=n,this.float32Array=new Float32Array(n),this.uint16Array=new Uint16Array(n),this.uint32Array=new Uint32Array(n)},this.clearBuffer=()=>{t=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,e.length!==0&&this.setBuffer(e.pop())}}}const be=new wa;let Lt,nn;const Gt=[],Gn=new Ti(()=>new p.Box3);function Ta(i,e,t,n,s,r){Lt=Gn.getPrimitive(),nn=Gn.getPrimitive(),Gt.push(Lt,nn),be.setBuffer(i._roots[e]);const o=ni(0,i.geometry,t,n,s,r);be.clearBuffer(),Gn.releasePrimitive(Lt),Gn.releasePrimitive(nn),Gt.pop(),Gt.pop();const a=Gt.length;return a>0&&(nn=Gt[a-1],Lt=Gt[a-2]),o}function ni(i,e,t,n,s=null,r=0,o=0){const{float32Array:a,uint16Array:c,uint32Array:u}=be;let d=i*2;if(Ce(d,c)){const f=Ve(i,u),m=Xe(d,c);return xe(i,a,Lt),n(f,m,!1,o,r+i/De,Lt)}else{let L=function(N){const{uint16Array:V,uint32Array:G}=be;let $=N*2;for(;!Ce($,V);)N=Fe(N),$=N*2;return Ve(N,G)},k=function(N){const{uint16Array:V,uint32Array:G}=be;let $=N*2;for(;!Ce($,V);)N=Be(N,G),$=N*2;return Ve(N,G)+Xe($,V)};const f=Fe(i),m=Be(i,u);let E=f,b=m,T,A,w,x;if(s&&(w=Lt,x=nn,xe(E,a,w),xe(b,a,x),T=s(w),A=s(x),A<T)){E=m,b=f;const N=T;T=A,A=N,w=x}w||(w=Lt,xe(E,a,w));const _=Ce(E*2,c),M=t(w,_,T,o+1,r+E/De);let P;if(M===Hi){const N=L(E),G=k(E)-N;P=n(N,G,!0,o+1,r+E/De,w)}else P=M&&ni(E,e,t,n,s,r,o+1);if(P)return!0;x=nn,xe(b,a,x);const I=Ce(b*2,c),C=t(x,I,A,o+1,r+b/De);let D;if(C===Hi){const N=L(b),G=k(b)-N;D=n(N,G,!0,o+1,r+b/De,x)}else D=C&&ni(b,e,t,n,s,r,o+1);return!!D}}const Tn=new be.constructor,ms=new be.constructor,Ct=new Ti(()=>new p.Box3),Wt=new p.Box3,Zt=new p.Box3,Ps=new p.Box3,Os=new p.Box3;let Ds=!1;function Sa(i,e,t,n){if(Ds)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");Ds=!0;const s=i._roots,r=e._roots;let o,a=0,c=0;const u=new p.Matrix4().copy(t).invert();for(let d=0,h=s.length;d<h;d++){Tn.setBuffer(s[d]),c=0;const f=Ct.getPrimitive();xe(0,Tn.float32Array,f),f.applyMatrix4(u);for(let m=0,E=r.length;m<E&&(ms.setBuffer(r[m]),o=ht(0,0,t,u,n,a,c,0,0,f),ms.clearBuffer(),c+=r[m].byteLength/He,!o);m++);if(Ct.releasePrimitive(f),Tn.clearBuffer(),a+=s[d].byteLength/He,o)break}return Ds=!1,o}function ht(i,e,t,n,s,r=0,o=0,a=0,c=0,u=null,d=!1){let h,f;d?(h=ms,f=Tn):(h=Tn,f=ms);const m=h.float32Array,E=h.uint32Array,b=h.uint16Array,T=f.float32Array,A=f.uint32Array,w=f.uint16Array,x=i*2,_=e*2,M=Ce(x,b),P=Ce(_,w);let I=!1;if(P&&M)d?I=s(Ve(e,A),Xe(e*2,w),Ve(i,E),Xe(i*2,b),c,o+e/De,a,r+i/De):I=s(Ve(i,E),Xe(i*2,b),Ve(e,A),Xe(e*2,w),a,r+i/De,c,o+e/De);else if(P){const C=Ct.getPrimitive();xe(e,T,C),C.applyMatrix4(t);const D=Fe(i),L=Be(i,E);xe(D,m,Wt),xe(L,m,Zt);const k=C.intersectsBox(Wt),N=C.intersectsBox(Zt);I=k&&ht(e,D,n,t,s,o,r,c,a+1,C,!d)||N&&ht(e,L,n,t,s,o,r,c,a+1,C,!d),Ct.releasePrimitive(C)}else{const C=Fe(e),D=Be(e,A);xe(C,T,Ps),xe(D,T,Os);const L=u.intersectsBox(Ps),k=u.intersectsBox(Os);if(L&&k)I=ht(i,C,t,n,s,r,o,a,c+1,u,d)||ht(i,D,t,n,s,r,o,a,c+1,u,d);else if(L)if(M)I=ht(i,C,t,n,s,r,o,a,c+1,u,d);else{const N=Ct.getPrimitive();N.copy(Ps).applyMatrix4(t);const V=Fe(i),G=Be(i,E);xe(V,m,Wt),xe(G,m,Zt);const $=N.intersectsBox(Wt),ie=N.intersectsBox(Zt);I=$&&ht(C,V,n,t,s,o,r,c,a+1,N,!d)||ie&&ht(C,G,n,t,s,o,r,c,a+1,N,!d),Ct.releasePrimitive(N)}else if(k)if(M)I=ht(i,D,t,n,s,r,o,a,c+1,u,d);else{const N=Ct.getPrimitive();N.copy(Os).applyMatrix4(t);const V=Fe(i),G=Be(i,E);xe(V,m,Wt),xe(G,m,Zt);const $=N.intersectsBox(Wt),ie=N.intersectsBox(Zt);I=$&&ht(D,V,n,t,s,o,r,c,a+1,N,!d)||ie&&ht(D,G,n,t,s,o,r,c,a+1,N,!d),Ct.releasePrimitive(N)}}return I}const Zi=new p.Box3,Kt=new Float32Array(6);class _a{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(e){e={...Or,...e},Ea(this,e)}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(e,t,n,s){let r=1/0,o=1/0,a=1/0,c=-1/0,u=-1/0,d=-1/0;for(let h=e,f=e+t;h<f;h++){this.writePrimitiveBounds(h,Kt,0);const[m,E,b,T,A,w]=Kt;m<r&&(r=m),T>c&&(c=T),E<o&&(o=E),A>u&&(u=A),b<a&&(a=b),w>d&&(d=w)}return n[s+0]=r,n[s+1]=o,n[s+2]=a,n[s+3]=c,n[s+4]=u,n[s+5]=d,n}computePrimitiveBounds(e,t,n){const s=n.offset||0;for(let r=e,o=e+t;r<o;r++){this.writePrimitiveBounds(r,Kt,0);const[a,c,u,d,h,f]=Kt,m=(a+d)/2,E=(c+h)/2,b=(u+f)/2,T=(d-a)/2,A=(h-c)/2,w=(f-u)/2,x=(r-s)*6;n[x+0]=m,n[x+1]=T+(Math.abs(m)+T)*us,n[x+2]=E,n[x+3]=A+(Math.abs(E)+A)*us,n[x+4]=b,n[x+5]=w+(Math.abs(b)+w)*us}return n}shiftPrimitiveOffsets(e){const t=this._indirectBuffer;if(t)for(let n=0,s=t.length;n<s;n++)t[n]+=e;else{const n=this._roots;for(let s=0;s<n.length;s++){const r=n[s],o=new Uint32Array(r),a=new Uint16Array(r),c=r.byteLength/He;for(let u=0;u<c;u++){const d=De*u,h=2*d;Ce(h,a)&&(o[d+6]+=e)}}}}traverse(e,t=0){const n=this._roots[t],s=new Uint32Array(n),r=new Uint16Array(n);o(0);function o(a,c=0){const u=a*2,d=Ce(u,r);if(d){const h=s[a+6],f=r[u+14];e(c,d,new Float32Array(n,a*4,6),h,f)}else{const h=Fe(a),f=Be(a,s),m=Ts(a,s);e(c,d,new Float32Array(n,a*4,6),m)||(o(h,c+1),o(f,c+1))}}}refit(){const e=this._roots;for(let t=0,n=e.length;t<n;t++){const s=e[t],r=new Uint32Array(s),o=new Uint16Array(s),a=new Float32Array(s),c=s.byteLength/He;for(let u=c-1;u>=0;u--){const d=u*De,h=d*2;if(Ce(h,o)){const m=Ve(d,r),E=Xe(h,o);this.writePrimitiveRangeBounds(m,E,Kt,0),a.set(Kt,d)}else{const m=Fe(d),E=Be(d,r);for(let b=0;b<3;b++){const T=a[m+b],A=a[m+b+3],w=a[E+b],x=a[E+b+3];a[d+b]=T<w?T:w,a[d+b+3]=A>x?A:x}}}}}getBoundingBox(e){return e.makeEmpty(),this._roots.forEach(n=>{xe(0,new Float32Array(n),Zi),e.union(Zi)}),e}shapecast(e){let{boundsTraverseOrder:t,intersectsBounds:n,intersectsRange:s,intersectsPrimitive:r,scratchPrimitive:o,iterate:a}=e;if(s&&r){const h=s;s=(f,m,E,b,T)=>h(f,m,E,b,T)?!0:a(f,m,this,r,E,b,o)}else s||(r?s=(h,f,m,E)=>a(h,f,this,r,m,E,o):s=(h,f,m)=>m);let c=!1,u=0;const d=this._roots;for(let h=0,f=d.length;h<f;h++){const m=d[h];if(c=Ta(this,h,n,s,t,u),c)break;u+=m.byteLength/He}return c}bvhcast(e,t,n){let{intersectsRanges:s}=n;return Sa(this,e,t,s)}}function ba(){return typeof SharedArrayBuffer<"u"}function Ss(i){return i.index?i.index.count:i.attributes.position.count}function _s(i){return Ss(i)/3}function kr(i,e=ArrayBuffer){return i>65535?new Uint32Array(new e(4*i)):new Uint16Array(new e(2*i))}function xa(i,e){if(!i.index){const t=i.attributes.position.count,n=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,s=kr(t,n);i.setIndex(new p.BufferAttribute(s,1));for(let r=0;r<t;r++)s[r]=r}}function Aa(i,e,t){const n=Ss(i)/t,s=e||i.drawRange,r=s.start/t,o=(s.start+s.count)/t,a=Math.max(0,r),c=Math.min(n,o)-a;return{offset:Math.floor(a),count:Math.floor(c)}}function Ma(i,e){return i.groups.map(t=>({offset:t.start/e,count:t.count/e}))}function Ki(i,e,t){const n=Aa(i,e,t),s=Ma(i,t);if(!s.length)return[n];const r=[],o=n.offset,a=n.offset+n.count,c=Ss(i)/t,u=[];for(const f of s){const{offset:m,count:E}=f,b=m,T=isFinite(E)?E:c-m,A=m+T;b<a&&A>o&&(u.push({pos:Math.max(o,b),isStart:!0}),u.push({pos:Math.min(a,A),isStart:!1}))}u.sort((f,m)=>f.pos!==m.pos?f.pos-m.pos:f.type==="end"?-1:1);let d=0,h=null;for(const f of u){const m=f.pos;d!==0&&m!==h&&r.push({offset:h,count:m-h}),d+=f.isStart?1:-1,h=m}return r}function Ra(i,e){const t=i[i.length-1],n=t.offset+t.count>2**16,s=i.reduce((u,d)=>u+d.count,0),r=n?4:2,o=e?new SharedArrayBuffer(s*r):new ArrayBuffer(s*r),a=n?new Uint32Array(o):new Uint16Array(o);let c=0;for(let u=0;u<i.length;u++){const{offset:d,count:h}=i[u];for(let f=0;f<h;f++)a[c+f]=d+f;c+=h}return a}class va extends _a{get indirect(){return!!this._indirectBuffer}get primitiveStride(){return null}get primitiveBufferStride(){return this.indirect?1:this.primitiveStride}set primitiveBufferStride(e){}get primitiveBuffer(){return this.indirect?this._indirectBuffer:this.geometry.index.array}set primitiveBuffer(e){}constructor(e,t={}){if(e.isBufferGeometry){if(e.index&&e.index.isInterleavedBufferAttribute)throw new Error("BVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("BVH: Only BufferGeometries are supported.");if(t.useSharedArrayBuffer&&!ba())throw new Error("BVH: SharedArrayBuffer is not available.");super(),this.geometry=e,this.resolvePrimitiveIndex=t.indirect?n=>this._indirectBuffer[n]:n=>n,this.primitiveBuffer=null,this.primitiveBufferStride=null,this._indirectBuffer=null,t={...Or,...t},t[wi]||this.init(t)}init(e){const{geometry:t,primitiveStride:n}=this;if(e.indirect){const s=Ki(t,e.range,n),r=Ra(s,e.useSharedArrayBuffer);this._indirectBuffer=r}else xa(t,e);super.init(e),!t.boundingBox&&e.setBoundingBox&&(t.boundingBox=this.getBoundingBox(new p.Box3))}getRootRanges(e){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:Ki(this.geometry,e,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class bt{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let n=1/0,s=-1/0;for(let r=0,o=e.length;r<o;r++){const c=e[r][t];n=c<n?c:n,s=c>s?c:s}this.min=n,this.max=s}setFromPoints(e,t){let n=1/0,s=-1/0;for(let r=0,o=t.length;r<o;r++){const a=t[r],c=e.dot(a);n=c<n?c:n,s=c>s?c:s}this.min=n,this.max=s}isSeparated(e){return this.min>e.max||e.min>this.max}}bt.prototype.setFromBox=(function(){const i=new p.Vector3;return function(t,n){const s=n.min,r=n.max;let o=1/0,a=-1/0;for(let c=0;c<=1;c++)for(let u=0;u<=1;u++)for(let d=0;d<=1;d++){i.x=s.x*c+r.x*(1-c),i.y=s.y*u+r.y*(1-u),i.z=s.z*d+r.z*(1-d);const h=t.dot(i);o=Math.min(h,o),a=Math.max(h,a)}this.min=o,this.max=a}})();const Ca=(function(){const i=new p.Vector3,e=new p.Vector3,t=new p.Vector3;return function(s,r,o){const a=s.start,c=i,u=r.start,d=e;t.subVectors(a,u),i.subVectors(s.end,s.start),e.subVectors(r.end,r.start);const h=t.dot(d),f=d.dot(c),m=d.dot(d),E=t.dot(c),T=c.dot(c)*m-f*f;let A,w;T!==0?A=(h*f-E*m)/T:A=0,w=(h+A*f)/m,o.x=A,o.y=w}})(),Si=(function(){const i=new p.Vector2,e=new p.Vector3,t=new p.Vector3;return function(s,r,o,a){Ca(s,r,i);let c=i.x,u=i.y;if(c>=0&&c<=1&&u>=0&&u<=1){s.at(c,o),r.at(u,a);return}else if(c>=0&&c<=1){u<0?r.at(0,a):r.at(1,a),s.closestPointToPoint(a,!0,o);return}else if(u>=0&&u<=1){c<0?s.at(0,o):s.at(1,o),r.closestPointToPoint(o,!0,a);return}else{let d;c<0?d=s.start:d=s.end;let h;u<0?h=r.start:h=r.end;const f=e,m=t;if(s.closestPointToPoint(h,!0,e),r.closestPointToPoint(d,!0,t),f.distanceToSquared(h)<=m.distanceToSquared(d)){o.copy(f),a.copy(h);return}else{o.copy(d),a.copy(m);return}}}})(),Ia=(function(){const i=new p.Vector3,e=new p.Vector3,t=new p.Plane,n=new p.Line3;return function(r,o){const{radius:a,center:c}=r,{a:u,b:d,c:h}=o;if(n.start=u,n.end=d,n.closestPointToPoint(c,!0,i).distanceTo(c)<=a||(n.start=u,n.end=h,n.closestPointToPoint(c,!0,i).distanceTo(c)<=a)||(n.start=d,n.end=h,n.closestPointToPoint(c,!0,i).distanceTo(c)<=a))return!0;const b=o.getPlane(t);if(Math.abs(b.distanceToPoint(c))<=a){const A=b.projectPoint(c,e);if(o.containsPoint(A))return!0}return!1}})(),La=["x","y","z"],Tt=1e-15,Xi=Tt*Tt;function nt(i){return Math.abs(i)<Tt}class dt extends p.Triangle{constructor(...e){super(...e),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new p.Vector3),this.satBounds=new Array(4).fill().map(()=>new bt),this.points=[this.a,this.b,this.c],this.plane=new p.Plane,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new p.Line3,this.needsUpdate=!0}intersectsSphere(e){return Ia(e,this)}update(){const e=this.a,t=this.b,n=this.c,s=this.points,r=this.satAxes,o=this.satBounds,a=r[0],c=o[0];this.getNormal(a),c.setFromPoints(a,s);const u=r[1],d=o[1];u.subVectors(e,t),d.setFromPoints(u,s);const h=r[2],f=o[2];h.subVectors(t,n),f.setFromPoints(h,s);const m=r[3],E=o[3];m.subVectors(n,e),E.setFromPoints(m,s);const b=u.length(),T=h.length(),A=m.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,b<Tt?T<Tt||A<Tt?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(n)):T<Tt?A<Tt?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(e)):A<Tt&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(n),this.degenerateSegment.end.copy(t)),this.plane.setFromNormalAndCoplanarPoint(a,e),this.needsUpdate=!1}}dt.prototype.closestPointToSegment=(function(){const i=new p.Vector3,e=new p.Vector3,t=new p.Line3;return function(s,r=null,o=null){const{start:a,end:c}=s,u=this.points;let d,h=1/0;for(let f=0;f<3;f++){const m=(f+1)%3;t.start.copy(u[f]),t.end.copy(u[m]),Si(t,s,i,e),d=i.distanceToSquared(e),d<h&&(h=d,r&&r.copy(i),o&&o.copy(e))}return this.closestPointToPoint(a,i),d=a.distanceToSquared(i),d<h&&(h=d,r&&r.copy(i),o&&o.copy(a)),this.closestPointToPoint(c,i),d=c.distanceToSquared(i),d<h&&(h=d,r&&r.copy(i),o&&o.copy(c)),Math.sqrt(h)}})();dt.prototype.intersectsTriangle=(function(){const i=new dt,e=new bt,t=new bt,n=new p.Vector3,s=new p.Vector3,r=new p.Vector3,o=new p.Vector3,a=new p.Line3,c=new p.Line3,u=new p.Vector3,d=new p.Vector2,h=new p.Vector2;function f(x,_,M,P){const I=n;!x.isDegenerateIntoPoint&&!x.isDegenerateIntoSegment?I.copy(x.plane.normal):I.copy(_.plane.normal);const C=x.satBounds,D=x.satAxes;for(let N=1;N<4;N++){const V=C[N],G=D[N];if(e.setFromPoints(G,_.points),V.isSeparated(e)||(o.copy(I).cross(G),e.setFromPoints(o,x.points),t.setFromPoints(o,_.points),e.isSeparated(t)))return!1}const L=_.satBounds,k=_.satAxes;for(let N=1;N<4;N++){const V=L[N],G=k[N];if(e.setFromPoints(G,x.points),V.isSeparated(e)||(o.crossVectors(I,G),e.setFromPoints(o,x.points),t.setFromPoints(o,_.points),e.isSeparated(t)))return!1}return M&&(P||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),M.start.set(0,0,0),M.end.set(0,0,0)),!0}function m(x,_,M,P,I,C,D,L,k,N,V){let G=D/(D-L);N.x=P+(I-P)*G,V.start.subVectors(_,x).multiplyScalar(G).add(x),G=D/(D-k),N.y=P+(C-P)*G,V.end.subVectors(M,x).multiplyScalar(G).add(x)}function E(x,_,M,P,I,C,D,L,k,N,V){if(I>0)m(x.c,x.a,x.b,P,_,M,k,D,L,N,V);else if(C>0)m(x.b,x.a,x.c,M,_,P,L,D,k,N,V);else if(L*k>0||D!=0)m(x.a,x.b,x.c,_,M,P,D,L,k,N,V);else if(L!=0)m(x.b,x.a,x.c,M,_,P,L,D,k,N,V);else if(k!=0)m(x.c,x.a,x.b,P,_,M,k,D,L,N,V);else return!0;return!1}function b(x,_,M,P){const I=_.degenerateSegment,C=x.plane.distanceToPoint(I.start),D=x.plane.distanceToPoint(I.end);return nt(C)?nt(D)?f(x,_,M,P):(M&&(M.start.copy(I.start),M.end.copy(I.start)),x.containsPoint(I.start)):nt(D)?(M&&(M.start.copy(I.end),M.end.copy(I.end)),x.containsPoint(I.end)):x.plane.intersectLine(I,n)!=null?(M&&(M.start.copy(n),M.end.copy(n)),x.containsPoint(n)):!1}function T(x,_,M){const P=_.a;return nt(x.plane.distanceToPoint(P))&&x.containsPoint(P)?(M&&(M.start.copy(P),M.end.copy(P)),!0):!1}function A(x,_,M){const P=x.degenerateSegment,I=_.a;return P.closestPointToPoint(I,!0,n),I.distanceToSquared(n)<Xi?(M&&(M.start.copy(I),M.end.copy(I)),!0):!1}function w(x,_,M,P){if(x.isDegenerateIntoSegment)if(_.isDegenerateIntoSegment){const I=x.degenerateSegment,C=_.degenerateSegment,D=s,L=r;I.delta(D),C.delta(L);const k=n.subVectors(C.start,I.start),N=D.x*L.y-D.y*L.x;if(nt(N))return!1;const V=(k.x*L.y-k.y*L.x)/N,G=-(D.x*k.y-D.y*k.x)/N;if(V<0||V>1||G<0||G>1)return!1;const $=I.start.z+D.z*V,ie=C.start.z+L.z*G;return nt($-ie)?(M&&(M.start.copy(I.start).addScaledVector(D,V),M.end.copy(I.start).addScaledVector(D,V)),!0):!1}else return _.isDegenerateIntoPoint?A(x,_,M):b(_,x,M,P);else{if(x.isDegenerateIntoPoint)return _.isDegenerateIntoPoint?_.a.distanceToSquared(x.a)<Xi?(M&&(M.start.copy(x.a),M.end.copy(x.a)),!0):!1:_.isDegenerateIntoSegment?A(_,x,M):T(_,x,M);if(_.isDegenerateIntoPoint)return T(x,_,M);if(_.isDegenerateIntoSegment)return b(x,_,M,P)}}return function(_,M=null,P=!1){this.needsUpdate&&this.update(),_.isExtendedTriangle?_.needsUpdate&&_.update():(i.copy(_),i.update(),_=i);const I=w(this,_,M,P);if(I!==void 0)return I;const C=this.plane,D=_.plane;let L=D.distanceToPoint(this.a),k=D.distanceToPoint(this.b),N=D.distanceToPoint(this.c);nt(L)&&(L=0),nt(k)&&(k=0),nt(N)&&(N=0);const V=L*k,G=L*N;if(V>0&&G>0)return!1;let $=C.distanceToPoint(_.a),ie=C.distanceToPoint(_.b),Ne=C.distanceToPoint(_.c);nt($)&&($=0),nt(ie)&&(ie=0),nt(Ne)&&(Ne=0);const ot=$*ie,Re=$*Ne;if(ot>0&&Re>0)return!1;s.copy(C.normal),r.copy(D.normal);const ze=s.cross(r);let je=0,Ae=Math.abs(ze.x);const ye=Math.abs(ze.y);ye>Ae&&(Ae=ye,je=1),Math.abs(ze.z)>Ae&&(je=2);const Ge=La[je],xt=this.a[Ge],ge=this.b[Ge],at=this.c[Ge],ct=_.a[Ge],on=_.b[Ge],Ht=_.c[Ge];if(E(this,xt,ge,at,V,G,L,k,N,d,a))return f(this,_,M,P);if(E(_,ct,on,Ht,ot,Re,$,ie,Ne,h,c))return f(this,_,M,P);if(d.y<d.x){const Et=d.y;d.y=d.x,d.x=Et,u.copy(a.start),a.start.copy(a.end),a.end.copy(u)}if(h.y<h.x){const Et=h.y;h.y=h.x,h.x=Et,u.copy(c.start),c.start.copy(c.end),c.end.copy(u)}return d.y<h.x||h.y<d.x?!1:(M&&(h.x>d.x?M.start.copy(c.start):M.start.copy(a.start),h.y<d.y?M.end.copy(c.end):M.end.copy(a.end)),!0)}})();dt.prototype.distanceToPoint=(function(){const i=new p.Vector3;return function(t){return this.closestPointToPoint(t,i),t.distanceTo(i)}})();dt.prototype.distanceToTriangle=(function(){const i=new p.Vector3,e=new p.Vector3,t=["a","b","c"],n=new p.Line3,s=new p.Line3;return function(o,a=null,c=null){const u=a||c?n:null;if(this.intersectsTriangle(o,u,!0))return(a||c)&&(a&&u.getCenter(a),c&&u.getCenter(c)),0;let d=1/0;for(let h=0;h<3;h++){let f;const m=t[h],E=o[m];this.closestPointToPoint(E,i),f=E.distanceToSquared(i),f<d&&(d=f,a&&a.copy(i),c&&c.copy(E));const b=this[m];o.closestPointToPoint(b,i),f=b.distanceToSquared(i),f<d&&(d=f,a&&a.copy(b),c&&c.copy(i))}for(let h=0;h<3;h++){const f=t[h],m=t[(h+1)%3];n.set(this[f],this[m]);for(let E=0;E<3;E++){const b=t[E],T=t[(E+1)%3];s.set(o[b],o[T]),Si(n,s,i,e);const A=i.distanceToSquared(e);A<d&&(d=A,a&&a.copy(i),c&&c.copy(e))}}return Math.sqrt(d)}})();class Ye{constructor(e,t,n){this.isOrientedBox=!0,this.min=new p.Vector3,this.max=new p.Vector3,this.matrix=new p.Matrix4,this.invMatrix=new p.Matrix4,this.points=new Array(8).fill().map(()=>new p.Vector3),this.satAxes=new Array(3).fill().map(()=>new p.Vector3),this.satBounds=new Array(3).fill().map(()=>new bt),this.alignedSatBounds=new Array(3).fill().map(()=>new bt),this.needsUpdate=!1,e&&this.min.copy(e),t&&this.max.copy(t),n&&this.matrix.copy(n)}set(e,t,n){this.min.copy(e),this.max.copy(t),this.matrix.copy(n),this.needsUpdate=!0}copy(e){this.min.copy(e.min),this.max.copy(e.max),this.matrix.copy(e.matrix),this.needsUpdate=!0}}Ye.prototype.update=(function(){return function(){const e=this.matrix,t=this.min,n=this.max,s=this.points;for(let u=0;u<=1;u++)for(let d=0;d<=1;d++)for(let h=0;h<=1;h++){const f=1*u|2*d|4*h,m=s[f];m.x=u?n.x:t.x,m.y=d?n.y:t.y,m.z=h?n.z:t.z,m.applyMatrix4(e)}const r=this.satBounds,o=this.satAxes,a=s[0];for(let u=0;u<3;u++){const d=o[u],h=r[u],f=1<<u,m=s[f];d.subVectors(a,m),h.setFromPoints(d,s)}const c=this.alignedSatBounds;c[0].setFromPointsField(s,"x"),c[1].setFromPointsField(s,"y"),c[2].setFromPointsField(s,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}})();Ye.prototype.intersectsBox=(function(){const i=new bt;return function(t){this.needsUpdate&&this.update();const n=t.min,s=t.max,r=this.satBounds,o=this.satAxes,a=this.alignedSatBounds;if(i.min=n.x,i.max=s.x,a[0].isSeparated(i)||(i.min=n.y,i.max=s.y,a[1].isSeparated(i))||(i.min=n.z,i.max=s.z,a[2].isSeparated(i)))return!1;for(let c=0;c<3;c++){const u=o[c],d=r[c];if(i.setFromBox(u,t),d.isSeparated(i))return!1}return!0}})();Ye.prototype.intersectsTriangle=(function(){const i=new dt,e=new Array(3),t=new bt,n=new bt,s=new p.Vector3;return function(o){this.needsUpdate&&this.update(),o.isExtendedTriangle?o.needsUpdate&&o.update():(i.copy(o),i.update(),o=i);const a=this.satBounds,c=this.satAxes;e[0]=o.a,e[1]=o.b,e[2]=o.c;for(let f=0;f<3;f++){const m=a[f],E=c[f];if(t.setFromPoints(E,e),m.isSeparated(t))return!1}const u=o.satBounds,d=o.satAxes,h=this.points;for(let f=0;f<3;f++){const m=u[f],E=d[f];if(t.setFromPoints(E,h),m.isSeparated(t))return!1}for(let f=0;f<3;f++){const m=c[f];for(let E=0;E<4;E++){const b=d[E];if(s.crossVectors(m,b),t.setFromPoints(s,e),n.setFromPoints(s,h),t.isSeparated(n))return!1}}return!0}})();Ye.prototype.closestPointToPoint=(function(){return function(e,t){return this.needsUpdate&&this.update(),t.copy(e).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),t}})();Ye.prototype.distanceToPoint=(function(){const i=new p.Vector3;return function(t){return this.closestPointToPoint(t,i),t.distanceTo(i)}})();Ye.prototype.distanceToBox=(function(){const i=["x","y","z"],e=new Array(12).fill().map(()=>new p.Line3),t=new Array(12).fill().map(()=>new p.Line3),n=new p.Vector3,s=new p.Vector3;return function(o,a=0,c=null,u=null){if(this.needsUpdate&&this.update(),this.intersectsBox(o))return(c||u)&&(o.getCenter(s),this.closestPointToPoint(s,n),o.closestPointToPoint(n,s),c&&c.copy(n),u&&u.copy(s)),0;const d=a*a,h=o.min,f=o.max,m=this.points;let E=1/0;for(let T=0;T<8;T++){const A=m[T];s.copy(A).clamp(h,f);const w=A.distanceToSquared(s);if(w<E&&(E=w,c&&c.copy(A),u&&u.copy(s),w<d))return Math.sqrt(w)}let b=0;for(let T=0;T<3;T++)for(let A=0;A<=1;A++)for(let w=0;w<=1;w++){const x=(T+1)%3,_=(T+2)%3,M=A<<x|w<<_,P=1<<T|A<<x|w<<_,I=m[M],C=m[P];e[b].set(I,C);const L=i[T],k=i[x],N=i[_],V=t[b],G=V.start,$=V.end;G[L]=h[L],G[k]=A?h[k]:f[k],G[N]=w?h[N]:f[k],$[L]=f[L],$[k]=A?h[k]:f[k],$[N]=w?h[N]:f[k],b++}for(let T=0;T<=1;T++)for(let A=0;A<=1;A++)for(let w=0;w<=1;w++){s.x=T?f.x:h.x,s.y=A?f.y:h.y,s.z=w?f.z:h.z,this.closestPointToPoint(s,n);const x=s.distanceToSquared(n);if(x<E&&(E=x,c&&c.copy(n),u&&u.copy(s),x<d))return Math.sqrt(x)}for(let T=0;T<12;T++){const A=e[T];for(let w=0;w<12;w++){const x=t[w];Si(A,x,n,s);const _=n.distanceToSquared(s);if(_<E&&(E=_,c&&c.copy(n),u&&u.copy(s),_<d))return Math.sqrt(_)}}return Math.sqrt(E)}})();class Pa extends Ti{constructor(){super(()=>new dt)}}const rt=new Pa,un=new p.Vector3,Ns=new p.Vector3;function Oa(i,e,t={},n=0,s=1/0){const r=n*n,o=s*s;let a=1/0,c=null;if(i.shapecast({boundsTraverseOrder:d=>(un.copy(e).clamp(d.min,d.max),un.distanceToSquared(e)),intersectsBounds:(d,h,f)=>f<a&&f<o,intersectsTriangle:(d,h)=>{d.closestPointToPoint(e,un);const f=e.distanceToSquared(un);return f<a&&(Ns.copy(un),a=f,c=h),f<r}}),a===1/0)return null;const u=Math.sqrt(a);return t.point?t.point.copy(Ns):t.point=Ns.clone(),t.distance=u,t.faceIndex=c,t}const Wn=parseInt(p.REVISION)>=169,Da=parseInt(p.REVISION)<=161,Nt=new p.Vector3,kt=new p.Vector3,Ft=new p.Vector3,Zn=new p.Vector2,Kn=new p.Vector2,Xn=new p.Vector2,Yi=new p.Vector3,qi=new p.Vector3,$i=new p.Vector3,dn=new p.Vector3;function Na(i,e,t,n,s,r,o,a){let c;if(r===p.BackSide?c=i.intersectTriangle(n,t,e,!0,s):c=i.intersectTriangle(e,t,n,r!==p.DoubleSide,s),c===null)return null;const u=i.origin.distanceTo(s);return u<o||u>a?null:{distance:u,point:s.clone()}}function Qi(i,e,t,n,s,r,o,a,c,u,d){Nt.fromBufferAttribute(e,r),kt.fromBufferAttribute(e,o),Ft.fromBufferAttribute(e,a);const h=Na(i,Nt,kt,Ft,dn,c,u,d);if(h){if(n){Zn.fromBufferAttribute(n,r),Kn.fromBufferAttribute(n,o),Xn.fromBufferAttribute(n,a),h.uv=new p.Vector2;const m=p.Triangle.getInterpolation(dn,Nt,kt,Ft,Zn,Kn,Xn,h.uv);Wn||(h.uv=m)}if(s){Zn.fromBufferAttribute(s,r),Kn.fromBufferAttribute(s,o),Xn.fromBufferAttribute(s,a),h.uv1=new p.Vector2;const m=p.Triangle.getInterpolation(dn,Nt,kt,Ft,Zn,Kn,Xn,h.uv1);Wn||(h.uv1=m),Da&&(h.uv2=h.uv1)}if(t){Yi.fromBufferAttribute(t,r),qi.fromBufferAttribute(t,o),$i.fromBufferAttribute(t,a),h.normal=new p.Vector3;const m=p.Triangle.getInterpolation(dn,Nt,kt,Ft,Yi,qi,$i,h.normal);h.normal.dot(i.direction)>0&&h.normal.multiplyScalar(-1),Wn||(h.normal=m)}const f={a:r,b:o,c:a,normal:new p.Vector3,materialIndex:0};if(p.Triangle.getNormal(Nt,kt,Ft,f.normal),h.face=f,h.faceIndex=r,Wn){const m=new p.Vector3;p.Triangle.getBarycoord(dn,Nt,kt,Ft,m),h.barycoord=m}}return h}function Ji(i){return i&&i.isMaterial?i.side:i}function bs(i,e,t,n,s,r,o){const a=n*3;let c=a+0,u=a+1,d=a+2;const{index:h,groups:f}=i;i.index&&(c=h.getX(c),u=h.getX(u),d=h.getX(d));const{position:m,normal:E,uv:b,uv1:T}=i.attributes;if(Array.isArray(e)){const A=n*3;for(let w=0,x=f.length;w<x;w++){const{start:_,count:M,materialIndex:P}=f[w];if(A>=_&&A<_+M){const I=Ji(e[P]),C=Qi(t,m,E,b,T,c,u,d,I,r,o);if(C)if(C.faceIndex=n,C.face.materialIndex=P,s)s.push(C);else return C}}}else{const A=Ji(e),w=Qi(t,m,E,b,T,c,u,d,A,r,o);if(w)if(w.faceIndex=n,w.face.materialIndex=0,s)s.push(w);else return w}return null}function Ie(i,e,t,n){const s=i.a,r=i.b,o=i.c;let a=e,c=e+1,u=e+2;t&&(a=t.getX(a),c=t.getX(c),u=t.getX(u)),s.x=n.getX(a),s.y=n.getY(a),s.z=n.getZ(a),r.x=n.getX(c),r.y=n.getY(c),r.z=n.getZ(c),o.x=n.getX(u),o.y=n.getY(u),o.z=n.getZ(u)}function ka(i,e,t,n,s,r,o,a){const{geometry:c,_indirectBuffer:u}=i;for(let d=n,h=n+s;d<h;d++)bs(c,e,t,d,r,o,a)}function Fa(i,e,t,n,s,r,o){const{geometry:a,_indirectBuffer:c}=i;let u=1/0,d=null;for(let h=n,f=n+s;h<f;h++){let m;m=bs(a,e,t,h,null,r,o),m&&m.distance<u&&(d=m,u=m.distance)}return d}function Ba(i,e,t,n,s,r,o){const{geometry:a}=t,{index:c}=a,u=a.attributes.position;for(let d=i,h=e+i;d<h;d++){let f;if(f=d,Ie(o,f*3,c,u),o.needsUpdate=!0,n(o,f,s,r))return!0}return!1}function za(i,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=i.geometry,n=t.index?t.index.array:null,s=t.attributes.position;let r,o,a,c,u=0;const d=i._roots;for(let f=0,m=d.length;f<m;f++)r=d[f],o=new Uint32Array(r),a=new Uint16Array(r),c=new Float32Array(r),h(0,u),u+=r.byteLength;function h(f,m,E=!1){const b=f*2;if(Ce(b,a)){const T=Ve(f,o),A=Xe(b,a);let w=1/0,x=1/0,_=1/0,M=-1/0,P=-1/0,I=-1/0;for(let C=3*T,D=3*(T+A);C<D;C++){let L=n[C];const k=s.getX(L),N=s.getY(L),V=s.getZ(L);k<w&&(w=k),k>M&&(M=k),N<x&&(x=N),N>P&&(P=N),V<_&&(_=V),V>I&&(I=V)}return c[f+0]!==w||c[f+1]!==x||c[f+2]!==_||c[f+3]!==M||c[f+4]!==P||c[f+5]!==I?(c[f+0]=w,c[f+1]=x,c[f+2]=_,c[f+3]=M,c[f+4]=P,c[f+5]=I,!0):!1}else{const T=Fe(f),A=Be(f,o);let w=E,x=!1,_=!1;if(e){if(!w){const L=T/De+m/He,k=A/De+m/He;x=e.has(L),_=e.has(k),w=!x&&!_}}else x=!0,_=!0;const M=w||x,P=w||_;let I=!1;M&&(I=h(T,m,w));let C=!1;P&&(C=h(A,m,w));const D=I||C;if(D)for(let L=0;L<3;L++){const k=T+L,N=A+L,V=c[k],G=c[k+3],$=c[N],ie=c[N+3];c[f+L]=V<$?V:$,c[f+L+3]=G>ie?G:ie}return D}}}function Ot(i,e,t,n,s){let r,o,a,c,u,d;const h=1/t.direction.x,f=1/t.direction.y,m=1/t.direction.z,E=t.origin.x,b=t.origin.y,T=t.origin.z;let A=e[i],w=e[i+3],x=e[i+1],_=e[i+3+1],M=e[i+2],P=e[i+3+2];return h>=0?(r=(A-E)*h,o=(w-E)*h):(r=(w-E)*h,o=(A-E)*h),f>=0?(a=(x-b)*f,c=(_-b)*f):(a=(_-b)*f,c=(x-b)*f),r>c||a>o||((a>r||isNaN(r))&&(r=a),(c<o||isNaN(o))&&(o=c),m>=0?(u=(M-T)*m,d=(P-T)*m):(u=(P-T)*m,d=(M-T)*m),r>d||u>o)?!1:((u>r||r!==r)&&(r=u),(d<o||o!==o)&&(o=d),r<=s&&o>=n)}function Ua(i,e,t,n,s,r,o,a){const{geometry:c,_indirectBuffer:u}=i;for(let d=n,h=n+s;d<h;d++){let f=u?u[d]:d;bs(c,e,t,f,r,o,a)}}function Ha(i,e,t,n,s,r,o){const{geometry:a,_indirectBuffer:c}=i;let u=1/0,d=null;for(let h=n,f=n+s;h<f;h++){let m;m=bs(a,e,t,c?c[h]:h,null,r,o),m&&m.distance<u&&(d=m,u=m.distance)}return d}function Va(i,e,t,n,s,r,o){const{geometry:a}=t,{index:c}=a,u=a.attributes.position;for(let d=i,h=e+i;d<h;d++){let f;if(f=t.resolveTriangleIndex(d),Ie(o,f*3,c,u),o.needsUpdate=!0,n(o,f,s,r))return!0}return!1}function ja(i,e,t,n,s,r,o){be.setBuffer(i._roots[e]),si(0,i,t,n,s,r,o),be.clearBuffer()}function si(i,e,t,n,s,r,o){const{float32Array:a,uint16Array:c,uint32Array:u}=be,d=i*2;if(Ce(d,c)){const f=Ve(i,u),m=Xe(d,c);ka(e,t,n,f,m,s,r,o)}else{const f=Fe(i);Ot(f,a,n,r,o)&&si(f,e,t,n,s,r,o);const m=Be(i,u);Ot(m,a,n,r,o)&&si(m,e,t,n,s,r,o)}}const Ga=["x","y","z"];function Wa(i,e,t,n,s,r){be.setBuffer(i._roots[e]);const o=ii(0,i,t,n,s,r);return be.clearBuffer(),o}function ii(i,e,t,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:c}=be;let u=i*2;if(Ce(u,a)){const h=Ve(i,c),f=Xe(u,a);return Fa(e,t,n,h,f,s,r)}else{const h=Ts(i,c),f=Ga[h],E=n.direction[f]>=0;let b,T;E?(b=Fe(i),T=Be(i,c)):(b=Be(i,c),T=Fe(i));const w=Ot(b,o,n,s,r)?ii(b,e,t,n,s,r):null;if(w){const M=w.point[f];if(E?M<=o[T+h]:M>=o[T+h+3])return w}const _=Ot(T,o,n,s,r)?ii(T,e,t,n,s,r):null;return w&&_?w.distance<=_.distance?w:_:w||_||null}}const Yn=new p.Box3,Xt=new dt,Yt=new dt,fn=new p.Matrix4,er=new Ye,qn=new Ye;function Za(i,e,t,n){be.setBuffer(i._roots[e]);const s=ri(0,i,t,n);return be.clearBuffer(),s}function ri(i,e,t,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=be;let c=i*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),er.set(t.boundingBox.min,t.boundingBox.max,n),s=er),Ce(c,o)){const d=e.geometry,h=d.index,f=d.attributes.position,m=t.index,E=t.attributes.position,b=Ve(i,a),T=Xe(c,o);if(fn.copy(n).invert(),t.boundsTree)return xe(i,r,qn),qn.matrix.copy(fn),qn.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:w=>qn.intersectsBox(w),intersectsTriangle:w=>{w.a.applyMatrix4(n),w.b.applyMatrix4(n),w.c.applyMatrix4(n),w.needsUpdate=!0;for(let x=b*3,_=(T+b)*3;x<_;x+=3)if(Ie(Yt,x,h,f),Yt.needsUpdate=!0,w.intersectsTriangle(Yt))return!0;return!1}});{const A=_s(t);for(let w=b*3,x=(T+b)*3;w<x;w+=3){Ie(Xt,w,h,f),Xt.a.applyMatrix4(fn),Xt.b.applyMatrix4(fn),Xt.c.applyMatrix4(fn),Xt.needsUpdate=!0;for(let _=0,M=A*3;_<M;_+=3)if(Ie(Yt,_,m,E),Yt.needsUpdate=!0,Xt.intersectsTriangle(Yt))return!0}}}else{const d=Fe(i),h=Be(i,a);return xe(d,r,Yn),!!(s.intersectsBox(Yn)&&ri(d,e,t,n,s)||(xe(h,r,Yn),s.intersectsBox(Yn)&&ri(h,e,t,n,s)))}}const $n=new p.Matrix4,ks=new Ye,pn=new Ye,Ka=new p.Vector3,Xa=new p.Vector3,Ya=new p.Vector3,qa=new p.Vector3;function $a(i,e,t,n={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),ks.set(e.boundingBox.min,e.boundingBox.max,t),ks.needsUpdate=!0;const a=i.geometry,c=a.attributes.position,u=a.index,d=e.attributes.position,h=e.index,f=rt.getPrimitive(),m=rt.getPrimitive();let E=Ka,b=Xa,T=null,A=null;s&&(T=Ya,A=qa);let w=1/0,x=null,_=null;return $n.copy(t).invert(),pn.matrix.copy($n),i.shapecast({boundsTraverseOrder:M=>ks.distanceToBox(M),intersectsBounds:(M,P,I)=>I<w&&I<o?(P&&(pn.min.copy(M.min),pn.max.copy(M.max),pn.needsUpdate=!0),!0):!1,intersectsRange:(M,P)=>{if(e.boundsTree)return e.boundsTree.shapecast({boundsTraverseOrder:C=>pn.distanceToBox(C),intersectsBounds:(C,D,L)=>L<w&&L<o,intersectsRange:(C,D)=>{for(let L=C,k=C+D;L<k;L++){Ie(m,3*L,h,d),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let N=M,V=M+P;N<V;N++){Ie(f,3*N,u,c),f.needsUpdate=!0;const G=f.distanceToTriangle(m,E,T);if(G<w&&(b.copy(E),A&&A.copy(T),w=G,x=N,_=L),G<r)return!0}}}});{const I=_s(e);for(let C=0,D=I;C<D;C++){Ie(m,3*C,h,d),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let L=M,k=M+P;L<k;L++){Ie(f,3*L,u,c),f.needsUpdate=!0;const N=f.distanceToTriangle(m,E,T);if(N<w&&(b.copy(E),A&&A.copy(T),w=N,x=L,_=C),N<r)return!0}}}}}),rt.releasePrimitive(f),rt.releasePrimitive(m),w===1/0?null:(n.point?n.point.copy(b):n.point=b.clone(),n.distance=w,n.faceIndex=x,s&&(s.point?s.point.copy(A):s.point=A.clone(),s.point.applyMatrix4($n),b.applyMatrix4($n),s.distance=b.sub(s.point).length(),s.faceIndex=_),n)}function Qa(i,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=i.geometry,n=t.index?t.index.array:null,s=t.attributes.position;let r,o,a,c,u=0;const d=i._roots;for(let f=0,m=d.length;f<m;f++)r=d[f],o=new Uint32Array(r),a=new Uint16Array(r),c=new Float32Array(r),h(0,u),u+=r.byteLength;function h(f,m,E=!1){const b=f*2;if(Ce(b,a)){const T=Ve(f,o),A=Xe(b,a);let w=1/0,x=1/0,_=1/0,M=-1/0,P=-1/0,I=-1/0;for(let C=T,D=T+A;C<D;C++){const L=3*i.resolveTriangleIndex(C);for(let k=0;k<3;k++){let N=L+k;N=n?n[N]:N;const V=s.getX(N),G=s.getY(N),$=s.getZ(N);V<w&&(w=V),V>M&&(M=V),G<x&&(x=G),G>P&&(P=G),$<_&&(_=$),$>I&&(I=$)}}return c[f+0]!==w||c[f+1]!==x||c[f+2]!==_||c[f+3]!==M||c[f+4]!==P||c[f+5]!==I?(c[f+0]=w,c[f+1]=x,c[f+2]=_,c[f+3]=M,c[f+4]=P,c[f+5]=I,!0):!1}else{const T=Fe(f),A=Be(f,o);let w=E,x=!1,_=!1;if(e){if(!w){const L=T/De+m/He,k=A/De+m/He;x=e.has(L),_=e.has(k),w=!x&&!_}}else x=!0,_=!0;const M=w||x,P=w||_;let I=!1;M&&(I=h(T,m,w));let C=!1;P&&(C=h(A,m,w));const D=I||C;if(D)for(let L=0;L<3;L++){const k=T+L,N=A+L,V=c[k],G=c[k+3],$=c[N],ie=c[N+3];c[f+L]=V<$?V:$,c[f+L+3]=G>ie?G:ie}return D}}}function Ja(i,e,t,n,s,r,o){be.setBuffer(i._roots[e]),oi(0,i,t,n,s,r,o),be.clearBuffer()}function oi(i,e,t,n,s,r,o){const{float32Array:a,uint16Array:c,uint32Array:u}=be,d=i*2;if(Ce(d,c)){const f=Ve(i,u),m=Xe(d,c);Ua(e,t,n,f,m,s,r,o)}else{const f=Fe(i);Ot(f,a,n,r,o)&&oi(f,e,t,n,s,r,o);const m=Be(i,u);Ot(m,a,n,r,o)&&oi(m,e,t,n,s,r,o)}}const ec=["x","y","z"];function tc(i,e,t,n,s,r){be.setBuffer(i._roots[e]);const o=ai(0,i,t,n,s,r);return be.clearBuffer(),o}function ai(i,e,t,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:c}=be;let u=i*2;if(Ce(u,a)){const h=Ve(i,c),f=Xe(u,a);return Ha(e,t,n,h,f,s,r)}else{const h=Ts(i,c),f=ec[h],E=n.direction[f]>=0;let b,T;E?(b=Fe(i),T=Be(i,c)):(b=Be(i,c),T=Fe(i));const w=Ot(b,o,n,s,r)?ai(b,e,t,n,s,r):null;if(w){const M=w.point[f];if(E?M<=o[T+h]:M>=o[T+h+3])return w}const _=Ot(T,o,n,s,r)?ai(T,e,t,n,s,r):null;return w&&_?w.distance<=_.distance?w:_:w||_||null}}const Qn=new p.Box3,qt=new dt,$t=new dt,mn=new p.Matrix4,tr=new Ye,Jn=new Ye;function nc(i,e,t,n){be.setBuffer(i._roots[e]);const s=ci(0,i,t,n);return be.clearBuffer(),s}function ci(i,e,t,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=be;let c=i*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),tr.set(t.boundingBox.min,t.boundingBox.max,n),s=tr),Ce(c,o)){const d=e.geometry,h=d.index,f=d.attributes.position,m=t.index,E=t.attributes.position,b=Ve(i,a),T=Xe(c,o);if(mn.copy(n).invert(),t.boundsTree)return xe(i,r,Jn),Jn.matrix.copy(mn),Jn.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:w=>Jn.intersectsBox(w),intersectsTriangle:w=>{w.a.applyMatrix4(n),w.b.applyMatrix4(n),w.c.applyMatrix4(n),w.needsUpdate=!0;for(let x=b,_=T+b;x<_;x++)if(Ie($t,3*e.resolveTriangleIndex(x),h,f),$t.needsUpdate=!0,w.intersectsTriangle($t))return!0;return!1}});{const A=_s(t);for(let w=b,x=T+b;w<x;w++){const _=e.resolveTriangleIndex(w);Ie(qt,3*_,h,f),qt.a.applyMatrix4(mn),qt.b.applyMatrix4(mn),qt.c.applyMatrix4(mn),qt.needsUpdate=!0;for(let M=0,P=A*3;M<P;M+=3)if(Ie($t,M,m,E),$t.needsUpdate=!0,qt.intersectsTriangle($t))return!0}}}else{const d=Fe(i),h=Be(i,a);return xe(d,r,Qn),!!(s.intersectsBox(Qn)&&ci(d,e,t,n,s)||(xe(h,r,Qn),s.intersectsBox(Qn)&&ci(h,e,t,n,s)))}}const es=new p.Matrix4,Fs=new Ye,gn=new Ye,sc=new p.Vector3,ic=new p.Vector3,rc=new p.Vector3,oc=new p.Vector3;function ac(i,e,t,n={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),Fs.set(e.boundingBox.min,e.boundingBox.max,t),Fs.needsUpdate=!0;const a=i.geometry,c=a.attributes.position,u=a.index,d=e.attributes.position,h=e.index,f=rt.getPrimitive(),m=rt.getPrimitive();let E=sc,b=ic,T=null,A=null;s&&(T=rc,A=oc);let w=1/0,x=null,_=null;return es.copy(t).invert(),gn.matrix.copy(es),i.shapecast({boundsTraverseOrder:M=>Fs.distanceToBox(M),intersectsBounds:(M,P,I)=>I<w&&I<o?(P&&(gn.min.copy(M.min),gn.max.copy(M.max),gn.needsUpdate=!0),!0):!1,intersectsRange:(M,P)=>{if(e.boundsTree){const I=e.boundsTree;return I.shapecast({boundsTraverseOrder:C=>gn.distanceToBox(C),intersectsBounds:(C,D,L)=>L<w&&L<o,intersectsRange:(C,D)=>{for(let L=C,k=C+D;L<k;L++){const N=I.resolveTriangleIndex(L);Ie(m,3*N,h,d),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let V=M,G=M+P;V<G;V++){const $=i.resolveTriangleIndex(V);Ie(f,3*$,u,c),f.needsUpdate=!0;const ie=f.distanceToTriangle(m,E,T);if(ie<w&&(b.copy(E),A&&A.copy(T),w=ie,x=V,_=L),ie<r)return!0}}}})}else{const I=_s(e);for(let C=0,D=I;C<D;C++){Ie(m,3*C,h,d),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let L=M,k=M+P;L<k;L++){const N=i.resolveTriangleIndex(L);Ie(f,3*N,u,c),f.needsUpdate=!0;const V=f.distanceToTriangle(m,E,T);if(V<w&&(b.copy(E),A&&A.copy(T),w=V,x=L,_=C),V<r)return!0}}}}}),rt.releasePrimitive(f),rt.releasePrimitive(m),w===1/0?null:(n.point?n.point.copy(b):n.point=b.clone(),n.distance=w,n.faceIndex=x,s&&(s.point?s.point.copy(A):s.point=A.clone(),s.point.applyMatrix4(es),b.applyMatrix4(es),s.distance=b.sub(s.point).length(),s.faceIndex=_),n)}function nr(i,e,t){return i===null?null:(i.point.applyMatrix4(e.matrixWorld),i.distance=i.point.distanceTo(t.ray.origin),i.object=e,i)}const ts=new Ye,ns=new p.Ray,sr=new p.Vector3,ir=new p.Matrix4,rr=new p.Vector3,Bs=["getX","getY","getZ"];class bn extends va{static serialize(e,t={}){t={cloneBuffers:!0,...t};const n=e.geometry,s=e._roots,r=e._indirectBuffer,o=n.getIndex(),a={version:1,roots:null,index:null,indirectBuffer:null};return t.cloneBuffers?(a.roots=s.map(c=>c.slice()),a.index=o?o.array.slice():null,a.indirectBuffer=r?r.slice():null):(a.roots=s,a.index=o?o.array:null,a.indirectBuffer=r),a}static deserialize(e,t,n={}){n={setIndex:!0,indirect:!!e.indirectBuffer,...n};const{index:s,roots:r,indirectBuffer:o}=e;e.version||(console.warn("MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."),c(r));const a=new bn(t,{...n,[wi]:!0});if(a._roots=r,a._indirectBuffer=o||null,n.setIndex){const u=t.getIndex();if(u===null){const d=new p.BufferAttribute(e.index,1,!1);t.setIndex(d)}else u.array!==s&&(u.array.set(s),u.needsUpdate=!0)}return a;function c(u){for(let d=0;d<u.length;d++){const h=u[d],f=new Uint32Array(h),m=new Uint16Array(h);for(let E=0,b=h.byteLength/He;E<b;E++){const T=De*E,A=2*T;Ce(A,m)||(f[T+6]=f[T+6]/De-E)}}}}get primitiveStride(){return 3}get resolveTriangleIndex(){return this.resolvePrimitiveIndex}constructor(e,t={}){t.maxLeafTris&&(console.warn('MeshBVH: "maxLeafTris" option has been deprecated. Use maxLeafSize, instead.'),t={...t,maxLeafSize:t.maxLeafTris}),super(e,t)}shiftTriangleOffsets(e){return super.shiftPrimitiveOffsets(e)}writePrimitiveBounds(e,t,n){const s=this.geometry,r=this._indirectBuffer,o=s.attributes.position,a=s.index?s.index.array:null,u=(r?r[e]:e)*3;let d=u+0,h=u+1,f=u+2;a&&(d=a[d],h=a[h],f=a[f]);for(let m=0;m<3;m++){const E=o[Bs[m]](d),b=o[Bs[m]](h),T=o[Bs[m]](f);let A=E;b<A&&(A=b),T<A&&(A=T);let w=E;b>w&&(w=b),T>w&&(w=T),t[n+m]=A,t[n+m+3]=w}return t}computePrimitiveBounds(e,t,n){const s=this.geometry,r=this._indirectBuffer,o=s.attributes.position,a=s.index?s.index.array:null,c=o.normalized;if(e<0||t+e-n.offset>n.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const u=o.array,d=o.offset||0;let h=3;o.isInterleavedBufferAttribute&&(h=o.data.stride);const f=["getX","getY","getZ"],m=n.offset;for(let E=e,b=e+t;E<b;E++){const A=(r?r[E]:E)*3,w=(E-m)*6;let x=A+0,_=A+1,M=A+2;a&&(x=a[x],_=a[_],M=a[M]),c||(x=x*h+d,_=_*h+d,M=M*h+d);for(let P=0;P<3;P++){let I,C,D;c?(I=o[f[P]](x),C=o[f[P]](_),D=o[f[P]](M)):(I=u[x+P],C=u[_+P],D=u[M+P]);let L=I;C<L&&(L=C),D<L&&(L=D);let k=I;C>k&&(k=C),D>k&&(k=D);const N=(k-L)/2,V=P*2;n[w+V+0]=L+N,n[w+V+1]=N+(Math.abs(L)+N)*us}}return n}raycastObject3D(e,t,n=[]){const{material:s}=e;if(s===void 0)return;ir.copy(e.matrixWorld).invert(),ns.copy(t.ray).applyMatrix4(ir),rr.setFromMatrixScale(e.matrixWorld),sr.copy(ns.direction).multiply(rr);const r=sr.length(),o=t.near/r,a=t.far/r;if(t.firstHitOnly===!0){let c=this.raycastFirst(ns,s,o,a);c=nr(c,e,t),c&&n.push(c)}else{const c=this.raycast(ns,s,o,a);for(let u=0,d=c.length;u<d;u++){const h=nr(c[u],e,t);h&&n.push(h)}}return n}refit(e=null){return(this.indirect?Qa:za)(this,e)}raycast(e,t=p.FrontSide,n=0,s=1/0){const r=this._roots,o=[],a=this.indirect?Ja:ja;for(let c=0,u=r.length;c<u;c++)a(this,c,t,e,o,n,s);return o}raycastFirst(e,t=p.FrontSide,n=0,s=1/0){const r=this._roots;let o=null;const a=this.indirect?tc:Wa;for(let c=0,u=r.length;c<u;c++){const d=a(this,c,t,e,n,s);d!=null&&(o==null||d.distance<o.distance)&&(o=d)}return o}intersectsGeometry(e,t){let n=!1;const s=this._roots,r=this.indirect?nc:Za;for(let o=0,a=s.length;o<a&&(n=r(this,o,e,t),!n);o++);return n}shapecast(e){const t=rt.getPrimitive(),n=super.shapecast({...e,intersectsPrimitive:e.intersectsTriangle,scratchPrimitive:t,iterate:this.indirect?Va:Ba});return rt.releasePrimitive(t),n}bvhcast(e,t,n){let{intersectsRanges:s,intersectsTriangles:r}=n;const o=rt.getPrimitive(),a=this.geometry.index,c=this.geometry.attributes.position,u=this.indirect?E=>{const b=this.resolveTriangleIndex(E);Ie(o,b*3,a,c)}:E=>{Ie(o,E*3,a,c)},d=rt.getPrimitive(),h=e.geometry.index,f=e.geometry.attributes.position,m=e.indirect?E=>{const b=e.resolveTriangleIndex(E);Ie(d,b*3,h,f)}:E=>{Ie(d,E*3,h,f)};if(r){if(!(e instanceof bn))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const E=(b,T,A,w,x,_,M,P)=>{for(let I=A,C=A+w;I<C;I++){m(I),d.a.applyMatrix4(t),d.b.applyMatrix4(t),d.c.applyMatrix4(t),d.needsUpdate=!0;for(let D=b,L=b+T;D<L;D++)if(u(D),o.needsUpdate=!0,r(o,d,D,I,x,_,M,P))return!0}return!1};if(s){const b=s;s=function(T,A,w,x,_,M,P,I){return b(T,A,w,x,_,M,P,I)?!0:E(T,A,w,x,_,M,P,I)}}else s=E}return super.bvhcast(e,t,{intersectsRanges:s})}intersectsBox(e,t){return ts.set(e.min,e.max,t),ts.needsUpdate=!0,this.shapecast({intersectsBounds:n=>ts.intersectsBox(n),intersectsTriangle:n=>ts.intersectsTriangle(n)})}intersectsSphere(e){return this.shapecast({intersectsBounds:t=>e.intersectsBox(t),intersectsTriangle:t=>t.intersectsSphere(e)})}closestPointToGeometry(e,t,n={},s={},r=0,o=1/0){return(this.indirect?ac:$a)(this,e,t,n,s,r,o)}closestPointToPoint(e,t={},n=0,s=1/0){return Oa(this,e,t,n,s)}}const tn={Mesh:p.Mesh.prototype.raycast,Line:p.Line.prototype.raycast,LineSegments:p.LineSegments.prototype.raycast,LineLoop:p.LineLoop.prototype.raycast,Points:p.Points.prototype.raycast,BatchedMesh:p.BatchedMesh.prototype.raycast},Ue=new p.Mesh,ss=[];function cc(i,e){if(this.isBatchedMesh)lc.call(this,i,e);else{const{geometry:t}=this;if(t.boundsTree)t.boundsTree.raycastObject3D(this,i,e);else{let n;if(this instanceof p.Mesh)n=tn.Mesh;else if(this instanceof p.LineSegments)n=tn.LineSegments;else if(this instanceof p.LineLoop)n=tn.LineLoop;else if(this instanceof p.Line)n=tn.Line;else if(this instanceof p.Points)n=tn.Points;else throw new Error("BVH: Fallback raycast function not found.");n.call(this,i,e)}}}function lc(i,e){if(this.boundsTrees){const t=this.boundsTrees,n=this._drawInfo||this._instanceInfo,s=this._drawRanges||this._geometryInfo,r=this.matrixWorld;Ue.material=this.material,Ue.geometry=this.geometry;const o=Ue.geometry.boundsTree,a=Ue.geometry.drawRange;Ue.geometry.boundingSphere===null&&(Ue.geometry.boundingSphere=new p.Sphere);for(let c=0,u=n.length;c<u;c++){if(!this.getVisibleAt(c))continue;const d=n[c].geometryIndex;if(Ue.geometry.boundsTree=t[d],this.getMatrixAt(c,Ue.matrixWorld).premultiply(r),!Ue.geometry.boundsTree){this.getBoundingBoxAt(d,Ue.geometry.boundingBox),this.getBoundingSphereAt(d,Ue.geometry.boundingSphere);const h=s[d];Ue.geometry.setDrawRange(h.start,h.count)}Ue.raycast(i,ss);for(let h=0,f=ss.length;h<f;h++){const m=ss[h];m.object=this,m.batchId=c,e.push(m)}ss.length=0}Ue.geometry.boundsTree=o,Ue.geometry.drawRange=a,Ue.material=null,Ue.geometry=null}else tn.BatchedMesh.call(this,i,e)}function Fr(i){i.traverse(e=>{var s,r,o;const t=e;if(!t.isMesh||t.isSkinnedMesh||t.isInstancedMesh||t.isBatchedMesh)return;const n=t.geometry;!((s=n==null?void 0:n.attributes)!=null&&s.position)||(o=(r=n.morphAttributes)==null?void 0:r.position)!=null&&o.length||(n.boundsTree||(n.boundsTree=new bn(n)),t.raycast=cc)})}function hc(i){i.boundsTree&&(i.boundsTree=void 0)}function or(i){const e=i;for(const n of Object.keys(e)){const s=e[n];s instanceof S.Texture&&s.dispose()}const t=i;if(t.isShaderMaterial&&t.uniforms)for(const n of Object.values(t.uniforms))(n==null?void 0:n.value)instanceof S.Texture&&n.value.dispose();i.dispose()}function xs(i){i.traverse(e=>{var r;const t=e;t.geometry&&typeof t.geometry.dispose=="function"&&(hc(t.geometry),t.geometry.dispose());const n=t.material;Array.isArray(n)?n.forEach(or):n&&or(n);const s=e;s.isLight&&((r=s.shadow)!=null&&r.dispose)&&s.shadow.dispose()})}function uc(i,e){if(!(e!=null&&e.keepBackgrounds)){i.background instanceof S.Texture&&(i.background.dispose(),i.background=null),i.environment instanceof S.Texture&&(i.environment.dispose(),i.environment=null);const t=i;t.__originalEnvironmentTexture&&(t.__originalEnvironmentTexture=void 0)}for(const t of[...i.children])xs(t),i.remove(t)}class Oe{constructor(e){this.object=e,this.positionAdapter=Pt.fromThreeVector(e.position),this.rotationAdapter=Pt.fromThreeVector(e.rotation),this.scaleAdapter=Pt.fromThreeVector(e.scale)}get id(){return this.object.uuid}get name(){return this.object.name}set name(e){this.object.name=e}get visible(){return this.object.visible}set visible(e){this.object.visible=e}get castShadow(){return this.object.castShadow}set castShadow(e){this.object.castShadow=e}get receiveShadow(){return this.object.receiveShadow}set receiveShadow(e){this.object.receiveShadow=e}get position(){return this.positionAdapter}get rotation(){return this.rotationAdapter}get scale(){return this.scaleAdapter}add(e){try{return e instanceof Oe?(this.object.add(e.getThreeObject()),F.ok(void 0)):F.err(new K("Child must be a ThreeObject3DAdapter",Y.INVALID_PARAMETER))}catch(t){return F.err(new K("Failed to add child object",Y.SCENE_OPERATION_FAILED,{originalError:t}))}}remove(e){try{return e instanceof Oe?(this.object.remove(e.getThreeObject()),F.ok(void 0)):F.err(new K("Child must be a ThreeObject3DAdapter",Y.INVALID_PARAMETER))}catch(t){return F.err(new K("Failed to remove child object",Y.SCENE_OPERATION_FAILED,{originalError:t}))}}traverse(e){this.object.traverse(t=>{e(new Oe(t))})}clone(){return new Oe(this.object.clone())}dispose(){xs(this.object)}getThreeObject(){return this.object}static fromThreeObject(e){return new Oe(e)}static create(){return new Oe(new S.Object3D)}}class St{constructor(e){this.scene=e||new S.Scene}get id(){return this.scene.uuid}get name(){return this.scene.name}set name(e){this.scene.name=e}add(e){try{return e instanceof Oe?(this.scene.add(e.getThreeObject()),F.ok(void 0)):F.err(new K("Object must be a ThreeObject3DAdapter",Y.INVALID_PARAMETER))}catch(t){return F.err(new K("Failed to add object to scene",Y.SCENE_OPERATION_FAILED,{originalError:t}))}}remove(e){try{return e instanceof Oe?(this.scene.remove(e.getThreeObject()),F.ok(void 0)):F.err(new K("Object must be a ThreeObject3DAdapter",Y.INVALID_PARAMETER))}catch(t){return F.err(new K("Failed to remove object from scene",Y.SCENE_OPERATION_FAILED,{originalError:t}))}}clear(){for(;this.scene.children.length>0;)this.scene.remove(this.scene.children[0])}disposeContents(e){uc(this.scene,e)}traverse(e){this.scene.traverse(t=>{e(new Oe(t))})}get background(){return this.scene.background instanceof S.Color?new li(this.scene.background):this.scene.background instanceof S.Texture?new is(this.scene.background):null}set background(e){e instanceof li?this.scene.background=e.getThreeColor():e instanceof is?this.scene.background=e.getThreeTexture():this.scene.background=null}get fog(){return this.scene.fog?new ar(this.scene.fog):null}set fog(e){e instanceof ar?this.scene.fog=e.getThreeFog():this.scene.fog=null}get environment(){return this.scene.environment?new is(this.scene.environment):null}set environment(e){e instanceof is?this.scene.environment=e.getThreeTexture():this.scene.environment=null}setEnvironmentIntensity(e){this.scene.environmentIntensity=e}getInternalRenderer(){return this.scene}getThreeScene(){return this.scene}}class li{constructor(e){this.color=e}get r(){return this.color.r}set r(e){this.color.r=e}get g(){return this.color.g}set g(e){this.color.g=e}get b(){return this.color.b}set b(e){this.color.b=e}setHex(e){this.color.setHex(e)}setRGB(e,t,n){this.color.setRGB(e,t,n)}getHex(){return this.color.getHex()}getThreeColor(){return this.color}}let is=class{constructor(e){this.texture=e}get id(){return this.texture.uuid}get image(){return this.texture.image||null}get needsUpdate(){return this.texture.needsUpdate}set needsUpdate(e){this.texture.needsUpdate=e}dispose(){this.texture.dispose()}getThreeTexture(){return this.texture}};class ar{constructor(e){this.fog=e}get color(){return new li(this.fog.color)}get near(){return this.fog.near||0}get far(){return this.fog.far||1e3}getThreeFog(){return this.fog}}class Br extends Oe{constructor(e){super(e),this.camera=e}get near(){return this.camera instanceof S.PerspectiveCamera||this.camera instanceof S.OrthographicCamera?this.camera.near:.1}set near(e){(this.camera instanceof S.PerspectiveCamera||this.camera instanceof S.OrthographicCamera)&&(this.camera.near=e)}get far(){return this.camera instanceof S.PerspectiveCamera||this.camera instanceof S.OrthographicCamera?this.camera.far:1e3}set far(e){(this.camera instanceof S.PerspectiveCamera||this.camera instanceof S.OrthographicCamera)&&(this.camera.far=e)}lookAt(e){e instanceof Pt?this.camera.lookAt(e.getThreeVector()):this.camera.lookAt(e.x,e.y,e.z)}updateProjectionMatrix(){(this.camera instanceof S.PerspectiveCamera||this.camera instanceof S.OrthographicCamera)&&this.camera.updateProjectionMatrix()}getWorldDirection(e){const t=new S.Vector3;this.camera.getWorldDirection(t),e.set(t.x,t.y,t.z)}getInternalRenderer(){return this.camera}getThreeCamera(){return this.camera}}class _i extends Br{constructor(e){const t=e||new S.PerspectiveCamera;super(t),this.perspectiveCamera=t}get type(){return"perspective"}get fov(){return this.perspectiveCamera.fov}set fov(e){this.perspectiveCamera.fov=e}get aspect(){return this.perspectiveCamera.aspect}set aspect(e){this.perspectiveCamera.aspect=e}static create(e=75,t=1,n=.1,s=1e3){return new _i(new S.PerspectiveCamera(e,t,n,s))}}class dc{constructor(e){this.renderer=null,this._id=Ir(),this.canvas=e}get id(){return this._id}initialize(e){try{if(this.renderer=new S.WebGLRenderer({canvas:this.canvas,antialias:e.antialias??!0,alpha:e.alpha??!1,premultipliedAlpha:e.premultipliedAlpha??!0,preserveDrawingBuffer:e.preserveDrawingBuffer??!1,powerPreference:e.powerPreference??"default"}),e.shadowMap&&(this.renderer.shadowMap.enabled=e.shadowMap.enabled,this.renderer.shadowMap.autoUpdate=!0,e.shadowMap.type)){const t={basic:S.BasicShadowMap,pcf:S.PCFShadowMap,pcfsoft:S.PCFSoftShadowMap,vsm:S.VSMShadowMap};this.renderer.shadowMap.type=t[e.shadowMap.type]}if(e.toneMapping){const t={none:S.NoToneMapping,linear:S.LinearToneMapping,reinhard:S.ReinhardToneMapping,cineon:S.CineonToneMapping,aces:S.ACESFilmicToneMapping};this.renderer.toneMapping=t[e.toneMapping.type],this.renderer.toneMappingExposure=e.toneMapping.exposure}if(e.pixelRatio!==void 0?this.renderer.setPixelRatio(e.pixelRatio):this.renderer.setPixelRatio(window.devicePixelRatio),this.canvas){const{clientWidth:t,clientHeight:n}=this.canvas.parentElement||this.canvas;t&&n&&this.renderer.setSize(t,n)}return this.renderer.outputColorSpace=S.SRGBColorSpace,F.ok(void 0)}catch(t){return F.err(new K("Failed to initialize renderer",Y.RENDERER_INIT_FAILED,{originalError:t,options:e}))}}render(e,t){if(!this.renderer)return F.err(new K("Renderer not initialized",Y.RENDERER_NOT_INITIALIZED));try{if(!(e instanceof St))return F.err(new K("Scene must be a ThreeSceneAdapter",Y.INVALID_PARAMETER));if(!(t instanceof Br))return F.err(new K("Camera must be a ThreeCameraAdapter",Y.INVALID_PARAMETER));const n=e.getThreeScene(),s=t.getThreeCamera();return this.renderer.render(n,s),F.ok(void 0)}catch(n){return F.err(new K("Failed to render frame",Y.RENDER_FAILED,{originalError:n}))}}setSize(e,t){if(this.renderer){this.renderer.setSize(e,t,!1);const n=this.renderer.domElement;n.style.width="100%",n.style.height="100%"}}setPixelRatio(e){this.renderer&&this.renderer.setPixelRatio(e)}getPixelRatio(){return this.renderer?this.renderer.getPixelRatio():1}setToneMappingExposure(e){this.renderer&&(this.renderer.toneMappingExposure=e)}getDomElement(){if(!this.renderer)throw new Error("Renderer not initialized");return this.renderer.domElement}getContext(){if(!this.renderer)throw new Error("Renderer not initialized");return this.renderer.getContext()}get capabilities(){if(!this.renderer)return{maxTextureSize:0,maxCubemapSize:0,maxAttributes:0,maxVertexUniforms:0,maxFragmentUniforms:0,maxSamples:0,isWebGL2:!1};const e=this.renderer.capabilities;return{maxTextureSize:e.maxTextureSize,maxCubemapSize:e.maxCubemapSize,maxAttributes:e.maxAttributes,maxVertexUniforms:e.maxVertexUniforms,maxFragmentUniforms:e.maxFragmentUniforms,maxSamples:e.maxSamples||0,isWebGL2:e.isWebGL2}}dispose(){this.renderer&&(this.renderer.dispose(),this.renderer=null)}isDisposed(){return this.renderer===null}getInternalRenderer(){return this.renderer}getThreeRenderer(){return this.getInternalRenderer()}}function cr(i,e){if(e===p.TrianglesDrawMode)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),i;if(e===p.TriangleFanDrawMode||e===p.TriangleStripDrawMode){let t=i.getIndex();if(t===null){const o=[],a=i.getAttribute("position");if(a!==void 0){for(let c=0;c<a.count;c++)o.push(c);i.setIndex(o),t=i.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),i}const n=t.count-2,s=[];if(e===p.TriangleFanDrawMode)for(let o=1;o<=n;o++)s.push(t.getX(0)),s.push(t.getX(o)),s.push(t.getX(o+1));else for(let o=0;o<n;o++)o%2===0?(s.push(t.getX(o)),s.push(t.getX(o+1)),s.push(t.getX(o+2))):(s.push(t.getX(o+2)),s.push(t.getX(o+1)),s.push(t.getX(o)));s.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const r=i.clone();return r.setIndex(s),r.clearGroups(),r}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),i}function fc(i){const e=new Map,t=new Map,n=i.clone();return zr(i,n,function(s,r){e.set(r,s),t.set(s,r)}),n.traverse(function(s){if(!s.isSkinnedMesh)return;const r=s,o=e.get(s),a=o.skeleton.bones;r.skeleton=o.skeleton.clone(),r.bindMatrix.copy(o.bindMatrix),r.skeleton.bones=a.map(function(c){return t.get(c)}),r.bind(r.skeleton,r.bindMatrix)}),n}function zr(i,e,t){t(i,e);for(let n=0;n<i.children.length;n++)zr(i.children[n],e.children[n],t)}class pc extends p.Loader{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new wc(t)}),this.register(function(t){return new Tc(t)}),this.register(function(t){return new Cc(t)}),this.register(function(t){return new Ic(t)}),this.register(function(t){return new Lc(t)}),this.register(function(t){return new _c(t)}),this.register(function(t){return new bc(t)}),this.register(function(t){return new xc(t)}),this.register(function(t){return new Ac(t)}),this.register(function(t){return new Ec(t)}),this.register(function(t){return new Mc(t)}),this.register(function(t){return new Sc(t)}),this.register(function(t){return new vc(t)}),this.register(function(t){return new Rc(t)}),this.register(function(t){return new gc(t)}),this.register(function(t){return new lr(t,le.EXT_MESHOPT_COMPRESSION)}),this.register(function(t){return new lr(t,le.KHR_MESHOPT_COMPRESSION)}),this.register(function(t){return new Pc(t)})}load(e,t,n,s){const r=this;let o;if(this.resourcePath!=="")o=this.resourcePath;else if(this.path!==""){const u=p.LoaderUtils.extractUrlBase(e);o=p.LoaderUtils.resolveURL(u,this.path)}else o=p.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const a=function(u){s?s(u):console.error(u),r.manager.itemError(e),r.manager.itemEnd(e)},c=new p.FileLoader(this.manager);c.setPath(this.path),c.setResponseType("arraybuffer"),c.setRequestHeader(this.requestHeader),c.setWithCredentials(this.withCredentials),c.load(e,function(u){try{r.parse(u,o,function(d){t(d),r.manager.itemEnd(e)},a)}catch(d){a(d)}},n,a)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,s){let r;const o={},a={},c=new TextDecoder;if(typeof e=="string")r=JSON.parse(e);else if(e instanceof ArrayBuffer)if(c.decode(new Uint8Array(e,0,4))===Ur){try{o[le.KHR_BINARY_GLTF]=new Oc(e)}catch(h){s&&s(h);return}r=JSON.parse(o[le.KHR_BINARY_GLTF].content)}else r=JSON.parse(c.decode(e));else r=e;if(r.asset===void 0||r.asset.version[0]<2){s&&s(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const u=new Zc(r,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});u.fileLoader.setRequestHeader(this.requestHeader);for(let d=0;d<this.pluginCallbacks.length;d++){const h=this.pluginCallbacks[d](u);h.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),a[h.name]=h,o[h.name]=!0}if(r.extensionsUsed)for(let d=0;d<r.extensionsUsed.length;++d){const h=r.extensionsUsed[d],f=r.extensionsRequired||[];switch(h){case le.KHR_MATERIALS_UNLIT:o[h]=new yc;break;case le.KHR_DRACO_MESH_COMPRESSION:o[h]=new Dc(r,this.dracoLoader);break;case le.KHR_TEXTURE_TRANSFORM:o[h]=new Nc;break;case le.KHR_MESH_QUANTIZATION:o[h]=new kc;break;default:f.indexOf(h)>=0&&a[h]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+h+'".')}}u.setExtensions(o),u.setPlugins(a),u.parse(n,s)}parseAsync(e,t){const n=this;return new Promise(function(s,r){n.parse(e,t,s,r)})}}function mc(){let i={};return{get:function(e){return i[e]},add:function(e,t){i[e]=t},remove:function(e){delete i[e]},removeAll:function(){i={}}}}function Me(i,e,t){const n=i.json.materials[e];return n.extensions&&n.extensions[t]?n.extensions[t]:null}const le={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",KHR_MESHOPT_COMPRESSION:"KHR_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class gc{constructor(e){this.parser=e,this.name=le.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,s=t.length;n<s;n++){const r=t[n];r.extensions&&r.extensions[this.name]&&r.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,r.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let s=t.cache.get(n);if(s)return s;const r=t.json,c=((r.extensions&&r.extensions[this.name]||{}).lights||[])[e];let u;const d=new p.Color(16777215);c.color!==void 0&&d.setRGB(c.color[0],c.color[1],c.color[2],p.LinearSRGBColorSpace);const h=c.range!==void 0?c.range:0;switch(c.type){case"directional":u=new p.DirectionalLight(d),u.target.position.set(0,0,-1),u.add(u.target);break;case"point":u=new p.PointLight(d),u.distance=h;break;case"spot":u=new p.SpotLight(d),u.distance=h,c.spot=c.spot||{},c.spot.innerConeAngle=c.spot.innerConeAngle!==void 0?c.spot.innerConeAngle:0,c.spot.outerConeAngle=c.spot.outerConeAngle!==void 0?c.spot.outerConeAngle:Math.PI/4,u.angle=c.spot.outerConeAngle,u.penumbra=1-c.spot.innerConeAngle/c.spot.outerConeAngle,u.target.position.set(0,0,-1),u.add(u.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+c.type)}return u.position.set(0,0,0),yt(u,c),c.intensity!==void 0&&(u.intensity=c.intensity),u.name=t.createUniqueName(c.name||"light_"+e),s=Promise.resolve(u),t.cache.add(n,s),s}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,n=this.parser,r=n.json.nodes[e],a=(r.extensions&&r.extensions[this.name]||{}).light;return a===void 0?null:this._loadLight(a).then(function(c){return n._getNodeRef(t.cache,a,c)})}}class yc{constructor(){this.name=le.KHR_MATERIALS_UNLIT}getMaterialType(){return p.MeshBasicMaterial}extendParams(e,t,n){const s=[];e.color=new p.Color(1,1,1),e.opacity=1;const r=t.pbrMetallicRoughness;if(r){if(Array.isArray(r.baseColorFactor)){const o=r.baseColorFactor;e.color.setRGB(o[0],o[1],o[2],p.LinearSRGBColorSpace),e.opacity=o[3]}r.baseColorTexture!==void 0&&s.push(n.assignTexture(e,"map",r.baseColorTexture,p.SRGBColorSpace))}return Promise.all(s)}}class Ec{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const n=Me(this.parser,e,this.name);return n===null||n.emissiveStrength!==void 0&&(t.emissiveIntensity=n.emissiveStrength),Promise.resolve()}}class wc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];if(n.clearcoatFactor!==void 0&&(t.clearcoat=n.clearcoatFactor),n.clearcoatTexture!==void 0&&s.push(this.parser.assignTexture(t,"clearcoatMap",n.clearcoatTexture)),n.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=n.clearcoatRoughnessFactor),n.clearcoatRoughnessTexture!==void 0&&s.push(this.parser.assignTexture(t,"clearcoatRoughnessMap",n.clearcoatRoughnessTexture)),n.clearcoatNormalTexture!==void 0&&(s.push(this.parser.assignTexture(t,"clearcoatNormalMap",n.clearcoatNormalTexture)),n.clearcoatNormalTexture.scale!==void 0)){const r=n.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new p.Vector2(r,r)}return Promise.all(s)}}class Tc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_DISPERSION}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(this.parser,e,this.name);return n===null||(t.dispersion=n.dispersion!==void 0?n.dispersion:0),Promise.resolve()}}class Sc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];return n.iridescenceFactor!==void 0&&(t.iridescence=n.iridescenceFactor),n.iridescenceTexture!==void 0&&s.push(this.parser.assignTexture(t,"iridescenceMap",n.iridescenceTexture)),n.iridescenceIor!==void 0&&(t.iridescenceIOR=n.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),n.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=n.iridescenceThicknessMinimum),n.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=n.iridescenceThicknessMaximum),n.iridescenceThicknessTexture!==void 0&&s.push(this.parser.assignTexture(t,"iridescenceThicknessMap",n.iridescenceThicknessTexture)),Promise.all(s)}}class _c{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_SHEEN}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];if(t.sheenColor=new p.Color(0,0,0),t.sheenRoughness=0,t.sheen=1,n.sheenColorFactor!==void 0){const r=n.sheenColorFactor;t.sheenColor.setRGB(r[0],r[1],r[2],p.LinearSRGBColorSpace)}return n.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=n.sheenRoughnessFactor),n.sheenColorTexture!==void 0&&s.push(this.parser.assignTexture(t,"sheenColorMap",n.sheenColorTexture,p.SRGBColorSpace)),n.sheenRoughnessTexture!==void 0&&s.push(this.parser.assignTexture(t,"sheenRoughnessMap",n.sheenRoughnessTexture)),Promise.all(s)}}class bc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];return n.transmissionFactor!==void 0&&(t.transmission=n.transmissionFactor),n.transmissionTexture!==void 0&&s.push(this.parser.assignTexture(t,"transmissionMap",n.transmissionTexture)),Promise.all(s)}}class xc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_VOLUME}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];t.thickness=n.thicknessFactor!==void 0?n.thicknessFactor:0,n.thicknessTexture!==void 0&&s.push(this.parser.assignTexture(t,"thicknessMap",n.thicknessTexture)),t.attenuationDistance=n.attenuationDistance||1/0;const r=n.attenuationColor||[1,1,1];return t.attenuationColor=new p.Color().setRGB(r[0],r[1],r[2],p.LinearSRGBColorSpace),Promise.all(s)}}class Ac{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_IOR}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(this.parser,e,this.name);return n===null||(t.ior=n.ior!==void 0?n.ior:1.5,t.ior===0&&(t.ior=1e3)),Promise.resolve()}}class Mc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_SPECULAR}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];t.specularIntensity=n.specularFactor!==void 0?n.specularFactor:1,n.specularTexture!==void 0&&s.push(this.parser.assignTexture(t,"specularIntensityMap",n.specularTexture));const r=n.specularColorFactor||[1,1,1];return t.specularColor=new p.Color().setRGB(r[0],r[1],r[2],p.LinearSRGBColorSpace),n.specularColorTexture!==void 0&&s.push(this.parser.assignTexture(t,"specularColorMap",n.specularColorTexture,p.SRGBColorSpace)),Promise.all(s)}}class Rc{constructor(e){this.parser=e,this.name=le.EXT_MATERIALS_BUMP}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];return t.bumpScale=n.bumpFactor!==void 0?n.bumpFactor:1,n.bumpTexture!==void 0&&s.push(this.parser.assignTexture(t,"bumpMap",n.bumpTexture)),Promise.all(s)}}class vc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];return n.anisotropyStrength!==void 0&&(t.anisotropy=n.anisotropyStrength),n.anisotropyRotation!==void 0&&(t.anisotropyRotation=n.anisotropyRotation),n.anisotropyTexture!==void 0&&s.push(this.parser.assignTexture(t,"anisotropyMap",n.anisotropyTexture)),Promise.all(s)}}class Cc{constructor(e){this.parser=e,this.name=le.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,s=n.textures[e];if(!s.extensions||!s.extensions[this.name])return null;const r=s.extensions[this.name],o=t.options.ktx2Loader;if(!o){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,r.source,o)}}class Ic{constructor(e){this.parser=e,this.name=le.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,n=this.parser,s=n.json,r=s.textures[e];if(!r.extensions||!r.extensions[t])return null;const o=r.extensions[t],a=s.images[o.source];let c=n.textureLoader;if(a.uri){const u=n.options.manager.getHandler(a.uri);u!==null&&(c=u)}return n.loadTextureImage(e,o.source,c)}}class Lc{constructor(e){this.parser=e,this.name=le.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,n=this.parser,s=n.json,r=s.textures[e];if(!r.extensions||!r.extensions[t])return null;const o=r.extensions[t],a=s.images[o.source];let c=n.textureLoader;if(a.uri){const u=n.options.manager.getHandler(a.uri);u!==null&&(c=u)}return n.loadTextureImage(e,o.source,c)}}class lr{constructor(e,t){this.name=t,this.parser=e}loadBufferView(e){const t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){const s=n.extensions[this.name],r=this.parser.getDependency("buffer",s.buffer),o=this.parser.options.meshoptDecoder;if(!o||!o.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return r.then(function(a){const c=s.byteOffset||0,u=s.byteLength||0,d=s.count,h=s.byteStride,f=new Uint8Array(a,c,u);return o.decodeGltfBufferAsync?o.decodeGltfBufferAsync(d,h,f,s.mode,s.filter).then(function(m){return m.buffer}):o.ready.then(function(){const m=new ArrayBuffer(d*h);return o.decodeGltfBuffer(new Uint8Array(m),d,h,f,s.mode,s.filter),m})})}else return null}}class Pc{constructor(e){this.name=le.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;const s=t.meshes[n.mesh];for(const u of s.primitives)if(u.mode!==st.TRIANGLES&&u.mode!==st.TRIANGLE_STRIP&&u.mode!==st.TRIANGLE_FAN&&u.mode!==void 0)return null;const o=n.extensions[this.name].attributes,a=[],c={};for(const u in o)a.push(this.parser.getDependency("accessor",o[u]).then(d=>(c[u]=d,c[u])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(u=>{const d=u.pop(),h=d.isGroup?d.children:[d],f=u[0].count,m=[];for(const E of h){const b=new p.Matrix4,T=new p.Vector3,A=new p.Quaternion,w=new p.Vector3(1,1,1),x=new p.InstancedMesh(E.geometry,E.material,f);for(let _=0;_<f;_++)c.TRANSLATION&&T.fromBufferAttribute(c.TRANSLATION,_),c.ROTATION&&A.fromBufferAttribute(c.ROTATION,_),c.SCALE&&w.fromBufferAttribute(c.SCALE,_),x.setMatrixAt(_,b.compose(T,A,w));for(const _ in c)if(_==="_COLOR_0"){const M=c[_];x.instanceColor=new p.InstancedBufferAttribute(M.array,M.itemSize,M.normalized)}else _!=="TRANSLATION"&&_!=="ROTATION"&&_!=="SCALE"&&E.geometry.setAttribute(_,c[_]);p.Object3D.prototype.copy.call(x,E),this.parser.assignFinalMaterial(x),m.push(x)}return d.isGroup?(d.clear(),d.add(...m),d):m[0]}))}}const Ur="glTF",yn=12,hr={JSON:1313821514,BIN:5130562};class Oc{constructor(e){this.name=le.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,yn),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==Ur)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const s=this.header.length-yn,r=new DataView(e,yn);let o=0;for(;o<s;){const a=r.getUint32(o,!0);o+=4;const c=r.getUint32(o,!0);if(o+=4,c===hr.JSON){const u=new Uint8Array(e,yn+o,a);this.content=n.decode(u)}else if(c===hr.BIN){const u=yn+o;this.body=e.slice(u,u+a)}o+=a}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class Dc{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=le.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,s=this.dracoLoader,r=e.extensions[this.name].bufferView,o=e.extensions[this.name].attributes,a={},c={},u={};for(const d in o){const h=hi[d]||d.toLowerCase();a[h]=o[d]}for(const d in e.attributes){const h=hi[d]||d.toLowerCase();if(o[d]!==void 0){const f=n.accessors[e.attributes[d]],m=rn[f.componentType];u[h]=m.name,c[h]=f.normalized===!0}}return t.getDependency("bufferView",r).then(function(d){return new Promise(function(h,f){s.decodeDracoFile(d,function(m){for(const E in m.attributes){const b=m.attributes[E],T=c[E];T!==void 0&&(b.normalized=T)}h(m)},a,u,p.LinearSRGBColorSpace,f)})})}}class Nc{constructor(){this.name=le.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}}class kc{constructor(){this.name=le.KHR_MESH_QUANTIZATION}}class Hr extends p.Interpolant{constructor(e,t,n,s){super(e,t,n,s)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,s=this.valueSize,r=e*s*3+s;for(let o=0;o!==s;o++)t[o]=n[r+o];return t}interpolate_(e,t,n,s){const r=this.resultBuffer,o=this.sampleValues,a=this.valueSize,c=a*2,u=a*3,d=s-t,h=(n-t)/d,f=h*h,m=f*h,E=e*u,b=E-u,T=-2*m+3*f,A=m-f,w=1-T,x=A-f+h;for(let _=0;_!==a;_++){const M=o[b+_+a],P=o[b+_+c]*d,I=o[E+_+a],C=o[E+_]*d;r[_]=w*M+x*P+T*I+A*C}return r}}const Fc=new p.Quaternion;class Bc extends Hr{interpolate_(e,t,n,s){const r=super.interpolate_(e,t,n,s);return Fc.fromArray(r).normalize().toArray(r),r}}const st={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},rn={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},ur={9728:p.NearestFilter,9729:p.LinearFilter,9984:p.NearestMipmapNearestFilter,9985:p.LinearMipmapNearestFilter,9986:p.NearestMipmapLinearFilter,9987:p.LinearMipmapLinearFilter},dr={33071:p.ClampToEdgeWrapping,33648:p.MirroredRepeatWrapping,10497:p.RepeatWrapping},zs={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},hi={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},Rt={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},zc={CUBICSPLINE:void 0,LINEAR:p.InterpolateLinear,STEP:p.InterpolateDiscrete},Us={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function Uc(i){return i.DefaultMaterial===void 0&&(i.DefaultMaterial=new p.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:p.FrontSide})),i.DefaultMaterial}function Bt(i,e,t){for(const n in t.extensions)i[n]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[n]=t.extensions[n])}function yt(i,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(i.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function Hc(i,e,t){let n=!1,s=!1,r=!1;for(let u=0,d=e.length;u<d;u++){const h=e[u];if(h.POSITION!==void 0&&(n=!0),h.NORMAL!==void 0&&(s=!0),h.COLOR_0!==void 0&&(r=!0),n&&s&&r)break}if(!n&&!s&&!r)return Promise.resolve(i);const o=[],a=[],c=[];for(let u=0,d=e.length;u<d;u++){const h=e[u];if(n){const f=h.POSITION!==void 0?t.getDependency("accessor",h.POSITION):i.attributes.position;o.push(f)}if(s){const f=h.NORMAL!==void 0?t.getDependency("accessor",h.NORMAL):i.attributes.normal;a.push(f)}if(r){const f=h.COLOR_0!==void 0?t.getDependency("accessor",h.COLOR_0):i.attributes.color;c.push(f)}}return Promise.all([Promise.all(o),Promise.all(a),Promise.all(c)]).then(function(u){const d=u[0],h=u[1],f=u[2];return n&&(i.morphAttributes.position=d),s&&(i.morphAttributes.normal=h),r&&(i.morphAttributes.color=f),i.morphTargetsRelative=!0,i})}function Vc(i,e){if(i.updateMorphTargets(),e.weights!==void 0)for(let t=0,n=e.weights.length;t<n;t++)i.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(i.morphTargetInfluences.length===t.length){i.morphTargetDictionary={};for(let n=0,s=t.length;n<s;n++)i.morphTargetDictionary[t[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function jc(i){let e;const t=i.extensions&&i.extensions[le.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+Hs(t.attributes):e=i.indices+":"+Hs(i.attributes)+":"+i.mode,i.targets!==void 0)for(let n=0,s=i.targets.length;n<s;n++)e+=":"+Hs(i.targets[n]);return e}function Hs(i){let e="";const t=Object.keys(i).sort();for(let n=0,s=t.length;n<s;n++)e+=t[n]+":"+i[t[n]]+";";return e}function ui(i){switch(i){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function Gc(i){return i.search(/\.jpe?g($|\?)/i)>0||i.search(/^data\:image\/jpeg/)===0?"image/jpeg":i.search(/\.webp($|\?)/i)>0||i.search(/^data\:image\/webp/)===0?"image/webp":i.search(/\.ktx2($|\?)/i)>0||i.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const Wc=new p.Matrix4;class Zc{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new mc,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,s=-1,r=!1,o=-1;if(typeof navigator<"u"&&typeof navigator.userAgent<"u"){const a=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(a)===!0;const c=a.match(/Version\/(\d+)/);s=n&&c?parseInt(c[1],10):-1,r=a.indexOf("Firefox")>-1,o=r?a.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&s<17||r&&o<98?this.textureLoader=new p.TextureLoader(this.options.manager):this.textureLoader=new p.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new p.FileLoader(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const n=this,s=this.json,r=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(o){return o._markDefs&&o._markDefs()}),Promise.all(this._invokeAll(function(o){return o.beforeRoot&&o.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(o){const a={scene:o[0][s.scene||0],scenes:o[0],animations:o[1],cameras:o[2],asset:s.asset,parser:n,userData:{}};return Bt(r,a,s),yt(a,s),Promise.all(n._invokeAll(function(c){return c.afterRoot&&c.afterRoot(a)})).then(function(){for(const c of a.scenes)c.updateMatrixWorld();e(a)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let s=0,r=t.length;s<r;s++){const o=t[s].joints;for(let a=0,c=o.length;a<c;a++)e[o[a]].isBone=!0}for(let s=0,r=e.length;s<r;s++){const o=e[s];o.mesh!==void 0&&(this._addNodeRef(this.meshCache,o.mesh),o.skin!==void 0&&(n[o.mesh].isSkinnedMesh=!0)),o.camera!==void 0&&this._addNodeRef(this.cameraCache,o.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;const s=n.clone(),r=(o,a)=>{const c=this.associations.get(o);c!=null&&this.associations.set(a,c);for(const[u,d]of o.children.entries())r(d,a.children[u])};return r(n,s),s.name+="_instance_"+e.uses[t]++,s}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const s=e(t[n]);if(s)return s}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let s=0;s<t.length;s++){const r=e(t[s]);r&&n.push(r)}return n}getDependency(e,t){const n=e+":"+t;let s=this.cache.get(n);if(!s){switch(e){case"scene":s=this.loadScene(t);break;case"node":s=this._invokeOne(function(r){return r.loadNode&&r.loadNode(t)});break;case"mesh":s=this._invokeOne(function(r){return r.loadMesh&&r.loadMesh(t)});break;case"accessor":s=this.loadAccessor(t);break;case"bufferView":s=this._invokeOne(function(r){return r.loadBufferView&&r.loadBufferView(t)});break;case"buffer":s=this.loadBuffer(t);break;case"material":s=this._invokeOne(function(r){return r.loadMaterial&&r.loadMaterial(t)});break;case"texture":s=this._invokeOne(function(r){return r.loadTexture&&r.loadTexture(t)});break;case"skin":s=this.loadSkin(t);break;case"animation":s=this._invokeOne(function(r){return r.loadAnimation&&r.loadAnimation(t)});break;case"camera":s=this.loadCamera(t);break;default:if(s=this._invokeOne(function(r){return r!=this&&r.getDependency&&r.getDependency(e,t)}),!s)throw new Error("Unknown type: "+e);break}this.cache.add(n,s)}return s}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,s=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(s.map(function(r,o){return n.getDependency(e,o)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[le.KHR_BINARY_GLTF].body);const s=this.options;return new Promise(function(r,o){n.load(p.LoaderUtils.resolveURL(t.uri,s.path),r,void 0,function(){o(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(n){const s=t.byteLength||0,r=t.byteOffset||0;return n.slice(r,r+s)})}loadAccessor(e){const t=this,n=this.json,s=this.json.accessors[e];if(s.bufferView===void 0&&s.sparse===void 0){const o=zs[s.type],a=rn[s.componentType],c=s.normalized===!0,u=new a(s.count*o);return Promise.resolve(new p.BufferAttribute(u,o,c))}const r=[];return s.bufferView!==void 0?r.push(this.getDependency("bufferView",s.bufferView)):r.push(null),s.sparse!==void 0&&(r.push(this.getDependency("bufferView",s.sparse.indices.bufferView)),r.push(this.getDependency("bufferView",s.sparse.values.bufferView))),Promise.all(r).then(function(o){const a=o[0],c=zs[s.type],u=rn[s.componentType],d=u.BYTES_PER_ELEMENT,h=d*c,f=s.byteOffset||0,m=s.bufferView!==void 0?n.bufferViews[s.bufferView].byteStride:void 0,E=s.normalized===!0;let b,T;if(m&&m!==h){const A=Math.floor(f/m),w="InterleavedBuffer:"+s.bufferView+":"+s.componentType+":"+A+":"+s.count;let x=t.cache.get(w);x||(b=new u(a,A*m,s.count*m/d),x=new p.InterleavedBuffer(b,m/d),t.cache.add(w,x)),T=new p.InterleavedBufferAttribute(x,c,f%m/d,E)}else a===null?b=new u(s.count*c):b=new u(a,f,s.count*c),T=new p.BufferAttribute(b,c,E);if(s.sparse!==void 0){const A=zs.SCALAR,w=rn[s.sparse.indices.componentType],x=s.sparse.indices.byteOffset||0,_=s.sparse.values.byteOffset||0,M=new w(o[1],x,s.sparse.count*A),P=new u(o[2],_,s.sparse.count*c);a!==null&&(T=new p.BufferAttribute(T.array.slice(),T.itemSize,T.normalized)),T.normalized=!1;for(let I=0,C=M.length;I<C;I++){const D=M[I];if(T.setX(D,P[I*c]),c>=2&&T.setY(D,P[I*c+1]),c>=3&&T.setZ(D,P[I*c+2]),c>=4&&T.setW(D,P[I*c+3]),c>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}T.normalized=E}return T})}loadTexture(e){const t=this.json,n=this.options,r=t.textures[e].source,o=t.images[r];let a=this.textureLoader;if(o.uri){const c=n.manager.getHandler(o.uri);c!==null&&(a=c)}return this.loadTextureImage(e,r,a)}loadTextureImage(e,t,n){const s=this,r=this.json,o=r.textures[e],a=r.images[t],c=(a.uri||a.bufferView)+":"+o.sampler;if(this.textureCache[c])return this.textureCache[c];const u=this.loadImageSource(t,n).then(function(d){d.flipY=!1,d.name=o.name||a.name||"",d.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(d.name=a.uri);const f=(r.samplers||{})[o.sampler]||{};return d.magFilter=ur[f.magFilter]||p.LinearFilter,d.minFilter=ur[f.minFilter]||p.LinearMipmapLinearFilter,d.wrapS=dr[f.wrapS]||p.RepeatWrapping,d.wrapT=dr[f.wrapT]||p.RepeatWrapping,d.generateMipmaps=!d.isCompressedTexture&&d.minFilter!==p.NearestFilter&&d.minFilter!==p.LinearFilter,s.associations.set(d,{textures:e}),d}).catch(function(){return null});return this.textureCache[c]=u,u}loadImageSource(e,t){const n=this,s=this.json,r=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(h=>h.clone());const o=s.images[e],a=self.URL||self.webkitURL;let c=o.uri||"",u=!1;if(o.bufferView!==void 0)c=n.getDependency("bufferView",o.bufferView).then(function(h){u=!0;const f=new Blob([h],{type:o.mimeType});return c=a.createObjectURL(f),c});else if(o.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const d=Promise.resolve(c).then(function(h){return new Promise(function(f,m){let E=f;t.isImageBitmapLoader===!0&&(E=function(b){const T=new p.Texture(b);T.needsUpdate=!0,f(T)}),t.load(p.LoaderUtils.resolveURL(h,r.path),E,void 0,m)})}).then(function(h){return u===!0&&a.revokeObjectURL(c),yt(h,o),h.userData.mimeType=o.mimeType||Gc(o.uri),h}).catch(function(h){throw console.error("THREE.GLTFLoader: Couldn't load texture",c),h});return this.sourceCache[e]=d,d}assignTexture(e,t,n,s){const r=this;return this.getDependency("texture",n.index).then(function(o){if(!o)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(o=o.clone(),o.channel=n.texCoord),r.extensions[le.KHR_TEXTURE_TRANSFORM]){const a=n.extensions!==void 0?n.extensions[le.KHR_TEXTURE_TRANSFORM]:void 0;if(a){const c=r.associations.get(o);o=r.extensions[le.KHR_TEXTURE_TRANSFORM].extendTexture(o,a),r.associations.set(o,c)}}return s!==void 0&&(o.colorSpace=s),e[t]=o,o})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const s=t.attributes.tangent===void 0,r=t.attributes.color!==void 0,o=t.attributes.normal===void 0;if(e.isPoints){const a="PointsMaterial:"+n.uuid;let c=this.cache.get(a);c||(c=new p.PointsMaterial,p.Material.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,c.sizeAttenuation=!1,this.cache.add(a,c)),n=c}else if(e.isLine){const a="LineBasicMaterial:"+n.uuid;let c=this.cache.get(a);c||(c=new p.LineBasicMaterial,p.Material.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,this.cache.add(a,c)),n=c}if(s||r||o){let a="ClonedMaterial:"+n.uuid+":";s&&(a+="derivative-tangents:"),r&&(a+="vertex-colors:"),o&&(a+="flat-shading:");let c=this.cache.get(a);c||(c=n.clone(),r&&(c.vertexColors=!0),o&&(c.flatShading=!0),s&&(c.normalScale&&(c.normalScale.y*=-1),c.clearcoatNormalScale&&(c.clearcoatNormalScale.y*=-1)),this.cache.add(a,c),this.associations.set(c,this.associations.get(n))),n=c}e.material=n}getMaterialType(){return p.MeshStandardMaterial}loadMaterial(e){const t=this,n=this.json,s=this.extensions,r=n.materials[e];let o;const a={},c=r.extensions||{},u=[];if(c[le.KHR_MATERIALS_UNLIT]){const h=s[le.KHR_MATERIALS_UNLIT];o=h.getMaterialType(),u.push(h.extendParams(a,r,t))}else{const h=r.pbrMetallicRoughness||{};if(a.color=new p.Color(1,1,1),a.opacity=1,Array.isArray(h.baseColorFactor)){const f=h.baseColorFactor;a.color.setRGB(f[0],f[1],f[2],p.LinearSRGBColorSpace),a.opacity=f[3]}h.baseColorTexture!==void 0&&u.push(t.assignTexture(a,"map",h.baseColorTexture,p.SRGBColorSpace)),a.metalness=h.metallicFactor!==void 0?h.metallicFactor:1,a.roughness=h.roughnessFactor!==void 0?h.roughnessFactor:1,h.metallicRoughnessTexture!==void 0&&(u.push(t.assignTexture(a,"metalnessMap",h.metallicRoughnessTexture)),u.push(t.assignTexture(a,"roughnessMap",h.metallicRoughnessTexture))),o=this._invokeOne(function(f){return f.getMaterialType&&f.getMaterialType(e)}),u.push(Promise.all(this._invokeAll(function(f){return f.extendMaterialParams&&f.extendMaterialParams(e,a)})))}r.doubleSided===!0&&(a.side=p.DoubleSide);const d=r.alphaMode||Us.OPAQUE;if(d===Us.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,d===Us.MASK&&(a.alphaTest=r.alphaCutoff!==void 0?r.alphaCutoff:.5)),r.normalTexture!==void 0&&o!==p.MeshBasicMaterial&&(u.push(t.assignTexture(a,"normalMap",r.normalTexture)),a.normalScale=new p.Vector2(1,1),r.normalTexture.scale!==void 0)){const h=r.normalTexture.scale;a.normalScale.set(h,h)}if(r.occlusionTexture!==void 0&&o!==p.MeshBasicMaterial&&(u.push(t.assignTexture(a,"aoMap",r.occlusionTexture)),r.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=r.occlusionTexture.strength)),r.emissiveFactor!==void 0&&o!==p.MeshBasicMaterial){const h=r.emissiveFactor;a.emissive=new p.Color().setRGB(h[0],h[1],h[2],p.LinearSRGBColorSpace)}return r.emissiveTexture!==void 0&&o!==p.MeshBasicMaterial&&u.push(t.assignTexture(a,"emissiveMap",r.emissiveTexture,p.SRGBColorSpace)),Promise.all(u).then(function(){const h=new o(a);return r.name&&(h.name=r.name),yt(h,r),t.associations.set(h,{materials:e}),r.extensions&&Bt(s,h,r),h})}createUniqueName(e){const t=p.PropertyBinding.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,n=this.extensions,s=this.primitiveCache;function r(a){return n[le.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,t).then(function(c){return fr(c,a,t)})}const o=[];for(let a=0,c=e.length;a<c;a++){const u=e[a],d=jc(u),h=s[d];if(h)o.push(h.promise);else{let f;u.extensions&&u.extensions[le.KHR_DRACO_MESH_COMPRESSION]?f=r(u):f=fr(new p.BufferGeometry,u,t),s[d]={primitive:u,promise:f},o.push(f)}}return Promise.all(o)}loadMesh(e){const t=this,n=this.json,s=this.extensions,r=n.meshes[e],o=r.primitives,a=[];for(let c=0,u=o.length;c<u;c++){const d=o[c].material===void 0?Uc(this.cache):this.getDependency("material",o[c].material);a.push(d)}return a.push(t.loadGeometries(o)),Promise.all(a).then(function(c){const u=c.slice(0,c.length-1),d=c[c.length-1],h=[];for(let m=0,E=d.length;m<E;m++){const b=d[m],T=o[m];let A;const w=u[m];if(T.mode===st.TRIANGLES||T.mode===st.TRIANGLE_STRIP||T.mode===st.TRIANGLE_FAN||T.mode===void 0)A=r.isSkinnedMesh===!0?new p.SkinnedMesh(b,w):new p.Mesh(b,w),A.isSkinnedMesh===!0&&A.normalizeSkinWeights(),T.mode===st.TRIANGLE_STRIP?A.geometry=cr(A.geometry,p.TriangleStripDrawMode):T.mode===st.TRIANGLE_FAN&&(A.geometry=cr(A.geometry,p.TriangleFanDrawMode));else if(T.mode===st.LINES)A=new p.LineSegments(b,w);else if(T.mode===st.LINE_STRIP)A=new p.Line(b,w);else if(T.mode===st.LINE_LOOP)A=new p.LineLoop(b,w);else if(T.mode===st.POINTS)A=new p.Points(b,w);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+T.mode);Object.keys(A.geometry.morphAttributes).length>0&&Vc(A,r),A.name=t.createUniqueName(r.name||"mesh_"+e),yt(A,r),T.extensions&&Bt(s,A,T),t.assignFinalMaterial(A),h.push(A)}for(let m=0,E=h.length;m<E;m++)t.associations.set(h[m],{meshes:e,primitives:m});if(h.length===1)return r.extensions&&Bt(s,h[0],r),h[0];const f=new p.Group;r.extensions&&Bt(s,f,r),t.associations.set(f,{meshes:e});for(let m=0,E=h.length;m<E;m++)f.add(h[m]);return f})}loadCamera(e){let t;const n=this.json.cameras[e],s=n[n.type];if(!s){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?t=new p.PerspectiveCamera(p.MathUtils.radToDeg(s.yfov),s.aspectRatio||1,s.znear||1,s.zfar||2e6):n.type==="orthographic"&&(t=new p.OrthographicCamera(-s.xmag,s.xmag,s.ymag,-s.ymag,s.znear,s.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),yt(t,n),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],n=[];for(let s=0,r=t.joints.length;s<r;s++)n.push(this._loadNodeShallow(t.joints[s]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(s){const r=s.pop(),o=s,a=[],c=[];for(let u=0,d=o.length;u<d;u++){const h=o[u];if(h){a.push(h);const f=new p.Matrix4;r!==null&&f.fromArray(r.array,u*16),c.push(f)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[u])}return new p.Skeleton(a,c)})}loadAnimation(e){const t=this.json,n=this,s=t.animations[e],r=s.name?s.name:"animation_"+e,o=[],a=[],c=[],u=[],d=[];for(let h=0,f=s.channels.length;h<f;h++){const m=s.channels[h],E=s.samplers[m.sampler],b=m.target,T=b.node,A=s.parameters!==void 0?s.parameters[E.input]:E.input,w=s.parameters!==void 0?s.parameters[E.output]:E.output;b.node!==void 0&&(o.push(this.getDependency("node",T)),a.push(this.getDependency("accessor",A)),c.push(this.getDependency("accessor",w)),u.push(E),d.push(b))}return Promise.all([Promise.all(o),Promise.all(a),Promise.all(c),Promise.all(u),Promise.all(d)]).then(function(h){const f=h[0],m=h[1],E=h[2],b=h[3],T=h[4],A=[];for(let x=0,_=f.length;x<_;x++){const M=f[x],P=m[x],I=E[x],C=b[x],D=T[x];if(M===void 0)continue;M.updateMatrix&&M.updateMatrix();const L=n._createAnimationTracks(M,P,I,C,D);if(L)for(let k=0;k<L.length;k++)A.push(L[k])}const w=new p.AnimationClip(r,void 0,A);return yt(w,s),w})}createNodeMesh(e){const t=this.json,n=this,s=t.nodes[e];return s.mesh===void 0?null:n.getDependency("mesh",s.mesh).then(function(r){const o=n._getNodeRef(n.meshCache,s.mesh,r);return s.weights!==void 0&&o.traverse(function(a){if(a.isMesh)for(let c=0,u=s.weights.length;c<u;c++)a.morphTargetInfluences[c]=s.weights[c]}),o})}loadNode(e){const t=this.json,n=this,s=t.nodes[e],r=n._loadNodeShallow(e),o=[],a=s.children||[];for(let u=0,d=a.length;u<d;u++)o.push(n.getDependency("node",a[u]));const c=s.skin===void 0?Promise.resolve(null):n.getDependency("skin",s.skin);return Promise.all([r,Promise.all(o),c]).then(function(u){const d=u[0],h=u[1],f=u[2];f!==null&&d.traverse(function(m){m.isSkinnedMesh&&m.bind(f,Wc)});for(let m=0,E=h.length;m<E;m++)d.add(h[m]);if(d.userData.pivot!==void 0&&h.length>0){const m=d.userData.pivot,E=h[0];d.pivot=new p.Vector3().fromArray(m),d.position.x-=m[0],d.position.y-=m[1],d.position.z-=m[2],E.position.set(0,0,0),delete d.userData.pivot}return d})}_loadNodeShallow(e){const t=this.json,n=this.extensions,s=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const r=t.nodes[e],o=r.name?s.createUniqueName(r.name):"",a=[],c=s._invokeOne(function(u){return u.createNodeMesh&&u.createNodeMesh(e)});return c&&a.push(c),r.camera!==void 0&&a.push(s.getDependency("camera",r.camera).then(function(u){return s._getNodeRef(s.cameraCache,r.camera,u)})),s._invokeAll(function(u){return u.createNodeAttachment&&u.createNodeAttachment(e)}).forEach(function(u){a.push(u)}),this.nodeCache[e]=Promise.all(a).then(function(u){let d;if(r.isBone===!0?d=new p.Bone:u.length>1?d=new p.Group:u.length===1?d=u[0]:d=new p.Object3D,d!==u[0])for(let h=0,f=u.length;h<f;h++)d.add(u[h]);if(r.name&&(d.userData.name=r.name,d.name=o),yt(d,r),r.extensions&&Bt(n,d,r),r.matrix!==void 0){const h=new p.Matrix4;h.fromArray(r.matrix),d.applyMatrix4(h)}else r.translation!==void 0&&d.position.fromArray(r.translation),r.rotation!==void 0&&d.quaternion.fromArray(r.rotation),r.scale!==void 0&&d.scale.fromArray(r.scale);if(!s.associations.has(d))s.associations.set(d,{});else if(r.mesh!==void 0&&s.meshCache.refs[r.mesh]>1){const h=s.associations.get(d);s.associations.set(d,{...h})}return s.associations.get(d).nodes=e,d}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],s=this,r=new p.Group;n.name&&(r.name=s.createUniqueName(n.name)),yt(r,n),n.extensions&&Bt(t,r,n);const o=n.nodes||[],a=[];for(let c=0,u=o.length;c<u;c++)a.push(s.getDependency("node",o[c]));return Promise.all(a).then(function(c){for(let d=0,h=c.length;d<h;d++){const f=c[d];f.parent!==null?r.add(fc(f)):r.add(f)}const u=d=>{const h=new Map;for(const[f,m]of s.associations)(f instanceof p.Material||f instanceof p.Texture)&&h.set(f,m);return d.traverse(f=>{const m=s.associations.get(f);m!=null&&h.set(f,m)}),h};return s.associations=u(r),r})}_createAnimationTracks(e,t,n,s,r){const o=[],a=e.name?e.name:e.uuid,c=[];function u(m){m.morphTargetInfluences&&c.push(m.name?m.name:m.uuid)}Rt[r.path]===Rt.weights?(u(e),e.isGroup&&e.children.forEach(u)):c.push(a);let d;switch(Rt[r.path]){case Rt.weights:d=p.NumberKeyframeTrack;break;case Rt.rotation:d=p.QuaternionKeyframeTrack;break;case Rt.translation:case Rt.scale:d=p.VectorKeyframeTrack;break;default:switch(n.itemSize){case 1:d=p.NumberKeyframeTrack;break;case 2:case 3:default:d=p.VectorKeyframeTrack;break}break}const h=s.interpolation!==void 0?zc[s.interpolation]:p.InterpolateLinear,f=this._getArrayFromAccessor(n);for(let m=0,E=c.length;m<E;m++){const b=new d(c[m]+"."+Rt[r.path],t.array,f,h);s.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(b),o.push(b)}return o}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const n=ui(t.constructor),s=new Float32Array(t.length);for(let r=0,o=t.length;r<o;r++)s[r]=t[r]*n;t=s}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){const s=this instanceof p.QuaternionKeyframeTrack?Bc:Hr;return new s(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function Kc(i,e,t){const n=e.attributes,s=new p.Box3;if(n.POSITION!==void 0){const a=t.json.accessors[n.POSITION],c=a.min,u=a.max;if(c!==void 0&&u!==void 0){if(s.set(new p.Vector3(c[0],c[1],c[2]),new p.Vector3(u[0],u[1],u[2])),a.normalized){const d=ui(rn[a.componentType]);s.min.multiplyScalar(d),s.max.multiplyScalar(d)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const r=e.targets;if(r!==void 0){const a=new p.Vector3,c=new p.Vector3;for(let u=0,d=r.length;u<d;u++){const h=r[u];if(h.POSITION!==void 0){const f=t.json.accessors[h.POSITION],m=f.min,E=f.max;if(m!==void 0&&E!==void 0){if(c.setX(Math.max(Math.abs(m[0]),Math.abs(E[0]))),c.setY(Math.max(Math.abs(m[1]),Math.abs(E[1]))),c.setZ(Math.max(Math.abs(m[2]),Math.abs(E[2]))),f.normalized){const b=ui(rn[f.componentType]);c.multiplyScalar(b)}a.max(c)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}s.expandByVector(a)}i.boundingBox=s;const o=new p.Sphere;s.getCenter(o.center),o.radius=s.min.distanceTo(s.max)/2,i.boundingSphere=o}function fr(i,e,t){const n=e.attributes,s=[];function r(o,a){return t.getDependency("accessor",o).then(function(c){i.setAttribute(a,c)})}for(const o in n){const a=hi[o]||o.toLowerCase();a in i.attributes||s.push(r(n[o],a))}if(e.indices!==void 0&&!i.index){const o=t.getDependency("accessor",e.indices).then(function(a){i.setIndex(a)});s.push(o)}return p.ColorManagement.workingColorSpace!==p.LinearSRGBColorSpace&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${p.ColorManagement.workingColorSpace}" not supported.`),yt(i,e),Kc(i,e,t),Promise.all(s).then(function(){return e.targets!==void 0?Hc(i,e.targets,t):i})}const Xc=S.REVISION.replace(/\D/g,""),Vr=`https://cdn.jsdelivr.net/npm/three@0.${Xc}/examples/jsm/libs`,Yc=`${Vr}/draco/`,qc=`${Vr}/basis/`;class $c{constructor(e={}){this.loadingManager=new S.LoadingManager,this.loader=new pc(this.loadingManager),this.config=e}ensureDecoders(){return this.decodersReady||(this.decodersReady=this.configureDecoders()),this.decodersReady}async configureDecoders(){const e=this.config,t=[];(e.draco??!0)&&t.push(this.configureDraco(e)),(e.ktx2??!0)&&t.push(this.configureKtx2(e)),(e.meshopt??!0)&&t.push(this.configureMeshopt());const n=await Promise.allSettled(t);for(const s of n)s.status==="rejected"&&console.warn("softbox: a compression decoder failed to initialize; compressed assets using it may not load.",s.reason)}async configureDraco(e){const{DRACOLoader:t}=await import("three/examples/jsm/loaders/DRACOLoader.js"),n=new t(this.loadingManager);n.setDecoderPath(e.dracoDecoderPath??Yc),this.dracoLoader=n,this.loader.setDRACOLoader(n)}async configureKtx2(e){const{KTX2Loader:t}=await import("three/examples/jsm/loaders/KTX2Loader.js"),n=new t(this.loadingManager);n.setTranscoderPath(e.ktx2TranscoderPath??qc),e.renderer&&n.detectSupport(e.renderer),this.ktx2Loader=n,this.loader.setKTX2Loader(n)}async configureMeshopt(){const e=await import("three/examples/jsm/libs/meshopt_decoder.module.js");this.loader.setMeshoptDecoder(e.MeshoptDecoder)}async load(e,t){try{return await this.ensureDecoders(),new Promise(n=>{this.loader.load(e,s=>{var o;(this.config.bvh??!0)&&Fr(s.scene),s.scene.animations=s.animations;const r={scene:new Oe(s.scene),animations:this.convertAnimations(s.animations),cameras:(o=s.cameras)==null?void 0:o.map(a=>{const c=a instanceof S.PerspectiveCamera,u=a instanceof S.OrthographicCamera;return{name:a.name,type:a.type,fov:c?a.fov:void 0,aspect:c?a.aspect:void 0,near:c||u?a.near:.1,far:c||u?a.far:1e3}}),userData:s.userData};n(F.ok(r))},s=>{s.total>0&&(t==null||t(s.loaded,s.total))},s=>{n(F.err(new K("Failed to load GLTF model",Y.MODEL_LOAD_FAILED,{url:e,originalError:s})))})})}catch(n){return F.err(new K("Failed to initiate model loading",Y.MODEL_LOAD_FAILED,{url:e,originalError:n}))}}supports(e){var n;const t=(n=e.split(".").pop())==null?void 0:n.toLowerCase();return t==="gltf"||t==="glb"}dispose(){var e,t;(e=this.dracoLoader)==null||e.dispose(),(t=this.ktx2Loader)==null||t.dispose()}convertAnimations(e){return e.map(t=>({name:t.name,duration:t.duration,tracks:t.tracks.map(n=>({name:n.name,type:this.getTrackType(n),times:n.times,values:n.values}))}))}getTrackType(e){return e instanceof S.VectorKeyframeTrack?"vector":e instanceof S.QuaternionKeyframeTrack?"quaternion":e instanceof S.NumberKeyframeTrack?"number":e instanceof S.BooleanKeyframeTrack?"boolean":"number"}}class pr{static createLoader(e,t={}){var s;const n=(s=e.split(".").pop())==null?void 0:s.toLowerCase();switch(n){case"gltf":case"glb":return new $c(t);default:throw new K(`Unsupported file format: ${n}`,Y.UNSUPPORTED_FORMAT,{url:e,extension:n})}}}const mr={type:"change"},bi={type:"start"},jr={type:"end"},rs=new p.Ray,gr=new p.Plane,Qc=Math.cos(70*p.MathUtils.DEG2RAD),Le=new p.Vector3,$e=2*Math.PI,we={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},Vs=1e-6;class Gr extends p.Controls{constructor(e,t=null){super(e,t),this.state=we.NONE,this.target=new p.Vector3,this.cursor=new p.Vector3,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:p.MOUSE.ROTATE,MIDDLE:p.MOUSE.DOLLY,RIGHT:p.MOUSE.PAN},this.touches={ONE:p.TOUCH.ROTATE,TWO:p.TOUCH.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new p.Vector3,this._lastQuaternion=new p.Quaternion,this._lastTargetPosition=new p.Vector3,this._quat=new p.Quaternion().setFromUnitVectors(e.up,new p.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new p.Spherical,this._sphericalDelta=new p.Spherical,this._scale=1,this._panOffset=new p.Vector3,this._rotateStart=new p.Vector2,this._rotateEnd=new p.Vector2,this._rotateDelta=new p.Vector2,this._panStart=new p.Vector2,this._panEnd=new p.Vector2,this._panDelta=new p.Vector2,this._dollyStart=new p.Vector2,this._dollyEnd=new p.Vector2,this._dollyDelta=new p.Vector2,this._dollyDirection=new p.Vector3,this._mouse=new p.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=el.bind(this),this._onPointerDown=Jc.bind(this),this._onPointerUp=tl.bind(this),this._onContextMenu=cl.bind(this),this._onMouseWheel=il.bind(this),this._onKeyDown=rl.bind(this),this._onTouchStart=ol.bind(this),this._onTouchMove=al.bind(this),this._onMouseDown=nl.bind(this),this._onMouseMove=sl.bind(this),this._interceptControlDown=ll.bind(this),this._interceptControlUp=hl.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}set cursorStyle(e){this._cursorStyle=e,e==="grab"?this.domElement.style.cursor="grab":this.domElement.style.cursor="auto"}get cursorStyle(){return this._cursorStyle}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction=""}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(mr),this.update(),this.state=we.NONE}pan(e,t){this._pan(e,t),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(e=null){const t=this.object.position;Le.copy(t).sub(this.target),Le.applyQuaternion(this._quat),this._spherical.setFromVector3(Le),this.autoRotate&&this.state===we.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let n=this.minAzimuthAngle,s=this.maxAzimuthAngle;isFinite(n)&&isFinite(s)&&(n<-Math.PI?n+=$e:n>Math.PI&&(n-=$e),s<-Math.PI?s+=$e:s>Math.PI&&(s-=$e),n<=s?this._spherical.theta=Math.max(n,Math.min(s,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+s)/2?Math.max(n,this._spherical.theta):Math.min(s,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let r=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const o=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),r=o!=this._spherical.radius}if(Le.setFromSpherical(this._spherical),Le.applyQuaternion(this._quatInverse),t.copy(this.target).add(Le),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let o=null;if(this.object.isPerspectiveCamera){const a=Le.length();o=this._clampDistance(a*this._scale);const c=a-o;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),r=!!c}else if(this.object.isOrthographicCamera){const a=new p.Vector3(this._mouse.x,this._mouse.y,0);a.unproject(this.object);const c=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=c!==this.object.zoom;const u=new p.Vector3(this._mouse.x,this._mouse.y,0);u.unproject(this.object),this.object.position.sub(u).add(a),this.object.updateMatrixWorld(),o=Le.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;o!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(o).add(this.object.position):(rs.origin.copy(this.object.position),rs.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(rs.direction))<Qc?this.object.lookAt(this.target):(gr.setFromNormalAndCoplanarPoint(this.object.up,this.target),rs.intersectPlane(gr,this.target))))}else if(this.object.isOrthographicCamera){const o=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),o!==this.object.zoom&&(this.object.updateProjectionMatrix(),r=!0)}return this._scale=1,this._performCursorZoom=!1,r||this._lastPosition.distanceToSquared(this.object.position)>Vs||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Vs||this._lastTargetPosition.distanceToSquared(this.target)>Vs?(this.dispatchEvent(mr),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?$e/60*this.autoRotateSpeed*e:$e/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){Le.setFromMatrixColumn(t,0),Le.multiplyScalar(-e),this._panOffset.add(Le)}_panUp(e,t){this.screenSpacePanning===!0?Le.setFromMatrixColumn(t,1):(Le.setFromMatrixColumn(t,0),Le.crossVectors(this.object.up,Le)),Le.multiplyScalar(e),this._panOffset.add(Le)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;Le.copy(s).sub(this.target);let r=Le.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/n.clientHeight,this.object.matrix),this._panUp(2*t*r/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const n=this.domElement.getBoundingClientRect(),s=e-n.left,r=t-n.top,o=n.width,a=n.height;this._mouse.x=s/o*2-1,this._mouse.y=-(r/a)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft($e*this._rotateDelta.x/t.clientHeight),this._rotateUp($e*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp($e*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-$e*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft($e*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-$e*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._rotateStart.set(n,s)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panStart.set(n,s)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,r=Math.sqrt(n*n+s*s);this._dollyStart.set(0,r)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),s=.5*(e.pageX+n.x),r=.5*(e.pageY+n.y);this._rotateEnd.set(s,r)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft($e*this._rotateDelta.x/t.clientHeight),this._rotateUp($e*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panEnd.set(n,s)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,r=Math.sqrt(n*n+s*s);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const o=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(o,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new p.Vector2,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(n.deltaY*=10),n}}function Jc(i){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(i.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(i)&&(this._addPointer(i),i.pointerType==="touch"?this._onTouchStart(i):this._onMouseDown(i),this._cursorStyle==="grab"&&(this.domElement.style.cursor="grabbing")))}function el(i){this.enabled!==!1&&(i.pointerType==="touch"?this._onTouchMove(i):this._onMouseMove(i))}function tl(i){switch(this._removePointer(i),this._pointers.length){case 0:this.domElement.releasePointerCapture(i.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(jr),this.state=we.NONE,this._cursorStyle==="grab"&&(this.domElement.style.cursor="grab");break;case 1:const e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function nl(i){let e;switch(i.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case p.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(i),this.state=we.DOLLY;break;case p.MOUSE.ROTATE:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=we.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=we.ROTATE}break;case p.MOUSE.PAN:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=we.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=we.PAN}break;default:this.state=we.NONE}this.state!==we.NONE&&this.dispatchEvent(bi)}function sl(i){switch(this.state){case we.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(i);break;case we.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(i);break;case we.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(i);break}}function il(i){this.enabled===!1||this.enableZoom===!1||this.state!==we.NONE||(i.preventDefault(),this.dispatchEvent(bi),this._handleMouseWheel(this._customWheelEvent(i)),this.dispatchEvent(jr))}function rl(i){this.enabled!==!1&&this._handleKeyDown(i)}function ol(i){switch(this._trackPointer(i),this._pointers.length){case 1:switch(this.touches.ONE){case p.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(i),this.state=we.TOUCH_ROTATE;break;case p.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(i),this.state=we.TOUCH_PAN;break;default:this.state=we.NONE}break;case 2:switch(this.touches.TWO){case p.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(i),this.state=we.TOUCH_DOLLY_PAN;break;case p.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(i),this.state=we.TOUCH_DOLLY_ROTATE;break;default:this.state=we.NONE}break;default:this.state=we.NONE}this.state!==we.NONE&&this.dispatchEvent(bi)}function al(i){switch(this._trackPointer(i),this.state){case we.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(i),this.update();break;case we.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(i),this.update();break;case we.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(i),this.update();break;case we.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(i),this.update();break;default:this.state=we.NONE}}function cl(i){this.enabled!==!1&&i.preventDefault()}function ll(i){i.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function hl(i){i.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}const js=new p.Plane,os=new p.Raycaster,Qt=new p.Vector2,Gs=new p.Vector3;class ul extends Gr{constructor(e,t){super(e,t),this.screenSpacePanning=!1,this.mouseButtons={LEFT:p.MOUSE.PAN,MIDDLE:p.MOUSE.DOLLY,RIGHT:p.MOUSE.ROTATE},this.touches={ONE:p.TOUCH.PAN,TWO:p.TOUCH.DOLLY_ROTATE},this._panWorldStart=new p.Vector3}_handleMouseDownPan(e){if(super._handleMouseDownPan(e),this._panOffset.set(0,0,0),this.screenSpacePanning===!0)return;js.setFromNormalAndCoplanarPoint(this.object.up,this.target);const n=this.domElement.getBoundingClientRect();Qt.x=(e.clientX-n.left)/n.width*2-1,Qt.y=-((e.clientY-n.top)/n.height)*2+1,os.setFromCamera(Qt,this.object),os.ray.intersectPlane(js,this._panWorldStart)}_handleMouseMovePan(e){if(this.screenSpacePanning===!0){super._handleMouseMovePan(e);return}const n=this.domElement.getBoundingClientRect();Qt.x=(e.clientX-n.left)/n.width*2-1,Qt.y=-((e.clientY-n.top)/n.height)*2+1,os.setFromCamera(Qt,this.object),os.ray.intersectPlane(js,Gs)&&(Gs.sub(this._panWorldStart),this._panOffset.copy(Gs).negate(),this.update())}}class Wr{constructor(e){this.controls=e,this.targetAdapter=Pt.fromThreeVector(e.target)}get enabled(){return this.controls.enabled}set enabled(e){this.controls.enabled=e}get enableDamping(){return this.controls.enableDamping}set enableDamping(e){this.controls.enableDamping=e}get dampingFactor(){return this.controls.dampingFactor}set dampingFactor(e){this.controls.dampingFactor=e}get enableZoom(){return this.controls.enableZoom}set enableZoom(e){this.controls.enableZoom=e}get enableRotate(){return this.controls.enableRotate}set enableRotate(e){this.controls.enableRotate=e}get enablePan(){return this.controls.enablePan}set enablePan(e){this.controls.enablePan=e}get zoomSpeed(){return this.controls.zoomSpeed}set zoomSpeed(e){this.controls.zoomSpeed=e}get minDistance(){return this.controls.minDistance}set minDistance(e){this.controls.minDistance=e}get maxDistance(){return this.controls.maxDistance}set maxDistance(e){this.controls.maxDistance=e}get rotateSpeed(){return this.controls.rotateSpeed}set rotateSpeed(e){this.controls.rotateSpeed=e}get minPolarAngle(){return this.controls.minPolarAngle}set minPolarAngle(e){this.controls.minPolarAngle=e}get maxPolarAngle(){return this.controls.maxPolarAngle}set maxPolarAngle(e){this.controls.maxPolarAngle=e}get minAzimuthAngle(){return this.controls.minAzimuthAngle}set minAzimuthAngle(e){this.controls.minAzimuthAngle=e}get maxAzimuthAngle(){return this.controls.maxAzimuthAngle}set maxAzimuthAngle(e){this.controls.maxAzimuthAngle=e}get panSpeed(){return this.controls.panSpeed}set panSpeed(e){this.controls.panSpeed=e}get screenSpacePanning(){return this.controls.screenSpacePanning}set screenSpacePanning(e){this.controls.screenSpacePanning=e}get target(){return this.targetAdapter}update(){return this.controls.update()}reset(){this.controls.reset()}dispose(){this.controls.dispose()}connect(e){}disconnect(){this.controls.dispose()}get autoRotate(){return this.controls.autoRotate}set autoRotate(e){this.controls.autoRotate=e}get autoRotateSpeed(){return this.controls.autoRotateSpeed}set autoRotateSpeed(e){this.controls.autoRotateSpeed=e}getThreeControls(){return this.controls}}class dl extends Wr{constructor(e,t){super(new Gr(e,t))}get type(){return"orbit"}}class fl extends Wr{constructor(e,t){const n=new ul(e,t);super(n),n.screenSpacePanning=!0}get type(){return"map"}get screenSpacePanning(){return!0}set screenSpacePanning(e){}}const Rn=(i,e)=>{if(i&&typeof i=="object"){const t=i[e];if(typeof t=="function")return t.call(i)}return null};function zt(i){return Rn(i,"getThreeObject")??(i instanceof S.Object3D?i:null)}function vn(i){return Rn(i,"getThreeCamera")??(i instanceof S.Camera?i:null)}function di(i){return Rn(i,"getThreeScene")??(i instanceof S.Scene?i:null)}function Zr(i){return Rn(i,"getThreeRenderer")??(i instanceof S.WebGLRenderer?i:null)}function xi(i){return Rn(i,"getThreeControls")}const fi="contact-shadow-baked",xn="contact-shadow-live",Ai="softboxContactShadowHelper",yr=Math.PI*(3-Math.sqrt(5)),Ke=class Ke{constructor(e){this.passes=(e==null?void 0:e.passes)??96}bake(e){const{renderer:t,scene:n,object:s,light:r}=e,o=this.measureBakeRegion(s);if(!o)return;const a=n.getObjectByName(xn);(a==null?void 0:a.geometry)instanceof S.CircleGeometry&&(o.halfExtent=Math.min(o.halfExtent,a.geometry.parameters.radius));const c=new S.WebGLRenderTarget(Ke.ACCUMULATION_TEXTURE_SIZE,Ke.ACCUMULATION_TEXTURE_SIZE,{type:t.capabilities.isWebGL2?S.HalfFloatType:S.UnsignedByteType,depthBuffer:!1,stencilBuffer:!1}),u=new S.CircleGeometry(o.halfExtent,64);this.accumulateShadowPasses(t,s,r,o,c,u),this.installBakedMesh(n,o,c,u)}measureBakeRegion(e){const t=new S.Box3().setFromObject(e);if(t.isEmpty()||!Number.isFinite(t.min.x)||!Number.isFinite(t.max.x))return null;const n=t.getSize(new S.Vector3),s=t.getCenter(new S.Vector3),o=Math.max(Math.max(n.x,n.z)*1.6+n.y,.05);return{center:s,halfExtent:o,objectHeight:n.y}}accumulateShadowPasses(e,t,n,s,r,o){const a=new S.Scene,c=t.parent;a.add(t);const u=this.disableColorWrite(t),d=this.createBakeLight(n);a.add(d),a.add(d.target);const h=new S.ShadowMaterial({transparent:!0,opacity:1/this.passes,depthWrite:!1});h.blending=S.CustomBlending,h.blendEquation=S.AddEquation,h.blendSrc=S.OneFactor,h.blendDst=S.OneFactor;const f=new S.Mesh(o,h);f.rotation.x=-Math.PI/2,f.position.set(s.center.x,0,s.center.z),f.receiveShadow=!0,a.add(f);const m=this.createBakeCamera(s);a.add(m);const E=e.getRenderTarget(),b=e.autoClear,T=e.getClearColor(new S.Color),A=e.getClearAlpha(),w=e.shadowMap.autoUpdate;try{e.shadowMap.autoUpdate=!0,e.setRenderTarget(r),e.setClearColor(0,0),e.clear(!0,!1,!1),e.autoClear=!1;for(const x of this.sampleLightPositions(n))d.position.copy(x),e.render(a,m)}finally{e.autoClear=b,e.setClearColor(T,A),e.setRenderTarget(E),e.shadowMap.autoUpdate=w,this.restoreColorWrite(u),c?c.add(t):a.remove(t),d.dispose(),h.dispose()}}createBakeLight(e){const t=new S.DirectionalLight(16777215,1);t.castShadow=!0,t.shadow.mapSize.set(Ke.BAKE_SHADOW_MAP_SIZE,Ke.BAKE_SHADOW_MAP_SIZE),t.shadow.bias=e.shadow.bias,t.shadow.normalBias=e.shadow.normalBias,t.shadow.radius=4;const n=e.shadow.camera,s=t.shadow.camera;return s.left=n.left,s.right=n.right,s.top=n.top,s.bottom=n.bottom,s.near=n.near,s.far=n.far,s.updateProjectionMatrix(),t}createBakeCamera(e){const t=new S.OrthographicCamera(-e.halfExtent,e.halfExtent,e.halfExtent,-e.halfExtent,.1,Math.max(e.objectHeight,1)*4);return t.position.set(e.center.x,Math.max(e.objectHeight,1)*2,e.center.z),t.up.set(0,0,-1),t.lookAt(e.center.x,0,e.center.z),t.updateProjectionMatrix(),t.updateMatrixWorld(!0),t}sampleLightPositions(e){const t=e.position.clone(),n=e.target.parent?e.target.getWorldPosition(new S.Vector3):e.target.position.clone(),s=n.clone().sub(t),r=s.length(),o=s.normalize(),a=new S.Vector3().crossVectors(o,new S.Vector3(0,1,0));a.lengthSq()<1e-6&&a.set(1,0,0),a.normalize();const c=new S.Vector3().crossVectors(o,a),u=Math.round(this.passes*Ke.AMBIENT_RATIO),d=this.passes-u,h=S.MathUtils.degToRad(Ke.LIGHT_APERTURE_DEGREES),f=Math.tan(h/2)*r,m=[];for(let T=0;T<d;T++){const A=f*Math.sqrt((T+.5)/d),w=T*yr;m.push(t.clone().addScaledVector(a,A*Math.cos(w)).addScaledVector(c,A*Math.sin(w)))}const E=Math.sin(S.MathUtils.degToRad(Ke.AMBIENT_MIN_ELEVATION_DEGREES)),b=.98;for(let T=0;T<u;T++){const A=Math.sqrt((T+.5)/u),w=E+(b-E)*A,x=Math.sqrt(1-w*w),_=T*yr;m.push(new S.Vector3(x*Math.cos(_),w,x*Math.sin(_)).multiplyScalar(r).add(n))}return m}installBakedMesh(e,t,n,s){const r=e.getObjectByName(fi);r&&(e.remove(r),xs(r));const o=new S.MeshBasicMaterial({map:n.texture,transparent:!0,opacity:Ke.SHADOW_STRENGTH,depthWrite:!1,toneMapped:!1});o.onBeforeCompile=d=>{d.fragmentShader=d.fragmentShader.replace("#include <map_fragment>",`#include <map_fragment>
2
+ diffuseColor.a = pow(diffuseColor.a, 0.75);`)},o.customProgramCacheKey=()=>"contact-shadow-alpha-gamma",o.addEventListener("dispose",()=>n.dispose());const a=new S.Mesh(s,o);a.name=fi,a.userData[Ai]=!0,a.rotation.x=-Math.PI/2;const c=S.MathUtils.clamp(t.objectHeight*.0025,2e-4,.01);a.position.set(t.center.x,c,t.center.z),a.userData.renderTarget=n,e.add(a);const u=e.getObjectByName(xn);u&&(u.visible=!1)}disableColorWrite(e){const t=new Map;return e.traverse(n=>{const s=n;if(!s.isMesh)return;const r=Array.isArray(s.material)?s.material:[s.material];for(const o of r)o&&!t.has(o)&&(t.set(o,o.colorWrite),o.colorWrite=!1)}),t}restoreColorWrite(e){e.forEach((t,n)=>{n.colorWrite=t})}};Ke.AMBIENT_RATIO=.45,Ke.LIGHT_APERTURE_DEGREES=9,Ke.AMBIENT_MIN_ELEVATION_DEGREES=55,Ke.ACCUMULATION_TEXTURE_SIZE=1024,Ke.BAKE_SHADOW_MAP_SIZE=1024,Ke.SHADOW_STRENGTH=.85;let pi=Ke;const _n=class _n{static getHeight(e){return e*this.HEIGHT_RATIO}static getBevelSize(e){return e*this.BEVEL_RATIO}static getBevelThickness(e){return this.getBevelSize(e)}static getBaseSize(e){return e+this.getBevelSize(e)+this.getBevelThickness(e)}static getGapFactor(){return this.GAP_FACTOR}static getGridSpacing(e){const t=this.getBaseSize(e),n=this.getGapFactor();return{width:Math.sqrt(3)*t*n,height:2*t*n}}static getYPosition(e){return-this.getBevelSize(e)}};_n.HEIGHT_RATIO=.075,_n.BEVEL_RATIO=.04,_n.GAP_FACTOR=1.05;let Ut=_n;var _t=(i=>(i.SQUARE_WIRE="square_wire",i.HEXAGONAL_WIRE="hexagonal_wire",i.HEXAGONAL_GLASS="hexagonal_glass",i.STONE_TILES="stone_tiles",i.CUSTOM="custom",i))(_t||{});class pl{constructor(){this.name="Square Wire Grid"}createGrid(e){const t=e.size||10,n=e.divisions||10,s=new S.Color(e.color||8947848),r=new S.Color(e.centerLineColor||e.color||4473924),o=new S.GridHelper(t,n,r,s);if(e.opacity!==void 0&&e.opacity<1){const a=o.material;a.transparent=!0,a.opacity=e.opacity}return o}dispose(){}}class ml{constructor(){this.name="Hexagonal Wire Grid"}createGrid(e){var d;const t=new S.Group,n=((d=e.styleOptions)==null?void 0:d.hexRadius)||Math.floor(e.divisions/2),s=e.size/Math.max(1,n*2),r=new S.Color(e.color||8947848),o=e.opacity||.4,a=new S.LineBasicMaterial({color:r,transparent:!0,opacity:o}),c=s*Math.sqrt(3),u=s*2;for(let h=-n;h<=n;h++){const f=Math.max(-n,-h-n),m=Math.min(n,-h+n);for(let E=f;E<=m;E++){const b=c*(h+E/2),T=u*.75*E,A=[],w=Math.PI*2/6;for(let M=0;M<=6;M++){const P=M*w+Math.PI/6,I=b+s*Math.cos(P),C=T+s*Math.sin(P);A.push(new S.Vector3(I,0,C))}const x=new S.BufferGeometry().setFromPoints(A),_=new S.Line(x,a);t.add(_)}}return t}dispose(){}}class gl{constructor(e,t,n,s={}){this.position=e,this.size=t,this.color=n,this.materialOptions=s,this.height=Ut.getHeight(this.size),this.bevel=Ut.getBevelSize(this.size)}createMesh(){const e=new S.Shape,t=this.size+this.bevel,n=Math.PI*2/6;for(let b=0;b<6;b++){const T=t*Math.cos(b*n),A=t*Math.sin(b*n);b===0?e.moveTo(T,A):e.lineTo(T,A)}e.closePath();const s={depth:this.height,bevelEnabled:!0,bevelSize:this.bevel,bevelThickness:this.bevel,bevelSegments:2},r=new S.ExtrudeGeometry(e,s),{metalness:o=0,roughness:a=.15,transmission:c=1,thickness:u=.4,ior:d=1.5}=this.materialOptions,h=c>0,f=new S.MeshPhysicalMaterial({color:new S.Color(this.color),metalness:o,roughness:a,transparent:h,transmission:c,thickness:u,ior:d,opacity:1,clearcoat:h?1:0,clearcoatRoughness:.05,sheen:h?1:0,sheenColor:new S.Color(16777215),envMapIntensity:1}),m=new S.Mesh(r,f);m.receiveShadow=!0;const E=new S.Group;return E.add(m),E.position.set(this.position.x,this.position.y,this.position.z),E.rotation.x=Math.PI/2,E.rotation.z=Math.PI/6,E}}class yl{constructor(){this.name="Hexagonal Glass Grid"}createGrid(e){var u,d,h,f,m,E,b;const t=new S.Group,n=((u=e.styleOptions)==null?void 0:u.hexRadius)||Math.floor(e.divisions/2),s=((d=e.styleOptions)==null?void 0:d.tileSize)||1,r=String(e.color||"#ffffff"),o=Ut.getGridSpacing(s),a=o.width,c=o.height;for(let T=-n;T<=n;T++){const A=Math.max(-n,-T-n),w=Math.min(n,-T+n);for(let x=A;x<=w;x++){const _=a*(T+x/2),M=c*.75*x,P=Ut.getYPosition(s),C=new gl(new S.Vector3(_,P,M),s,r,{metalness:(h=e.styleOptions)==null?void 0:h.metalness,roughness:(f=e.styleOptions)==null?void 0:f.roughness,transmission:(m=e.styleOptions)==null?void 0:m.transmission,thickness:(E=e.styleOptions)==null?void 0:E.thickness,ior:(b=e.styleOptions)==null?void 0:b.ior}).createMesh();t.add(C)}}return t.add(this.createShadowCatcher(a*(n+.5))),t}createShadowCatcher(e){const t=new S.Mesh(new S.CircleGeometry(Math.max(e,1),64),new S.ShadowMaterial({opacity:.35}));return t.name=xn,t.userData[Ai]=!0,t.rotation.x=-Math.PI/2,t.position.y=.002,t.receiveShadow=!0,t}dispose(){}}class El{constructor(){this.name="Stone Tile Grid",this.textureLoader=new S.TextureLoader}createGrid(e){var m,E,b,T;const t=new S.Group,n=e.size,s=Math.max(1,e.divisions),r=n/s,o=r*.02,a=r-o,c=((m=e.styleOptions)==null?void 0:m.height)||r*.05,u=((E=e.styleOptions)==null?void 0:E.bevelSize)||c*.2,d=((b=e.styleOptions)==null?void 0:b.randomHeight)||!1,h=((T=e.styleOptions)==null?void 0:T.randomRotation)||!1,f=this.createStoneMaterial(e);for(let A=0;A<s;A++)for(let w=0;w<s;w++){const x=(A-s/2)*r+r/2,_=(w-s/2)*r+r/2,M=d?c*(.8+Math.random()*.4):c,P=new S.Shape,I=a/2;P.moveTo(-I,-I),P.lineTo(I,-I),P.lineTo(I,I),P.lineTo(-I,I),P.closePath();const C={depth:M,bevelEnabled:!0,bevelSize:u,bevelThickness:u,bevelSegments:2},D=new S.ExtrudeGeometry(P,C);D.rotateX(-Math.PI/2);const L=new S.Mesh(D,f);L.position.set(x,-M/2,_),L.castShadow=!0,L.receiveShadow=!0,h&&(L.rotation.y=Math.floor(Math.random()*4)*(Math.PI/2)),t.add(L)}return t}createStoneMaterial(e){var o,a,c,u,d;const t=new S.Color(e.color||8421504),n=((o=e.styleOptions)==null?void 0:o.metalness)||0,s=((a=e.styleOptions)==null?void 0:a.roughness)||.8,r={color:t,metalness:n,roughness:s};if((c=e.styleOptions)!=null&&c.texture){const h=this.loadTexture(e.styleOptions.texture);h&&(r.map=h,h.wrapS=h.wrapT=S.RepeatWrapping,h.repeat.set(1,1))}if((u=e.styleOptions)!=null&&u.normalMap){const h=this.loadTexture(e.styleOptions.normalMap);h&&(r.normalMap=h,h.wrapS=h.wrapT=S.RepeatWrapping,h.repeat.set(1,1))}if((d=e.styleOptions)!=null&&d.roughnessMap){const h=this.loadTexture(e.styleOptions.roughnessMap);h&&(r.roughnessMap=h,h.wrapS=h.wrapT=S.RepeatWrapping,h.repeat.set(1,1))}return new S.MeshStandardMaterial(r)}loadTexture(e){try{return this.textureLoader.load(e)}catch(t){return console.warn("Failed to load texture:",e,t),null}}}const vi=class vi{static createGrid(e,t){const n=this.gridStyles.get(e);if(!n){console.warn(`Unknown grid type: ${e}, falling back to square wire grid`);const r=this.gridStyles.get(_t.SQUARE_WIRE);if(!r)throw new Error("Square wire grid style not found");return r.createGrid(t)}const s=n.createGrid(t);return s.name=`Grid_${e}`,s}static registerGridStyle(e,t){this.gridStyles.set(e,t)}static getAvailableTypes(){return Array.from(this.gridStyles.keys())}static disposeGridStyle(e){const t=this.gridStyles.get(e);t&&t.dispose&&t.dispose()}};vi.gridStyles=new Map([[_t.SQUARE_WIRE,new pl],[_t.HEXAGONAL_WIRE,new ml],[_t.HEXAGONAL_GLASS,new yl],[_t.STONE_TILES,new El]]);let gs=vi;const Er=i=>{let e=null;return i.traverse(t=>{!e&&t.isDirectionalLight&&(e=t)}),e};class wl{constructor(){this.contactShadowBaker=new pi}addHelpers(e,t){try{if(!(e instanceof St))return F.err(new K("Scene must be ThreeSceneAdapter",Y.INVALID_PARAMETER));const n=e.getThreeScene();if(t.grid){const s=n.userData,r=typeof t.grid=="object"?t.grid:null,o={enabled:!0,color:(r==null?void 0:r.colorGrid)||t.gridColor||"#AAAAAA",type:r!=null&&r.type?r.type:_t.HEXAGONAL_GLASS,opacity:r==null?void 0:r.opacity,styleOptions:r==null?void 0:r.styleOptions};if(n.userData={...s,gridOptions:o},r!=null&&r.size||r!=null&&r.divisions){const a=o.type||_t.HEXAGONAL_GLASS,c=r.size||10,u=r.divisions||10,d={size:c,divisions:u,color:o.color,opacity:o.opacity,styleOptions:{hexRadius:Math.floor(u/2),tileSize:1,...o.styleOptions}},h=gs.createGrid(a,d);h.userData.isGrid=!0,h.userData.isDefaultGrid=!0,n.add(h)}}if(t.axes){const s=t.axesSize||5,r=new S.AxesHelper(s);n.add(r)}return F.ok(void 0)}catch(n){return F.err(new K("Failed to add helpers to scene",Y.SCENE_OPERATION_FAILED,{originalError:n,options:t}))}}addDynamicGrid(e,t,n=1.2){var s;try{if(!(e instanceof St))return F.err(new K("Scene must be ThreeSceneAdapter",Y.INVALID_PARAMETER));const r=e.getThreeScene(),o=r.userData,a=o==null?void 0:o.gridOptions;if(!(a!=null&&a.enabled))return F.ok(void 0);const c=[];r.traverse(C=>{var D,L,k;((D=C.userData)!=null&&D.isGrid||(L=C.userData)!=null&&L.isHexGrid||(k=C.userData)!=null&&k.isDefaultGrid)&&c.push(C)}),c.forEach(C=>{xs(C),r.remove(C)});let u;t instanceof Oe||"getThreeObject"in t&&typeof t.getThreeObject=="function"?u=t.getThreeObject():u=t;const d=new S.Box3().setFromObject(u),h=d.getSize(new S.Vector3);if(d.isEmpty()||!Number.isFinite(h.x)||!Number.isFinite(h.z))return console.warn("Skipping dynamic grid: object has an empty or non-finite bounding box"),F.ok(void 0);const f=(s=a.styleOptions)==null?void 0:s.tileSize,m=typeof f=="number"?f:1,b=Ut.getGridSpacing(m).width,T=Math.max(h.x,h.z)*n+h.y;let A=T<=b?0:Math.ceil((T/b-1)/2);const w=60;A>w&&(console.warn(`Dynamic grid would need ${A} rings to cover the object; capping at ${w}. The floor will not fully reach the configured coverage for this tileSize/object-size combination.`),A=w),T<b*.8?A=0:A<3&&T>b*2&&(A=3);const x=a.type||_t.HEXAGONAL_GLASS,M={size:Math.max(h.x,h.z)*n,divisions:A*2+1,color:a.color,opacity:a.opacity,styleOptions:{hexRadius:A,tileSize:m,...a.styleOptions}},P=gs.createGrid(x,M);P.userData.isGrid=!0,P.userData.isHexGrid=!0;const I=P.getObjectByName(xn);return I&&(I.position.y=S.MathUtils.clamp(h.y*.0025,2e-4,.002)),r.add(P),F.ok(void 0)}catch(r){return F.err(new K("Failed to add dynamic grid",Y.SCENE_OPERATION_FAILED,{originalError:r}))}}snapObjectToFloor(e,t){try{if(!(e instanceof St))return F.err(new K("Scene must be ThreeSceneAdapter",Y.INVALID_PARAMETER));let n;t instanceof Oe||"getThreeObject"in t&&typeof t.getThreeObject=="function"?n=t.getThreeObject():n=t;const s=_=>{var P,I,C;let M=_;for(;M;){if((P=M.userData)!=null&&P.isGrid||(I=M.userData)!=null&&I.isHexGrid||(C=M.userData)!=null&&C.isDefaultGrid)return!0;M=M.parent}return!1},r=e.getThreeScene();r.updateMatrixWorld(!0);const o=[];r.traverse(_=>{_.isMesh&&s(_)&&o.push(_)});const a=[];if(n.traverse(_=>{_.isMesh&&a.push(_)}),o.length===0||a.length===0)return F.ok(void 0);let c=-1/0;const u=new S.Box3;for(const _ of o)u.setFromObject(_),Number.isFinite(u.max.y)&&(c=Math.max(c,u.max.y));if(!Number.isFinite(c))return F.ok(void 0);const d=new S.Box3().setFromObject(n);if(d.isEmpty()||!Number.isFinite(d.min.x)||!Number.isFinite(d.max.x))return F.ok(void 0);const h=40,f=Math.max(1,d.max.y-d.min.y),m=d.max.y+f,E=d.min.y-f,b=new S.Raycaster,T=new S.Vector3(0,-1,0),A=new S.Vector3(0,1,0);let w=1/0;const x=(_,M,P,I)=>{b.set(new S.Vector3(_,M,P),I);for(const C of b.intersectObjects(a,!1))C.point.y<w&&(w=C.point.y)};for(let _=0;_<=h;_++)for(let M=0;M<=h;M++){const P=d.min.x+(d.max.x-d.min.x)*(_/h),I=d.min.z+(d.max.z-d.min.z)*(M/h);x(P,m,I,T),x(P,E,I,A)}if(Number.isFinite(w)){const _=w-c;Math.abs(_)>1e-4&&(n.position.y-=_)}return F.ok(void 0)}catch(n){return F.err(new K("Failed to snap object to floor",Y.SCENE_OPERATION_FAILED,{originalError:n}))}}fitShadowCameraToObject(e,t){try{if(!(e instanceof St))return F.err(new K("Scene must be ThreeSceneAdapter",Y.INVALID_PARAMETER));let n;t instanceof Oe||"getThreeObject"in t&&typeof t.getThreeObject=="function"?n=t.getThreeObject():n=t;const s=new S.Box3().setFromObject(n);if(s.isEmpty()||!Number.isFinite(s.min.x)||!Number.isFinite(s.max.x))return F.ok(void 0);const r=s.getSize(new S.Vector3),o=e.getThreeScene(),a=Er(o);if(!a||!a.castShadow)return F.ok(void 0);const d=Math.max(r.x,r.y,r.z,.1)*2,h=a.shadow.camera;return h.left=-d,h.right=d,h.top=d,h.bottom=-d,h.updateProjectionMatrix(),F.ok(void 0)}catch(n){return F.err(new K("Failed to fit shadow camera to object",Y.SCENE_OPERATION_FAILED,{originalError:n}))}}bakeContactShadow(e,t,n){try{const s=di(e);if(!s)return F.err(new K("Scene must be ThreeSceneAdapter",Y.INVALID_PARAMETER));const r=zt(t);if(!r)return F.err(new K("Object must expose a Three.js Object3D",Y.INVALID_PARAMETER));const o=Zr(n.getInternalRenderer());if(!o||!o.shadowMap.enabled)return F.ok(void 0);const a=Er(s);return!a||!a.castShadow||this.contactShadowBaker.bake({renderer:o,scene:s,object:r,light:a}),F.ok(void 0)}catch(s){return F.err(new K("Failed to bake contact shadow",Y.SCENE_OPERATION_FAILED,{originalError:s}))}}setContactShadowMode(e,t){try{const n=di(e);if(!n)return F.err(new K("Scene must be ThreeSceneAdapter",Y.INVALID_PARAMETER));const s=n.getObjectByName(fi),r=n.getObjectByName(xn);return t==="baked"&&!s||(s&&(s.visible=t==="baked"),r&&(r.visible=t==="live")),F.ok(void 0)}catch(n){return F.err(new K("Failed to switch contact shadow mode",Y.SCENE_OPERATION_FAILED,{originalError:n}))}}wrapInUnitsScaleGroup(e,t){try{const n=zt(e);if(!n)return F.err(new K("Object must expose a Three.js Object3D",Y.INVALID_PARAMETER));const s=new S.Group;return s.name=$o,s.scale.setScalar(t),s.add(n),F.ok(new Oe(s))}catch(n){return F.err(new K("Failed to apply the units scale to the model",Y.SCENE_OPERATION_FAILED,{originalError:n}))}}addLighting(e,t){try{if(!(e instanceof St))return F.err(new K("Scene must be ThreeSceneAdapter",Y.INVALID_PARAMETER));const n=e.getThreeScene();if(t.ambient){const s=new S.Color(t.ambient.color||"#404040"),r=t.ambient.intensity??Math.PI,o=new S.AmbientLight(s,r);n.add(o)}if(t.hemisphere){const s=new S.Color(t.hemisphere.skyColor||"#ffffbb"),r=new S.Color(t.hemisphere.groundColor||"#080820"),o=t.hemisphere.intensity??1,a=new S.HemisphereLight(s,r,o);n.add(a)}if(t.directional){const s=new S.Color(t.directional.color||"#ffffff"),r=t.directional.intensity??Math.PI,o=new S.DirectionalLight(s,r);if(t.directional.position){const a=t.directional.position;if(a instanceof S.Vector3)o.position.copy(a);else if(Array.isArray(a))o.position.set(a[0],a[1],a[2]);else if(typeof a=="object"&&"x"in a&&"y"in a&&"z"in a){const c=a;o.position.set(c.x,c.y,c.z)}}else o.position.set(6,6,6);if(t.directional.castShadow&&(o.castShadow=!0,t.directional.shadow)){const a=t.directional.shadow;if(a.mapSize&&(o.shadow.mapSize.width=a.mapSize.width,o.shadow.mapSize.height=a.mapSize.height),a.camera){const c=o.shadow.camera;a.camera.near!==void 0&&(c.near=a.camera.near),a.camera.far!==void 0&&(c.far=a.camera.far),a.camera.left!==void 0&&(c.left=a.camera.left),a.camera.right!==void 0&&(c.right=a.camera.right),a.camera.top!==void 0&&(c.top=a.camera.top),a.camera.bottom!==void 0&&(c.bottom=a.camera.bottom)}a.bias!==void 0&&(o.shadow.bias=a.bias),a.radius!==void 0&&(o.shadow.radius=a.radius)}o.target.position.set(0,0,0),n.add(o),n.add(o.target),o.shadow&&o.shadow.camera.updateProjectionMatrix()}return F.ok(void 0)}catch(n){return F.err(new K("Failed to add lighting to scene",Y.SCENE_OPERATION_FAILED,{originalError:n,options:t}))}}createGradientBackground(e,t){try{if(!(e instanceof St))return F.err(new K("Scene must be ThreeSceneAdapter",Y.INVALID_PARAMETER));const n=e.getThreeScene(),s=document.createElement("canvas");s.width=2,s.height=512;const r=s.getContext("2d");if(!r)return F.err(new K("Failed to create canvas context",Y.SCENE_OPERATION_FAILED));const o=r.createLinearGradient(0,0,0,s.height);o.addColorStop(0,t.topColor),o.addColorStop(1,t.bottomColor),r.fillStyle=o,r.fillRect(0,0,s.width,s.height);const a=new S.CanvasTexture(s);a.needsUpdate=!0;const c=n.background;return c instanceof S.Texture&&c!==n.environment&&c.dispose(),n.background=a,F.ok(void 0)}catch(n){return F.err(new K("Failed to create gradient background",Y.SCENE_OPERATION_FAILED,{originalError:n,options:t}))}}fitCameraToObject(e,t,n){try{const s=zt(e)??e,r=vn(t)??t,o=xi(n)??n,a=new S.Box3().setFromObject(s),c=a.getCenter(new S.Vector3),u=a.getSize(new S.Vector3),d=Math.max(u.x,u.y,u.z);let h;"fov"in r?h=r.fov*(Math.PI/180):h=50*(Math.PI/180);let f=Math.abs(d/2/Math.tan(h/2));f*=2;const m=-Math.PI/4,E=Math.PI/8,b=c.x+f*Math.sin(m)*Math.cos(E),T=c.y+f*Math.sin(E),A=c.z+f*Math.cos(m)*Math.cos(E);return r.position.set(b,T,A),r.lookAt(c),r.updateProjectionMatrix(),o&&o.target&&(o.target.copy(c),o.update()),F.ok(void 0)}catch(s){return F.err(new K("Failed to fit camera to object",Y.CAMERA_INIT_FAILED,{originalError:s}))}}}class Tl{constructor(){this.events=new ws,this.disposed=!1}async initialize(e){const{ThreePathTracingService:t}=await Promise.resolve().then(()=>require("./ThreePathTracingService-k4X0y0xh.cjs"));if(this.disposed)return F.ok(void 0);const n=new t;return this.inner=n,n.events.on("pathtracing:paused",s=>{this.events.emit("pathtracing:paused",s)}),this.pendingSettings&&(n.updateSettings(this.pendingSettings),this.pendingSettings=void 0),this.pendingEnabled!==void 0&&(n.setEnabled(this.pendingEnabled),this.pendingEnabled=void 0),n.initialize(e)}setEnabled(e){this.inner?this.inner.setEnabled(e):this.pendingEnabled=e}updateSettings(e){this.inner?this.inner.updateSettings(e):this.pendingSettings={...this.pendingSettings,...e}}render(e,t){return this.inner?this.inner.render(e,t):Promise.resolve(F.ok(void 0))}getSampleCount(){var e;return((e=this.inner)==null?void 0:e.getSampleCount())??0}isEnabled(){var e;return((e=this.inner)==null?void 0:e.isEnabled())??!1}isPathTracerDisposed(){var e;return((e=this.inner)==null?void 0:e.isPathTracerDisposed())??!1}reset(e){var t;(t=this.inner)==null||t.reset(e)}dispose(){var e;this.disposed=!0,(e=this.inner)==null||e.dispose()}isSupported(){var e;return((e=this.inner)==null?void 0:e.isSupported())??!0}}/*!
3
+ fflate - fast JavaScript compression/decompression
4
+ <https://101arrowz.github.io/fflate>
5
+ Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSE
6
+ version 0.8.2
7
+ */var it=Uint8Array,sn=Uint16Array,Sl=Int32Array,Kr=new it([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Xr=new it([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),_l=new it([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Yr=function(i,e){for(var t=new sn(31),n=0;n<31;++n)t[n]=e+=1<<i[n-1];for(var s=new Sl(t[30]),n=1;n<30;++n)for(var r=t[n];r<t[n+1];++r)s[r]=r-t[n]<<5|n;return{b:t,r:s}},qr=Yr(Kr,2),$r=qr.b,bl=qr.r;$r[28]=258,bl[258]=28;var xl=Yr(Xr,0),Al=xl.b,mi=new sn(32768);for(var _e=0;_e<32768;++_e){var vt=(_e&43690)>>1|(_e&21845)<<1;vt=(vt&52428)>>2|(vt&13107)<<2,vt=(vt&61680)>>4|(vt&3855)<<4,mi[_e]=((vt&65280)>>8|(vt&255)<<8)>>1}var Sn=(function(i,e,t){for(var n=i.length,s=0,r=new sn(e);s<n;++s)i[s]&&++r[i[s]-1];var o=new sn(e);for(s=1;s<e;++s)o[s]=o[s-1]+r[s-1]<<1;var a;if(t){a=new sn(1<<e);var c=15-e;for(s=0;s<n;++s)if(i[s])for(var u=s<<4|i[s],d=e-i[s],h=o[i[s]-1]++<<d,f=h|(1<<d)-1;h<=f;++h)a[mi[h]>>c]=u}else for(a=new sn(n),s=0;s<n;++s)i[s]&&(a[s]=mi[o[i[s]-1]++]>>15-i[s]);return a}),Cn=new it(288);for(var _e=0;_e<144;++_e)Cn[_e]=8;for(var _e=144;_e<256;++_e)Cn[_e]=9;for(var _e=256;_e<280;++_e)Cn[_e]=7;for(var _e=280;_e<288;++_e)Cn[_e]=8;var Qr=new it(32);for(var _e=0;_e<32;++_e)Qr[_e]=5;var Ml=Sn(Cn,9,1),Rl=Sn(Qr,5,1),Ws=function(i){for(var e=i[0],t=1;t<i.length;++t)i[t]>e&&(e=i[t]);return e},lt=function(i,e,t){var n=e/8|0;return(i[n]|i[n+1]<<8)>>(e&7)&t},Zs=function(i,e){var t=e/8|0;return(i[t]|i[t+1]<<8|i[t+2]<<16)>>(e&7)},vl=function(i){return(i+7)/8|0},Cl=function(i,e,t){return(t==null||t>i.length)&&(t=i.length),new it(i.subarray(e,t))},Il=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],ut=function(i,e,t){var n=new Error(e||Il[i]);if(n.code=i,Error.captureStackTrace&&Error.captureStackTrace(n,ut),!t)throw n;return n},Ll=function(i,e,t,n){var s=i.length,r=0;if(!s||e.f&&!e.l)return t||new it(0);var o=!t,a=o||e.i!=2,c=e.i;o&&(t=new it(s*3));var u=function(Ht){var Et=t.length;if(Ht>Et){var In=new it(Math.max(Et*2,Ht));In.set(t),t=In}},d=e.f||0,h=e.p||0,f=e.b||0,m=e.l,E=e.d,b=e.m,T=e.n,A=s*8;do{if(!m){d=lt(i,h,1);var w=lt(i,h+1,3);if(h+=3,w)if(w==1)m=Ml,E=Rl,b=9,T=5;else if(w==2){var P=lt(i,h,31)+257,I=lt(i,h+10,15)+4,C=P+lt(i,h+5,31)+1;h+=14;for(var D=new it(C),L=new it(19),k=0;k<I;++k)L[_l[k]]=lt(i,h+k*3,7);h+=I*3;for(var N=Ws(L),V=(1<<N)-1,G=Sn(L,N,1),k=0;k<C;){var $=G[lt(i,h,V)];h+=$&15;var x=$>>4;if(x<16)D[k++]=x;else{var ie=0,Ne=0;for(x==16?(Ne=3+lt(i,h,3),h+=2,ie=D[k-1]):x==17?(Ne=3+lt(i,h,7),h+=3):x==18&&(Ne=11+lt(i,h,127),h+=7);Ne--;)D[k++]=ie}}var ot=D.subarray(0,P),Re=D.subarray(P);b=Ws(ot),T=Ws(Re),m=Sn(ot,b,1),E=Sn(Re,T,1)}else ut(1);else{var x=vl(h)+4,_=i[x-4]|i[x-3]<<8,M=x+_;if(M>s){c&&ut(0);break}a&&u(f+_),t.set(i.subarray(x,M),f),e.b=f+=_,e.p=h=M*8,e.f=d;continue}if(h>A){c&&ut(0);break}}a&&u(f+131072);for(var ze=(1<<b)-1,je=(1<<T)-1,Ae=h;;Ae=h){var ie=m[Zs(i,h)&ze],ye=ie>>4;if(h+=ie&15,h>A){c&&ut(0);break}if(ie||ut(2),ye<256)t[f++]=ye;else if(ye==256){Ae=h,m=null;break}else{var ft=ye-254;if(ye>264){var k=ye-257,Ge=Kr[k];ft=lt(i,h,(1<<Ge)-1)+$r[k],h+=Ge}var xt=E[Zs(i,h)&je],ge=xt>>4;xt||ut(3),h+=xt&15;var Re=Al[ge];if(ge>3){var Ge=Xr[ge];Re+=Zs(i,h)&(1<<Ge)-1,h+=Ge}if(h>A){c&&ut(0);break}a&&u(f+131072);var at=f+ft;if(f<Re){var ct=r-Re,on=Math.min(Re,at);for(ct+f<0&&ut(3);f<on;++f)t[f]=n[ct+f]}for(;f<at;++f)t[f]=t[f-Re]}}e.l=m,e.p=Ae,e.b=f,e.f=d,m&&(d=1,e.m=b,e.d=E,e.n=T)}while(!d);return f!=t.length&&o?Cl(t,0,f):t.subarray(0,f)},Pl=new it(0),Ol=function(i,e){return((i[0]&15)!=8||i[0]>>4>7||(i[0]<<8|i[1])%31)&&ut(6,"invalid zlib data"),(i[1]>>5&1)==1&&ut(6,"invalid zlib data: "+(i[1]&32?"need":"unexpected")+" dictionary"),(i[1]>>3&4)+2};function En(i,e){return Ll(i.subarray(Ol(i),-4),{i:2},e,e)}var Dl=typeof TextDecoder<"u"&&new TextDecoder,Nl=0;try{Dl.decode(Pl,{stream:!0}),Nl=1}catch{}class kl extends p.DataTextureLoader{constructor(e){super(e),this.type=p.HalfFloatType,this.outputFormat=p.RGBAFormat,this.part=0}parse(e){const D=Math.pow(2.7182818,2.2);let L=null;function k(l,g){let y=0;for(let O=0;O<65536;++O)(O==0||l[O>>3]&1<<(O&7))&&(g[y++]=O);const v=y-1;for(;y<65536;)g[y++]=0;return v}function N(l){for(let g=0;g<16384;g++)l[g]={},l[g].len=0,l[g].lit=0,l[g].p=null}const V={l:0,c:0,lc:0};function G(l,g,y,v,O){for(;y<l;)g=g<<8|Di(v,O),y+=8;y-=l,V.l=g>>y&(1<<l)-1,V.c=g,V.lc=y}const $=new Array(59);function ie(l){for(let y=0;y<=58;++y)$[y]=0;for(let y=0;y<65537;++y)$[l[y]]+=1;let g=0;for(let y=58;y>0;--y){const v=g+$[y]>>1;$[y]=g,g=v}for(let y=0;y<65537;++y){const v=l[y];v>0&&(l[y]=v|$[v]++<<6)}}function Ne(l,g,y,v,O,z){const R=g;let H=0,B=0;for(;v<=O;v++){if(R.value-g.value>y)return!1;G(6,H,B,l,R);const U=V.l;if(H=V.c,B=V.lc,z[v]=U,U==63){if(R.value-g.value>y)throw new Error("THREE.EXRLoader: Something wrong with hufUnpackEncTable");G(8,H,B,l,R);let j=V.l+6;if(H=V.c,B=V.lc,v+j>O+1)throw new Error("THREE.EXRLoader: Something wrong with hufUnpackEncTable");for(;j--;)z[v++]=0;v--}else if(U>=59){let j=U-59+2;if(v+j>O+1)throw new Error("THREE.EXRLoader: Something wrong with hufUnpackEncTable");for(;j--;)z[v++]=0;v--}}ie(z)}function ot(l){return l&63}function Re(l){return l>>6}function ze(l,g,y,v){for(;g<=y;g++){const O=Re(l[g]),z=ot(l[g]);if(O>>z)throw new Error("THREE.EXRLoader: Invalid table entry");if(z>14){const R=v[O>>z-14];if(R.len)throw new Error("THREE.EXRLoader: Invalid table entry");if(R.lit++,R.p){const H=R.p;R.p=new Array(R.lit);for(let B=0;B<R.lit-1;++B)R.p[B]=H[B]}else R.p=new Array(1);R.p[R.lit-1]=g}else if(z){let R=0;for(let H=1<<14-z;H>0;H--){const B=v[(O<<14-z)+R];if(B.len||B.p)throw new Error("THREE.EXRLoader: Invalid table entry");B.len=z,B.lit=g,R++}}}return!0}const je={c:0,lc:0};function Ae(l,g,y,v){l=l<<8|Di(y,v),g+=8,je.c=l,je.lc=g}const ye={c:0,lc:0};function ft(l,g,y,v,O,z,R,H,B){if(l==g){v<8&&(Ae(y,v,O,z),y=je.c,v=je.lc),v-=8;let U=y>>v;if(U=new Uint8Array([U])[0],H.value+U>B)return!1;const j=R[H.value-1];for(;U-- >0;)R[H.value++]=j}else if(H.value<B)R[H.value++]=l;else return!1;ye.c=y,ye.lc=v}function Ge(l){return l&65535}function xt(l){const g=Ge(l);return g>32767?g-65536:g}const ge={a:0,b:0};function at(l,g){const y=xt(l),O=xt(g),z=y+(O&1)+(O>>1),R=z,H=z-O;ge.a=R,ge.b=H}function ct(l,g){const y=Ge(l),v=Ge(g),O=y-(v>>1)&65535,z=v+O-32768&65535;ge.a=z,ge.b=O}function on(l,g,y,v,O,z,R){const H=R<16384,B=y>O?O:y;let U=1,j,Z;for(;U<=B;)U<<=1;for(U>>=1,j=U,U>>=1;U>=1;){Z=0;const W=Z+z*(O-j),q=z*U,ee=z*j,X=v*U,Q=v*j;let oe,he,ae,de;for(;Z<=W;Z+=ee){let ne=Z;const te=Z+v*(y-j);for(;ne<=te;ne+=Q){const se=ne+X,Ee=ne+q,pe=Ee+X;H?(at(l[ne+g],l[Ee+g]),oe=ge.a,ae=ge.b,at(l[se+g],l[pe+g]),he=ge.a,de=ge.b,at(oe,he),l[ne+g]=ge.a,l[se+g]=ge.b,at(ae,de),l[Ee+g]=ge.a,l[pe+g]=ge.b):(ct(l[ne+g],l[Ee+g]),oe=ge.a,ae=ge.b,ct(l[se+g],l[pe+g]),he=ge.a,de=ge.b,ct(oe,he),l[ne+g]=ge.a,l[se+g]=ge.b,ct(ae,de),l[Ee+g]=ge.a,l[pe+g]=ge.b)}if(y&U){const se=ne+q;H?at(l[ne+g],l[se+g]):ct(l[ne+g],l[se+g]),oe=ge.a,l[se+g]=ge.b,l[ne+g]=oe}}if(O&U){let ne=Z;const te=Z+v*(y-j);for(;ne<=te;ne+=Q){const se=ne+X;H?at(l[ne+g],l[se+g]):ct(l[ne+g],l[se+g]),oe=ge.a,l[se+g]=ge.b,l[ne+g]=oe}}j=U,U>>=1}return Z}function Ht(l,g,y,v,O,z,R,H,B){let U=0,j=0;const Z=R,W=Math.trunc(v.value+(O+7)/8);for(;v.value<W;)for(Ae(U,j,y,v),U=je.c,j=je.lc;j>=14;){const ee=U>>j-14&16383,X=g[ee];if(X.len)j-=X.len,ft(X.lit,z,U,j,y,v,H,B,Z),U=ye.c,j=ye.lc;else{if(!X.p)throw new Error("THREE.EXRLoader: hufDecode issues");let Q;for(Q=0;Q<X.lit;Q++){const oe=ot(l[X.p[Q]]);for(;j<oe&&v.value<W;)Ae(U,j,y,v),U=je.c,j=je.lc;if(j>=oe&&Re(l[X.p[Q]])==(U>>j-oe&(1<<oe)-1)){j-=oe,ft(X.p[Q],z,U,j,y,v,H,B,Z),U=ye.c,j=ye.lc;break}}if(Q==X.lit)throw new Error("THREE.EXRLoader: hufDecode issues")}}const q=8-O&7;for(U>>=q,j-=q;j>0;){const ee=g[U<<14-j&16383];if(ee.len)j-=ee.len,ft(ee.lit,z,U,j,y,v,H,B,Z),U=ye.c,j=ye.lc;else throw new Error("THREE.EXRLoader: hufDecode issues")}return!0}function Et(l,g,y,v,O,z){const R={value:0},H=y.value,B=Je(g,y),U=Je(g,y);y.value+=4;const j=Je(g,y);if(y.value+=4,B<0||B>=65537||U<0||U>=65537)throw new Error("THREE.EXRLoader: Something wrong with HUF_ENCSIZE");const Z=new Array(65537),W=new Array(16384);N(W);const q=v-(y.value-H);if(Ne(l,y,q,B,U,Z),j>8*(v-(y.value-H)))throw new Error("THREE.EXRLoader: Something wrong with hufUncompress");ze(Z,B,U,W),Ht(Z,W,l,y,j,U,z,O,R)}function In(l,g,y){for(let v=0;v<y;++v)g[v]=l[g[v]]}function Ln(l){for(let g=1;g<l.length;g++){const y=l[g-1]+l[g]-128;l[g]=y}}function Pn(l,g){let y=0,v=Math.floor((l.length+1)/2),O=0;const z=l.length-1;for(;!(O>z||(g[O++]=l[y++],O>z));)g[O++]=l[v++]}function As(l){let g=l.byteLength;const y=new Array;let v=0;const O=new DataView(l);for(;g>0;){const z=O.getInt8(v++);if(z<0){const R=-z;g-=R+1;for(let H=0;H<R;H++)y.push(O.getUint8(v++))}else{const R=z;g-=2;const H=O.getUint8(v++);for(let B=0;B<R+1;B++)y.push(H)}}return y}function uo(l,g,y,v,O,z){let R=new DataView(z.buffer);const H=y[l.idx[0]].width,B=y[l.idx[0]].height,U=3,j=Math.floor(H/8),Z=Math.ceil(H/8),W=Math.ceil(B/8),q=H-(Z-1)*8,ee=B-(W-1)*8,X={value:0},Q=new Array(U),oe=new Array(U),he=new Array(U),ae=new Array(U),de=new Array(U);for(let te=0;te<U;++te)de[te]=g[l.idx[te]],Q[te]=te<1?0:Q[te-1]+Z*W,oe[te]=new Float32Array(64),he[te]=new Uint16Array(64),ae[te]=new Uint16Array(Z*64);for(let te=0;te<W;++te){let se=8;te==W-1&&(se=ee);let Ee=8;for(let ce=0;ce<Z;++ce){ce==Z-1&&(Ee=q);for(let ue=0;ue<U;++ue)he[ue].fill(0),he[ue][0]=O[Q[ue]++],Ci(X,v,he[ue]),Ii(he[ue],oe[ue]),Li(oe[ue]);po(oe);for(let ue=0;ue<U;++ue)Pi(oe[ue],ae[ue],ce*64)}let pe=0;for(let ce=0;ce<U;++ce){const ue=y[l.idx[ce]].type;for(let ve=8*te;ve<8*te+se;++ve){pe=de[ce][ve];for(let et=0;et<j;++et){const Se=et*64+(ve&7)*8;R.setUint16(pe+0*ue,ae[ce][Se+0],!0),R.setUint16(pe+2*ue,ae[ce][Se+1],!0),R.setUint16(pe+4*ue,ae[ce][Se+2],!0),R.setUint16(pe+6*ue,ae[ce][Se+3],!0),R.setUint16(pe+8*ue,ae[ce][Se+4],!0),R.setUint16(pe+10*ue,ae[ce][Se+5],!0),R.setUint16(pe+12*ue,ae[ce][Se+6],!0),R.setUint16(pe+14*ue,ae[ce][Se+7],!0),pe+=16*ue}}if(j!=Z)for(let ve=8*te;ve<8*te+se;++ve){const et=de[ce][ve]+8*j*2*ue,Se=j*64+(ve&7)*8;for(let pt=0;pt<Ee;++pt)R.setUint16(et+pt*2*ue,ae[ce][Se+pt],!0)}}}const ne=new Uint16Array(H);R=new DataView(z.buffer);for(let te=0;te<U;++te){y[l.idx[te]].decoded=!0;const se=y[l.idx[te]].type;if(y[te].type==2)for(let Ee=0;Ee<B;++Ee){const pe=de[te][Ee];for(let ce=0;ce<H;++ce)ne[ce]=R.getUint16(pe+ce*2*se,!0);for(let ce=0;ce<H;++ce)R.setFloat32(pe+ce*2*se,J(ne[ce]),!0)}}}function fo(l,g,y,v,O,z){const R=new DataView(z.buffer),H=y[l],B=H.width,U=H.height,j=Math.ceil(B/8),Z=Math.ceil(U/8),W=Math.floor(B/8),q=B-(j-1)*8,ee=U-(Z-1)*8,X={value:0};let Q=0;const oe=new Float32Array(64),he=new Uint16Array(64),ae=new Uint16Array(j*64);for(let de=0;de<Z;++de){let ne=8;de==Z-1&&(ne=ee);for(let te=0;te<j;++te)he.fill(0),he[0]=O[Q++],Ci(X,v,he),Ii(he,oe),Li(oe),Pi(oe,ae,te*64);for(let te=8*de;te<8*de+ne;++te){let se=g[l][te];for(let Ee=0;Ee<W;++Ee){const pe=Ee*64+(te&7)*8;for(let ce=0;ce<8;++ce)R.setUint16(se+ce*2*H.type,ae[pe+ce],!0);se+=16*H.type}if(j!=W){const Ee=W*64+(te&7)*8;for(let pe=0;pe<q;++pe)R.setUint16(se+pe*2*H.type,ae[Ee+pe],!0)}}}H.decoded=!0}function Ci(l,g,y){let v,O=1;for(;O<64;)v=g[l.value],v==65280?O=64:v>>8==255?O+=v&255:(y[O]=v,O++),l.value++}function Ii(l,g){g[0]=J(l[0]),g[1]=J(l[1]),g[2]=J(l[5]),g[3]=J(l[6]),g[4]=J(l[14]),g[5]=J(l[15]),g[6]=J(l[27]),g[7]=J(l[28]),g[8]=J(l[2]),g[9]=J(l[4]),g[10]=J(l[7]),g[11]=J(l[13]),g[12]=J(l[16]),g[13]=J(l[26]),g[14]=J(l[29]),g[15]=J(l[42]),g[16]=J(l[3]),g[17]=J(l[8]),g[18]=J(l[12]),g[19]=J(l[17]),g[20]=J(l[25]),g[21]=J(l[30]),g[22]=J(l[41]),g[23]=J(l[43]),g[24]=J(l[9]),g[25]=J(l[11]),g[26]=J(l[18]),g[27]=J(l[24]),g[28]=J(l[31]),g[29]=J(l[40]),g[30]=J(l[44]),g[31]=J(l[53]),g[32]=J(l[10]),g[33]=J(l[19]),g[34]=J(l[23]),g[35]=J(l[32]),g[36]=J(l[39]),g[37]=J(l[45]),g[38]=J(l[52]),g[39]=J(l[54]),g[40]=J(l[20]),g[41]=J(l[22]),g[42]=J(l[33]),g[43]=J(l[38]),g[44]=J(l[46]),g[45]=J(l[51]),g[46]=J(l[55]),g[47]=J(l[60]),g[48]=J(l[21]),g[49]=J(l[34]),g[50]=J(l[37]),g[51]=J(l[47]),g[52]=J(l[50]),g[53]=J(l[56]),g[54]=J(l[59]),g[55]=J(l[61]),g[56]=J(l[35]),g[57]=J(l[36]),g[58]=J(l[48]),g[59]=J(l[49]),g[60]=J(l[57]),g[61]=J(l[58]),g[62]=J(l[62]),g[63]=J(l[63])}function Li(l){const g=.5*Math.cos(.7853975),y=.5*Math.cos(3.14159/16),v=.5*Math.cos(3.14159/8),O=.5*Math.cos(3*3.14159/16),z=.5*Math.cos(5*3.14159/16),R=.5*Math.cos(3*3.14159/8),H=.5*Math.cos(7*3.14159/16),B=new Array(4),U=new Array(4),j=new Array(4),Z=new Array(4);for(let W=0;W<8;++W){const q=W*8;B[0]=v*l[q+2],B[1]=R*l[q+2],B[2]=v*l[q+6],B[3]=R*l[q+6],U[0]=y*l[q+1]+O*l[q+3]+z*l[q+5]+H*l[q+7],U[1]=O*l[q+1]-H*l[q+3]-y*l[q+5]-z*l[q+7],U[2]=z*l[q+1]-y*l[q+3]+H*l[q+5]+O*l[q+7],U[3]=H*l[q+1]-z*l[q+3]+O*l[q+5]-y*l[q+7],j[0]=g*(l[q+0]+l[q+4]),j[3]=g*(l[q+0]-l[q+4]),j[1]=B[0]+B[3],j[2]=B[1]-B[2],Z[0]=j[0]+j[1],Z[1]=j[3]+j[2],Z[2]=j[3]-j[2],Z[3]=j[0]-j[1],l[q+0]=Z[0]+U[0],l[q+1]=Z[1]+U[1],l[q+2]=Z[2]+U[2],l[q+3]=Z[3]+U[3],l[q+4]=Z[3]-U[3],l[q+5]=Z[2]-U[2],l[q+6]=Z[1]-U[1],l[q+7]=Z[0]-U[0]}for(let W=0;W<8;++W)B[0]=v*l[16+W],B[1]=R*l[16+W],B[2]=v*l[48+W],B[3]=R*l[48+W],U[0]=y*l[8+W]+O*l[24+W]+z*l[40+W]+H*l[56+W],U[1]=O*l[8+W]-H*l[24+W]-y*l[40+W]-z*l[56+W],U[2]=z*l[8+W]-y*l[24+W]+H*l[40+W]+O*l[56+W],U[3]=H*l[8+W]-z*l[24+W]+O*l[40+W]-y*l[56+W],j[0]=g*(l[W]+l[32+W]),j[3]=g*(l[W]-l[32+W]),j[1]=B[0]+B[3],j[2]=B[1]-B[2],Z[0]=j[0]+j[1],Z[1]=j[3]+j[2],Z[2]=j[3]-j[2],Z[3]=j[0]-j[1],l[0+W]=Z[0]+U[0],l[8+W]=Z[1]+U[1],l[16+W]=Z[2]+U[2],l[24+W]=Z[3]+U[3],l[32+W]=Z[3]-U[3],l[40+W]=Z[2]-U[2],l[48+W]=Z[1]-U[1],l[56+W]=Z[0]-U[0]}function po(l){for(let g=0;g<64;++g){const y=l[0][g],v=l[1][g],O=l[2][g];l[0][g]=y+1.5747*O,l[1][g]=y-.1873*v-.4682*O,l[2][g]=y+1.8556*v}}function Pi(l,g,y){for(let v=0;v<64;++v)g[y+v]=p.DataUtils.toHalfFloat(mo(l[v]))}function mo(l){return l<=1?Math.sign(l)*Math.pow(Math.abs(l),2.2):Math.sign(l)*Math.pow(D,Math.abs(l)-1)}function On(l){return new DataView(l.array.buffer,l.offset.value,l.size)}function go(l){const g=l.viewer.buffer.slice(l.offset.value,l.offset.value+l.size),y=new Uint8Array(As(g)),v=new Uint8Array(y.length);return Ln(y),Pn(y,v),new DataView(v.buffer)}function Ms(l){const g=l.array.slice(l.offset.value,l.offset.value+l.size),y=En(g),v=new Uint8Array(y.length);return Ln(y),Pn(y,v),new DataView(v.buffer)}function yo(l){const g=l.viewer,y={value:l.offset.value},v=new Uint16Array(l.columns*l.lines*(l.inputChannels.length*l.type)),O=new Uint8Array(8192);let z=0;const R=new Array(l.inputChannels.length);for(let ee=0,X=l.inputChannels.length;ee<X;ee++)R[ee]={},R[ee].start=z,R[ee].end=R[ee].start,R[ee].nx=l.columns,R[ee].ny=l.lines,R[ee].size=l.type,z+=R[ee].nx*R[ee].ny*R[ee].size;const H=an(g,y),B=an(g,y);if(B>=8192)throw new Error("THREE.EXRLoader: Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(H<=B)for(let ee=0;ee<B-H+1;ee++)O[ee+H]=At(g,y);const U=new Uint16Array(65536),j=k(O,U),Z=Je(g,y);Et(l.array,g,y,Z,v,z);for(let ee=0;ee<l.inputChannels.length;++ee){const X=R[ee];for(let Q=0;Q<R[ee].size;++Q)on(v,X.start+Q,X.nx,X.size,X.ny,X.nx*X.size,j)}In(U,v,z);let W=0;const q=new Uint8Array(v.buffer.byteLength);for(let ee=0;ee<l.lines;ee++)for(let X=0;X<l.inputChannels.length;X++){const Q=R[X],oe=Q.nx*Q.size,he=new Uint8Array(v.buffer,Q.end*2,oe*2);q.set(he,W),W+=oe*2,Q.end+=oe}return new DataView(q.buffer)}function Eo(l){const g=l.array.slice(l.offset.value,l.offset.value+l.size),y=En(g),v=l.inputChannels.length*l.lines*l.columns*l.totalBytes,O=new ArrayBuffer(v),z=new DataView(O);let R=0,H=0;const B=new Array(4);for(let U=0;U<l.lines;U++)for(let j=0;j<l.inputChannels.length;j++){let Z=0;switch(l.inputChannels[j].pixelType){case 1:B[0]=R,B[1]=B[0]+l.columns,R=B[1]+l.columns;for(let q=0;q<l.columns;++q){const ee=y[B[0]++]<<8|y[B[1]++];Z+=ee,z.setUint16(H,Z,!0),H+=2}break;case 2:B[0]=R,B[1]=B[0]+l.columns,B[2]=B[1]+l.columns,R=B[2]+l.columns;for(let q=0;q<l.columns;++q){const ee=y[B[0]++]<<24|y[B[1]++]<<16|y[B[2]++]<<8;Z+=ee,z.setUint32(H,Z,!0),H+=4}break}}return z}function wo(l){const g=l.array;let y=l.offset.value;const v=l.columns,O=l.lines,z=l.inputChannels,R=l.totalBytes,H=Ze.compression==="B44A_COMPRESSION",B=new Uint8Array(O*v*R),U=new Uint16Array(16);let j=0;for(let Z=0;Z<z.length;Z++){const W=z[Z],q=W.pixelType*2,ee=Math.ceil(v/W.xSampling),X=Math.ceil(O/W.ySampling),Q=W.xSampling===1&&W.ySampling===1;if(W.pixelType!==1){for(let ae=0;ae<X;ae++)if(Q){const de=ae*v*R+j*v;for(let ne=0;ne<ee*q;ne++)B[de+ne]=g[y++]}else y+=ee*q;j+=q;continue}const oe=Math.ceil(ee/4),he=Math.ceil(X/4);for(let ae=0;ae<he;ae++)for(let de=0;de<oe;de++){if(H&&g[y+2]>=52){const ne=g[y]<<8|g[y+1],te=ne&32768?ne&32767:~ne&65535;U.fill(te),y+=3}else{const ne=g[y]<<8|g[y+1],te=g[y+2]>>2,se=32<<te,Ee=ne+((g[y+2]<<4|g[y+3]>>4)&63)*(1<<te)-se&65535,pe=Ee+((g[y+3]<<2|g[y+4]>>6)&63)*(1<<te)-se&65535,ce=pe+(g[y+4]&63)*(1<<te)-se&65535,ue=ne+(g[y+5]>>2&63)*(1<<te)-se&65535,ve=Ee+((g[y+5]<<4|g[y+6]>>4)&63)*(1<<te)-se&65535,et=pe+((g[y+6]<<2|g[y+7]>>6)&63)*(1<<te)-se&65535,Se=ce+(g[y+7]&63)*(1<<te)-se&65535,pt=ue+(g[y+8]>>2&63)*(1<<te)-se&65535,Vt=ve+((g[y+8]<<4|g[y+9]>>4)&63)*(1<<te)-se&65535,cn=et+((g[y+9]<<2|g[y+10]>>6)&63)*(1<<te)-se&65535,mt=Se+(g[y+10]&63)*(1<<te)-se&65535,Dt=pt+(g[y+11]>>2&63)*(1<<te)-se&65535,Bn=Vt+((g[y+11]<<4|g[y+12]>>4)&63)*(1<<te)-se&65535,zn=cn+((g[y+12]<<2|g[y+13]>>6)&63)*(1<<te)-se&65535,Un=mt+(g[y+13]&63)*(1<<te)-se&65535,ln=[ne,ue,pt,Dt,Ee,ve,Vt,Bn,pe,et,cn,zn,ce,Se,mt,Un];for(let jt=0;jt<16;jt++)U[jt]=ln[jt]&32768?ln[jt]&32767:~ln[jt]&65535;y+=14}if(W.pLinear){if(L===null){L=new Uint16Array(65536);for(let ne=0;ne<65536;ne++)if((ne&31744)===31744||ne>32768)L[ne]=0;else{const te=J(ne);L[ne]=te<=0?0:p.DataUtils.toHalfFloat(8*Math.log(te))}}for(let ne=0;ne<16;ne++)U[ne]=L[U[ne]]}for(let ne=0;ne<4;ne++){const te=ae*4+ne;if(!(te>=X))for(let se=0;se<4;se++){const Ee=de*4+se;if(Ee>=ee)continue;const pe=U[ne*4+se];for(let ce=0;ce<W.ySampling;ce++){const ue=te*W.ySampling+ce;if(!(ue>=O))for(let ve=0;ve<W.xSampling;ve++){const et=Ee*W.xSampling+ve;if(et>=v)continue;const Se=ue*v*R+j*v+et*2;B[Se]=pe&255,B[Se+1]=pe>>8&255}}}}}j+=2}return new DataView(B.buffer)}function Oi(l){const g=l.viewer,y={value:l.offset.value},v=new Uint8Array(l.columns*l.lines*(l.inputChannels.length*l.type*2)),O={version:ke(g,y),unknownUncompressedSize:ke(g,y),unknownCompressedSize:ke(g,y),acCompressedSize:ke(g,y),dcCompressedSize:ke(g,y),rleCompressedSize:ke(g,y),rleUncompressedSize:ke(g,y),rleRawSize:ke(g,y),totalAcUncompressedCount:ke(g,y),totalDcUncompressedCount:ke(g,y),acCompression:ke(g,y)};if(O.version<2)throw new Error("THREE.EXRLoader: "+Ze.compression+" version "+O.version+" is unsupported");const z=new Array;let R=an(g,y)-2;for(;R>0;){const X=Dn(g.buffer,y),Q=At(g,y),oe=Q>>2&3,he=(Q>>4)-1,ae=new Int8Array([he])[0],de=At(g,y);z.push({name:X,index:ae,type:de,compression:oe}),R-=X.length+3}const H=Ze.channels,B=new Array(l.inputChannels.length);for(let X=0;X<l.inputChannels.length;++X){const Q=B[X]={},oe=H[X];Q.name=oe.name,Q.compression=0,Q.decoded=!1,Q.type=oe.pixelType,Q.pLinear=oe.pLinear,Q.width=l.columns,Q.height=l.lines}const U={idx:new Array(3)};for(let X=0;X<l.inputChannels.length;++X){const Q=B[X],oe=Q.name.lastIndexOf("."),he=oe>=0?Q.name.substring(oe+1):Q.name;for(let ae=0;ae<z.length;++ae){const de=z[ae];he===de.name&&Q.type===de.type&&(Q.compression=de.compression,de.index>=0&&(U.idx[de.index]=X),Q.offset=X)}}let j,Z,W;if(O.acCompressedSize>0)switch(O.acCompression){case 0:j=new Uint16Array(O.totalAcUncompressedCount),Et(l.array,g,y,O.acCompressedSize,j,O.totalAcUncompressedCount);break;case 1:const X=l.array.slice(y.value,y.value+O.totalAcUncompressedCount),Q=En(X);j=new Uint16Array(Q.buffer),y.value+=O.totalAcUncompressedCount;break}if(O.dcCompressedSize>0){const X={array:l.array,offset:y,size:O.dcCompressedSize};Z=new Uint16Array(Ms(X).buffer),y.value+=O.dcCompressedSize}if(O.rleRawSize>0){const X=l.array.slice(y.value,y.value+O.rleCompressedSize),Q=En(X);W=As(Q.buffer),y.value+=O.rleCompressedSize}let q=0;const ee=new Array(B.length);for(let X=0;X<ee.length;++X)ee[X]=new Array;for(let X=0;X<l.lines;++X)for(let Q=0;Q<B.length;++Q)ee[Q].push(q),q+=B[Q].width*l.type*2;U.idx[0]!==void 0&&B[U.idx[0]]&&uo(U,ee,B,j,Z,v);for(let X=0;X<B.length;++X){const Q=B[X];if(!Q.decoded)switch(Q.compression){case 2:let oe=0,he=0;for(let ae=0;ae<l.lines;++ae){let de=ee[X][oe];for(let ne=0;ne<Q.width;++ne){for(let te=0;te<2*Q.type;++te)v[de++]=W[he+te*Q.width*Q.height];he++}oe++}break;case 1:fo(X,ee,B,j,Z,v);break;default:throw new Error("THREE.EXRLoader: unsupported channel compression")}}return new DataView(v.buffer)}function Dn(l,g){const y=new Uint8Array(l);let v=0;for(;y[g.value+v]!=0;)v+=1;const O=new TextDecoder().decode(y.slice(g.value,g.value+v));return g.value=g.value+v+1,O}function To(l,g,y){const v=new TextDecoder().decode(new Uint8Array(l).slice(g.value,g.value+y));return g.value=g.value+y,v}function So(l,g){const y=qe(l,g),v=Je(l,g);return[y,v]}function _o(l,g){const y=Je(l,g),v=Je(l,g);return[y,v]}function qe(l,g){const y=l.getInt32(g.value,!0);return g.value=g.value+4,y}function Je(l,g){const y=l.getUint32(g.value,!0);return g.value=g.value+4,y}function Di(l,g){const y=l[g.value];return g.value=g.value+1,y}function At(l,g){const y=l.getUint8(g.value);return g.value=g.value+1,y}const ke=function(l,g){const y=Number(l.getBigInt64(g.value,!0));return g.value+=8,y};function We(l,g){const y=l.getFloat32(g.value,!0);return g.value+=4,y}function bo(l,g){return p.DataUtils.toHalfFloat(We(l,g))}function J(l){const g=(l&31744)>>10,y=l&1023;return(l>>15?-1:1)*(g?g===31?y?NaN:1/0:Math.pow(2,g-15)*(1+y/1024):6103515625e-14*(y/1024))}function an(l,g){const y=l.getUint16(g.value,!0);return g.value+=2,y}function xo(l,g){return J(an(l,g))}function Ao(l,g,y,v){const O=y.value,z=[];for(;y.value<O+v-1;){const R=Dn(g,y),H=qe(l,y),B=At(l,y);y.value+=3;const U=qe(l,y),j=qe(l,y);z.push({name:R,pixelType:H,pLinear:B,xSampling:U,ySampling:j})}return y.value+=1,z}function Mo(l,g){const y=We(l,g),v=We(l,g),O=We(l,g),z=We(l,g),R=We(l,g),H=We(l,g),B=We(l,g),U=We(l,g);return{redX:y,redY:v,greenX:O,greenY:z,blueX:R,blueY:H,whiteX:B,whiteY:U}}function Ro(l,g){const y=["NO_COMPRESSION","RLE_COMPRESSION","ZIPS_COMPRESSION","ZIP_COMPRESSION","PIZ_COMPRESSION","PXR24_COMPRESSION","B44_COMPRESSION","B44A_COMPRESSION","DWAA_COMPRESSION","DWAB_COMPRESSION"],v=At(l,g);return y[v]}function vo(l,g){const y=qe(l,g),v=qe(l,g),O=qe(l,g),z=qe(l,g);return{xMin:y,yMin:v,xMax:O,yMax:z}}function Co(l,g){const y=["INCREASING_Y","DECREASING_Y","RANDOM_Y"],v=At(l,g);return y[v]}function Io(l,g){const y=["ENVMAP_LATLONG","ENVMAP_CUBE"],v=At(l,g);return y[v]}function Lo(l,g){const y=["ONE_LEVEL","MIPMAP_LEVELS","RIPMAP_LEVELS"],v=["ROUND_DOWN","ROUND_UP"],O=Je(l,g),z=Je(l,g),R=At(l,g);return{xSize:O,ySize:z,levelMode:y[R&15],roundingMode:v[R>>4]}}function Po(l,g){const y=We(l,g),v=We(l,g);return[y,v]}function Oo(l,g){const y=We(l,g),v=We(l,g),O=We(l,g);return[y,v,O]}function Do(l,g,y,v,O){if(v==="string"||v==="stringvector"||v==="iccProfile")return To(g,y,O);if(v==="chlist")return Ao(l,g,y,O);if(v==="chromaticities")return Mo(l,y);if(v==="compression")return Ro(l,y);if(v==="box2i")return vo(l,y);if(v==="envmap")return Io(l,y);if(v==="tiledesc")return Lo(l,y);if(v==="lineOrder")return Co(l,y);if(v==="float")return We(l,y);if(v==="v2f")return Po(l,y);if(v==="v3f")return Oo(l,y);if(v==="int")return qe(l,y);if(v==="rational")return So(l,y);if(v==="timecode")return _o(l,y);if(v==="preview"||v==="deepImageState"||v==="idmanifest")return y.value+=O,"skipped";y.value+=O}function No(l,g){const y=Math.log2(l);return g=="ROUND_DOWN"?Math.floor(y):Math.ceil(y)}function ko(l,g,y){let v=0;switch(l.levelMode){case"ONE_LEVEL":v=1;break;case"MIPMAP_LEVELS":v=No(Math.max(g,y),l.roundingMode)+1;break;case"RIPMAP_LEVELS":throw new Error("THREE.EXRLoader: RIPMAP_LEVELS tiles currently unsupported.")}return v}function Ni(l,g,y,v){const O=new Array(l);for(let z=0;z<l;z++){const R=1<<z;let H=g/R|0;v=="ROUND_UP"&&H*R<g&&(H+=1);const B=Math.max(H,1);O[z]=(B+y-1)/y|0}return O}function Fo(){const l=this,g=l.offset,y={value:0};for(let v=0;v<l.tileCount;v++){const O=qe(l.viewer,g),z=qe(l.viewer,g);g.value+=8,l.size=Je(l.viewer,g);const R=O*l.blockWidth,H=z*l.blockHeight;l.columns=R+l.blockWidth>l.width?l.width-R:l.blockWidth,l.lines=H+l.blockHeight>l.height?l.height-H:l.blockHeight;const B=l.columns*l.totalBytes,j=l.size<l.lines*B?l.uncompress(l):On(l);g.value+=l.size;for(let Z=0;Z<l.lines;Z++){const W=Z*l.columns*l.totalBytes;for(let q=0;q<l.inputChannels.length;q++){const ee=Ze.channels[q].name,X=l.channelByteOffsets[ee]*l.columns,Q=l.decodeChannels[ee];if(Q===void 0)continue;y.value=W+X;const oe=(l.height-(1+H+Z))*l.outLineWidth;for(let he=0;he<l.columns;he++){const ae=oe+(he+R)*l.outputChannels+Q;l.byteArray[ae]=l.getter(j,y)}}}}}function Bo(){const l=this,g=l.offset,y={value:0};for(let v=0;v<l.height/l.blockHeight;v++){const O=qe(l.viewer,g)-Ze.dataWindow.yMin;l.size=Je(l.viewer,g),l.lines=O+l.blockHeight>l.height?l.height-O:l.blockHeight;const z=l.columns*l.totalBytes,H=l.size<l.lines*z?l.uncompress(l):On(l);g.value+=l.size;for(let B=0;B<l.lines;B++){const U=O+B,j=B*z,Z=(l.height-1-U)*l.outLineWidth;for(let W=0;W<l.inputChannels.length;W++){const q=Ze.channels[W].name,ee=l.channelByteOffsets[q]*l.columns,X=l.decodeChannels[q];if(X!==void 0){y.value=j+ee;for(let Q=0;Q<l.columns;Q++){const oe=Z+Q*l.outputChannels+X;l.byteArray[oe]=l.getter(H,y)}}}}}}function zo(){const l=this,g=l.chunkOffsets,y={value:0};for(let v=0;v<g.length;v++){const O={value:g[v]};O.value+=4;const z=qe(l.viewer,O)-Ze.dataWindow.yMin;l.size=Je(l.viewer,O),l.lines=z+l.blockHeight>l.height?l.height-z:l.blockHeight;const R=l.columns*l.totalBytes,H=l.size<l.lines*R,B=l.offset;l.offset=O;const U=H?l.uncompress(l):On(l);l.offset=B;for(let j=0;j<l.lines;j++){const Z=z+j,W=j*R,q=(l.height-1-Z)*l.outLineWidth;for(let ee=0;ee<l.inputChannels.length;ee++){const X=Ze.channels[ee].name,Q=l.channelByteOffsets[X]*l.columns,oe=l.decodeChannels[X];if(oe!==void 0){y.value=W+Q;for(let he=0;he<l.columns;he++){const ae=q+he*l.outputChannels+oe;l.byteArray[ae]=l.getter(U,y)}}}}}}function ki(l,g,y,v){if(y===0)return null;const O=l.slice(g,g+y);switch(v){case"NO_COMPRESSION":return new DataView(O.buffer,O.byteOffset,O.byteLength);case"RLE_COMPRESSION":{const z=new Uint8Array(As(O.buffer.slice(O.byteOffset,O.byteOffset+O.byteLength))),R=new Uint8Array(z.length);return Ln(z),Pn(z,R),new DataView(R.buffer)}case"ZIPS_COMPRESSION":{const z=En(O),R=new Uint8Array(z.length);return Ln(z),Pn(z,R),new DataView(R.buffer)}default:throw new Error("THREE.EXRLoader: "+v+" is unsupported for deep data")}}function Uo(){const l=this,g=l.chunkOffsets,y=l.width,v=l.height,O=l.deepChannels,z=Ze.compression,R=l.multiPart,H=l.decodeChannels,B=l.outputChannels,U=l.byteArray instanceof Uint16Array;let j=-1;for(let Z=0;Z<O.length;Z++)if(O[Z].name==="A"){j=Z;break}for(let Z=0;Z<g.length;Z++){const W={value:g[Z]};R&&(W.value+=4);const q=qe(l.viewer,W)-Ze.dataWindow.yMin,ee=ke(l.viewer,W),X=ke(l.viewer,W);ke(l.viewer,W);const Q=ki(l.array,W.value,ee,z);if(W.value+=ee,Q===null)continue;const oe=new Uint32Array(y);for(let se=0;se<y;se++)oe[se]=Q.getUint32(se*4,!0);const he=oe[y-1];if(he===0){W.value+=X;continue}const ae=ki(l.array,W.value,X,z),de=[];let ne=0;for(let se=0;se<O.length;se++)de.push(ne),ne+=he*O[se].bytesPerSample;const te=(v-1-q)*l.outLineWidth;for(let se=0;se<y;se++){const Ee=se===0?0:oe[se-1],ce=oe[se]-Ee;if(ce===0)continue;const ue=new Float32Array(B);let ve=0;for(let Se=0;Se<ce;Se++){const pt=Ee+Se,Vt=1-ve;if(Vt<=0)break;let cn=1;if(j>=0){const mt=O[j].bytesPerSample,Dt=de[j]+pt*mt;cn=mt===2?J(ae.getUint16(Dt,!0)):ae.getFloat32(Dt,!0)}for(let mt=0;mt<O.length;mt++){const Dt=O[mt],Bn=H[Dt.name];if(Bn===void 0)continue;const zn=Dt.bytesPerSample,Un=de[mt]+pt*zn,ln=zn===2?J(ae.getUint16(Un,!0)):ae.getFloat32(Un,!0);ue[Bn]+=ln*Vt}ve+=cn*Vt}H.A!==void 0&&(ue[H.A]=ve);const et=te+se*B;for(let Se=0;Se<B;Se++)l.byteArray[et+Se]=U?p.DataUtils.toHalfFloat(ue[Se]):ue[Se]}}}function Fi(l,g,y){const v={};let O=!1;for(;;){const z=Dn(g,y);if(z==="")break;O=!0;const R=Dn(g,y),H=Je(l,y),B=Do(l,g,y,R,H);B===void 0?console.warn(`THREE.EXRLoader: Skipped unknown header attribute type '${R}'.`):v[z]=B}return O?v:null}function Ho(l,g,y){if(l.getUint32(0,!0)!=20000630)throw new Error("THREE.EXRLoader: Provided file doesn't appear to be in OpenEXR format.");const v=l.getUint8(4),O=l.getUint8(5),z={singleTile:!!(O&2),longName:!!(O&4),deepFormat:!!(O&8),multiPart:!!(O&16)};y.value=8;const R=[];if(z.multiPart){for(;;){const H=Fi(l,g,y);if(H===null)break;H.version=v,H.spec=z,R.push(H)}if(R.length===0)throw new Error("THREE.EXRLoader: No valid part headers found.")}else{const H=Fi(l,g,y);H.version=v,H.spec=z,R.push(H)}return R}function Vo(l,g,y,v,O,z){const R={size:0,viewer:g,array:y,offset:v,width:l.dataWindow.xMax-l.dataWindow.xMin+1,height:l.dataWindow.yMax-l.dataWindow.yMin+1,inputChannels:l.channels,channelByteOffsets:{},shouldExpand:!1,yCbCr:!1,totalBytes:null,columns:null,lines:null,type:null,uncompress:null,getter:null,format:null,colorSpace:p.LinearSRGBColorSpace};switch(l.compression){case"NO_COMPRESSION":R.blockHeight=1,R.uncompress=On;break;case"RLE_COMPRESSION":R.blockHeight=1,R.uncompress=go;break;case"ZIPS_COMPRESSION":R.blockHeight=1,R.uncompress=Ms;break;case"ZIP_COMPRESSION":R.blockHeight=16,R.uncompress=Ms;break;case"PIZ_COMPRESSION":R.blockHeight=32,R.uncompress=yo;break;case"PXR24_COMPRESSION":R.blockHeight=16,R.uncompress=Eo;break;case"B44_COMPRESSION":case"B44A_COMPRESSION":R.blockHeight=32,R.uncompress=wo;break;case"DWAA_COMPRESSION":R.blockHeight=32,R.uncompress=Oi;break;case"DWAB_COMPRESSION":R.blockHeight=256,R.uncompress=Oi;break;default:throw new Error("THREE.EXRLoader: "+l.compression+" is unsupported")}const H={};for(const W of l.channels)switch(W.name){case"BY":case"RY":case"Y":case"R":case"G":case"B":case"A":H[W.name]=!0,R.type=W.pixelType}let B=!1,U=!1;if(H.Y&&H.RY&&H.BY)R.outputChannels=4,R.yCbCr=!0;else if(H.R&&H.G&&H.B)R.outputChannels=4;else if(H.Y)R.outputChannels=1;else throw new Error("THREE.EXRLoader: file contains unsupported data channels.");switch(R.outputChannels){case 4:z==p.RGBAFormat?(B=!H.A,R.format=p.RGBAFormat,R.colorSpace=p.LinearSRGBColorSpace,R.outputChannels=4,R.decodeChannels={R:0,G:1,B:2,A:3}):z==p.RGFormat?(R.format=p.RGFormat,R.colorSpace=p.LinearSRGBColorSpace,R.outputChannels=2,R.decodeChannels={R:0,G:1}):z==p.RedFormat?(R.format=p.RedFormat,R.colorSpace=p.LinearSRGBColorSpace,R.outputChannels=1,R.decodeChannels={R:0}):U=!0;break;case 1:z==p.RGBAFormat?(B=!0,R.format=p.RGBAFormat,R.colorSpace=p.LinearSRGBColorSpace,R.outputChannels=4,R.shouldExpand=!0,R.decodeChannels={Y:0}):z==p.RGFormat?(R.format=p.RGFormat,R.colorSpace=p.LinearSRGBColorSpace,R.outputChannels=2,R.shouldExpand=!0,R.decodeChannels={Y:0}):z==p.RedFormat?(R.format=p.RedFormat,R.colorSpace=p.LinearSRGBColorSpace,R.outputChannels=1,R.decodeChannels={Y:0}):U=!0;break;default:U=!0}if(U)throw new Error("THREE.EXRLoader: invalid output format for specified file.");if(R.yCbCr&&(R.format=p.RGBAFormat,R.outputChannels=4,R.decodeChannels={Y:0,RY:1,BY:2},B=!0),R.type==1)switch(O){case p.FloatType:R.getter=xo;break;case p.HalfFloatType:R.getter=an;break}else if(R.type==2)switch(O){case p.FloatType:R.getter=We;break;case p.HalfFloatType:R.getter=bo}else throw new Error("THREE.EXRLoader: unsupported pixelType "+R.type+" for "+l.compression+".");R.columns=R.width;const j=R.width*R.height*R.outputChannels;switch(O){case p.FloatType:R.byteArray=new Float32Array(j),B&&R.byteArray.fill(1,0,j);break;case p.HalfFloatType:R.byteArray=new Uint16Array(j),B&&R.byteArray.fill(15360,0,j);break;default:console.error("THREE.EXRLoader: unsupported type: ",O);break}let Z=0;for(const W of l.channels)R.decodeChannels[W.name]!==void 0&&(R.channelByteOffsets[W.name]=Z),Z+=W.pixelType*2;if(R.totalBytes=Z,R.outLineWidth=R.width*R.outputChannels,l.spec.deepFormat){R.deepChannels=[];let W=0;for(const q of l.channels){const ee=q.pixelType===0?4:q.pixelType*2;R.deepChannels.push({name:q.name,pixelType:q.pixelType,bytesPerSample:ee}),W+=ee}R.deepBytesPerSample=W,R.chunkOffsets=l._chunkOffsets,R.multiPart=l.spec.multiPart,R.decode=Uo.bind(R)}else if(l.spec.singleTile){R.blockHeight=l.tiles.ySize,R.blockWidth=l.tiles.xSize;const W=ko(l.tiles,R.width,R.height),q=Ni(W,R.width,l.tiles.xSize,l.tiles.roundingMode),ee=Ni(W,R.height,l.tiles.ySize,l.tiles.roundingMode);R.tileCount=q[0]*ee[0];for(let X=0;X<W;X++)for(let Q=0;Q<ee[X];Q++)for(let oe=0;oe<q[X];oe++)ke(g,v);R.decode=Fo.bind(R)}else if(l.spec.multiPart)R.blockWidth=R.width,R.chunkOffsets=l._chunkOffsets,R.decode=zo.bind(R);else{R.blockWidth=R.width;const W=Math.ceil(R.height/R.blockHeight);for(let q=0;q<W;q++)ke(g,v);R.decode=Bo.bind(R)}return R}const Nn={value:0},kn=new DataView(e),jo=new Uint8Array(e),Fn=Ho(kn,e,Nn),Bi=Math.max(0,Math.min(this.part,Fn.length-1)),Ze=Fn[Bi];if(Ze.spec.multiPart||Ze.spec.deepFormat)for(let l=0;l<Fn.length;l++){const g=Fn[l].chunkCount;if(l===Bi){Ze._chunkOffsets=[];for(let y=0;y<g;y++)Ze._chunkOffsets.push(ke(kn,Nn))}else for(let y=0;y<g;y++)ke(kn,Nn)}const tt=Vo(Ze,kn,jo,Nn,this.type,this.outputFormat);if(tt.decode(),tt.shouldExpand){const l=tt.byteArray;if(this.outputFormat==p.RGBAFormat)for(let g=0;g<l.length;g+=4)l[g+2]=l[g+1]=l[g];else if(this.outputFormat==p.RGFormat)for(let g=0;g<l.length;g+=2)l[g+1]=l[g]}if(tt.yCbCr){const l=tt.byteArray,g=tt.width*tt.height;if(this.type===p.HalfFloatType)for(let y=0;y<g;y++){const v=y*4,O=J(l[v]),z=J(l[v+1]),R=J(l[v+2]),H=(1+z)*O,B=(1+R)*O,U=(O-H*.2126-B*.0722)/.7152;l[v]=p.DataUtils.toHalfFloat(Math.max(0,H)),l[v+1]=p.DataUtils.toHalfFloat(Math.max(0,U)),l[v+2]=p.DataUtils.toHalfFloat(Math.max(0,B))}else for(let y=0;y<g;y++){const v=y*4,O=l[v],z=l[v+1],R=l[v+2],H=(1+z)*O,B=(1+R)*O;l[v]=Math.max(0,H),l[v+1]=Math.max(0,(O-H*.2126-B*.0722)/.7152),l[v+2]=Math.max(0,B)}}return{header:Ze,width:tt.width,height:tt.height,data:tt.byteArray,format:tt.format,colorSpace:tt.colorSpace,type:this.type,minFilter:p.LinearFilter,magFilter:p.LinearFilter,generateMipmaps:!1,flipY:!1}}setDataType(e){return this.type=e,this}setOutputFormat(e){return this.outputFormat=e,this}setPart(e){return this.part=e,this}}class Fl extends p.DataTextureLoader{constructor(e){super(e),this.type=p.HalfFloatType}parse(e){const o=function(C,D){switch(C){case 1:throw new Error("THREE.HDRLoader: Read Error: "+(D||""));case 2:throw new Error("THREE.HDRLoader: Write Error: "+(D||""));case 3:throw new Error("THREE.HDRLoader: Bad File Format: "+(D||""));default:case 4:throw new Error("THREE.HDRLoader: Memory Error: "+(D||""))}},h=function(C,D,L){D=D||1024;let N=C.pos,V=-1,G=0,$="",ie=String.fromCharCode.apply(null,new Uint16Array(C.subarray(N,N+128)));for(;0>(V=ie.indexOf(`
8
+ `))&&G<D&&N<C.byteLength;)$+=ie,G+=ie.length,N+=128,ie=String.fromCharCode.apply(null,new Uint16Array(C.subarray(N,N+128)));return-1<V?(C.pos+=G+V+1,$+ie.slice(0,V)):!1},f=function(C){const D=/^#\?(\S+)/,L=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,k=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,N=/^\s*FORMAT=(\S+)\s*$/,V=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,G={valid:0,string:"",comments:"",programtype:"RGBE",format:"",gamma:1,exposure:1,width:0,height:0};let $,ie;for((C.pos>=C.byteLength||!($=h(C)))&&o(1,"no header found"),(ie=$.match(D))||o(3,"bad initial token"),G.valid|=1,G.programtype=ie[1],G.string+=$+`
9
+ `;$=h(C),$!==!1;){if(G.string+=$+`
10
+ `,$.charAt(0)==="#"){G.comments+=$+`
11
+ `;continue}if((ie=$.match(L))&&(G.gamma=parseFloat(ie[1])),(ie=$.match(k))&&(G.exposure=parseFloat(ie[1])),(ie=$.match(N))&&(G.valid|=2,G.format=ie[1]),(ie=$.match(V))&&(G.valid|=4,G.height=parseInt(ie[1],10),G.width=parseInt(ie[2],10)),G.valid&2&&G.valid&4)break}return G.valid&2||o(3,"missing format specifier"),G.valid&4||o(3,"missing image size specifier"),G},m=function(C,D,L){const k=D;if(k<8||k>32767||C[0]!==2||C[1]!==2||C[2]&128)return new Uint8Array(C);k!==(C[2]<<8|C[3])&&o(3,"wrong scanline width");const N=new Uint8Array(4*D*L);N.length||o(4,"unable to allocate buffer space");let V=0,G=0;const $=4*k,ie=new Uint8Array(4),Ne=new Uint8Array($);let ot=L;for(;ot>0&&G<C.byteLength;){G+4>C.byteLength&&o(1),ie[0]=C[G++],ie[1]=C[G++],ie[2]=C[G++],ie[3]=C[G++],(ie[0]!=2||ie[1]!=2||(ie[2]<<8|ie[3])!=k)&&o(3,"bad rgbe scanline format");let Re=0,ze;for(;Re<$&&G<C.byteLength;){ze=C[G++];const Ae=ze>128;if(Ae&&(ze-=128),(ze===0||Re+ze>$)&&o(3,"bad scanline data"),Ae){const ye=C[G++];for(let ft=0;ft<ze;ft++)Ne[Re++]=ye}else Ne.set(C.subarray(G,G+ze),Re),Re+=ze,G+=ze}const je=k;for(let Ae=0;Ae<je;Ae++){let ye=0;N[V]=Ne[Ae+ye],ye+=k,N[V+1]=Ne[Ae+ye],ye+=k,N[V+2]=Ne[Ae+ye],ye+=k,N[V+3]=Ne[Ae+ye],V+=4}ot--}return N},E=function(C,D,L,k){const N=C[D+3],V=Math.pow(2,N-128)/255;L[k+0]=C[D+0]*V,L[k+1]=C[D+1]*V,L[k+2]=C[D+2]*V,L[k+3]=1},b=function(C,D,L,k){const N=C[D+3],V=Math.pow(2,N-128)/255;L[k+0]=p.DataUtils.toHalfFloat(Math.min(C[D+0]*V,65504)),L[k+1]=p.DataUtils.toHalfFloat(Math.min(C[D+1]*V,65504)),L[k+2]=p.DataUtils.toHalfFloat(Math.min(C[D+2]*V,65504)),L[k+3]=p.DataUtils.toHalfFloat(1)},T=new Uint8Array(e);T.pos=0;const A=f(T),w=A.width,x=A.height,_=m(T.subarray(T.pos),w,x);let M,P,I;switch(this.type){case p.FloatType:I=_.length/4;const C=new Float32Array(I*4);for(let L=0;L<I;L++)E(_,L*4,C,L*4);M=C,P=p.FloatType;break;case p.HalfFloatType:I=_.length/4;const D=new Uint16Array(I*4);for(let L=0;L<I;L++)b(_,L*4,D,L*4);M=D,P=p.HalfFloatType;break;default:throw new Error("THREE.HDRLoader: Unsupported type: "+this.type)}return{width:w,height:x,data:M,header:A.string,gamma:A.gamma,exposure:A.exposure,type:P,colorSpace:p.LinearSRGBColorSpace,minFilter:p.LinearFilter,magFilter:p.LinearFilter,generateMipmaps:!1,flipY:!0}}setDataType(e){return this.type=e,this}}class Bl extends Fl{constructor(e){console.warn("RGBELoader has been deprecated. Please use HDRLoader instead."),super(e)}}class zl extends p.Scene{constructor(){super(),this.name="RoomEnvironment",this.position.y=-3.5;const e=new p.BoxGeometry;e.deleteAttribute("uv");const t=new p.MeshStandardMaterial({side:p.BackSide}),n=new p.MeshStandardMaterial,s=new p.PointLight(16777215,900,28,2);s.position.set(.418,16.199,.3),this.add(s);const r=new p.Mesh(e,t);r.position.set(-.757,13.219,.717),r.scale.set(31.713,28.305,28.591),this.add(r);const o=new p.InstancedMesh(e,n,6),a=new p.Object3D;a.position.set(-10.906,2.009,1.846),a.rotation.set(0,-.195,0),a.scale.set(2.328,7.905,4.651),a.updateMatrix(),o.setMatrixAt(0,a.matrix),a.position.set(-5.607,-.754,-.758),a.rotation.set(0,.994,0),a.scale.set(1.97,1.534,3.955),a.updateMatrix(),o.setMatrixAt(1,a.matrix),a.position.set(6.167,.857,7.803),a.rotation.set(0,.561,0),a.scale.set(3.927,6.285,3.687),a.updateMatrix(),o.setMatrixAt(2,a.matrix),a.position.set(-2.017,.018,6.124),a.rotation.set(0,.333,0),a.scale.set(2.002,4.566,2.064),a.updateMatrix(),o.setMatrixAt(3,a.matrix),a.position.set(2.291,-.756,-2.621),a.rotation.set(0,-.286,0),a.scale.set(1.546,1.552,1.496),a.updateMatrix(),o.setMatrixAt(4,a.matrix),a.position.set(-2.193,-.369,-5.547),a.rotation.set(0,.516,0),a.scale.set(3.875,3.487,2.986),a.updateMatrix(),o.setMatrixAt(5,a.matrix),this.add(o);const c=new p.Mesh(e,Jt(50));c.position.set(-16.116,14.37,8.208),c.scale.set(.1,2.428,2.739),this.add(c);const u=new p.Mesh(e,Jt(50));u.position.set(-16.109,18.021,-8.207),u.scale.set(.1,2.425,2.751),this.add(u);const d=new p.Mesh(e,Jt(17));d.position.set(14.904,12.198,-1.832),d.scale.set(.15,4.265,6.331),this.add(d);const h=new p.Mesh(e,Jt(43));h.position.set(-.462,8.89,14.52),h.scale.set(4.38,5.441,.088),this.add(h);const f=new p.Mesh(e,Jt(20));f.position.set(3.235,11.486,-12.541),f.scale.set(2.5,2,.1),this.add(f);const m=new p.Mesh(e,Jt(100));m.position.set(0,20,0),m.scale.set(1,.1,1),this.add(m)}dispose(){const e=new Set;this.traverse(t=>{t.isMesh&&(e.add(t.geometry),e.add(t.material))});for(const t of e)t.dispose()}}function Jt(i){return new p.MeshLambertMaterial({color:0,emissive:16777215,emissiveIntensity:i})}class Ul{constructor(){this.pmremGenerator=null,this.loadedTextures=new Map,this.renderTargets=[],this.disposed=!1}async initialize(e){var t;try{const n=e.renderer;let s=n.renderer||((t=n.getThreeRenderer)==null?void 0:t.call(n));if(!s&&n.getDomElement){const r=n.getDomElement();if(r&&"parentElement"in r&&r.parentElement){const o=r.parentElement.renderer;o instanceof S.WebGLRenderer&&(s=o)}}return s?(this.pmremGenerator=new S.PMREMGenerator(s),this.pmremGenerator.compileEquirectangularShader(),F.ok(void 0)):F.err(new K("Could not access Three.js renderer",Y.INITIALIZATION_FAILED))}catch(n){return F.err(new K("Failed to initialize environment service",Y.INITIALIZATION_FAILED,{originalError:n}))}}async loadEnvironmentMap(e){var t;try{const n=this.loadedTextures.get(e);if(n)return F.ok(new en(n));const s=(t=e.split(".").pop())==null?void 0:t.toLowerCase();let r;switch(s){case"hdr":r=new Bl;break;case"exr":r=new kl;break;case"jpg":case"jpeg":case"png":r=new S.TextureLoader;break;default:return F.err(new K(`Unsupported environment map format: ${s}`,Y.UNSUPPORTED_FORMAT,{url:e,extension:s}))}const o=await new Promise((a,c)=>{r.load(e,u=>{a(u)},void 0,u=>c(u))});if(this.disposed)return o.dispose(),F.err(new K("Environment service was disposed during the load",Y.INVALID_STATE,{url:e}));if(this.pmremGenerator){o.mapping=S.EquirectangularReflectionMapping;const a=this.pmremGenerator.fromEquirectangular(o);this.renderTargets.push(a);const c=a.texture;return this.loadedTextures.set(e,c),this.loadedTextures.set(e+"_original",o),F.ok(new en(c))}return this.loadedTextures.set(e,o),F.ok(new en(o))}catch(n){return F.err(new K("Failed to load environment map",Y.TEXTURE_LOAD_FAILED,{url:e,originalError:n}))}}applyToScene(e,t,n){try{if(!(e instanceof St))return F.err(new K("Scene must be ThreeSceneAdapter",Y.INVALID_PARAMETER));if(!(t instanceof en))return F.err(new K("Texture must be ThreeTextureAdapter",Y.INVALID_PARAMETER));const s=e.getThreeScene(),r=t.getThreeTexture();if(s.environment=r,n&&(n.backgroundBlurriness!==void 0&&(s.backgroundBlurriness=n.backgroundBlurriness),n.backgroundIntensity!==void 0&&(s.backgroundIntensity=n.backgroundIntensity),n.environmentIntensity!==void 0&&(s.environmentIntensity=n.environmentIntensity)),r.mapping===S.CubeUVReflectionMapping){const a=Array.from(this.loadedTextures.entries()).find(([c,u])=>c.endsWith("_original")&&u.mapping===S.EquirectangularReflectionMapping);a&&(s.__originalEnvironmentTexture=a[1])}else r.mapping===S.EquirectangularReflectionMapping&&(s.__originalEnvironmentTexture=r);if((n==null?void 0:n.setBackground)??!0)if(r.mapping===S.EquirectangularReflectionMapping)s.background=r;else if(r.mapping===S.CubeUVReflectionMapping){const a=Array.from(this.loadedTextures.entries()).find(([c,u])=>c.endsWith("_original")&&u.mapping===S.EquirectangularReflectionMapping);a?s.background=a[1]:s.background=r}else s.background=r;return F.ok(void 0)}catch(s){return F.err(new K("Failed to apply environment to scene",Y.SCENE_OPERATION_FAILED,{originalError:s}))}}getOriginalEnvironmentTexture(e){const t=this.loadedTextures.get(e+"_original");return t?new en(t):null}createStudioEnvironment(e={}){try{if(!this.pmremGenerator)return F.err(new K("Environment service not initialized",Y.INITIALIZATION_FAILED));const t=new zl,n=this.pmremGenerator.fromScene(t);this.renderTargets.push(n);const s=n.texture;return t.dispose(),F.ok(new en(s))}catch(t){return F.err(new K("Failed to create studio environment",Y.TEXTURE_LOAD_FAILED,{originalError:t}))}}dispose(){this.disposed=!0,this.loadedTextures.forEach(e=>e.dispose()),this.loadedTextures.clear(),this.renderTargets.forEach(e=>e.dispose()),this.renderTargets=[],this.pmremGenerator&&(this.pmremGenerator.dispose(),this.pmremGenerator=null)}}class en{constructor(e){this.texture=e}get id(){return this.texture.uuid}get image(){return this.texture.image}get needsUpdate(){return this.texture.needsUpdate}set needsUpdate(e){this.texture.needsUpdate=e}dispose(){this.texture.dispose()}getThreeTexture(){return this.texture}}class Hl{constructor(e){this.object=e,this.boundingBox=new S.Box3().setFromObject(this.object)}alignToFloor(){const e=this.calculateFloorOffset();this.applyOffset(e)}calculateFloorOffset(){const e=this.boundingBox.min.y,t=this.boundingBox.max.y-e,n=new S.Vector3;return t>0?n.y=-e:n.y=0,n}applyOffset(e){this.object.position.add(e)}}class Vl{alignToFloor(e){try{let t=null;return"getThreeObject"in e&&typeof e.getThreeObject=="function"?t=e.getThreeObject():e instanceof S.Object3D&&(t=e),t?(new Hl(t).alignToFloor(),F.ok(void 0)):F.err(new K("Could not get Three.js object for floor alignment",Y.INVALID_PARAMETER))}catch(t){return F.err(new K("Failed to align object to floor",Y.OPERATION_FAILED,{originalError:t}))}}}const wr={touch:10,default:5};class jl{constructor(){this.raycaster=new S.Raycaster,this.activePointers=new Set,this.options=null,this.pending=null,this.detach=null}initialize(e){this.dispose(),this.options=e;const{canvas:t}=e,n=o=>{this.activePointers.add(o.pointerId);try{t.setPointerCapture(o.pointerId)}catch{}if(this.activePointers.size>1||o.button!==0){this.pending=null;return}this.pending={pointerId:o.pointerId,x:o.clientX,y:o.clientY,threshold:o.pointerType==="touch"?wr.touch:wr.default}},s=o=>{this.activePointers.delete(o.pointerId);const a=this.pending;!a||a.pointerId!==o.pointerId||(this.pending=null,Math.hypot(o.clientX-a.x,o.clientY-a.y)>a.threshold)||this.pick(o.clientX,o.clientY)},r=o=>{this.activePointers.delete(o.pointerId),this.pending=null};t.addEventListener("pointerdown",n),t.addEventListener("pointerup",s),t.addEventListener("pointercancel",r),this.detach=()=>{t.removeEventListener("pointerdown",n),t.removeEventListener("pointerup",s),t.removeEventListener("pointercancel",r)}}pick(e,t){if(!this.options)return;const{canvas:n,camera:s,getPickRoot:r,onPick:o}=this.options,a=r(),c=zt(a),u=vn(s);if(!c||!u){o(null);return}const d=n.getBoundingClientRect();if(d.width===0||d.height===0){o(null);return}const h=new S.Vector2((e-d.left)/d.width*2-1,-((t-d.top)/d.height)*2+1);(this.options.bvh??!0)&&Fr(c),this.raycaster.setFromCamera(h,u),this.raycaster.firstHitOnly=!0;const f=this.raycaster.intersectObject(c,!0)[0];if(!f){o(null);return}o({object:new Oe(f.object),point:{x:f.point.x,y:f.point.y,z:f.point.z}})}dispose(){var e;(e=this.detach)==null||e.call(this),this.detach=null,this.options=null,this.pending=null,this.activePointers.clear()}}const Gl=.001,Tr={visible:!1};class Wl{constructor(e){this.sources=e,this.anchor=new S.Vector3,this.projected=new S.Vector3,this.cameraPosition=new S.Vector3,this.toAnchor=new S.Vector3,this.raycaster=new S.Raycaster,this.lastCameraMatrix=new S.Matrix4,this.lastWidth=-1,this.lastHeight=-1,this.hasProjected=!1}invalidate(){this.hasProjected=!1}project(e,t){const n=vn(this.sources.camera),s=this.sources.getCanvas();if(!n||!s)return null;const r=s.clientWidth||s.width,o=s.clientHeight||s.height;return this.hasProjected&&r===this.lastWidth&&o===this.lastHeight&&this.lastCameraMatrix.equals(n.matrixWorld)?null:(this.lastCameraMatrix.copy(n.matrixWorld),this.lastWidth=r,this.lastHeight=o,this.hasProjected=!0,this.anchor.set(e.x,e.y,e.z),n.getWorldPosition(this.cameraPosition),this.projected.copy(this.anchor).applyMatrix4(n.matrixWorldInverse),this.projected.z>=0||t&&this.isOccluded(n)?Tr:(this.projected.copy(this.anchor).project(n),{visible:!0,left:(this.projected.x+1)/2*r,top:(1-this.projected.y)/2*o}))}isOccluded(e){const t=zt(this.sources.getModel());if(!t)return!1;this.toAnchor.copy(this.anchor).sub(this.cameraPosition);const n=this.toAnchor.length();this.raycaster.set(this.cameraPosition,this.toAnchor.normalize()),this.raycaster.camera=e,this.raycaster.firstHitOnly=!0;const s=this.raycaster.intersectObject(t,!0)[0];return!!(s&&s.distance<n-Gl)}}class Zl{createProjector(e){return new Wl(e)}}class Kl{constructor(){this.mixer=null,this.clips=[],this.activeActions=[],this.playing=!1,this.speed=1}attach(e){this.detach();const t=zt(e);if(!t)return;const n=Xl(t);n&&(this.clips=n.animations,this.mixer=new S.AnimationMixer(n),this.mixer.timeScale=this.speed)}getClipNames(){return this.clips.map(e=>e.name)}play(e){if(e!==void 0){if(this.clips.length===0)return F.err(new K(`Cannot play animation clip '${e}': no animation clips are attached`,Y.INVALID_STATE));if(!this.clips.some(s=>s.name===e)){const s=this.clips.map(r=>r.name);return F.err(new K(`Unknown animation clip '${e}'. Available clips: ${s.join(", ")}`,Y.INVALID_PARAMETER))}}if(!this.mixer)return F.ok(void 0);if(!this.playing&&this.activeActions.length>0&&e===void 0)return this.playing=!0,F.ok(void 0);const t=e?this.clips.filter(s=>s.name===e):this.clips;if(t.length===0)return F.ok(void 0);const n=this.mixer;return n.stopAllAction(),this.activeActions=t.map(s=>{const r=n.clipAction(s);return r.play(),r}),this.playing=!0,F.ok(void 0)}pause(){this.playing=!1}isPlaying(){return this.playing}setSpeed(e){this.speed=e,this.mixer&&(this.mixer.timeScale=e)}update(e){this.playing&&this.mixer&&this.mixer.update(e)}detach(){this.mixer&&(this.mixer.stopAllAction(),this.mixer.uncacheRoot(this.mixer.getRoot())),this.mixer=null,this.clips=[],this.activeActions=[],this.playing=!1}}function Xl(i){let e=null;return i.traverse(t=>{var n;!e&&(((n=t.animations)==null?void 0:n.length)??0)>0&&(e=t)}),e}var An=(i=>(i.MapControls="MapControls",i.OrbitControls="OrbitControls",i))(An||{});class Yl{static convertRendererOptions(e){const t={antialias:e.antialias,alpha:e.alpha,premultipliedAlpha:e.premultipliedAlpha,preserveDrawingBuffer:e.preserveDrawingBuffer,powerPreference:e.powerPreference,pixelRatio:e.pixelRatio};return(e.shadowMapEnabled!==void 0||e.shadowMapType!==void 0)&&(t.shadowMap={enabled:e.shadowMapEnabled??!0,type:this.convertShadowMapType(e.shadowMapType)}),(e.toneMapping!==void 0||e.toneMappingExposure!==void 0)&&(t.toneMapping={type:this.convertToneMappingType(e.toneMapping),exposure:e.toneMappingExposure??1}),t}static convertShadowMapType(e){if(typeof e=="number"){if(e===S.BasicShadowMap)return"basic";if(e===S.PCFShadowMap)return"pcf";if(e===S.PCFSoftShadowMap)return"pcfsoft";if(e===S.VSMShadowMap)return"vsm"}return typeof e=="string"?e:void 0}static convertToneMappingType(e){if(typeof e=="number"){if(e===S.NoToneMapping)return"none";if(e===S.LinearToneMapping)return"linear";if(e===S.ReinhardToneMapping)return"reinhard";if(e===S.CineonToneMapping)return"cineon";if(e===S.ACESFilmicToneMapping)return"aces"}return typeof e=="string"?e:"aces"}}class ql{static createViewer(e,t){var w,x,_;Mr(t.units);const n=new dc(e),s=new St,r=this.createCamera(t),o=this.createControls(r.getThreeCamera(),e,t),a=new $l().createDefaultLoader({renderer:n.getThreeRenderer()??void 0,bvh:(w=t.selection)==null?void 0:w.bvh,...t.loaders}),c=new wl,u=new Ul;let d;(((x=t.pathTracing)==null?void 0:x.enabled)??!1)&&(d=new Tl);const f=new Vl,m=new jl,E=new Zl,b=new Kl,T=Yl.convertRendererOptions(t.renderer||{});(t.replaceWithScreenshotOnComplete||(_=t.pathTracing)!=null&&_.enabled)&&(T.preserveDrawingBuffer=!0);const A={renderer:n,scene:s,camera:r,controls:o,modelLoader:a,options:t,rendererOptions:T,sceneSetupService:c,environmentService:u,pathTracingService:d,floorAlignmentService:f,selectionService:m,anchorProjectionService:E,animationService:b};return new aa(A)}static createCamera(e){const n=e.camera||{},s=n.fov||n.cameraFov||75,r=n.near||n.cameraNear||.1,o=n.far||n.cameraFar||1e5,a=n.position||n.cameraPosition,c=n.target||n.cameraTarget,u=_i.create(s,1,r,o);return a&&u.position.set(a[0],a[1],a[2]),c&&u.lookAt({x:c[0],y:c[1],z:c[2],set:()=>{},copy:()=>{},add:()=>{},multiply:()=>{},normalize:()=>{},length:()=>0}),u}static createControls(e,t,n){const s=n.controls||{},r=s.type||An.OrbitControls;let o;r===An.MapControls?o=new fl(e,t):o=new dl(e,t),o.enabled=s.enabled??!0,o.enableDamping=s.enableDamping??!0,o.dampingFactor=s.dampingFactor??.25,o.enableZoom=s.enableZoom??!0,o.enableRotate=s.enableRotate??!0,o.enablePan=s.enablePan??!0,o.autoRotate=s.autoRotate??!1,s.autoRotateSpeed!==void 0&&(o.autoRotateSpeed=s.autoRotateSpeed),s.minDistance!==void 0&&(o.minDistance=s.minDistance),s.maxDistance!==void 0&&(o.maxDistance=s.maxDistance),s.minPolarAngle!==void 0&&(o.minPolarAngle=s.minPolarAngle),s.maxPolarAngle!==void 0&&(o.maxPolarAngle=s.maxPolarAngle);const c=n.camera||{},u=c.target||c.cameraTarget;return u&&o.target&&(o.target.set(u[0],u[1],u[2]),o.update()),o}}class $l extends pr{createDefaultLoader(e={}){return pr.createLoader("model.glb",e)}}const Ql=["toneMappingExposure"],Jl=["environmentIntensity"],eh=["autoRotate","autoRotateSpeed"];function Jr(i){var t,n,s,r,o,a,c,u,d,h;const e={backgroundColor:i.backgroundColor};return((t=i.renderer)==null?void 0:t.toneMappingExposure)!==void 0&&(e.renderer={toneMappingExposure:i.renderer.toneMappingExposure}),((n=i.environment)==null?void 0:n.environmentIntensity)!==void 0&&(e.environment={environmentIntensity:i.environment.environmentIntensity}),(((s=i.controls)==null?void 0:s.autoRotate)!==void 0||((r=i.controls)==null?void 0:r.autoRotateSpeed)!==void 0)&&(e.controls={autoRotate:(o=i.controls)==null?void 0:o.autoRotate,autoRotateSpeed:(a=i.controls)==null?void 0:a.autoRotateSpeed}),(((c=i.animations)==null?void 0:c.autoplay)!==void 0||((u=i.animations)==null?void 0:u.speed)!==void 0)&&(e.animations={autoplay:(d=i.animations)==null?void 0:d.autoplay,speed:(h=i.animations)==null?void 0:h.speed}),e}const ys={staticScene:!1,backgroundColor:"#f0f0f7",replaceWithScreenshotOnComplete:!0,units:"meters",pathTracing:{enabled:!1,maxSamples:16,bounces:16,transmissiveBounces:4,renderScale:.8,lowResScale:.25,dynamicLowRes:!0},camera:{position:[60,60,60],target:[0,0,0],fov:45,near:.1,far:1e5,autoFitToObject:!0},environment:{backgroundIntensity:1,environmentIntensity:.7},lighting:{ambientLight:{color:"#404040",intensity:.3},hemisphereLight:{skyColor:"#ffffbb",groundColor:"#080820",intensity:.3},directionalLight:{color:"#ffffff",intensity:2,position:[40,90,40],castShadow:!0,shadow:{mapSize:{width:4096,height:4096},camera:{near:.5,far:200,left:-50,right:50,top:50,bottom:-50},bias:-1e-4,radius:14}}},renderer:{antialias:!0,alpha:!1,shadowMapEnabled:!0,pixelRatio:typeof window<"u"?window.devicePixelRatio:1,shadowMapType:1,toneMapping:6,toneMappingExposure:1.1},controls:{type:An.OrbitControls,enabled:!0,enableDamping:!0,dampingFactor:.25,enableZoom:!0,enableRotate:!0,enablePan:!0},helpers:{grid:{type:"hexagonal_glass",size:20,divisions:20,colorGrid:"#a8a8a2",opacity:.5,styleOptions:{tileSize:.1173,metalness:0,roughness:.9,transmission:0}},axes:!1,stats:!1,gizmo:!1,studioEnvironment:!0,darkStudioMode:!1}},Mi={studio:{backgroundColor:"#f0f0f7",renderer:{toneMappingExposure:1.1},environment:{environmentIntensity:.7}},product:{backgroundColor:"#ffffff",renderer:{toneMappingExposure:1.25},environment:{environmentIntensity:.85}},neutral:{backgroundColor:"#d9d9de",renderer:{toneMappingExposure:1},environment:{environmentIntensity:.6}},dark:{backgroundColor:"#1a1a1f",renderer:{toneMappingExposure:1.15},environment:{environmentIntensity:.8}},outdoor:{backgroundColor:"#bcd4e6",renderer:{toneMappingExposure:1.15},environment:{environmentIntensity:.85}}};function eo(i){return i?Mi[i]:{}}function gi(i,e){return ps(ps(i,eo(e.preset)),e)}const Ks=(i,...e)=>{if(!i)return;const t={...i};for(const n of e)delete t[n];return Object.keys(t).length>0?t:void 0};function th(i){const e=re.useMemo(()=>{var s;return JSON.stringify({pathTracing:i.pathTracing,staticScene:i.staticScene,renderer:Ks(i.renderer,...Ql),camera:i.camera,controls:Ks(i.controls,...eh),environment:Ks(i.environment,...Jl),lighting:i.lighting,helpers:i.helpers,rendering:i.rendering,replaceWithScreenshotOnComplete:i.replaceWithScreenshotOnComplete,loaders:i.loaders,units:i.units??"meters",selectionBvh:((s=i.selection)==null?void 0:s.bvh)!==!1})},[i.pathTracing,i.staticScene,i.renderer,i.camera,i.controls,i.environment,i.lighting,i.helpers,i.rendering,i.replaceWithScreenshotOnComplete,i.loaders,i.units,i.selection]),t=re.useMemo(()=>{const s=gi(ys,i);return JSON.stringify(Jr(s))},[i.preset,i.backgroundColor,i.renderer,i.environment,i.controls,i.animations]);return{options:re.useMemo(()=>i,[e,t]),structuralKey:e,runtimeKey:t}}function nh(i,e){const t=re.useRef(null),[n,s]=re.useState(!1),[r,o]=re.useState(null),{options:a,structuralKey:c,runtimeKey:u}=th(e);re.useEffect(()=>{if(!i.current||t.current)return;o(null);const h=gi(ys,a);let f;try{f=ql.createViewer(i.current,h)}catch(E){console.error("Failed to create viewer:",E),o(E instanceof Error?E:new Error(String(E)));return}t.current=f;let m=!1;return f.initialize().then(E=>{m||(E.ok?s(!0):(console.error("Failed to initialize viewer:",E.error),o(E.error)))}),()=>{m=!0,f.dispose(),t.current=null,s(!1)}},[i,c]),re.useEffect(()=>{if(!t.current||!n)return;const h=gi(ys,a);t.current.updateOptions(Jr(h))},[u,n]);const d=re.useRef({width:0,height:0});return re.useEffect(()=>{if(!t.current||!i.current)return;let h=null;const f=b=>{if(i.current&&t.current){const T=i.current.parentElement||i.current;let{clientWidth:A,clientHeight:w}=T;if(b&&b[0]){const{width:x,height:_}=b[0].contentRect;A=Math.floor(x),w=Math.floor(_)}if(d.current.width===A&&d.current.height===w)return;h!==null&&cancelAnimationFrame(h),h=requestAnimationFrame(()=>{t.current&&i.current&&(t.current.resize(A,w),d.current={width:A,height:w})})}};f();const m=()=>f();window.addEventListener("resize",m);let E=null;return typeof ResizeObserver<"u"&&i.current.parentElement&&(E=new ResizeObserver(f),E.observe(i.current.parentElement)),()=>{window.removeEventListener("resize",m),E==null||E.disconnect(),h!==null&&cancelAnimationFrame(h)}},[n,i]),{viewer:t.current,isInitialized:n,initError:r}}function to(i,e){const t=re.useRef(e);t.current=e,re.useEffect(()=>{if(!i)return;const n=i.getEvents(),s=[],r=o=>{const a=c=>{var u,d;(d=(u=t.current)[o])==null||d.call(u,c)};return n.on(o,a),()=>n.off(o,a)};return Object.keys(e).forEach(o=>{e[o]&&s.push(r(o))}),()=>{s.forEach(o=>o())}},[i])}function sh(i,e){const[t,n]=re.useState(null),s=re.useRef(new Set);re.useEffect(()=>{if(i!==void 0&&s.current.has(i)){s.current.delete(i),n(c=>c===i?null:c);return}s.current.clear(),n(null)},[i]);const r=!!(e!=null&&e.presets);re.useEffect(()=>{r||(s.current.clear(),n(null))},[r]);const o=e==null?void 0:e.onPresetChange,a=re.useCallback(c=>{n(c),o&&(s.current.add(c),o(c))},[o]);return{activePreset:t??i,pickerEnabled:r,selectPreset:a}}function ih(i,e,t,n,s){return re.useMemo(()=>{var u,d,h;const r=i.preset!==e,o=t===!0&&((u=i.pathTracing)==null?void 0:u.enabled)===void 0,a=n!==void 0&&((d=i.controls)==null?void 0:d.autoRotate)===void 0,c=s!==void 0&&((h=i.animations)==null?void 0:h.autoplay)===void 0;return!r&&!o&&!a&&!c?i:{...i,...r?{preset:e}:{},...o?{pathTracing:{...i.pathTracing,enabled:!0}}:{},...a?{controls:{...i.controls,autoRotate:n}}:{},...c?{animations:{...i.animations,autoplay:s}}:{}}},[i,e,t,n,s])}function rh(i,e,t){const n=re.useMemo(()=>{if(typeof t=="string")return t;if(t)return`object-${t.uuid||"no-uuid"}`},[t]),[s,r]=re.useState(()=>({status:t?"loading":"idle"}));return re.useEffect(()=>{r({status:t?"loading":"idle"})},[n]),re.useEffect(()=>{if(!i||!e||!t)return;let o=!0;const a=typeof t=="string"?t:new Oe(t);return i.loadModel(a).then(c=>{o&&(c.ok?r({status:"loaded"}):(r({status:"error",error:c.error.message}),console.error("Failed to load model:",c.error)))}),()=>{o=!1}},[i,e,n]),s}class Xs{static toThreeObject(e){const t=zt(e);if(t)return t;const n=new S.Object3D;return n.position.set(e.position.x,e.position.y,e.position.z),n.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z),n.scale.set(e.scale.x,e.scale.y,e.scale.z),n}static toThreeCamera(e){return vn(e)??new S.PerspectiveCamera}static toThreeControls(e){return xi(e)??e}static convertModelLoaded(e){return{model:this.toThreeObject(e.model),loadTime:e.loadTime}}static convertControlsChange(e){return{type:e.type,camera:e.camera?this.toThreeCamera(e.camera):void 0,controls:e.controls?this.toThreeControls(e.controls):void 0}}static convertObjectSelected(e){return{object:this.toThreeObject(e.object),point:e.point}}static convertInitialized(e,t){return{viewer:t}}static convertDisposed(e,t){return{viewer:t}}}function oh(i){const e=re.useRef(new ws),t=re.useMemo(()=>({"model:loading":n=>e.current.emit("model:loading",n),"model:progress":n=>e.current.emit("model:progress",n),"model:loaded":n=>e.current.emit("model:loaded",Xs.convertModelLoaded(n)),"model:error":n=>e.current.emit("model:error",n),"render:complete":n=>e.current.emit("render:complete",n),"controls:change":n=>e.current.emit("controls:change",Xs.convertControlsChange(n)),"object:selected":n=>e.current.emit("object:selected",Xs.convertObjectSelected(n)),error:n=>e.current.emit("error",n)}),[]);return to(i,t),e.current}function ah(i,e,t){const n=re.useRef(t);n.current=t;const s=re.useMemo(()=>({"model:loaded":()=>{var o,a;return(a=(o=n.current).onLoad)==null?void 0:a.call(o)},"model:progress":o=>{var a,c;return(c=(a=n.current).onProgress)==null?void 0:c.call(a,Math.min(1,o.loaded/o.total))},"model:error":o=>{var a,c;return(c=(a=n.current).onError)==null?void 0:c.call(a,o.error)}}),[]);to(i,s);const r=re.useRef(null);re.useEffect(()=>{if(!e){r.current=null;return}const o=n.current.onError;o&&r.current!==e&&(r.current=e,o(e))})}const no=re.createContext(null);function ch({viewer:i,canvasRef:e,children:t}){const n=re.useMemo(()=>({viewer:i,canvasRef:e}),[i,e]);return me.jsx(no.Provider,{value:n,children:t})}function so(){const i=re.useContext(no);if(!i)throw new Error("useViewerContext must be used within ViewerProvider");return i}function lh(){const{canvasRef:i}=so();return me.jsx("canvas",{ref:i,style:{width:"100%",height:"100%",display:"block",imageRendering:"auto",background:"transparent"}})}(function(){try{if(typeof document<"u"){var i=document.createElement("style");i.appendChild(document.createTextNode(".gizmo-default{width:100px;height:100px;position:absolute;top:0;right:0;z-index:2;cursor:pointer}.custom-gizmo-style{width:360px;height:360px;position:absolute;top:0;right:0;z-index:2;cursor:pointer}.map-gizmo-style,.cad-gizmo-style{width:96px;height:96px;position:absolute;top:0;right:0;z-index:2;cursor:pointer}.example-container{position:relative;width:640px;height:360px;background-color:#3d5361;border-radius:6px;overflow:hidden}body{background-color:#f0f0f0;margin:0;padding:0}.content{display:flex;justify-content:center;align-items:center;flex-direction:column;height:100vh}.example-select{margin-bottom:24px}")),document.head.appendChild(i)}}catch(e){console.error("vite-plugin-css-injected-by-js",e)}})();const hh=(i,e,t,n,s,r)=>{const o=performance.now(),a=()=>{const c=performance.now()-o,u=Math.min(c/s,1);i.position.lerpVectors(t,n,u),e==null||e.update(),r(),u<1&&requestAnimationFrame(a)};requestAnimationFrame(a)},Sr={type:"change"},Ri={type:"start"},io={type:"end"},as=new p.Ray,_r=new p.Plane,uh=Math.cos(70*p.MathUtils.DEG2RAD),Pe=new p.Vector3,Qe=2*Math.PI,Te={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},Ys=1e-6;class ro extends p.Controls{constructor(e,t=null){super(e,t),this.state=Te.NONE,this.target=new p.Vector3,this.cursor=new p.Vector3,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:p.MOUSE.ROTATE,MIDDLE:p.MOUSE.DOLLY,RIGHT:p.MOUSE.PAN},this.touches={ONE:p.TOUCH.ROTATE,TWO:p.TOUCH.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new p.Vector3,this._lastQuaternion=new p.Quaternion,this._lastTargetPosition=new p.Vector3,this._quat=new p.Quaternion().setFromUnitVectors(e.up,new p.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new p.Spherical,this._sphericalDelta=new p.Spherical,this._scale=1,this._panOffset=new p.Vector3,this._rotateStart=new p.Vector2,this._rotateEnd=new p.Vector2,this._rotateDelta=new p.Vector2,this._panStart=new p.Vector2,this._panEnd=new p.Vector2,this._panDelta=new p.Vector2,this._dollyStart=new p.Vector2,this._dollyEnd=new p.Vector2,this._dollyDelta=new p.Vector2,this._dollyDirection=new p.Vector3,this._mouse=new p.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=fh.bind(this),this._onPointerDown=dh.bind(this),this._onPointerUp=ph.bind(this),this._onContextMenu=Sh.bind(this),this._onMouseWheel=yh.bind(this),this._onKeyDown=Eh.bind(this),this._onTouchStart=wh.bind(this),this._onTouchMove=Th.bind(this),this._onMouseDown=mh.bind(this),this._onMouseMove=gh.bind(this),this._interceptControlDown=_h.bind(this),this._interceptControlUp=bh.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(Sr),this.update(),this.state=Te.NONE}update(e=null){const t=this.object.position;Pe.copy(t).sub(this.target),Pe.applyQuaternion(this._quat),this._spherical.setFromVector3(Pe),this.autoRotate&&this.state===Te.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let n=this.minAzimuthAngle,s=this.maxAzimuthAngle;isFinite(n)&&isFinite(s)&&(n<-Math.PI?n+=Qe:n>Math.PI&&(n-=Qe),s<-Math.PI?s+=Qe:s>Math.PI&&(s-=Qe),n<=s?this._spherical.theta=Math.max(n,Math.min(s,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+s)/2?Math.max(n,this._spherical.theta):Math.min(s,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let r=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const o=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),r=o!=this._spherical.radius}if(Pe.setFromSpherical(this._spherical),Pe.applyQuaternion(this._quatInverse),t.copy(this.target).add(Pe),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let o=null;if(this.object.isPerspectiveCamera){const a=Pe.length();o=this._clampDistance(a*this._scale);const c=a-o;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),r=!!c}else if(this.object.isOrthographicCamera){const a=new p.Vector3(this._mouse.x,this._mouse.y,0);a.unproject(this.object);const c=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=c!==this.object.zoom;const u=new p.Vector3(this._mouse.x,this._mouse.y,0);u.unproject(this.object),this.object.position.sub(u).add(a),this.object.updateMatrixWorld(),o=Pe.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;o!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(o).add(this.object.position):(as.origin.copy(this.object.position),as.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(as.direction))<uh?this.object.lookAt(this.target):(_r.setFromNormalAndCoplanarPoint(this.object.up,this.target),as.intersectPlane(_r,this.target))))}else if(this.object.isOrthographicCamera){const o=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),o!==this.object.zoom&&(this.object.updateProjectionMatrix(),r=!0)}return this._scale=1,this._performCursorZoom=!1,r||this._lastPosition.distanceToSquared(this.object.position)>Ys||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Ys||this._lastTargetPosition.distanceToSquared(this.target)>Ys?(this.dispatchEvent(Sr),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?Qe/60*this.autoRotateSpeed*e:Qe/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){Pe.setFromMatrixColumn(t,0),Pe.multiplyScalar(-e),this._panOffset.add(Pe)}_panUp(e,t){this.screenSpacePanning===!0?Pe.setFromMatrixColumn(t,1):(Pe.setFromMatrixColumn(t,0),Pe.crossVectors(this.object.up,Pe)),Pe.multiplyScalar(e),this._panOffset.add(Pe)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;Pe.copy(s).sub(this.target);let r=Pe.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/n.clientHeight,this.object.matrix),this._panUp(2*t*r/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const n=this.domElement.getBoundingClientRect(),s=e-n.left,r=t-n.top,o=n.width,a=n.height;this._mouse.x=s/o*2-1,this._mouse.y=-(r/a)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Qe*this._rotateDelta.x/t.clientHeight),this._rotateUp(Qe*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(Qe*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-Qe*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(Qe*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-Qe*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._rotateStart.set(n,s)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panStart.set(n,s)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,r=Math.sqrt(n*n+s*s);this._dollyStart.set(0,r)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),s=.5*(e.pageX+n.x),r=.5*(e.pageY+n.y);this._rotateEnd.set(s,r)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Qe*this._rotateDelta.x/t.clientHeight),this._rotateUp(Qe*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panEnd.set(n,s)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,r=Math.sqrt(n*n+s*s);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const o=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(o,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new p.Vector2,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(n.deltaY*=10),n}}function dh(i){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(i.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(i)&&(this._addPointer(i),i.pointerType==="touch"?this._onTouchStart(i):this._onMouseDown(i)))}function fh(i){this.enabled!==!1&&(i.pointerType==="touch"?this._onTouchMove(i):this._onMouseMove(i))}function ph(i){switch(this._removePointer(i),this._pointers.length){case 0:this.domElement.releasePointerCapture(i.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(io),this.state=Te.NONE;break;case 1:const e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function mh(i){let e;switch(i.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case p.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(i),this.state=Te.DOLLY;break;case p.MOUSE.ROTATE:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=Te.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=Te.ROTATE}break;case p.MOUSE.PAN:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=Te.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=Te.PAN}break;default:this.state=Te.NONE}this.state!==Te.NONE&&this.dispatchEvent(Ri)}function gh(i){switch(this.state){case Te.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(i);break;case Te.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(i);break;case Te.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(i);break}}function yh(i){this.enabled===!1||this.enableZoom===!1||this.state!==Te.NONE||(i.preventDefault(),this.dispatchEvent(Ri),this._handleMouseWheel(this._customWheelEvent(i)),this.dispatchEvent(io))}function Eh(i){this.enabled!==!1&&this._handleKeyDown(i)}function wh(i){switch(this._trackPointer(i),this._pointers.length){case 1:switch(this.touches.ONE){case p.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(i),this.state=Te.TOUCH_ROTATE;break;case p.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(i),this.state=Te.TOUCH_PAN;break;default:this.state=Te.NONE}break;case 2:switch(this.touches.TWO){case p.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(i),this.state=Te.TOUCH_DOLLY_PAN;break;case p.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(i),this.state=Te.TOUCH_DOLLY_ROTATE;break;default:this.state=Te.NONE}break;default:this.state=Te.NONE}this.state!==Te.NONE&&this.dispatchEvent(Ri)}function Th(i){switch(this._trackPointer(i),this.state){case Te.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(i),this.update();break;case Te.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(i),this.update();break;case Te.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(i),this.update();break;case Te.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(i),this.update();break;default:this.state=Te.NONE}}function Sh(i){this.enabled!==!1&&i.preventDefault()}function _h(i){i.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function bh(i){i.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}class xh extends ro{constructor(e,t){super(e,t),this.screenSpacePanning=!1,this.mouseButtons={LEFT:p.MOUSE.PAN,MIDDLE:p.MOUSE.DOLLY,RIGHT:p.MOUSE.ROTATE},this.touches={ONE:p.TOUCH.PAN,TWO:p.TOUCH.DOLLY_ROTATE}}}const fe={CUBE_SIZE:1.8,EDGE_SECTION_SIZE:.35,FACE_THICKNESS:.35,CANVAS_SIZE:256,FONT_SIZE:"62px",TEXT_COLOR:"#000000",TEXT_ALIGN:"center",TEXT_BASELINE:"middle",FACE_COLOR:"#EFF3F2",EDGE_COLOR:"#EFF3F2",CORNER_COLOR:"#EFF3F2",LINE_COLOR:0};var It=(i=>(i.FRONT="FRONT",i.BACK="BACK",i.RIGHT="RIGHT",i.LEFT="LEFT",i.TOP="TOP",i.BOTTOM="BOTTOM",i))(It||{});new S.Vector3(0,1,0);const Mn="rotation-arrows-name",yi="left-rotation-arrow-name",Es="right-rotation-arrow-name",Ah="gizmo-group-name",Mh=[Es,yi],fs={GIZMO_DISTANCE:8,DEFAULT_UP:new S.Vector3(0,1,0),FORWARD:new S.Vector3(0,0,-1)},qs=i=>fs.FORWARD.clone().applyQuaternion(i),br=(i,e,t=new S.Vector3)=>t.clone().add(i.multiplyScalar(-e));class Rh{constructor(e,t=Mn){this.gizmoScene=e,this.gizmoArrowsName=t}syncGizmoWithMain(e,t){e.quaternion.copy(t.quaternion),e.up.copy(t.up);const n=qs(e.quaternion).normalize();e.position.copy(br(n,fs.GIZMO_DISTANCE)),e.camera.updateMatrixWorld(!0);const s=this.gizmoScene.getObjectByName(this.gizmoArrowsName);s&&s.rotation.copy(e.camera.rotation)}syncMainWithGizmo(e,t,n){const s=n.target.clone(),r=e.position.distanceTo(s),o=e.camera instanceof S.PerspectiveCamera;n instanceof xh&&!o?this.syncMapControls(e,t,s,r):this.syncOrbitControls(e,t,s,r),e.camera.updateMatrix(),e.camera.updateMatrixWorld(!0),n.update()}syncMapControls(e,t,n,s){const r=e.position.y-n.y,o=qs(t.quaternion);o.y=0,o.normalize();const a=n.clone();a.y+=r,a.add(o.multiplyScalar(-s)),e.position.copy(a),e.up.copy(fs.DEFAULT_UP),e.camera.lookAt(n)}syncOrbitControls(e,t,n,s){const r=qs(t.quaternion),o=fs.DEFAULT_UP.clone().applyQuaternion(t.quaternion),a=br(r,s,n);e.position.copy(a),e.up.copy(o),e.camera.lookAt(n)}}const oo=i=>new Rh(i),xr=(i,e,t)=>{oo(t).syncGizmoWithMain({camera:i,position:i.position,quaternion:i.quaternion,up:i.up},{camera:e,position:e.position,quaternion:e.quaternion,up:e.up})},vh=(i,e,t)=>{oo(e.userData.scene).syncMainWithGizmo({camera:i,position:i.position,quaternion:i.quaternion,up:i.up},{camera:e,position:e.position,quaternion:e.quaternion,up:e.up},t)},Ch=()=>{try{const i=document.createElement("canvas");return!!(window.WebGLRenderingContext&&(i.getContext("webgl")||i.getContext("experimental-webgl")))}catch{return!1}},Ih=()=>Ch()?new S.WebGLRenderer({alpha:!0,antialias:!1}):(console.error("WebGL is not supported in this environment."),null),Lh=i=>{const e=new S.AmbientLight(16777215,1);i.add(e);const t=new S.DirectionalLight(16777215,1);t.position.set(5,10,5),i.add(t);const n=new S.DirectionalLight(16777215,1);n.position.set(-5,-10,5),i.add(n);const s=new S.PointLight(16777215,1,100);s.position.set(0,0,5),i.add(s),t.castShadow=!1,n.castShadow=!1,s.castShadow=!1};class Ph{static createTextTexture(e){const t=document.createElement("canvas"),n=t.getContext("2d");t.width=fe.CANVAS_SIZE,t.height=fe.CANVAS_SIZE,n&&(n.clearRect(0,0,t.width,t.height),n.font=`${fe.FONT_SIZE} Arial`,n.fillStyle=fe.TEXT_COLOR,n.textAlign=fe.TEXT_ALIGN,n.textBaseline=fe.TEXT_BASELINE,n.fillText(e,t.width/2,t.height/2));const s=new S.CanvasTexture(t);return s.needsUpdate=!0,s}}class cs{static createWireframe([e,t,n]){const s=new S.BoxGeometry(e,t,n),r=new S.EdgesGeometry(s),o=new S.LineBasicMaterial({color:fe.LINE_COLOR}),a=new S.LineSegments(r,o);return a.name="Wireframe",a}static createEdgeBox(e,t,n){const s=fe.CUBE_SIZE-fe.EDGE_SECTION_SIZE,r={x:fe.EDGE_SECTION_SIZE,y:fe.EDGE_SECTION_SIZE,z:fe.EDGE_SECTION_SIZE};r[t]=s;const o=new S.BoxGeometry(r.x,r.y,r.z),a=new S.MeshStandardMaterial({color:fe.EDGE_COLOR}),c=new S.Mesh(o,a);return c.position.copy(e),c.name=`Edge Box ${n}`,c}static createCornerCube(e,t){const n=new S.BoxGeometry(fe.EDGE_SECTION_SIZE,fe.EDGE_SECTION_SIZE,fe.EDGE_SECTION_SIZE),s=new S.MeshStandardMaterial({color:fe.CORNER_COLOR}),r=new S.Mesh(n,s);return r.position.copy(e),r.name=`Corner Cube ${t}`,r}static createFace(e,t,n){const s=new S.Group,r=new S.BoxGeometry(fe.CUBE_SIZE-fe.EDGE_SECTION_SIZE,fe.CUBE_SIZE-fe.EDGE_SECTION_SIZE,fe.FACE_THICKNESS),o=new S.MeshStandardMaterial({color:fe.FACE_COLOR}),a=new S.Mesh(r,o);a.name=`Face Box ${n}`,s.add(a);const c=new S.PlaneGeometry(fe.CUBE_SIZE-fe.EDGE_SECTION_SIZE,fe.CUBE_SIZE-fe.EDGE_SECTION_SIZE),u=new S.MeshStandardMaterial({map:Ph.createTextTexture(n),transparent:!0,depthWrite:!1}),d=new S.Mesh(c,u);return d.position.set(0,0,fe.FACE_THICKNESS/2+.01),s.add(d),s.position.copy(e),s.rotation.copy(t),s}}const Oh=(i,e)=>{const t=document.createElement("canvas");t.width=64,t.height=64;const n=t.getContext("2d");n.fillStyle="rgba(0, 0, 0, 0)",n.fillRect(0,0,t.width,t.height),n.font="Bold 48px Arial",n.fillStyle=`#${e.toString(16).padStart(6,"0")}`,n.textAlign="center",n.textBaseline="middle",n.fillText(i,t.width/2,t.height/2);const s=new S.CanvasTexture(t),r=new S.SpriteMaterial({map:s}),o=new S.Sprite(r);return o.scale.set(.5,.5,.5),o};class Dh{constructor(e){this.hoveredObject=null,this.originalColor=null,this.config=e}get vectorToCube(){var e;return(e=this.hoveredObject)==null?void 0:e.userData.vectorToCube}getInitialRotation(){switch(this.config.initialFace){case It.BACK:return new S.Euler(0,Math.PI,0);case It.RIGHT:return new S.Euler(0,-Math.PI/2,0);case It.LEFT:return new S.Euler(0,Math.PI/2,0);case It.TOP:return new S.Euler(Math.PI/2,0,0);case It.BOTTOM:return new S.Euler(-Math.PI/2,0,0);case It.FRONT:default:return new S.Euler(0,0,0)}}createWireframe(){const e=fe.CUBE_SIZE+fe.EDGE_SECTION_SIZE,t=cs.createWireframe([e,e,e]);return t.userData.gizmoCube=this,t}createEdgeBox(e,t,n){const s=cs.createEdgeBox(e,t,n);return s.userData.gizmoCube=this,s}createCornerCube(e,t){const n=cs.createCornerCube(e,t);return n.userData.gizmoCube=this,n}createFace(e,t,n){const s=cs.createFace(e,t,n),r=s.getObjectByName(`Face Box ${n}`);return r.userData.gizmoCube=this,s}createEdges(e){const t=fe.CUBE_SIZE/2;[{axis:"x",pos:new S.Vector3(0,t,-t)},{axis:"x",pos:new S.Vector3(0,t,t)},{axis:"x",pos:new S.Vector3(0,-t,-t)},{axis:"x",pos:new S.Vector3(0,-t,t)},{axis:"y",pos:new S.Vector3(t,0,-t)},{axis:"y",pos:new S.Vector3(t,0,t)},{axis:"y",pos:new S.Vector3(-t,0,-t)},{axis:"y",pos:new S.Vector3(-t,0,t)},{axis:"z",pos:new S.Vector3(t,t,0)},{axis:"z",pos:new S.Vector3(t,-t,0)},{axis:"z",pos:new S.Vector3(-t,t,0)},{axis:"z",pos:new S.Vector3(-t,-t,0)}].forEach(({axis:n,pos:s},r)=>{const o=this.createEdgeBox(s,n,r+1);e.add(o)})}createCorners(e){const t=fe.CUBE_SIZE/2;[new S.Vector3(-t,-t,-t),new S.Vector3(-t,-t,t),new S.Vector3(-t,t,-t),new S.Vector3(-t,t,t),new S.Vector3(t,-t,-t),new S.Vector3(t,-t,t),new S.Vector3(t,t,-t),new S.Vector3(t,t,t)].forEach((n,s)=>{const r=this.createCornerCube(n,s+1);e.add(r)})}createFaces(e){const t=fe.CUBE_SIZE/2;[{pos:new S.Vector3(0,0,t),rotation:new S.Euler(0,0,0),label:"FRONT"},{pos:new S.Vector3(0,0,-t),rotation:new S.Euler(0,Math.PI,0),label:"BACK"},{pos:new S.Vector3(t,0,0),rotation:new S.Euler(0,Math.PI/2,0),label:"RIGHT"},{pos:new S.Vector3(-t,0,0),rotation:new S.Euler(0,-Math.PI/2,0),label:"LEFT"},{pos:new S.Vector3(0,t,0),rotation:new S.Euler(-Math.PI/2,0,0),label:"TOP"},{pos:new S.Vector3(0,-t,0),rotation:new S.Euler(Math.PI/2,0,0),label:"BOTTOM"}].forEach(({pos:n,rotation:s,label:r})=>{const o=this.createFace(n,s,r);e.add(o)})}createAxis(e){const{color:t,direction:n,length:s,origin:r,lineWidth:o,label:a}=e,c=new S.Group,u=o/2,d=new S.CylinderGeometry(u,u,s,32),h=new S.MeshBasicMaterial({color:t}),f=new S.Mesh(d,h);if(f.position.copy(r).add(n.clone().multiplyScalar(s/2)),!n.equals(new S.Vector3(0,1,0))){const E=new S.Vector3(0,1,0).cross(n).normalize(),b=Math.acos(new S.Vector3(0,1,0).dot(n));f.setRotationFromAxisAngle(E,b)}c.add(f);const m=Oh(a,t);return m.position.copy(r).add(n.clone().multiplyScalar(s+.1)),c.add(m),c}createCoordinateAxes(){const e=new S.Group,t=fe.CUBE_SIZE,n=fe.EDGE_SECTION_SIZE,s=-1.075,r=a=>{const c=new S.Vector3(1,1,1);return new S.Vector3(a,a,a).add(c.clone().normalize().negate().multiplyScalar(.04))},o=t+1.25*n;return[{color:16711680,direction:new S.Vector3(1,0,0),length:o,origin:r(s),lineWidth:.04,label:"X"},{color:65280,direction:new S.Vector3(0,1,0),length:o,origin:r(s),lineWidth:.04,label:"Y"},{color:255,direction:new S.Vector3(0,0,1),length:o,origin:r(s),lineWidth:.04,label:"Z"}].forEach(a=>{const c=this.createAxis(a);e.add(c)}),e}create(){const e=new S.Group;e.name=Ah;const t=this.createWireframe();e.add(t),this.createEdges(e),this.createCorners(e),this.createFaces(e);const n=this.createCoordinateAxes();e.add(n);const s=this.getInitialRotation();return e.setRotationFromEuler(s),e}highlightObject(e){if(this.hoveredObject!==e)if(this.hoveredObject&&this.originalColor&&this.hoveredObject.material.color.set(this.originalColor),e&&e instanceof S.Mesh){const t=e.material;this.hoveredObject=e,this.originalColor=t.color.clone(),t.color.set(11519973)}else this.hoveredObject=null,this.originalColor=null}handleClick(){if(this.hoveredObject){let e=new S.Vector3;e=this.hoveredObject.getWorldPosition(e).clone();const t=new S.Vector3(0,0,0),n=e.sub(t).normalize();this.hoveredObject.userData.vectorToCube=n}}}class Nh{constructor(e){this.onChangeMainControlsListener=()=>{},this.onChangeGizmoControlsListener=()=>{},this.animationId=0;const{gizmoParams:t,mainParams:n,syncFunctions:s,options:r}=e;this.gizmoDiv=t.gizmoDiv,this.gizmoScene=t.gizmoScene,this.gizmoRenderer=t.gizmoRenderer,this.gizmoCamera=t.gizmoCamera,this.mainCamera=n.mainCamera,this.mainControls=n.mainControls,this.renderGizmo=n.renderGizmo,this.syncFunctions=s,this.options=r,this.gizmoControls=new ro(this.gizmoCamera,this.gizmoRenderer.domElement),this.initializeRenderer(),this.initializeScene(),this.initializeControls(),this.startAnimationLoop()}initializeRenderer(){var e;this.gizmoRenderer.setPixelRatio(window.devicePixelRatio),this.gizmoRenderer.setSize(this.gizmoDiv.clientWidth,this.gizmoDiv.clientHeight);const t=this.gizmoDiv.clientWidth/this.gizmoDiv.clientHeight;this.gizmoCamera.aspect=t,this.gizmoCamera.updateProjectionMatrix(),(e=this.options)!=null&&e.up&&this.gizmoCamera.up.copy(this.options.up),this.gizmoDiv.appendChild(this.gizmoRenderer.domElement)}initializeScene(){var e;const t=new Dh({initialFace:((e=this.options)==null?void 0:e.initialFace)??It.FRONT}).create();this.gizmoScene.add(t),Lh(this.gizmoScene)}initializeControls(){this.onChangeMainControlsListener=()=>this.syncFunctions.syncGizmoCameraWithMain(this.gizmoCamera,this.mainCamera,this.gizmoScene),this.mainControls.addEventListener("change",this.onChangeMainControlsListener),this.gizmoControls.enableZoom=!1,this.gizmoControls.enablePan=!1,this.gizmoControls.rotateSpeed=.5,this.gizmoControls.update(),this.onChangeGizmoControlsListener=()=>{const e=this.gizmoScene.getObjectByName(Mn);e==null||e.rotation.copy(this.gizmoCamera.rotation),this.syncFunctions.syncMainCameraWithGizmo(this.mainCamera,this.gizmoCamera,this.mainControls),this.renderGizmo()},this.gizmoControls.addEventListener("change",this.onChangeGizmoControlsListener)}startAnimationLoop(){const e=()=>{this.gizmoRenderer.render(this.gizmoScene,this.gizmoCamera)},t=()=>{this.animationId=requestAnimationFrame(t),e()};t()}dispose(){this.mainControls.removeEventListener("change",this.onChangeMainControlsListener),this.gizmoControls.removeEventListener("change",this.onChangeGizmoControlsListener),this.gizmoScene.clear(),cancelAnimationFrame(this.animationId)}}const kh=(i,e)=>{let t;return function(...n){t||(i.apply(this,n),t=!0,setTimeout(()=>t=!1,e))}};function Ar(i,e,t){if(!e)return;const n=e.domElement.getBoundingClientRect();t.x=(i.clientX-n.left)/n.width*2-1,t.y=-((i.clientY-n.top)/n.height)*2+1}const ao=(i,e,t,n)=>(n.setFromCamera(i,e),n.intersectObjects(t.children,!0)),co=i=>{var e;const t=["Wireframe",""];return((e=i.find(n=>!t.includes(n.object.name)))==null?void 0:e.object)||null};function Fh(i,e,t,n){if(!e||!t)return null;const s=ao(i,e,t,n);return co(s)}function Bh(i,e){const t=i==null?void 0:i.userData.gizmoCube;if(i&&t){t.handleClick();const n=t.vectorToCube;n&&e(n)}}const zh={radius:2.1,color:12369854,tubeRadius:.1,tubeSegments:8,numPoints:64,tubeOffset:1.5},Uh={size:.2,depth:.1,heightRatio:1.4,segments:1};class Hh{constructor(e={}){this.config={...zh,...e},this.material=new S.MeshBasicMaterial({color:this.config.color})}create(){const e=new S.Group,t=this.createQuarterCircleCurves();return e.add(...this.createTubes(t),...this.createArrowHeads(t)),e.name=Mn,e}createQuarterCircleCurves(){const e=this.generateQuarterCirclePoints(),t=Math.floor(e.length/2);return[new S.CatmullRomCurve3(e.slice(0,t-this.config.tubeOffset)),new S.CatmullRomCurve3(e.slice(t+this.config.tubeOffset))]}generateQuarterCirclePoints(){const e=Math.PI/2,t=e/2,n=e/4;return Array.from({length:this.config.numPoints+1},(s,r)=>{const o=r/this.config.numPoints,a=n+t*o,c=this.config.radius*Math.sin(a),u=this.config.radius*Math.cos(a);return new S.Vector3(c,u,0)})}createTubes([e,t]){const n=(s,r)=>{const o=new S.TubeGeometry(s,this.config.numPoints,this.config.tubeRadius,this.config.tubeSegments,!1),a=new S.Mesh(o,this.material);return a.name=r,a};return[n(e,yi),n(t,Es)]}createArrowHeads([e,t]){const{size:n,depth:s,heightRatio:r,segments:o}=Uh,a=this.createArrowShape(n,r),c=new S.ExtrudeGeometry(a,{steps:o,depth:s,bevelEnabled:!1}).center(),u=(d,h,f)=>{const m=new S.Mesh(c,this.material);return m.position.copy(d),m.rotation.z=h,m.name=f,m};return[u(e.getPoint(0),this.calculateArrowRotation(e.getTangent(0))+Math.PI/2,yi),u(t.getPoint(1),this.calculateArrowRotation(t.getTangent(1))-Math.PI/2,Es)]}createArrowShape(e,t){return new S.Shape().moveTo(0,0).lineTo(e,-e*t).lineTo(-e,-e*t).lineTo(0,0)}calculateArrowRotation(e){return Math.atan2(e.y,e.x)}}const Vh=i=>{const e=i.rotation,t=.01,n=Math.PI,s=(Math.abs(e.x)%(2*n)+2*n)%(2*n),r=(Math.abs(e.y)%(2*n)+2*n)%(2*n),o=Math.abs(s-n/2)<t||Math.abs(s-3*n/2)<t||Math.abs(r-n/2)<t||Math.abs(r-3*n/2)<t,a=(Math.abs(s)<t||Math.abs(s-n)<t)&&(Math.abs(r)<t||Math.abs(r-n)<t);return!(o||a)},jh=25,Gh=200;function Wh({gizmoRenderer:i,gizmoScene:e,gizmoCamera:t,alignCameraWithVector:n,gizmoControlRef:s}){const r=re.useRef(null),o=re.useRef(null),a=re.useRef(new S.Raycaster).current,c=re.useRef(new S.Vector2).current,u=re.useCallback(()=>{const b=e.getObjectByName(Mn),T=Vh(t);if(b&&T){e.remove(b);return}if(b||T)return;const A=new Hh().create();A.rotation.copy(t.rotation),e.add(A)},[e,t]),d=re.useCallback(()=>{const b=e.getObjectByName(Mn);b&&e.remove(b)},[e]),h=re.useCallback(kh(b=>{if(!s.current||!i)return;Ar(b,i,c);const T=ao(c,t,e,a),A=co(T);A!=null&&A.userData.gizmoCube?A.userData.gizmoCube.highlightObject(A):e.traverse(w=>{w.userData.gizmoCube&&w.userData.gizmoCube.highlightObject(null)}),T.length>0?u():d()},1e3/jh),[s,i,t,e,a,c,u,d]),f=re.useCallback(b=>{r.current=Date.now(),o.current={x:b.clientX,y:b.clientY}},[]),m=re.useCallback(b=>{var T;const A=b.name===Es?1:-1,w=90*Math.PI/180,x=new S.Vector3(0,0,0),_=A*w,M=new S.Matrix4;M.makeRotationZ(_),t.up.applyMatrix4(M),t.lookAt(x),(T=s.current)==null||T.gizmoControls.update()},[t,s]),E=re.useCallback(b=>{if((r.current?Date.now()-r.current:0)<Gh){Ar(b,i,c);const T=Fh(c,t,e,a);T!=null&&T.name&&Mh.includes(T.name)?m(T):Bh(T,n)}r.current=null,o.current=null},[m,n,i,t,e,a,c]);return{onMouseDown:f,onMouseMove:h,onMouseUp:E,onMouseLeave:d}}const Zh=({camera:i,controls:e,className:t,render:n,options:s})=>{const r=re.useRef(null),o=re.useRef(new S.Scene).current,[a]=re.useState(()=>Ih()),c=30,u=1,d=.1,h=10,f=new S.PerspectiveCamera(c,u,d,h),m=re.useRef(f).current,E=re.useRef(null),b=re.useCallback(()=>{a&&(n(),a.render(o,m))},[n,a,o,m]),T=re.useCallback(M=>{if(!i||!e)return;const P=i.position.length(),I=M.clone().multiplyScalar(P),C=400,D=new S.Matrix4;D.lookAt(I,new S.Vector3(0,0,0),new S.Vector3(0,1,0));const L=new S.Quaternion;L.setFromRotationMatrix(D),i.quaternion.copy(L),hh(i,e,i.position.clone(),I,C,b),i.up.set(0,1,0),i.lookAt(new S.Vector3(0,0,0)),e.target.set(0,0,0),e.update()},[i,e,b,o]),{onMouseDown:A,onMouseMove:w,onMouseUp:x,onMouseLeave:_}=Wh({gizmoRenderer:a,gizmoScene:o,gizmoCamera:m,alignCameraWithVector:T,gizmoControlRef:E});return re.useEffect(()=>{const M=r.current;if(!M||!i||!e||!a)return;E.current&&E.current.dispose();const P={gizmoDiv:M,gizmoScene:o,gizmoRenderer:a,gizmoCamera:m},I={mainCamera:i,mainControls:e,renderGizmo:b},C={syncGizmoCameraWithMain:xr,syncMainCameraWithGizmo:vh};return E.current=new Nh({gizmoParams:P,mainParams:I,syncFunctions:C,options:s}),M.addEventListener("mousedown",A),M.addEventListener("mousemove",w),M.addEventListener("mouseup",x),M.addEventListener("mouseleave",_),()=>{E.current&&(E.current.dispose(),E.current=null),M.removeEventListener("mousedown",A),M.removeEventListener("mousemove",w),M.removeEventListener("mouseup",x),M.removeEventListener("mouseleave",_)}},[i,e,b,w,A,x]),re.useEffect(()=>{i&&(xr(m,i,o),b())},[i,b]),me.jsx("div",{className:t?`${t}`:"gizmo-default",ref:r})},ls=10,Kh=i=>({top:i.startsWith("top")?ls:"auto",bottom:i.startsWith("bottom")?ls:"auto",left:i.endsWith("left")?ls:"auto",right:i.endsWith("right")?ls:"auto"}),Xh=({camera:i,controls:e,render:t,placement:n="top-right",size:s=128})=>{if(!i||!e)return null;const r=e;return me.jsx("div",{className:"viewer-gizmo-container",style:{position:"absolute",width:s,height:s,zIndex:1e3,...Kh(n)},children:me.jsx(Zh,{camera:i,controls:r,render:t})})};class Yh extends re.Component{constructor(e){super(e),this.reset=()=>{this.setState({hasError:!1,error:null})},this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){console.error("ViewerErrorBoundary caught error:",e,t)}render(){var e;return this.state.hasError?this.props.fallback?this.props.fallback:me.jsx("div",{style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"#f0f0f0",color:"#333",fontFamily:"sans-serif",padding:"20px",textAlign:"center"},children:me.jsxs("div",{children:[me.jsx("h3",{children:"Error Loading 3D Viewer"}),me.jsx("p",{children:((e=this.state.error)==null?void 0:e.message)||"An unexpected error occurred"}),me.jsx("button",{type:"button",onClick:this.reset,children:"Try again"})]})}):this.props.children}}function qh({status:i,label:e,color:t,backdrop:n}){const s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;return me.jsxs("div",{"data-testid":"viewer-loading-overlay",role:"status","aria-live":"polite","aria-busy":i==="loading",style:{position:"absolute",inset:0,zIndex:20,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,background:n,color:t,pointerEvents:"none",userSelect:"none",fontFamily:"system-ui, -apple-system, Segoe UI, Roboto, sans-serif",fontSize:14},children:[i==="loading"?me.jsxs("svg",{width:"44",height:"44",viewBox:"0 0 44 44","aria-hidden":"true",children:[me.jsx("circle",{cx:"22",cy:"22",r:"18",fill:"none",stroke:t,strokeOpacity:"0.25",strokeWidth:"4"}),me.jsx("path",{d:"M22 4 a18 18 0 0 1 18 18",fill:"none",stroke:t,strokeWidth:"4",strokeLinecap:"round",children:!s&&me.jsx("animateTransform",{attributeName:"transform",type:"rotate",from:"0 22 22",to:"360 22 22",dur:"0.9s",repeatCount:"indefinite"})})]}):me.jsxs("svg",{width:"40",height:"40",viewBox:"0 0 24 24",fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[me.jsx("path",{d:"M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),me.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),me.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),e&&me.jsx("div",{style:{opacity:.92,maxWidth:"80%",textAlign:"center"},children:e})]})}const $h='-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',Qh={background:"rgba(255,255,255,0.78)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)",border:"1px solid rgba(0,0,0,0.06)",boxShadow:"0 8px 30px rgba(0,0,0,0.10)"},Jh=Object.keys(Mi);function eu({active:i,onSelect:e}){return me.jsx("div",{"data-testid":"viewer-preset-picker",role:"group","aria-label":"Visual preset",style:{position:"absolute",bottom:16,left:"50%",transform:"translateX(-50%)",zIndex:10,display:"flex",gap:2,padding:4,borderRadius:999,maxWidth:"calc(100% - 16px)",overflowX:"auto",...Qh},children:Jh.map(t=>me.jsx("button",{type:"button","aria-pressed":t===i,onClick:()=>e(t),style:{padding:"6px 14px",borderRadius:999,border:t===i?"1px solid #111318":"1px solid transparent",background:t===i?"#111318":"transparent",color:t===i?"#fff":"#3f3f4a",fontFamily:$h,fontSize:13,fontWeight:500,lineHeight:1,whiteSpace:"nowrap",flexShrink:0,cursor:"pointer",textTransform:"capitalize",transition:"background 120ms ease, color 120ms ease"},children:t},t))})}const wn={enabled:!0,label:"Loading…",color:"#ffffff",backdrop:"rgba(15,16,20,0.6)"};function tu(i){return i===void 0||i===!0?wn:i===!1?{...wn,enabled:!1}:{enabled:i.enabled??!0,label:i.label??wn.label,errorLabel:i.errorLabel,color:i.color??wn.color,backdrop:i.backdrop??wn.backdrop}}const hs=()=>new K("Viewer is not ready yet",Y.COMPONENT_NOT_MOUNTED),lo=re.forwardRef(({object:i,options:e={},preset:t,pathTraced:n,turntable:s,animations:r,children:o},a)=>{var N,V;const c=re.useRef(null),u=e.preset??t,{activePreset:d,pickerEnabled:h,selectPreset:f}=sh(u,e.ui),m=ih(e,d,n,s,r),{viewer:E,isInitialized:b,initError:T}=nh(c,m),A=rh(E,b,i),w=oh(E);ah(E,T,e);const x=E?vn(E.getCamera()):null,_=E?xi(E.getControls()):null,M=E?Zr(E.getRenderer()):null,P=re.useCallback(()=>{E==null||E.requestRender()},[E]),I=((N=e.helpers)==null?void 0:N.gizmo)!==void 0&&e.helpers.gizmo!==!1,C=typeof((V=e.helpers)==null?void 0:V.gizmo)=="object"?e.helpers.gizmo:{},D=re.useMemo(()=>tu(e.loadingIndicator),[e.loadingIndicator]),L=A.status==="error"||!!T,k=D.enabled&&(A.status==="loading"||L);return re.useImperativeHandle(a,()=>({scene:E?di(E.getScene()):null,camera:x,renderer:M,controls:_,events:w,loadModel:async G=>{if(!E)throw hs();const $=typeof G=="string"?G:new Oe(G),ie=await E.loadModel($);if(!ie.ok)throw ie.error},captureStill:async G=>{if(!E)throw hs();const $=await E.captureStill(G);if(!$.ok)throw $.error;return $.value},captureVideo:async G=>{if(!E)throw hs();const $=await E.captureVideo(G);if(!$.ok)throw $.error;return $.value},getAnimationNames:()=>(E==null?void 0:E.getAnimationNames())??[],playAnimations:G=>{if(!E)throw hs();const $=E.playAnimations(G);if(!$.ok)throw $.error},pauseAnimations:()=>{E==null||E.pauseAnimations()},dispose:()=>{E==null||E.dispose()}}),[E,x,M,_,w]),me.jsx(Yh,{children:me.jsx(ch,{viewer:E,canvasRef:c,children:me.jsxs("div",{style:{position:"relative",width:"100%",height:"100%"},children:[me.jsx(lh,{}),I&&b&&x&&_&&me.jsx(Xh,{camera:x,controls:_,render:P,placement:C.placement,size:C.size}),k&&me.jsx(qh,{status:L?"error":"loading",label:L?D.errorLabel??(T==null?void 0:T.message)??A.error??"Failed to load model":D.label,color:D.color,backdrop:D.backdrop}),h&&me.jsx(eu,{active:d??"studio",onSelect:f}),o]})})})});lo.displayName="SimpleViewer";const ho=re.forwardRef((i,e)=>me.jsx(lo,{ref:e,...i}));ho.displayName="SimpleViewer";const nu=()=>me.jsx("span",{"aria-hidden":"true",style:{display:"block",width:14,height:14,borderRadius:"50%",background:"rgba(17,19,24,0.9)",border:"2px solid rgba(255,255,255,0.95)",boxShadow:"0 2px 8px rgba(0,0,0,0.35)"}});function su({position:i,occlude:e=!1,children:t}){const{viewer:n}=so(),s=re.useRef(null),[r,o,a]=i;re.useEffect(()=>{if(!n)return;const u=s.current;if(!u)return;const d=n.createAnchorProjector();if(!d)return;const h={x:r,y:o,z:a},f=()=>{const T=d.project(h,e);if(T){if(!T.visible){u.style.visibility="hidden";return}u.style.visibility="visible",u.style.left=`${T.left}px`,u.style.top=`${T.top}px`}},m=()=>{d.invalidate(),f()};f();const E=n.getEvents(),b=[E.on("render:complete",f),E.on("controls:change",f),E.on("model:loaded",m)];return window.addEventListener("resize",m),()=>{b.forEach(T=>T()),window.removeEventListener("resize",m)}},[n,r,o,a,e]);const c=t!=null&&t!==!1;return me.jsx("div",{ref:s,"data-testid":"viewer-hotspot",style:{position:"absolute",left:0,top:0,transform:"translate(-50%, -50%)",visibility:"hidden",zIndex:5,pointerEvents:c?"auto":"none"},children:c?t:me.jsx(nu,{})})}exports.BOUNDING_DATA_INDEX=ha;exports.BYTES_PER_NODE=He;exports.CONTACT_SHADOW_HELPER_FLAG=Ai;exports.COUNT=Xe;exports.ControlType=An;exports.DEFAULT_PATH_TRACING_SAMPLES=$s;exports.ErrorCode=Y;exports.Hotspot=su;exports.IS_LEAF=Ce;exports.LEAFNODE_MASK_32=la;exports.MeshBVH=bn;exports.OFFSET=Ve;exports.Result=F;exports.SAH=Pr;exports.SPLIT_AXIS=Ts;exports.SimpleViewerWrapper=ho;exports.ThreeViewerError=K;exports.TypedEventEmitter=ws;exports.VIEWER_PRESETS=Mi;exports.defaultOptions=ys;exports.getIndexArray=kr;exports.getVertexCount=Ss;exports.hasInternalRenderer=Cr;exports.resolvePreset=eo;