softbox 4.4.1 → 4.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,11 @@
1
+ "use strict";var Go=Object.create;var Bi=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&&Bi(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?Bi(t,"default",{value:i,enumerable:!0}):t,i));const me=require("react/jsx-runtime"),se=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 E=qo(p);class Z 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,Z)}static fromError(e,t,n){if(e instanceof Z)return e;const s=e instanceof Error?e.message:String(e),o={...n,originalError:e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:e};return new Z(s,t,o)}}var X=(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))(X||{});const k={ok(i){return{ok:!0,value:i}},err(i){return{ok:!1,error:i}},wrap(i){try{return k.ok(i())}catch(e){return k.err(e instanceof Z?e:new Z(String(e),X.UNKNOWN,{originalError:e}))}}};class Es{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(o){console.error(`Error in event listener for ${String(e)}:`,o)}})}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 xr(i){const e=i??"meters";if(!Object.prototype.hasOwnProperty.call(vs,e))throw new Z(`Unknown units '${String(e)}'. Valid values: ${Object.keys(vs).join(", ")}`,X.INVALID_PARAMETER);return vs[e]}const zi="#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 o=(a=n.environment)==null?void 0:a.url,r=(((c=n.helpers)==null?void 0:c.studioEnvironment)??!1)&&(((u=n.helpers)==null?void 0:u.darkStudioMode)??!1);if(n.backgroundColor&&!o&&!r){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,o,r){var d,h,f,m,w,x;const a=await t.initialize({renderer:s,autoDispose:!0});if(r())return;a.ok||console.warn("Failed to initialize environment service:",a.error);const c={backgroundBlurriness:(d=o.environment)==null?void 0:d.backgroundBlurriness,backgroundIntensity:(h=o.environment)==null?void 0:h.backgroundIntensity,environmentIntensity:(f=o.environment)==null?void 0:f.environmentIntensity},u=(m=o.environment)==null?void 0:m.url;if(u){const _=await t.loadEnvironmentMap(u);if(r())return;_.ok?t.applyToScene(e,_.value,c):console.warn("Failed to load environment map:",_.error)}else if((w=o.helpers)!=null&&w.studioEnvironment){const _=t.createStudioEnvironment();if(_.ok){if(t.applyToScene(e,_.value,{...c,setBackground:!1}),(x=o.helpers)!=null&&x.darkStudioMode&&n){const A=n.createGradientBackground(e,{topColor:zi,bottomColor:zi});A.ok||console.warn("Failed to set dark studio background:",A.error)}}else console.warn("Failed to create studio environment:",_.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 Vn(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function ps(i,e){if(!Vn(i)||!Vn(e))return e===void 0?i:e;const t=e,n={...i};for(const s of Object.keys(t)){const o=t[s];if(o===void 0)continue;const r=n[s];n[s]=Vn(r)&&Vn(o)?ps(r,o):o}return n}class Ar{static serialize(e,t,n,s){const o=t.position,r=n.target||{x:0,y:0,z:0};return{modelUrl:e,cameraPosition:{x:o.x,y:o.y,z:o.z},cameraTarget:{x:r.x,y:r.y,z:r.z},controlsTarget:{x:r.x,y:r.y,z:r.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 Mr(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 o=this.renderer.getDomElement(),r=Mr(o);if(!r){console.warn("[ScreenshotManager] Screenshot capture produced no image, keeping live scene");return}const a=document.createElement("img");a.src=r,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=o.parentElement;if(c){this.serializedSceneState=Ar.serialize(n,e,t,o),o.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 Z("A units conversion is configured but no scene setup service is available to apply it",X.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 o=this.scene.add(s);if(!o.ok)throw o.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 r=performance.now()-n;return t.emit("model:loaded",{model:s,loadTime:r}),k.ok(s)}catch(s){const o=s instanceof Z?s:new Z("Failed to load model",X.MODEL_LOAD_FAILED,{originalError:s,source:e});return t.emit("model:error",{error:o,url:typeof e=="string"?e:void 0}),k.err(o)}}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 Rr(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:o,schedule:r}=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})=>{o.releaseContinuous("path-tracing"),t().staticScene||o.setAlwaysRender(!1),r(()=>{o.hasContinuousDemand()||o.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(),o=s>=this.getMaxSamples()&&s>0;return!n.isEnabled()&&!o?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:o,schedule:r,replaceWithScreenshot:a,renderer:c}=this.deps;this.completeHandled=!0,s.releaseContinuous("path-tracing"),o().staticScene||s.setAlwaysRender(!1),n.emit("pathtracing:complete",{samples:e,totalTime:t-(this.startTime||0)});const u=()=>{s.hasContinuousDemand()||s.stop()};if(o().replaceWithScreenshotOnComplete){r(()=>{a(),r(u,200)},100);return}if(s.requestRender(),r(u,100),Rr(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 vr(){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()?k.err(new Z("Cannot capture a still from a disposed viewer",X.INVALID_STATE)):(await this.deps.awaitModelLoads().catch(()=>{}),this.deps.isDisposed()?k.err(new Z("Viewer was disposed while a model load finished",X.INVALID_STATE)):this.deps.isScreenshotActive()?k.err(new Z("Cannot capture a still while a screenshot is replacing the canvas",X.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 k.err(new Z("Cannot capture video from a disposed viewer",X.INVALID_STATE));if(await this.deps.awaitModelLoads().catch(()=>{}),this.deps.isDisposed())return k.err(new Z("Viewer was disposed while a model load finished",X.INVALID_STATE));if(this.deps.isScreenshotActive())return k.err(new Z("Cannot capture video while a screenshot is replacing the canvas",X.INVALID_STATE));const t=e.duration??3;if(!(t>0))return k.err(new Z("Video duration must be a positive number of seconds",X.INVALID_PARAMETER));const n=this.deps.renderer.getDomElement();if(typeof MediaRecorder>"u"||typeof n.captureStream!="function")return k.err(new Z("Video capture needs MediaRecorder and canvas.captureStream support",X.UNSUPPORTED_FORMAT));const s=n.captureStream(e.fps??30);let o;try{o=new MediaRecorder(s,{mimeType:ra(e.mimeType),videoBitsPerSecond:e.videoBitsPerSecond})}catch(h){return s.getTracks().forEach(f=>f.stop()),k.err(new Z("Failed to start the video recorder",X.OPERATION_FAILED,{originalError:h}))}const r=s.getVideoTracks()[0],a=(d=r==null?void 0:r.requestFrame)==null?void 0:d.bind(r),c=a?this.deps.events.on("render:complete",()=>a()):()=>{},u=`video-capture:${vr()}`;return this.deps.renderLoopManager.requireContinuous(u),this.deps.reviveRenderLoop(),this.deps.renderLoopManager.requestRender(),new Promise(h=>{const f=[];let m=null,w=!1;const x=A=>{w||(w=!0,this.pendingSettlers.delete(_),c(),m!==null&&clearTimeout(m),this.deps.renderLoopManager.releaseContinuous(u),s.getTracks().forEach(T=>T.stop()),h(A))},_=()=>{x(k.err(new Z("Viewer was disposed during video capture",X.INVALID_STATE)));try{o.stop()}catch{}};this.pendingSettlers.add(_),o.ondataavailable=A=>{A.data.size>0&&f.push(A.data)},o.onstop=()=>{x(k.ok(new Blob(f,{type:o.mimeType||"video/webm"})))},o.onerror=()=>{x(k.err(new Z("Video recording failed",X.OPERATION_FAILED)))},o.start(250),m=setTimeout(()=>{o.state!=="inactive"&&o.stop()},t*1e3)})}async capturePathTracedStill(e){if(e.width!==void 0||e.height!==void 0)return k.err(new Z("Path-traced stills are captured at the canvas resolution; omit width/height",X.INVALID_PARAMETER));if(this.deps.isAutoRotating())return k.err(new Z("Cannot capture a path-traced still while the turntable is spinning — pause autoRotate first",X.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 k.err(new Z("Viewer was disposed while waiting for the path tracer",X.INVALID_STATE));if(n==="error")return k.err(new Z("Model failed while waiting for the path tracer",X.RENDER_FAILED));if(n==="turntable")return k.err(new Z("Cannot capture a path-traced still while the turntable is spinning — pause autoRotate first",X.INVALID_STATE))}return this.readCanvasPng()}waitForPathTracingOutcome(){return new Promise(e=>{let t=()=>{},n=()=>{},s=()=>{},o=()=>{};const r=a=>{this.pendingSettlers.delete(r),this.pathTracedWaitSettlers.delete(r),t(),n(),s(),o(),e(a)};this.pendingSettlers.add(r),this.pathTracedWaitSettlers.add(r),t=this.deps.events.once("pathtracing:complete",()=>r("complete")),n=this.deps.events.once("model:error",()=>r("error")),s=this.deps.pathTracing.onSelfPause(()=>r("complete")),o=this.deps.events.on("controls:change",()=>{this.deps.isAutoRotating()&&r("turntable")})})}captureRasterStill(e){const{renderer:t,scene:n,camera:s,renderLoopManager:o}=this.deps,r=t.getDomElement(),a=t.getPixelRatio(),c=r.clientWidth>0&&r.clientHeight>0,u=c?r.clientWidth:Math.round(r.width/a),d=c?r.clientHeight:Math.round(r.height/a);if(u<=0||d<=0)return k.err(new Z("Cannot capture: the canvas has no size",X.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)),w=t.capabilities.maxTextureSize;if(!Number.isFinite(f)||!Number.isFinite(m)||f<=0||m<=0||f>w||m>w)return k.err(new Z(`Requested still size ${f}x${m} is outside 1..${w}`,X.INVALID_PARAMETER));t.setPixelRatio(1),t.setSize(f,m),Qs(s,f/m);const x=t.render(n,s),_=x.ok?this.readCanvasPng():k.err(x.error);return t.setSize(u,d),t.setPixelRatio(a),Qs(s,h),t.render(n,s),o.requestRender(),_}readCanvasPng(){const e=Mr(this.deps.renderer.getDomElement());return e?k.ok(e):k.err(new Z("Canvas produced an empty image",X.RENDER_FAILED))}}class aa{constructor(e){var o;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=xr(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:(o=this.options.camera)==null?void 0:o.autoFitToObject,unitsScaleToMeters:t}),this.resourceManager=new sa({scene:this.scene,pathTracingService:e.pathTracingService,environmentService:this.environmentService}),this.sceneConfigurator=new Qo,this.events=new Es;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:(r,a)=>this.schedule(r,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()),k.ok(void 0)):n}catch(n){const s=new Z("Failed to initialize viewer",X.INITIALIZATION_FAILED,{originalError:n});return this.stateManager.setError(s),this.events.emit("error",{error:s}),k.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 k.err(new Z("Cannot load model after dispose",X.INVALID_STATE));if(!this.stateManager.canLoad())return k.err(new Z("Cannot load model in current state",X.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(),k.err(new Z("Viewer was disposed while the model was loading",X.INVALID_STATE))):t.ok?(this.stateManager.setLoaded(t.value),this.attachAnimations(t.value),this.renderLoopManager.requestRender(),this.pathTracing.resetAccumulation(!0),k.ok(void 0)):(this.stateManager.setError(t.error),t)}catch(t){const n=t instanceof Z?t:new Z("Failed to load model",X.MODEL_LOAD_FAILED,{originalError:t,source:e});return this.stateManager.setError(n),k.err(n)}}startRenderLoop(){this.renderLoopManager.start(e=>{var r;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()),(r=this.animationService)!=null&&r.isPlaying()&&this.animationService.update(e/1e3);const o=this.pathTracing.beforeFrame();this.renderFrame().catch(a=>{console.error("[ViewerCore] Render frame error:",a)}),this.pathTracing.detectCompletion(o,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,w,x,_,A,T,S;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 o=(m=e.renderer)==null?void 0:m.toneMappingExposure;o!==void 0&&(this.renderer.setToneMappingExposure(o),s=!0);const r=(w=e.environment)==null?void 0:w.environmentIntensity;r!==void 0&&(this.scene.setEnvironmentIntensity(r),s=!0);const a=(x=e.controls)==null?void 0:x.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=(_=e.controls)==null?void 0:_.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=(T=e.animations)==null?void 0:T.speed;d!==void 0&&((S=this.animationService)==null||S.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?k.err(new Z(`Cannot play animation clip '${e}': the viewer was assembled without an animation service`,X.INVALID_STATE)):k.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()),k.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 Ar.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 Ot{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 Ot(e)}static create(e=0,t=0,n=0){return new Ot(new E.Vector3(e,t,n))}}const Cr=0,ca=1,Ir=2,Ui=2,Cs=1.25,Vi=1,Ve=32,De=Ve/4,yi=65535,la=yi<<16,us=Math.pow(2,-24),wi=Symbol("SKIP_GENERATION"),Lr={strategy:Cr,maxDepth:40,maxLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[wi]:!1};function Ae(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 Hi(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 ji(i,e){e.set(i)}function Gi(i,e,t){let n,s;for(let o=0;o<3;o++){const r=o+3;n=i[o],s=e[o],t[o]=n<s?n:s,n=i[r],s=e[r],t[r]=n>s?n:s}}function Hn(i,e,t){for(let n=0;n<3;n++){const s=e[i+2*n],o=e[i+2*n+1],r=s-o,a=s+o;r<t[n]&&(t[n]=r),a>t[n+3]&&(t[n+3]=a)}}function un(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 Ie(i,e){return e[i+15]===yi}function He(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 o=1/0,r=1/0,a=1/0,c=-1/0,u=-1/0,d=-1/0,h=1/0,f=1/0,m=1/0,w=-1/0,x=-1/0,_=-1/0;const A=i.offset||0;for(let T=(e-A)*6,S=(e+t-A)*6;T<S;T+=6){const b=i[T+0],M=i[T+1],P=b-M,L=b+M;P<o&&(o=P),L>c&&(c=L),b<h&&(h=b),b>w&&(w=b);const C=i[T+2],D=i[T+3],I=C-D,F=C+D;I<r&&(r=I),F>u&&(u=F),C<f&&(f=C),C>x&&(x=C);const N=i[T+4],H=i[T+5],G=N-H,$=N+H;G<a&&(a=G),$>d&&(d=$),N<m&&(m=N),N>_&&(_=N)}n[0]=o,n[1]=r,n[2]=a,n[3]=c,n[4]=u,n[5]=d,s[0]=h,s[1]=f,s[2]=m,s[3]=w,s[4]=x,s[5]=_}const St=32,ua=(i,e)=>i.candidate-e.candidate,Rt=new Array(St).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,o){let r=-1,a=0;if(o===Cr)r=Hi(e),r!==-1&&(a=(e[r]+e[r+3])/2);else if(o===ca)r=Hi(i),r!==-1&&(a=fa(t,n,s,r));else if(o===Ir){const c=un(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 w=e[m],A=(e[m+3]-w)/St;if(s<St/4){const T=[...Rt];T.length=s;let S=0;for(let M=h;M<f;M+=6,S++){const P=T[S];P.candidate=t[M+2*m],P.count=0;const{bounds:L,leftCacheBounds:C,rightCacheBounds:D}=P;for(let I=0;I<3;I++)D[I]=1/0,D[I+3]=-1/0,C[I]=1/0,C[I+3]=-1/0,L[I]=1/0,L[I+3]=-1/0;Hn(M,t,L)}T.sort(ua);let b=s;for(let M=0;M<b;M++){const P=T[M];for(;M+1<b&&T[M+1].candidate===P.candidate;)T.splice(M+1,1),b--}for(let M=h;M<f;M+=6){const P=t[M+2*m];for(let L=0;L<b;L++){const C=T[L];P>=C.candidate?Hn(M,t,C.rightCacheBounds):(Hn(M,t,C.leftCacheBounds),C.count++)}}for(let M=0;M<b;M++){const P=T[M],L=P.count,C=s-P.count,D=P.leftCacheBounds,I=P.rightCacheBounds;let F=0;L!==0&&(F=un(D)/c);let N=0;C!==0&&(N=un(I)/c);const H=Vi+Cs*(F*L+N*C);H<u&&(r=m,u=H,a=P.candidate)}}else{for(let b=0;b<St;b++){const M=Rt[b];M.count=0,M.candidate=w+A+b*A;const P=M.bounds;for(let L=0;L<3;L++)P[L]=1/0,P[L+3]=-1/0}for(let b=h;b<f;b+=6){let L=~~((t[b+2*m]-w)/A);L>=St&&(L=St-1);const C=Rt[L];C.count++,Hn(b,t,C.bounds)}const T=Rt[St-1];ji(T.bounds,T.rightCacheBounds);for(let b=St-2;b>=0;b--){const M=Rt[b],P=Rt[b+1];Gi(M.bounds,P.rightCacheBounds,M.rightCacheBounds)}let S=0;for(let b=0;b<St-1;b++){const M=Rt[b],P=M.count,L=M.bounds,D=Rt[b+1].rightCacheBounds;P!==0&&(S===0?ji(L,jn):Gi(L,jn,jn)),S+=P;let I=0,F=0;S!==0&&(I=un(jn)/c);const N=s-S;N!==0&&(F=un(D)/c);const H=Vi+Cs*(I*S+F*N);H<u&&(r=m,u=H,a=M.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${o} used.`);return{axis:r,pos:a}}function fa(i,e,t,n){let s=0;const o=i.offset;for(let r=e,a=e+t;r<a;r++)s+=i[(r-o)*6+n*2];return s/t}class Ls{constructor(){this.boundingData=new Float32Array(6)}}function pa(i,e,t,n,s,o){let r=n,a=n+s-1;const c=o.pos,u=o.axis*2,d=t.offset||0;for(;;){for(;r<=a&&t[(r-d)*6+u]<c;)r++;for(;r<=a&&t[(a-d)*6+u]>=c;)a--;if(r<a){for(let h=0;h<e;h++){let f=i[r*e+h];i[r*e+h]=i[a*e+h],i[a*e+h]=f}for(let h=0;h<6;h++){const f=r-d,m=a-d,w=t[f*6+h];t[f*6+h]=t[m*6+h],t[m*6+h]=w}r++,a--}else return r}}let Pr,ds,Js,Or;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 Pr=new Float32Array(t),ds=new Uint32Array(t),Js=new Uint16Array(t),Or=new Uint8Array(t),ti(i,e)}function ti(i,e){const t=i/4,n=i/2,s="count"in e,o=e.boundingData;for(let r=0;r<6;r++)Pr[t+r]=o[r];if(s)return e.buffer?(Or.set(new Uint8Array(e.buffer),i),i+e.buffer.byteLength):(ds[t+6]=e.offset,Js[n+14]=e.count,Js[n+15]=yi,i+Ve);{const{left:r,right:a,splitAxis:c}=e,u=i+Ve;let d=ti(u,r);const h=i/Ve,m=d/Ve-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,o){const{maxDepth:r,verbose:a,maxLeafSize:c,strategy:u,onProgress:d}=s,h=i.primitiveBuffer,f=i.primitiveBufferStride,m=new Float32Array(6);let w=!1;const x=new Ls;return Is(e,t,n,x.boundingData,m),A(x,t,n,m),x;function _(T){d&&d((T-o.offset)/o.count)}function A(T,S,b,M=null,P=0){if(!w&&P>=r&&(w=!0,a&&console.warn(`BVH: Max depth of ${r} reached when generating BVH. Consider increasing maxDepth.`)),b<=c||P>=r)return _(S+b),T.offset=S,T.count=b,T;const L=da(T.boundingData,M,e,S,b,u);if(L.axis===-1)return _(S+b),T.offset=S,T.count=b,T;const C=pa(h,f,e,S,b,L);if(C===S||C===S+b)_(S+b),T.offset=S,T.count=b;else{T.splitAxis=L.axis;const D=new Ls,I=S,F=C-S;T.left=D,Is(e,I,F,D.boundingData,m),A(D,I,F,m,P+1);const N=new Ls,H=C,G=b-F;T.right=N,Is(e,H,G,N.boundingData,m),A(N,H,G,m,P+1)}return T}}function wa(i,e){const t=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=i.getRootRanges(e.range),s=n[0],o=n[n.length-1],r={offset:s.offset,count:o.offset+o.count-s.offset},a=new Float32Array(6*r.count);a.offset=r.offset,i.computePrimitiveBounds(r.offset,r.count,a),i._roots=n.map(c=>{const u=ya(i,a,c.offset,c.count,e,r),d=ei(u),h=new t(Ve*d);return ga(0,u,h),h})}class Ei{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 Ea{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 Ea;let Pt,tn;const Gt=[],Gn=new Ei(()=>new p.Box3);function Ta(i,e,t,n,s,o){Pt=Gn.getPrimitive(),tn=Gn.getPrimitive(),Gt.push(Pt,tn),be.setBuffer(i._roots[e]);const r=ni(0,i.geometry,t,n,s,o);be.clearBuffer(),Gn.releasePrimitive(Pt),Gn.releasePrimitive(tn),Gt.pop(),Gt.pop();const a=Gt.length;return a>0&&(tn=Gt[a-1],Pt=Gt[a-2]),r}function ni(i,e,t,n,s=null,o=0,r=0){const{float32Array:a,uint16Array:c,uint32Array:u}=be;let d=i*2;if(Ie(d,c)){const f=He(i,u),m=Xe(d,c);return Ae(i,a,Pt),n(f,m,!1,r,o+i/De,Pt)}else{let I=function(N){const{uint16Array:H,uint32Array:G}=be;let $=N*2;for(;!Ie($,H);)N=Fe(N),$=N*2;return He(N,G)},F=function(N){const{uint16Array:H,uint32Array:G}=be;let $=N*2;for(;!Ie($,H);)N=Be(N,G),$=N*2;return He(N,G)+Xe($,H)};const f=Fe(i),m=Be(i,u);let w=f,x=m,_,A,T,S;if(s&&(T=Pt,S=tn,Ae(w,a,T),Ae(x,a,S),_=s(T),A=s(S),A<_)){w=m,x=f;const N=_;_=A,A=N,T=S}T||(T=Pt,Ae(w,a,T));const b=Ie(w*2,c),M=t(T,b,_,r+1,o+w/De);let P;if(M===Ui){const N=I(w),G=F(w)-N;P=n(N,G,!0,r+1,o+w/De,T)}else P=M&&ni(w,e,t,n,s,o,r+1);if(P)return!0;S=tn,Ae(x,a,S);const L=Ie(x*2,c),C=t(S,L,A,r+1,o+x/De);let D;if(C===Ui){const N=I(x),G=F(x)-N;D=n(N,G,!0,r+1,o+x/De,S)}else D=C&&ni(x,e,t,n,s,o,r+1);return!!D}}const _n=new be.constructor,ms=new be.constructor,It=new Ei(()=>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,o=e._roots;let r,a=0,c=0;const u=new p.Matrix4().copy(t).invert();for(let d=0,h=s.length;d<h;d++){_n.setBuffer(s[d]),c=0;const f=It.getPrimitive();Ae(0,_n.float32Array,f),f.applyMatrix4(u);for(let m=0,w=o.length;m<w&&(ms.setBuffer(o[m]),r=ht(0,0,t,u,n,a,c,0,0,f),ms.clearBuffer(),c+=o[m].byteLength/Ve,!r);m++);if(It.releasePrimitive(f),_n.clearBuffer(),a+=s[d].byteLength/Ve,r)break}return Ds=!1,r}function ht(i,e,t,n,s,o=0,r=0,a=0,c=0,u=null,d=!1){let h,f;d?(h=ms,f=_n):(h=_n,f=ms);const m=h.float32Array,w=h.uint32Array,x=h.uint16Array,_=f.float32Array,A=f.uint32Array,T=f.uint16Array,S=i*2,b=e*2,M=Ie(S,x),P=Ie(b,T);let L=!1;if(P&&M)d?L=s(He(e,A),Xe(e*2,T),He(i,w),Xe(i*2,x),c,r+e/De,a,o+i/De):L=s(He(i,w),Xe(i*2,x),He(e,A),Xe(e*2,T),a,o+i/De,c,r+e/De);else if(P){const C=It.getPrimitive();Ae(e,_,C),C.applyMatrix4(t);const D=Fe(i),I=Be(i,w);Ae(D,m,Wt),Ae(I,m,Zt);const F=C.intersectsBox(Wt),N=C.intersectsBox(Zt);L=F&&ht(e,D,n,t,s,r,o,c,a+1,C,!d)||N&&ht(e,I,n,t,s,r,o,c,a+1,C,!d),It.releasePrimitive(C)}else{const C=Fe(e),D=Be(e,A);Ae(C,_,Ps),Ae(D,_,Os);const I=u.intersectsBox(Ps),F=u.intersectsBox(Os);if(I&&F)L=ht(i,C,t,n,s,o,r,a,c+1,u,d)||ht(i,D,t,n,s,o,r,a,c+1,u,d);else if(I)if(M)L=ht(i,C,t,n,s,o,r,a,c+1,u,d);else{const N=It.getPrimitive();N.copy(Ps).applyMatrix4(t);const H=Fe(i),G=Be(i,w);Ae(H,m,Wt),Ae(G,m,Zt);const $=N.intersectsBox(Wt),re=N.intersectsBox(Zt);L=$&&ht(C,H,n,t,s,r,o,c,a+1,N,!d)||re&&ht(C,G,n,t,s,r,o,c,a+1,N,!d),It.releasePrimitive(N)}else if(F)if(M)L=ht(i,D,t,n,s,o,r,a,c+1,u,d);else{const N=It.getPrimitive();N.copy(Os).applyMatrix4(t);const H=Fe(i),G=Be(i,w);Ae(H,m,Wt),Ae(G,m,Zt);const $=N.intersectsBox(Wt),re=N.intersectsBox(Zt);L=$&&ht(D,H,n,t,s,r,o,c,a+1,N,!d)||re&&ht(D,G,n,t,s,r,o,c,a+1,N,!d),It.releasePrimitive(N)}}return L}const Wi=new p.Box3,Kt=new Float32Array(6);class _a{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(e){e={...Lr,...e},wa(this,e)}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(e,t,n,s){let o=1/0,r=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,w,x,_,A,T]=Kt;m<o&&(o=m),_>c&&(c=_),w<r&&(r=w),A>u&&(u=A),x<a&&(a=x),T>d&&(d=T)}return n[s+0]=o,n[s+1]=r,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 o=e,r=e+t;o<r;o++){this.writePrimitiveBounds(o,Kt,0);const[a,c,u,d,h,f]=Kt,m=(a+d)/2,w=(c+h)/2,x=(u+f)/2,_=(d-a)/2,A=(h-c)/2,T=(f-u)/2,S=(o-s)*6;n[S+0]=m,n[S+1]=_+(Math.abs(m)+_)*us,n[S+2]=w,n[S+3]=A+(Math.abs(w)+A)*us,n[S+4]=x,n[S+5]=T+(Math.abs(x)+T)*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 o=n[s],r=new Uint32Array(o),a=new Uint16Array(o),c=o.byteLength/Ve;for(let u=0;u<c;u++){const d=De*u,h=2*d;Ie(h,a)&&(r[d+6]+=e)}}}}traverse(e,t=0){const n=this._roots[t],s=new Uint32Array(n),o=new Uint16Array(n);r(0);function r(a,c=0){const u=a*2,d=Ie(u,o);if(d){const h=s[a+6],f=o[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)||(r(h,c+1),r(f,c+1))}}}refit(){const e=this._roots;for(let t=0,n=e.length;t<n;t++){const s=e[t],o=new Uint32Array(s),r=new Uint16Array(s),a=new Float32Array(s),c=s.byteLength/Ve;for(let u=c-1;u>=0;u--){const d=u*De,h=d*2;if(Ie(h,r)){const m=He(d,o),w=Xe(h,r);this.writePrimitiveRangeBounds(m,w,Kt,0),a.set(Kt,d)}else{const m=Fe(d),w=Be(d,o);for(let x=0;x<3;x++){const _=a[m+x],A=a[m+x+3],T=a[w+x],S=a[w+x+3];a[d+x]=_<T?_:T,a[d+x+3]=A>S?A:S}}}}}getBoundingBox(e){return e.makeEmpty(),this._roots.forEach(n=>{Ae(0,new Float32Array(n),Wi),e.union(Wi)}),e}shapecast(e){let{boundsTraverseOrder:t,intersectsBounds:n,intersectsRange:s,intersectsPrimitive:o,scratchPrimitive:r,iterate:a}=e;if(s&&o){const h=s;s=(f,m,w,x,_)=>h(f,m,w,x,_)?!0:a(f,m,this,o,w,x,r)}else s||(o?s=(h,f,m,w)=>a(h,f,this,o,m,w,r):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/Ve}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 Dr(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=Dr(t,n);i.setIndex(new p.BufferAttribute(s,1));for(let o=0;o<t;o++)s[o]=o}}function Aa(i,e,t){const n=Ss(i)/t,s=e||i.drawRange,o=s.start/t,r=(s.start+s.count)/t,a=Math.max(0,o),c=Math.min(n,r)-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 Zi(i,e,t){const n=Aa(i,e,t),s=Ma(i,t);if(!s.length)return[n];const o=[],r=n.offset,a=n.offset+n.count,c=Ss(i)/t,u=[];for(const f of s){const{offset:m,count:w}=f,x=m,_=isFinite(w)?w:c-m,A=m+_;x<a&&A>r&&(u.push({pos:Math.max(r,x),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&&o.push({offset:h,count:m-h}),d+=f.isStart?1:-1,h=m}return o}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),o=n?4:2,r=e?new SharedArrayBuffer(s*o):new ArrayBuffer(s*o),a=n?new Uint32Array(r):new Uint16Array(r);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={...Lr,...t},t[wi]||this.init(t)}init(e){const{geometry:t,primitiveStride:n}=this;if(e.indirect){const s=Zi(t,e.range,n),o=Ra(s,e.useSharedArrayBuffer);this._indirectBuffer=o}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}]:Zi(this.geometry,e,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class xt{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let n=1/0,s=-1/0;for(let o=0,r=e.length;o<r;o++){const c=e[o][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 o=0,r=t.length;o<r;o++){const a=t[o],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}}xt.prototype.setFromBox=(function(){const i=new p.Vector3;return function(t,n){const s=n.min,o=n.max;let r=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+o.x*(1-c),i.y=s.y*u+o.y*(1-u),i.z=s.z*d+o.z*(1-d);const h=t.dot(i);r=Math.min(h,r),a=Math.max(h,a)}this.min=r,this.max=a}})();const Ca=(function(){const i=new p.Vector3,e=new p.Vector3,t=new p.Vector3;return function(s,o,r){const a=s.start,c=i,u=o.start,d=e;t.subVectors(a,u),i.subVectors(s.end,s.start),e.subVectors(o.end,o.start);const h=t.dot(d),f=d.dot(c),m=d.dot(d),w=t.dot(c),_=c.dot(c)*m-f*f;let A,T;_!==0?A=(h*f-w*m)/_:A=0,T=(h+A*f)/m,r.x=A,r.y=T}})(),Ti=(function(){const i=new p.Vector2,e=new p.Vector3,t=new p.Vector3;return function(s,o,r,a){Ca(s,o,i);let c=i.x,u=i.y;if(c>=0&&c<=1&&u>=0&&u<=1){s.at(c,r),o.at(u,a);return}else if(c>=0&&c<=1){u<0?o.at(0,a):o.at(1,a),s.closestPointToPoint(a,!0,r);return}else if(u>=0&&u<=1){c<0?s.at(0,r):s.at(1,r),o.closestPointToPoint(r,!0,a);return}else{let d;c<0?d=s.start:d=s.end;let h;u<0?h=o.start:h=o.end;const f=e,m=t;if(s.closestPointToPoint(h,!0,e),o.closestPointToPoint(d,!0,t),f.distanceToSquared(h)<=m.distanceToSquared(d)){r.copy(f),a.copy(h);return}else{r.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(o,r){const{radius:a,center:c}=o,{a:u,b:d,c:h}=r;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 x=r.getPlane(t);if(Math.abs(x.distanceToPoint(c))<=a){const A=x.projectPoint(c,e);if(r.containsPoint(A))return!0}return!1}})(),La=["x","y","z"],_t=1e-15,Ki=_t*_t;function nt(i){return Math.abs(i)<_t}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 xt),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,o=this.satAxes,r=this.satBounds,a=o[0],c=r[0];this.getNormal(a),c.setFromPoints(a,s);const u=o[1],d=r[1];u.subVectors(e,t),d.setFromPoints(u,s);const h=o[2],f=r[2];h.subVectors(t,n),f.setFromPoints(h,s);const m=o[3],w=r[3];m.subVectors(n,e),w.setFromPoints(m,s);const x=u.length(),_=h.length(),A=m.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,x<_t?_<_t||A<_t?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(n)):_<_t?A<_t?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(e)):A<_t&&(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,o=null,r=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]),Ti(t,s,i,e),d=i.distanceToSquared(e),d<h&&(h=d,o&&o.copy(i),r&&r.copy(e))}return this.closestPointToPoint(a,i),d=a.distanceToSquared(i),d<h&&(h=d,o&&o.copy(i),r&&r.copy(a)),this.closestPointToPoint(c,i),d=c.distanceToSquared(i),d<h&&(h=d,o&&o.copy(i),r&&r.copy(c)),Math.sqrt(h)}})();dt.prototype.intersectsTriangle=(function(){const i=new dt,e=new xt,t=new xt,n=new p.Vector3,s=new p.Vector3,o=new p.Vector3,r=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(S,b,M,P){const L=n;!S.isDegenerateIntoPoint&&!S.isDegenerateIntoSegment?L.copy(S.plane.normal):L.copy(b.plane.normal);const C=S.satBounds,D=S.satAxes;for(let N=1;N<4;N++){const H=C[N],G=D[N];if(e.setFromPoints(G,b.points),H.isSeparated(e)||(r.copy(L).cross(G),e.setFromPoints(r,S.points),t.setFromPoints(r,b.points),e.isSeparated(t)))return!1}const I=b.satBounds,F=b.satAxes;for(let N=1;N<4;N++){const H=I[N],G=F[N];if(e.setFromPoints(G,S.points),H.isSeparated(e)||(r.crossVectors(L,G),e.setFromPoints(r,S.points),t.setFromPoints(r,b.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(S,b,M,P,L,C,D,I,F,N,H){let G=D/(D-I);N.x=P+(L-P)*G,H.start.subVectors(b,S).multiplyScalar(G).add(S),G=D/(D-F),N.y=P+(C-P)*G,H.end.subVectors(M,S).multiplyScalar(G).add(S)}function w(S,b,M,P,L,C,D,I,F,N,H){if(L>0)m(S.c,S.a,S.b,P,b,M,F,D,I,N,H);else if(C>0)m(S.b,S.a,S.c,M,b,P,I,D,F,N,H);else if(I*F>0||D!=0)m(S.a,S.b,S.c,b,M,P,D,I,F,N,H);else if(I!=0)m(S.b,S.a,S.c,M,b,P,I,D,F,N,H);else if(F!=0)m(S.c,S.a,S.b,P,b,M,F,D,I,N,H);else return!0;return!1}function x(S,b,M,P){const L=b.degenerateSegment,C=S.plane.distanceToPoint(L.start),D=S.plane.distanceToPoint(L.end);return nt(C)?nt(D)?f(S,b,M,P):(M&&(M.start.copy(L.start),M.end.copy(L.start)),S.containsPoint(L.start)):nt(D)?(M&&(M.start.copy(L.end),M.end.copy(L.end)),S.containsPoint(L.end)):S.plane.intersectLine(L,n)!=null?(M&&(M.start.copy(n),M.end.copy(n)),S.containsPoint(n)):!1}function _(S,b,M){const P=b.a;return nt(S.plane.distanceToPoint(P))&&S.containsPoint(P)?(M&&(M.start.copy(P),M.end.copy(P)),!0):!1}function A(S,b,M){const P=S.degenerateSegment,L=b.a;return P.closestPointToPoint(L,!0,n),L.distanceToSquared(n)<Ki?(M&&(M.start.copy(L),M.end.copy(L)),!0):!1}function T(S,b,M,P){if(S.isDegenerateIntoSegment)if(b.isDegenerateIntoSegment){const L=S.degenerateSegment,C=b.degenerateSegment,D=s,I=o;L.delta(D),C.delta(I);const F=n.subVectors(C.start,L.start),N=D.x*I.y-D.y*I.x;if(nt(N))return!1;const H=(F.x*I.y-F.y*I.x)/N,G=-(D.x*F.y-D.y*F.x)/N;if(H<0||H>1||G<0||G>1)return!1;const $=L.start.z+D.z*H,re=C.start.z+I.z*G;return nt($-re)?(M&&(M.start.copy(L.start).addScaledVector(D,H),M.end.copy(L.start).addScaledVector(D,H)),!0):!1}else return b.isDegenerateIntoPoint?A(S,b,M):x(b,S,M,P);else{if(S.isDegenerateIntoPoint)return b.isDegenerateIntoPoint?b.a.distanceToSquared(S.a)<Ki?(M&&(M.start.copy(S.a),M.end.copy(S.a)),!0):!1:b.isDegenerateIntoSegment?A(b,S,M):_(b,S,M);if(b.isDegenerateIntoPoint)return _(S,b,M);if(b.isDegenerateIntoSegment)return x(S,b,M,P)}}return function(b,M=null,P=!1){this.needsUpdate&&this.update(),b.isExtendedTriangle?b.needsUpdate&&b.update():(i.copy(b),i.update(),b=i);const L=T(this,b,M,P);if(L!==void 0)return L;const C=this.plane,D=b.plane;let I=D.distanceToPoint(this.a),F=D.distanceToPoint(this.b),N=D.distanceToPoint(this.c);nt(I)&&(I=0),nt(F)&&(F=0),nt(N)&&(N=0);const H=I*F,G=I*N;if(H>0&&G>0)return!1;let $=C.distanceToPoint(b.a),re=C.distanceToPoint(b.b),Ne=C.distanceToPoint(b.c);nt($)&&($=0),nt(re)&&(re=0),nt(Ne)&&(Ne=0);const ot=$*re,ve=$*Ne;if(ot>0&&ve>0)return!1;s.copy(C.normal),o.copy(D.normal);const ze=s.cross(o);let je=0,Me=Math.abs(ze.x);const ye=Math.abs(ze.y);ye>Me&&(Me=ye,je=1),Math.abs(ze.z)>Me&&(je=2);const Ge=La[je],At=this.a[Ge],ge=this.b[Ge],at=this.c[Ge],ct=b.a[Ge],an=b.b[Ge],Vt=b.c[Ge];if(w(this,At,ge,at,H,G,I,F,N,d,a))return f(this,b,M,P);if(w(b,ct,an,Vt,ot,ve,$,re,Ne,h,c))return f(this,b,M,P);if(d.y<d.x){const Tt=d.y;d.y=d.x,d.x=Tt,u.copy(a.start),a.start.copy(a.end),a.end.copy(u)}if(h.y<h.x){const Tt=h.y;h.y=h.x,h.x=Tt,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(r,a=null,c=null){const u=a||c?n:null;if(this.intersectsTriangle(r,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],w=r[m];this.closestPointToPoint(w,i),f=w.distanceToSquared(i),f<d&&(d=f,a&&a.copy(i),c&&c.copy(w));const x=this[m];r.closestPointToPoint(x,i),f=x.distanceToSquared(i),f<d&&(d=f,a&&a.copy(x),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 w=0;w<3;w++){const x=t[w],_=t[(w+1)%3];s.set(r[x],r[_]),Ti(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 xt),this.alignedSatBounds=new Array(3).fill().map(()=>new xt),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 o=this.satBounds,r=this.satAxes,a=s[0];for(let u=0;u<3;u++){const d=r[u],h=o[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 xt;return function(t){this.needsUpdate&&this.update();const n=t.min,s=t.max,o=this.satBounds,r=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=r[c],d=o[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 xt,n=new xt,s=new p.Vector3;return function(r){this.needsUpdate&&this.update(),r.isExtendedTriangle?r.needsUpdate&&r.update():(i.copy(r),i.update(),r=i);const a=this.satBounds,c=this.satAxes;e[0]=r.a,e[1]=r.b,e[2]=r.c;for(let f=0;f<3;f++){const m=a[f],w=c[f];if(t.setFromPoints(w,e),m.isSeparated(t))return!1}const u=r.satBounds,d=r.satAxes,h=this.points;for(let f=0;f<3;f++){const m=u[f],w=d[f];if(t.setFromPoints(w,h),m.isSeparated(t))return!1}for(let f=0;f<3;f++){const m=c[f];for(let w=0;w<4;w++){const x=d[w];if(s.crossVectors(m,x),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(r,a=0,c=null,u=null){if(this.needsUpdate&&this.update(),this.intersectsBox(r))return(c||u)&&(r.getCenter(s),this.closestPointToPoint(s,n),r.closestPointToPoint(n,s),c&&c.copy(n),u&&u.copy(s)),0;const d=a*a,h=r.min,f=r.max,m=this.points;let w=1/0;for(let _=0;_<8;_++){const A=m[_];s.copy(A).clamp(h,f);const T=A.distanceToSquared(s);if(T<w&&(w=T,c&&c.copy(A),u&&u.copy(s),T<d))return Math.sqrt(T)}let x=0;for(let _=0;_<3;_++)for(let A=0;A<=1;A++)for(let T=0;T<=1;T++){const S=(_+1)%3,b=(_+2)%3,M=A<<S|T<<b,P=1<<_|A<<S|T<<b,L=m[M],C=m[P];e[x].set(L,C);const I=i[_],F=i[S],N=i[b],H=t[x],G=H.start,$=H.end;G[I]=h[I],G[F]=A?h[F]:f[F],G[N]=T?h[N]:f[F],$[I]=f[I],$[F]=A?h[F]:f[F],$[N]=T?h[N]:f[F],x++}for(let _=0;_<=1;_++)for(let A=0;A<=1;A++)for(let T=0;T<=1;T++){s.x=_?f.x:h.x,s.y=A?f.y:h.y,s.z=T?f.z:h.z,this.closestPointToPoint(s,n);const S=s.distanceToSquared(n);if(S<w&&(w=S,c&&c.copy(n),u&&u.copy(s),S<d))return Math.sqrt(S)}for(let _=0;_<12;_++){const A=e[_];for(let T=0;T<12;T++){const S=t[T];Ti(A,S,n,s);const b=n.distanceToSquared(s);if(b<w&&(w=b,c&&c.copy(n),u&&u.copy(s),b<d))return Math.sqrt(b)}}return Math.sqrt(w)}})();class Pa extends Ei{constructor(){super(()=>new dt)}}const rt=new Pa,dn=new p.Vector3,Ns=new p.Vector3;function Oa(i,e,t={},n=0,s=1/0){const o=n*n,r=s*s;let a=1/0,c=null;if(i.shapecast({boundsTraverseOrder:d=>(dn.copy(e).clamp(d.min,d.max),dn.distanceToSquared(e)),intersectsBounds:(d,h,f)=>f<a&&f<r,intersectsTriangle:(d,h)=>{d.closestPointToPoint(e,dn);const f=e.distanceToSquared(dn);return f<a&&(Ns.copy(dn),a=f,c=h),f<o}}),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,kt=new p.Vector3,Ft=new p.Vector3,Bt=new p.Vector3,Zn=new p.Vector2,Kn=new p.Vector2,Xn=new p.Vector2,Xi=new p.Vector3,Yi=new p.Vector3,qi=new p.Vector3,fn=new p.Vector3;function Na(i,e,t,n,s,o,r,a){let c;if(o===p.BackSide?c=i.intersectTriangle(n,t,e,!0,s):c=i.intersectTriangle(e,t,n,o!==p.DoubleSide,s),c===null)return null;const u=i.origin.distanceTo(s);return u<r||u>a?null:{distance:u,point:s.clone()}}function $i(i,e,t,n,s,o,r,a,c,u,d){kt.fromBufferAttribute(e,o),Ft.fromBufferAttribute(e,r),Bt.fromBufferAttribute(e,a);const h=Na(i,kt,Ft,Bt,fn,c,u,d);if(h){if(n){Zn.fromBufferAttribute(n,o),Kn.fromBufferAttribute(n,r),Xn.fromBufferAttribute(n,a),h.uv=new p.Vector2;const m=p.Triangle.getInterpolation(fn,kt,Ft,Bt,Zn,Kn,Xn,h.uv);Wn||(h.uv=m)}if(s){Zn.fromBufferAttribute(s,o),Kn.fromBufferAttribute(s,r),Xn.fromBufferAttribute(s,a),h.uv1=new p.Vector2;const m=p.Triangle.getInterpolation(fn,kt,Ft,Bt,Zn,Kn,Xn,h.uv1);Wn||(h.uv1=m),Da&&(h.uv2=h.uv1)}if(t){Xi.fromBufferAttribute(t,o),Yi.fromBufferAttribute(t,r),qi.fromBufferAttribute(t,a),h.normal=new p.Vector3;const m=p.Triangle.getInterpolation(fn,kt,Ft,Bt,Xi,Yi,qi,h.normal);h.normal.dot(i.direction)>0&&h.normal.multiplyScalar(-1),Wn||(h.normal=m)}const f={a:o,b:r,c:a,normal:new p.Vector3,materialIndex:0};if(p.Triangle.getNormal(kt,Ft,Bt,f.normal),h.face=f,h.faceIndex=o,Wn){const m=new p.Vector3;p.Triangle.getBarycoord(fn,kt,Ft,Bt,m),h.barycoord=m}}return h}function Qi(i){return i&&i.isMaterial?i.side:i}function bs(i,e,t,n,s,o,r){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:w,uv:x,uv1:_}=i.attributes;if(Array.isArray(e)){const A=n*3;for(let T=0,S=f.length;T<S;T++){const{start:b,count:M,materialIndex:P}=f[T];if(A>=b&&A<b+M){const L=Qi(e[P]),C=$i(t,m,w,x,_,c,u,d,L,o,r);if(C)if(C.faceIndex=n,C.face.materialIndex=P,s)s.push(C);else return C}}}else{const A=Qi(e),T=$i(t,m,w,x,_,c,u,d,A,o,r);if(T)if(T.faceIndex=n,T.face.materialIndex=0,s)s.push(T);else return T}return null}function Le(i,e,t,n){const s=i.a,o=i.b,r=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),o.x=n.getX(c),o.y=n.getY(c),o.z=n.getZ(c),r.x=n.getX(u),r.y=n.getY(u),r.z=n.getZ(u)}function ka(i,e,t,n,s,o,r,a){const{geometry:c,_indirectBuffer:u}=i;for(let d=n,h=n+s;d<h;d++)bs(c,e,t,d,o,r,a)}function Fa(i,e,t,n,s,o,r){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,o,r),m&&m.distance<u&&(d=m,u=m.distance)}return d}function Ba(i,e,t,n,s,o,r){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,Le(r,f*3,c,u),r.needsUpdate=!0,n(r,f,s,o))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 o,r,a,c,u=0;const d=i._roots;for(let f=0,m=d.length;f<m;f++)o=d[f],r=new Uint32Array(o),a=new Uint16Array(o),c=new Float32Array(o),h(0,u),u+=o.byteLength;function h(f,m,w=!1){const x=f*2;if(Ie(x,a)){const _=He(f,r),A=Xe(x,a);let T=1/0,S=1/0,b=1/0,M=-1/0,P=-1/0,L=-1/0;for(let C=3*_,D=3*(_+A);C<D;C++){let I=n[C];const F=s.getX(I),N=s.getY(I),H=s.getZ(I);F<T&&(T=F),F>M&&(M=F),N<S&&(S=N),N>P&&(P=N),H<b&&(b=H),H>L&&(L=H)}return c[f+0]!==T||c[f+1]!==S||c[f+2]!==b||c[f+3]!==M||c[f+4]!==P||c[f+5]!==L?(c[f+0]=T,c[f+1]=S,c[f+2]=b,c[f+3]=M,c[f+4]=P,c[f+5]=L,!0):!1}else{const _=Fe(f),A=Be(f,r);let T=w,S=!1,b=!1;if(e){if(!T){const I=_/De+m/Ve,F=A/De+m/Ve;S=e.has(I),b=e.has(F),T=!S&&!b}}else S=!0,b=!0;const M=T||S,P=T||b;let L=!1;M&&(L=h(_,m,T));let C=!1;P&&(C=h(A,m,T));const D=L||C;if(D)for(let I=0;I<3;I++){const F=_+I,N=A+I,H=c[F],G=c[F+3],$=c[N],re=c[N+3];c[f+I]=H<$?H:$,c[f+I+3]=G>re?G:re}return D}}}function Dt(i,e,t,n,s){let o,r,a,c,u,d;const h=1/t.direction.x,f=1/t.direction.y,m=1/t.direction.z,w=t.origin.x,x=t.origin.y,_=t.origin.z;let A=e[i],T=e[i+3],S=e[i+1],b=e[i+3+1],M=e[i+2],P=e[i+3+2];return h>=0?(o=(A-w)*h,r=(T-w)*h):(o=(T-w)*h,r=(A-w)*h),f>=0?(a=(S-x)*f,c=(b-x)*f):(a=(b-x)*f,c=(S-x)*f),o>c||a>r||((a>o||isNaN(o))&&(o=a),(c<r||isNaN(r))&&(r=c),m>=0?(u=(M-_)*m,d=(P-_)*m):(u=(P-_)*m,d=(M-_)*m),o>d||u>r)?!1:((u>o||o!==o)&&(o=u),(d<r||r!==r)&&(r=d),o<=s&&r>=n)}function Ua(i,e,t,n,s,o,r,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,o,r,a)}}function Va(i,e,t,n,s,o,r){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,o,r),m&&m.distance<u&&(d=m,u=m.distance)}return d}function Ha(i,e,t,n,s,o,r){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),Le(r,f*3,c,u),r.needsUpdate=!0,n(r,f,s,o))return!0}return!1}function ja(i,e,t,n,s,o,r){be.setBuffer(i._roots[e]),si(0,i,t,n,s,o,r),be.clearBuffer()}function si(i,e,t,n,s,o,r){const{float32Array:a,uint16Array:c,uint32Array:u}=be,d=i*2;if(Ie(d,c)){const f=He(i,u),m=Xe(d,c);ka(e,t,n,f,m,s,o,r)}else{const f=Fe(i);Dt(f,a,n,o,r)&&si(f,e,t,n,s,o,r);const m=Be(i,u);Dt(m,a,n,o,r)&&si(m,e,t,n,s,o,r)}}const Ga=["x","y","z"];function Wa(i,e,t,n,s,o){be.setBuffer(i._roots[e]);const r=ii(0,i,t,n,s,o);return be.clearBuffer(),r}function ii(i,e,t,n,s,o){const{float32Array:r,uint16Array:a,uint32Array:c}=be;let u=i*2;if(Ie(u,a)){const h=He(i,c),f=Xe(u,a);return Fa(e,t,n,h,f,s,o)}else{const h=Ts(i,c),f=Ga[h],w=n.direction[f]>=0;let x,_;w?(x=Fe(i),_=Be(i,c)):(x=Be(i,c),_=Fe(i));const T=Dt(x,r,n,s,o)?ii(x,e,t,n,s,o):null;if(T){const M=T.point[f];if(w?M<=r[_+h]:M>=r[_+h+3])return T}const b=Dt(_,r,n,s,o)?ii(_,e,t,n,s,o):null;return T&&b?T.distance<=b.distance?T:b:T||b||null}}const Yn=new p.Box3,Xt=new dt,Yt=new dt,pn=new p.Matrix4,Ji=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:o,uint16Array:r,uint32Array:a}=be;let c=i*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),Ji.set(t.boundingBox.min,t.boundingBox.max,n),s=Ji),Ie(c,r)){const d=e.geometry,h=d.index,f=d.attributes.position,m=t.index,w=t.attributes.position,x=He(i,a),_=Xe(c,r);if(pn.copy(n).invert(),t.boundsTree)return Ae(i,o,qn),qn.matrix.copy(pn),qn.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:T=>qn.intersectsBox(T),intersectsTriangle:T=>{T.a.applyMatrix4(n),T.b.applyMatrix4(n),T.c.applyMatrix4(n),T.needsUpdate=!0;for(let S=x*3,b=(_+x)*3;S<b;S+=3)if(Le(Yt,S,h,f),Yt.needsUpdate=!0,T.intersectsTriangle(Yt))return!0;return!1}});{const A=_s(t);for(let T=x*3,S=(_+x)*3;T<S;T+=3){Le(Xt,T,h,f),Xt.a.applyMatrix4(pn),Xt.b.applyMatrix4(pn),Xt.c.applyMatrix4(pn),Xt.needsUpdate=!0;for(let b=0,M=A*3;b<M;b+=3)if(Le(Yt,b,m,w),Yt.needsUpdate=!0,Xt.intersectsTriangle(Yt))return!0}}}else{const d=Fe(i),h=Be(i,a);return Ae(d,o,Yn),!!(s.intersectsBox(Yn)&&ri(d,e,t,n,s)||(Ae(h,o,Yn),s.intersectsBox(Yn)&&ri(h,e,t,n,s)))}}const $n=new p.Matrix4,ks=new Ye,mn=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={},o=0,r=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 w=Ka,x=Xa,_=null,A=null;s&&(_=Ya,A=qa);let T=1/0,S=null,b=null;return $n.copy(t).invert(),mn.matrix.copy($n),i.shapecast({boundsTraverseOrder:M=>ks.distanceToBox(M),intersectsBounds:(M,P,L)=>L<T&&L<r?(P&&(mn.min.copy(M.min),mn.max.copy(M.max),mn.needsUpdate=!0),!0):!1,intersectsRange:(M,P)=>{if(e.boundsTree)return e.boundsTree.shapecast({boundsTraverseOrder:C=>mn.distanceToBox(C),intersectsBounds:(C,D,I)=>I<T&&I<r,intersectsRange:(C,D)=>{for(let I=C,F=C+D;I<F;I++){Le(m,3*I,h,d),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let N=M,H=M+P;N<H;N++){Le(f,3*N,u,c),f.needsUpdate=!0;const G=f.distanceToTriangle(m,w,_);if(G<T&&(x.copy(w),A&&A.copy(_),T=G,S=N,b=I),G<o)return!0}}}});{const L=_s(e);for(let C=0,D=L;C<D;C++){Le(m,3*C,h,d),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let I=M,F=M+P;I<F;I++){Le(f,3*I,u,c),f.needsUpdate=!0;const N=f.distanceToTriangle(m,w,_);if(N<T&&(x.copy(w),A&&A.copy(_),T=N,S=I,b=C),N<o)return!0}}}}}),rt.releasePrimitive(f),rt.releasePrimitive(m),T===1/0?null:(n.point?n.point.copy(x):n.point=x.clone(),n.distance=T,n.faceIndex=S,s&&(s.point?s.point.copy(A):s.point=A.clone(),s.point.applyMatrix4($n),x.applyMatrix4($n),s.distance=x.sub(s.point).length(),s.faceIndex=b),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 o,r,a,c,u=0;const d=i._roots;for(let f=0,m=d.length;f<m;f++)o=d[f],r=new Uint32Array(o),a=new Uint16Array(o),c=new Float32Array(o),h(0,u),u+=o.byteLength;function h(f,m,w=!1){const x=f*2;if(Ie(x,a)){const _=He(f,r),A=Xe(x,a);let T=1/0,S=1/0,b=1/0,M=-1/0,P=-1/0,L=-1/0;for(let C=_,D=_+A;C<D;C++){const I=3*i.resolveTriangleIndex(C);for(let F=0;F<3;F++){let N=I+F;N=n?n[N]:N;const H=s.getX(N),G=s.getY(N),$=s.getZ(N);H<T&&(T=H),H>M&&(M=H),G<S&&(S=G),G>P&&(P=G),$<b&&(b=$),$>L&&(L=$)}}return c[f+0]!==T||c[f+1]!==S||c[f+2]!==b||c[f+3]!==M||c[f+4]!==P||c[f+5]!==L?(c[f+0]=T,c[f+1]=S,c[f+2]=b,c[f+3]=M,c[f+4]=P,c[f+5]=L,!0):!1}else{const _=Fe(f),A=Be(f,r);let T=w,S=!1,b=!1;if(e){if(!T){const I=_/De+m/Ve,F=A/De+m/Ve;S=e.has(I),b=e.has(F),T=!S&&!b}}else S=!0,b=!0;const M=T||S,P=T||b;let L=!1;M&&(L=h(_,m,T));let C=!1;P&&(C=h(A,m,T));const D=L||C;if(D)for(let I=0;I<3;I++){const F=_+I,N=A+I,H=c[F],G=c[F+3],$=c[N],re=c[N+3];c[f+I]=H<$?H:$,c[f+I+3]=G>re?G:re}return D}}}function Ja(i,e,t,n,s,o,r){be.setBuffer(i._roots[e]),oi(0,i,t,n,s,o,r),be.clearBuffer()}function oi(i,e,t,n,s,o,r){const{float32Array:a,uint16Array:c,uint32Array:u}=be,d=i*2;if(Ie(d,c)){const f=He(i,u),m=Xe(d,c);Ua(e,t,n,f,m,s,o,r)}else{const f=Fe(i);Dt(f,a,n,o,r)&&oi(f,e,t,n,s,o,r);const m=Be(i,u);Dt(m,a,n,o,r)&&oi(m,e,t,n,s,o,r)}}const ec=["x","y","z"];function tc(i,e,t,n,s,o){be.setBuffer(i._roots[e]);const r=ai(0,i,t,n,s,o);return be.clearBuffer(),r}function ai(i,e,t,n,s,o){const{float32Array:r,uint16Array:a,uint32Array:c}=be;let u=i*2;if(Ie(u,a)){const h=He(i,c),f=Xe(u,a);return Va(e,t,n,h,f,s,o)}else{const h=Ts(i,c),f=ec[h],w=n.direction[f]>=0;let x,_;w?(x=Fe(i),_=Be(i,c)):(x=Be(i,c),_=Fe(i));const T=Dt(x,r,n,s,o)?ai(x,e,t,n,s,o):null;if(T){const M=T.point[f];if(w?M<=r[_+h]:M>=r[_+h+3])return T}const b=Dt(_,r,n,s,o)?ai(_,e,t,n,s,o):null;return T&&b?T.distance<=b.distance?T:b:T||b||null}}const Qn=new p.Box3,qt=new dt,$t=new dt,gn=new p.Matrix4,er=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:o,uint16Array:r,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),Ie(c,r)){const d=e.geometry,h=d.index,f=d.attributes.position,m=t.index,w=t.attributes.position,x=He(i,a),_=Xe(c,r);if(gn.copy(n).invert(),t.boundsTree)return Ae(i,o,Jn),Jn.matrix.copy(gn),Jn.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:T=>Jn.intersectsBox(T),intersectsTriangle:T=>{T.a.applyMatrix4(n),T.b.applyMatrix4(n),T.c.applyMatrix4(n),T.needsUpdate=!0;for(let S=x,b=_+x;S<b;S++)if(Le($t,3*e.resolveTriangleIndex(S),h,f),$t.needsUpdate=!0,T.intersectsTriangle($t))return!0;return!1}});{const A=_s(t);for(let T=x,S=_+x;T<S;T++){const b=e.resolveTriangleIndex(T);Le(qt,3*b,h,f),qt.a.applyMatrix4(gn),qt.b.applyMatrix4(gn),qt.c.applyMatrix4(gn),qt.needsUpdate=!0;for(let M=0,P=A*3;M<P;M+=3)if(Le($t,M,m,w),$t.needsUpdate=!0,qt.intersectsTriangle($t))return!0}}}else{const d=Fe(i),h=Be(i,a);return Ae(d,o,Qn),!!(s.intersectsBox(Qn)&&ci(d,e,t,n,s)||(Ae(h,o,Qn),s.intersectsBox(Qn)&&ci(h,e,t,n,s)))}}const es=new p.Matrix4,Fs=new Ye,yn=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={},o=0,r=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 w=sc,x=ic,_=null,A=null;s&&(_=rc,A=oc);let T=1/0,S=null,b=null;return es.copy(t).invert(),yn.matrix.copy(es),i.shapecast({boundsTraverseOrder:M=>Fs.distanceToBox(M),intersectsBounds:(M,P,L)=>L<T&&L<r?(P&&(yn.min.copy(M.min),yn.max.copy(M.max),yn.needsUpdate=!0),!0):!1,intersectsRange:(M,P)=>{if(e.boundsTree){const L=e.boundsTree;return L.shapecast({boundsTraverseOrder:C=>yn.distanceToBox(C),intersectsBounds:(C,D,I)=>I<T&&I<r,intersectsRange:(C,D)=>{for(let I=C,F=C+D;I<F;I++){const N=L.resolveTriangleIndex(I);Le(m,3*N,h,d),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let H=M,G=M+P;H<G;H++){const $=i.resolveTriangleIndex(H);Le(f,3*$,u,c),f.needsUpdate=!0;const re=f.distanceToTriangle(m,w,_);if(re<T&&(x.copy(w),A&&A.copy(_),T=re,S=H,b=I),re<o)return!0}}}})}else{const L=_s(e);for(let C=0,D=L;C<D;C++){Le(m,3*C,h,d),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let I=M,F=M+P;I<F;I++){const N=i.resolveTriangleIndex(I);Le(f,3*N,u,c),f.needsUpdate=!0;const H=f.distanceToTriangle(m,w,_);if(H<T&&(x.copy(w),A&&A.copy(_),T=H,S=I,b=C),H<o)return!0}}}}}),rt.releasePrimitive(f),rt.releasePrimitive(m),T===1/0?null:(n.point?n.point.copy(x):n.point=x.clone(),n.distance=T,n.faceIndex=S,s&&(s.point?s.point.copy(A):s.point=A.clone(),s.point.applyMatrix4(es),x.applyMatrix4(es),s.distance=x.sub(s.point).length(),s.faceIndex=b),n)}function tr(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,nr=new p.Vector3,sr=new p.Matrix4,ir=new p.Vector3,Bs=["getX","getY","getZ"];class An extends va{static serialize(e,t={}){t={cloneBuffers:!0,...t};const n=e.geometry,s=e._roots,o=e._indirectBuffer,r=n.getIndex(),a={version:1,roots:null,index:null,indirectBuffer:null};return t.cloneBuffers?(a.roots=s.map(c=>c.slice()),a.index=r?r.array.slice():null,a.indirectBuffer=o?o.slice():null):(a.roots=s,a.index=r?r.array:null,a.indirectBuffer=o),a}static deserialize(e,t,n={}){n={setIndex:!0,indirect:!!e.indirectBuffer,...n};const{index:s,roots:o,indirectBuffer:r}=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(o));const a=new An(t,{...n,[wi]:!0});if(a._roots=o,a._indirectBuffer=r||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 w=0,x=h.byteLength/Ve;w<x;w++){const _=De*w,A=2*_;Ie(A,m)||(f[_+6]=f[_+6]/De-w)}}}}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,o=this._indirectBuffer,r=s.attributes.position,a=s.index?s.index.array:null,u=(o?o[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 w=r[Bs[m]](d),x=r[Bs[m]](h),_=r[Bs[m]](f);let A=w;x<A&&(A=x),_<A&&(A=_);let T=w;x>T&&(T=x),_>T&&(T=_),t[n+m]=A,t[n+m+3]=T}return t}computePrimitiveBounds(e,t,n){const s=this.geometry,o=this._indirectBuffer,r=s.attributes.position,a=s.index?s.index.array:null,c=r.normalized;if(e<0||t+e-n.offset>n.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const u=r.array,d=r.offset||0;let h=3;r.isInterleavedBufferAttribute&&(h=r.data.stride);const f=["getX","getY","getZ"],m=n.offset;for(let w=e,x=e+t;w<x;w++){const A=(o?o[w]:w)*3,T=(w-m)*6;let S=A+0,b=A+1,M=A+2;a&&(S=a[S],b=a[b],M=a[M]),c||(S=S*h+d,b=b*h+d,M=M*h+d);for(let P=0;P<3;P++){let L,C,D;c?(L=r[f[P]](S),C=r[f[P]](b),D=r[f[P]](M)):(L=u[S+P],C=u[b+P],D=u[M+P]);let I=L;C<I&&(I=C),D<I&&(I=D);let F=L;C>F&&(F=C),D>F&&(F=D);const N=(F-I)/2,H=P*2;n[T+H+0]=I+N,n[T+H+1]=N+(Math.abs(I)+N)*us}}return n}raycastObject3D(e,t,n=[]){const{material:s}=e;if(s===void 0)return;sr.copy(e.matrixWorld).invert(),ns.copy(t.ray).applyMatrix4(sr),ir.setFromMatrixScale(e.matrixWorld),nr.copy(ns.direction).multiply(ir);const o=nr.length(),r=t.near/o,a=t.far/o;if(t.firstHitOnly===!0){let c=this.raycastFirst(ns,s,r,a);c=tr(c,e,t),c&&n.push(c)}else{const c=this.raycast(ns,s,r,a);for(let u=0,d=c.length;u<d;u++){const h=tr(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 o=this._roots,r=[],a=this.indirect?Ja:ja;for(let c=0,u=o.length;c<u;c++)a(this,c,t,e,r,n,s);return r}raycastFirst(e,t=p.FrontSide,n=0,s=1/0){const o=this._roots;let r=null;const a=this.indirect?tc:Wa;for(let c=0,u=o.length;c<u;c++){const d=a(this,c,t,e,n,s);d!=null&&(r==null||d.distance<r.distance)&&(r=d)}return r}intersectsGeometry(e,t){let n=!1;const s=this._roots,o=this.indirect?nc:Za;for(let r=0,a=s.length;r<a&&(n=o(this,r,e,t),!n);r++);return n}shapecast(e){const t=rt.getPrimitive(),n=super.shapecast({...e,intersectsPrimitive:e.intersectsTriangle,scratchPrimitive:t,iterate:this.indirect?Ha:Ba});return rt.releasePrimitive(t),n}bvhcast(e,t,n){let{intersectsRanges:s,intersectsTriangles:o}=n;const r=rt.getPrimitive(),a=this.geometry.index,c=this.geometry.attributes.position,u=this.indirect?w=>{const x=this.resolveTriangleIndex(w);Le(r,x*3,a,c)}:w=>{Le(r,w*3,a,c)},d=rt.getPrimitive(),h=e.geometry.index,f=e.geometry.attributes.position,m=e.indirect?w=>{const x=e.resolveTriangleIndex(w);Le(d,x*3,h,f)}:w=>{Le(d,w*3,h,f)};if(o){if(!(e instanceof An))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const w=(x,_,A,T,S,b,M,P)=>{for(let L=A,C=A+T;L<C;L++){m(L),d.a.applyMatrix4(t),d.b.applyMatrix4(t),d.c.applyMatrix4(t),d.needsUpdate=!0;for(let D=x,I=x+_;D<I;D++)if(u(D),r.needsUpdate=!0,o(r,d,D,L,S,b,M,P))return!0}return!1};if(s){const x=s;s=function(_,A,T,S,b,M,P,L){return x(_,A,T,S,b,M,P,L)?!0:w(_,A,T,S,b,M,P,L)}}else s=w}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={},o=0,r=1/0){return(this.indirect?ac:$a)(this,e,t,n,s,o,r)}closestPointToPoint(e,t={},n=0,s=1/0){return Oa(this,e,t,n,s)}}const en={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=en.Mesh;else if(this instanceof p.LineSegments)n=en.LineSegments;else if(this instanceof p.LineLoop)n=en.LineLoop;else if(this instanceof p.Line)n=en.Line;else if(this instanceof p.Points)n=en.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,o=this.matrixWorld;Ue.material=this.material,Ue.geometry=this.geometry;const r=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(o),!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=r,Ue.geometry.drawRange=a,Ue.material=null,Ue.geometry=null}else en.BatchedMesh.call(this,i,e)}function Nr(i){i.traverse(e=>{var s,o,r;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)||(r=(o=n.morphAttributes)==null?void 0:o.position)!=null&&r.length||(n.boundsTree||(n.boundsTree=new An(n)),t.raycast=cc)})}function hc(i){i.boundsTree&&(i.boundsTree=void 0)}function rr(i){const e=i;for(const n of Object.keys(e)){const s=e[n];s instanceof E.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 E.Texture&&n.value.dispose();i.dispose()}function xs(i){i.traverse(e=>{var o;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(rr):n&&rr(n);const s=e;s.isLight&&((o=s.shadow)!=null&&o.dispose)&&s.shadow.dispose()})}function uc(i,e){if(!(e!=null&&e.keepBackgrounds)){i.background instanceof E.Texture&&(i.background.dispose(),i.background=null),i.environment instanceof E.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 Ke{constructor(e){this.object=e,this.positionAdapter=Ot.fromThreeVector(e.position),this.rotationAdapter=Ot.fromThreeVector(e.rotation),this.scaleAdapter=Ot.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 Ke?(this.object.add(e.getThreeObject()),k.ok(void 0)):k.err(new Z("Child must be a ThreeObject3DAdapter",X.INVALID_PARAMETER))}catch(t){return k.err(new Z("Failed to add child object",X.SCENE_OPERATION_FAILED,{originalError:t}))}}remove(e){try{return e instanceof Ke?(this.object.remove(e.getThreeObject()),k.ok(void 0)):k.err(new Z("Child must be a ThreeObject3DAdapter",X.INVALID_PARAMETER))}catch(t){return k.err(new Z("Failed to remove child object",X.SCENE_OPERATION_FAILED,{originalError:t}))}}traverse(e){this.object.traverse(t=>{e(new Ke(t))})}clone(){return new Ke(this.object.clone())}dispose(){xs(this.object)}getThreeObject(){return this.object}static fromThreeObject(e){return new Ke(e)}static create(){return new Ke(new E.Object3D)}}class kr{constructor(e){this.scene=e||new E.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 Ke?(this.scene.add(e.getThreeObject()),k.ok(void 0)):k.err(new Z("Object must be a ThreeObject3DAdapter",X.INVALID_PARAMETER))}catch(t){return k.err(new Z("Failed to add object to scene",X.SCENE_OPERATION_FAILED,{originalError:t}))}}remove(e){try{return e instanceof Ke?(this.scene.remove(e.getThreeObject()),k.ok(void 0)):k.err(new Z("Object must be a ThreeObject3DAdapter",X.INVALID_PARAMETER))}catch(t){return k.err(new Z("Failed to remove object from scene",X.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 Ke(t))})}get background(){return this.scene.background instanceof E.Color?new li(this.scene.background):this.scene.background instanceof E.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 or(this.scene.fog):null}set fog(e){e instanceof or?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 or{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 Fr extends Ke{constructor(e){super(e),this.camera=e}get near(){return this.camera instanceof E.PerspectiveCamera||this.camera instanceof E.OrthographicCamera?this.camera.near:.1}set near(e){(this.camera instanceof E.PerspectiveCamera||this.camera instanceof E.OrthographicCamera)&&(this.camera.near=e)}get far(){return this.camera instanceof E.PerspectiveCamera||this.camera instanceof E.OrthographicCamera?this.camera.far:1e3}set far(e){(this.camera instanceof E.PerspectiveCamera||this.camera instanceof E.OrthographicCamera)&&(this.camera.far=e)}lookAt(e){e instanceof Ot?this.camera.lookAt(e.getThreeVector()):this.camera.lookAt(e.x,e.y,e.z)}updateProjectionMatrix(){(this.camera instanceof E.PerspectiveCamera||this.camera instanceof E.OrthographicCamera)&&this.camera.updateProjectionMatrix()}getWorldDirection(e){const t=new E.Vector3;this.camera.getWorldDirection(t),e.set(t.x,t.y,t.z)}getInternalRenderer(){return this.camera}getThreeCamera(){return this.camera}}class Si extends Fr{constructor(e){const t=e||new E.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 Si(new E.PerspectiveCamera(e,t,n,s))}}class dc{constructor(e){this.renderer=null,this._id=vr(),this.canvas=e}get id(){return this._id}initialize(e){try{if(this.renderer=new E.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:E.BasicShadowMap,pcf:E.PCFShadowMap,pcfsoft:E.PCFSoftShadowMap,vsm:E.VSMShadowMap};this.renderer.shadowMap.type=t[e.shadowMap.type]}if(e.toneMapping){const t={none:E.NoToneMapping,linear:E.LinearToneMapping,reinhard:E.ReinhardToneMapping,cineon:E.CineonToneMapping,aces:E.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=E.SRGBColorSpace,k.ok(void 0)}catch(t){return k.err(new Z("Failed to initialize renderer",X.RENDERER_INIT_FAILED,{originalError:t,options:e}))}}render(e,t){if(!this.renderer)return k.err(new Z("Renderer not initialized",X.RENDERER_NOT_INITIALIZED));try{if(!(e instanceof kr))return k.err(new Z("Scene must be a ThreeSceneAdapter",X.INVALID_PARAMETER));if(!(t instanceof Fr))return k.err(new Z("Camera must be a ThreeCameraAdapter",X.INVALID_PARAMETER));const n=e.getThreeScene(),s=t.getThreeCamera();return this.renderer.render(n,s),k.ok(void 0)}catch(n){return k.err(new Z("Failed to render frame",X.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 ar(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 r=[],a=i.getAttribute("position");if(a!==void 0){for(let c=0;c<a.count;c++)r.push(c);i.setIndex(r),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 r=1;r<=n;r++)s.push(t.getX(0)),s.push(t.getX(r)),s.push(t.getX(r+1));else for(let r=0;r<n;r++)r%2===0?(s.push(t.getX(r)),s.push(t.getX(r+1)),s.push(t.getX(r+2))):(s.push(t.getX(r+2)),s.push(t.getX(r+1)),s.push(t.getX(r)));s.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const o=i.clone();return o.setIndex(s),o.clearGroups(),o}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 Br(i,n,function(s,o){e.set(o,s),t.set(s,o)}),n.traverse(function(s){if(!s.isSkinnedMesh)return;const o=s,r=e.get(s),a=r.skeleton.bones;o.skeleton=r.skeleton.clone(),o.bindMatrix.copy(r.bindMatrix),o.skeleton.bones=a.map(function(c){return t.get(c)}),o.bind(o.skeleton,o.bindMatrix)}),n}function Br(i,e,t){t(i,e);for(let n=0;n<i.children.length;n++)Br(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 Ec(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 wc(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 cr(t,le.EXT_MESHOPT_COMPRESSION)}),this.register(function(t){return new cr(t,le.KHR_MESHOPT_COMPRESSION)}),this.register(function(t){return new Pc(t)})}load(e,t,n,s){const o=this;let r;if(this.resourcePath!=="")r=this.resourcePath;else if(this.path!==""){const u=p.LoaderUtils.extractUrlBase(e);r=p.LoaderUtils.resolveURL(u,this.path)}else r=p.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const a=function(u){s?s(u):console.error(u),o.manager.itemError(e),o.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{o.parse(u,r,function(d){t(d),o.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 o;const r={},a={},c=new TextDecoder;if(typeof e=="string")o=JSON.parse(e);else if(e instanceof ArrayBuffer)if(c.decode(new Uint8Array(e,0,4))===zr){try{r[le.KHR_BINARY_GLTF]=new Oc(e)}catch(h){s&&s(h);return}o=JSON.parse(r[le.KHR_BINARY_GLTF].content)}else o=JSON.parse(c.decode(e));else o=e;if(o.asset===void 0||o.asset.version[0]<2){s&&s(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const u=new Zc(o,{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,r[h.name]=!0}if(o.extensionsUsed)for(let d=0;d<o.extensionsUsed.length;++d){const h=o.extensionsUsed[d],f=o.extensionsRequired||[];switch(h){case le.KHR_MATERIALS_UNLIT:r[h]=new yc;break;case le.KHR_DRACO_MESH_COMPRESSION:r[h]=new Dc(o,this.dracoLoader);break;case le.KHR_TEXTURE_TRANSFORM:r[h]=new Nc;break;case le.KHR_MESH_QUANTIZATION:r[h]=new kc;break;default:f.indexOf(h)>=0&&a[h]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+h+'".')}}u.setExtensions(r),u.setPlugins(a),u.parse(n,s)}parseAsync(e,t){const n=this;return new Promise(function(s,o){n.parse(e,t,s,o)})}}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 Re(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 o=t[n];o.extensions&&o.extensions[this.name]&&o.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,o.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let s=t.cache.get(n);if(s)return s;const o=t.json,c=((o.extensions&&o.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,o=n.json.nodes[e],a=(o.extensions&&o.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 o=t.pbrMetallicRoughness;if(o){if(Array.isArray(o.baseColorFactor)){const r=o.baseColorFactor;e.color.setRGB(r[0],r[1],r[2],p.LinearSRGBColorSpace),e.opacity=r[3]}o.baseColorTexture!==void 0&&s.push(n.assignTexture(e,"map",o.baseColorTexture,p.SRGBColorSpace))}return Promise.all(s)}}class wc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);return n===null||n.emissiveStrength!==void 0&&(t.emissiveIntensity=n.emissiveStrength),Promise.resolve()}}class Ec{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(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 o=n.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new p.Vector2(o,o)}return Promise.all(s)}}class Tc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_DISPERSION}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(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 Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(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 Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(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 o=n.sheenColorFactor;t.sheenColor.setRGB(o[0],o[1],o[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 Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(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 Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(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 o=n.attenuationColor||[1,1,1];return t.attenuationColor=new p.Color().setRGB(o[0],o[1],o[2],p.LinearSRGBColorSpace),Promise.all(s)}}class Ac{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_IOR}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(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 Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(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 o=n.specularColorFactor||[1,1,1];return t.specularColor=new p.Color().setRGB(o[0],o[1],o[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 Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(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 Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(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 o=s.extensions[this.name],r=t.options.ktx2Loader;if(!r){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,o.source,r)}}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,o=s.textures[e];if(!o.extensions||!o.extensions[t])return null;const r=o.extensions[t],a=s.images[r.source];let c=n.textureLoader;if(a.uri){const u=n.options.manager.getHandler(a.uri);u!==null&&(c=u)}return n.loadTextureImage(e,r.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,o=s.textures[e];if(!o.extensions||!o.extensions[t])return null;const r=o.extensions[t],a=s.images[r.source];let c=n.textureLoader;if(a.uri){const u=n.options.manager.getHandler(a.uri);u!==null&&(c=u)}return n.loadTextureImage(e,r.source,c)}}class cr{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],o=this.parser.getDependency("buffer",s.buffer),r=this.parser.options.meshoptDecoder;if(!r||!r.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 o.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 r.decodeGltfBufferAsync?r.decodeGltfBufferAsync(d,h,f,s.mode,s.filter).then(function(m){return m.buffer}):r.ready.then(function(){const m=new ArrayBuffer(d*h);return r.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 r=n.extensions[this.name].attributes,a=[],c={};for(const u in r)a.push(this.parser.getDependency("accessor",r[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 w of h){const x=new p.Matrix4,_=new p.Vector3,A=new p.Quaternion,T=new p.Vector3(1,1,1),S=new p.InstancedMesh(w.geometry,w.material,f);for(let b=0;b<f;b++)c.TRANSLATION&&_.fromBufferAttribute(c.TRANSLATION,b),c.ROTATION&&A.fromBufferAttribute(c.ROTATION,b),c.SCALE&&T.fromBufferAttribute(c.SCALE,b),S.setMatrixAt(b,x.compose(_,A,T));for(const b in c)if(b==="_COLOR_0"){const M=c[b];S.instanceColor=new p.InstancedBufferAttribute(M.array,M.itemSize,M.normalized)}else b!=="TRANSLATION"&&b!=="ROTATION"&&b!=="SCALE"&&w.geometry.setAttribute(b,c[b]);p.Object3D.prototype.copy.call(S,w),this.parser.assignFinalMaterial(S),m.push(S)}return d.isGroup?(d.clear(),d.add(...m),d):m[0]}))}}const zr="glTF",wn=12,lr={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,wn),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!==zr)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-wn,o=new DataView(e,wn);let r=0;for(;r<s;){const a=o.getUint32(r,!0);r+=4;const c=o.getUint32(r,!0);if(r+=4,c===lr.JSON){const u=new Uint8Array(e,wn+r,a);this.content=n.decode(u)}else if(c===lr.BIN){const u=wn+r;this.body=e.slice(u,u+a)}r+=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,o=e.extensions[this.name].bufferView,r=e.extensions[this.name].attributes,a={},c={},u={};for(const d in r){const h=hi[d]||d.toLowerCase();a[h]=r[d]}for(const d in e.attributes){const h=hi[d]||d.toLowerCase();if(r[d]!==void 0){const f=n.accessors[e.attributes[d]],m=sn[f.componentType];u[h]=m.name,c[h]=f.normalized===!0}}return t.getDependency("bufferView",o).then(function(d){return new Promise(function(h,f){s.decodeDracoFile(d,function(m){for(const w in m.attributes){const x=m.attributes[w],_=c[w];_!==void 0&&(x.normalized=_)}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 Ur 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,o=e*s*3+s;for(let r=0;r!==s;r++)t[r]=n[o+r];return t}interpolate_(e,t,n,s){const o=this.resultBuffer,r=this.sampleValues,a=this.valueSize,c=a*2,u=a*3,d=s-t,h=(n-t)/d,f=h*h,m=f*h,w=e*u,x=w-u,_=-2*m+3*f,A=m-f,T=1-_,S=A-f+h;for(let b=0;b!==a;b++){const M=r[x+b+a],P=r[x+b+c]*d,L=r[w+b+a],C=r[w+b]*d;o[b]=T*M+S*P+_*L+A*C}return o}}const Fc=new p.Quaternion;class Bc extends Ur{interpolate_(e,t,n,s){const o=super.interpolate_(e,t,n,s);return Fc.fromArray(o).normalize().toArray(o),o}}const st={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},sn={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},hr={9728:p.NearestFilter,9729:p.LinearFilter,9984:p.NearestMipmapNearestFilter,9985:p.LinearMipmapNearestFilter,9986:p.NearestMipmapLinearFilter,9987:p.LinearMipmapLinearFilter},ur={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"},vt={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 zt(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 Vc(i,e,t){let n=!1,s=!1,o=!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&&(o=!0),n&&s&&o)break}if(!n&&!s&&!o)return Promise.resolve(i);const r=[],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;r.push(f)}if(s){const f=h.NORMAL!==void 0?t.getDependency("accessor",h.NORMAL):i.attributes.normal;a.push(f)}if(o){const f=h.COLOR_0!==void 0?t.getDependency("accessor",h.COLOR_0):i.attributes.color;c.push(f)}}return Promise.all([Promise.all(r),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),o&&(i.morphAttributes.color=f),i.morphTargetsRelative=!0,i})}function Hc(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+":"+Vs(t.attributes):e=i.indices+":"+Vs(i.attributes)+":"+i.mode,i.targets!==void 0)for(let n=0,s=i.targets.length;n<s;n++)e+=":"+Vs(i.targets[n]);return e}function Vs(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,o=!1,r=-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,o=a.indexOf("Firefox")>-1,r=o?a.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&s<17||o&&r<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,o=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(r){return r._markDefs&&r._markDefs()}),Promise.all(this._invokeAll(function(r){return r.beforeRoot&&r.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(r){const a={scene:r[0][s.scene||0],scenes:r[0],animations:r[1],cameras:r[2],asset:s.asset,parser:n,userData:{}};return zt(o,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,o=t.length;s<o;s++){const r=t[s].joints;for(let a=0,c=r.length;a<c;a++)e[r[a]].isBone=!0}for(let s=0,o=e.length;s<o;s++){const r=e[s];r.mesh!==void 0&&(this._addNodeRef(this.meshCache,r.mesh),r.skin!==void 0&&(n[r.mesh].isSkinnedMesh=!0)),r.camera!==void 0&&this._addNodeRef(this.cameraCache,r.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(),o=(r,a)=>{const c=this.associations.get(r);c!=null&&this.associations.set(a,c);for(const[u,d]of r.children.entries())o(d,a.children[u])};return o(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 o=e(t[s]);o&&n.push(o)}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(o){return o.loadNode&&o.loadNode(t)});break;case"mesh":s=this._invokeOne(function(o){return o.loadMesh&&o.loadMesh(t)});break;case"accessor":s=this.loadAccessor(t);break;case"bufferView":s=this._invokeOne(function(o){return o.loadBufferView&&o.loadBufferView(t)});break;case"buffer":s=this.loadBuffer(t);break;case"material":s=this._invokeOne(function(o){return o.loadMaterial&&o.loadMaterial(t)});break;case"texture":s=this._invokeOne(function(o){return o.loadTexture&&o.loadTexture(t)});break;case"skin":s=this.loadSkin(t);break;case"animation":s=this._invokeOne(function(o){return o.loadAnimation&&o.loadAnimation(t)});break;case"camera":s=this.loadCamera(t);break;default:if(s=this._invokeOne(function(o){return o!=this&&o.getDependency&&o.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(o,r){return n.getDependency(e,r)})),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(o,r){n.load(p.LoaderUtils.resolveURL(t.uri,s.path),o,void 0,function(){r(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,o=t.byteOffset||0;return n.slice(o,o+s)})}loadAccessor(e){const t=this,n=this.json,s=this.json.accessors[e];if(s.bufferView===void 0&&s.sparse===void 0){const r=zs[s.type],a=sn[s.componentType],c=s.normalized===!0,u=new a(s.count*r);return Promise.resolve(new p.BufferAttribute(u,r,c))}const o=[];return s.bufferView!==void 0?o.push(this.getDependency("bufferView",s.bufferView)):o.push(null),s.sparse!==void 0&&(o.push(this.getDependency("bufferView",s.sparse.indices.bufferView)),o.push(this.getDependency("bufferView",s.sparse.values.bufferView))),Promise.all(o).then(function(r){const a=r[0],c=zs[s.type],u=sn[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,w=s.normalized===!0;let x,_;if(m&&m!==h){const A=Math.floor(f/m),T="InterleavedBuffer:"+s.bufferView+":"+s.componentType+":"+A+":"+s.count;let S=t.cache.get(T);S||(x=new u(a,A*m,s.count*m/d),S=new p.InterleavedBuffer(x,m/d),t.cache.add(T,S)),_=new p.InterleavedBufferAttribute(S,c,f%m/d,w)}else a===null?x=new u(s.count*c):x=new u(a,f,s.count*c),_=new p.BufferAttribute(x,c,w);if(s.sparse!==void 0){const A=zs.SCALAR,T=sn[s.sparse.indices.componentType],S=s.sparse.indices.byteOffset||0,b=s.sparse.values.byteOffset||0,M=new T(r[1],S,s.sparse.count*A),P=new u(r[2],b,s.sparse.count*c);a!==null&&(_=new p.BufferAttribute(_.array.slice(),_.itemSize,_.normalized)),_.normalized=!1;for(let L=0,C=M.length;L<C;L++){const D=M[L];if(_.setX(D,P[L*c]),c>=2&&_.setY(D,P[L*c+1]),c>=3&&_.setZ(D,P[L*c+2]),c>=4&&_.setW(D,P[L*c+3]),c>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}_.normalized=w}return _})}loadTexture(e){const t=this.json,n=this.options,o=t.textures[e].source,r=t.images[o];let a=this.textureLoader;if(r.uri){const c=n.manager.getHandler(r.uri);c!==null&&(a=c)}return this.loadTextureImage(e,o,a)}loadTextureImage(e,t,n){const s=this,o=this.json,r=o.textures[e],a=o.images[t],c=(a.uri||a.bufferView)+":"+r.sampler;if(this.textureCache[c])return this.textureCache[c];const u=this.loadImageSource(t,n).then(function(d){d.flipY=!1,d.name=r.name||a.name||"",d.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(d.name=a.uri);const f=(o.samplers||{})[r.sampler]||{};return d.magFilter=hr[f.magFilter]||p.LinearFilter,d.minFilter=hr[f.minFilter]||p.LinearMipmapLinearFilter,d.wrapS=ur[f.wrapS]||p.RepeatWrapping,d.wrapT=ur[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,o=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(h=>h.clone());const r=s.images[e],a=self.URL||self.webkitURL;let c=r.uri||"",u=!1;if(r.bufferView!==void 0)c=n.getDependency("bufferView",r.bufferView).then(function(h){u=!0;const f=new Blob([h],{type:r.mimeType});return c=a.createObjectURL(f),c});else if(r.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 w=f;t.isImageBitmapLoader===!0&&(w=function(x){const _=new p.Texture(x);_.needsUpdate=!0,f(_)}),t.load(p.LoaderUtils.resolveURL(h,o.path),w,void 0,m)})}).then(function(h){return u===!0&&a.revokeObjectURL(c),yt(h,r),h.userData.mimeType=r.mimeType||Gc(r.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 o=this;return this.getDependency("texture",n.index).then(function(r){if(!r)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(r=r.clone(),r.channel=n.texCoord),o.extensions[le.KHR_TEXTURE_TRANSFORM]){const a=n.extensions!==void 0?n.extensions[le.KHR_TEXTURE_TRANSFORM]:void 0;if(a){const c=o.associations.get(r);r=o.extensions[le.KHR_TEXTURE_TRANSFORM].extendTexture(r,a),o.associations.set(r,c)}}return s!==void 0&&(r.colorSpace=s),e[t]=r,r})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const s=t.attributes.tangent===void 0,o=t.attributes.color!==void 0,r=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||o||r){let a="ClonedMaterial:"+n.uuid+":";s&&(a+="derivative-tangents:"),o&&(a+="vertex-colors:"),r&&(a+="flat-shading:");let c=this.cache.get(a);c||(c=n.clone(),o&&(c.vertexColors=!0),r&&(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,o=n.materials[e];let r;const a={},c=o.extensions||{},u=[];if(c[le.KHR_MATERIALS_UNLIT]){const h=s[le.KHR_MATERIALS_UNLIT];r=h.getMaterialType(),u.push(h.extendParams(a,o,t))}else{const h=o.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))),r=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)})))}o.doubleSided===!0&&(a.side=p.DoubleSide);const d=o.alphaMode||Us.OPAQUE;if(d===Us.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,d===Us.MASK&&(a.alphaTest=o.alphaCutoff!==void 0?o.alphaCutoff:.5)),o.normalTexture!==void 0&&r!==p.MeshBasicMaterial&&(u.push(t.assignTexture(a,"normalMap",o.normalTexture)),a.normalScale=new p.Vector2(1,1),o.normalTexture.scale!==void 0)){const h=o.normalTexture.scale;a.normalScale.set(h,h)}if(o.occlusionTexture!==void 0&&r!==p.MeshBasicMaterial&&(u.push(t.assignTexture(a,"aoMap",o.occlusionTexture)),o.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=o.occlusionTexture.strength)),o.emissiveFactor!==void 0&&r!==p.MeshBasicMaterial){const h=o.emissiveFactor;a.emissive=new p.Color().setRGB(h[0],h[1],h[2],p.LinearSRGBColorSpace)}return o.emissiveTexture!==void 0&&r!==p.MeshBasicMaterial&&u.push(t.assignTexture(a,"emissiveMap",o.emissiveTexture,p.SRGBColorSpace)),Promise.all(u).then(function(){const h=new r(a);return o.name&&(h.name=o.name),yt(h,o),t.associations.set(h,{materials:e}),o.extensions&&zt(s,h,o),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 o(a){return n[le.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,t).then(function(c){return dr(c,a,t)})}const r=[];for(let a=0,c=e.length;a<c;a++){const u=e[a],d=jc(u),h=s[d];if(h)r.push(h.promise);else{let f;u.extensions&&u.extensions[le.KHR_DRACO_MESH_COMPRESSION]?f=o(u):f=dr(new p.BufferGeometry,u,t),s[d]={primitive:u,promise:f},r.push(f)}}return Promise.all(r)}loadMesh(e){const t=this,n=this.json,s=this.extensions,o=n.meshes[e],r=o.primitives,a=[];for(let c=0,u=r.length;c<u;c++){const d=r[c].material===void 0?Uc(this.cache):this.getDependency("material",r[c].material);a.push(d)}return a.push(t.loadGeometries(r)),Promise.all(a).then(function(c){const u=c.slice(0,c.length-1),d=c[c.length-1],h=[];for(let m=0,w=d.length;m<w;m++){const x=d[m],_=r[m];let A;const T=u[m];if(_.mode===st.TRIANGLES||_.mode===st.TRIANGLE_STRIP||_.mode===st.TRIANGLE_FAN||_.mode===void 0)A=o.isSkinnedMesh===!0?new p.SkinnedMesh(x,T):new p.Mesh(x,T),A.isSkinnedMesh===!0&&A.normalizeSkinWeights(),_.mode===st.TRIANGLE_STRIP?A.geometry=ar(A.geometry,p.TriangleStripDrawMode):_.mode===st.TRIANGLE_FAN&&(A.geometry=ar(A.geometry,p.TriangleFanDrawMode));else if(_.mode===st.LINES)A=new p.LineSegments(x,T);else if(_.mode===st.LINE_STRIP)A=new p.Line(x,T);else if(_.mode===st.LINE_LOOP)A=new p.LineLoop(x,T);else if(_.mode===st.POINTS)A=new p.Points(x,T);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+_.mode);Object.keys(A.geometry.morphAttributes).length>0&&Hc(A,o),A.name=t.createUniqueName(o.name||"mesh_"+e),yt(A,o),_.extensions&&zt(s,A,_),t.assignFinalMaterial(A),h.push(A)}for(let m=0,w=h.length;m<w;m++)t.associations.set(h[m],{meshes:e,primitives:m});if(h.length===1)return o.extensions&&zt(s,h[0],o),h[0];const f=new p.Group;o.extensions&&zt(s,f,o),t.associations.set(f,{meshes:e});for(let m=0,w=h.length;m<w;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,o=t.joints.length;s<o;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 o=s.pop(),r=s,a=[],c=[];for(let u=0,d=r.length;u<d;u++){const h=r[u];if(h){a.push(h);const f=new p.Matrix4;o!==null&&f.fromArray(o.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],o=s.name?s.name:"animation_"+e,r=[],a=[],c=[],u=[],d=[];for(let h=0,f=s.channels.length;h<f;h++){const m=s.channels[h],w=s.samplers[m.sampler],x=m.target,_=x.node,A=s.parameters!==void 0?s.parameters[w.input]:w.input,T=s.parameters!==void 0?s.parameters[w.output]:w.output;x.node!==void 0&&(r.push(this.getDependency("node",_)),a.push(this.getDependency("accessor",A)),c.push(this.getDependency("accessor",T)),u.push(w),d.push(x))}return Promise.all([Promise.all(r),Promise.all(a),Promise.all(c),Promise.all(u),Promise.all(d)]).then(function(h){const f=h[0],m=h[1],w=h[2],x=h[3],_=h[4],A=[];for(let S=0,b=f.length;S<b;S++){const M=f[S],P=m[S],L=w[S],C=x[S],D=_[S];if(M===void 0)continue;M.updateMatrix&&M.updateMatrix();const I=n._createAnimationTracks(M,P,L,C,D);if(I)for(let F=0;F<I.length;F++)A.push(I[F])}const T=new p.AnimationClip(o,void 0,A);return yt(T,s),T})}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(o){const r=n._getNodeRef(n.meshCache,s.mesh,o);return s.weights!==void 0&&r.traverse(function(a){if(a.isMesh)for(let c=0,u=s.weights.length;c<u;c++)a.morphTargetInfluences[c]=s.weights[c]}),r})}loadNode(e){const t=this.json,n=this,s=t.nodes[e],o=n._loadNodeShallow(e),r=[],a=s.children||[];for(let u=0,d=a.length;u<d;u++)r.push(n.getDependency("node",a[u]));const c=s.skin===void 0?Promise.resolve(null):n.getDependency("skin",s.skin);return Promise.all([o,Promise.all(r),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,w=h.length;m<w;m++)d.add(h[m]);if(d.userData.pivot!==void 0&&h.length>0){const m=d.userData.pivot,w=h[0];d.pivot=new p.Vector3().fromArray(m),d.position.x-=m[0],d.position.y-=m[1],d.position.z-=m[2],w.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 o=t.nodes[e],r=o.name?s.createUniqueName(o.name):"",a=[],c=s._invokeOne(function(u){return u.createNodeMesh&&u.createNodeMesh(e)});return c&&a.push(c),o.camera!==void 0&&a.push(s.getDependency("camera",o.camera).then(function(u){return s._getNodeRef(s.cameraCache,o.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(o.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(o.name&&(d.userData.name=o.name,d.name=r),yt(d,o),o.extensions&&zt(n,d,o),o.matrix!==void 0){const h=new p.Matrix4;h.fromArray(o.matrix),d.applyMatrix4(h)}else o.translation!==void 0&&d.position.fromArray(o.translation),o.rotation!==void 0&&d.quaternion.fromArray(o.rotation),o.scale!==void 0&&d.scale.fromArray(o.scale);if(!s.associations.has(d))s.associations.set(d,{});else if(o.mesh!==void 0&&s.meshCache.refs[o.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,o=new p.Group;n.name&&(o.name=s.createUniqueName(n.name)),yt(o,n),n.extensions&&zt(t,o,n);const r=n.nodes||[],a=[];for(let c=0,u=r.length;c<u;c++)a.push(s.getDependency("node",r[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?o.add(fc(f)):o.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(o),o})}_createAnimationTracks(e,t,n,s,o){const r=[],a=e.name?e.name:e.uuid,c=[];function u(m){m.morphTargetInfluences&&c.push(m.name?m.name:m.uuid)}vt[o.path]===vt.weights?(u(e),e.isGroup&&e.children.forEach(u)):c.push(a);let d;switch(vt[o.path]){case vt.weights:d=p.NumberKeyframeTrack;break;case vt.rotation:d=p.QuaternionKeyframeTrack;break;case vt.translation:case vt.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,w=c.length;m<w;m++){const x=new d(c[m]+"."+vt[o.path],t.array,f,h);s.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(x),r.push(x)}return r}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const n=ui(t.constructor),s=new Float32Array(t.length);for(let o=0,r=t.length;o<r;o++)s[o]=t[o]*n;t=s}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){const s=this instanceof p.QuaternionKeyframeTrack?Bc:Ur;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(sn[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 o=e.targets;if(o!==void 0){const a=new p.Vector3,c=new p.Vector3;for(let u=0,d=o.length;u<d;u++){const h=o[u];if(h.POSITION!==void 0){const f=t.json.accessors[h.POSITION],m=f.min,w=f.max;if(m!==void 0&&w!==void 0){if(c.setX(Math.max(Math.abs(m[0]),Math.abs(w[0]))),c.setY(Math.max(Math.abs(m[1]),Math.abs(w[1]))),c.setZ(Math.max(Math.abs(m[2]),Math.abs(w[2]))),f.normalized){const x=ui(sn[f.componentType]);c.multiplyScalar(x)}a.max(c)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}s.expandByVector(a)}i.boundingBox=s;const r=new p.Sphere;s.getCenter(r.center),r.radius=s.min.distanceTo(s.max)/2,i.boundingSphere=r}function dr(i,e,t){const n=e.attributes,s=[];function o(r,a){return t.getDependency("accessor",r).then(function(c){i.setAttribute(a,c)})}for(const r in n){const a=hi[r]||r.toLowerCase();a in i.attributes||s.push(o(n[r],a))}if(e.indices!==void 0&&!i.index){const r=t.getDependency("accessor",e.indices).then(function(a){i.setIndex(a)});s.push(r)}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?Vc(i,e.targets,t):i})}const Xc=E.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 E.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 r;(this.config.bvh??!0)&&Nr(s.scene),s.scene.animations=s.animations;const o={scene:new Ke(s.scene),animations:this.convertAnimations(s.animations),cameras:(r=s.cameras)==null?void 0:r.map(a=>{const c=a instanceof E.PerspectiveCamera,u=a instanceof E.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(k.ok(o))},s=>{s.total>0&&(t==null||t(s.loaded,s.total))},s=>{n(k.err(new Z("Failed to load GLTF model",X.MODEL_LOAD_FAILED,{url:e,originalError:s})))})})}catch(n){return k.err(new Z("Failed to initiate model loading",X.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 E.VectorKeyframeTrack?"vector":e instanceof E.QuaternionKeyframeTrack?"quaternion":e instanceof E.NumberKeyframeTrack?"number":e instanceof E.BooleanKeyframeTrack?"boolean":"number"}}class fr{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 Z(`Unsupported file format: ${n}`,X.UNSUPPORTED_FORMAT,{url:e,extension:n})}}}const pr={type:"change"},_i={type:"start"},Hr={type:"end"},rs=new p.Ray,mr=new p.Plane,Qc=Math.cos(70*p.MathUtils.DEG2RAD),Pe=new p.Vector3,$e=2*Math.PI,Ee={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},Hs=1e-6;class jr extends p.Controls{constructor(e,t=null){super(e,t),this.state=Ee.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(pr),this.update(),this.state=Ee.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;Pe.copy(t).sub(this.target),Pe.applyQuaternion(this._quat),this._spherical.setFromVector3(Pe),this.autoRotate&&this.state===Ee.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 o=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const r=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),o=r!=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 r=null;if(this.object.isPerspectiveCamera){const a=Pe.length();r=this._clampDistance(a*this._scale);const c=a-r;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),o=!!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(),o=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(),r=Pe.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;r!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(r).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):(mr.setFromNormalAndCoplanarPoint(this.object.up,this.target),rs.intersectPlane(mr,this.target))))}else if(this.object.isOrthographicCamera){const r=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),r!==this.object.zoom&&(this.object.updateProjectionMatrix(),o=!0)}return this._scale=1,this._performCursorZoom=!1,o||this._lastPosition.distanceToSquared(this.object.position)>Hs||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Hs||this._lastTargetPosition.distanceToSquared(this.target)>Hs?(this.dispatchEvent(pr),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){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 o=Pe.length();o*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*o/n.clientHeight,this.object.matrix),this._panUp(2*t*o/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,o=t-n.top,r=n.width,a=n.height;this._mouse.x=s/r*2-1,this._mouse.y=-(o/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,o=Math.sqrt(n*n+s*s);this._dollyStart.set(0,o)}_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),o=.5*(e.pageY+n.y);this._rotateEnd.set(s,o)}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,o=Math.sqrt(n*n+s*s);this._dollyEnd.set(0,o),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 r=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(r,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(Hr),this.state=Ee.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=Ee.DOLLY;break;case p.MOUSE.ROTATE:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=Ee.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=Ee.ROTATE}break;case p.MOUSE.PAN:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=Ee.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=Ee.PAN}break;default:this.state=Ee.NONE}this.state!==Ee.NONE&&this.dispatchEvent(_i)}function sl(i){switch(this.state){case Ee.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(i);break;case Ee.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(i);break;case Ee.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(i);break}}function il(i){this.enabled===!1||this.enableZoom===!1||this.state!==Ee.NONE||(i.preventDefault(),this.dispatchEvent(_i),this._handleMouseWheel(this._customWheelEvent(i)),this.dispatchEvent(Hr))}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=Ee.TOUCH_ROTATE;break;case p.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(i),this.state=Ee.TOUCH_PAN;break;default:this.state=Ee.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=Ee.TOUCH_DOLLY_PAN;break;case p.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(i),this.state=Ee.TOUCH_DOLLY_ROTATE;break;default:this.state=Ee.NONE}break;default:this.state=Ee.NONE}this.state!==Ee.NONE&&this.dispatchEvent(_i)}function al(i){switch(this._trackPointer(i),this.state){case Ee.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(i),this.update();break;case Ee.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(i),this.update();break;case Ee.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(i),this.update();break;case Ee.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(i),this.update();break;default:this.state=Ee.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 jr{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 Gr{constructor(e){this.controls=e,this.targetAdapter=Ot.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 Gr{constructor(e,t){super(new jr(e,t))}get type(){return"orbit"}}class fl extends Gr{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 di="contact-shadow-baked",rn="contact-shadow-live",bi="softboxContactShadowHelper",gr=Math.PI*(3-Math.sqrt(5)),xe=class xe{constructor(e){this.explicitPasses=e==null?void 0:e.passes}bake(e){const{renderer:t,scene:n,object:s,light:o}=e;if(t.getContext().isContextLost()){this.leaveLiveCatcherInCharge(n);return}const r=this.measureBakeRegion(s);if(!r)return;const a=n.getObjectByName(rn);(a==null?void 0:a.geometry)instanceof E.CircleGeometry&&(r.halfExtent=Math.min(r.halfExtent,a.geometry.parameters.radius));const c=new E.WebGLRenderTarget(xe.ACCUMULATION_TEXTURE_SIZE,xe.ACCUMULATION_TEXTURE_SIZE,{type:t.capabilities.isWebGL2?E.HalfFloatType:E.UnsignedByteType,depthBuffer:!1,stencilBuffer:!1}),u=new E.CircleGeometry(r.halfExtent,64);if(this.accumulateShadowPasses(t,s,o,r,c,u),t.getContext().isContextLost()){c.dispose(),u.dispose(),this.leaveLiveCatcherInCharge(n),console.warn("Contact-shadow bake aborted: WebGL context was lost mid-bake");return}this.installBakedMesh(n,r,c,u)}leaveLiveCatcherInCharge(e){this.evictBakedMesh(e);const t=e.getObjectByName(rn);t&&(t.visible=!0)}evictBakedMesh(e){const t=e.getObjectByName(di);t&&(e.remove(t),xs(t))}measureBakeRegion(e){const t=new E.Box3().setFromObject(e);if(t.isEmpty()||!Number.isFinite(t.min.x)||!Number.isFinite(t.max.x))return null;const n=t.getSize(new E.Vector3),s=t.getCenter(new E.Vector3),r=Math.max(Math.max(n.x,n.z)*1.6+n.y,.05);return{center:s,halfExtent:r,objectHeight:n.y}}accumulateShadowPasses(e,t,n,s,o,r){const a=new E.Scene,c=t.parent;a.add(t);const u=this.disableColorWrite(t),d=this.createBakeLight(n);a.add(d),a.add(d.target),d.target.position.copy(n.target.parent?n.target.getWorldPosition(new E.Vector3):n.target.position);const h=new E.ShadowMaterial({transparent:!0,opacity:0,depthWrite:!1});h.blending=E.CustomBlending,h.blendEquation=E.AddEquation,h.blendSrc=E.OneFactor,h.blendDst=E.OneFactor;const f=new E.Mesh(r,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 w=e.getRenderTarget(),x=e.autoClear,_=e.getClearColor(new E.Color),A=e.getClearAlpha(),T=e.shadowMap.autoUpdate;try{e.shadowMap.autoUpdate=!0,e.setRenderTarget(o),e.setClearColor(0,0),e.clear(!0,!1,!1),e.autoClear=!1;const S=this.explicitPasses??this.measureAffordablePasses(e,a,m,n,d,o);h.opacity=1/S;for(const b of this.sampleLightPositions(n,S))d.position.copy(b),e.render(a,m)}finally{e.autoClear=x,e.setClearColor(_,A),e.setRenderTarget(w),e.shadowMap.autoUpdate=T,this.restoreColorWrite(u),c?c.add(t):a.remove(t),d.dispose(),h.dispose()}}measureAffordablePasses(e,t,n,s,o,r){o.position.copy(s.position),e.render(t,n),this.awaitGpuIdle(e,r);const a=performance.now();e.render(t,n),this.awaitGpuIdle(e,r);const c=Math.max(performance.now()-a,.01);return E.MathUtils.clamp(Math.round(xe.BAKE_BUDGET_MS/c),xe.MIN_PASSES,xe.MAX_PASSES)}awaitGpuIdle(e,t){if(!e.capabilities.textureTypeReadable(t.texture.type))return;const n=t.texture.type===E.HalfFloatType?new Uint16Array(4):new Uint8Array(4);e.readRenderTargetPixels(t,0,0,1,1,n)}createBakeLight(e){const t=new E.DirectionalLight(16777215,1);t.castShadow=!0,t.shadow.mapSize.set(xe.BAKE_SHADOW_MAP_SIZE,xe.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 E.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,t){const n=e.position.clone(),s=e.target.parent?e.target.getWorldPosition(new E.Vector3):e.target.position.clone(),o=s.clone().sub(n),r=o.length(),a=o.normalize(),c=new E.Vector3().crossVectors(a,new E.Vector3(0,1,0));c.lengthSq()<1e-6&&c.set(1,0,0),c.normalize();const u=new E.Vector3().crossVectors(a,c),d=Math.round(t*xe.AMBIENT_RATIO),h=t-d,f=E.MathUtils.degToRad(xe.LIGHT_APERTURE_DEGREES),m=Math.tan(f/2)*r,w=[];for(let A=0;A<h;A++){const T=m*Math.sqrt((A+.5)/h),S=A*gr;w.push(n.clone().addScaledVector(c,T*Math.cos(S)).addScaledVector(u,T*Math.sin(S)))}const x=Math.sin(E.MathUtils.degToRad(xe.AMBIENT_MIN_ELEVATION_DEGREES)),_=.98;for(let A=0;A<d;A++){const T=Math.sqrt((A+.5)/d),S=x+(_-x)*T,b=Math.sqrt(1-S*S),M=A*gr;w.push(new E.Vector3(b*Math.cos(M),S,b*Math.sin(M)).multiplyScalar(r).add(s))}return w}installBakedMesh(e,t,n,s){this.evictBakedMesh(e);const o=new E.MeshBasicMaterial({map:n.texture,transparent:!0,opacity:xe.SHADOW_STRENGTH,depthWrite:!1,toneMapped:!1});o.onBeforeCompile=u=>{u.fragmentShader=u.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 r=new E.Mesh(s,o);r.name=di,r.userData[bi]=!0,r.rotation.x=-Math.PI/2;const a=E.MathUtils.clamp(t.objectHeight*.0025,2e-4,.01);r.position.set(t.center.x,a,t.center.z),r.userData.renderTarget=n,e.add(r);const c=e.getObjectByName(rn);c&&(c.visible=!1)}disableColorWrite(e){const t=new Map;return e.traverse(n=>{const s=n;if(!s.isMesh)return;const o=Array.isArray(s.material)?s.material:[s.material];for(const r of o)r&&!t.has(r)&&(t.set(r,r.colorWrite),r.colorWrite=!1)}),t}restoreColorWrite(e){e.forEach((t,n)=>{n.colorWrite=t})}};xe.AMBIENT_RATIO=.45,xe.LIGHT_APERTURE_DEGREES=9,xe.AMBIENT_MIN_ELEVATION_DEGREES=55,xe.ACCUMULATION_TEXTURE_SIZE=1024,xe.BAKE_SHADOW_MAP_SIZE=1024,xe.SHADOW_STRENGTH=.85,xe.BAKE_BUDGET_MS=100,xe.MIN_PASSES=24,xe.MAX_PASSES=96;let fi=xe;const on=(i,e)=>{if(i&&typeof i=="object"){const t=i[e];if(typeof t=="function")return t.call(i)}return null};function wt(i){return on(i,"getThreeObject")??(i instanceof E.Object3D?i:null)}function vn(i){return on(i,"getThreeCamera")??(i instanceof E.Camera?i:null)}function Et(i){return on(i,"getThreeScene")??(i instanceof E.Scene?i:null)}function pl(i){return on(i,"getThreeTexture")??(i instanceof E.Texture?i:null)}function Wr(i){return on(i,"getThreeRenderer")??(i instanceof E.WebGLRenderer?i:null)}function xi(i){return on(i,"getThreeControls")}var bt=(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))(bt||{});class ml{constructor(){this.name="Square Wire Grid"}createGrid(e){const t=e.size||10,n=e.divisions||10,s=new E.Color(e.color||8947848),o=new E.Color(e.centerLineColor||e.color||4473924),r=new E.GridHelper(t,n,o,s);if(e.opacity!==void 0&&e.opacity<1){const a=r.material;a.transparent=!0,a.opacity=e.opacity}return r}dispose(){}}class gl{constructor(){this.name="Hexagonal Wire Grid"}createGrid(e){var d;const t=new E.Group,n=((d=e.styleOptions)==null?void 0:d.hexRadius)??Math.floor(e.divisions/2),s=e.size/Math.max(1,n*2),o=new E.Color(e.color||8947848),r=e.opacity||.4,a=new E.LineBasicMaterial({color:o,transparent:!0,opacity:r}),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 w=f;w<=m;w++){const x=c*(h+w/2),_=u*.75*w,A=[],T=Math.PI*2/6;for(let M=0;M<=6;M++){const P=M*T+Math.PI/6,L=x+s*Math.cos(P),C=_+s*Math.sin(P);A.push(new E.Vector3(L,0,C))}const S=new E.BufferGeometry().setFromPoints(A),b=new E.Line(S,a);t.add(b)}}return t}dispose(){}}const xn=class xn{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)}};xn.HEIGHT_RATIO=.075,xn.BEVEL_RATIO=.04,xn.GAP_FACTOR=1.05;let Ut=xn;class yl{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)}createGeometry(){const e=new E.Shape,t=this.size+this.bevel,n=Math.PI*2/6;for(let r=0;r<6;r++){const a=t*Math.cos(r*n),c=t*Math.sin(r*n);r===0?e.moveTo(a,c):e.lineTo(a,c)}e.closePath();const s={depth:this.height,bevelEnabled:!0,bevelSize:this.bevel,bevelThickness:this.bevel,bevelSegments:2},o=new E.ExtrudeGeometry(e,s);return o.rotateZ(Math.PI/6),o.rotateX(Math.PI/2),o.translate(this.position.x,this.position.y,this.position.z),o}createMaterial(){const{metalness:e=0,roughness:t=.15,transmission:n=1,thickness:s=.4,ior:o=1.5}=this.materialOptions,r=n>0;return new E.MeshPhysicalMaterial({color:new E.Color(this.color),metalness:e,roughness:t,transparent:r,transmission:n,thickness:s,ior:o,opacity:1,clearcoat:r?1:0,clearcoatRoughness:.05,sheen:r?1:0,sheenColor:new E.Color(16777215),envMapIntensity:1})}}function wl(i,e){var d;const t=i.getIndex()?i.toNonIndexed():i,n=t.getAttribute("position").array,s=t.getAttribute("normal").array,o=(d=t.getAttribute("uv"))==null?void 0:d.array,r=new Float32Array(n.length*e.length),a=new Float32Array(s.length*e.length),c=o?new Float32Array(o.length*e.length):void 0;e.forEach((h,f)=>{const m=f*n.length;r.set(n,m);for(let w=m;w<m+n.length;w+=3)r[w]+=h.x,r[w+1]+=h.y,r[w+2]+=h.z;a.set(s,f*s.length),c&&o&&c.set(o,f*o.length)});const u=new E.BufferGeometry;return u.setAttribute("position",new E.BufferAttribute(r,3)),u.setAttribute("normal",new E.BufferAttribute(a,3)),c&&u.setAttribute("uv",new E.BufferAttribute(c,2)),u}class El{constructor(){this.name="Hexagonal Glass Grid"}createGrid(e){var w,x,_,A,T,S,b;const t=new E.Group,n=((w=e.styleOptions)==null?void 0:w.hexRadius)??Math.floor(e.divisions/2),s=((x=e.styleOptions)==null?void 0:x.tileSize)||1,o=String(e.color||"#ffffff"),r=Ut.getGridSpacing(s),a=r.width,c=r.height,u=new yl(new E.Vector3(0,0,0),s,o,{metalness:(_=e.styleOptions)==null?void 0:_.metalness,roughness:(A=e.styleOptions)==null?void 0:A.roughness,transmission:(T=e.styleOptions)==null?void 0:T.transmission,thickness:(S=e.styleOptions)==null?void 0:S.thickness,ior:(b=e.styleOptions)==null?void 0:b.ior}),d=u.createGeometry(),h=Ut.getYPosition(s),f=[];for(let M=-n;M<=n;M++){const P=Math.max(-n,-M-n),L=Math.min(n,-M+n);for(let C=P;C<=L;C++)f.push(new E.Vector3(a*(M+C/2),h,c*.75*C))}const m=new E.Mesh(wl(d,f),u.createMaterial());return m.receiveShadow=!0,t.add(m),d.dispose(),t.add(this.createShadowCatcher(a*(n+.5))),t}createShadowCatcher(e){const t=new E.Mesh(new E.CircleGeometry(Math.max(e,1),64),new E.ShadowMaterial({opacity:.35}));return t.name=rn,t.userData[bi]=!0,t.rotation.x=-Math.PI/2,t.position.y=.002,t.receiveShadow=!0,t}dispose(){}}class Tl{constructor(){this.name="Stone Tile Grid",this.textureLoader=new E.TextureLoader}createGrid(e){var m,w,x,_;const t=new E.Group,n=e.size,s=Math.max(1,e.divisions),o=n/s,r=o*.02,a=o-r,c=((m=e.styleOptions)==null?void 0:m.height)||o*.05,u=((w=e.styleOptions)==null?void 0:w.bevelSize)||c*.2,d=((x=e.styleOptions)==null?void 0:x.randomHeight)||!1,h=((_=e.styleOptions)==null?void 0:_.randomRotation)||!1,f=this.createStoneMaterial(e);for(let A=0;A<s;A++)for(let T=0;T<s;T++){const S=(A-s/2)*o+o/2,b=(T-s/2)*o+o/2,M=d?c*(.8+Math.random()*.4):c,P=new E.Shape,L=a/2;P.moveTo(-L,-L),P.lineTo(L,-L),P.lineTo(L,L),P.lineTo(-L,L),P.closePath();const C={depth:M,bevelEnabled:!0,bevelSize:u,bevelThickness:u,bevelSegments:2},D=new E.ExtrudeGeometry(P,C);D.rotateX(-Math.PI/2);const I=new E.Mesh(D,f);I.position.set(S,-M/2,b),I.castShadow=!0,I.receiveShadow=!0,h&&(I.rotation.y=Math.floor(Math.random()*4)*(Math.PI/2)),t.add(I)}return t}createStoneMaterial(e){var r,a,c,u,d;const t=new E.Color(e.color||8421504),n=((r=e.styleOptions)==null?void 0:r.metalness)||0,s=((a=e.styleOptions)==null?void 0:a.roughness)||.8,o={color:t,metalness:n,roughness:s};if((c=e.styleOptions)!=null&&c.texture){const h=this.loadTexture(e.styleOptions.texture);h&&(o.map=h,h.wrapS=h.wrapT=E.RepeatWrapping,h.repeat.set(1,1))}if((u=e.styleOptions)!=null&&u.normalMap){const h=this.loadTexture(e.styleOptions.normalMap);h&&(o.normalMap=h,h.wrapS=h.wrapT=E.RepeatWrapping,h.repeat.set(1,1))}if((d=e.styleOptions)!=null&&d.roughnessMap){const h=this.loadTexture(e.styleOptions.roughnessMap);h&&(o.roughnessMap=h,h.wrapS=h.wrapT=E.RepeatWrapping,h.repeat.set(1,1))}return new E.MeshStandardMaterial(o)}loadTexture(e){try{return this.textureLoader.load(e)}catch(t){return console.warn("Failed to load texture:",e,t),null}}}const Ri=class Ri{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 o=this.gridStyles.get(bt.SQUARE_WIRE);if(!o)throw new Error("Square wire grid style not found");return o.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()}};Ri.gridStyles=new Map([[bt.SQUARE_WIRE,new ml],[bt.HEXAGONAL_WIRE,new gl],[bt.HEXAGONAL_GLASS,new El],[bt.STONE_TILES,new Tl]]);let gs=Ri;function Sl(i,e){try{const t=Et(i);if(!t)return k.err(new Z("Scene must be ThreeSceneAdapter",X.INVALID_PARAMETER));if(e.grid){const n=t.userData,s=typeof e.grid=="object"?e.grid:null,o={enabled:!0,color:(s==null?void 0:s.colorGrid)||e.gridColor||"#AAAAAA",type:s!=null&&s.type?s.type:bt.HEXAGONAL_GLASS,opacity:s==null?void 0:s.opacity,styleOptions:s==null?void 0:s.styleOptions};if(t.userData={...n,gridOptions:o},s!=null&&s.size||s!=null&&s.divisions){const r=o.type||bt.HEXAGONAL_GLASS,a=s.size||10,c=s.divisions||10,u={size:a,divisions:c,color:o.color,opacity:o.opacity,styleOptions:{hexRadius:Math.floor(c/2),tileSize:1,...o.styleOptions}},d=gs.createGrid(r,u);d.userData.isGrid=!0,d.userData.isDefaultGrid=!0,t.add(d)}}if(e.axes){const n=e.axesSize||5,s=new E.AxesHelper(n);t.add(s)}return k.ok(void 0)}catch(t){return k.err(new Z("Failed to add helpers to scene",X.SCENE_OPERATION_FAILED,{originalError:t,options:e}))}}function _l(i,e,t=1.2){var n;try{const s=Et(i);if(!s)return k.err(new Z("Scene must be ThreeSceneAdapter",X.INVALID_PARAMETER));const o=s.userData,r=o==null?void 0:o.gridOptions;if(!(r!=null&&r.enabled))return k.ok(void 0);const a=[];s.traverse(C=>{var D,I,F;((D=C.userData)!=null&&D.isGrid||(I=C.userData)!=null&&I.isHexGrid||(F=C.userData)!=null&&F.isDefaultGrid)&&a.push(C)}),a.forEach(C=>{xs(C),s.remove(C)});const c=wt(e);if(!c)return k.err(new Z("Object must expose a Three.js Object3D",X.INVALID_PARAMETER));const u=new E.Box3().setFromObject(c),d=u.getSize(new E.Vector3);if(u.isEmpty()||!Number.isFinite(d.x)||!Number.isFinite(d.z))return console.warn("Skipping dynamic grid: object has an empty or non-finite bounding box"),k.ok(void 0);const h=(n=r.styleOptions)==null?void 0:n.tileSize,f=typeof h=="number"?h:1,w=Ut.getGridSpacing(f).width,x=Math.max(d.x,d.z)*t+d.y;let _=x<=w?0:Math.ceil((x/w-1)/2);const A=60;_>A&&(console.warn(`Dynamic grid would need ${_} rings to cover the object; capping at ${A}. The floor will not fully reach the configured coverage for this tileSize/object-size combination.`),_=A),x<w*.8?_=0:_<3&&x>w*2&&(_=3);const T=r.type||bt.HEXAGONAL_GLASS,b={size:Math.max(d.x,d.z)*t,divisions:_*2+1,color:r.color,opacity:r.opacity,styleOptions:{hexRadius:_,tileSize:f,...r.styleOptions}},M=gs.createGrid(T,b);M.userData.isGrid=!0,M.userData.isHexGrid=!0;const P=M.getObjectByName(rn);P&&(P.position.y=E.MathUtils.clamp(d.y*.0025,2e-4,.002));const L=u.getCenter(new E.Vector3);return M.position.set(L.x,0,L.z),s.add(M),k.ok(void 0)}catch(s){return k.err(new Z("Failed to add dynamic grid",X.SCENE_OPERATION_FAILED,{originalError:s}))}}function bl(i,e){try{const t=Et(i);if(!t)return k.err(new Z("Scene must be ThreeSceneAdapter",X.INVALID_PARAMETER));const n=wt(e);if(!n)return k.err(new Z("Object must expose a Three.js Object3D",X.INVALID_PARAMETER));const s=S=>{var M,P,L;let b=S;for(;b;){if((M=b.userData)!=null&&M.isGrid||(P=b.userData)!=null&&P.isHexGrid||(L=b.userData)!=null&&L.isDefaultGrid)return!0;b=b.parent}return!1};t.updateMatrixWorld(!0);const o=[];t.traverse(S=>{S.isMesh&&s(S)&&o.push(S)});const r=[];if(n.traverse(S=>{S.isMesh&&r.push(S)}),o.length===0||r.length===0)return k.ok(void 0);let a=-1/0;const c=new E.Box3;for(const S of o)c.setFromObject(S),Number.isFinite(c.max.y)&&(a=Math.max(a,c.max.y));if(!Number.isFinite(a))return k.ok(void 0);const u=new E.Box3().setFromObject(n);if(u.isEmpty()||!Number.isFinite(u.min.x)||!Number.isFinite(u.max.x))return k.ok(void 0);const d=40,h=Math.max(1,u.max.y-u.min.y),f=u.max.y+h,m=u.min.y-h,w=new E.Raycaster,x=new E.Vector3(0,-1,0),_=new E.Vector3(0,1,0);let A=1/0;const T=(S,b,M,P)=>{w.set(new E.Vector3(S,b,M),P);for(const L of w.intersectObjects(r,!1))L.point.y<A&&(A=L.point.y)};for(let S=0;S<=d;S++)for(let b=0;b<=d;b++){const M=u.min.x+(u.max.x-u.min.x)*(S/d),P=u.min.z+(u.max.z-u.min.z)*(b/d);T(M,f,P,x),T(M,m,P,_)}if(Number.isFinite(A)){const S=A-a;Math.abs(S)>1e-4&&(n.position.y-=S)}return k.ok(void 0)}catch(t){return k.err(new Z("Failed to snap object to floor",X.SCENE_OPERATION_FAILED,{originalError:t}))}}const Zr=i=>{let e=null;return i.traverse(t=>{!e&&t.isDirectionalLight&&(e=t)}),e};function xl(i,e){try{const t=Et(i);if(!t)return k.err(new Z("Scene must be ThreeSceneAdapter",X.INVALID_PARAMETER));const n=wt(e);if(!n)return k.err(new Z("Object must expose a Three.js Object3D",X.INVALID_PARAMETER));const s=new E.Box3().setFromObject(n);if(s.isEmpty()||!Number.isFinite(s.min.x)||!Number.isFinite(s.max.x))return k.ok(void 0);const o=s.getSize(new E.Vector3),r=s.getCenter(new E.Vector3),a=Zr(t);if(!a||!a.castShadow)return k.ok(void 0);if(a.parent===t&&a.target.parent===t){const m=a.position.clone().sub(a.target.position);a.target.position.copy(r),a.position.copy(r).add(m)}const h=Math.max(o.x,o.y,o.z,.1)*2,f=a.shadow.camera;return f.left=-h,f.right=h,f.top=h,f.bottom=-h,f.updateProjectionMatrix(),k.ok(void 0)}catch(t){return k.err(new Z("Failed to fit shadow camera to object",X.SCENE_OPERATION_FAILED,{originalError:t}))}}function Al(i,e,t,n){try{const s=Et(i);if(!s)return k.err(new Z("Scene must be ThreeSceneAdapter",X.INVALID_PARAMETER));const o=wt(e);if(!o)return k.err(new Z("Object must expose a Three.js Object3D",X.INVALID_PARAMETER));const r=Wr(t.getInternalRenderer());if(!r||!r.shadowMap.enabled)return k.ok(void 0);const a=Zr(s);return!a||!a.castShadow||n.bake({renderer:r,scene:s,object:o,light:a}),k.ok(void 0)}catch(s){return k.err(new Z("Failed to bake contact shadow",X.SCENE_OPERATION_FAILED,{originalError:s}))}}function Ml(i,e){try{const t=Et(i);if(!t)return k.err(new Z("Scene must be ThreeSceneAdapter",X.INVALID_PARAMETER));const n=t.getObjectByName(di),s=t.getObjectByName(rn);return e==="baked"&&!n||(n&&(n.visible=e==="baked"),s&&(s.visible=e==="live")),k.ok(void 0)}catch(t){return k.err(new Z("Failed to switch contact shadow mode",X.SCENE_OPERATION_FAILED,{originalError:t}))}}function Rl(i,e){try{const t=wt(i);if(!t)return k.err(new Z("Object must expose a Three.js Object3D",X.INVALID_PARAMETER));const n=new E.Group;return n.name=$o,n.scale.setScalar(e),n.add(t),k.ok(new Ke(n))}catch(t){return k.err(new Z("Failed to apply the units scale to the model",X.SCENE_OPERATION_FAILED,{originalError:t}))}}function vl(i,e){try{const t=Et(i);if(!t)return k.err(new Z("Scene must be ThreeSceneAdapter",X.INVALID_PARAMETER));if(e.ambient){const n=new E.Color(e.ambient.color||"#404040"),s=e.ambient.intensity??Math.PI,o=new E.AmbientLight(n,s);t.add(o)}if(e.hemisphere){const n=new E.Color(e.hemisphere.skyColor||"#ffffbb"),s=new E.Color(e.hemisphere.groundColor||"#080820"),o=e.hemisphere.intensity??1,r=new E.HemisphereLight(n,s,o);t.add(r)}if(e.directional){const n=new E.Color(e.directional.color||"#ffffff"),s=e.directional.intensity??Math.PI,o=new E.DirectionalLight(n,s);if(e.directional.position){const r=e.directional.position;if(r instanceof E.Vector3)o.position.copy(r);else if(Array.isArray(r))o.position.set(r[0],r[1],r[2]);else if(typeof r=="object"&&"x"in r&&"y"in r&&"z"in r){const a=r;o.position.set(a.x,a.y,a.z)}}else o.position.set(6,6,6);if(e.directional.castShadow&&(o.castShadow=!0,e.directional.shadow)){const r=e.directional.shadow;if(r.mapSize&&(o.shadow.mapSize.width=r.mapSize.width,o.shadow.mapSize.height=r.mapSize.height),r.camera){const a=o.shadow.camera;r.camera.near!==void 0&&(a.near=r.camera.near),r.camera.far!==void 0&&(a.far=r.camera.far),r.camera.left!==void 0&&(a.left=r.camera.left),r.camera.right!==void 0&&(a.right=r.camera.right),r.camera.top!==void 0&&(a.top=r.camera.top),r.camera.bottom!==void 0&&(a.bottom=r.camera.bottom)}r.bias!==void 0&&(o.shadow.bias=r.bias),r.radius!==void 0&&(o.shadow.radius=r.radius)}o.target.position.set(0,0,0),t.add(o),t.add(o.target),o.shadow&&o.shadow.camera.updateProjectionMatrix()}return k.ok(void 0)}catch(t){return k.err(new Z("Failed to add lighting to scene",X.SCENE_OPERATION_FAILED,{originalError:t,options:e}))}}function Cl(i,e){try{const t=Et(i);if(!t)return k.err(new Z("Scene must be ThreeSceneAdapter",X.INVALID_PARAMETER));const n=document.createElement("canvas");n.width=2,n.height=512;const s=n.getContext("2d");if(!s)return k.err(new Z("Failed to create canvas context",X.SCENE_OPERATION_FAILED));const o=s.createLinearGradient(0,0,0,n.height);o.addColorStop(0,e.topColor),o.addColorStop(1,e.bottomColor),s.fillStyle=o,s.fillRect(0,0,n.width,n.height);const r=new E.CanvasTexture(n);r.needsUpdate=!0;const a=t.background;return a instanceof E.Texture&&a!==t.environment&&a.dispose(),t.background=r,k.ok(void 0)}catch(t){return k.err(new Z("Failed to create gradient background",X.SCENE_OPERATION_FAILED,{originalError:t,options:e}))}}function Il(i,e,t){try{const n=wt(i);if(!n)return k.err(new Z("Object must expose a Three.js Object3D",X.INVALID_PARAMETER));const s=vn(e);if(!(s instanceof E.PerspectiveCamera)&&!(s instanceof E.OrthographicCamera))return k.err(new Z("Camera must expose a perspective or orthographic Three.js camera",X.INVALID_PARAMETER));const o=xi(t);if(!o)return k.err(new Z("Controls must expose the underlying Three.js controls",X.INVALID_PARAMETER));const r=new E.Box3().setFromObject(n),a=r.getCenter(new E.Vector3),c=r.getSize(new E.Vector3),u=Math.max(c.x,c.y,c.z);let d;"fov"in s?d=s.fov*(Math.PI/180):d=50*(Math.PI/180);let h=Math.abs(u/2/Math.tan(d/2));h*=2;const f=-Math.PI/4,m=Math.PI/8,w=a.x+h*Math.sin(f)*Math.cos(m),x=a.y+h*Math.sin(m),_=a.z+h*Math.cos(f)*Math.cos(m);return s.position.set(w,x,_),s.lookAt(a),s.updateProjectionMatrix(),o.target&&(o.target.copy(a),o.update()),k.ok(void 0)}catch(n){return k.err(new Z("Failed to fit camera to object",X.CAMERA_INIT_FAILED,{originalError:n}))}}class Ll{constructor(){this.contactShadowBaker=new fi}addHelpers(e,t){return Sl(e,t)}addDynamicGrid(e,t,n=1.2){return _l(e,t,n)}snapObjectToFloor(e,t){return bl(e,t)}fitShadowCameraToObject(e,t){return xl(e,t)}bakeContactShadow(e,t,n){return Al(e,t,n,this.contactShadowBaker)}setContactShadowMode(e,t){return Ml(e,t)}wrapInUnitsScaleGroup(e,t){return Rl(e,t)}addLighting(e,t){return vl(e,t)}createGradientBackground(e,t){return Cl(e,t)}fitCameraToObject(e,t,n){return Il(e,t,n)}}class Pl{constructor(){this.events=new Es,this.disposed=!1}async initialize(e){const{ThreePathTracingService:t}=await Promise.resolve().then(()=>require("./ThreePathTracingService-BroJh4xX.cjs"));if(this.disposed)return k.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(k.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,nn=Uint16Array,Ol=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]),Dl=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 nn(31),n=0;n<31;++n)t[n]=e+=1<<i[n-1];for(var s=new Ol(t[30]),n=1;n<30;++n)for(var o=t[n];o<t[n+1];++o)s[o]=o-t[n]<<5|n;return{b:t,r:s}},qr=Yr(Kr,2),$r=qr.b,Nl=qr.r;$r[28]=258,Nl[258]=28;var kl=Yr(Xr,0),Fl=kl.b,pi=new nn(32768);for(var _e=0;_e<32768;++_e){var Ct=(_e&43690)>>1|(_e&21845)<<1;Ct=(Ct&52428)>>2|(Ct&13107)<<2,Ct=(Ct&61680)>>4|(Ct&3855)<<4,pi[_e]=((Ct&65280)>>8|(Ct&255)<<8)>>1}var bn=(function(i,e,t){for(var n=i.length,s=0,o=new nn(e);s<n;++s)i[s]&&++o[i[s]-1];var r=new nn(e);for(s=1;s<e;++s)r[s]=r[s-1]+o[s-1]<<1;var a;if(t){a=new nn(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=r[i[s]-1]++<<d,f=h|(1<<d)-1;h<=f;++h)a[pi[h]>>c]=u}else for(a=new nn(n),s=0;s<n;++s)i[s]&&(a[s]=pi[r[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 Bl=bn(Cn,9,1),zl=bn(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)},Ul=function(i){return(i+7)/8|0},Vl=function(i,e,t){return(t==null||t>i.length)&&(t=i.length),new it(i.subarray(e,t))},Hl=["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||Hl[i]);if(n.code=i,Error.captureStackTrace&&Error.captureStackTrace(n,ut),!t)throw n;return n},jl=function(i,e,t,n){var s=i.length,o=0;if(!s||e.f&&!e.l)return t||new it(0);var r=!t,a=r||e.i!=2,c=e.i;r&&(t=new it(s*3));var u=function(Vt){var Tt=t.length;if(Vt>Tt){var In=new it(Math.max(Tt*2,Vt));In.set(t),t=In}},d=e.f||0,h=e.p||0,f=e.b||0,m=e.l,w=e.d,x=e.m,_=e.n,A=s*8;do{if(!m){d=lt(i,h,1);var T=lt(i,h+1,3);if(h+=3,T)if(T==1)m=Bl,w=zl,x=9,_=5;else if(T==2){var P=lt(i,h,31)+257,L=lt(i,h+10,15)+4,C=P+lt(i,h+5,31)+1;h+=14;for(var D=new it(C),I=new it(19),F=0;F<L;++F)I[Dl[F]]=lt(i,h+F*3,7);h+=L*3;for(var N=Ws(I),H=(1<<N)-1,G=bn(I,N,1),F=0;F<C;){var $=G[lt(i,h,H)];h+=$&15;var S=$>>4;if(S<16)D[F++]=S;else{var re=0,Ne=0;for(S==16?(Ne=3+lt(i,h,3),h+=2,re=D[F-1]):S==17?(Ne=3+lt(i,h,7),h+=3):S==18&&(Ne=11+lt(i,h,127),h+=7);Ne--;)D[F++]=re}}var ot=D.subarray(0,P),ve=D.subarray(P);x=Ws(ot),_=Ws(ve),m=bn(ot,x,1),w=bn(ve,_,1)}else ut(1);else{var S=Ul(h)+4,b=i[S-4]|i[S-3]<<8,M=S+b;if(M>s){c&&ut(0);break}a&&u(f+b),t.set(i.subarray(S,M),f),e.b=f+=b,e.p=h=M*8,e.f=d;continue}if(h>A){c&&ut(0);break}}a&&u(f+131072);for(var ze=(1<<x)-1,je=(1<<_)-1,Me=h;;Me=h){var re=m[Zs(i,h)&ze],ye=re>>4;if(h+=re&15,h>A){c&&ut(0);break}if(re||ut(2),ye<256)t[f++]=ye;else if(ye==256){Me=h,m=null;break}else{var ft=ye-254;if(ye>264){var F=ye-257,Ge=Kr[F];ft=lt(i,h,(1<<Ge)-1)+$r[F],h+=Ge}var At=w[Zs(i,h)&je],ge=At>>4;At||ut(3),h+=At&15;var ve=Fl[ge];if(ge>3){var Ge=Xr[ge];ve+=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<ve){var ct=o-ve,an=Math.min(ve,at);for(ct+f<0&&ut(3);f<an;++f)t[f]=n[ct+f]}for(;f<at;++f)t[f]=t[f-ve]}}e.l=m,e.p=Me,e.b=f,e.f=d,m&&(d=1,e.m=x,e.d=w,e.n=_)}while(!d);return f!=t.length&&r?Vl(t,0,f):t.subarray(0,f)},Gl=new it(0),Wl=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 jl(i.subarray(Wl(i),-4),{i:2},e,e)}var Zl=typeof TextDecoder<"u"&&new TextDecoder,Kl=0;try{Zl.decode(Gl,{stream:!0}),Kl=1}catch{}class Xl 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 I=null;function F(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 H={l:0,c:0,lc:0};function G(l,g,y,v,O){for(;y<l;)g=g<<8|Oi(v,O),y+=8;y-=l,H.l=g>>y&(1<<l)-1,H.c=g,H.lc=y}const $=new Array(59);function re(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 V=0,B=0;for(;v<=O;v++){if(R.value-g.value>y)return!1;G(6,V,B,l,R);const U=H.l;if(V=H.c,B=H.lc,z[v]=U,U==63){if(R.value-g.value>y)throw new Error("THREE.EXRLoader: Something wrong with hufUnpackEncTable");G(8,V,B,l,R);let j=H.l+6;if(V=H.c,B=H.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--}}re(z)}function ot(l){return l&63}function ve(l){return l>>6}function ze(l,g,y,v){for(;g<=y;g++){const O=ve(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 V=R.p;R.p=new Array(R.lit);for(let B=0;B<R.lit-1;++B)R.p[B]=V[B]}else R.p=new Array(1);R.p[R.lit-1]=g}else if(z){let R=0;for(let V=1<<14-z;V>0;V--){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 Me(l,g,y,v){l=l<<8|Oi(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,V,B){if(l==g){v<8&&(Me(y,v,O,z),y=je.c,v=je.lc),v-=8;let U=y>>v;if(U=new Uint8Array([U])[0],V.value+U>B)return!1;const j=R[V.value-1];for(;U-- >0;)R[V.value++]=j}else if(V.value<B)R[V.value++]=l;else return!1;ye.c=y,ye.lc=v}function Ge(l){return l&65535}function At(l){const g=Ge(l);return g>32767?g-65536:g}const ge={a:0,b:0};function at(l,g){const y=At(l),O=At(g),z=y+(O&1)+(O>>1),R=z,V=z-O;ge.a=R,ge.b=V}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 an(l,g,y,v,O,z,R){const V=R<16384,B=y>O?O:y;let U=1,j,K;for(;U<=B;)U<<=1;for(U>>=1,j=U,U>>=1;U>=1;){K=0;const W=K+z*(O-j),q=z*U,ee=z*j,Y=v*U,Q=v*j;let oe,he,ae,de;for(;K<=W;K+=ee){let ne=K;const te=K+v*(y-j);for(;ne<=te;ne+=Q){const ie=ne+Y,we=ne+q,pe=we+Y;V?(at(l[ne+g],l[we+g]),oe=ge.a,ae=ge.b,at(l[ie+g],l[pe+g]),he=ge.a,de=ge.b,at(oe,he),l[ne+g]=ge.a,l[ie+g]=ge.b,at(ae,de),l[we+g]=ge.a,l[pe+g]=ge.b):(ct(l[ne+g],l[we+g]),oe=ge.a,ae=ge.b,ct(l[ie+g],l[pe+g]),he=ge.a,de=ge.b,ct(oe,he),l[ne+g]=ge.a,l[ie+g]=ge.b,ct(ae,de),l[we+g]=ge.a,l[pe+g]=ge.b)}if(y&U){const ie=ne+q;V?at(l[ne+g],l[ie+g]):ct(l[ne+g],l[ie+g]),oe=ge.a,l[ie+g]=ge.b,l[ne+g]=oe}}if(O&U){let ne=K;const te=K+v*(y-j);for(;ne<=te;ne+=Q){const ie=ne+Y;V?at(l[ne+g],l[ie+g]):ct(l[ne+g],l[ie+g]),oe=ge.a,l[ie+g]=ge.b,l[ne+g]=oe}}j=U,U>>=1}return K}function Vt(l,g,y,v,O,z,R,V,B){let U=0,j=0;const K=R,W=Math.trunc(v.value+(O+7)/8);for(;v.value<W;)for(Me(U,j,y,v),U=je.c,j=je.lc;j>=14;){const ee=U>>j-14&16383,Y=g[ee];if(Y.len)j-=Y.len,ft(Y.lit,z,U,j,y,v,V,B,K),U=ye.c,j=ye.lc;else{if(!Y.p)throw new Error("THREE.EXRLoader: hufDecode issues");let Q;for(Q=0;Q<Y.lit;Q++){const oe=ot(l[Y.p[Q]]);for(;j<oe&&v.value<W;)Me(U,j,y,v),U=je.c,j=je.lc;if(j>=oe&&ve(l[Y.p[Q]])==(U>>j-oe&(1<<oe)-1)){j-=oe,ft(Y.p[Q],z,U,j,y,v,V,B,K),U=ye.c,j=ye.lc;break}}if(Q==Y.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,V,B,K),U=ye.c,j=ye.lc;else throw new Error("THREE.EXRLoader: hufDecode issues")}return!0}function Tt(l,g,y,v,O,z){const R={value:0},V=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 K=new Array(65537),W=new Array(16384);N(W);const q=v-(y.value-V);if(Ne(l,y,q,B,U,K),j>8*(v-(y.value-V)))throw new Error("THREE.EXRLoader: Something wrong with hufUncompress");ze(K,B,U,W),Vt(K,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 V=0;V<R;V++)y.push(O.getUint8(v++))}else{const R=z;g-=2;const V=O.getUint8(v++);for(let B=0;B<R+1;B++)y.push(V)}}return y}function uo(l,g,y,v,O,z){let R=new DataView(z.buffer);const V=y[l.idx[0]].width,B=y[l.idx[0]].height,U=3,j=Math.floor(V/8),K=Math.ceil(V/8),W=Math.ceil(B/8),q=V-(K-1)*8,ee=B-(W-1)*8,Y={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]+K*W,oe[te]=new Float32Array(64),he[te]=new Uint16Array(64),ae[te]=new Uint16Array(K*64);for(let te=0;te<W;++te){let ie=8;te==W-1&&(ie=ee);let we=8;for(let ce=0;ce<K;++ce){ce==K-1&&(we=q);for(let ue=0;ue<U;++ue)he[ue].fill(0),he[ue][0]=O[Q[ue]++],vi(Y,v,he[ue]),Ci(he[ue],oe[ue]),Ii(oe[ue]);po(oe);for(let ue=0;ue<U;++ue)Li(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 Ce=8*te;Ce<8*te+ie;++Ce){pe=de[ce][Ce];for(let et=0;et<j;++et){const Se=et*64+(Ce&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!=K)for(let Ce=8*te;Ce<8*te+ie;++Ce){const et=de[ce][Ce]+8*j*2*ue,Se=j*64+(Ce&7)*8;for(let pt=0;pt<we;++pt)R.setUint16(et+pt*2*ue,ae[ce][Se+pt],!0)}}}const ne=new Uint16Array(V);R=new DataView(z.buffer);for(let te=0;te<U;++te){y[l.idx[te]].decoded=!0;const ie=y[l.idx[te]].type;if(y[te].type==2)for(let we=0;we<B;++we){const pe=de[te][we];for(let ce=0;ce<V;++ce)ne[ce]=R.getUint16(pe+ce*2*ie,!0);for(let ce=0;ce<V;++ce)R.setFloat32(pe+ce*2*ie,J(ne[ce]),!0)}}}function fo(l,g,y,v,O,z){const R=new DataView(z.buffer),V=y[l],B=V.width,U=V.height,j=Math.ceil(B/8),K=Math.ceil(U/8),W=Math.floor(B/8),q=B-(j-1)*8,ee=U-(K-1)*8,Y={value:0};let Q=0;const oe=new Float32Array(64),he=new Uint16Array(64),ae=new Uint16Array(j*64);for(let de=0;de<K;++de){let ne=8;de==K-1&&(ne=ee);for(let te=0;te<j;++te)he.fill(0),he[0]=O[Q++],vi(Y,v,he),Ci(he,oe),Ii(oe),Li(oe,ae,te*64);for(let te=8*de;te<8*de+ne;++te){let ie=g[l][te];for(let we=0;we<W;++we){const pe=we*64+(te&7)*8;for(let ce=0;ce<8;++ce)R.setUint16(ie+ce*2*V.type,ae[pe+ce],!0);ie+=16*V.type}if(j!=W){const we=W*64+(te&7)*8;for(let pe=0;pe<q;++pe)R.setUint16(ie+pe*2*V.type,ae[we+pe],!0)}}}V.decoded=!0}function vi(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 Ci(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 Ii(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),V=.5*Math.cos(7*3.14159/16),B=new Array(4),U=new Array(4),j=new Array(4),K=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]+V*l[q+7],U[1]=O*l[q+1]-V*l[q+3]-y*l[q+5]-z*l[q+7],U[2]=z*l[q+1]-y*l[q+3]+V*l[q+5]+O*l[q+7],U[3]=V*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],K[0]=j[0]+j[1],K[1]=j[3]+j[2],K[2]=j[3]-j[2],K[3]=j[0]-j[1],l[q+0]=K[0]+U[0],l[q+1]=K[1]+U[1],l[q+2]=K[2]+U[2],l[q+3]=K[3]+U[3],l[q+4]=K[3]-U[3],l[q+5]=K[2]-U[2],l[q+6]=K[1]-U[1],l[q+7]=K[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]+V*l[56+W],U[1]=O*l[8+W]-V*l[24+W]-y*l[40+W]-z*l[56+W],U[2]=z*l[8+W]-y*l[24+W]+V*l[40+W]+O*l[56+W],U[3]=V*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],K[0]=j[0]+j[1],K[1]=j[3]+j[2],K[2]=j[3]-j[2],K[3]=j[0]-j[1],l[0+W]=K[0]+U[0],l[8+W]=K[1]+U[1],l[16+W]=K[2]+U[2],l[24+W]=K[3]+U[3],l[32+W]=K[3]-U[3],l[40+W]=K[2]-U[2],l[48+W]=K[1]-U[1],l[56+W]=K[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 Li(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,Y=l.inputChannels.length;ee<Y;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 V=cn(g,y),B=cn(g,y);if(B>=8192)throw new Error("THREE.EXRLoader: Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(V<=B)for(let ee=0;ee<B-V+1;ee++)O[ee+V]=Mt(g,y);const U=new Uint16Array(65536),j=F(O,U),K=Je(g,y);Tt(l.array,g,y,K,v,z);for(let ee=0;ee<l.inputChannels.length;++ee){const Y=R[ee];for(let Q=0;Q<R[ee].size;++Q)an(v,Y.start+Q,Y.nx,Y.size,Y.ny,Y.nx*Y.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 Y=0;Y<l.inputChannels.length;Y++){const Q=R[Y],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 wo(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,V=0;const B=new Array(4);for(let U=0;U<l.lines;U++)for(let j=0;j<l.inputChannels.length;j++){let K=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]++];K+=ee,z.setUint16(V,K,!0),V+=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;K+=ee,z.setUint32(V,K,!0),V+=4}break}}return z}function Eo(l){const g=l.array;let y=l.offset.value;const v=l.columns,O=l.lines,z=l.inputChannels,R=l.totalBytes,V=Ze.compression==="B44A_COMPRESSION",B=new Uint8Array(O*v*R),U=new Uint16Array(16);let j=0;for(let K=0;K<z.length;K++){const W=z[K],q=W.pixelType*2,ee=Math.ceil(v/W.xSampling),Y=Math.ceil(O/W.ySampling),Q=W.xSampling===1&&W.ySampling===1;if(W.pixelType!==1){for(let ae=0;ae<Y;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(Y/4);for(let ae=0;ae<he;ae++)for(let de=0;de<oe;de++){if(V&&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,ie=32<<te,we=ne+((g[y+2]<<4|g[y+3]>>4)&63)*(1<<te)-ie&65535,pe=we+((g[y+3]<<2|g[y+4]>>6)&63)*(1<<te)-ie&65535,ce=pe+(g[y+4]&63)*(1<<te)-ie&65535,ue=ne+(g[y+5]>>2&63)*(1<<te)-ie&65535,Ce=we+((g[y+5]<<4|g[y+6]>>4)&63)*(1<<te)-ie&65535,et=pe+((g[y+6]<<2|g[y+7]>>6)&63)*(1<<te)-ie&65535,Se=ce+(g[y+7]&63)*(1<<te)-ie&65535,pt=ue+(g[y+8]>>2&63)*(1<<te)-ie&65535,Ht=Ce+((g[y+8]<<4|g[y+9]>>4)&63)*(1<<te)-ie&65535,ln=et+((g[y+9]<<2|g[y+10]>>6)&63)*(1<<te)-ie&65535,mt=Se+(g[y+10]&63)*(1<<te)-ie&65535,Nt=pt+(g[y+11]>>2&63)*(1<<te)-ie&65535,Bn=Ht+((g[y+11]<<4|g[y+12]>>4)&63)*(1<<te)-ie&65535,zn=ln+((g[y+12]<<2|g[y+13]>>6)&63)*(1<<te)-ie&65535,Un=mt+(g[y+13]&63)*(1<<te)-ie&65535,hn=[ne,ue,pt,Nt,we,Ce,Ht,Bn,pe,et,ln,zn,ce,Se,mt,Un];for(let jt=0;jt<16;jt++)U[jt]=hn[jt]&32768?hn[jt]&32767:~hn[jt]&65535;y+=14}if(W.pLinear){if(I===null){I=new Uint16Array(65536);for(let ne=0;ne<65536;ne++)if((ne&31744)===31744||ne>32768)I[ne]=0;else{const te=J(ne);I[ne]=te<=0?0:p.DataUtils.toHalfFloat(8*Math.log(te))}}for(let ne=0;ne<16;ne++)U[ne]=I[U[ne]]}for(let ne=0;ne<4;ne++){const te=ae*4+ne;if(!(te>=Y))for(let ie=0;ie<4;ie++){const we=de*4+ie;if(we>=ee)continue;const pe=U[ne*4+ie];for(let ce=0;ce<W.ySampling;ce++){const ue=te*W.ySampling+ce;if(!(ue>=O))for(let Ce=0;Ce<W.xSampling;Ce++){const et=we*W.xSampling+Ce;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 Pi(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=cn(g,y)-2;for(;R>0;){const Y=Dn(g.buffer,y),Q=Mt(g,y),oe=Q>>2&3,he=(Q>>4)-1,ae=new Int8Array([he])[0],de=Mt(g,y);z.push({name:Y,index:ae,type:de,compression:oe}),R-=Y.length+3}const V=Ze.channels,B=new Array(l.inputChannels.length);for(let Y=0;Y<l.inputChannels.length;++Y){const Q=B[Y]={},oe=V[Y];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 Y=0;Y<l.inputChannels.length;++Y){const Q=B[Y],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]=Y),Q.offset=Y)}}let j,K,W;if(O.acCompressedSize>0)switch(O.acCompression){case 0:j=new Uint16Array(O.totalAcUncompressedCount),Tt(l.array,g,y,O.acCompressedSize,j,O.totalAcUncompressedCount);break;case 1:const Y=l.array.slice(y.value,y.value+O.totalAcUncompressedCount),Q=En(Y);j=new Uint16Array(Q.buffer),y.value+=O.totalAcUncompressedCount;break}if(O.dcCompressedSize>0){const Y={array:l.array,offset:y,size:O.dcCompressedSize};K=new Uint16Array(Ms(Y).buffer),y.value+=O.dcCompressedSize}if(O.rleRawSize>0){const Y=l.array.slice(y.value,y.value+O.rleCompressedSize),Q=En(Y);W=As(Q.buffer),y.value+=O.rleCompressedSize}let q=0;const ee=new Array(B.length);for(let Y=0;Y<ee.length;++Y)ee[Y]=new Array;for(let Y=0;Y<l.lines;++Y)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,K,v);for(let Y=0;Y<B.length;++Y){const Q=B[Y];if(!Q.decoded)switch(Q.compression){case 2:let oe=0,he=0;for(let ae=0;ae<l.lines;++ae){let de=ee[Y][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(Y,ee,B,j,K,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 Oi(l,g){const y=l[g.value];return g.value=g.value+1,y}function Mt(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 cn(l,g){const y=l.getUint16(g.value,!0);return g.value+=2,y}function xo(l,g){return J(cn(l,g))}function Ao(l,g,y,v){const O=y.value,z=[];for(;y.value<O+v-1;){const R=Dn(g,y),V=qe(l,y),B=Mt(l,y);y.value+=3;const U=qe(l,y),j=qe(l,y);z.push({name:R,pixelType:V,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),V=We(l,g),B=We(l,g),U=We(l,g);return{redX:y,redY:v,greenX:O,greenY:z,blueX:R,blueY:V,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=Mt(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=Mt(l,g);return y[v]}function Io(l,g){const y=["ENVMAP_LATLONG","ENVMAP_CUBE"],v=Mt(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=Mt(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 Di(l,g,y,v){const O=new Array(l);for(let z=0;z<l;z++){const R=1<<z;let V=g/R|0;v=="ROUND_UP"&&V*R<g&&(V+=1);const B=Math.max(V,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,V=z*l.blockHeight;l.columns=R+l.blockWidth>l.width?l.width-R:l.blockWidth,l.lines=V+l.blockHeight>l.height?l.height-V: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 K=0;K<l.lines;K++){const W=K*l.columns*l.totalBytes;for(let q=0;q<l.inputChannels.length;q++){const ee=Ze.channels[q].name,Y=l.channelByteOffsets[ee]*l.columns,Q=l.decodeChannels[ee];if(Q===void 0)continue;y.value=W+Y;const oe=(l.height-(1+V+K))*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,V=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,K=(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,Y=l.decodeChannels[q];if(Y!==void 0){y.value=j+ee;for(let Q=0;Q<l.columns;Q++){const oe=K+Q*l.outputChannels+Y;l.byteArray[oe]=l.getter(V,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,V=l.size<l.lines*R,B=l.offset;l.offset=O;const U=V?l.uncompress(l):On(l);l.offset=B;for(let j=0;j<l.lines;j++){const K=z+j,W=j*R,q=(l.height-1-K)*l.outLineWidth;for(let ee=0;ee<l.inputChannels.length;ee++){const Y=Ze.channels[ee].name,Q=l.channelByteOffsets[Y]*l.columns,oe=l.decodeChannels[Y];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 Ni(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,V=l.decodeChannels,B=l.outputChannels,U=l.byteArray instanceof Uint16Array;let j=-1;for(let K=0;K<O.length;K++)if(O[K].name==="A"){j=K;break}for(let K=0;K<g.length;K++){const W={value:g[K]};R&&(W.value+=4);const q=qe(l.viewer,W)-Ze.dataWindow.yMin,ee=ke(l.viewer,W),Y=ke(l.viewer,W);ke(l.viewer,W);const Q=Ni(l.array,W.value,ee,z);if(W.value+=ee,Q===null)continue;const oe=new Uint32Array(y);for(let ie=0;ie<y;ie++)oe[ie]=Q.getUint32(ie*4,!0);const he=oe[y-1];if(he===0){W.value+=Y;continue}const ae=Ni(l.array,W.value,Y,z),de=[];let ne=0;for(let ie=0;ie<O.length;ie++)de.push(ne),ne+=he*O[ie].bytesPerSample;const te=(v-1-q)*l.outLineWidth;for(let ie=0;ie<y;ie++){const we=ie===0?0:oe[ie-1],ce=oe[ie]-we;if(ce===0)continue;const ue=new Float32Array(B);let Ce=0;for(let Se=0;Se<ce;Se++){const pt=we+Se,Ht=1-Ce;if(Ht<=0)break;let ln=1;if(j>=0){const mt=O[j].bytesPerSample,Nt=de[j]+pt*mt;ln=mt===2?J(ae.getUint16(Nt,!0)):ae.getFloat32(Nt,!0)}for(let mt=0;mt<O.length;mt++){const Nt=O[mt],Bn=V[Nt.name];if(Bn===void 0)continue;const zn=Nt.bytesPerSample,Un=de[mt]+pt*zn,hn=zn===2?J(ae.getUint16(Un,!0)):ae.getFloat32(Un,!0);ue[Bn]+=hn*Ht}Ce+=ln*Ht}V.A!==void 0&&(ue[V.A]=Ce);const et=te+ie*B;for(let Se=0;Se<B;Se++)l.byteArray[et+Se]=U?p.DataUtils.toHalfFloat(ue[Se]):ue[Se]}}}function ki(l,g,y){const v={};let O=!1;for(;;){const z=Dn(g,y);if(z==="")break;O=!0;const R=Dn(g,y),V=Je(l,y),B=Do(l,g,y,R,V);B===void 0?console.warn(`THREE.EXRLoader: Skipped unknown header attribute type '${R}'.`):v[z]=B}return O?v:null}function Vo(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 V=ki(l,g,y);if(V===null)break;V.version=v,V.spec=z,R.push(V)}if(R.length===0)throw new Error("THREE.EXRLoader: No valid part headers found.")}else{const V=ki(l,g,y);V.version=v,V.spec=z,R.push(V)}return R}function Ho(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=wo;break;case"B44_COMPRESSION":case"B44A_COMPRESSION":R.blockHeight=32,R.uncompress=Eo;break;case"DWAA_COMPRESSION":R.blockHeight=32,R.uncompress=Pi;break;case"DWAB_COMPRESSION":R.blockHeight=256,R.uncompress=Pi;break;default:throw new Error("THREE.EXRLoader: "+l.compression+" is unsupported")}const V={};for(const W of l.channels)switch(W.name){case"BY":case"RY":case"Y":case"R":case"G":case"B":case"A":V[W.name]=!0,R.type=W.pixelType}let B=!1,U=!1;if(V.Y&&V.RY&&V.BY)R.outputChannels=4,R.yCbCr=!0;else if(V.R&&V.G&&V.B)R.outputChannels=4;else if(V.Y)R.outputChannels=1;else throw new Error("THREE.EXRLoader: file contains unsupported data channels.");switch(R.outputChannels){case 4:z==p.RGBAFormat?(B=!V.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=cn;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 K=0;for(const W of l.channels)R.decodeChannels[W.name]!==void 0&&(R.channelByteOffsets[W.name]=K),K+=W.pixelType*2;if(R.totalBytes=K,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=Di(W,R.width,l.tiles.xSize,l.tiles.roundingMode),ee=Di(W,R.height,l.tiles.ySize,l.tiles.roundingMode);R.tileCount=q[0]*ee[0];for(let Y=0;Y<W;Y++)for(let Q=0;Q<ee[Y];Q++)for(let oe=0;oe<q[Y];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=Vo(kn,e,Nn),Fi=Math.max(0,Math.min(this.part,Fn.length-1)),Ze=Fn[Fi];if(Ze.spec.multiPart||Ze.spec.deepFormat)for(let l=0;l<Fn.length;l++){const g=Fn[l].chunkCount;if(l===Fi){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=Ho(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]),V=(1+z)*O,B=(1+R)*O,U=(O-V*.2126-B*.0722)/.7152;l[v]=p.DataUtils.toHalfFloat(Math.max(0,V)),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],V=(1+z)*O,B=(1+R)*O;l[v]=Math.max(0,V),l[v+1]=Math.max(0,(O-V*.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 Yl extends p.DataTextureLoader{constructor(e){super(e),this.type=p.HalfFloatType}parse(e){const r=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,I){D=D||1024;let N=C.pos,H=-1,G=0,$="",re=String.fromCharCode.apply(null,new Uint16Array(C.subarray(N,N+128)));for(;0>(H=re.indexOf(`
8
+ `))&&G<D&&N<C.byteLength;)$+=re,G+=re.length,N+=128,re=String.fromCharCode.apply(null,new Uint16Array(C.subarray(N,N+128)));return-1<H?(C.pos+=G+H+1,$+re.slice(0,H)):!1},f=function(C){const D=/^#\?(\S+)/,I=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,F=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,N=/^\s*FORMAT=(\S+)\s*$/,H=/^\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 $,re;for((C.pos>=C.byteLength||!($=h(C)))&&r(1,"no header found"),(re=$.match(D))||r(3,"bad initial token"),G.valid|=1,G.programtype=re[1],G.string+=$+`
9
+ `;$=h(C),$!==!1;){if(G.string+=$+`
10
+ `,$.charAt(0)==="#"){G.comments+=$+`
11
+ `;continue}if((re=$.match(I))&&(G.gamma=parseFloat(re[1])),(re=$.match(F))&&(G.exposure=parseFloat(re[1])),(re=$.match(N))&&(G.valid|=2,G.format=re[1]),(re=$.match(H))&&(G.valid|=4,G.height=parseInt(re[1],10),G.width=parseInt(re[2],10)),G.valid&2&&G.valid&4)break}return G.valid&2||r(3,"missing format specifier"),G.valid&4||r(3,"missing image size specifier"),G},m=function(C,D,I){const F=D;if(F<8||F>32767||C[0]!==2||C[1]!==2||C[2]&128)return new Uint8Array(C);F!==(C[2]<<8|C[3])&&r(3,"wrong scanline width");const N=new Uint8Array(4*D*I);N.length||r(4,"unable to allocate buffer space");let H=0,G=0;const $=4*F,re=new Uint8Array(4),Ne=new Uint8Array($);let ot=I;for(;ot>0&&G<C.byteLength;){G+4>C.byteLength&&r(1),re[0]=C[G++],re[1]=C[G++],re[2]=C[G++],re[3]=C[G++],(re[0]!=2||re[1]!=2||(re[2]<<8|re[3])!=F)&&r(3,"bad rgbe scanline format");let ve=0,ze;for(;ve<$&&G<C.byteLength;){ze=C[G++];const Me=ze>128;if(Me&&(ze-=128),(ze===0||ve+ze>$)&&r(3,"bad scanline data"),Me){const ye=C[G++];for(let ft=0;ft<ze;ft++)Ne[ve++]=ye}else Ne.set(C.subarray(G,G+ze),ve),ve+=ze,G+=ze}const je=F;for(let Me=0;Me<je;Me++){let ye=0;N[H]=Ne[Me+ye],ye+=F,N[H+1]=Ne[Me+ye],ye+=F,N[H+2]=Ne[Me+ye],ye+=F,N[H+3]=Ne[Me+ye],H+=4}ot--}return N},w=function(C,D,I,F){const N=C[D+3],H=Math.pow(2,N-128)/255;I[F+0]=C[D+0]*H,I[F+1]=C[D+1]*H,I[F+2]=C[D+2]*H,I[F+3]=1},x=function(C,D,I,F){const N=C[D+3],H=Math.pow(2,N-128)/255;I[F+0]=p.DataUtils.toHalfFloat(Math.min(C[D+0]*H,65504)),I[F+1]=p.DataUtils.toHalfFloat(Math.min(C[D+1]*H,65504)),I[F+2]=p.DataUtils.toHalfFloat(Math.min(C[D+2]*H,65504)),I[F+3]=p.DataUtils.toHalfFloat(1)},_=new Uint8Array(e);_.pos=0;const A=f(_),T=A.width,S=A.height,b=m(_.subarray(_.pos),T,S);let M,P,L;switch(this.type){case p.FloatType:L=b.length/4;const C=new Float32Array(L*4);for(let I=0;I<L;I++)w(b,I*4,C,I*4);M=C,P=p.FloatType;break;case p.HalfFloatType:L=b.length/4;const D=new Uint16Array(L*4);for(let I=0;I<L;I++)x(b,I*4,D,I*4);M=D,P=p.HalfFloatType;break;default:throw new Error("THREE.HDRLoader: Unsupported type: "+this.type)}return{width:T,height:S,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 ql extends Yl{constructor(e){console.warn("RGBELoader has been deprecated. Please use HDRLoader instead."),super(e)}}class $l 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 o=new p.Mesh(e,t);o.position.set(-.757,13.219,.717),o.scale.set(31.713,28.305,28.591),this.add(o);const r=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(),r.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(),r.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(),r.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(),r.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(),r.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(),r.setMatrixAt(5,a.matrix),this.add(r);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 Ql{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 o=n.getDomElement();if(o&&"parentElement"in o&&o.parentElement){const r=o.parentElement.renderer;r instanceof E.WebGLRenderer&&(s=r)}}return s?(this.pmremGenerator=new E.PMREMGenerator(s),this.pmremGenerator.compileEquirectangularShader(),k.ok(void 0)):k.err(new Z("Could not access Three.js renderer",X.INITIALIZATION_FAILED))}catch(n){return k.err(new Z("Failed to initialize environment service",X.INITIALIZATION_FAILED,{originalError:n}))}}async loadEnvironmentMap(e){var t;try{const n=this.loadedTextures.get(e);if(n)return k.ok(new Tn(n));const s=(t=e.split(".").pop())==null?void 0:t.toLowerCase();let o;switch(s){case"hdr":o=new ql;break;case"exr":o=new Xl;break;case"jpg":case"jpeg":case"png":o=new E.TextureLoader;break;default:return k.err(new Z(`Unsupported environment map format: ${s}`,X.UNSUPPORTED_FORMAT,{url:e,extension:s}))}const r=await new Promise((a,c)=>{o.load(e,u=>{a(u)},void 0,u=>c(u))});if(this.disposed)return r.dispose(),k.err(new Z("Environment service was disposed during the load",X.INVALID_STATE,{url:e}));if(this.pmremGenerator){r.mapping=E.EquirectangularReflectionMapping;const a=this.pmremGenerator.fromEquirectangular(r);this.renderTargets.push(a);const c=a.texture;return this.loadedTextures.set(e,c),this.loadedTextures.set(e+"_original",r),k.ok(new Tn(c))}return this.loadedTextures.set(e,r),k.ok(new Tn(r))}catch(n){return k.err(new Z("Failed to load environment map",X.TEXTURE_LOAD_FAILED,{url:e,originalError:n}))}}applyToScene(e,t,n){try{const s=Et(e);if(!s)return k.err(new Z("Scene must be ThreeSceneAdapter",X.INVALID_PARAMETER));const o=pl(t);if(!o)return k.err(new Z("Texture must be ThreeTextureAdapter",X.INVALID_PARAMETER));if(s.environment=o,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)),o.mapping===E.CubeUVReflectionMapping){const a=Array.from(this.loadedTextures.entries()).find(([c,u])=>c.endsWith("_original")&&u.mapping===E.EquirectangularReflectionMapping);a&&(s.__originalEnvironmentTexture=a[1])}else o.mapping===E.EquirectangularReflectionMapping&&(s.__originalEnvironmentTexture=o);if((n==null?void 0:n.setBackground)??!0)if(o.mapping===E.EquirectangularReflectionMapping)s.background=o;else if(o.mapping===E.CubeUVReflectionMapping){const a=Array.from(this.loadedTextures.entries()).find(([c,u])=>c.endsWith("_original")&&u.mapping===E.EquirectangularReflectionMapping);a?s.background=a[1]:s.background=o}else s.background=o;return k.ok(void 0)}catch(s){return k.err(new Z("Failed to apply environment to scene",X.SCENE_OPERATION_FAILED,{originalError:s}))}}getOriginalEnvironmentTexture(e){const t=this.loadedTextures.get(e+"_original");return t?new Tn(t):null}createStudioEnvironment(e={}){try{if(!this.pmremGenerator)return k.err(new Z("Environment service not initialized",X.INITIALIZATION_FAILED));const t=new $l,n=this.pmremGenerator.fromScene(t);this.renderTargets.push(n);const s=n.texture;return t.dispose(),k.ok(new Tn(s))}catch(t){return k.err(new Z("Failed to create studio environment",X.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 Tn{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 Jl{constructor(e){this.object=e,this.boundingBox=new E.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 E.Vector3;return t>0?n.y=-e:n.y=0,n}applyOffset(e){this.object.position.add(e)}}class eh{alignToFloor(e){try{let t=null;return"getThreeObject"in e&&typeof e.getThreeObject=="function"?t=e.getThreeObject():e instanceof E.Object3D&&(t=e),t?(new Jl(t).alignToFloor(),k.ok(void 0)):k.err(new Z("Could not get Three.js object for floor alignment",X.INVALID_PARAMETER))}catch(t){return k.err(new Z("Failed to align object to floor",X.OPERATION_FAILED,{originalError:t}))}}}const yr={touch:10,default:5};class th{constructor(){this.raycaster=new E.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=r=>{this.activePointers.add(r.pointerId);try{t.setPointerCapture(r.pointerId)}catch{}if(this.activePointers.size>1||r.button!==0){this.pending=null;return}this.pending={pointerId:r.pointerId,x:r.clientX,y:r.clientY,threshold:r.pointerType==="touch"?yr.touch:yr.default}},s=r=>{this.activePointers.delete(r.pointerId);const a=this.pending;!a||a.pointerId!==r.pointerId||(this.pending=null,Math.hypot(r.clientX-a.x,r.clientY-a.y)>a.threshold)||this.pick(r.clientX,r.clientY)},o=r=>{this.activePointers.delete(r.pointerId),this.pending=null};t.addEventListener("pointerdown",n),t.addEventListener("pointerup",s),t.addEventListener("pointercancel",o),this.detach=()=>{t.removeEventListener("pointerdown",n),t.removeEventListener("pointerup",s),t.removeEventListener("pointercancel",o)}}pick(e,t){if(!this.options)return;const{canvas:n,camera:s,getPickRoot:o,onPick:r}=this.options,a=o(),c=wt(a),u=vn(s);if(!c||!u){r(null);return}const d=n.getBoundingClientRect();if(d.width===0||d.height===0){r(null);return}const h=new E.Vector2((e-d.left)/d.width*2-1,-((t-d.top)/d.height)*2+1);(this.options.bvh??!0)&&Nr(c),this.raycaster.setFromCamera(h,u),this.raycaster.firstHitOnly=!0;const f=this.raycaster.intersectObject(c,!0)[0];if(!f){r(null);return}r({object:new Ke(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 nh=.001,wr={visible:!1};class sh{constructor(e){this.sources=e,this.anchor=new E.Vector3,this.projected=new E.Vector3,this.cameraPosition=new E.Vector3,this.toAnchor=new E.Vector3,this.raycaster=new E.Raycaster,this.lastCameraMatrix=new E.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 o=s.clientWidth||s.width,r=s.clientHeight||s.height;return this.hasProjected&&o===this.lastWidth&&r===this.lastHeight&&this.lastCameraMatrix.equals(n.matrixWorld)?null:(this.lastCameraMatrix.copy(n.matrixWorld),this.lastWidth=o,this.lastHeight=r,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)?wr:(this.projected.copy(this.anchor).project(n),{visible:!0,left:(this.projected.x+1)/2*o,top:(1-this.projected.y)/2*r}))}isOccluded(e){const t=wt(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-nh)}}class ih{createProjector(e){return new sh(e)}}class rh{constructor(){this.mixer=null,this.clips=[],this.activeActions=[],this.playing=!1,this.speed=1}attach(e){this.detach();const t=wt(e);if(!t)return;const n=oh(t);n&&(this.clips=n.animations,this.mixer=new E.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 k.err(new Z(`Cannot play animation clip '${e}': no animation clips are attached`,X.INVALID_STATE));if(!this.clips.some(s=>s.name===e)){const s=this.clips.map(o=>o.name);return k.err(new Z(`Unknown animation clip '${e}'. Available clips: ${s.join(", ")}`,X.INVALID_PARAMETER))}}if(!this.mixer)return k.ok(void 0);if(!this.playing&&this.activeActions.length>0&&e===void 0)return this.playing=!0,k.ok(void 0);const t=e?this.clips.filter(s=>s.name===e):this.clips;if(t.length===0)return k.ok(void 0);const n=this.mixer;return n.stopAllAction(),this.activeActions=t.map(s=>{const o=n.clipAction(s);return o.play(),o}),this.playing=!0,k.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 oh(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 Mn=(i=>(i.MapControls="MapControls",i.OrbitControls="OrbitControls",i))(Mn||{});class ah{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===E.BasicShadowMap)return"basic";if(e===E.PCFShadowMap)return"pcf";if(e===E.PCFSoftShadowMap)return"pcfsoft";if(e===E.VSMShadowMap)return"vsm"}return typeof e=="string"?e:void 0}static convertToneMappingType(e){if(typeof e=="number"){if(e===E.NoToneMapping)return"none";if(e===E.LinearToneMapping)return"linear";if(e===E.ReinhardToneMapping)return"reinhard";if(e===E.CineonToneMapping)return"cineon";if(e===E.ACESFilmicToneMapping)return"aces"}return typeof e=="string"?e:"aces"}}class ch{static createViewer(e,t){var T,S,b;xr(t.units);const n=new dc(e),s=new kr,o=this.createCamera(t),r=this.createControls(o.getThreeCamera(),e,t),a=new lh().createDefaultLoader({renderer:n.getThreeRenderer()??void 0,bvh:(T=t.selection)==null?void 0:T.bvh,...t.loaders}),c=new Ll,u=new Ql;let d;(((S=t.pathTracing)==null?void 0:S.enabled)??!1)&&(d=new Pl);const f=new eh,m=new th,w=new ih,x=new rh,_=ah.convertRendererOptions(t.renderer||{});(t.replaceWithScreenshotOnComplete||(b=t.pathTracing)!=null&&b.enabled)&&(_.preserveDrawingBuffer=!0);const A={renderer:n,scene:s,camera:o,controls:r,modelLoader:a,options:t,rendererOptions:_,sceneSetupService:c,environmentService:u,pathTracingService:d,floorAlignmentService:f,selectionService:m,anchorProjectionService:w,animationService:x};return new aa(A)}static createCamera(e){const n=e.camera||{},s=n.fov||n.cameraFov||75,o=n.near||n.cameraNear||.1,r=n.far||n.cameraFar||1e5,a=n.position||n.cameraPosition,c=n.target||n.cameraTarget,u=Si.create(s,1,o,r);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||{},o=s.type||Mn.OrbitControls;let r;o===Mn.MapControls?r=new fl(e,t):r=new dl(e,t),r.enabled=s.enabled??!0,r.enableDamping=s.enableDamping??!0,r.dampingFactor=s.dampingFactor??.25,r.enableZoom=s.enableZoom??!0,r.enableRotate=s.enableRotate??!0,r.enablePan=s.enablePan??!0,r.autoRotate=s.autoRotate??!1,s.autoRotateSpeed!==void 0&&(r.autoRotateSpeed=s.autoRotateSpeed),s.minDistance!==void 0&&(r.minDistance=s.minDistance),s.maxDistance!==void 0&&(r.maxDistance=s.maxDistance),s.minPolarAngle!==void 0&&(r.minPolarAngle=s.minPolarAngle),s.maxPolarAngle!==void 0&&(r.maxPolarAngle=s.maxPolarAngle);const c=n.camera||{},u=c.target||c.cameraTarget;return u&&r.target&&(r.target.set(u[0],u[1],u[2]),r.update()),r}}class lh extends fr{createDefaultLoader(e={}){return fr.createLoader("model.glb",e)}}const hh=["toneMappingExposure"],uh=["environmentIntensity"],dh=["autoRotate","autoRotateSpeed"];function Jr(i){var t,n,s,o,r,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||((o=i.controls)==null?void 0:o.autoRotateSpeed)!==void 0)&&(e.controls={autoRotate:(r=i.controls)==null?void 0:r.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:Mn.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}},Ai={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?Ai[i]:{}}function mi(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 fh(i){const e=se.useMemo(()=>{var s;return JSON.stringify({pathTracing:i.pathTracing,staticScene:i.staticScene,renderer:Ks(i.renderer,...hh),camera:i.camera,controls:Ks(i.controls,...dh),environment:Ks(i.environment,...uh),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=se.useMemo(()=>{const s=mi(ys,i);return JSON.stringify(Jr(s))},[i.preset,i.backgroundColor,i.renderer,i.environment,i.controls,i.animations]);return{options:se.useMemo(()=>i,[e,t]),structuralKey:e,runtimeKey:t}}const ph="200px";function mh(i,e){const[t,n]=se.useState(!e);return se.useEffect(()=>{if(t)return;if(!e){n(!0);return}const s=i.current;if(!s||typeof IntersectionObserver>"u"){n(!0);return}const o=new IntersectionObserver(r=>{r.some(a=>a.isIntersecting)&&n(!0)},{rootMargin:ph});return o.observe(s),()=>o.disconnect()},[i,e,t]),t}function gh(i,e){const t=se.useRef(null),[n,s]=se.useState(!1),[o,r]=se.useState(null),{options:a,structuralKey:c,runtimeKey:u}=fh(e),d=mh(i,(e.loading??"eager")==="lazy");se.useEffect(()=>{if(!d||!i.current||t.current)return;r(null);const f=mi(ys,a);let m;try{m=ch.createViewer(i.current,f)}catch(x){console.error("Failed to create viewer:",x),r(x instanceof Error?x:new Error(String(x)));return}t.current=m;let w=!1;return m.initialize().then(x=>{w||(x.ok?s(!0):(console.error("Failed to initialize viewer:",x.error),r(x.error)))}),()=>{w=!0,m.dispose(),t.current=null,s(!1)}},[i,c,d]),se.useEffect(()=>{if(!t.current||!n)return;const f=mi(ys,a);t.current.updateOptions(Jr(f))},[u,n]);const h=se.useRef({width:0,height:0});return se.useEffect(()=>{if(!t.current||!i.current)return;let f=null;const m=_=>{if(i.current&&t.current){const A=i.current.parentElement||i.current;let{clientWidth:T,clientHeight:S}=A;if(_&&_[0]){const{width:b,height:M}=_[0].contentRect;T=Math.floor(b),S=Math.floor(M)}if(h.current.width===T&&h.current.height===S)return;f!==null&&cancelAnimationFrame(f),f=requestAnimationFrame(()=>{t.current&&i.current&&(t.current.resize(T,S),h.current={width:T,height:S})})}};m();const w=()=>m();window.addEventListener("resize",w);let x=null;return typeof ResizeObserver<"u"&&i.current.parentElement&&(x=new ResizeObserver(m),x.observe(i.current.parentElement)),()=>{window.removeEventListener("resize",w),x==null||x.disconnect(),f!==null&&cancelAnimationFrame(f)}},[n,i]),{viewer:t.current,isInitialized:n,initError:o}}function to(i,e){const t=se.useRef(e);t.current=e,se.useEffect(()=>{if(!i)return;const n=i.getEvents(),s=[],o=r=>{const a=c=>{var u,d;(d=(u=t.current)[r])==null||d.call(u,c)};return n.on(r,a),()=>n.off(r,a)};return Object.keys(e).forEach(r=>{e[r]&&s.push(o(r))}),()=>{s.forEach(r=>r())}},[i])}function yh(i,e){const[t,n]=se.useState(null),s=se.useRef(new Set);se.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 o=!!(e!=null&&e.presets);se.useEffect(()=>{o||(s.current.clear(),n(null))},[o]);const r=e==null?void 0:e.onPresetChange,a=se.useCallback(c=>{n(c),r&&(s.current.add(c),r(c))},[r]);return{activePreset:t??i,pickerEnabled:o,selectPreset:a}}function wh(i,e,t,n,s){return se.useMemo(()=>{var u,d,h;const o=i.preset!==e,r=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!o&&!r&&!a&&!c?i:{...i,...o?{preset:e}:{},...r?{pathTracing:{...i.pathTracing,enabled:!0}}:{},...a?{controls:{...i.controls,autoRotate:n}}:{},...c?{animations:{...i.animations,autoplay:s}}:{}}},[i,e,t,n,s])}function Eh(i,e,t){const n=se.useMemo(()=>{if(typeof t=="string")return t;if(t)return`object-${t.uuid||"no-uuid"}`},[t]),[s,o]=se.useState(()=>({status:t?"loading":"idle"}));return se.useEffect(()=>{o({status:t?"loading":"idle"})},[n]),se.useEffect(()=>{if(!i||!e||!t)return;let r=!0;const a=typeof t=="string"?t:new Ke(t);return i.loadModel(a).then(c=>{r&&(c.ok?o({status:"loaded"}):(o({status:"error",error:c.error.message}),console.error("Failed to load model:",c.error)))}),()=>{r=!1}},[i,e,n]),s}class Xs{static toThreeObject(e){const t=wt(e);if(t)return t;const n=new E.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 E.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 Th(i){const e=se.useRef(new Es),t=se.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 Sh(i,e,t){const n=se.useRef(t);n.current=t;const s=se.useMemo(()=>({"model:loaded":()=>{var r,a;return(a=(r=n.current).onLoad)==null?void 0:a.call(r)},"model:progress":r=>{var a,c;return(c=(a=n.current).onProgress)==null?void 0:c.call(a,Math.min(1,r.loaded/r.total))},"model:error":r=>{var a,c;return(c=(a=n.current).onError)==null?void 0:c.call(a,r.error)}}),[]);to(i,s);const o=se.useRef(null);se.useEffect(()=>{if(!e){o.current=null;return}const r=n.current.onError;r&&o.current!==e&&(o.current=e,r(e))})}const no=se.createContext(null);function _h({viewer:i,canvasRef:e,children:t}){const n=se.useMemo(()=>({viewer:i,canvasRef:e}),[i,e]);return me.jsx(no.Provider,{value:n,children:t})}function so(){const i=se.useContext(no);if(!i)throw new Error("useViewerContext must be used within ViewerProvider");return i}function bh(){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 xh=(i,e,t,n,s,o)=>{const r=performance.now(),a=()=>{const c=performance.now()-r,u=Math.min(c/s,1);i.position.lerpVectors(t,n,u),e==null||e.update(),o(),u<1&&requestAnimationFrame(a)};requestAnimationFrame(a)},Er={type:"change"},Mi={type:"start"},io={type:"end"},as=new p.Ray,Tr=new p.Plane,Ah=Math.cos(70*p.MathUtils.DEG2RAD),Oe=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=Rh.bind(this),this._onPointerDown=Mh.bind(this),this._onPointerUp=vh.bind(this),this._onContextMenu=Nh.bind(this),this._onMouseWheel=Lh.bind(this),this._onKeyDown=Ph.bind(this),this._onTouchStart=Oh.bind(this),this._onTouchMove=Dh.bind(this),this._onMouseDown=Ch.bind(this),this._onMouseMove=Ih.bind(this),this._interceptControlDown=kh.bind(this),this._interceptControlUp=Fh.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(Er),this.update(),this.state=Te.NONE}update(e=null){const t=this.object.position;Oe.copy(t).sub(this.target),Oe.applyQuaternion(this._quat),this._spherical.setFromVector3(Oe),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 o=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const r=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),o=r!=this._spherical.radius}if(Oe.setFromSpherical(this._spherical),Oe.applyQuaternion(this._quatInverse),t.copy(this.target).add(Oe),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 r=null;if(this.object.isPerspectiveCamera){const a=Oe.length();r=this._clampDistance(a*this._scale);const c=a-r;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),o=!!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(),o=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(),r=Oe.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;r!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(r).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))<Ah?this.object.lookAt(this.target):(Tr.setFromNormalAndCoplanarPoint(this.object.up,this.target),as.intersectPlane(Tr,this.target))))}else if(this.object.isOrthographicCamera){const r=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),r!==this.object.zoom&&(this.object.updateProjectionMatrix(),o=!0)}return this._scale=1,this._performCursorZoom=!1,o||this._lastPosition.distanceToSquared(this.object.position)>Ys||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Ys||this._lastTargetPosition.distanceToSquared(this.target)>Ys?(this.dispatchEvent(Er),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){Oe.setFromMatrixColumn(t,0),Oe.multiplyScalar(-e),this._panOffset.add(Oe)}_panUp(e,t){this.screenSpacePanning===!0?Oe.setFromMatrixColumn(t,1):(Oe.setFromMatrixColumn(t,0),Oe.crossVectors(this.object.up,Oe)),Oe.multiplyScalar(e),this._panOffset.add(Oe)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;Oe.copy(s).sub(this.target);let o=Oe.length();o*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*o/n.clientHeight,this.object.matrix),this._panUp(2*t*o/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,o=t-n.top,r=n.width,a=n.height;this._mouse.x=s/r*2-1,this._mouse.y=-(o/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,o=Math.sqrt(n*n+s*s);this._dollyStart.set(0,o)}_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),o=.5*(e.pageY+n.y);this._rotateEnd.set(s,o)}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,o=Math.sqrt(n*n+s*s);this._dollyEnd.set(0,o),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 r=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(r,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 Mh(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 Rh(i){this.enabled!==!1&&(i.pointerType==="touch"?this._onTouchMove(i):this._onMouseMove(i))}function vh(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 Ch(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(Mi)}function Ih(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 Lh(i){this.enabled===!1||this.enableZoom===!1||this.state!==Te.NONE||(i.preventDefault(),this.dispatchEvent(Mi),this._handleMouseWheel(this._customWheelEvent(i)),this.dispatchEvent(io))}function Ph(i){this.enabled!==!1&&this._handleKeyDown(i)}function Oh(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(Mi)}function Dh(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 Nh(i){this.enabled!==!1&&i.preventDefault()}function kh(i){i.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function Fh(i){i.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}class Bh 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 Lt=(i=>(i.FRONT="FRONT",i.BACK="BACK",i.RIGHT="RIGHT",i.LEFT="LEFT",i.TOP="TOP",i.BOTTOM="BOTTOM",i))(Lt||{});new E.Vector3(0,1,0);const Rn="rotation-arrows-name",gi="left-rotation-arrow-name",ws="right-rotation-arrow-name",zh="gizmo-group-name",Uh=[ws,gi],fs={GIZMO_DISTANCE:8,DEFAULT_UP:new E.Vector3(0,1,0),FORWARD:new E.Vector3(0,0,-1)},qs=i=>fs.FORWARD.clone().applyQuaternion(i),Sr=(i,e,t=new E.Vector3)=>t.clone().add(i.multiplyScalar(-e));class Vh{constructor(e,t=Rn){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(Sr(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(),o=e.position.distanceTo(s),r=e.camera instanceof E.PerspectiveCamera;n instanceof Bh&&!r?this.syncMapControls(e,t,s,o):this.syncOrbitControls(e,t,s,o),e.camera.updateMatrix(),e.camera.updateMatrixWorld(!0),n.update()}syncMapControls(e,t,n,s){const o=e.position.y-n.y,r=qs(t.quaternion);r.y=0,r.normalize();const a=n.clone();a.y+=o,a.add(r.multiplyScalar(-s)),e.position.copy(a),e.up.copy(fs.DEFAULT_UP),e.camera.lookAt(n)}syncOrbitControls(e,t,n,s){const o=qs(t.quaternion),r=fs.DEFAULT_UP.clone().applyQuaternion(t.quaternion),a=Sr(o,s,n);e.position.copy(a),e.up.copy(r),e.camera.lookAt(n)}}const oo=i=>new Vh(i),_r=(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})},Hh=(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)},jh=()=>{try{const i=document.createElement("canvas");return!!(window.WebGLRenderingContext&&(i.getContext("webgl")||i.getContext("experimental-webgl")))}catch{return!1}},Gh=()=>jh()?new E.WebGLRenderer({alpha:!0,antialias:!1}):(console.error("WebGL is not supported in this environment."),null),Wh=i=>{const e=new E.AmbientLight(16777215,1);i.add(e);const t=new E.DirectionalLight(16777215,1);t.position.set(5,10,5),i.add(t);const n=new E.DirectionalLight(16777215,1);n.position.set(-5,-10,5),i.add(n);const s=new E.PointLight(16777215,1,100);s.position.set(0,0,5),i.add(s),t.castShadow=!1,n.castShadow=!1,s.castShadow=!1};class Zh{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 E.CanvasTexture(t);return s.needsUpdate=!0,s}}class cs{static createWireframe([e,t,n]){const s=new E.BoxGeometry(e,t,n),o=new E.EdgesGeometry(s),r=new E.LineBasicMaterial({color:fe.LINE_COLOR}),a=new E.LineSegments(o,r);return a.name="Wireframe",a}static createEdgeBox(e,t,n){const s=fe.CUBE_SIZE-fe.EDGE_SECTION_SIZE,o={x:fe.EDGE_SECTION_SIZE,y:fe.EDGE_SECTION_SIZE,z:fe.EDGE_SECTION_SIZE};o[t]=s;const r=new E.BoxGeometry(o.x,o.y,o.z),a=new E.MeshStandardMaterial({color:fe.EDGE_COLOR}),c=new E.Mesh(r,a);return c.position.copy(e),c.name=`Edge Box ${n}`,c}static createCornerCube(e,t){const n=new E.BoxGeometry(fe.EDGE_SECTION_SIZE,fe.EDGE_SECTION_SIZE,fe.EDGE_SECTION_SIZE),s=new E.MeshStandardMaterial({color:fe.CORNER_COLOR}),o=new E.Mesh(n,s);return o.position.copy(e),o.name=`Corner Cube ${t}`,o}static createFace(e,t,n){const s=new E.Group,o=new E.BoxGeometry(fe.CUBE_SIZE-fe.EDGE_SECTION_SIZE,fe.CUBE_SIZE-fe.EDGE_SECTION_SIZE,fe.FACE_THICKNESS),r=new E.MeshStandardMaterial({color:fe.FACE_COLOR}),a=new E.Mesh(o,r);a.name=`Face Box ${n}`,s.add(a);const c=new E.PlaneGeometry(fe.CUBE_SIZE-fe.EDGE_SECTION_SIZE,fe.CUBE_SIZE-fe.EDGE_SECTION_SIZE),u=new E.MeshStandardMaterial({map:Zh.createTextTexture(n),transparent:!0,depthWrite:!1}),d=new E.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 Kh=(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 E.CanvasTexture(t),o=new E.SpriteMaterial({map:s}),r=new E.Sprite(o);return r.scale.set(.5,.5,.5),r};class Xh{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 Lt.BACK:return new E.Euler(0,Math.PI,0);case Lt.RIGHT:return new E.Euler(0,-Math.PI/2,0);case Lt.LEFT:return new E.Euler(0,Math.PI/2,0);case Lt.TOP:return new E.Euler(Math.PI/2,0,0);case Lt.BOTTOM:return new E.Euler(-Math.PI/2,0,0);case Lt.FRONT:default:return new E.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),o=s.getObjectByName(`Face Box ${n}`);return o.userData.gizmoCube=this,s}createEdges(e){const t=fe.CUBE_SIZE/2;[{axis:"x",pos:new E.Vector3(0,t,-t)},{axis:"x",pos:new E.Vector3(0,t,t)},{axis:"x",pos:new E.Vector3(0,-t,-t)},{axis:"x",pos:new E.Vector3(0,-t,t)},{axis:"y",pos:new E.Vector3(t,0,-t)},{axis:"y",pos:new E.Vector3(t,0,t)},{axis:"y",pos:new E.Vector3(-t,0,-t)},{axis:"y",pos:new E.Vector3(-t,0,t)},{axis:"z",pos:new E.Vector3(t,t,0)},{axis:"z",pos:new E.Vector3(t,-t,0)},{axis:"z",pos:new E.Vector3(-t,t,0)},{axis:"z",pos:new E.Vector3(-t,-t,0)}].forEach(({axis:n,pos:s},o)=>{const r=this.createEdgeBox(s,n,o+1);e.add(r)})}createCorners(e){const t=fe.CUBE_SIZE/2;[new E.Vector3(-t,-t,-t),new E.Vector3(-t,-t,t),new E.Vector3(-t,t,-t),new E.Vector3(-t,t,t),new E.Vector3(t,-t,-t),new E.Vector3(t,-t,t),new E.Vector3(t,t,-t),new E.Vector3(t,t,t)].forEach((n,s)=>{const o=this.createCornerCube(n,s+1);e.add(o)})}createFaces(e){const t=fe.CUBE_SIZE/2;[{pos:new E.Vector3(0,0,t),rotation:new E.Euler(0,0,0),label:"FRONT"},{pos:new E.Vector3(0,0,-t),rotation:new E.Euler(0,Math.PI,0),label:"BACK"},{pos:new E.Vector3(t,0,0),rotation:new E.Euler(0,Math.PI/2,0),label:"RIGHT"},{pos:new E.Vector3(-t,0,0),rotation:new E.Euler(0,-Math.PI/2,0),label:"LEFT"},{pos:new E.Vector3(0,t,0),rotation:new E.Euler(-Math.PI/2,0,0),label:"TOP"},{pos:new E.Vector3(0,-t,0),rotation:new E.Euler(Math.PI/2,0,0),label:"BOTTOM"}].forEach(({pos:n,rotation:s,label:o})=>{const r=this.createFace(n,s,o);e.add(r)})}createAxis(e){const{color:t,direction:n,length:s,origin:o,lineWidth:r,label:a}=e,c=new E.Group,u=r/2,d=new E.CylinderGeometry(u,u,s,32),h=new E.MeshBasicMaterial({color:t}),f=new E.Mesh(d,h);if(f.position.copy(o).add(n.clone().multiplyScalar(s/2)),!n.equals(new E.Vector3(0,1,0))){const w=new E.Vector3(0,1,0).cross(n).normalize(),x=Math.acos(new E.Vector3(0,1,0).dot(n));f.setRotationFromAxisAngle(w,x)}c.add(f);const m=Kh(a,t);return m.position.copy(o).add(n.clone().multiplyScalar(s+.1)),c.add(m),c}createCoordinateAxes(){const e=new E.Group,t=fe.CUBE_SIZE,n=fe.EDGE_SECTION_SIZE,s=-1.075,o=a=>{const c=new E.Vector3(1,1,1);return new E.Vector3(a,a,a).add(c.clone().normalize().negate().multiplyScalar(.04))},r=t+1.25*n;return[{color:16711680,direction:new E.Vector3(1,0,0),length:r,origin:o(s),lineWidth:.04,label:"X"},{color:65280,direction:new E.Vector3(0,1,0),length:r,origin:o(s),lineWidth:.04,label:"Y"},{color:255,direction:new E.Vector3(0,0,1),length:r,origin:o(s),lineWidth:.04,label:"Z"}].forEach(a=>{const c=this.createAxis(a);e.add(c)}),e}create(){const e=new E.Group;e.name=zh;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 E.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 E.Vector3;e=this.hoveredObject.getWorldPosition(e).clone();const t=new E.Vector3(0,0,0),n=e.sub(t).normalize();this.hoveredObject.userData.vectorToCube=n}}}class Yh{constructor(e){this.onChangeMainControlsListener=()=>{},this.onChangeGizmoControlsListener=()=>{},this.animationId=0;const{gizmoParams:t,mainParams:n,syncFunctions:s,options:o}=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=o,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 Xh({initialFace:((e=this.options)==null?void 0:e.initialFace)??Lt.FRONT}).create();this.gizmoScene.add(t),Wh(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(Rn);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 qh=(i,e)=>{let t;return function(...n){t||(i.apply(this,n),t=!0,setTimeout(()=>t=!1,e))}};function br(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 $h(i,e,t,n){if(!e||!t)return null;const s=ao(i,e,t,n);return co(s)}function Qh(i,e){const t=i==null?void 0:i.userData.gizmoCube;if(i&&t){t.handleClick();const n=t.vectorToCube;n&&e(n)}}const Jh={radius:2.1,color:12369854,tubeRadius:.1,tubeSegments:8,numPoints:64,tubeOffset:1.5},eu={size:.2,depth:.1,heightRatio:1.4,segments:1};class tu{constructor(e={}){this.config={...Jh,...e},this.material=new E.MeshBasicMaterial({color:this.config.color})}create(){const e=new E.Group,t=this.createQuarterCircleCurves();return e.add(...this.createTubes(t),...this.createArrowHeads(t)),e.name=Rn,e}createQuarterCircleCurves(){const e=this.generateQuarterCirclePoints(),t=Math.floor(e.length/2);return[new E.CatmullRomCurve3(e.slice(0,t-this.config.tubeOffset)),new E.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,o)=>{const r=o/this.config.numPoints,a=n+t*r,c=this.config.radius*Math.sin(a),u=this.config.radius*Math.cos(a);return new E.Vector3(c,u,0)})}createTubes([e,t]){const n=(s,o)=>{const r=new E.TubeGeometry(s,this.config.numPoints,this.config.tubeRadius,this.config.tubeSegments,!1),a=new E.Mesh(r,this.material);return a.name=o,a};return[n(e,gi),n(t,ws)]}createArrowHeads([e,t]){const{size:n,depth:s,heightRatio:o,segments:r}=eu,a=this.createArrowShape(n,o),c=new E.ExtrudeGeometry(a,{steps:r,depth:s,bevelEnabled:!1}).center(),u=(d,h,f)=>{const m=new E.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,gi),u(t.getPoint(1),this.calculateArrowRotation(t.getTangent(1))-Math.PI/2,ws)]}createArrowShape(e,t){return new E.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 nu=i=>{const e=i.rotation,t=.01,n=Math.PI,s=(Math.abs(e.x)%(2*n)+2*n)%(2*n),o=(Math.abs(e.y)%(2*n)+2*n)%(2*n),r=Math.abs(s-n/2)<t||Math.abs(s-3*n/2)<t||Math.abs(o-n/2)<t||Math.abs(o-3*n/2)<t,a=(Math.abs(s)<t||Math.abs(s-n)<t)&&(Math.abs(o)<t||Math.abs(o-n)<t);return!(r||a)},su=25,iu=200;function ru({gizmoRenderer:i,gizmoScene:e,gizmoCamera:t,alignCameraWithVector:n,gizmoControlRef:s}){const o=se.useRef(null),r=se.useRef(null),a=se.useRef(new E.Raycaster).current,c=se.useRef(new E.Vector2).current,u=se.useCallback(()=>{const x=e.getObjectByName(Rn),_=nu(t);if(x&&_){e.remove(x);return}if(x||_)return;const A=new tu().create();A.rotation.copy(t.rotation),e.add(A)},[e,t]),d=se.useCallback(()=>{const x=e.getObjectByName(Rn);x&&e.remove(x)},[e]),h=se.useCallback(qh(x=>{if(!s.current||!i)return;br(x,i,c);const _=ao(c,t,e,a),A=co(_);A!=null&&A.userData.gizmoCube?A.userData.gizmoCube.highlightObject(A):e.traverse(T=>{T.userData.gizmoCube&&T.userData.gizmoCube.highlightObject(null)}),_.length>0?u():d()},1e3/su),[s,i,t,e,a,c,u,d]),f=se.useCallback(x=>{o.current=Date.now(),r.current={x:x.clientX,y:x.clientY}},[]),m=se.useCallback(x=>{var _;const A=x.name===ws?1:-1,T=90*Math.PI/180,S=new E.Vector3(0,0,0),b=A*T,M=new E.Matrix4;M.makeRotationZ(b),t.up.applyMatrix4(M),t.lookAt(S),(_=s.current)==null||_.gizmoControls.update()},[t,s]),w=se.useCallback(x=>{if((o.current?Date.now()-o.current:0)<iu){br(x,i,c);const _=$h(c,t,e,a);_!=null&&_.name&&Uh.includes(_.name)?m(_):Qh(_,n)}o.current=null,r.current=null},[m,n,i,t,e,a,c]);return{onMouseDown:f,onMouseMove:h,onMouseUp:w,onMouseLeave:d}}const ou=({camera:i,controls:e,className:t,render:n,options:s})=>{const o=se.useRef(null),r=se.useRef(new E.Scene).current,[a]=se.useState(()=>Gh()),c=30,u=1,d=.1,h=10,f=new E.PerspectiveCamera(c,u,d,h),m=se.useRef(f).current,w=se.useRef(null),x=se.useCallback(()=>{a&&(n(),a.render(r,m))},[n,a,r,m]),_=se.useCallback(M=>{if(!i||!e)return;const P=i.position.length(),L=M.clone().multiplyScalar(P),C=400,D=new E.Matrix4;D.lookAt(L,new E.Vector3(0,0,0),new E.Vector3(0,1,0));const I=new E.Quaternion;I.setFromRotationMatrix(D),i.quaternion.copy(I),xh(i,e,i.position.clone(),L,C,x),i.up.set(0,1,0),i.lookAt(new E.Vector3(0,0,0)),e.target.set(0,0,0),e.update()},[i,e,x,r]),{onMouseDown:A,onMouseMove:T,onMouseUp:S,onMouseLeave:b}=ru({gizmoRenderer:a,gizmoScene:r,gizmoCamera:m,alignCameraWithVector:_,gizmoControlRef:w});return se.useEffect(()=>{const M=o.current;if(!M||!i||!e||!a)return;w.current&&w.current.dispose();const P={gizmoDiv:M,gizmoScene:r,gizmoRenderer:a,gizmoCamera:m},L={mainCamera:i,mainControls:e,renderGizmo:x},C={syncGizmoCameraWithMain:_r,syncMainCameraWithGizmo:Hh};return w.current=new Yh({gizmoParams:P,mainParams:L,syncFunctions:C,options:s}),M.addEventListener("mousedown",A),M.addEventListener("mousemove",T),M.addEventListener("mouseup",S),M.addEventListener("mouseleave",b),()=>{w.current&&(w.current.dispose(),w.current=null),M.removeEventListener("mousedown",A),M.removeEventListener("mousemove",T),M.removeEventListener("mouseup",S),M.removeEventListener("mouseleave",b)}},[i,e,x,T,A,S]),se.useEffect(()=>{i&&(_r(m,i,r),x())},[i,x]),me.jsx("div",{className:t?`${t}`:"gizmo-default",ref:o})},ls=10,au=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"}),cu=({camera:i,controls:e,render:t,placement:n="top-right",size:s=128})=>{if(!i||!e)return null;const o=e;return me.jsx("div",{className:"viewer-gizmo-container",style:{position:"absolute",width:s,height:s,zIndex:1e3,...au(n)},children:me.jsx(ou,{camera:i,controls:o,render:t})})};class lu extends se.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 hu({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 uu='-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',du={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)"},fu=Object.keys(Ai);function pu({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",...du},children:fu.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:uu,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 Sn={enabled:!0,label:"Loading…",color:"#ffffff",backdrop:"rgba(15,16,20,0.6)"};function mu(i){return i===void 0||i===!0?Sn:i===!1?{...Sn,enabled:!1}:{enabled:i.enabled??!0,label:i.label??Sn.label,errorLabel:i.errorLabel,color:i.color??Sn.color,backdrop:i.backdrop??Sn.backdrop}}const hs=()=>new Z("Viewer is not ready yet",X.COMPONENT_NOT_MOUNTED),lo=se.forwardRef(({object:i,options:e={},preset:t,pathTraced:n,turntable:s,animations:o,children:r},a)=>{var N,H;const c=se.useRef(null),u=e.preset??t,{activePreset:d,pickerEnabled:h,selectPreset:f}=yh(u,e.ui),m=wh(e,d,n,s,o),{viewer:w,isInitialized:x,initError:_}=gh(c,m),A=Eh(w,x,i),T=Th(w);Sh(w,_,e);const S=w?vn(w.getCamera()):null,b=w?xi(w.getControls()):null,M=w?Wr(w.getRenderer()):null,P=se.useCallback(()=>{w==null||w.requestRender()},[w]),L=((N=e.helpers)==null?void 0:N.gizmo)!==void 0&&e.helpers.gizmo!==!1,C=typeof((H=e.helpers)==null?void 0:H.gizmo)=="object"?e.helpers.gizmo:{},D=se.useMemo(()=>mu(e.loadingIndicator),[e.loadingIndicator]),I=A.status==="error"||!!_,F=D.enabled&&(A.status==="loading"||I);return se.useImperativeHandle(a,()=>({scene:w?Et(w.getScene()):null,camera:S,renderer:M,controls:b,events:T,loadModel:async G=>{if(!w)throw hs();const $=typeof G=="string"?G:new Ke(G),re=await w.loadModel($);if(!re.ok)throw re.error},captureStill:async G=>{if(!w)throw hs();const $=await w.captureStill(G);if(!$.ok)throw $.error;return $.value},captureVideo:async G=>{if(!w)throw hs();const $=await w.captureVideo(G);if(!$.ok)throw $.error;return $.value},getAnimationNames:()=>(w==null?void 0:w.getAnimationNames())??[],playAnimations:G=>{if(!w)throw hs();const $=w.playAnimations(G);if(!$.ok)throw $.error},pauseAnimations:()=>{w==null||w.pauseAnimations()},dispose:()=>{w==null||w.dispose()}}),[w,S,M,b,T]),me.jsx(lu,{children:me.jsx(_h,{viewer:w,canvasRef:c,children:me.jsxs("div",{style:{position:"relative",width:"100%",height:"100%"},children:[me.jsx(bh,{}),L&&x&&S&&b&&me.jsx(cu,{camera:S,controls:b,render:P,placement:C.placement,size:C.size}),F&&me.jsx(hu,{status:I?"error":"loading",label:I?D.errorLabel??(_==null?void 0:_.message)??A.error??"Failed to load model":D.label,color:D.color,backdrop:D.backdrop}),h&&me.jsx(pu,{active:d??"studio",onSelect:f}),r]})})})});lo.displayName="SimpleViewer";const ho=se.forwardRef((i,e)=>me.jsx(lo,{ref:e,...i}));ho.displayName="SimpleViewer";const gu=()=>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 yu({position:i,occlude:e=!1,children:t}){const{viewer:n}=so(),s=se.useRef(null),[o,r,a]=i;se.useEffect(()=>{if(!n)return;const u=s.current;if(!u)return;const d=n.createAnchorProjector();if(!d)return;const h={x:o,y:r,z:a},f=()=>{const _=d.project(h,e);if(_){if(!_.visible){u.style.visibility="hidden";return}u.style.visibility="visible",u.style.left=`${_.left}px`,u.style.top=`${_.top}px`}},m=()=>{d.invalidate(),f()};f();const w=n.getEvents(),x=[w.on("render:complete",f),w.on("controls:change",f),w.on("model:loaded",m)];return window.addEventListener("resize",m),()=>{x.forEach(_=>_()),window.removeEventListener("resize",m)}},[n,o,r,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(gu,{})})}exports.BOUNDING_DATA_INDEX=ha;exports.BYTES_PER_NODE=Ve;exports.CONTACT_SHADOW_HELPER_FLAG=bi;exports.COUNT=Xe;exports.ControlType=Mn;exports.DEFAULT_PATH_TRACING_SAMPLES=$s;exports.ErrorCode=X;exports.Hotspot=yu;exports.IS_LEAF=Ie;exports.LEAFNODE_MASK_32=la;exports.MeshBVH=An;exports.OFFSET=He;exports.Result=k;exports.SAH=Ir;exports.SPLIT_AXIS=Ts;exports.SimpleViewerWrapper=ho;exports.ThreeViewerError=Z;exports.TypedEventEmitter=Es;exports.VIEWER_PRESETS=Ai;exports.defaultOptions=ys;exports.getIndexArray=Dr;exports.getVertexCount=Ss;exports.hasInternalRenderer=Rr;exports.resolvePreset=eo;