softbox 4.0.0 → 4.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,11 @@
1
+ "use strict";var Uo=Object.create;var Fi=Object.defineProperty;var Ho=Object.getOwnPropertyDescriptor;var Vo=Object.getOwnPropertyNames;var jo=Object.getPrototypeOf,Go=Object.prototype.hasOwnProperty;var Wo=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Vo(e))!Go.call(i,s)&&s!==t&&Fi(i,s,{get:()=>e[s],enumerable:!(n=Ho(e,s))||n.enumerable});return i};var Rs=(i,e,t)=>(t=i!=null?Uo(jo(i)):{},Wo(e||!i||!i.__esModule?Fi(t,"default",{value:i,enumerable:!0}):t,i));const me=require("react/jsx-runtime"),oe=require("react"),p=require("three");function Zo(i){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const t in i)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(i,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>i[t]})}}return e.default=i,Object.freeze(e)}const S=Zo(p);class K extends Error{constructor(e,t,n){super(e),this.code=t,this.context=n,this.name="ThreeViewerError",this.timestamp=new Date,Error.captureStackTrace&&Error.captureStackTrace(this,K)}static fromError(e,t,n){if(e instanceof K)return e;const s=e instanceof Error?e.message:String(e),r={...n,originalError:e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:e};return new K(s,t,r)}}var q=(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))(q||{});const z={ok(i){return{ok:!0,value:i}},err(i){return{ok:!1,error:i}},wrap(i){try{return z.ok(i())}catch(e){return z.err(e instanceof K?e:new K(String(e),q.UNKNOWN,{originalError:e}))}}};class ws{constructor(){this.listeners=new Map}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);const n=this.listeners.get(e);return n&&n.add(t),()=>{var s;(s=this.listeners.get(e))==null||s.delete(t)}}emit(e,t){var n;(n=this.listeners.get(e))==null||n.forEach(s=>{try{s(t)}catch(r){console.error(`Error in event listener for ${String(e)}:`,r)}})}once(e,t){const n=this.on(e,s=>{n(),t(s)});return n}removeAllListeners(e){e?this.listeners.delete(e):this.listeners.clear()}listenerCount(e){var t;return((t=this.listeners.get(e))==null?void 0:t.size)||0}off(e,t){var n;(n=this.listeners.get(e))==null||n.delete(t)}removeListener(e,t){this.off(e,t)}}const qs=300,Ko={meters:1,centimeters:.01,millimeters:.001,feet:.3048,inches:.0254},Xo="softbox-units-scale",Bi="#1a1a1f";class Yo{configureScene(e,t,n){var a,c,d;if(n.helpers){const u={grid:n.helpers.grid,axes:n.helpers.axes,gridColor:"#AAAAAA"},h=t.addHelpers(e,u);h.ok||console.warn("Failed to add helpers:",h.error)}const s=n.lighting;if(s){const u={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,u);h.ok||console.warn("Failed to add lighting:",h.error)}const r=(a=n.environment)==null?void 0:a.url,o=(((c=n.helpers)==null?void 0:c.studioEnvironment)??!1)&&(((d=n.helpers)==null?void 0:d.darkStudioMode)??!1);if(n.backgroundColor&&!r&&!o){const u=String(n.backgroundColor),h=t.createGradientBackground(e,{topColor:u,bottomColor:u});h.ok||console.warn("Failed to set background:",h.error)}}async configureEnvironment(e,t,n,s,r,o){var u,h,f,m,w,_;const a=await t.initialize({renderer:s,autoDispose:!0});if(o())return;a.ok||console.warn("Failed to initialize environment service:",a.error);const c={backgroundBlurriness:(u=r.environment)==null?void 0:u.backgroundBlurriness,backgroundIntensity:(h=r.environment)==null?void 0:h.backgroundIntensity,environmentIntensity:(f=r.environment)==null?void 0:f.environmentIntensity},d=(m=r.environment)==null?void 0:m.url;if(d){const E=await t.loadEnvironmentMap(d);if(o())return;E.ok?t.applyToScene(e,E.value,c):console.warn("Failed to load environment map:",E.error)}else if((w=r.helpers)!=null&&w.studioEnvironment){const E=t.createStudioEnvironment();if(E.ok){if(t.applyToScene(e,E.value,{...c,setBackground:!1}),(_=r.helpers)!=null&&_.darkStudioMode&&n){const b=n.createGradientBackground(e,{topColor:Bi,bottomColor:Bi});b.ok||console.warn("Failed to set dark studio background:",b.error)}}else console.warn("Failed to create studio environment:",E.error)}}}class qo{constructor(e={}){this.animationFrameId=null,this.lastRenderTime=0,this.idleTimeout=null,this.isIdle=!1,this.needsRender=!0,this.continuousRenderingEnabled=!1,this.continuousReasons=new Set,this.alwaysRender=!1,this.enableIdleDetection=e.enableIdleDetection??!0,this.idleDelay=e.idleDelay??1e3,this.targetFPS=e.targetFPS??60,this.frameInterval=1e3/this.targetFPS,this.enableFrameRateLimiting=e.enableFrameRateLimiting??!0,this.alwaysRender=e.alwaysRender??!1,this.lastRenderTime=performance.now()}requestRender(){this.needsRender=!0,this.wakeUp()}requireContinuous(e){this.continuousReasons.add(e),this.continuousRenderingEnabled=!0,this.wakeUp()}releaseContinuous(e){this.continuousReasons.delete(e),this.continuousRenderingEnabled=this.continuousReasons.size>0}hasContinuousDemand(){return this.continuousReasons.size>0}setAlwaysRender(e){this.alwaysRender=e,e&&this.wakeUp()}wakeUp(){this.idleTimeout!==null&&(clearTimeout(this.idleTimeout),this.idleTimeout=null),this.isIdle=!1}start(e){if(this.animationFrameId!==null)return;const t=n=>{if(this.animationFrameId===null)return;const s=n-this.lastRenderTime;if(this.enableFrameRateLimiting&&s<this.frameInterval){this.animationFrameId=requestAnimationFrame(t);return}(this.alwaysRender||this.needsRender||this.continuousRenderingEnabled)&&(e(s),this.lastRenderTime=n,this.needsRender=!1),this.enableIdleDetection&&!this.alwaysRender&&(this.continuousRenderingEnabled||this.needsRender?this.wakeUp():this.idleTimeout===null&&!this.isIdle&&(this.idleTimeout=window.setTimeout(()=>{this.isIdle=!0},this.idleDelay))),this.alwaysRender||!this.enableIdleDetection||!this.isIdle||this.continuousRenderingEnabled||this.needsRender?this.animationFrameId=requestAnimationFrame(t):this.animationFrameId=null};this.animationFrameId=requestAnimationFrame(t)}stop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.idleTimeout!==null&&(clearTimeout(this.idleTimeout),this.idleTimeout=null),this.isIdle=!1,this.needsRender=!1,this.continuousRenderingEnabled=!1,this.continuousReasons.clear(),this.alwaysRender=!1}isRunning(){return this.animationFrameId!==null}getIsIdle(){return this.isIdle}getNeedsRender(){return this.needsRender||this.continuousRenderingEnabled||this.alwaysRender}}function Hn(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function ps(i,e){if(!Hn(i)||!Hn(e))return e===void 0?i:e;const t=e,n={...i};for(const s of Object.keys(t)){const r=t[s];if(r===void 0)continue;const o=n[s];n[s]=Hn(o)&&Hn(r)?ps(o,r):r}return n}class xr{static serialize(e,t,n,s){const r=t.position,o=n.target||{x:0,y:0,z:0};return{modelUrl:e,cameraPosition:{x:r.x,y:r.y,z:r.z},cameraTarget:{x:o.x,y:o.y,z:o.z},controlsTarget:{x:o.x,y:o.y,z:o.z},rendererSize:{width:s.clientWidth,height:s.clientHeight}}}static async restore(e,t,n,s){t.position.set(e.cameraPosition.x,e.cameraPosition.y,e.cameraPosition.z),t.lookAt({x:e.cameraTarget.x,y:e.cameraTarget.y,z:e.cameraTarget.z,set:()=>{},copy:()=>{},add:()=>{},multiply:()=>{},normalize:()=>{},length:()=>0}),n.target&&n.target.set(e.controlsTarget.x,e.controlsTarget.y,e.controlsTarget.z),n.update&&n.update(),e.modelUrl&&s&&await s(e.modelUrl)}}function $s(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 $o{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 Ar(i){const e=i.toDataURL("image/png");return!e||e==="data:,"?null:e}class Qo{constructor(e){this.screenshotElement=null,this.isShowingScreenshot=!1,this.renderer=e.renderer,this.onRestore=e.onRestore}isActive(){return this.isShowingScreenshot}captureAndReplace(e,t,n,s){if(this.isShowingScreenshot)return;const r=this.renderer.getDomElement(),o=Ar(r);if(!o){console.warn("[ScreenshotManager] Screenshot capture produced no image, keeping live scene");return}const a=document.createElement("img");a.src=o,a.style.position="absolute",a.style.top="0",a.style.left="0",a.style.width="100%",a.style.height="100%",a.style.pointerEvents="auto",a.style.cursor="grab";const c=r.parentElement;if(c){this.serializedSceneState=xr.serialize(n,e,t,r),r.style.display="none",c.appendChild(a),this.screenshotElement=a,this.isShowingScreenshot=!0;const d=()=>{this.restore()};a.addEventListener("mousedown",d),a.addEventListener("touchstart",d);const u=()=>{this.isShowingScreenshot&&this.restore()};window.addEventListener("resize",u),this.screenshotResizeHandler=u,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 Jo{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);if(!a.ok)throw a.error;s=a.value.scene}else s=e;if(this.unitsScaleToMeters!==1){if(!this.sceneSetupService)throw new K("A units conversion is configured but no scene setup service is available to apply it",q.INVALID_PARAMETER);const a=this.sceneSetupService.wrapInUnitsScaleGroup(s,this.unitsScaleToMeters);if(!a.ok)throw a.error;s=a.value}this.currentModel&&(this.scene.remove(this.currentModel),this.disposeObject(this.currentModel));const r=this.scene.add(s);if(!r.ok)throw r.error;if(this.floorAlignmentService){const a=this.floorAlignmentService.alignToFloor(s);a.ok||console.warn("Failed to align model to floor:",a.error)}if(s.traverse(a=>{"castShadow"in a&&"receiveShadow"in a&&(a.castShadow=!0,a.receiveShadow=!0)}),this.currentModel=s,this.sceneSetupService){const a=this.sceneSetupService.addDynamicGrid(this.scene,s,2);a.ok||console.warn("Failed to add dynamic grid:",a.error);const c=this.sceneSetupService.snapObjectToFloor(this.scene,s);c.ok||console.warn("Failed to snap object to floor:",c.error);const d=this.sceneSetupService.fitShadowCameraToObject(this.scene,s);if(d.ok||console.warn("Failed to fit shadow camera to object:",d.error),this.renderer){const u=this.sceneSetupService.bakeContactShadow(this.scene,s,this.renderer);u.ok||console.warn("Failed to bake contact shadow:",u.error)}}if(this.autoFitToObject&&this.sceneSetupService){const a=this.sceneSetupService.fitCameraToObject(s,this.camera,this.controls);a.ok||console.warn("Failed to fit camera to object:",a.error)}const o=performance.now()-n;return t.emit("model:loaded",{model:s,loadTime:o}),z.ok(s)}catch(s){const r=s instanceof K?s:new K("Failed to load model",q.MODEL_LOAD_FAILED,{originalError:s,source:e});return t.emit("model:error",{error:r,url:typeof e=="string"?e:void 0}),z.err(r)}}disposeCurrentModel(){this.currentModel&&(this.scene.remove(this.currentModel),this.disposeObject(this.currentModel),this.currentModel=null)}disposeObject(e){e.dispose()}dispose(){var e,t;this.disposeCurrentModel(),(t=(e=this.modelLoader).dispose)==null||t.call(e),this.lastModelUrl=void 0}}class ea{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 Mr(i){return typeof i=="object"&&i!==null&&"getInternalRenderer"in i&&typeof i.getInternalRenderer=="function"}class ta{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)??qs}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 d;const{service:e,getOptions:t,isDisposed:n,renderer:s,renderLoopManager:r,schedule:o}=this.deps;if(!e||!(((d=t().pathTracing)==null?void 0:d.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??qs,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:u})=>{r.releaseContinuous("path-tracing"),t().staticScene||r.setAlwaysRender(!1),o(()=>{r.hasContinuousDemand()||r.stop()},100),u==="gave-up"&&this.selfPauseListeners.forEach(h=>h())})}resetAccumulation(){this.deps.service&&this.isEnabled()&&(this.deps.service.reset(),this.completeHandled=!1)}getSampleCount(){var e;return((e=this.deps.service)==null?void 0:e.getSampleCount())||0}beforeFrame(){var e;return{wasActive:((e=this.deps.service)==null?void 0:e.isEnabled())||!1,samples:this.getSampleCount()}}render(e,t){const n=this.deps.service;if(!n||n.isPathTracerDisposed())return null;const s=n.getSampleCount(),r=s>=this.getMaxSamples()&&s>0;return!n.isEnabled()&&!r?null:(s===0&&(this.startTime=performance.now()),n.render(e,t))}detectCompletion(e,t){const n=this.deps.service;if(!n)return;(n.getSampleCount()||0)>=this.getMaxSamples()&&!this.completeHandled&&e.wasActive&&this.handleComplete(e.samples,t)}handleComplete(e,t){const{events:n,renderLoopManager:s,getOptions:r,schedule:o,replaceWithScreenshot:a,renderer:c}=this.deps;this.completeHandled=!0,s.releaseContinuous("path-tracing"),r().staticScene||s.setAlwaysRender(!1),n.emit("pathtracing:complete",{samples:e,totalTime:t-(this.startTime||0)});const d=()=>{s.hasContinuousDemand()||s.stop()};if(r().replaceWithScreenshotOnComplete){o(()=>{a(),o(d,200)},100);return}if(s.requestRender(),o(d,100),Mr(c)){const u=c.getInternalRenderer();u&&(u.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 Rr(){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 na=i=>[i,"video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"].filter(t=>!!t).find(t=>MediaRecorder.isTypeSupported(t));class sa{constructor(e){this.pendingSettlers=new Set,this.deps=e}async captureStill(e={}){return this.deps.isDisposed()?z.err(new K("Cannot capture a still from a disposed viewer",q.INVALID_STATE)):(await this.deps.awaitModelLoads().catch(()=>{}),this.deps.isDisposed()?z.err(new K("Viewer was disposed while a model load finished",q.INVALID_STATE)):this.deps.isScreenshotActive()?z.err(new K("Cannot capture a still while a screenshot is replacing the canvas",q.INVALID_STATE)):this.deps.pathTracing.isEnabled()?this.capturePathTracedStill(e):this.captureRasterStill(e))}settleOnDispose(){[...this.pendingSettlers].forEach(e=>e("disposed"))}async captureVideo(e={}){var u;if(this.deps.isDisposed())return z.err(new K("Cannot capture video from a disposed viewer",q.INVALID_STATE));if(await this.deps.awaitModelLoads().catch(()=>{}),this.deps.isDisposed())return z.err(new K("Viewer was disposed while a model load finished",q.INVALID_STATE));if(this.deps.isScreenshotActive())return z.err(new K("Cannot capture video while a screenshot is replacing the canvas",q.INVALID_STATE));const t=e.duration??3;if(!(t>0))return z.err(new K("Video duration must be a positive number of seconds",q.INVALID_PARAMETER));const n=this.deps.renderer.getDomElement();if(typeof MediaRecorder>"u"||typeof n.captureStream!="function")return z.err(new K("Video capture needs MediaRecorder and canvas.captureStream support",q.UNSUPPORTED_FORMAT));const s=n.captureStream(e.fps??30);let r;try{r=new MediaRecorder(s,{mimeType:na(e.mimeType),videoBitsPerSecond:e.videoBitsPerSecond})}catch(h){return s.getTracks().forEach(f=>f.stop()),z.err(new K("Failed to start the video recorder",q.OPERATION_FAILED,{originalError:h}))}const o=s.getVideoTracks()[0],a=(u=o==null?void 0:o.requestFrame)==null?void 0:u.bind(o),c=a?this.deps.events.on("render:complete",()=>a()):()=>{},d=`video-capture:${Rr()}`;return this.deps.renderLoopManager.requireContinuous(d),this.deps.reviveRenderLoop(),this.deps.renderLoopManager.requestRender(),new Promise(h=>{const f=[];let m=null,w=!1;const _=b=>{w||(w=!0,this.pendingSettlers.delete(E),c(),m!==null&&clearTimeout(m),this.deps.renderLoopManager.releaseContinuous(d),s.getTracks().forEach(T=>T.stop()),h(b))},E=()=>{_(z.err(new K("Viewer was disposed during video capture",q.INVALID_STATE)));try{r.stop()}catch{}};this.pendingSettlers.add(E),r.ondataavailable=b=>{b.data.size>0&&f.push(b.data)},r.onstop=()=>{_(z.ok(new Blob(f,{type:r.mimeType||"video/webm"})))},r.onerror=()=>{_(z.err(new K("Video recording failed",q.OPERATION_FAILED)))},r.start(250),m=setTimeout(()=>{r.state!=="inactive"&&r.stop()},t*1e3)})}async capturePathTracedStill(e){if(e.width!==void 0||e.height!==void 0)return z.err(new K("Path-traced stills are captured at the canvas resolution; omit width/height",q.INVALID_PARAMETER));if(this.deps.isAutoRotating())return z.err(new K("Cannot capture a path-traced still while the turntable is spinning — pause autoRotate first",q.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 z.err(new K("Viewer was disposed while waiting for the path tracer",q.INVALID_STATE));if(n==="error")return z.err(new K("Model failed while waiting for the path tracer",q.RENDER_FAILED))}return this.readCanvasPng()}waitForPathTracingOutcome(){return new Promise(e=>{let t=()=>{},n=()=>{},s=()=>{};const r=o=>{this.pendingSettlers.delete(r),t(),n(),s(),e(o)};this.pendingSettlers.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"))})}captureRasterStill(e){const{renderer:t,scene:n,camera:s,renderLoopManager:r}=this.deps,o=t.getDomElement(),a=t.getPixelRatio(),c=o.clientWidth>0&&o.clientHeight>0,d=c?o.clientWidth:Math.round(o.width/a),u=c?o.clientHeight:Math.round(o.height/a);if(d<=0||u<=0)return z.err(new K("Cannot capture: the canvas has no size",q.INVALID_STATE));const h=d/u,f=Math.round(e.width??(e.height!==void 0?e.height*h:d*a)),m=Math.round(e.height??(e.width!==void 0?e.width/h:u*a)),w=t.capabilities.maxTextureSize;if(!Number.isFinite(f)||!Number.isFinite(m)||f<=0||m<=0||f>w||m>w)return z.err(new K(`Requested still size ${f}x${m} is outside 1..${w}`,q.INVALID_PARAMETER));t.setPixelRatio(1),t.setSize(f,m),$s(s,f/m);const _=t.render(n,s),E=_.ok?this.readCanvasPng():z.err(_.error);return t.setSize(d,u),t.setPixelRatio(a),$s(s,h),t.render(n,s),r.requestRender(),E}readCanvasPng(){const e=Ar(this.deps.renderer.getDomElement());return e?z.ok(e):z.err(new K("Canvas produced an empty image",q.RENDER_FAILED))}}class ia{constructor(e){var s;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 $o,this.screenshotManager=new Qo({renderer:this.renderer,onRestore:async()=>{await this.restoreFromScreenshot()}}),this.modelManager=new Jo({modelLoader:e.modelLoader,scene:this.scene,camera:this.camera,controls:this.controls,floorAlignmentService:e.floorAlignmentService,sceneSetupService:this.sceneSetupService,renderer:this.renderer,autoFitToObject:(s=this.options.camera)==null?void 0:s.autoFitToObject,unitsScaleToMeters:Ko[this.options.units??"meters"]}),this.resourceManager=new ea({scene:this.scene,pathTracingService:e.pathTracingService,environmentService:this.environmentService}),this.sceneConfigurator=new Yo,this.events=new ws;const t=this.options.rendering||{},n=this.options.staticScene!==!1;this.renderLoopManager=new qo({enableIdleDetection:t.enableIdleDetection??n,idleDelay:t.idleDelay,targetFPS:t.targetFPS,enableFrameRateLimiting:t.enableFrameRateLimiting,alwaysRender:!1}),this.pathTracing=new ta({service:e.pathTracingService,events:this.events,renderLoopManager:this.renderLoopManager,renderer:this.renderer,getOptions:()=>this.options,isDisposed:()=>this.disposed,schedule:(r,o)=>this.schedule(r,o),replaceWithScreenshot:()=>this.replaceWithScreenshot()}),this.capture=new sa({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()),z.ok(void 0)):n}catch(n){const s=new K("Failed to initialize viewer",q.INITIALIZATION_FAILED,{originalError:n});return this.stateManager.setError(s),this.events.emit("error",{error:s}),z.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 z.err(new K("Cannot load model after dispose",q.INVALID_STATE));if(!this.stateManager.canLoad())return z.err(new K("Cannot load model in current state",q.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(),z.err(new K("Viewer was disposed while the model was loading",q.INVALID_STATE))):t.ok?(this.stateManager.setLoaded(t.value),this.attachAnimations(t.value),this.renderLoopManager.requestRender(),this.pathTracing.resetAccumulation(),z.ok(void 0)):(this.stateManager.setError(t.error),t)}catch(t){const n=t instanceof K?t:new K("Failed to load model",q.MODEL_LOAD_FAILED,{originalError:t,source:e});return this.stateManager.setError(n),z.err(n)}}startRenderLoop(){this.renderLoopManager.start(e=>{var o;if(this.disposed){this.renderLoopManager.stop();return}if(!this.stateManager.isInitialized()||this.stateManager.getStatus()==="error")return;if(!this.renderer||this.renderer.isDisposed()){this.renderLoopManager.stop();return}const t=performance.now(),n=e>0?1e3/e:0;this.controls.update()&&(this.events.emit("controls:change",{controls:this.controls}),this.pathTracing.resetAccumulation(),this.renderLoopManager.requestRender()),(o=this.animationService)!=null&&o.isPlaying()&&this.animationService.update(e/1e3);const r=this.pathTracing.beforeFrame();this.renderFrame().catch(a=>{console.error("[ViewerCore] Render frame error:",a)}),this.pathTracing.detectCompletion(r,t),this.frameCount++,this.stateManager.updateRenderInfo({frameCount:this.frameCount,fps:Math.round(n),lastRenderTime:performance.now()-t})})}stopRenderLoop(){this.renderLoopManager.stop()}schedule(e,t){const n=setTimeout(()=>{this.pendingTimers.delete(n),!this.disposed&&e()},t);this.pendingTimers.add(n)}async renderFrame(){const e=performance.now();if(!this.renderer||!this.scene||!this.camera){console.warn("[ViewerCore] Cannot render - components not initialized");return}if(this.screenshotManager.isActive())return;this.stateManager.startRendering();const t=await(this.pathTracing.render(this.scene,this.camera)??Promise.resolve(this.renderer.render(this.scene,this.camera)));if(!t.ok){console.error("[ViewerCore] Render failed:",t.error),this.events.emit("error",{error:t.error});return}this.events.emit("render:complete",{frame:this.frameCount,renderTime:performance.now()-e,samples:this.pathTracing.getSampleCount()})}updateOptions(e){var u,h,f,m,w,_,E,b;if(this.disposed)return;const t=(u=this.options.animations)==null?void 0:u.autoplay;this.options=ps(this.options,e);let n=!1;e.backgroundColor!==void 0&&this.applyBackgroundColor(e.backgroundColor);const s=(h=e.renderer)==null?void 0:h.toneMappingExposure;s!==void 0&&(this.renderer.setToneMappingExposure(s),n=!0);const r=(f=e.environment)==null?void 0:f.environmentIntensity;r!==void 0&&(this.scene.setEnvironmentIntensity(r),n=!0);const o=(m=e.controls)==null?void 0:m.autoRotate;o!==void 0&&(this.controls.autoRotate=o,o?this.renderLoopManager.requireContinuous("turntable"):this.renderLoopManager.releaseContinuous("turntable"),n=!0);const a=(w=e.controls)==null?void 0:w.autoRotateSpeed;a!==void 0&&(this.controls.autoRotateSpeed=a,n=!0);const c=(_=e.animations)==null?void 0:_.autoplay;c!==void 0&&c!==t&&(c?this.playAnimations(typeof c=="string"?c:void 0):this.pauseAnimations(),n=!0);const d=(E=e.animations)==null?void 0:E.speed;d!==void 0&&((b=this.animationService)==null||b.setSpeed(d),n=!0),n&&(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();$s(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 t;this.animationService&&(this.animationService.play(e),this.animationService.isPlaying()&&((t=this.sceneSetupService)==null||t.setContactShadowMode(this.scene,"live"),this.renderLoopManager.requireContinuous("animations"),this.reviveRenderLoop(),this.renderLoopManager.requestRender()))}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.playAnimations(typeof n=="string"?n:void 0)}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 xr.restore(e,this.camera,this.controls,async t=>{const n=await this.loadModel(t);n.ok||console.error("[ViewerCore] Failed to reload model:",n.error)}),this.renderLoopManager.isRunning()||this.startRenderLoop(),this.renderLoopManager.requestRender()}dispose(){var e,t;this.disposed=!0,this.pendingTimers.forEach(n=>clearTimeout(n)),this.pendingTimers.clear(),this.stopRenderLoop(),(e=this.selectionService)==null||e.dispose(),(t=this.animationService)==null||t.detach(),this.modelManager.dispose(),this.resourceManager.dispose(),this.screenshotManager.dispose(),this.controls.dispose(),this.renderer.dispose(),this.stateManager.setDisposed(),this.capture.settleOnDispose(),this.events.removeAllListeners(),this.stateManager.clearCallbacks()}}class Pt{constructor(e){this.vector=e}get x(){return this.vector.x}set x(e){this.vector.x=e}get y(){return this.vector.y}set y(e){this.vector.y=e}get z(){return this.vector.z}set z(e){this.vector.z=e}set(e,t,n){this.vector.set(e,t,n)}copy(e){this.vector.set(e.x,e.y,e.z)}add(e){this.vector.x+=e.x,this.vector.y+=e.y,this.vector.z+=e.z}multiply(e){this.vector.x*=e.x,this.vector.y*=e.y,this.vector.z*=e.z}normalize(){this.vector.normalize()}length(){return this.vector.length()}getThreeVector(){return this.vector}static fromThreeVector(e){return new Pt(e)}static create(e=0,t=0,n=0){return new Pt(new S.Vector3(e,t,n))}}const vr=0,ra=1,Cr=2,zi=2,vs=1.25,Ui=1,He=32,De=He/4,yi=65535,oa=yi<<16,us=Math.pow(2,-24),Ei=Symbol("SKIP_GENERATION"),Ir={strategy:vr,maxDepth:40,maxLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[Ei]:!1};function xe(i,e,t){return t.min.x=e[i],t.min.y=e[i+1],t.min.z=e[i+2],t.max.x=e[i+3],t.max.y=e[i+4],t.max.z=e[i+5],t}function 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 Vi(i,e){e.set(i)}function ji(i,e,t){let n,s;for(let r=0;r<3;r++){const o=r+3;n=i[r],s=e[r],t[r]=n<s?n:s,n=i[o],s=e[o],t[o]=n>s?n:s}}function Vn(i,e,t){for(let n=0;n<3;n++){const s=e[i+2*n],r=e[i+2*n+1],o=s-r,a=s+r;o<t[n]&&(t[n]=o),a>t[n+3]&&(t[n+3]=a)}}function hn(i){const e=i[3]-i[0],t=i[4]-i[1],n=i[5]-i[2];return 2*(e*t+t*n+n*e)}function Ce(i,e){return e[i+15]===yi}function Ve(i,e){return e[i+6]}function Xe(i,e){return e[i+14]}function Fe(i){return i+De}function Be(i,e){const t=e[i+6];return i+t*De}function Ts(i,e){return e[i+7]}function aa(i){return i}function Cs(i,e,t,n,s){let r=1/0,o=1/0,a=1/0,c=-1/0,d=-1/0,u=-1/0,h=1/0,f=1/0,m=1/0,w=-1/0,_=-1/0,E=-1/0;const b=i.offset||0;for(let T=(e-b)*6,x=(e+t-b)*6;T<x;T+=6){const A=i[T+0],R=i[T+1],O=A-R,L=A+R;O<r&&(r=O),L>c&&(c=L),A<h&&(h=A),A>w&&(w=A);const C=i[T+2],N=i[T+3],I=C-N,k=C+N;I<o&&(o=I),k>d&&(d=k),C<f&&(f=C),C>_&&(_=C);const D=i[T+4],B=i[T+5],W=D-B,te=D+B;W<a&&(a=W),te>u&&(u=te),D<m&&(m=D),D>E&&(E=D)}n[0]=r,n[1]=o,n[2]=a,n[3]=c,n[4]=d,n[5]=u,s[0]=h,s[1]=f,s[2]=m,s[3]=w,s[4]=_,s[5]=E}const wt=32,ca=(i,e)=>i.candidate-e.candidate,Mt=new Array(wt).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),jn=new Float32Array(6);function la(i,e,t,n,s,r){let o=-1,a=0;if(r===vr)o=Hi(e),o!==-1&&(a=(e[o]+e[o+3])/2);else if(r===ra)o=Hi(i),o!==-1&&(a=ha(t,n,s,o));else if(r===Cr){const c=hn(i);let d=vs*s;const u=t.offset||0,h=(n-u)*6,f=(n+s-u)*6;for(let m=0;m<3;m++){const w=e[m],b=(e[m+3]-w)/wt;if(s<wt/4){const T=[...Mt];T.length=s;let x=0;for(let R=h;R<f;R+=6,x++){const O=T[x];O.candidate=t[R+2*m],O.count=0;const{bounds:L,leftCacheBounds:C,rightCacheBounds:N}=O;for(let I=0;I<3;I++)N[I]=1/0,N[I+3]=-1/0,C[I]=1/0,C[I+3]=-1/0,L[I]=1/0,L[I+3]=-1/0;Vn(R,t,L)}T.sort(ca);let A=s;for(let R=0;R<A;R++){const O=T[R];for(;R+1<A&&T[R+1].candidate===O.candidate;)T.splice(R+1,1),A--}for(let R=h;R<f;R+=6){const O=t[R+2*m];for(let L=0;L<A;L++){const C=T[L];O>=C.candidate?Vn(R,t,C.rightCacheBounds):(Vn(R,t,C.leftCacheBounds),C.count++)}}for(let R=0;R<A;R++){const O=T[R],L=O.count,C=s-O.count,N=O.leftCacheBounds,I=O.rightCacheBounds;let k=0;L!==0&&(k=hn(N)/c);let D=0;C!==0&&(D=hn(I)/c);const B=Ui+vs*(k*L+D*C);B<d&&(o=m,d=B,a=O.candidate)}}else{for(let A=0;A<wt;A++){const R=Mt[A];R.count=0,R.candidate=w+b+A*b;const O=R.bounds;for(let L=0;L<3;L++)O[L]=1/0,O[L+3]=-1/0}for(let A=h;A<f;A+=6){let L=~~((t[A+2*m]-w)/b);L>=wt&&(L=wt-1);const C=Mt[L];C.count++,Vn(A,t,C.bounds)}const T=Mt[wt-1];Vi(T.bounds,T.rightCacheBounds);for(let A=wt-2;A>=0;A--){const R=Mt[A],O=Mt[A+1];ji(R.bounds,O.rightCacheBounds,R.rightCacheBounds)}let x=0;for(let A=0;A<wt-1;A++){const R=Mt[A],O=R.count,L=R.bounds,N=Mt[A+1].rightCacheBounds;O!==0&&(x===0?Vi(L,jn):ji(L,jn,jn)),x+=O;let I=0,k=0;x!==0&&(I=hn(jn)/c);const D=s-x;D!==0&&(k=hn(N)/c);const B=Ui+vs*(I*x+k*D);B<d&&(o=m,d=B,a=R.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${r} used.`);return{axis:o,pos:a}}function ha(i,e,t,n){let s=0;const r=i.offset;for(let o=e,a=e+t;o<a;o++)s+=i[(o-r)*6+n*2];return s/t}class Is{constructor(){this.boundingData=new Float32Array(6)}}function ua(i,e,t,n,s,r){let o=n,a=n+s-1;const c=r.pos,d=r.axis*2,u=t.offset||0;for(;;){for(;o<=a&&t[(o-u)*6+d]<c;)o++;for(;o<=a&&t[(a-u)*6+d]>=c;)a--;if(o<a){for(let h=0;h<e;h++){let f=i[o*e+h];i[o*e+h]=i[a*e+h],i[a*e+h]=f}for(let h=0;h<6;h++){const f=o-u,m=a-u,w=t[f*6+h];t[f*6+h]=t[m*6+h],t[m*6+h]=w}o++,a--}else return o}}let Lr,ds,Qs,Pr;const da=Math.pow(2,32);function Js(i){return"count"in i?1:1+Js(i.left)+Js(i.right)}function fa(i,e,t){return Lr=new Float32Array(t),ds=new Uint32Array(t),Qs=new Uint16Array(t),Pr=new Uint8Array(t),ei(i,e)}function ei(i,e){const t=i/4,n=i/2,s="count"in e,r=e.boundingData;for(let o=0;o<6;o++)Lr[t+o]=r[o];if(s)return e.buffer?(Pr.set(new Uint8Array(e.buffer),i),i+e.buffer.byteLength):(ds[t+6]=e.offset,Qs[n+14]=e.count,Qs[n+15]=yi,i+He);{const{left:o,right:a,splitAxis:c}=e,d=i+He;let u=ei(d,o);const h=i/He,m=u/He-h;if(m>da)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return ds[t+6]=m,ds[t+7]=c,ei(u,a)}}function pa(i,e,t,n,s,r){const{maxDepth:o,verbose:a,maxLeafSize:c,strategy:d,onProgress:u}=s,h=i.primitiveBuffer,f=i.primitiveBufferStride,m=new Float32Array(6);let w=!1;const _=new Is;return Cs(e,t,n,_.boundingData,m),b(_,t,n,m),_;function E(T){u&&u((T-r.offset)/r.count)}function b(T,x,A,R=null,O=0){if(!w&&O>=o&&(w=!0,a&&console.warn(`BVH: Max depth of ${o} reached when generating BVH. Consider increasing maxDepth.`)),A<=c||O>=o)return E(x+A),T.offset=x,T.count=A,T;const L=la(T.boundingData,R,e,x,A,d);if(L.axis===-1)return E(x+A),T.offset=x,T.count=A,T;const C=ua(h,f,e,x,A,L);if(C===x||C===x+A)E(x+A),T.offset=x,T.count=A;else{T.splitAxis=L.axis;const N=new Is,I=x,k=C-x;T.left=N,Cs(e,I,k,N.boundingData,m),b(N,I,k,m,O+1);const D=new Is,B=C,W=A-k;T.right=D,Cs(e,B,W,D.boundingData,m),b(D,B,W,m,O+1)}return T}}function ma(i,e){const t=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=i.getRootRanges(e.range),s=n[0],r=n[n.length-1],o={offset:s.offset,count:r.offset+r.count-s.offset},a=new Float32Array(6*o.count);a.offset=o.offset,i.computePrimitiveBounds(o.offset,o.count,a),i._roots=n.map(c=>{const d=pa(i,a,c.offset,c.count,e,o),u=Js(d),h=new t(He*u);return fa(0,d,h),h})}class wi{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 ga{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 ga;let Lt,nn;const Gt=[],Gn=new wi(()=>new p.Box3);function ya(i,e,t,n,s,r){Lt=Gn.getPrimitive(),nn=Gn.getPrimitive(),Gt.push(Lt,nn),be.setBuffer(i._roots[e]);const o=ti(0,i.geometry,t,n,s,r);be.clearBuffer(),Gn.releasePrimitive(Lt),Gn.releasePrimitive(nn),Gt.pop(),Gt.pop();const a=Gt.length;return a>0&&(nn=Gt[a-1],Lt=Gt[a-2]),o}function ti(i,e,t,n,s=null,r=0,o=0){const{float32Array:a,uint16Array:c,uint32Array:d}=be;let u=i*2;if(Ce(u,c)){const f=Ve(i,d),m=Xe(u,c);return xe(i,a,Lt),n(f,m,!1,o,r+i/De,Lt)}else{let I=function(D){const{uint16Array:B,uint32Array:W}=be;let te=D*2;for(;!Ce(te,B);)D=Fe(D),te=D*2;return Ve(D,W)},k=function(D){const{uint16Array:B,uint32Array:W}=be;let te=D*2;for(;!Ce(te,B);)D=Be(D,W),te=D*2;return Ve(D,W)+Xe(te,B)};const f=Fe(i),m=Be(i,d);let w=f,_=m,E,b,T,x;if(s&&(T=Lt,x=nn,xe(w,a,T),xe(_,a,x),E=s(T),b=s(x),b<E)){w=m,_=f;const D=E;E=b,b=D,T=x}T||(T=Lt,xe(w,a,T));const A=Ce(w*2,c),R=t(T,A,E,o+1,r+w/De);let O;if(R===zi){const D=I(w),W=k(w)-D;O=n(D,W,!0,o+1,r+w/De,T)}else O=R&&ti(w,e,t,n,s,r,o+1);if(O)return!0;x=nn,xe(_,a,x);const L=Ce(_*2,c),C=t(x,L,b,o+1,r+_/De);let N;if(C===zi){const D=I(_),W=k(_)-D;N=n(D,W,!0,o+1,r+_/De,x)}else N=C&&ti(_,e,t,n,s,r,o+1);return!!N}}const Tn=new be.constructor,ms=new be.constructor,Ct=new wi(()=>new p.Box3),Wt=new p.Box3,Zt=new p.Box3,Ls=new p.Box3,Ps=new p.Box3;let Os=!1;function Ea(i,e,t,n){if(Os)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");Os=!0;const s=i._roots,r=e._roots;let o,a=0,c=0;const d=new p.Matrix4().copy(t).invert();for(let u=0,h=s.length;u<h;u++){Tn.setBuffer(s[u]),c=0;const f=Ct.getPrimitive();xe(0,Tn.float32Array,f),f.applyMatrix4(d);for(let m=0,w=r.length;m<w&&(ms.setBuffer(r[m]),o=ht(0,0,t,d,n,a,c,0,0,f),ms.clearBuffer(),c+=r[m].byteLength/He,!o);m++);if(Ct.releasePrimitive(f),Tn.clearBuffer(),a+=s[u].byteLength/He,o)break}return Os=!1,o}function ht(i,e,t,n,s,r=0,o=0,a=0,c=0,d=null,u=!1){let h,f;u?(h=ms,f=Tn):(h=Tn,f=ms);const m=h.float32Array,w=h.uint32Array,_=h.uint16Array,E=f.float32Array,b=f.uint32Array,T=f.uint16Array,x=i*2,A=e*2,R=Ce(x,_),O=Ce(A,T);let L=!1;if(O&&R)u?L=s(Ve(e,b),Xe(e*2,T),Ve(i,w),Xe(i*2,_),c,o+e/De,a,r+i/De):L=s(Ve(i,w),Xe(i*2,_),Ve(e,b),Xe(e*2,T),a,r+i/De,c,o+e/De);else if(O){const C=Ct.getPrimitive();xe(e,E,C),C.applyMatrix4(t);const N=Fe(i),I=Be(i,w);xe(N,m,Wt),xe(I,m,Zt);const k=C.intersectsBox(Wt),D=C.intersectsBox(Zt);L=k&&ht(e,N,n,t,s,o,r,c,a+1,C,!u)||D&&ht(e,I,n,t,s,o,r,c,a+1,C,!u),Ct.releasePrimitive(C)}else{const C=Fe(e),N=Be(e,b);xe(C,E,Ls),xe(N,E,Ps);const I=d.intersectsBox(Ls),k=d.intersectsBox(Ps);if(I&&k)L=ht(i,C,t,n,s,r,o,a,c+1,d,u)||ht(i,N,t,n,s,r,o,a,c+1,d,u);else if(I)if(R)L=ht(i,C,t,n,s,r,o,a,c+1,d,u);else{const D=Ct.getPrimitive();D.copy(Ls).applyMatrix4(t);const B=Fe(i),W=Be(i,w);xe(B,m,Wt),xe(W,m,Zt);const te=D.intersectsBox(Wt),re=D.intersectsBox(Zt);L=te&&ht(C,B,n,t,s,o,r,c,a+1,D,!u)||re&&ht(C,W,n,t,s,o,r,c,a+1,D,!u),Ct.releasePrimitive(D)}else if(k)if(R)L=ht(i,N,t,n,s,r,o,a,c+1,d,u);else{const D=Ct.getPrimitive();D.copy(Ps).applyMatrix4(t);const B=Fe(i),W=Be(i,w);xe(B,m,Wt),xe(W,m,Zt);const te=D.intersectsBox(Wt),re=D.intersectsBox(Zt);L=te&&ht(N,B,n,t,s,o,r,c,a+1,D,!u)||re&&ht(N,W,n,t,s,o,r,c,a+1,D,!u),Ct.releasePrimitive(D)}}return L}const Gi=new p.Box3,Kt=new Float32Array(6);class wa{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(e){e={...Ir,...e},ma(this,e)}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(e,t,n,s){let r=1/0,o=1/0,a=1/0,c=-1/0,d=-1/0,u=-1/0;for(let h=e,f=e+t;h<f;h++){this.writePrimitiveBounds(h,Kt,0);const[m,w,_,E,b,T]=Kt;m<r&&(r=m),E>c&&(c=E),w<o&&(o=w),b>d&&(d=b),_<a&&(a=_),T>u&&(u=T)}return n[s+0]=r,n[s+1]=o,n[s+2]=a,n[s+3]=c,n[s+4]=d,n[s+5]=u,n}computePrimitiveBounds(e,t,n){const s=n.offset||0;for(let r=e,o=e+t;r<o;r++){this.writePrimitiveBounds(r,Kt,0);const[a,c,d,u,h,f]=Kt,m=(a+u)/2,w=(c+h)/2,_=(d+f)/2,E=(u-a)/2,b=(h-c)/2,T=(f-d)/2,x=(r-s)*6;n[x+0]=m,n[x+1]=E+(Math.abs(m)+E)*us,n[x+2]=w,n[x+3]=b+(Math.abs(w)+b)*us,n[x+4]=_,n[x+5]=T+(Math.abs(_)+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 r=n[s],o=new Uint32Array(r),a=new Uint16Array(r),c=r.byteLength/He;for(let d=0;d<c;d++){const u=De*d,h=2*u;Ce(h,a)&&(o[u+6]+=e)}}}}traverse(e,t=0){const n=this._roots[t],s=new Uint32Array(n),r=new Uint16Array(n);o(0);function o(a,c=0){const d=a*2,u=Ce(d,r);if(u){const h=s[a+6],f=r[d+14];e(c,u,new Float32Array(n,a*4,6),h,f)}else{const h=Fe(a),f=Be(a,s),m=Ts(a,s);e(c,u,new Float32Array(n,a*4,6),m)||(o(h,c+1),o(f,c+1))}}}refit(){const e=this._roots;for(let t=0,n=e.length;t<n;t++){const s=e[t],r=new Uint32Array(s),o=new Uint16Array(s),a=new Float32Array(s),c=s.byteLength/He;for(let d=c-1;d>=0;d--){const u=d*De,h=u*2;if(Ce(h,o)){const m=Ve(u,r),w=Xe(h,o);this.writePrimitiveRangeBounds(m,w,Kt,0),a.set(Kt,u)}else{const m=Fe(u),w=Be(u,r);for(let _=0;_<3;_++){const E=a[m+_],b=a[m+_+3],T=a[w+_],x=a[w+_+3];a[u+_]=E<T?E:T,a[u+_+3]=b>x?b:x}}}}}getBoundingBox(e){return e.makeEmpty(),this._roots.forEach(n=>{xe(0,new Float32Array(n),Gi),e.union(Gi)}),e}shapecast(e){let{boundsTraverseOrder:t,intersectsBounds:n,intersectsRange:s,intersectsPrimitive:r,scratchPrimitive:o,iterate:a}=e;if(s&&r){const h=s;s=(f,m,w,_,E)=>h(f,m,w,_,E)?!0:a(f,m,this,r,w,_,o)}else s||(r?s=(h,f,m,w)=>a(h,f,this,r,m,w,o):s=(h,f,m)=>m);let c=!1,d=0;const u=this._roots;for(let h=0,f=u.length;h<f;h++){const m=u[h];if(c=ya(this,h,n,s,t,d),c)break;d+=m.byteLength/He}return c}bvhcast(e,t,n){let{intersectsRanges:s}=n;return Ea(this,e,t,s)}}function Ta(){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 Or(i,e=ArrayBuffer){return i>65535?new Uint32Array(new e(4*i)):new Uint16Array(new e(2*i))}function Sa(i,e){if(!i.index){const t=i.attributes.position.count,n=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,s=Or(t,n);i.setIndex(new p.BufferAttribute(s,1));for(let r=0;r<t;r++)s[r]=r}}function _a(i,e,t){const n=Ss(i)/t,s=e||i.drawRange,r=s.start/t,o=(s.start+s.count)/t,a=Math.max(0,r),c=Math.min(n,o)-a;return{offset:Math.floor(a),count:Math.floor(c)}}function ba(i,e){return i.groups.map(t=>({offset:t.start/e,count:t.count/e}))}function Wi(i,e,t){const n=_a(i,e,t),s=ba(i,t);if(!s.length)return[n];const r=[],o=n.offset,a=n.offset+n.count,c=Ss(i)/t,d=[];for(const f of s){const{offset:m,count:w}=f,_=m,E=isFinite(w)?w:c-m,b=m+E;_<a&&b>o&&(d.push({pos:Math.max(o,_),isStart:!0}),d.push({pos:Math.min(a,b),isStart:!1}))}d.sort((f,m)=>f.pos!==m.pos?f.pos-m.pos:f.type==="end"?-1:1);let u=0,h=null;for(const f of d){const m=f.pos;u!==0&&m!==h&&r.push({offset:h,count:m-h}),u+=f.isStart?1:-1,h=m}return r}function xa(i,e){const t=i[i.length-1],n=t.offset+t.count>2**16,s=i.reduce((d,u)=>d+u.count,0),r=n?4:2,o=e?new SharedArrayBuffer(s*r):new ArrayBuffer(s*r),a=n?new Uint32Array(o):new Uint16Array(o);let c=0;for(let d=0;d<i.length;d++){const{offset:u,count:h}=i[d];for(let f=0;f<h;f++)a[c+f]=u+f;c+=h}return a}class Aa extends wa{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&&!Ta())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={...Ir,...t},t[Ei]||this.init(t)}init(e){const{geometry:t,primitiveStride:n}=this;if(e.indirect){const s=Wi(t,e.range,n),r=xa(s,e.useSharedArrayBuffer);this._indirectBuffer=r}else Sa(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}]:Wi(this.geometry,e,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class bt{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let n=1/0,s=-1/0;for(let r=0,o=e.length;r<o;r++){const c=e[r][t];n=c<n?c:n,s=c>s?c:s}this.min=n,this.max=s}setFromPoints(e,t){let n=1/0,s=-1/0;for(let r=0,o=t.length;r<o;r++){const a=t[r],c=e.dot(a);n=c<n?c:n,s=c>s?c:s}this.min=n,this.max=s}isSeparated(e){return this.min>e.max||e.min>this.max}}bt.prototype.setFromBox=(function(){const i=new p.Vector3;return function(t,n){const s=n.min,r=n.max;let o=1/0,a=-1/0;for(let c=0;c<=1;c++)for(let d=0;d<=1;d++)for(let u=0;u<=1;u++){i.x=s.x*c+r.x*(1-c),i.y=s.y*d+r.y*(1-d),i.z=s.z*u+r.z*(1-u);const h=t.dot(i);o=Math.min(h,o),a=Math.max(h,a)}this.min=o,this.max=a}})();const Ma=(function(){const i=new p.Vector3,e=new p.Vector3,t=new p.Vector3;return function(s,r,o){const a=s.start,c=i,d=r.start,u=e;t.subVectors(a,d),i.subVectors(s.end,s.start),e.subVectors(r.end,r.start);const h=t.dot(u),f=u.dot(c),m=u.dot(u),w=t.dot(c),E=c.dot(c)*m-f*f;let b,T;E!==0?b=(h*f-w*m)/E:b=0,T=(h+b*f)/m,o.x=b,o.y=T}})(),Ti=(function(){const i=new p.Vector2,e=new p.Vector3,t=new p.Vector3;return function(s,r,o,a){Ma(s,r,i);let c=i.x,d=i.y;if(c>=0&&c<=1&&d>=0&&d<=1){s.at(c,o),r.at(d,a);return}else if(c>=0&&c<=1){d<0?r.at(0,a):r.at(1,a),s.closestPointToPoint(a,!0,o);return}else if(d>=0&&d<=1){c<0?s.at(0,o):s.at(1,o),r.closestPointToPoint(o,!0,a);return}else{let u;c<0?u=s.start:u=s.end;let h;d<0?h=r.start:h=r.end;const f=e,m=t;if(s.closestPointToPoint(h,!0,e),r.closestPointToPoint(u,!0,t),f.distanceToSquared(h)<=m.distanceToSquared(u)){o.copy(f),a.copy(h);return}else{o.copy(u),a.copy(m);return}}}})(),Ra=(function(){const i=new p.Vector3,e=new p.Vector3,t=new p.Plane,n=new p.Line3;return function(r,o){const{radius:a,center:c}=r,{a:d,b:u,c:h}=o;if(n.start=d,n.end=u,n.closestPointToPoint(c,!0,i).distanceTo(c)<=a||(n.start=d,n.end=h,n.closestPointToPoint(c,!0,i).distanceTo(c)<=a)||(n.start=u,n.end=h,n.closestPointToPoint(c,!0,i).distanceTo(c)<=a))return!0;const _=o.getPlane(t);if(Math.abs(_.distanceToPoint(c))<=a){const b=_.projectPoint(c,e);if(o.containsPoint(b))return!0}return!1}})(),va=["x","y","z"],Tt=1e-15,Zi=Tt*Tt;function nt(i){return Math.abs(i)<Tt}class dt extends p.Triangle{constructor(...e){super(...e),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new p.Vector3),this.satBounds=new Array(4).fill().map(()=>new bt),this.points=[this.a,this.b,this.c],this.plane=new p.Plane,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new p.Line3,this.needsUpdate=!0}intersectsSphere(e){return Ra(e,this)}update(){const e=this.a,t=this.b,n=this.c,s=this.points,r=this.satAxes,o=this.satBounds,a=r[0],c=o[0];this.getNormal(a),c.setFromPoints(a,s);const d=r[1],u=o[1];d.subVectors(e,t),u.setFromPoints(d,s);const h=r[2],f=o[2];h.subVectors(t,n),f.setFromPoints(h,s);const m=r[3],w=o[3];m.subVectors(n,e),w.setFromPoints(m,s);const _=d.length(),E=h.length(),b=m.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,_<Tt?E<Tt||b<Tt?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(n)):E<Tt?b<Tt?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(e)):b<Tt&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(n),this.degenerateSegment.end.copy(t)),this.plane.setFromNormalAndCoplanarPoint(a,e),this.needsUpdate=!1}}dt.prototype.closestPointToSegment=(function(){const i=new p.Vector3,e=new p.Vector3,t=new p.Line3;return function(s,r=null,o=null){const{start:a,end:c}=s,d=this.points;let u,h=1/0;for(let f=0;f<3;f++){const m=(f+1)%3;t.start.copy(d[f]),t.end.copy(d[m]),Ti(t,s,i,e),u=i.distanceToSquared(e),u<h&&(h=u,r&&r.copy(i),o&&o.copy(e))}return this.closestPointToPoint(a,i),u=a.distanceToSquared(i),u<h&&(h=u,r&&r.copy(i),o&&o.copy(a)),this.closestPointToPoint(c,i),u=c.distanceToSquared(i),u<h&&(h=u,r&&r.copy(i),o&&o.copy(c)),Math.sqrt(h)}})();dt.prototype.intersectsTriangle=(function(){const i=new dt,e=new bt,t=new bt,n=new p.Vector3,s=new p.Vector3,r=new p.Vector3,o=new p.Vector3,a=new p.Line3,c=new p.Line3,d=new p.Vector3,u=new p.Vector2,h=new p.Vector2;function f(x,A,R,O){const L=n;!x.isDegenerateIntoPoint&&!x.isDegenerateIntoSegment?L.copy(x.plane.normal):L.copy(A.plane.normal);const C=x.satBounds,N=x.satAxes;for(let D=1;D<4;D++){const B=C[D],W=N[D];if(e.setFromPoints(W,A.points),B.isSeparated(e)||(o.copy(L).cross(W),e.setFromPoints(o,x.points),t.setFromPoints(o,A.points),e.isSeparated(t)))return!1}const I=A.satBounds,k=A.satAxes;for(let D=1;D<4;D++){const B=I[D],W=k[D];if(e.setFromPoints(W,x.points),B.isSeparated(e)||(o.crossVectors(L,W),e.setFromPoints(o,x.points),t.setFromPoints(o,A.points),e.isSeparated(t)))return!1}return R&&(O||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),R.start.set(0,0,0),R.end.set(0,0,0)),!0}function m(x,A,R,O,L,C,N,I,k,D,B){let W=N/(N-I);D.x=O+(L-O)*W,B.start.subVectors(A,x).multiplyScalar(W).add(x),W=N/(N-k),D.y=O+(C-O)*W,B.end.subVectors(R,x).multiplyScalar(W).add(x)}function w(x,A,R,O,L,C,N,I,k,D,B){if(L>0)m(x.c,x.a,x.b,O,A,R,k,N,I,D,B);else if(C>0)m(x.b,x.a,x.c,R,A,O,I,N,k,D,B);else if(I*k>0||N!=0)m(x.a,x.b,x.c,A,R,O,N,I,k,D,B);else if(I!=0)m(x.b,x.a,x.c,R,A,O,I,N,k,D,B);else if(k!=0)m(x.c,x.a,x.b,O,A,R,k,N,I,D,B);else return!0;return!1}function _(x,A,R,O){const L=A.degenerateSegment,C=x.plane.distanceToPoint(L.start),N=x.plane.distanceToPoint(L.end);return nt(C)?nt(N)?f(x,A,R,O):(R&&(R.start.copy(L.start),R.end.copy(L.start)),x.containsPoint(L.start)):nt(N)?(R&&(R.start.copy(L.end),R.end.copy(L.end)),x.containsPoint(L.end)):x.plane.intersectLine(L,n)!=null?(R&&(R.start.copy(n),R.end.copy(n)),x.containsPoint(n)):!1}function E(x,A,R){const O=A.a;return nt(x.plane.distanceToPoint(O))&&x.containsPoint(O)?(R&&(R.start.copy(O),R.end.copy(O)),!0):!1}function b(x,A,R){const O=x.degenerateSegment,L=A.a;return O.closestPointToPoint(L,!0,n),L.distanceToSquared(n)<Zi?(R&&(R.start.copy(L),R.end.copy(L)),!0):!1}function T(x,A,R,O){if(x.isDegenerateIntoSegment)if(A.isDegenerateIntoSegment){const L=x.degenerateSegment,C=A.degenerateSegment,N=s,I=r;L.delta(N),C.delta(I);const k=n.subVectors(C.start,L.start),D=N.x*I.y-N.y*I.x;if(nt(D))return!1;const B=(k.x*I.y-k.y*I.x)/D,W=-(N.x*k.y-N.y*k.x)/D;if(B<0||B>1||W<0||W>1)return!1;const te=L.start.z+N.z*B,re=C.start.z+I.z*W;return nt(te-re)?(R&&(R.start.copy(L.start).addScaledVector(N,B),R.end.copy(L.start).addScaledVector(N,B)),!0):!1}else return A.isDegenerateIntoPoint?b(x,A,R):_(A,x,R,O);else{if(x.isDegenerateIntoPoint)return A.isDegenerateIntoPoint?A.a.distanceToSquared(x.a)<Zi?(R&&(R.start.copy(x.a),R.end.copy(x.a)),!0):!1:A.isDegenerateIntoSegment?b(A,x,R):E(A,x,R);if(A.isDegenerateIntoPoint)return E(x,A,R);if(A.isDegenerateIntoSegment)return _(x,A,R,O)}}return function(A,R=null,O=!1){this.needsUpdate&&this.update(),A.isExtendedTriangle?A.needsUpdate&&A.update():(i.copy(A),i.update(),A=i);const L=T(this,A,R,O);if(L!==void 0)return L;const C=this.plane,N=A.plane;let I=N.distanceToPoint(this.a),k=N.distanceToPoint(this.b),D=N.distanceToPoint(this.c);nt(I)&&(I=0),nt(k)&&(k=0),nt(D)&&(D=0);const B=I*k,W=I*D;if(B>0&&W>0)return!1;let te=C.distanceToPoint(A.a),re=C.distanceToPoint(A.b),Ne=C.distanceToPoint(A.c);nt(te)&&(te=0),nt(re)&&(re=0),nt(Ne)&&(Ne=0);const ot=te*re,Re=te*Ne;if(ot>0&&Re>0)return!1;s.copy(C.normal),r.copy(N.normal);const ze=s.cross(r);let je=0,Ae=Math.abs(ze.x);const ye=Math.abs(ze.y);ye>Ae&&(Ae=ye,je=1),Math.abs(ze.z)>Ae&&(je=2);const Ge=va[je],xt=this.a[Ge],ge=this.b[Ge],at=this.c[Ge],ct=A.a[Ge],on=A.b[Ge],Ht=A.c[Ge];if(w(this,xt,ge,at,B,W,I,k,D,u,a))return f(this,A,R,O);if(w(A,ct,on,Ht,ot,Re,te,re,Ne,h,c))return f(this,A,R,O);if(u.y<u.x){const Et=u.y;u.y=u.x,u.x=Et,d.copy(a.start),a.start.copy(a.end),a.end.copy(d)}if(h.y<h.x){const Et=h.y;h.y=h.x,h.x=Et,d.copy(c.start),c.start.copy(c.end),c.end.copy(d)}return u.y<h.x||h.y<u.x?!1:(R&&(h.x>u.x?R.start.copy(c.start):R.start.copy(a.start),h.y<u.y?R.end.copy(c.end):R.end.copy(a.end)),!0)}})();dt.prototype.distanceToPoint=(function(){const i=new p.Vector3;return function(t){return this.closestPointToPoint(t,i),t.distanceTo(i)}})();dt.prototype.distanceToTriangle=(function(){const i=new p.Vector3,e=new p.Vector3,t=["a","b","c"],n=new p.Line3,s=new p.Line3;return function(o,a=null,c=null){const d=a||c?n:null;if(this.intersectsTriangle(o,d,!0))return(a||c)&&(a&&d.getCenter(a),c&&d.getCenter(c)),0;let u=1/0;for(let h=0;h<3;h++){let f;const m=t[h],w=o[m];this.closestPointToPoint(w,i),f=w.distanceToSquared(i),f<u&&(u=f,a&&a.copy(i),c&&c.copy(w));const _=this[m];o.closestPointToPoint(_,i),f=_.distanceToSquared(i),f<u&&(u=f,a&&a.copy(_),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 _=t[w],E=t[(w+1)%3];s.set(o[_],o[E]),Ti(n,s,i,e);const b=i.distanceToSquared(e);b<u&&(u=b,a&&a.copy(i),c&&c.copy(e))}}return Math.sqrt(u)}})();class Ye{constructor(e,t,n){this.isOrientedBox=!0,this.min=new p.Vector3,this.max=new p.Vector3,this.matrix=new p.Matrix4,this.invMatrix=new p.Matrix4,this.points=new Array(8).fill().map(()=>new p.Vector3),this.satAxes=new Array(3).fill().map(()=>new p.Vector3),this.satBounds=new Array(3).fill().map(()=>new bt),this.alignedSatBounds=new Array(3).fill().map(()=>new bt),this.needsUpdate=!1,e&&this.min.copy(e),t&&this.max.copy(t),n&&this.matrix.copy(n)}set(e,t,n){this.min.copy(e),this.max.copy(t),this.matrix.copy(n),this.needsUpdate=!0}copy(e){this.min.copy(e.min),this.max.copy(e.max),this.matrix.copy(e.matrix),this.needsUpdate=!0}}Ye.prototype.update=(function(){return function(){const e=this.matrix,t=this.min,n=this.max,s=this.points;for(let d=0;d<=1;d++)for(let u=0;u<=1;u++)for(let h=0;h<=1;h++){const f=1*d|2*u|4*h,m=s[f];m.x=d?n.x:t.x,m.y=u?n.y:t.y,m.z=h?n.z:t.z,m.applyMatrix4(e)}const r=this.satBounds,o=this.satAxes,a=s[0];for(let d=0;d<3;d++){const u=o[d],h=r[d],f=1<<d,m=s[f];u.subVectors(a,m),h.setFromPoints(u,s)}const c=this.alignedSatBounds;c[0].setFromPointsField(s,"x"),c[1].setFromPointsField(s,"y"),c[2].setFromPointsField(s,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}})();Ye.prototype.intersectsBox=(function(){const i=new bt;return function(t){this.needsUpdate&&this.update();const n=t.min,s=t.max,r=this.satBounds,o=this.satAxes,a=this.alignedSatBounds;if(i.min=n.x,i.max=s.x,a[0].isSeparated(i)||(i.min=n.y,i.max=s.y,a[1].isSeparated(i))||(i.min=n.z,i.max=s.z,a[2].isSeparated(i)))return!1;for(let c=0;c<3;c++){const d=o[c],u=r[c];if(i.setFromBox(d,t),u.isSeparated(i))return!1}return!0}})();Ye.prototype.intersectsTriangle=(function(){const i=new dt,e=new Array(3),t=new bt,n=new bt,s=new p.Vector3;return function(o){this.needsUpdate&&this.update(),o.isExtendedTriangle?o.needsUpdate&&o.update():(i.copy(o),i.update(),o=i);const a=this.satBounds,c=this.satAxes;e[0]=o.a,e[1]=o.b,e[2]=o.c;for(let f=0;f<3;f++){const m=a[f],w=c[f];if(t.setFromPoints(w,e),m.isSeparated(t))return!1}const d=o.satBounds,u=o.satAxes,h=this.points;for(let f=0;f<3;f++){const m=d[f],w=u[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 _=u[w];if(s.crossVectors(m,_),t.setFromPoints(s,e),n.setFromPoints(s,h),t.isSeparated(n))return!1}}return!0}})();Ye.prototype.closestPointToPoint=(function(){return function(e,t){return this.needsUpdate&&this.update(),t.copy(e).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),t}})();Ye.prototype.distanceToPoint=(function(){const i=new p.Vector3;return function(t){return this.closestPointToPoint(t,i),t.distanceTo(i)}})();Ye.prototype.distanceToBox=(function(){const i=["x","y","z"],e=new Array(12).fill().map(()=>new p.Line3),t=new Array(12).fill().map(()=>new p.Line3),n=new p.Vector3,s=new p.Vector3;return function(o,a=0,c=null,d=null){if(this.needsUpdate&&this.update(),this.intersectsBox(o))return(c||d)&&(o.getCenter(s),this.closestPointToPoint(s,n),o.closestPointToPoint(n,s),c&&c.copy(n),d&&d.copy(s)),0;const u=a*a,h=o.min,f=o.max,m=this.points;let w=1/0;for(let E=0;E<8;E++){const b=m[E];s.copy(b).clamp(h,f);const T=b.distanceToSquared(s);if(T<w&&(w=T,c&&c.copy(b),d&&d.copy(s),T<u))return Math.sqrt(T)}let _=0;for(let E=0;E<3;E++)for(let b=0;b<=1;b++)for(let T=0;T<=1;T++){const x=(E+1)%3,A=(E+2)%3,R=b<<x|T<<A,O=1<<E|b<<x|T<<A,L=m[R],C=m[O];e[_].set(L,C);const I=i[E],k=i[x],D=i[A],B=t[_],W=B.start,te=B.end;W[I]=h[I],W[k]=b?h[k]:f[k],W[D]=T?h[D]:f[k],te[I]=f[I],te[k]=b?h[k]:f[k],te[D]=T?h[D]:f[k],_++}for(let E=0;E<=1;E++)for(let b=0;b<=1;b++)for(let T=0;T<=1;T++){s.x=E?f.x:h.x,s.y=b?f.y:h.y,s.z=T?f.z:h.z,this.closestPointToPoint(s,n);const x=s.distanceToSquared(n);if(x<w&&(w=x,c&&c.copy(n),d&&d.copy(s),x<u))return Math.sqrt(x)}for(let E=0;E<12;E++){const b=e[E];for(let T=0;T<12;T++){const x=t[T];Ti(b,x,n,s);const A=n.distanceToSquared(s);if(A<w&&(w=A,c&&c.copy(n),d&&d.copy(s),A<u))return Math.sqrt(A)}}return Math.sqrt(w)}})();class Ca extends wi{constructor(){super(()=>new dt)}}const rt=new Ca,un=new p.Vector3,Ds=new p.Vector3;function Ia(i,e,t={},n=0,s=1/0){const r=n*n,o=s*s;let a=1/0,c=null;if(i.shapecast({boundsTraverseOrder:u=>(un.copy(e).clamp(u.min,u.max),un.distanceToSquared(e)),intersectsBounds:(u,h,f)=>f<a&&f<o,intersectsTriangle:(u,h)=>{u.closestPointToPoint(e,un);const f=e.distanceToSquared(un);return f<a&&(Ds.copy(un),a=f,c=h),f<r}}),a===1/0)return null;const d=Math.sqrt(a);return t.point?t.point.copy(Ds):t.point=Ds.clone(),t.distance=d,t.faceIndex=c,t}const Wn=parseInt(p.REVISION)>=169,La=parseInt(p.REVISION)<=161,Nt=new p.Vector3,kt=new p.Vector3,Ft=new p.Vector3,Zn=new p.Vector2,Kn=new p.Vector2,Xn=new p.Vector2,Ki=new p.Vector3,Xi=new p.Vector3,Yi=new p.Vector3,dn=new p.Vector3;function Pa(i,e,t,n,s,r,o,a){let c;if(r===p.BackSide?c=i.intersectTriangle(n,t,e,!0,s):c=i.intersectTriangle(e,t,n,r!==p.DoubleSide,s),c===null)return null;const d=i.origin.distanceTo(s);return d<o||d>a?null:{distance:d,point:s.clone()}}function qi(i,e,t,n,s,r,o,a,c,d,u){Nt.fromBufferAttribute(e,r),kt.fromBufferAttribute(e,o),Ft.fromBufferAttribute(e,a);const h=Pa(i,Nt,kt,Ft,dn,c,d,u);if(h){if(n){Zn.fromBufferAttribute(n,r),Kn.fromBufferAttribute(n,o),Xn.fromBufferAttribute(n,a),h.uv=new p.Vector2;const m=p.Triangle.getInterpolation(dn,Nt,kt,Ft,Zn,Kn,Xn,h.uv);Wn||(h.uv=m)}if(s){Zn.fromBufferAttribute(s,r),Kn.fromBufferAttribute(s,o),Xn.fromBufferAttribute(s,a),h.uv1=new p.Vector2;const m=p.Triangle.getInterpolation(dn,Nt,kt,Ft,Zn,Kn,Xn,h.uv1);Wn||(h.uv1=m),La&&(h.uv2=h.uv1)}if(t){Ki.fromBufferAttribute(t,r),Xi.fromBufferAttribute(t,o),Yi.fromBufferAttribute(t,a),h.normal=new p.Vector3;const m=p.Triangle.getInterpolation(dn,Nt,kt,Ft,Ki,Xi,Yi,h.normal);h.normal.dot(i.direction)>0&&h.normal.multiplyScalar(-1),Wn||(h.normal=m)}const f={a:r,b:o,c:a,normal:new p.Vector3,materialIndex:0};if(p.Triangle.getNormal(Nt,kt,Ft,f.normal),h.face=f,h.faceIndex=r,Wn){const m=new p.Vector3;p.Triangle.getBarycoord(dn,Nt,kt,Ft,m),h.barycoord=m}}return h}function $i(i){return i&&i.isMaterial?i.side:i}function bs(i,e,t,n,s,r,o){const a=n*3;let c=a+0,d=a+1,u=a+2;const{index:h,groups:f}=i;i.index&&(c=h.getX(c),d=h.getX(d),u=h.getX(u));const{position:m,normal:w,uv:_,uv1:E}=i.attributes;if(Array.isArray(e)){const b=n*3;for(let T=0,x=f.length;T<x;T++){const{start:A,count:R,materialIndex:O}=f[T];if(b>=A&&b<A+R){const L=$i(e[O]),C=qi(t,m,w,_,E,c,d,u,L,r,o);if(C)if(C.faceIndex=n,C.face.materialIndex=O,s)s.push(C);else return C}}}else{const b=$i(e),T=qi(t,m,w,_,E,c,d,u,b,r,o);if(T)if(T.faceIndex=n,T.face.materialIndex=0,s)s.push(T);else return T}return null}function Ie(i,e,t,n){const s=i.a,r=i.b,o=i.c;let a=e,c=e+1,d=e+2;t&&(a=t.getX(a),c=t.getX(c),d=t.getX(d)),s.x=n.getX(a),s.y=n.getY(a),s.z=n.getZ(a),r.x=n.getX(c),r.y=n.getY(c),r.z=n.getZ(c),o.x=n.getX(d),o.y=n.getY(d),o.z=n.getZ(d)}function Oa(i,e,t,n,s,r,o,a){const{geometry:c,_indirectBuffer:d}=i;for(let u=n,h=n+s;u<h;u++)bs(c,e,t,u,r,o,a)}function Da(i,e,t,n,s,r,o){const{geometry:a,_indirectBuffer:c}=i;let d=1/0,u=null;for(let h=n,f=n+s;h<f;h++){let m;m=bs(a,e,t,h,null,r,o),m&&m.distance<d&&(u=m,d=m.distance)}return u}function Na(i,e,t,n,s,r,o){const{geometry:a}=t,{index:c}=a,d=a.attributes.position;for(let u=i,h=e+i;u<h;u++){let f;if(f=u,Ie(o,f*3,c,d),o.needsUpdate=!0,n(o,f,s,r))return!0}return!1}function ka(i,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=i.geometry,n=t.index?t.index.array:null,s=t.attributes.position;let r,o,a,c,d=0;const u=i._roots;for(let f=0,m=u.length;f<m;f++)r=u[f],o=new Uint32Array(r),a=new Uint16Array(r),c=new Float32Array(r),h(0,d),d+=r.byteLength;function h(f,m,w=!1){const _=f*2;if(Ce(_,a)){const E=Ve(f,o),b=Xe(_,a);let T=1/0,x=1/0,A=1/0,R=-1/0,O=-1/0,L=-1/0;for(let C=3*E,N=3*(E+b);C<N;C++){let I=n[C];const k=s.getX(I),D=s.getY(I),B=s.getZ(I);k<T&&(T=k),k>R&&(R=k),D<x&&(x=D),D>O&&(O=D),B<A&&(A=B),B>L&&(L=B)}return c[f+0]!==T||c[f+1]!==x||c[f+2]!==A||c[f+3]!==R||c[f+4]!==O||c[f+5]!==L?(c[f+0]=T,c[f+1]=x,c[f+2]=A,c[f+3]=R,c[f+4]=O,c[f+5]=L,!0):!1}else{const E=Fe(f),b=Be(f,o);let T=w,x=!1,A=!1;if(e){if(!T){const I=E/De+m/He,k=b/De+m/He;x=e.has(I),A=e.has(k),T=!x&&!A}}else x=!0,A=!0;const R=T||x,O=T||A;let L=!1;R&&(L=h(E,m,T));let C=!1;O&&(C=h(b,m,T));const N=L||C;if(N)for(let I=0;I<3;I++){const k=E+I,D=b+I,B=c[k],W=c[k+3],te=c[D],re=c[D+3];c[f+I]=B<te?B:te,c[f+I+3]=W>re?W:re}return N}}}function Ot(i,e,t,n,s){let r,o,a,c,d,u;const h=1/t.direction.x,f=1/t.direction.y,m=1/t.direction.z,w=t.origin.x,_=t.origin.y,E=t.origin.z;let b=e[i],T=e[i+3],x=e[i+1],A=e[i+3+1],R=e[i+2],O=e[i+3+2];return h>=0?(r=(b-w)*h,o=(T-w)*h):(r=(T-w)*h,o=(b-w)*h),f>=0?(a=(x-_)*f,c=(A-_)*f):(a=(A-_)*f,c=(x-_)*f),r>c||a>o||((a>r||isNaN(r))&&(r=a),(c<o||isNaN(o))&&(o=c),m>=0?(d=(R-E)*m,u=(O-E)*m):(d=(O-E)*m,u=(R-E)*m),r>u||d>o)?!1:((d>r||r!==r)&&(r=d),(u<o||o!==o)&&(o=u),r<=s&&o>=n)}function Fa(i,e,t,n,s,r,o,a){const{geometry:c,_indirectBuffer:d}=i;for(let u=n,h=n+s;u<h;u++){let f=d?d[u]:u;bs(c,e,t,f,r,o,a)}}function Ba(i,e,t,n,s,r,o){const{geometry:a,_indirectBuffer:c}=i;let d=1/0,u=null;for(let h=n,f=n+s;h<f;h++){let m;m=bs(a,e,t,c?c[h]:h,null,r,o),m&&m.distance<d&&(u=m,d=m.distance)}return u}function za(i,e,t,n,s,r,o){const{geometry:a}=t,{index:c}=a,d=a.attributes.position;for(let u=i,h=e+i;u<h;u++){let f;if(f=t.resolveTriangleIndex(u),Ie(o,f*3,c,d),o.needsUpdate=!0,n(o,f,s,r))return!0}return!1}function Ua(i,e,t,n,s,r,o){be.setBuffer(i._roots[e]),ni(0,i,t,n,s,r,o),be.clearBuffer()}function ni(i,e,t,n,s,r,o){const{float32Array:a,uint16Array:c,uint32Array:d}=be,u=i*2;if(Ce(u,c)){const f=Ve(i,d),m=Xe(u,c);Oa(e,t,n,f,m,s,r,o)}else{const f=Fe(i);Ot(f,a,n,r,o)&&ni(f,e,t,n,s,r,o);const m=Be(i,d);Ot(m,a,n,r,o)&&ni(m,e,t,n,s,r,o)}}const Ha=["x","y","z"];function Va(i,e,t,n,s,r){be.setBuffer(i._roots[e]);const o=si(0,i,t,n,s,r);return be.clearBuffer(),o}function si(i,e,t,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:c}=be;let d=i*2;if(Ce(d,a)){const h=Ve(i,c),f=Xe(d,a);return Da(e,t,n,h,f,s,r)}else{const h=Ts(i,c),f=Ha[h],w=n.direction[f]>=0;let _,E;w?(_=Fe(i),E=Be(i,c)):(_=Be(i,c),E=Fe(i));const T=Ot(_,o,n,s,r)?si(_,e,t,n,s,r):null;if(T){const R=T.point[f];if(w?R<=o[E+h]:R>=o[E+h+3])return T}const A=Ot(E,o,n,s,r)?si(E,e,t,n,s,r):null;return T&&A?T.distance<=A.distance?T:A:T||A||null}}const Yn=new p.Box3,Xt=new dt,Yt=new dt,fn=new p.Matrix4,Qi=new Ye,qn=new Ye;function ja(i,e,t,n){be.setBuffer(i._roots[e]);const s=ii(0,i,t,n);return be.clearBuffer(),s}function ii(i,e,t,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=be;let c=i*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),Qi.set(t.boundingBox.min,t.boundingBox.max,n),s=Qi),Ce(c,o)){const u=e.geometry,h=u.index,f=u.attributes.position,m=t.index,w=t.attributes.position,_=Ve(i,a),E=Xe(c,o);if(fn.copy(n).invert(),t.boundsTree)return xe(i,r,qn),qn.matrix.copy(fn),qn.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:T=>qn.intersectsBox(T),intersectsTriangle:T=>{T.a.applyMatrix4(n),T.b.applyMatrix4(n),T.c.applyMatrix4(n),T.needsUpdate=!0;for(let x=_*3,A=(E+_)*3;x<A;x+=3)if(Ie(Yt,x,h,f),Yt.needsUpdate=!0,T.intersectsTriangle(Yt))return!0;return!1}});{const b=_s(t);for(let T=_*3,x=(E+_)*3;T<x;T+=3){Ie(Xt,T,h,f),Xt.a.applyMatrix4(fn),Xt.b.applyMatrix4(fn),Xt.c.applyMatrix4(fn),Xt.needsUpdate=!0;for(let A=0,R=b*3;A<R;A+=3)if(Ie(Yt,A,m,w),Yt.needsUpdate=!0,Xt.intersectsTriangle(Yt))return!0}}}else{const u=Fe(i),h=Be(i,a);return xe(u,r,Yn),!!(s.intersectsBox(Yn)&&ii(u,e,t,n,s)||(xe(h,r,Yn),s.intersectsBox(Yn)&&ii(h,e,t,n,s)))}}const $n=new p.Matrix4,Ns=new Ye,pn=new Ye,Ga=new p.Vector3,Wa=new p.Vector3,Za=new p.Vector3,Ka=new p.Vector3;function Xa(i,e,t,n={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),Ns.set(e.boundingBox.min,e.boundingBox.max,t),Ns.needsUpdate=!0;const a=i.geometry,c=a.attributes.position,d=a.index,u=e.attributes.position,h=e.index,f=rt.getPrimitive(),m=rt.getPrimitive();let w=Ga,_=Wa,E=null,b=null;s&&(E=Za,b=Ka);let T=1/0,x=null,A=null;return $n.copy(t).invert(),pn.matrix.copy($n),i.shapecast({boundsTraverseOrder:R=>Ns.distanceToBox(R),intersectsBounds:(R,O,L)=>L<T&&L<o?(O&&(pn.min.copy(R.min),pn.max.copy(R.max),pn.needsUpdate=!0),!0):!1,intersectsRange:(R,O)=>{if(e.boundsTree)return e.boundsTree.shapecast({boundsTraverseOrder:C=>pn.distanceToBox(C),intersectsBounds:(C,N,I)=>I<T&&I<o,intersectsRange:(C,N)=>{for(let I=C,k=C+N;I<k;I++){Ie(m,3*I,h,u),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let D=R,B=R+O;D<B;D++){Ie(f,3*D,d,c),f.needsUpdate=!0;const W=f.distanceToTriangle(m,w,E);if(W<T&&(_.copy(w),b&&b.copy(E),T=W,x=D,A=I),W<r)return!0}}}});{const L=_s(e);for(let C=0,N=L;C<N;C++){Ie(m,3*C,h,u),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let I=R,k=R+O;I<k;I++){Ie(f,3*I,d,c),f.needsUpdate=!0;const D=f.distanceToTriangle(m,w,E);if(D<T&&(_.copy(w),b&&b.copy(E),T=D,x=I,A=C),D<r)return!0}}}}}),rt.releasePrimitive(f),rt.releasePrimitive(m),T===1/0?null:(n.point?n.point.copy(_):n.point=_.clone(),n.distance=T,n.faceIndex=x,s&&(s.point?s.point.copy(b):s.point=b.clone(),s.point.applyMatrix4($n),_.applyMatrix4($n),s.distance=_.sub(s.point).length(),s.faceIndex=A),n)}function Ya(i,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=i.geometry,n=t.index?t.index.array:null,s=t.attributes.position;let r,o,a,c,d=0;const u=i._roots;for(let f=0,m=u.length;f<m;f++)r=u[f],o=new Uint32Array(r),a=new Uint16Array(r),c=new Float32Array(r),h(0,d),d+=r.byteLength;function h(f,m,w=!1){const _=f*2;if(Ce(_,a)){const E=Ve(f,o),b=Xe(_,a);let T=1/0,x=1/0,A=1/0,R=-1/0,O=-1/0,L=-1/0;for(let C=E,N=E+b;C<N;C++){const I=3*i.resolveTriangleIndex(C);for(let k=0;k<3;k++){let D=I+k;D=n?n[D]:D;const B=s.getX(D),W=s.getY(D),te=s.getZ(D);B<T&&(T=B),B>R&&(R=B),W<x&&(x=W),W>O&&(O=W),te<A&&(A=te),te>L&&(L=te)}}return c[f+0]!==T||c[f+1]!==x||c[f+2]!==A||c[f+3]!==R||c[f+4]!==O||c[f+5]!==L?(c[f+0]=T,c[f+1]=x,c[f+2]=A,c[f+3]=R,c[f+4]=O,c[f+5]=L,!0):!1}else{const E=Fe(f),b=Be(f,o);let T=w,x=!1,A=!1;if(e){if(!T){const I=E/De+m/He,k=b/De+m/He;x=e.has(I),A=e.has(k),T=!x&&!A}}else x=!0,A=!0;const R=T||x,O=T||A;let L=!1;R&&(L=h(E,m,T));let C=!1;O&&(C=h(b,m,T));const N=L||C;if(N)for(let I=0;I<3;I++){const k=E+I,D=b+I,B=c[k],W=c[k+3],te=c[D],re=c[D+3];c[f+I]=B<te?B:te,c[f+I+3]=W>re?W:re}return N}}}function qa(i,e,t,n,s,r,o){be.setBuffer(i._roots[e]),ri(0,i,t,n,s,r,o),be.clearBuffer()}function ri(i,e,t,n,s,r,o){const{float32Array:a,uint16Array:c,uint32Array:d}=be,u=i*2;if(Ce(u,c)){const f=Ve(i,d),m=Xe(u,c);Fa(e,t,n,f,m,s,r,o)}else{const f=Fe(i);Ot(f,a,n,r,o)&&ri(f,e,t,n,s,r,o);const m=Be(i,d);Ot(m,a,n,r,o)&&ri(m,e,t,n,s,r,o)}}const $a=["x","y","z"];function Qa(i,e,t,n,s,r){be.setBuffer(i._roots[e]);const o=oi(0,i,t,n,s,r);return be.clearBuffer(),o}function oi(i,e,t,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:c}=be;let d=i*2;if(Ce(d,a)){const h=Ve(i,c),f=Xe(d,a);return Ba(e,t,n,h,f,s,r)}else{const h=Ts(i,c),f=$a[h],w=n.direction[f]>=0;let _,E;w?(_=Fe(i),E=Be(i,c)):(_=Be(i,c),E=Fe(i));const T=Ot(_,o,n,s,r)?oi(_,e,t,n,s,r):null;if(T){const R=T.point[f];if(w?R<=o[E+h]:R>=o[E+h+3])return T}const A=Ot(E,o,n,s,r)?oi(E,e,t,n,s,r):null;return T&&A?T.distance<=A.distance?T:A:T||A||null}}const Qn=new p.Box3,qt=new dt,$t=new dt,mn=new p.Matrix4,Ji=new Ye,Jn=new Ye;function Ja(i,e,t,n){be.setBuffer(i._roots[e]);const s=ai(0,i,t,n);return be.clearBuffer(),s}function ai(i,e,t,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=be;let c=i*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),Ji.set(t.boundingBox.min,t.boundingBox.max,n),s=Ji),Ce(c,o)){const u=e.geometry,h=u.index,f=u.attributes.position,m=t.index,w=t.attributes.position,_=Ve(i,a),E=Xe(c,o);if(mn.copy(n).invert(),t.boundsTree)return xe(i,r,Jn),Jn.matrix.copy(mn),Jn.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:T=>Jn.intersectsBox(T),intersectsTriangle:T=>{T.a.applyMatrix4(n),T.b.applyMatrix4(n),T.c.applyMatrix4(n),T.needsUpdate=!0;for(let x=_,A=E+_;x<A;x++)if(Ie($t,3*e.resolveTriangleIndex(x),h,f),$t.needsUpdate=!0,T.intersectsTriangle($t))return!0;return!1}});{const b=_s(t);for(let T=_,x=E+_;T<x;T++){const A=e.resolveTriangleIndex(T);Ie(qt,3*A,h,f),qt.a.applyMatrix4(mn),qt.b.applyMatrix4(mn),qt.c.applyMatrix4(mn),qt.needsUpdate=!0;for(let R=0,O=b*3;R<O;R+=3)if(Ie($t,R,m,w),$t.needsUpdate=!0,qt.intersectsTriangle($t))return!0}}}else{const u=Fe(i),h=Be(i,a);return xe(u,r,Qn),!!(s.intersectsBox(Qn)&&ai(u,e,t,n,s)||(xe(h,r,Qn),s.intersectsBox(Qn)&&ai(h,e,t,n,s)))}}const es=new p.Matrix4,ks=new Ye,gn=new Ye,ec=new p.Vector3,tc=new p.Vector3,nc=new p.Vector3,sc=new p.Vector3;function ic(i,e,t,n={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),ks.set(e.boundingBox.min,e.boundingBox.max,t),ks.needsUpdate=!0;const a=i.geometry,c=a.attributes.position,d=a.index,u=e.attributes.position,h=e.index,f=rt.getPrimitive(),m=rt.getPrimitive();let w=ec,_=tc,E=null,b=null;s&&(E=nc,b=sc);let T=1/0,x=null,A=null;return es.copy(t).invert(),gn.matrix.copy(es),i.shapecast({boundsTraverseOrder:R=>ks.distanceToBox(R),intersectsBounds:(R,O,L)=>L<T&&L<o?(O&&(gn.min.copy(R.min),gn.max.copy(R.max),gn.needsUpdate=!0),!0):!1,intersectsRange:(R,O)=>{if(e.boundsTree){const L=e.boundsTree;return L.shapecast({boundsTraverseOrder:C=>gn.distanceToBox(C),intersectsBounds:(C,N,I)=>I<T&&I<o,intersectsRange:(C,N)=>{for(let I=C,k=C+N;I<k;I++){const D=L.resolveTriangleIndex(I);Ie(m,3*D,h,u),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let B=R,W=R+O;B<W;B++){const te=i.resolveTriangleIndex(B);Ie(f,3*te,d,c),f.needsUpdate=!0;const re=f.distanceToTriangle(m,w,E);if(re<T&&(_.copy(w),b&&b.copy(E),T=re,x=B,A=I),re<r)return!0}}}})}else{const L=_s(e);for(let C=0,N=L;C<N;C++){Ie(m,3*C,h,u),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let I=R,k=R+O;I<k;I++){const D=i.resolveTriangleIndex(I);Ie(f,3*D,d,c),f.needsUpdate=!0;const B=f.distanceToTriangle(m,w,E);if(B<T&&(_.copy(w),b&&b.copy(E),T=B,x=I,A=C),B<r)return!0}}}}}),rt.releasePrimitive(f),rt.releasePrimitive(m),T===1/0?null:(n.point?n.point.copy(_):n.point=_.clone(),n.distance=T,n.faceIndex=x,s&&(s.point?s.point.copy(b):s.point=b.clone(),s.point.applyMatrix4(es),_.applyMatrix4(es),s.distance=_.sub(s.point).length(),s.faceIndex=A),n)}function er(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,tr=new p.Vector3,nr=new p.Matrix4,sr=new p.Vector3,Fs=["getX","getY","getZ"];class bn extends Aa{static serialize(e,t={}){t={cloneBuffers:!0,...t};const n=e.geometry,s=e._roots,r=e._indirectBuffer,o=n.getIndex(),a={version:1,roots:null,index:null,indirectBuffer:null};return t.cloneBuffers?(a.roots=s.map(c=>c.slice()),a.index=o?o.array.slice():null,a.indirectBuffer=r?r.slice():null):(a.roots=s,a.index=o?o.array:null,a.indirectBuffer=r),a}static deserialize(e,t,n={}){n={setIndex:!0,indirect:!!e.indirectBuffer,...n};const{index:s,roots:r,indirectBuffer:o}=e;e.version||(console.warn("MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."),c(r));const a=new bn(t,{...n,[Ei]:!0});if(a._roots=r,a._indirectBuffer=o||null,n.setIndex){const d=t.getIndex();if(d===null){const u=new p.BufferAttribute(e.index,1,!1);t.setIndex(u)}else d.array!==s&&(d.array.set(s),d.needsUpdate=!0)}return a;function c(d){for(let u=0;u<d.length;u++){const h=d[u],f=new Uint32Array(h),m=new Uint16Array(h);for(let w=0,_=h.byteLength/He;w<_;w++){const E=De*w,b=2*E;Ce(b,m)||(f[E+6]=f[E+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,r=this._indirectBuffer,o=s.attributes.position,a=s.index?s.index.array:null,d=(r?r[e]:e)*3;let u=d+0,h=d+1,f=d+2;a&&(u=a[u],h=a[h],f=a[f]);for(let m=0;m<3;m++){const w=o[Fs[m]](u),_=o[Fs[m]](h),E=o[Fs[m]](f);let b=w;_<b&&(b=_),E<b&&(b=E);let T=w;_>T&&(T=_),E>T&&(T=E),t[n+m]=b,t[n+m+3]=T}return t}computePrimitiveBounds(e,t,n){const s=this.geometry,r=this._indirectBuffer,o=s.attributes.position,a=s.index?s.index.array:null,c=o.normalized;if(e<0||t+e-n.offset>n.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const d=o.array,u=o.offset||0;let h=3;o.isInterleavedBufferAttribute&&(h=o.data.stride);const f=["getX","getY","getZ"],m=n.offset;for(let w=e,_=e+t;w<_;w++){const b=(r?r[w]:w)*3,T=(w-m)*6;let x=b+0,A=b+1,R=b+2;a&&(x=a[x],A=a[A],R=a[R]),c||(x=x*h+u,A=A*h+u,R=R*h+u);for(let O=0;O<3;O++){let L,C,N;c?(L=o[f[O]](x),C=o[f[O]](A),N=o[f[O]](R)):(L=d[x+O],C=d[A+O],N=d[R+O]);let I=L;C<I&&(I=C),N<I&&(I=N);let k=L;C>k&&(k=C),N>k&&(k=N);const D=(k-I)/2,B=O*2;n[T+B+0]=I+D,n[T+B+1]=D+(Math.abs(I)+D)*us}}return n}raycastObject3D(e,t,n=[]){const{material:s}=e;if(s===void 0)return;nr.copy(e.matrixWorld).invert(),ns.copy(t.ray).applyMatrix4(nr),sr.setFromMatrixScale(e.matrixWorld),tr.copy(ns.direction).multiply(sr);const r=tr.length(),o=t.near/r,a=t.far/r;if(t.firstHitOnly===!0){let c=this.raycastFirst(ns,s,o,a);c=er(c,e,t),c&&n.push(c)}else{const c=this.raycast(ns,s,o,a);for(let d=0,u=c.length;d<u;d++){const h=er(c[d],e,t);h&&n.push(h)}}return n}refit(e=null){return(this.indirect?Ya:ka)(this,e)}raycast(e,t=p.FrontSide,n=0,s=1/0){const r=this._roots,o=[],a=this.indirect?qa:Ua;for(let c=0,d=r.length;c<d;c++)a(this,c,t,e,o,n,s);return o}raycastFirst(e,t=p.FrontSide,n=0,s=1/0){const r=this._roots;let o=null;const a=this.indirect?Qa:Va;for(let c=0,d=r.length;c<d;c++){const u=a(this,c,t,e,n,s);u!=null&&(o==null||u.distance<o.distance)&&(o=u)}return o}intersectsGeometry(e,t){let n=!1;const s=this._roots,r=this.indirect?Ja:ja;for(let o=0,a=s.length;o<a&&(n=r(this,o,e,t),!n);o++);return n}shapecast(e){const t=rt.getPrimitive(),n=super.shapecast({...e,intersectsPrimitive:e.intersectsTriangle,scratchPrimitive:t,iterate:this.indirect?za:Na});return rt.releasePrimitive(t),n}bvhcast(e,t,n){let{intersectsRanges:s,intersectsTriangles:r}=n;const o=rt.getPrimitive(),a=this.geometry.index,c=this.geometry.attributes.position,d=this.indirect?w=>{const _=this.resolveTriangleIndex(w);Ie(o,_*3,a,c)}:w=>{Ie(o,w*3,a,c)},u=rt.getPrimitive(),h=e.geometry.index,f=e.geometry.attributes.position,m=e.indirect?w=>{const _=e.resolveTriangleIndex(w);Ie(u,_*3,h,f)}:w=>{Ie(u,w*3,h,f)};if(r){if(!(e instanceof bn))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const w=(_,E,b,T,x,A,R,O)=>{for(let L=b,C=b+T;L<C;L++){m(L),u.a.applyMatrix4(t),u.b.applyMatrix4(t),u.c.applyMatrix4(t),u.needsUpdate=!0;for(let N=_,I=_+E;N<I;N++)if(d(N),o.needsUpdate=!0,r(o,u,N,L,x,A,R,O))return!0}return!1};if(s){const _=s;s=function(E,b,T,x,A,R,O,L){return _(E,b,T,x,A,R,O,L)?!0:w(E,b,T,x,A,R,O,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={},r=0,o=1/0){return(this.indirect?ic:Xa)(this,e,t,n,s,r,o)}closestPointToPoint(e,t={},n=0,s=1/0){return Ia(this,e,t,n,s)}}const tn={Mesh:p.Mesh.prototype.raycast,Line:p.Line.prototype.raycast,LineSegments:p.LineSegments.prototype.raycast,LineLoop:p.LineLoop.prototype.raycast,Points:p.Points.prototype.raycast,BatchedMesh:p.BatchedMesh.prototype.raycast},Ue=new p.Mesh,ss=[];function rc(i,e){if(this.isBatchedMesh)oc.call(this,i,e);else{const{geometry:t}=this;if(t.boundsTree)t.boundsTree.raycastObject3D(this,i,e);else{let n;if(this instanceof p.Mesh)n=tn.Mesh;else if(this instanceof p.LineSegments)n=tn.LineSegments;else if(this instanceof p.LineLoop)n=tn.LineLoop;else if(this instanceof p.Line)n=tn.Line;else if(this instanceof p.Points)n=tn.Points;else throw new Error("BVH: Fallback raycast function not found.");n.call(this,i,e)}}}function oc(i,e){if(this.boundsTrees){const t=this.boundsTrees,n=this._drawInfo||this._instanceInfo,s=this._drawRanges||this._geometryInfo,r=this.matrixWorld;Ue.material=this.material,Ue.geometry=this.geometry;const o=Ue.geometry.boundsTree,a=Ue.geometry.drawRange;Ue.geometry.boundingSphere===null&&(Ue.geometry.boundingSphere=new p.Sphere);for(let c=0,d=n.length;c<d;c++){if(!this.getVisibleAt(c))continue;const u=n[c].geometryIndex;if(Ue.geometry.boundsTree=t[u],this.getMatrixAt(c,Ue.matrixWorld).premultiply(r),!Ue.geometry.boundsTree){this.getBoundingBoxAt(u,Ue.geometry.boundingBox),this.getBoundingSphereAt(u,Ue.geometry.boundingSphere);const h=s[u];Ue.geometry.setDrawRange(h.start,h.count)}Ue.raycast(i,ss);for(let h=0,f=ss.length;h<f;h++){const m=ss[h];m.object=this,m.batchId=c,e.push(m)}ss.length=0}Ue.geometry.boundsTree=o,Ue.geometry.drawRange=a,Ue.material=null,Ue.geometry=null}else tn.BatchedMesh.call(this,i,e)}function Dr(i){i.traverse(e=>{var s,r,o;const t=e;if(!t.isMesh||t.isSkinnedMesh||t.isInstancedMesh||t.isBatchedMesh)return;const n=t.geometry;!((s=n==null?void 0:n.attributes)!=null&&s.position)||(o=(r=n.morphAttributes)==null?void 0:r.position)!=null&&o.length||(n.boundsTree||(n.boundsTree=new bn(n)),t.raycast=rc)})}function ac(i){i.boundsTree&&(i.boundsTree=void 0)}function ir(i){const e=i;for(const n of Object.keys(e)){const s=e[n];s instanceof S.Texture&&s.dispose()}const t=i;if(t.isShaderMaterial&&t.uniforms)for(const n of Object.values(t.uniforms))(n==null?void 0:n.value)instanceof S.Texture&&n.value.dispose();i.dispose()}function xs(i){i.traverse(e=>{var r;const t=e;t.geometry&&typeof t.geometry.dispose=="function"&&(ac(t.geometry),t.geometry.dispose());const n=t.material;Array.isArray(n)?n.forEach(ir):n&&ir(n);const s=e;s.isLight&&((r=s.shadow)!=null&&r.dispose)&&s.shadow.dispose()})}function cc(i,e){if(!(e!=null&&e.keepBackgrounds)){i.background instanceof S.Texture&&(i.background.dispose(),i.background=null),i.environment instanceof S.Texture&&(i.environment.dispose(),i.environment=null);const t=i;t.__originalEnvironmentTexture&&(t.__originalEnvironmentTexture=void 0)}for(const t of[...i.children])xs(t),i.remove(t)}class Oe{constructor(e){this.object=e,this.positionAdapter=Pt.fromThreeVector(e.position),this.rotationAdapter=Pt.fromThreeVector(e.rotation),this.scaleAdapter=Pt.fromThreeVector(e.scale)}get id(){return this.object.uuid}get name(){return this.object.name}set name(e){this.object.name=e}get visible(){return this.object.visible}set visible(e){this.object.visible=e}get castShadow(){return this.object.castShadow}set castShadow(e){this.object.castShadow=e}get receiveShadow(){return this.object.receiveShadow}set receiveShadow(e){this.object.receiveShadow=e}get position(){return this.positionAdapter}get rotation(){return this.rotationAdapter}get scale(){return this.scaleAdapter}add(e){try{return e instanceof Oe?(this.object.add(e.getThreeObject()),z.ok(void 0)):z.err(new K("Child must be a ThreeObject3DAdapter",q.INVALID_PARAMETER))}catch(t){return z.err(new K("Failed to add child object",q.SCENE_OPERATION_FAILED,{originalError:t}))}}remove(e){try{return e instanceof Oe?(this.object.remove(e.getThreeObject()),z.ok(void 0)):z.err(new K("Child must be a ThreeObject3DAdapter",q.INVALID_PARAMETER))}catch(t){return z.err(new K("Failed to remove child object",q.SCENE_OPERATION_FAILED,{originalError:t}))}}traverse(e){this.object.traverse(t=>{e(new Oe(t))})}clone(){return new Oe(this.object.clone())}dispose(){xs(this.object)}getThreeObject(){return this.object}static fromThreeObject(e){return new Oe(e)}static create(){return new Oe(new S.Object3D)}}class St{constructor(e){this.scene=e||new S.Scene}get id(){return this.scene.uuid}get name(){return this.scene.name}set name(e){this.scene.name=e}add(e){try{return e instanceof Oe?(this.scene.add(e.getThreeObject()),z.ok(void 0)):z.err(new K("Object must be a ThreeObject3DAdapter",q.INVALID_PARAMETER))}catch(t){return z.err(new K("Failed to add object to scene",q.SCENE_OPERATION_FAILED,{originalError:t}))}}remove(e){try{return e instanceof Oe?(this.scene.remove(e.getThreeObject()),z.ok(void 0)):z.err(new K("Object must be a ThreeObject3DAdapter",q.INVALID_PARAMETER))}catch(t){return z.err(new K("Failed to remove object from scene",q.SCENE_OPERATION_FAILED,{originalError:t}))}}clear(){for(;this.scene.children.length>0;)this.scene.remove(this.scene.children[0])}disposeContents(e){cc(this.scene,e)}traverse(e){this.scene.traverse(t=>{e(new Oe(t))})}get background(){return this.scene.background instanceof S.Color?new ci(this.scene.background):this.scene.background instanceof S.Texture?new is(this.scene.background):null}set background(e){e instanceof ci?this.scene.background=e.getThreeColor():e instanceof is?this.scene.background=e.getThreeTexture():this.scene.background=null}get fog(){return this.scene.fog?new rr(this.scene.fog):null}set fog(e){e instanceof rr?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 ci{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 rr{constructor(e){this.fog=e}get color(){return new ci(this.fog.color)}get near(){return this.fog.near||0}get far(){return this.fog.far||1e3}getThreeFog(){return this.fog}}class Nr extends Oe{constructor(e){super(e),this.camera=e}get near(){return this.camera instanceof S.PerspectiveCamera||this.camera instanceof S.OrthographicCamera?this.camera.near:.1}set near(e){(this.camera instanceof S.PerspectiveCamera||this.camera instanceof S.OrthographicCamera)&&(this.camera.near=e)}get far(){return this.camera instanceof S.PerspectiveCamera||this.camera instanceof S.OrthographicCamera?this.camera.far:1e3}set far(e){(this.camera instanceof S.PerspectiveCamera||this.camera instanceof S.OrthographicCamera)&&(this.camera.far=e)}lookAt(e){e instanceof Pt?this.camera.lookAt(e.getThreeVector()):this.camera.lookAt(e.x,e.y,e.z)}updateProjectionMatrix(){(this.camera instanceof S.PerspectiveCamera||this.camera instanceof S.OrthographicCamera)&&this.camera.updateProjectionMatrix()}getWorldDirection(e){const t=new S.Vector3;this.camera.getWorldDirection(t),e.set(t.x,t.y,t.z)}getInternalRenderer(){return this.camera}getThreeCamera(){return this.camera}}class Si extends Nr{constructor(e){const t=e||new S.PerspectiveCamera;super(t),this.perspectiveCamera=t}get type(){return"perspective"}get fov(){return this.perspectiveCamera.fov}set fov(e){this.perspectiveCamera.fov=e}get aspect(){return this.perspectiveCamera.aspect}set aspect(e){this.perspectiveCamera.aspect=e}static create(e=75,t=1,n=.1,s=1e3){return new Si(new S.PerspectiveCamera(e,t,n,s))}}class lc{constructor(e){this.renderer=null,this._id=Rr(),this.canvas=e}get id(){return this._id}initialize(e){try{if(this.renderer=new S.WebGLRenderer({canvas:this.canvas,antialias:e.antialias??!0,alpha:e.alpha??!1,premultipliedAlpha:e.premultipliedAlpha??!0,preserveDrawingBuffer:e.preserveDrawingBuffer??!1,powerPreference:e.powerPreference??"default"}),e.shadowMap&&(this.renderer.shadowMap.enabled=e.shadowMap.enabled,this.renderer.shadowMap.autoUpdate=!0,e.shadowMap.type)){const t={basic:S.BasicShadowMap,pcf:S.PCFShadowMap,pcfsoft:S.PCFSoftShadowMap,vsm:S.VSMShadowMap};this.renderer.shadowMap.type=t[e.shadowMap.type]}if(e.toneMapping){const t={none:S.NoToneMapping,linear:S.LinearToneMapping,reinhard:S.ReinhardToneMapping,cineon:S.CineonToneMapping,aces:S.ACESFilmicToneMapping};this.renderer.toneMapping=t[e.toneMapping.type],this.renderer.toneMappingExposure=e.toneMapping.exposure}if(e.pixelRatio!==void 0?this.renderer.setPixelRatio(e.pixelRatio):this.renderer.setPixelRatio(window.devicePixelRatio),this.canvas){const{clientWidth:t,clientHeight:n}=this.canvas.parentElement||this.canvas;t&&n&&this.renderer.setSize(t,n)}return this.renderer.outputColorSpace=S.SRGBColorSpace,z.ok(void 0)}catch(t){return z.err(new K("Failed to initialize renderer",q.RENDERER_INIT_FAILED,{originalError:t,options:e}))}}render(e,t){if(!this.renderer)return z.err(new K("Renderer not initialized",q.RENDERER_NOT_INITIALIZED));try{if(!(e instanceof St))return z.err(new K("Scene must be a ThreeSceneAdapter",q.INVALID_PARAMETER));if(!(t instanceof Nr))return z.err(new K("Camera must be a ThreeCameraAdapter",q.INVALID_PARAMETER));const n=e.getThreeScene(),s=t.getThreeCamera();return this.renderer.render(n,s),z.ok(void 0)}catch(n){return z.err(new K("Failed to render frame",q.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 or(i,e){if(e===p.TrianglesDrawMode)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),i;if(e===p.TriangleFanDrawMode||e===p.TriangleStripDrawMode){let t=i.getIndex();if(t===null){const o=[],a=i.getAttribute("position");if(a!==void 0){for(let c=0;c<a.count;c++)o.push(c);i.setIndex(o),t=i.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),i}const n=t.count-2,s=[];if(e===p.TriangleFanDrawMode)for(let o=1;o<=n;o++)s.push(t.getX(0)),s.push(t.getX(o)),s.push(t.getX(o+1));else for(let o=0;o<n;o++)o%2===0?(s.push(t.getX(o)),s.push(t.getX(o+1)),s.push(t.getX(o+2))):(s.push(t.getX(o+2)),s.push(t.getX(o+1)),s.push(t.getX(o)));s.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const r=i.clone();return r.setIndex(s),r.clearGroups(),r}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),i}function hc(i){const e=new Map,t=new Map,n=i.clone();return kr(i,n,function(s,r){e.set(r,s),t.set(s,r)}),n.traverse(function(s){if(!s.isSkinnedMesh)return;const r=s,o=e.get(s),a=o.skeleton.bones;r.skeleton=o.skeleton.clone(),r.bindMatrix.copy(o.bindMatrix),r.skeleton.bones=a.map(function(c){return t.get(c)}),r.bind(r.skeleton,r.bindMatrix)}),n}function kr(i,e,t){t(i,e);for(let n=0;n<i.children.length;n++)kr(i.children[n],e.children[n],t)}class uc extends p.Loader{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new gc(t)}),this.register(function(t){return new yc(t)}),this.register(function(t){return new Mc(t)}),this.register(function(t){return new Rc(t)}),this.register(function(t){return new vc(t)}),this.register(function(t){return new wc(t)}),this.register(function(t){return new Tc(t)}),this.register(function(t){return new Sc(t)}),this.register(function(t){return new _c(t)}),this.register(function(t){return new mc(t)}),this.register(function(t){return new bc(t)}),this.register(function(t){return new Ec(t)}),this.register(function(t){return new Ac(t)}),this.register(function(t){return new xc(t)}),this.register(function(t){return new fc(t)}),this.register(function(t){return new ar(t,le.EXT_MESHOPT_COMPRESSION)}),this.register(function(t){return new ar(t,le.KHR_MESHOPT_COMPRESSION)}),this.register(function(t){return new Cc(t)})}load(e,t,n,s){const r=this;let o;if(this.resourcePath!=="")o=this.resourcePath;else if(this.path!==""){const d=p.LoaderUtils.extractUrlBase(e);o=p.LoaderUtils.resolveURL(d,this.path)}else o=p.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const a=function(d){s?s(d):console.error(d),r.manager.itemError(e),r.manager.itemEnd(e)},c=new p.FileLoader(this.manager);c.setPath(this.path),c.setResponseType("arraybuffer"),c.setRequestHeader(this.requestHeader),c.setWithCredentials(this.withCredentials),c.load(e,function(d){try{r.parse(d,o,function(u){t(u),r.manager.itemEnd(e)},a)}catch(u){a(u)}},n,a)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,s){let r;const o={},a={},c=new TextDecoder;if(typeof e=="string")r=JSON.parse(e);else if(e instanceof ArrayBuffer)if(c.decode(new Uint8Array(e,0,4))===Fr){try{o[le.KHR_BINARY_GLTF]=new Ic(e)}catch(h){s&&s(h);return}r=JSON.parse(o[le.KHR_BINARY_GLTF].content)}else r=JSON.parse(c.decode(e));else r=e;if(r.asset===void 0||r.asset.version[0]<2){s&&s(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const d=new jc(r,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});d.fileLoader.setRequestHeader(this.requestHeader);for(let u=0;u<this.pluginCallbacks.length;u++){const h=this.pluginCallbacks[u](d);h.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),a[h.name]=h,o[h.name]=!0}if(r.extensionsUsed)for(let u=0;u<r.extensionsUsed.length;++u){const h=r.extensionsUsed[u],f=r.extensionsRequired||[];switch(h){case le.KHR_MATERIALS_UNLIT:o[h]=new pc;break;case le.KHR_DRACO_MESH_COMPRESSION:o[h]=new Lc(r,this.dracoLoader);break;case le.KHR_TEXTURE_TRANSFORM:o[h]=new Pc;break;case le.KHR_MESH_QUANTIZATION:o[h]=new Oc;break;default:f.indexOf(h)>=0&&a[h]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+h+'".')}}d.setExtensions(o),d.setPlugins(a),d.parse(n,s)}parseAsync(e,t){const n=this;return new Promise(function(s,r){n.parse(e,t,s,r)})}}function dc(){let i={};return{get:function(e){return i[e]},add:function(e,t){i[e]=t},remove:function(e){delete i[e]},removeAll:function(){i={}}}}function Me(i,e,t){const n=i.json.materials[e];return n.extensions&&n.extensions[t]?n.extensions[t]:null}const le={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",KHR_MESHOPT_COMPRESSION:"KHR_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class fc{constructor(e){this.parser=e,this.name=le.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,s=t.length;n<s;n++){const r=t[n];r.extensions&&r.extensions[this.name]&&r.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,r.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let s=t.cache.get(n);if(s)return s;const r=t.json,c=((r.extensions&&r.extensions[this.name]||{}).lights||[])[e];let d;const u=new p.Color(16777215);c.color!==void 0&&u.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":d=new p.DirectionalLight(u),d.target.position.set(0,0,-1),d.add(d.target);break;case"point":d=new p.PointLight(u),d.distance=h;break;case"spot":d=new p.SpotLight(u),d.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,d.angle=c.spot.outerConeAngle,d.penumbra=1-c.spot.innerConeAngle/c.spot.outerConeAngle,d.target.position.set(0,0,-1),d.add(d.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+c.type)}return d.position.set(0,0,0),yt(d,c),c.intensity!==void 0&&(d.intensity=c.intensity),d.name=t.createUniqueName(c.name||"light_"+e),s=Promise.resolve(d),t.cache.add(n,s),s}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,n=this.parser,r=n.json.nodes[e],a=(r.extensions&&r.extensions[this.name]||{}).light;return a===void 0?null:this._loadLight(a).then(function(c){return n._getNodeRef(t.cache,a,c)})}}class pc{constructor(){this.name=le.KHR_MATERIALS_UNLIT}getMaterialType(){return p.MeshBasicMaterial}extendParams(e,t,n){const s=[];e.color=new p.Color(1,1,1),e.opacity=1;const r=t.pbrMetallicRoughness;if(r){if(Array.isArray(r.baseColorFactor)){const o=r.baseColorFactor;e.color.setRGB(o[0],o[1],o[2],p.LinearSRGBColorSpace),e.opacity=o[3]}r.baseColorTexture!==void 0&&s.push(n.assignTexture(e,"map",r.baseColorTexture,p.SRGBColorSpace))}return Promise.all(s)}}class mc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const n=Me(this.parser,e,this.name);return n===null||n.emissiveStrength!==void 0&&(t.emissiveIntensity=n.emissiveStrength),Promise.resolve()}}class gc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];if(n.clearcoatFactor!==void 0&&(t.clearcoat=n.clearcoatFactor),n.clearcoatTexture!==void 0&&s.push(this.parser.assignTexture(t,"clearcoatMap",n.clearcoatTexture)),n.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=n.clearcoatRoughnessFactor),n.clearcoatRoughnessTexture!==void 0&&s.push(this.parser.assignTexture(t,"clearcoatRoughnessMap",n.clearcoatRoughnessTexture)),n.clearcoatNormalTexture!==void 0&&(s.push(this.parser.assignTexture(t,"clearcoatNormalMap",n.clearcoatNormalTexture)),n.clearcoatNormalTexture.scale!==void 0)){const r=n.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new p.Vector2(r,r)}return Promise.all(s)}}class yc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_DISPERSION}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(this.parser,e,this.name);return n===null||(t.dispersion=n.dispersion!==void 0?n.dispersion:0),Promise.resolve()}}class Ec{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];return n.iridescenceFactor!==void 0&&(t.iridescence=n.iridescenceFactor),n.iridescenceTexture!==void 0&&s.push(this.parser.assignTexture(t,"iridescenceMap",n.iridescenceTexture)),n.iridescenceIor!==void 0&&(t.iridescenceIOR=n.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),n.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=n.iridescenceThicknessMinimum),n.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=n.iridescenceThicknessMaximum),n.iridescenceThicknessTexture!==void 0&&s.push(this.parser.assignTexture(t,"iridescenceThicknessMap",n.iridescenceThicknessTexture)),Promise.all(s)}}class wc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_SHEEN}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];if(t.sheenColor=new p.Color(0,0,0),t.sheenRoughness=0,t.sheen=1,n.sheenColorFactor!==void 0){const r=n.sheenColorFactor;t.sheenColor.setRGB(r[0],r[1],r[2],p.LinearSRGBColorSpace)}return n.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=n.sheenRoughnessFactor),n.sheenColorTexture!==void 0&&s.push(this.parser.assignTexture(t,"sheenColorMap",n.sheenColorTexture,p.SRGBColorSpace)),n.sheenRoughnessTexture!==void 0&&s.push(this.parser.assignTexture(t,"sheenRoughnessMap",n.sheenRoughnessTexture)),Promise.all(s)}}class Tc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];return n.transmissionFactor!==void 0&&(t.transmission=n.transmissionFactor),n.transmissionTexture!==void 0&&s.push(this.parser.assignTexture(t,"transmissionMap",n.transmissionTexture)),Promise.all(s)}}class Sc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_VOLUME}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];t.thickness=n.thicknessFactor!==void 0?n.thicknessFactor:0,n.thicknessTexture!==void 0&&s.push(this.parser.assignTexture(t,"thicknessMap",n.thicknessTexture)),t.attenuationDistance=n.attenuationDistance||1/0;const r=n.attenuationColor||[1,1,1];return t.attenuationColor=new p.Color().setRGB(r[0],r[1],r[2],p.LinearSRGBColorSpace),Promise.all(s)}}class _c{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_IOR}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(this.parser,e,this.name);return n===null||(t.ior=n.ior!==void 0?n.ior:1.5,t.ior===0&&(t.ior=1e3)),Promise.resolve()}}class bc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_SPECULAR}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];t.specularIntensity=n.specularFactor!==void 0?n.specularFactor:1,n.specularTexture!==void 0&&s.push(this.parser.assignTexture(t,"specularIntensityMap",n.specularTexture));const r=n.specularColorFactor||[1,1,1];return t.specularColor=new p.Color().setRGB(r[0],r[1],r[2],p.LinearSRGBColorSpace),n.specularColorTexture!==void 0&&s.push(this.parser.assignTexture(t,"specularColorMap",n.specularColorTexture,p.SRGBColorSpace)),Promise.all(s)}}class xc{constructor(e){this.parser=e,this.name=le.EXT_MATERIALS_BUMP}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];return t.bumpScale=n.bumpFactor!==void 0?n.bumpFactor:1,n.bumpTexture!==void 0&&s.push(this.parser.assignTexture(t,"bumpMap",n.bumpTexture)),Promise.all(s)}}class Ac{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];return n.anisotropyStrength!==void 0&&(t.anisotropy=n.anisotropyStrength),n.anisotropyRotation!==void 0&&(t.anisotropyRotation=n.anisotropyRotation),n.anisotropyTexture!==void 0&&s.push(this.parser.assignTexture(t,"anisotropyMap",n.anisotropyTexture)),Promise.all(s)}}class Mc{constructor(e){this.parser=e,this.name=le.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,s=n.textures[e];if(!s.extensions||!s.extensions[this.name])return null;const r=s.extensions[this.name],o=t.options.ktx2Loader;if(!o){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,r.source,o)}}class Rc{constructor(e){this.parser=e,this.name=le.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,n=this.parser,s=n.json,r=s.textures[e];if(!r.extensions||!r.extensions[t])return null;const o=r.extensions[t],a=s.images[o.source];let c=n.textureLoader;if(a.uri){const d=n.options.manager.getHandler(a.uri);d!==null&&(c=d)}return n.loadTextureImage(e,o.source,c)}}class vc{constructor(e){this.parser=e,this.name=le.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,n=this.parser,s=n.json,r=s.textures[e];if(!r.extensions||!r.extensions[t])return null;const o=r.extensions[t],a=s.images[o.source];let c=n.textureLoader;if(a.uri){const d=n.options.manager.getHandler(a.uri);d!==null&&(c=d)}return n.loadTextureImage(e,o.source,c)}}class ar{constructor(e,t){this.name=t,this.parser=e}loadBufferView(e){const t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){const s=n.extensions[this.name],r=this.parser.getDependency("buffer",s.buffer),o=this.parser.options.meshoptDecoder;if(!o||!o.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return r.then(function(a){const c=s.byteOffset||0,d=s.byteLength||0,u=s.count,h=s.byteStride,f=new Uint8Array(a,c,d);return o.decodeGltfBufferAsync?o.decodeGltfBufferAsync(u,h,f,s.mode,s.filter).then(function(m){return m.buffer}):o.ready.then(function(){const m=new ArrayBuffer(u*h);return o.decodeGltfBuffer(new Uint8Array(m),u,h,f,s.mode,s.filter),m})})}else return null}}class Cc{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 d of s.primitives)if(d.mode!==st.TRIANGLES&&d.mode!==st.TRIANGLE_STRIP&&d.mode!==st.TRIANGLE_FAN&&d.mode!==void 0)return null;const o=n.extensions[this.name].attributes,a=[],c={};for(const d in o)a.push(this.parser.getDependency("accessor",o[d]).then(u=>(c[d]=u,c[d])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(d=>{const u=d.pop(),h=u.isGroup?u.children:[u],f=d[0].count,m=[];for(const w of h){const _=new p.Matrix4,E=new p.Vector3,b=new p.Quaternion,T=new p.Vector3(1,1,1),x=new p.InstancedMesh(w.geometry,w.material,f);for(let A=0;A<f;A++)c.TRANSLATION&&E.fromBufferAttribute(c.TRANSLATION,A),c.ROTATION&&b.fromBufferAttribute(c.ROTATION,A),c.SCALE&&T.fromBufferAttribute(c.SCALE,A),x.setMatrixAt(A,_.compose(E,b,T));for(const A in c)if(A==="_COLOR_0"){const R=c[A];x.instanceColor=new p.InstancedBufferAttribute(R.array,R.itemSize,R.normalized)}else A!=="TRANSLATION"&&A!=="ROTATION"&&A!=="SCALE"&&w.geometry.setAttribute(A,c[A]);p.Object3D.prototype.copy.call(x,w),this.parser.assignFinalMaterial(x),m.push(x)}return u.isGroup?(u.clear(),u.add(...m),u):m[0]}))}}const Fr="glTF",yn=12,cr={JSON:1313821514,BIN:5130562};class Ic{constructor(e){this.name=le.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,yn),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==Fr)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const s=this.header.length-yn,r=new DataView(e,yn);let o=0;for(;o<s;){const a=r.getUint32(o,!0);o+=4;const c=r.getUint32(o,!0);if(o+=4,c===cr.JSON){const d=new Uint8Array(e,yn+o,a);this.content=n.decode(d)}else if(c===cr.BIN){const d=yn+o;this.body=e.slice(d,d+a)}o+=a}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class Lc{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=le.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,s=this.dracoLoader,r=e.extensions[this.name].bufferView,o=e.extensions[this.name].attributes,a={},c={},d={};for(const u in o){const h=li[u]||u.toLowerCase();a[h]=o[u]}for(const u in e.attributes){const h=li[u]||u.toLowerCase();if(o[u]!==void 0){const f=n.accessors[e.attributes[u]],m=rn[f.componentType];d[h]=m.name,c[h]=f.normalized===!0}}return t.getDependency("bufferView",r).then(function(u){return new Promise(function(h,f){s.decodeDracoFile(u,function(m){for(const w in m.attributes){const _=m.attributes[w],E=c[w];E!==void 0&&(_.normalized=E)}h(m)},a,d,p.LinearSRGBColorSpace,f)})})}}class Pc{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 Oc{constructor(){this.name=le.KHR_MESH_QUANTIZATION}}class Br extends p.Interpolant{constructor(e,t,n,s){super(e,t,n,s)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,s=this.valueSize,r=e*s*3+s;for(let o=0;o!==s;o++)t[o]=n[r+o];return t}interpolate_(e,t,n,s){const r=this.resultBuffer,o=this.sampleValues,a=this.valueSize,c=a*2,d=a*3,u=s-t,h=(n-t)/u,f=h*h,m=f*h,w=e*d,_=w-d,E=-2*m+3*f,b=m-f,T=1-E,x=b-f+h;for(let A=0;A!==a;A++){const R=o[_+A+a],O=o[_+A+c]*u,L=o[w+A+a],C=o[w+A]*u;r[A]=T*R+x*O+E*L+b*C}return r}}const Dc=new p.Quaternion;class Nc extends Br{interpolate_(e,t,n,s){const r=super.interpolate_(e,t,n,s);return Dc.fromArray(r).normalize().toArray(r),r}}const st={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},rn={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},lr={9728:p.NearestFilter,9729:p.LinearFilter,9984:p.NearestMipmapNearestFilter,9985:p.LinearMipmapNearestFilter,9986:p.NearestMipmapLinearFilter,9987:p.LinearMipmapLinearFilter},hr={33071:p.ClampToEdgeWrapping,33648:p.MirroredRepeatWrapping,10497:p.RepeatWrapping},Bs={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},li={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},Rt={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},kc={CUBICSPLINE:void 0,LINEAR:p.InterpolateLinear,STEP:p.InterpolateDiscrete},zs={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function Fc(i){return i.DefaultMaterial===void 0&&(i.DefaultMaterial=new p.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:p.FrontSide})),i.DefaultMaterial}function Bt(i,e,t){for(const n in t.extensions)i[n]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[n]=t.extensions[n])}function yt(i,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(i.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function Bc(i,e,t){let n=!1,s=!1,r=!1;for(let d=0,u=e.length;d<u;d++){const h=e[d];if(h.POSITION!==void 0&&(n=!0),h.NORMAL!==void 0&&(s=!0),h.COLOR_0!==void 0&&(r=!0),n&&s&&r)break}if(!n&&!s&&!r)return Promise.resolve(i);const o=[],a=[],c=[];for(let d=0,u=e.length;d<u;d++){const h=e[d];if(n){const f=h.POSITION!==void 0?t.getDependency("accessor",h.POSITION):i.attributes.position;o.push(f)}if(s){const f=h.NORMAL!==void 0?t.getDependency("accessor",h.NORMAL):i.attributes.normal;a.push(f)}if(r){const f=h.COLOR_0!==void 0?t.getDependency("accessor",h.COLOR_0):i.attributes.color;c.push(f)}}return Promise.all([Promise.all(o),Promise.all(a),Promise.all(c)]).then(function(d){const u=d[0],h=d[1],f=d[2];return n&&(i.morphAttributes.position=u),s&&(i.morphAttributes.normal=h),r&&(i.morphAttributes.color=f),i.morphTargetsRelative=!0,i})}function zc(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 Uc(i){let e;const t=i.extensions&&i.extensions[le.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+Us(t.attributes):e=i.indices+":"+Us(i.attributes)+":"+i.mode,i.targets!==void 0)for(let n=0,s=i.targets.length;n<s;n++)e+=":"+Us(i.targets[n]);return e}function Us(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 hi(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 Hc(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 Vc=new p.Matrix4;class jc{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new dc,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,s=-1,r=!1,o=-1;if(typeof navigator<"u"&&typeof navigator.userAgent<"u"){const a=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(a)===!0;const c=a.match(/Version\/(\d+)/);s=n&&c?parseInt(c[1],10):-1,r=a.indexOf("Firefox")>-1,o=r?a.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&s<17||r&&o<98?this.textureLoader=new p.TextureLoader(this.options.manager):this.textureLoader=new p.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new p.FileLoader(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const n=this,s=this.json,r=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(o){return o._markDefs&&o._markDefs()}),Promise.all(this._invokeAll(function(o){return o.beforeRoot&&o.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(o){const a={scene:o[0][s.scene||0],scenes:o[0],animations:o[1],cameras:o[2],asset:s.asset,parser:n,userData:{}};return Bt(r,a,s),yt(a,s),Promise.all(n._invokeAll(function(c){return c.afterRoot&&c.afterRoot(a)})).then(function(){for(const c of a.scenes)c.updateMatrixWorld();e(a)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let s=0,r=t.length;s<r;s++){const o=t[s].joints;for(let a=0,c=o.length;a<c;a++)e[o[a]].isBone=!0}for(let s=0,r=e.length;s<r;s++){const o=e[s];o.mesh!==void 0&&(this._addNodeRef(this.meshCache,o.mesh),o.skin!==void 0&&(n[o.mesh].isSkinnedMesh=!0)),o.camera!==void 0&&this._addNodeRef(this.cameraCache,o.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;const s=n.clone(),r=(o,a)=>{const c=this.associations.get(o);c!=null&&this.associations.set(a,c);for(const[d,u]of o.children.entries())r(u,a.children[d])};return r(n,s),s.name+="_instance_"+e.uses[t]++,s}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const s=e(t[n]);if(s)return s}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let s=0;s<t.length;s++){const r=e(t[s]);r&&n.push(r)}return n}getDependency(e,t){const n=e+":"+t;let s=this.cache.get(n);if(!s){switch(e){case"scene":s=this.loadScene(t);break;case"node":s=this._invokeOne(function(r){return r.loadNode&&r.loadNode(t)});break;case"mesh":s=this._invokeOne(function(r){return r.loadMesh&&r.loadMesh(t)});break;case"accessor":s=this.loadAccessor(t);break;case"bufferView":s=this._invokeOne(function(r){return r.loadBufferView&&r.loadBufferView(t)});break;case"buffer":s=this.loadBuffer(t);break;case"material":s=this._invokeOne(function(r){return r.loadMaterial&&r.loadMaterial(t)});break;case"texture":s=this._invokeOne(function(r){return r.loadTexture&&r.loadTexture(t)});break;case"skin":s=this.loadSkin(t);break;case"animation":s=this._invokeOne(function(r){return r.loadAnimation&&r.loadAnimation(t)});break;case"camera":s=this.loadCamera(t);break;default:if(s=this._invokeOne(function(r){return r!=this&&r.getDependency&&r.getDependency(e,t)}),!s)throw new Error("Unknown type: "+e);break}this.cache.add(n,s)}return s}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,s=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(s.map(function(r,o){return n.getDependency(e,o)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[le.KHR_BINARY_GLTF].body);const s=this.options;return new Promise(function(r,o){n.load(p.LoaderUtils.resolveURL(t.uri,s.path),r,void 0,function(){o(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(n){const s=t.byteLength||0,r=t.byteOffset||0;return n.slice(r,r+s)})}loadAccessor(e){const t=this,n=this.json,s=this.json.accessors[e];if(s.bufferView===void 0&&s.sparse===void 0){const o=Bs[s.type],a=rn[s.componentType],c=s.normalized===!0,d=new a(s.count*o);return Promise.resolve(new p.BufferAttribute(d,o,c))}const r=[];return s.bufferView!==void 0?r.push(this.getDependency("bufferView",s.bufferView)):r.push(null),s.sparse!==void 0&&(r.push(this.getDependency("bufferView",s.sparse.indices.bufferView)),r.push(this.getDependency("bufferView",s.sparse.values.bufferView))),Promise.all(r).then(function(o){const a=o[0],c=Bs[s.type],d=rn[s.componentType],u=d.BYTES_PER_ELEMENT,h=u*c,f=s.byteOffset||0,m=s.bufferView!==void 0?n.bufferViews[s.bufferView].byteStride:void 0,w=s.normalized===!0;let _,E;if(m&&m!==h){const b=Math.floor(f/m),T="InterleavedBuffer:"+s.bufferView+":"+s.componentType+":"+b+":"+s.count;let x=t.cache.get(T);x||(_=new d(a,b*m,s.count*m/u),x=new p.InterleavedBuffer(_,m/u),t.cache.add(T,x)),E=new p.InterleavedBufferAttribute(x,c,f%m/u,w)}else a===null?_=new d(s.count*c):_=new d(a,f,s.count*c),E=new p.BufferAttribute(_,c,w);if(s.sparse!==void 0){const b=Bs.SCALAR,T=rn[s.sparse.indices.componentType],x=s.sparse.indices.byteOffset||0,A=s.sparse.values.byteOffset||0,R=new T(o[1],x,s.sparse.count*b),O=new d(o[2],A,s.sparse.count*c);a!==null&&(E=new p.BufferAttribute(E.array.slice(),E.itemSize,E.normalized)),E.normalized=!1;for(let L=0,C=R.length;L<C;L++){const N=R[L];if(E.setX(N,O[L*c]),c>=2&&E.setY(N,O[L*c+1]),c>=3&&E.setZ(N,O[L*c+2]),c>=4&&E.setW(N,O[L*c+3]),c>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}E.normalized=w}return E})}loadTexture(e){const t=this.json,n=this.options,r=t.textures[e].source,o=t.images[r];let a=this.textureLoader;if(o.uri){const c=n.manager.getHandler(o.uri);c!==null&&(a=c)}return this.loadTextureImage(e,r,a)}loadTextureImage(e,t,n){const s=this,r=this.json,o=r.textures[e],a=r.images[t],c=(a.uri||a.bufferView)+":"+o.sampler;if(this.textureCache[c])return this.textureCache[c];const d=this.loadImageSource(t,n).then(function(u){u.flipY=!1,u.name=o.name||a.name||"",u.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(u.name=a.uri);const f=(r.samplers||{})[o.sampler]||{};return u.magFilter=lr[f.magFilter]||p.LinearFilter,u.minFilter=lr[f.minFilter]||p.LinearMipmapLinearFilter,u.wrapS=hr[f.wrapS]||p.RepeatWrapping,u.wrapT=hr[f.wrapT]||p.RepeatWrapping,u.generateMipmaps=!u.isCompressedTexture&&u.minFilter!==p.NearestFilter&&u.minFilter!==p.LinearFilter,s.associations.set(u,{textures:e}),u}).catch(function(){return null});return this.textureCache[c]=d,d}loadImageSource(e,t){const n=this,s=this.json,r=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(h=>h.clone());const o=s.images[e],a=self.URL||self.webkitURL;let c=o.uri||"",d=!1;if(o.bufferView!==void 0)c=n.getDependency("bufferView",o.bufferView).then(function(h){d=!0;const f=new Blob([h],{type:o.mimeType});return c=a.createObjectURL(f),c});else if(o.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const u=Promise.resolve(c).then(function(h){return new Promise(function(f,m){let w=f;t.isImageBitmapLoader===!0&&(w=function(_){const E=new p.Texture(_);E.needsUpdate=!0,f(E)}),t.load(p.LoaderUtils.resolveURL(h,r.path),w,void 0,m)})}).then(function(h){return d===!0&&a.revokeObjectURL(c),yt(h,o),h.userData.mimeType=o.mimeType||Hc(o.uri),h}).catch(function(h){throw console.error("THREE.GLTFLoader: Couldn't load texture",c),h});return this.sourceCache[e]=u,u}assignTexture(e,t,n,s){const r=this;return this.getDependency("texture",n.index).then(function(o){if(!o)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(o=o.clone(),o.channel=n.texCoord),r.extensions[le.KHR_TEXTURE_TRANSFORM]){const a=n.extensions!==void 0?n.extensions[le.KHR_TEXTURE_TRANSFORM]:void 0;if(a){const c=r.associations.get(o);o=r.extensions[le.KHR_TEXTURE_TRANSFORM].extendTexture(o,a),r.associations.set(o,c)}}return s!==void 0&&(o.colorSpace=s),e[t]=o,o})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const s=t.attributes.tangent===void 0,r=t.attributes.color!==void 0,o=t.attributes.normal===void 0;if(e.isPoints){const a="PointsMaterial:"+n.uuid;let c=this.cache.get(a);c||(c=new p.PointsMaterial,p.Material.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,c.sizeAttenuation=!1,this.cache.add(a,c)),n=c}else if(e.isLine){const a="LineBasicMaterial:"+n.uuid;let c=this.cache.get(a);c||(c=new p.LineBasicMaterial,p.Material.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,this.cache.add(a,c)),n=c}if(s||r||o){let a="ClonedMaterial:"+n.uuid+":";s&&(a+="derivative-tangents:"),r&&(a+="vertex-colors:"),o&&(a+="flat-shading:");let c=this.cache.get(a);c||(c=n.clone(),r&&(c.vertexColors=!0),o&&(c.flatShading=!0),s&&(c.normalScale&&(c.normalScale.y*=-1),c.clearcoatNormalScale&&(c.clearcoatNormalScale.y*=-1)),this.cache.add(a,c),this.associations.set(c,this.associations.get(n))),n=c}e.material=n}getMaterialType(){return p.MeshStandardMaterial}loadMaterial(e){const t=this,n=this.json,s=this.extensions,r=n.materials[e];let o;const a={},c=r.extensions||{},d=[];if(c[le.KHR_MATERIALS_UNLIT]){const h=s[le.KHR_MATERIALS_UNLIT];o=h.getMaterialType(),d.push(h.extendParams(a,r,t))}else{const h=r.pbrMetallicRoughness||{};if(a.color=new p.Color(1,1,1),a.opacity=1,Array.isArray(h.baseColorFactor)){const f=h.baseColorFactor;a.color.setRGB(f[0],f[1],f[2],p.LinearSRGBColorSpace),a.opacity=f[3]}h.baseColorTexture!==void 0&&d.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&&(d.push(t.assignTexture(a,"metalnessMap",h.metallicRoughnessTexture)),d.push(t.assignTexture(a,"roughnessMap",h.metallicRoughnessTexture))),o=this._invokeOne(function(f){return f.getMaterialType&&f.getMaterialType(e)}),d.push(Promise.all(this._invokeAll(function(f){return f.extendMaterialParams&&f.extendMaterialParams(e,a)})))}r.doubleSided===!0&&(a.side=p.DoubleSide);const u=r.alphaMode||zs.OPAQUE;if(u===zs.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,u===zs.MASK&&(a.alphaTest=r.alphaCutoff!==void 0?r.alphaCutoff:.5)),r.normalTexture!==void 0&&o!==p.MeshBasicMaterial&&(d.push(t.assignTexture(a,"normalMap",r.normalTexture)),a.normalScale=new p.Vector2(1,1),r.normalTexture.scale!==void 0)){const h=r.normalTexture.scale;a.normalScale.set(h,h)}if(r.occlusionTexture!==void 0&&o!==p.MeshBasicMaterial&&(d.push(t.assignTexture(a,"aoMap",r.occlusionTexture)),r.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=r.occlusionTexture.strength)),r.emissiveFactor!==void 0&&o!==p.MeshBasicMaterial){const h=r.emissiveFactor;a.emissive=new p.Color().setRGB(h[0],h[1],h[2],p.LinearSRGBColorSpace)}return r.emissiveTexture!==void 0&&o!==p.MeshBasicMaterial&&d.push(t.assignTexture(a,"emissiveMap",r.emissiveTexture,p.SRGBColorSpace)),Promise.all(d).then(function(){const h=new o(a);return r.name&&(h.name=r.name),yt(h,r),t.associations.set(h,{materials:e}),r.extensions&&Bt(s,h,r),h})}createUniqueName(e){const t=p.PropertyBinding.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,n=this.extensions,s=this.primitiveCache;function r(a){return n[le.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,t).then(function(c){return ur(c,a,t)})}const o=[];for(let a=0,c=e.length;a<c;a++){const d=e[a],u=Uc(d),h=s[u];if(h)o.push(h.promise);else{let f;d.extensions&&d.extensions[le.KHR_DRACO_MESH_COMPRESSION]?f=r(d):f=ur(new p.BufferGeometry,d,t),s[u]={primitive:d,promise:f},o.push(f)}}return Promise.all(o)}loadMesh(e){const t=this,n=this.json,s=this.extensions,r=n.meshes[e],o=r.primitives,a=[];for(let c=0,d=o.length;c<d;c++){const u=o[c].material===void 0?Fc(this.cache):this.getDependency("material",o[c].material);a.push(u)}return a.push(t.loadGeometries(o)),Promise.all(a).then(function(c){const d=c.slice(0,c.length-1),u=c[c.length-1],h=[];for(let m=0,w=u.length;m<w;m++){const _=u[m],E=o[m];let b;const T=d[m];if(E.mode===st.TRIANGLES||E.mode===st.TRIANGLE_STRIP||E.mode===st.TRIANGLE_FAN||E.mode===void 0)b=r.isSkinnedMesh===!0?new p.SkinnedMesh(_,T):new p.Mesh(_,T),b.isSkinnedMesh===!0&&b.normalizeSkinWeights(),E.mode===st.TRIANGLE_STRIP?b.geometry=or(b.geometry,p.TriangleStripDrawMode):E.mode===st.TRIANGLE_FAN&&(b.geometry=or(b.geometry,p.TriangleFanDrawMode));else if(E.mode===st.LINES)b=new p.LineSegments(_,T);else if(E.mode===st.LINE_STRIP)b=new p.Line(_,T);else if(E.mode===st.LINE_LOOP)b=new p.LineLoop(_,T);else if(E.mode===st.POINTS)b=new p.Points(_,T);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+E.mode);Object.keys(b.geometry.morphAttributes).length>0&&zc(b,r),b.name=t.createUniqueName(r.name||"mesh_"+e),yt(b,r),E.extensions&&Bt(s,b,E),t.assignFinalMaterial(b),h.push(b)}for(let m=0,w=h.length;m<w;m++)t.associations.set(h[m],{meshes:e,primitives:m});if(h.length===1)return r.extensions&&Bt(s,h[0],r),h[0];const f=new p.Group;r.extensions&&Bt(s,f,r),t.associations.set(f,{meshes:e});for(let m=0,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,r=t.joints.length;s<r;s++)n.push(this._loadNodeShallow(t.joints[s]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(s){const r=s.pop(),o=s,a=[],c=[];for(let d=0,u=o.length;d<u;d++){const h=o[d];if(h){a.push(h);const f=new p.Matrix4;r!==null&&f.fromArray(r.array,d*16),c.push(f)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[d])}return new p.Skeleton(a,c)})}loadAnimation(e){const t=this.json,n=this,s=t.animations[e],r=s.name?s.name:"animation_"+e,o=[],a=[],c=[],d=[],u=[];for(let h=0,f=s.channels.length;h<f;h++){const m=s.channels[h],w=s.samplers[m.sampler],_=m.target,E=_.node,b=s.parameters!==void 0?s.parameters[w.input]:w.input,T=s.parameters!==void 0?s.parameters[w.output]:w.output;_.node!==void 0&&(o.push(this.getDependency("node",E)),a.push(this.getDependency("accessor",b)),c.push(this.getDependency("accessor",T)),d.push(w),u.push(_))}return Promise.all([Promise.all(o),Promise.all(a),Promise.all(c),Promise.all(d),Promise.all(u)]).then(function(h){const f=h[0],m=h[1],w=h[2],_=h[3],E=h[4],b=[];for(let x=0,A=f.length;x<A;x++){const R=f[x],O=m[x],L=w[x],C=_[x],N=E[x];if(R===void 0)continue;R.updateMatrix&&R.updateMatrix();const I=n._createAnimationTracks(R,O,L,C,N);if(I)for(let k=0;k<I.length;k++)b.push(I[k])}const T=new p.AnimationClip(r,void 0,b);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(r){const o=n._getNodeRef(n.meshCache,s.mesh,r);return s.weights!==void 0&&o.traverse(function(a){if(a.isMesh)for(let c=0,d=s.weights.length;c<d;c++)a.morphTargetInfluences[c]=s.weights[c]}),o})}loadNode(e){const t=this.json,n=this,s=t.nodes[e],r=n._loadNodeShallow(e),o=[],a=s.children||[];for(let d=0,u=a.length;d<u;d++)o.push(n.getDependency("node",a[d]));const c=s.skin===void 0?Promise.resolve(null):n.getDependency("skin",s.skin);return Promise.all([r,Promise.all(o),c]).then(function(d){const u=d[0],h=d[1],f=d[2];f!==null&&u.traverse(function(m){m.isSkinnedMesh&&m.bind(f,Vc)});for(let m=0,w=h.length;m<w;m++)u.add(h[m]);if(u.userData.pivot!==void 0&&h.length>0){const m=u.userData.pivot,w=h[0];u.pivot=new p.Vector3().fromArray(m),u.position.x-=m[0],u.position.y-=m[1],u.position.z-=m[2],w.position.set(0,0,0),delete u.userData.pivot}return u})}_loadNodeShallow(e){const t=this.json,n=this.extensions,s=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const r=t.nodes[e],o=r.name?s.createUniqueName(r.name):"",a=[],c=s._invokeOne(function(d){return d.createNodeMesh&&d.createNodeMesh(e)});return c&&a.push(c),r.camera!==void 0&&a.push(s.getDependency("camera",r.camera).then(function(d){return s._getNodeRef(s.cameraCache,r.camera,d)})),s._invokeAll(function(d){return d.createNodeAttachment&&d.createNodeAttachment(e)}).forEach(function(d){a.push(d)}),this.nodeCache[e]=Promise.all(a).then(function(d){let u;if(r.isBone===!0?u=new p.Bone:d.length>1?u=new p.Group:d.length===1?u=d[0]:u=new p.Object3D,u!==d[0])for(let h=0,f=d.length;h<f;h++)u.add(d[h]);if(r.name&&(u.userData.name=r.name,u.name=o),yt(u,r),r.extensions&&Bt(n,u,r),r.matrix!==void 0){const h=new p.Matrix4;h.fromArray(r.matrix),u.applyMatrix4(h)}else r.translation!==void 0&&u.position.fromArray(r.translation),r.rotation!==void 0&&u.quaternion.fromArray(r.rotation),r.scale!==void 0&&u.scale.fromArray(r.scale);if(!s.associations.has(u))s.associations.set(u,{});else if(r.mesh!==void 0&&s.meshCache.refs[r.mesh]>1){const h=s.associations.get(u);s.associations.set(u,{...h})}return s.associations.get(u).nodes=e,u}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],s=this,r=new p.Group;n.name&&(r.name=s.createUniqueName(n.name)),yt(r,n),n.extensions&&Bt(t,r,n);const o=n.nodes||[],a=[];for(let c=0,d=o.length;c<d;c++)a.push(s.getDependency("node",o[c]));return Promise.all(a).then(function(c){for(let u=0,h=c.length;u<h;u++){const f=c[u];f.parent!==null?r.add(hc(f)):r.add(f)}const d=u=>{const h=new Map;for(const[f,m]of s.associations)(f instanceof p.Material||f instanceof p.Texture)&&h.set(f,m);return u.traverse(f=>{const m=s.associations.get(f);m!=null&&h.set(f,m)}),h};return s.associations=d(r),r})}_createAnimationTracks(e,t,n,s,r){const o=[],a=e.name?e.name:e.uuid,c=[];function d(m){m.morphTargetInfluences&&c.push(m.name?m.name:m.uuid)}Rt[r.path]===Rt.weights?(d(e),e.isGroup&&e.children.forEach(d)):c.push(a);let u;switch(Rt[r.path]){case Rt.weights:u=p.NumberKeyframeTrack;break;case Rt.rotation:u=p.QuaternionKeyframeTrack;break;case Rt.translation:case Rt.scale:u=p.VectorKeyframeTrack;break;default:switch(n.itemSize){case 1:u=p.NumberKeyframeTrack;break;case 2:case 3:default:u=p.VectorKeyframeTrack;break}break}const h=s.interpolation!==void 0?kc[s.interpolation]:p.InterpolateLinear,f=this._getArrayFromAccessor(n);for(let m=0,w=c.length;m<w;m++){const _=new u(c[m]+"."+Rt[r.path],t.array,f,h);s.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(_),o.push(_)}return o}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const n=hi(t.constructor),s=new Float32Array(t.length);for(let r=0,o=t.length;r<o;r++)s[r]=t[r]*n;t=s}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){const s=this instanceof p.QuaternionKeyframeTrack?Nc:Br;return new s(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function Gc(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,d=a.max;if(c!==void 0&&d!==void 0){if(s.set(new p.Vector3(c[0],c[1],c[2]),new p.Vector3(d[0],d[1],d[2])),a.normalized){const u=hi(rn[a.componentType]);s.min.multiplyScalar(u),s.max.multiplyScalar(u)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const r=e.targets;if(r!==void 0){const a=new p.Vector3,c=new p.Vector3;for(let d=0,u=r.length;d<u;d++){const h=r[d];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 _=hi(rn[f.componentType]);c.multiplyScalar(_)}a.max(c)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}s.expandByVector(a)}i.boundingBox=s;const o=new p.Sphere;s.getCenter(o.center),o.radius=s.min.distanceTo(s.max)/2,i.boundingSphere=o}function ur(i,e,t){const n=e.attributes,s=[];function r(o,a){return t.getDependency("accessor",o).then(function(c){i.setAttribute(a,c)})}for(const o in n){const a=li[o]||o.toLowerCase();a in i.attributes||s.push(r(n[o],a))}if(e.indices!==void 0&&!i.index){const o=t.getDependency("accessor",e.indices).then(function(a){i.setIndex(a)});s.push(o)}return p.ColorManagement.workingColorSpace!==p.LinearSRGBColorSpace&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${p.ColorManagement.workingColorSpace}" not supported.`),yt(i,e),Gc(i,e,t),Promise.all(s).then(function(){return e.targets!==void 0?Bc(i,e.targets,t):i})}const Wc=S.REVISION.replace(/\D/g,""),zr=`https://cdn.jsdelivr.net/npm/three@0.${Wc}/examples/jsm/libs`,Zc=`${zr}/draco/`,Kc=`${zr}/basis/`;class Xc{constructor(e={}){this.loadingManager=new S.LoadingManager,this.loader=new uc(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??Zc),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??Kc),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){try{return await this.ensureDecoders(),new Promise(t=>{this.loader.load(e,n=>{var r;(this.config.bvh??!0)&&Dr(n.scene),n.scene.animations=n.animations;const s={scene:new Oe(n.scene),animations:this.convertAnimations(n.animations),cameras:(r=n.cameras)==null?void 0:r.map(o=>{const a=o instanceof S.PerspectiveCamera,c=o instanceof S.OrthographicCamera;return{name:o.name,type:o.type,fov:a?o.fov:void 0,aspect:a?o.aspect:void 0,near:a||c?o.near:.1,far:a||c?o.far:1e3}}),userData:n.userData};t(z.ok(s))},n=>{n.total>0},n=>{t(z.err(new K("Failed to load GLTF model",q.MODEL_LOAD_FAILED,{url:e,originalError:n})))})})}catch(t){return z.err(new K("Failed to initiate model loading",q.MODEL_LOAD_FAILED,{url:e,originalError:t}))}}supports(e){var n;const t=(n=e.split(".").pop())==null?void 0:n.toLowerCase();return t==="gltf"||t==="glb"}dispose(){var e,t;(e=this.dracoLoader)==null||e.dispose(),(t=this.ktx2Loader)==null||t.dispose()}convertAnimations(e){return e.map(t=>({name:t.name,duration:t.duration,tracks:t.tracks.map(n=>({name:n.name,type:this.getTrackType(n),times:n.times,values:n.values}))}))}getTrackType(e){return e instanceof S.VectorKeyframeTrack?"vector":e instanceof S.QuaternionKeyframeTrack?"quaternion":e instanceof S.NumberKeyframeTrack?"number":e instanceof S.BooleanKeyframeTrack?"boolean":"number"}}class dr{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 Xc(t);default:throw new K(`Unsupported file format: ${n}`,q.UNSUPPORTED_FORMAT,{url:e,extension:n})}}}const fr={type:"change"},_i={type:"start"},Ur={type:"end"},rs=new p.Ray,pr=new p.Plane,Yc=Math.cos(70*p.MathUtils.DEG2RAD),Le=new p.Vector3,$e=2*Math.PI,we={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},Hs=1e-6;class Hr extends p.Controls{constructor(e,t=null){super(e,t),this.state=we.NONE,this.target=new p.Vector3,this.cursor=new p.Vector3,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:p.MOUSE.ROTATE,MIDDLE:p.MOUSE.DOLLY,RIGHT:p.MOUSE.PAN},this.touches={ONE:p.TOUCH.ROTATE,TWO:p.TOUCH.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new p.Vector3,this._lastQuaternion=new p.Quaternion,this._lastTargetPosition=new p.Vector3,this._quat=new p.Quaternion().setFromUnitVectors(e.up,new p.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new p.Spherical,this._sphericalDelta=new p.Spherical,this._scale=1,this._panOffset=new p.Vector3,this._rotateStart=new p.Vector2,this._rotateEnd=new p.Vector2,this._rotateDelta=new p.Vector2,this._panStart=new p.Vector2,this._panEnd=new p.Vector2,this._panDelta=new p.Vector2,this._dollyStart=new p.Vector2,this._dollyEnd=new p.Vector2,this._dollyDelta=new p.Vector2,this._dollyDirection=new p.Vector3,this._mouse=new p.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=$c.bind(this),this._onPointerDown=qc.bind(this),this._onPointerUp=Qc.bind(this),this._onContextMenu=rl.bind(this),this._onMouseWheel=tl.bind(this),this._onKeyDown=nl.bind(this),this._onTouchStart=sl.bind(this),this._onTouchMove=il.bind(this),this._onMouseDown=Jc.bind(this),this._onMouseMove=el.bind(this),this._interceptControlDown=ol.bind(this),this._interceptControlUp=al.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(fr),this.update(),this.state=we.NONE}pan(e,t){this._pan(e,t),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(e=null){const t=this.object.position;Le.copy(t).sub(this.target),Le.applyQuaternion(this._quat),this._spherical.setFromVector3(Le),this.autoRotate&&this.state===we.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let n=this.minAzimuthAngle,s=this.maxAzimuthAngle;isFinite(n)&&isFinite(s)&&(n<-Math.PI?n+=$e:n>Math.PI&&(n-=$e),s<-Math.PI?s+=$e:s>Math.PI&&(s-=$e),n<=s?this._spherical.theta=Math.max(n,Math.min(s,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+s)/2?Math.max(n,this._spherical.theta):Math.min(s,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let r=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const o=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),r=o!=this._spherical.radius}if(Le.setFromSpherical(this._spherical),Le.applyQuaternion(this._quatInverse),t.copy(this.target).add(Le),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let o=null;if(this.object.isPerspectiveCamera){const a=Le.length();o=this._clampDistance(a*this._scale);const c=a-o;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),r=!!c}else if(this.object.isOrthographicCamera){const a=new p.Vector3(this._mouse.x,this._mouse.y,0);a.unproject(this.object);const c=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=c!==this.object.zoom;const d=new p.Vector3(this._mouse.x,this._mouse.y,0);d.unproject(this.object),this.object.position.sub(d).add(a),this.object.updateMatrixWorld(),o=Le.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;o!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(o).add(this.object.position):(rs.origin.copy(this.object.position),rs.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(rs.direction))<Yc?this.object.lookAt(this.target):(pr.setFromNormalAndCoplanarPoint(this.object.up,this.target),rs.intersectPlane(pr,this.target))))}else if(this.object.isOrthographicCamera){const o=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),o!==this.object.zoom&&(this.object.updateProjectionMatrix(),r=!0)}return this._scale=1,this._performCursorZoom=!1,r||this._lastPosition.distanceToSquared(this.object.position)>Hs||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Hs||this._lastTargetPosition.distanceToSquared(this.target)>Hs?(this.dispatchEvent(fr),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?$e/60*this.autoRotateSpeed*e:$e/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){Le.setFromMatrixColumn(t,0),Le.multiplyScalar(-e),this._panOffset.add(Le)}_panUp(e,t){this.screenSpacePanning===!0?Le.setFromMatrixColumn(t,1):(Le.setFromMatrixColumn(t,0),Le.crossVectors(this.object.up,Le)),Le.multiplyScalar(e),this._panOffset.add(Le)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;Le.copy(s).sub(this.target);let r=Le.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/n.clientHeight,this.object.matrix),this._panUp(2*t*r/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const n=this.domElement.getBoundingClientRect(),s=e-n.left,r=t-n.top,o=n.width,a=n.height;this._mouse.x=s/o*2-1,this._mouse.y=-(r/a)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft($e*this._rotateDelta.x/t.clientHeight),this._rotateUp($e*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp($e*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-$e*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft($e*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-$e*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._rotateStart.set(n,s)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panStart.set(n,s)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,r=Math.sqrt(n*n+s*s);this._dollyStart.set(0,r)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),s=.5*(e.pageX+n.x),r=.5*(e.pageY+n.y);this._rotateEnd.set(s,r)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft($e*this._rotateDelta.x/t.clientHeight),this._rotateUp($e*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panEnd.set(n,s)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,r=Math.sqrt(n*n+s*s);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const o=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(o,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new p.Vector2,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(n.deltaY*=10),n}}function qc(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 $c(i){this.enabled!==!1&&(i.pointerType==="touch"?this._onTouchMove(i):this._onMouseMove(i))}function Qc(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(Ur),this.state=we.NONE,this._cursorStyle==="grab"&&(this.domElement.style.cursor="grab");break;case 1:const e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function Jc(i){let e;switch(i.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case p.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(i),this.state=we.DOLLY;break;case p.MOUSE.ROTATE:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=we.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=we.ROTATE}break;case p.MOUSE.PAN:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=we.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=we.PAN}break;default:this.state=we.NONE}this.state!==we.NONE&&this.dispatchEvent(_i)}function el(i){switch(this.state){case we.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(i);break;case we.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(i);break;case we.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(i);break}}function tl(i){this.enabled===!1||this.enableZoom===!1||this.state!==we.NONE||(i.preventDefault(),this.dispatchEvent(_i),this._handleMouseWheel(this._customWheelEvent(i)),this.dispatchEvent(Ur))}function nl(i){this.enabled!==!1&&this._handleKeyDown(i)}function sl(i){switch(this._trackPointer(i),this._pointers.length){case 1:switch(this.touches.ONE){case p.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(i),this.state=we.TOUCH_ROTATE;break;case p.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(i),this.state=we.TOUCH_PAN;break;default:this.state=we.NONE}break;case 2:switch(this.touches.TWO){case p.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(i),this.state=we.TOUCH_DOLLY_PAN;break;case p.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(i),this.state=we.TOUCH_DOLLY_ROTATE;break;default:this.state=we.NONE}break;default:this.state=we.NONE}this.state!==we.NONE&&this.dispatchEvent(_i)}function il(i){switch(this._trackPointer(i),this.state){case we.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(i),this.update();break;case we.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(i),this.update();break;case we.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(i),this.update();break;case we.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(i),this.update();break;default:this.state=we.NONE}}function rl(i){this.enabled!==!1&&i.preventDefault()}function ol(i){i.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function al(i){i.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}const Vs=new p.Plane,os=new p.Raycaster,Qt=new p.Vector2,js=new p.Vector3;class cl extends Hr{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;Vs.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(Vs,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(Vs,js)&&(js.sub(this._panWorldStart),this._panOffset.copy(js).negate(),this.update())}}class Vr{constructor(e){this.controls=e,this.targetAdapter=Pt.fromThreeVector(e.target)}get enabled(){return this.controls.enabled}set enabled(e){this.controls.enabled=e}get enableDamping(){return this.controls.enableDamping}set enableDamping(e){this.controls.enableDamping=e}get dampingFactor(){return this.controls.dampingFactor}set dampingFactor(e){this.controls.dampingFactor=e}get enableZoom(){return this.controls.enableZoom}set enableZoom(e){this.controls.enableZoom=e}get enableRotate(){return this.controls.enableRotate}set enableRotate(e){this.controls.enableRotate=e}get enablePan(){return this.controls.enablePan}set enablePan(e){this.controls.enablePan=e}get zoomSpeed(){return this.controls.zoomSpeed}set zoomSpeed(e){this.controls.zoomSpeed=e}get minDistance(){return this.controls.minDistance}set minDistance(e){this.controls.minDistance=e}get maxDistance(){return this.controls.maxDistance}set maxDistance(e){this.controls.maxDistance=e}get rotateSpeed(){return this.controls.rotateSpeed}set rotateSpeed(e){this.controls.rotateSpeed=e}get minPolarAngle(){return this.controls.minPolarAngle}set minPolarAngle(e){this.controls.minPolarAngle=e}get maxPolarAngle(){return this.controls.maxPolarAngle}set maxPolarAngle(e){this.controls.maxPolarAngle=e}get minAzimuthAngle(){return this.controls.minAzimuthAngle}set minAzimuthAngle(e){this.controls.minAzimuthAngle=e}get maxAzimuthAngle(){return this.controls.maxAzimuthAngle}set maxAzimuthAngle(e){this.controls.maxAzimuthAngle=e}get panSpeed(){return this.controls.panSpeed}set panSpeed(e){this.controls.panSpeed=e}get screenSpacePanning(){return this.controls.screenSpacePanning}set screenSpacePanning(e){this.controls.screenSpacePanning=e}get target(){return this.targetAdapter}update(){return this.controls.update()}reset(){this.controls.reset()}dispose(){this.controls.dispose()}connect(e){}disconnect(){this.controls.dispose()}get autoRotate(){return this.controls.autoRotate}set autoRotate(e){this.controls.autoRotate=e}get autoRotateSpeed(){return this.controls.autoRotateSpeed}set autoRotateSpeed(e){this.controls.autoRotateSpeed=e}getThreeControls(){return this.controls}}class ll extends Vr{constructor(e,t){super(new Hr(e,t))}get type(){return"orbit"}}class hl extends Vr{constructor(e,t){const n=new cl(e,t);super(n),n.screenSpacePanning=!0}get type(){return"map"}get screenSpacePanning(){return!0}set screenSpacePanning(e){}}const Rn=(i,e)=>{if(i&&typeof i=="object"){const t=i[e];if(typeof t=="function")return t.call(i)}return null};function zt(i){return Rn(i,"getThreeObject")??(i instanceof S.Object3D?i:null)}function vn(i){return Rn(i,"getThreeCamera")??(i instanceof S.Camera?i:null)}function ui(i){return Rn(i,"getThreeScene")??(i instanceof S.Scene?i:null)}function jr(i){return Rn(i,"getThreeRenderer")??(i instanceof S.WebGLRenderer?i:null)}function bi(i){return Rn(i,"getThreeControls")}const di="contact-shadow-baked",xn="contact-shadow-live",mr=Math.PI*(3-Math.sqrt(5)),Ke=class Ke{constructor(e){this.passes=(e==null?void 0:e.passes)??96}bake(e){const{renderer:t,scene:n,object:s,light:r}=e,o=this.measureBakeRegion(s);if(!o)return;const a=n.getObjectByName(xn);(a==null?void 0:a.geometry)instanceof S.CircleGeometry&&(o.halfExtent=Math.min(o.halfExtent,a.geometry.parameters.radius));const c=new S.WebGLRenderTarget(Ke.ACCUMULATION_TEXTURE_SIZE,Ke.ACCUMULATION_TEXTURE_SIZE,{type:t.capabilities.isWebGL2?S.HalfFloatType:S.UnsignedByteType,depthBuffer:!1,stencilBuffer:!1}),d=new S.CircleGeometry(o.halfExtent,64);this.accumulateShadowPasses(t,s,r,o,c,d),this.installBakedMesh(n,o,c,d)}measureBakeRegion(e){const t=new S.Box3().setFromObject(e);if(t.isEmpty()||!Number.isFinite(t.min.x)||!Number.isFinite(t.max.x))return null;const n=t.getSize(new S.Vector3),s=t.getCenter(new S.Vector3),o=Math.max(Math.max(n.x,n.z)*1.6+n.y,.05);return{center:s,halfExtent:o,objectHeight:n.y}}accumulateShadowPasses(e,t,n,s,r,o){const a=new S.Scene,c=t.parent;a.add(t);const d=this.disableColorWrite(t),u=this.createBakeLight(n);a.add(u),a.add(u.target);const h=new S.ShadowMaterial({transparent:!0,opacity:1/this.passes,depthWrite:!1});h.blending=S.CustomBlending,h.blendEquation=S.AddEquation,h.blendSrc=S.OneFactor,h.blendDst=S.OneFactor;const f=new S.Mesh(o,h);f.rotation.x=-Math.PI/2,f.position.set(s.center.x,0,s.center.z),f.receiveShadow=!0,a.add(f);const m=this.createBakeCamera(s);a.add(m);const w=e.getRenderTarget(),_=e.autoClear,E=e.getClearColor(new S.Color),b=e.getClearAlpha(),T=e.shadowMap.autoUpdate;try{e.shadowMap.autoUpdate=!0,e.setRenderTarget(r),e.setClearColor(0,0),e.clear(!0,!1,!1),e.autoClear=!1;for(const x of this.sampleLightPositions(n))u.position.copy(x),e.render(a,m)}finally{e.autoClear=_,e.setClearColor(E,b),e.setRenderTarget(w),e.shadowMap.autoUpdate=T,this.restoreColorWrite(d),c?c.add(t):a.remove(t),u.dispose(),h.dispose()}}createBakeLight(e){const t=new S.DirectionalLight(16777215,1);t.castShadow=!0,t.shadow.mapSize.set(Ke.BAKE_SHADOW_MAP_SIZE,Ke.BAKE_SHADOW_MAP_SIZE),t.shadow.bias=e.shadow.bias,t.shadow.normalBias=e.shadow.normalBias,t.shadow.radius=4;const n=e.shadow.camera,s=t.shadow.camera;return s.left=n.left,s.right=n.right,s.top=n.top,s.bottom=n.bottom,s.near=n.near,s.far=n.far,s.updateProjectionMatrix(),t}createBakeCamera(e){const t=new S.OrthographicCamera(-e.halfExtent,e.halfExtent,e.halfExtent,-e.halfExtent,.1,Math.max(e.objectHeight,1)*4);return t.position.set(e.center.x,Math.max(e.objectHeight,1)*2,e.center.z),t.up.set(0,0,-1),t.lookAt(e.center.x,0,e.center.z),t.updateProjectionMatrix(),t.updateMatrixWorld(!0),t}sampleLightPositions(e){const t=e.position.clone(),n=e.target.parent?e.target.getWorldPosition(new S.Vector3):e.target.position.clone(),s=n.clone().sub(t),r=s.length(),o=s.normalize(),a=new S.Vector3().crossVectors(o,new S.Vector3(0,1,0));a.lengthSq()<1e-6&&a.set(1,0,0),a.normalize();const c=new S.Vector3().crossVectors(o,a),d=Math.round(this.passes*Ke.AMBIENT_RATIO),u=this.passes-d,h=S.MathUtils.degToRad(Ke.LIGHT_APERTURE_DEGREES),f=Math.tan(h/2)*r,m=[];for(let E=0;E<u;E++){const b=f*Math.sqrt((E+.5)/u),T=E*mr;m.push(t.clone().addScaledVector(a,b*Math.cos(T)).addScaledVector(c,b*Math.sin(T)))}const w=Math.sin(S.MathUtils.degToRad(Ke.AMBIENT_MIN_ELEVATION_DEGREES)),_=.98;for(let E=0;E<d;E++){const b=Math.sqrt((E+.5)/d),T=w+(_-w)*b,x=Math.sqrt(1-T*T),A=E*mr;m.push(new S.Vector3(x*Math.cos(A),T,x*Math.sin(A)).multiplyScalar(r).add(n))}return m}installBakedMesh(e,t,n,s){const r=e.getObjectByName(di);r&&(e.remove(r),xs(r));const o=new S.MeshBasicMaterial({map:n.texture,transparent:!0,opacity:Ke.SHADOW_STRENGTH,depthWrite:!1,toneMapped:!1});o.onBeforeCompile=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 a=new S.Mesh(s,o);a.name=di,a.rotation.x=-Math.PI/2;const c=S.MathUtils.clamp(t.objectHeight*.0025,2e-4,.01);a.position.set(t.center.x,c,t.center.z),a.userData.renderTarget=n,e.add(a);const d=e.getObjectByName(xn);d&&(d.visible=!1)}disableColorWrite(e){const t=new Map;return e.traverse(n=>{const s=n;if(!s.isMesh)return;const r=Array.isArray(s.material)?s.material:[s.material];for(const o of r)o&&!t.has(o)&&(t.set(o,o.colorWrite),o.colorWrite=!1)}),t}restoreColorWrite(e){e.forEach((t,n)=>{n.colorWrite=t})}};Ke.AMBIENT_RATIO=.45,Ke.LIGHT_APERTURE_DEGREES=9,Ke.AMBIENT_MIN_ELEVATION_DEGREES=55,Ke.ACCUMULATION_TEXTURE_SIZE=1024,Ke.BAKE_SHADOW_MAP_SIZE=1024,Ke.SHADOW_STRENGTH=.85;let fi=Ke;const _n=class _n{static getHeight(e){return e*this.HEIGHT_RATIO}static getBevelSize(e){return e*this.BEVEL_RATIO}static getBevelThickness(e){return this.getBevelSize(e)}static getBaseSize(e){return e+this.getBevelSize(e)+this.getBevelThickness(e)}static getGapFactor(){return this.GAP_FACTOR}static getGridSpacing(e){const t=this.getBaseSize(e),n=this.getGapFactor();return{width:Math.sqrt(3)*t*n,height:2*t*n}}static getYPosition(e){return-this.getBevelSize(e)}};_n.HEIGHT_RATIO=.075,_n.BEVEL_RATIO=.04,_n.GAP_FACTOR=1.05;let Ut=_n;var _t=(i=>(i.SQUARE_WIRE="square_wire",i.HEXAGONAL_WIRE="hexagonal_wire",i.HEXAGONAL_GLASS="hexagonal_glass",i.STONE_TILES="stone_tiles",i.CUSTOM="custom",i))(_t||{});class ul{constructor(){this.name="Square Wire Grid"}createGrid(e){const t=e.size||10,n=e.divisions||10,s=new S.Color(e.color||8947848),r=new S.Color(e.centerLineColor||e.color||4473924),o=new S.GridHelper(t,n,r,s);if(e.opacity!==void 0&&e.opacity<1){const a=o.material;a.transparent=!0,a.opacity=e.opacity}return o}dispose(){}}class dl{constructor(){this.name="Hexagonal Wire Grid"}createGrid(e){var u;const t=new S.Group,n=((u=e.styleOptions)==null?void 0:u.hexRadius)||Math.floor(e.divisions/2),s=e.size/Math.max(1,n*2),r=new S.Color(e.color||8947848),o=e.opacity||.4,a=new S.LineBasicMaterial({color:r,transparent:!0,opacity:o}),c=s*Math.sqrt(3),d=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 _=c*(h+w/2),E=d*.75*w,b=[],T=Math.PI*2/6;for(let R=0;R<=6;R++){const O=R*T+Math.PI/6,L=_+s*Math.cos(O),C=E+s*Math.sin(O);b.push(new S.Vector3(L,0,C))}const x=new S.BufferGeometry().setFromPoints(b),A=new S.Line(x,a);t.add(A)}}return t}dispose(){}}class fl{constructor(e,t,n,s={}){this.position=e,this.size=t,this.color=n,this.materialOptions=s,this.height=Ut.getHeight(this.size),this.bevel=Ut.getBevelSize(this.size)}createMesh(){const e=new S.Shape,t=this.size+this.bevel,n=Math.PI*2/6;for(let _=0;_<6;_++){const E=t*Math.cos(_*n),b=t*Math.sin(_*n);_===0?e.moveTo(E,b):e.lineTo(E,b)}e.closePath();const s={depth:this.height,bevelEnabled:!0,bevelSize:this.bevel,bevelThickness:this.bevel,bevelSegments:2},r=new S.ExtrudeGeometry(e,s),{metalness:o=0,roughness:a=.15,transmission:c=1,thickness:d=.4,ior:u=1.5}=this.materialOptions,h=c>0,f=new S.MeshPhysicalMaterial({color:new S.Color(this.color),metalness:o,roughness:a,transparent:h,transmission:c,thickness:d,ior:u,opacity:1,clearcoat:h?1:0,clearcoatRoughness:.05,sheen:h?1:0,sheenColor:new S.Color(16777215),envMapIntensity:1}),m=new S.Mesh(r,f);m.receiveShadow=!0;const w=new S.Group;return w.add(m),w.position.set(this.position.x,this.position.y,this.position.z),w.rotation.x=Math.PI/2,w.rotation.z=Math.PI/6,w}}class pl{constructor(){this.name="Hexagonal Glass Grid"}createGrid(e){var d,u,h,f,m,w,_;const t=new S.Group,n=((d=e.styleOptions)==null?void 0:d.hexRadius)||Math.floor(e.divisions/2),s=((u=e.styleOptions)==null?void 0:u.tileSize)||1,r=String(e.color||"#ffffff"),o=Ut.getGridSpacing(s),a=o.width,c=o.height;for(let E=-n;E<=n;E++){const b=Math.max(-n,-E-n),T=Math.min(n,-E+n);for(let x=b;x<=T;x++){const A=a*(E+x/2),R=c*.75*x,O=Ut.getYPosition(s),C=new fl(new S.Vector3(A,O,R),s,r,{metalness:(h=e.styleOptions)==null?void 0:h.metalness,roughness:(f=e.styleOptions)==null?void 0:f.roughness,transmission:(m=e.styleOptions)==null?void 0:m.transmission,thickness:(w=e.styleOptions)==null?void 0:w.thickness,ior:(_=e.styleOptions)==null?void 0:_.ior}).createMesh();t.add(C)}}return t.add(this.createShadowCatcher(a*(n+.5))),t}createShadowCatcher(e){const t=new S.Mesh(new S.CircleGeometry(Math.max(e,1),64),new S.ShadowMaterial({opacity:.35}));return t.name=xn,t.rotation.x=-Math.PI/2,t.position.y=.002,t.receiveShadow=!0,t}dispose(){}}class ml{constructor(){this.name="Stone Tile Grid",this.textureLoader=new S.TextureLoader}createGrid(e){var m,w,_,E;const t=new S.Group,n=e.size,s=Math.max(1,e.divisions),r=n/s,o=r*.02,a=r-o,c=((m=e.styleOptions)==null?void 0:m.height)||r*.05,d=((w=e.styleOptions)==null?void 0:w.bevelSize)||c*.2,u=((_=e.styleOptions)==null?void 0:_.randomHeight)||!1,h=((E=e.styleOptions)==null?void 0:E.randomRotation)||!1,f=this.createStoneMaterial(e);for(let b=0;b<s;b++)for(let T=0;T<s;T++){const x=(b-s/2)*r+r/2,A=(T-s/2)*r+r/2,R=u?c*(.8+Math.random()*.4):c,O=new S.Shape,L=a/2;O.moveTo(-L,-L),O.lineTo(L,-L),O.lineTo(L,L),O.lineTo(-L,L),O.closePath();const C={depth:R,bevelEnabled:!0,bevelSize:d,bevelThickness:d,bevelSegments:2},N=new S.ExtrudeGeometry(O,C);N.rotateX(-Math.PI/2);const I=new S.Mesh(N,f);I.position.set(x,-R/2,A),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 o,a,c,d,u;const t=new S.Color(e.color||8421504),n=((o=e.styleOptions)==null?void 0:o.metalness)||0,s=((a=e.styleOptions)==null?void 0:a.roughness)||.8,r={color:t,metalness:n,roughness:s};if((c=e.styleOptions)!=null&&c.texture){const h=this.loadTexture(e.styleOptions.texture);h&&(r.map=h,h.wrapS=h.wrapT=S.RepeatWrapping,h.repeat.set(1,1))}if((d=e.styleOptions)!=null&&d.normalMap){const h=this.loadTexture(e.styleOptions.normalMap);h&&(r.normalMap=h,h.wrapS=h.wrapT=S.RepeatWrapping,h.repeat.set(1,1))}if((u=e.styleOptions)!=null&&u.roughnessMap){const h=this.loadTexture(e.styleOptions.roughnessMap);h&&(r.roughnessMap=h,h.wrapS=h.wrapT=S.RepeatWrapping,h.repeat.set(1,1))}return new S.MeshStandardMaterial(r)}loadTexture(e){try{return this.textureLoader.load(e)}catch(t){return console.warn("Failed to load texture:",e,t),null}}}const Mi=class Mi{static createGrid(e,t){const n=this.gridStyles.get(e);if(!n){console.warn(`Unknown grid type: ${e}, falling back to square wire grid`);const r=this.gridStyles.get(_t.SQUARE_WIRE);if(!r)throw new Error("Square wire grid style not found");return r.createGrid(t)}const s=n.createGrid(t);return s.name=`Grid_${e}`,s}static registerGridStyle(e,t){this.gridStyles.set(e,t)}static getAvailableTypes(){return Array.from(this.gridStyles.keys())}static disposeGridStyle(e){const t=this.gridStyles.get(e);t&&t.dispose&&t.dispose()}};Mi.gridStyles=new Map([[_t.SQUARE_WIRE,new ul],[_t.HEXAGONAL_WIRE,new dl],[_t.HEXAGONAL_GLASS,new pl],[_t.STONE_TILES,new ml]]);let gs=Mi;const gr=i=>{let e=null;return i.traverse(t=>{!e&&t.isDirectionalLight&&(e=t)}),e};class gl{constructor(){this.contactShadowBaker=new fi}addHelpers(e,t){try{if(!(e instanceof St))return z.err(new K("Scene must be ThreeSceneAdapter",q.INVALID_PARAMETER));const n=e.getThreeScene();if(t.grid){const s=n.userData,r=typeof t.grid=="object"?t.grid:null,o={enabled:!0,color:(r==null?void 0:r.colorGrid)||t.gridColor||"#AAAAAA",type:r!=null&&r.type?r.type:_t.HEXAGONAL_GLASS,opacity:r==null?void 0:r.opacity,styleOptions:r==null?void 0:r.styleOptions};if(n.userData={...s,gridOptions:o},r!=null&&r.size||r!=null&&r.divisions){const a=o.type||_t.HEXAGONAL_GLASS,c=r.size||10,d=r.divisions||10,u={size:c,divisions:d,color:o.color,opacity:o.opacity,styleOptions:{hexRadius:Math.floor(d/2),tileSize:1,...o.styleOptions}},h=gs.createGrid(a,u);h.userData.isGrid=!0,h.userData.isDefaultGrid=!0,n.add(h)}}if(t.axes){const s=t.axesSize||5,r=new S.AxesHelper(s);n.add(r)}return z.ok(void 0)}catch(n){return z.err(new K("Failed to add helpers to scene",q.SCENE_OPERATION_FAILED,{originalError:n,options:t}))}}addDynamicGrid(e,t,n=1.2){var s;try{if(!(e instanceof St))return z.err(new K("Scene must be ThreeSceneAdapter",q.INVALID_PARAMETER));const r=e.getThreeScene(),o=r.userData,a=o==null?void 0:o.gridOptions;if(!(a!=null&&a.enabled))return z.ok(void 0);const c=[];r.traverse(C=>{var N,I,k;((N=C.userData)!=null&&N.isGrid||(I=C.userData)!=null&&I.isHexGrid||(k=C.userData)!=null&&k.isDefaultGrid)&&c.push(C)}),c.forEach(C=>{xs(C),r.remove(C)});let d;t instanceof Oe||"getThreeObject"in t&&typeof t.getThreeObject=="function"?d=t.getThreeObject():d=t;const u=new S.Box3().setFromObject(d),h=u.getSize(new S.Vector3);if(u.isEmpty()||!Number.isFinite(h.x)||!Number.isFinite(h.z))return console.warn("Skipping dynamic grid: object has an empty or non-finite bounding box"),z.ok(void 0);const f=(s=a.styleOptions)==null?void 0:s.tileSize,m=typeof f=="number"?f:1,_=Ut.getGridSpacing(m).width,E=Math.max(h.x,h.z)*n+h.y;let b=E<=_?0:Math.ceil((E/_-1)/2);const T=60;b>T&&(console.warn(`Dynamic grid would need ${b} rings to cover the object; capping at ${T}. The floor will not fully reach the configured coverage for this tileSize/object-size combination.`),b=T),E<_*.8?b=0:b<3&&E>_*2&&(b=3);const x=a.type||_t.HEXAGONAL_GLASS,R={size:Math.max(h.x,h.z)*n,divisions:b*2+1,color:a.color,opacity:a.opacity,styleOptions:{hexRadius:b,tileSize:m,...a.styleOptions}},O=gs.createGrid(x,R);O.userData.isGrid=!0,O.userData.isHexGrid=!0;const L=O.getObjectByName(xn);return L&&(L.position.y=S.MathUtils.clamp(h.y*.0025,2e-4,.002)),r.add(O),z.ok(void 0)}catch(r){return z.err(new K("Failed to add dynamic grid",q.SCENE_OPERATION_FAILED,{originalError:r}))}}snapObjectToFloor(e,t){try{if(!(e instanceof St))return z.err(new K("Scene must be ThreeSceneAdapter",q.INVALID_PARAMETER));let n;t instanceof Oe||"getThreeObject"in t&&typeof t.getThreeObject=="function"?n=t.getThreeObject():n=t;const s=E=>{var T,x,A;let b=E;for(;b;){if((T=b.userData)!=null&&T.isGrid||(x=b.userData)!=null&&x.isHexGrid||(A=b.userData)!=null&&A.isDefaultGrid)return!0;b=b.parent}return!1},r=e.getThreeScene();r.updateMatrixWorld(!0);const o=[];r.traverse(E=>{E.isMesh&&s(E)&&o.push(E)});const a=[];if(n.traverse(E=>{E.isMesh&&a.push(E)}),o.length===0||a.length===0)return z.ok(void 0);let c=-1/0;const d=new S.Box3;for(const E of o)d.setFromObject(E),Number.isFinite(d.max.y)&&(c=Math.max(c,d.max.y));if(!Number.isFinite(c))return z.ok(void 0);const u=new S.Box3().setFromObject(n);if(u.isEmpty()||!Number.isFinite(u.min.x)||!Number.isFinite(u.max.x))return z.ok(void 0);const h=40,f=u.max.y+Math.max(1,u.max.y-u.min.y),m=new S.Raycaster,w=new S.Vector3(0,-1,0);let _=1/0;for(let E=0;E<=h;E++)for(let b=0;b<=h;b++){const T=u.min.x+(u.max.x-u.min.x)*(E/h),x=u.min.z+(u.max.z-u.min.z)*(b/h);m.set(new S.Vector3(T,f,x),w);for(const A of m.intersectObjects(a,!1))A.point.y<_&&(_=A.point.y)}if(Number.isFinite(_)){const E=_-c;Math.abs(E)>1e-4&&(n.position.y-=E)}return z.ok(void 0)}catch(n){return z.err(new K("Failed to snap object to floor",q.SCENE_OPERATION_FAILED,{originalError:n}))}}fitShadowCameraToObject(e,t){try{if(!(e instanceof St))return z.err(new K("Scene must be ThreeSceneAdapter",q.INVALID_PARAMETER));let n;t instanceof Oe||"getThreeObject"in t&&typeof t.getThreeObject=="function"?n=t.getThreeObject():n=t;const s=new S.Box3().setFromObject(n);if(s.isEmpty()||!Number.isFinite(s.min.x)||!Number.isFinite(s.max.x))return z.ok(void 0);const r=s.getSize(new S.Vector3),o=e.getThreeScene(),a=gr(o);if(!a||!a.castShadow)return z.ok(void 0);const u=Math.max(r.x,r.y,r.z,.1)*2,h=a.shadow.camera;return h.left=-u,h.right=u,h.top=u,h.bottom=-u,h.updateProjectionMatrix(),z.ok(void 0)}catch(n){return z.err(new K("Failed to fit shadow camera to object",q.SCENE_OPERATION_FAILED,{originalError:n}))}}bakeContactShadow(e,t,n){try{const s=ui(e);if(!s)return z.err(new K("Scene must be ThreeSceneAdapter",q.INVALID_PARAMETER));const r=zt(t);if(!r)return z.err(new K("Object must expose a Three.js Object3D",q.INVALID_PARAMETER));const o=jr(n.getInternalRenderer());if(!o||!o.shadowMap.enabled)return z.ok(void 0);const a=gr(s);return!a||!a.castShadow||this.contactShadowBaker.bake({renderer:o,scene:s,object:r,light:a}),z.ok(void 0)}catch(s){return z.err(new K("Failed to bake contact shadow",q.SCENE_OPERATION_FAILED,{originalError:s}))}}setContactShadowMode(e,t){try{const n=ui(e);if(!n)return z.err(new K("Scene must be ThreeSceneAdapter",q.INVALID_PARAMETER));const s=n.getObjectByName(di),r=n.getObjectByName(xn);return t==="baked"&&!s||(s&&(s.visible=t==="baked"),r&&(r.visible=t==="live")),z.ok(void 0)}catch(n){return z.err(new K("Failed to switch contact shadow mode",q.SCENE_OPERATION_FAILED,{originalError:n}))}}wrapInUnitsScaleGroup(e,t){try{const n=zt(e);if(!n)return z.err(new K("Object must expose a Three.js Object3D",q.INVALID_PARAMETER));const s=new S.Group;return s.name=Xo,s.scale.setScalar(t),s.add(n),z.ok(new Oe(s))}catch(n){return z.err(new K("Failed to apply the units scale to the model",q.SCENE_OPERATION_FAILED,{originalError:n}))}}addLighting(e,t){try{if(!(e instanceof St))return z.err(new K("Scene must be ThreeSceneAdapter",q.INVALID_PARAMETER));const n=e.getThreeScene();if(t.ambient){const s=new S.Color(t.ambient.color||"#404040"),r=t.ambient.intensity??Math.PI,o=new S.AmbientLight(s,r);n.add(o)}if(t.hemisphere){const s=new S.Color(t.hemisphere.skyColor||"#ffffbb"),r=new S.Color(t.hemisphere.groundColor||"#080820"),o=t.hemisphere.intensity??1,a=new S.HemisphereLight(s,r,o);n.add(a)}if(t.directional){const s=new S.Color(t.directional.color||"#ffffff"),r=t.directional.intensity??Math.PI,o=new S.DirectionalLight(s,r);if(t.directional.position){const a=t.directional.position;if(a instanceof S.Vector3)o.position.copy(a);else if(Array.isArray(a))o.position.set(a[0],a[1],a[2]);else if(typeof a=="object"&&"x"in a&&"y"in a&&"z"in a){const c=a;o.position.set(c.x,c.y,c.z)}}else o.position.set(6,6,6);if(t.directional.castShadow&&(o.castShadow=!0,t.directional.shadow)){const a=t.directional.shadow;if(a.mapSize&&(o.shadow.mapSize.width=a.mapSize.width,o.shadow.mapSize.height=a.mapSize.height),a.camera){const c=o.shadow.camera;a.camera.near!==void 0&&(c.near=a.camera.near),a.camera.far!==void 0&&(c.far=a.camera.far),a.camera.left!==void 0&&(c.left=a.camera.left),a.camera.right!==void 0&&(c.right=a.camera.right),a.camera.top!==void 0&&(c.top=a.camera.top),a.camera.bottom!==void 0&&(c.bottom=a.camera.bottom)}a.bias!==void 0&&(o.shadow.bias=a.bias),a.radius!==void 0&&(o.shadow.radius=a.radius)}o.target.position.set(0,0,0),n.add(o),n.add(o.target),o.shadow&&o.shadow.camera.updateProjectionMatrix()}return z.ok(void 0)}catch(n){return z.err(new K("Failed to add lighting to scene",q.SCENE_OPERATION_FAILED,{originalError:n,options:t}))}}createGradientBackground(e,t){try{if(!(e instanceof St))return z.err(new K("Scene must be ThreeSceneAdapter",q.INVALID_PARAMETER));const n=e.getThreeScene(),s=document.createElement("canvas");s.width=2,s.height=512;const r=s.getContext("2d");if(!r)return z.err(new K("Failed to create canvas context",q.SCENE_OPERATION_FAILED));const o=r.createLinearGradient(0,0,0,s.height);o.addColorStop(0,t.topColor),o.addColorStop(1,t.bottomColor),r.fillStyle=o,r.fillRect(0,0,s.width,s.height);const a=new S.CanvasTexture(s);a.needsUpdate=!0;const c=n.background;return c instanceof S.Texture&&c!==n.environment&&c.dispose(),n.background=a,z.ok(void 0)}catch(n){return z.err(new K("Failed to create gradient background",q.SCENE_OPERATION_FAILED,{originalError:n,options:t}))}}fitCameraToObject(e,t,n){try{const s=zt(e)??e,r=vn(t)??t,o=bi(n)??n,a=new S.Box3().setFromObject(s),c=a.getCenter(new S.Vector3),d=a.getSize(new S.Vector3),u=Math.max(d.x,d.y,d.z);let h;"fov"in r?h=r.fov*(Math.PI/180):h=50*(Math.PI/180);let f=Math.abs(u/2/Math.tan(h/2));f*=2;const m=-Math.PI/4,w=Math.PI/8,_=c.x+f*Math.sin(m)*Math.cos(w),E=c.y+f*Math.sin(w),b=c.z+f*Math.cos(m)*Math.cos(w);return r.position.set(_,E,b),r.lookAt(c),r.updateProjectionMatrix(),o&&o.target&&(o.target.copy(c),o.update()),z.ok(void 0)}catch(s){return z.err(new K("Failed to fit camera to object",q.CAMERA_INIT_FAILED,{originalError:s}))}}}class yl{constructor(){this.events=new ws,this.disposed=!1}async initialize(e){const{ThreePathTracingService:t}=await Promise.resolve().then(()=>require("./ThreePathTracingService-CmWxkAFu.cjs"));if(this.disposed)return z.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(z.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(){var e;(e=this.inner)==null||e.reset()}dispose(){var e;this.disposed=!0,(e=this.inner)==null||e.dispose()}isSupported(){var e;return((e=this.inner)==null?void 0:e.isSupported())??!0}}/*!
3
+ fflate - fast JavaScript compression/decompression
4
+ <https://101arrowz.github.io/fflate>
5
+ Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSE
6
+ version 0.8.2
7
+ */var it=Uint8Array,sn=Uint16Array,El=Int32Array,Gr=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]),Wr=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]),wl=new it([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Zr=function(i,e){for(var t=new sn(31),n=0;n<31;++n)t[n]=e+=1<<i[n-1];for(var s=new El(t[30]),n=1;n<30;++n)for(var r=t[n];r<t[n+1];++r)s[r]=r-t[n]<<5|n;return{b:t,r:s}},Kr=Zr(Gr,2),Xr=Kr.b,Tl=Kr.r;Xr[28]=258,Tl[258]=28;var Sl=Zr(Wr,0),_l=Sl.b,pi=new sn(32768);for(var _e=0;_e<32768;++_e){var vt=(_e&43690)>>1|(_e&21845)<<1;vt=(vt&52428)>>2|(vt&13107)<<2,vt=(vt&61680)>>4|(vt&3855)<<4,pi[_e]=((vt&65280)>>8|(vt&255)<<8)>>1}var Sn=(function(i,e,t){for(var n=i.length,s=0,r=new sn(e);s<n;++s)i[s]&&++r[i[s]-1];var o=new sn(e);for(s=1;s<e;++s)o[s]=o[s-1]+r[s-1]<<1;var a;if(t){a=new sn(1<<e);var c=15-e;for(s=0;s<n;++s)if(i[s])for(var d=s<<4|i[s],u=e-i[s],h=o[i[s]-1]++<<u,f=h|(1<<u)-1;h<=f;++h)a[pi[h]>>c]=d}else for(a=new sn(n),s=0;s<n;++s)i[s]&&(a[s]=pi[o[i[s]-1]++]>>15-i[s]);return a}),Cn=new it(288);for(var _e=0;_e<144;++_e)Cn[_e]=8;for(var _e=144;_e<256;++_e)Cn[_e]=9;for(var _e=256;_e<280;++_e)Cn[_e]=7;for(var _e=280;_e<288;++_e)Cn[_e]=8;var Yr=new it(32);for(var _e=0;_e<32;++_e)Yr[_e]=5;var bl=Sn(Cn,9,1),xl=Sn(Yr,5,1),Gs=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},Ws=function(i,e){var t=e/8|0;return(i[t]|i[t+1]<<8|i[t+2]<<16)>>(e&7)},Al=function(i){return(i+7)/8|0},Ml=function(i,e,t){return(t==null||t>i.length)&&(t=i.length),new it(i.subarray(e,t))},Rl=["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||Rl[i]);if(n.code=i,Error.captureStackTrace&&Error.captureStackTrace(n,ut),!t)throw n;return n},vl=function(i,e,t,n){var s=i.length,r=0;if(!s||e.f&&!e.l)return t||new it(0);var o=!t,a=o||e.i!=2,c=e.i;o&&(t=new it(s*3));var d=function(Ht){var Et=t.length;if(Ht>Et){var In=new it(Math.max(Et*2,Ht));In.set(t),t=In}},u=e.f||0,h=e.p||0,f=e.b||0,m=e.l,w=e.d,_=e.m,E=e.n,b=s*8;do{if(!m){u=lt(i,h,1);var T=lt(i,h+1,3);if(h+=3,T)if(T==1)m=bl,w=xl,_=9,E=5;else if(T==2){var O=lt(i,h,31)+257,L=lt(i,h+10,15)+4,C=O+lt(i,h+5,31)+1;h+=14;for(var N=new it(C),I=new it(19),k=0;k<L;++k)I[wl[k]]=lt(i,h+k*3,7);h+=L*3;for(var D=Gs(I),B=(1<<D)-1,W=Sn(I,D,1),k=0;k<C;){var te=W[lt(i,h,B)];h+=te&15;var x=te>>4;if(x<16)N[k++]=x;else{var re=0,Ne=0;for(x==16?(Ne=3+lt(i,h,3),h+=2,re=N[k-1]):x==17?(Ne=3+lt(i,h,7),h+=3):x==18&&(Ne=11+lt(i,h,127),h+=7);Ne--;)N[k++]=re}}var ot=N.subarray(0,O),Re=N.subarray(O);_=Gs(ot),E=Gs(Re),m=Sn(ot,_,1),w=Sn(Re,E,1)}else ut(1);else{var x=Al(h)+4,A=i[x-4]|i[x-3]<<8,R=x+A;if(R>s){c&&ut(0);break}a&&d(f+A),t.set(i.subarray(x,R),f),e.b=f+=A,e.p=h=R*8,e.f=u;continue}if(h>b){c&&ut(0);break}}a&&d(f+131072);for(var ze=(1<<_)-1,je=(1<<E)-1,Ae=h;;Ae=h){var re=m[Ws(i,h)&ze],ye=re>>4;if(h+=re&15,h>b){c&&ut(0);break}if(re||ut(2),ye<256)t[f++]=ye;else if(ye==256){Ae=h,m=null;break}else{var ft=ye-254;if(ye>264){var k=ye-257,Ge=Gr[k];ft=lt(i,h,(1<<Ge)-1)+Xr[k],h+=Ge}var xt=w[Ws(i,h)&je],ge=xt>>4;xt||ut(3),h+=xt&15;var Re=_l[ge];if(ge>3){var Ge=Wr[ge];Re+=Ws(i,h)&(1<<Ge)-1,h+=Ge}if(h>b){c&&ut(0);break}a&&d(f+131072);var at=f+ft;if(f<Re){var ct=r-Re,on=Math.min(Re,at);for(ct+f<0&&ut(3);f<on;++f)t[f]=n[ct+f]}for(;f<at;++f)t[f]=t[f-Re]}}e.l=m,e.p=Ae,e.b=f,e.f=u,m&&(u=1,e.m=_,e.d=w,e.n=E)}while(!u);return f!=t.length&&o?Ml(t,0,f):t.subarray(0,f)},Cl=new it(0),Il=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 vl(i.subarray(Il(i),-4),{i:2},e,e)}var Ll=typeof TextDecoder<"u"&&new TextDecoder,Pl=0;try{Ll.decode(Cl,{stream:!0}),Pl=1}catch{}class Ol extends p.DataTextureLoader{constructor(e){super(e),this.type=p.HalfFloatType,this.outputFormat=p.RGBAFormat,this.part=0}parse(e){const N=Math.pow(2.7182818,2.2);let I=null;function k(l,g){let y=0;for(let P=0;P<65536;++P)(P==0||l[P>>3]&1<<(P&7))&&(g[y++]=P);const v=y-1;for(;y<65536;)g[y++]=0;return v}function D(l){for(let g=0;g<16384;g++)l[g]={},l[g].len=0,l[g].lit=0,l[g].p=null}const B={l:0,c:0,lc:0};function W(l,g,y,v,P){for(;y<l;)g=g<<8|Pi(v,P),y+=8;y-=l,B.l=g>>y&(1<<l)-1,B.c=g,B.lc=y}const te=new Array(59);function re(l){for(let y=0;y<=58;++y)te[y]=0;for(let y=0;y<65537;++y)te[l[y]]+=1;let g=0;for(let y=58;y>0;--y){const v=g+te[y]>>1;te[y]=g,g=v}for(let y=0;y<65537;++y){const v=l[y];v>0&&(l[y]=v|te[v]++<<6)}}function Ne(l,g,y,v,P,U){const M=g;let V=0,F=0;for(;v<=P;v++){if(M.value-g.value>y)return!1;W(6,V,F,l,M);const H=B.l;if(V=B.c,F=B.lc,U[v]=H,H==63){if(M.value-g.value>y)throw new Error("THREE.EXRLoader: Something wrong with hufUnpackEncTable");W(8,V,F,l,M);let j=B.l+6;if(V=B.c,F=B.lc,v+j>P+1)throw new Error("THREE.EXRLoader: Something wrong with hufUnpackEncTable");for(;j--;)U[v++]=0;v--}else if(H>=59){let j=H-59+2;if(v+j>P+1)throw new Error("THREE.EXRLoader: Something wrong with hufUnpackEncTable");for(;j--;)U[v++]=0;v--}}re(U)}function ot(l){return l&63}function Re(l){return l>>6}function ze(l,g,y,v){for(;g<=y;g++){const P=Re(l[g]),U=ot(l[g]);if(P>>U)throw new Error("THREE.EXRLoader: Invalid table entry");if(U>14){const M=v[P>>U-14];if(M.len)throw new Error("THREE.EXRLoader: Invalid table entry");if(M.lit++,M.p){const V=M.p;M.p=new Array(M.lit);for(let F=0;F<M.lit-1;++F)M.p[F]=V[F]}else M.p=new Array(1);M.p[M.lit-1]=g}else if(U){let M=0;for(let V=1<<14-U;V>0;V--){const F=v[(P<<14-U)+M];if(F.len||F.p)throw new Error("THREE.EXRLoader: Invalid table entry");F.len=U,F.lit=g,M++}}}return!0}const je={c:0,lc:0};function Ae(l,g,y,v){l=l<<8|Pi(y,v),g+=8,je.c=l,je.lc=g}const ye={c:0,lc:0};function ft(l,g,y,v,P,U,M,V,F){if(l==g){v<8&&(Ae(y,v,P,U),y=je.c,v=je.lc),v-=8;let H=y>>v;if(H=new Uint8Array([H])[0],V.value+H>F)return!1;const j=M[V.value-1];for(;H-- >0;)M[V.value++]=j}else if(V.value<F)M[V.value++]=l;else return!1;ye.c=y,ye.lc=v}function Ge(l){return l&65535}function xt(l){const g=Ge(l);return g>32767?g-65536:g}const ge={a:0,b:0};function at(l,g){const y=xt(l),P=xt(g),U=y+(P&1)+(P>>1),M=U,V=U-P;ge.a=M,ge.b=V}function ct(l,g){const y=Ge(l),v=Ge(g),P=y-(v>>1)&65535,U=v+P-32768&65535;ge.a=U,ge.b=P}function on(l,g,y,v,P,U,M){const V=M<16384,F=y>P?P:y;let H=1,j,Z;for(;H<=F;)H<<=1;for(H>>=1,j=H,H>>=1;H>=1;){Z=0;const G=Z+U*(P-j),Y=U*H,J=U*j,X=v*H,$=v*j;let ie,he,ae,de;for(;Z<=G;Z+=J){let ne=Z;const ee=Z+v*(y-j);for(;ne<=ee;ne+=$){const se=ne+X,Ee=ne+Y,pe=Ee+X;V?(at(l[ne+g],l[Ee+g]),ie=ge.a,ae=ge.b,at(l[se+g],l[pe+g]),he=ge.a,de=ge.b,at(ie,he),l[ne+g]=ge.a,l[se+g]=ge.b,at(ae,de),l[Ee+g]=ge.a,l[pe+g]=ge.b):(ct(l[ne+g],l[Ee+g]),ie=ge.a,ae=ge.b,ct(l[se+g],l[pe+g]),he=ge.a,de=ge.b,ct(ie,he),l[ne+g]=ge.a,l[se+g]=ge.b,ct(ae,de),l[Ee+g]=ge.a,l[pe+g]=ge.b)}if(y&H){const se=ne+Y;V?at(l[ne+g],l[se+g]):ct(l[ne+g],l[se+g]),ie=ge.a,l[se+g]=ge.b,l[ne+g]=ie}}if(P&H){let ne=Z;const ee=Z+v*(y-j);for(;ne<=ee;ne+=$){const se=ne+X;V?at(l[ne+g],l[se+g]):ct(l[ne+g],l[se+g]),ie=ge.a,l[se+g]=ge.b,l[ne+g]=ie}}j=H,H>>=1}return Z}function Ht(l,g,y,v,P,U,M,V,F){let H=0,j=0;const Z=M,G=Math.trunc(v.value+(P+7)/8);for(;v.value<G;)for(Ae(H,j,y,v),H=je.c,j=je.lc;j>=14;){const J=H>>j-14&16383,X=g[J];if(X.len)j-=X.len,ft(X.lit,U,H,j,y,v,V,F,Z),H=ye.c,j=ye.lc;else{if(!X.p)throw new Error("THREE.EXRLoader: hufDecode issues");let $;for($=0;$<X.lit;$++){const ie=ot(l[X.p[$]]);for(;j<ie&&v.value<G;)Ae(H,j,y,v),H=je.c,j=je.lc;if(j>=ie&&Re(l[X.p[$]])==(H>>j-ie&(1<<ie)-1)){j-=ie,ft(X.p[$],U,H,j,y,v,V,F,Z),H=ye.c,j=ye.lc;break}}if($==X.lit)throw new Error("THREE.EXRLoader: hufDecode issues")}}const Y=8-P&7;for(H>>=Y,j-=Y;j>0;){const J=g[H<<14-j&16383];if(J.len)j-=J.len,ft(J.lit,U,H,j,y,v,V,F,Z),H=ye.c,j=ye.lc;else throw new Error("THREE.EXRLoader: hufDecode issues")}return!0}function Et(l,g,y,v,P,U){const M={value:0},V=y.value,F=Je(g,y),H=Je(g,y);y.value+=4;const j=Je(g,y);if(y.value+=4,F<0||F>=65537||H<0||H>=65537)throw new Error("THREE.EXRLoader: Something wrong with HUF_ENCSIZE");const Z=new Array(65537),G=new Array(16384);D(G);const Y=v-(y.value-V);if(Ne(l,y,Y,F,H,Z),j>8*(v-(y.value-V)))throw new Error("THREE.EXRLoader: Something wrong with hufUncompress");ze(Z,F,H,G),Ht(Z,G,l,y,j,H,U,P,M)}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),P=0;const U=l.length-1;for(;!(P>U||(g[P++]=l[y++],P>U));)g[P++]=l[v++]}function As(l){let g=l.byteLength;const y=new Array;let v=0;const P=new DataView(l);for(;g>0;){const U=P.getInt8(v++);if(U<0){const M=-U;g-=M+1;for(let V=0;V<M;V++)y.push(P.getUint8(v++))}else{const M=U;g-=2;const V=P.getUint8(v++);for(let F=0;F<M+1;F++)y.push(V)}}return y}function ao(l,g,y,v,P,U){let M=new DataView(U.buffer);const V=y[l.idx[0]].width,F=y[l.idx[0]].height,H=3,j=Math.floor(V/8),Z=Math.ceil(V/8),G=Math.ceil(F/8),Y=V-(Z-1)*8,J=F-(G-1)*8,X={value:0},$=new Array(H),ie=new Array(H),he=new Array(H),ae=new Array(H),de=new Array(H);for(let ee=0;ee<H;++ee)de[ee]=g[l.idx[ee]],$[ee]=ee<1?0:$[ee-1]+Z*G,ie[ee]=new Float32Array(64),he[ee]=new Uint16Array(64),ae[ee]=new Uint16Array(Z*64);for(let ee=0;ee<G;++ee){let se=8;ee==G-1&&(se=J);let Ee=8;for(let ce=0;ce<Z;++ce){ce==Z-1&&(Ee=Y);for(let ue=0;ue<H;++ue)he[ue].fill(0),he[ue][0]=P[$[ue]++],Ri(X,v,he[ue]),vi(he[ue],ie[ue]),Ci(ie[ue]);lo(ie);for(let ue=0;ue<H;++ue)Ii(ie[ue],ae[ue],ce*64)}let pe=0;for(let ce=0;ce<H;++ce){const ue=y[l.idx[ce]].type;for(let ve=8*ee;ve<8*ee+se;++ve){pe=de[ce][ve];for(let et=0;et<j;++et){const Se=et*64+(ve&7)*8;M.setUint16(pe+0*ue,ae[ce][Se+0],!0),M.setUint16(pe+2*ue,ae[ce][Se+1],!0),M.setUint16(pe+4*ue,ae[ce][Se+2],!0),M.setUint16(pe+6*ue,ae[ce][Se+3],!0),M.setUint16(pe+8*ue,ae[ce][Se+4],!0),M.setUint16(pe+10*ue,ae[ce][Se+5],!0),M.setUint16(pe+12*ue,ae[ce][Se+6],!0),M.setUint16(pe+14*ue,ae[ce][Se+7],!0),pe+=16*ue}}if(j!=Z)for(let ve=8*ee;ve<8*ee+se;++ve){const et=de[ce][ve]+8*j*2*ue,Se=j*64+(ve&7)*8;for(let pt=0;pt<Ee;++pt)M.setUint16(et+pt*2*ue,ae[ce][Se+pt],!0)}}}const ne=new Uint16Array(V);M=new DataView(U.buffer);for(let ee=0;ee<H;++ee){y[l.idx[ee]].decoded=!0;const se=y[l.idx[ee]].type;if(y[ee].type==2)for(let Ee=0;Ee<F;++Ee){const pe=de[ee][Ee];for(let ce=0;ce<V;++ce)ne[ce]=M.getUint16(pe+ce*2*se,!0);for(let ce=0;ce<V;++ce)M.setFloat32(pe+ce*2*se,Q(ne[ce]),!0)}}}function co(l,g,y,v,P,U){const M=new DataView(U.buffer),V=y[l],F=V.width,H=V.height,j=Math.ceil(F/8),Z=Math.ceil(H/8),G=Math.floor(F/8),Y=F-(j-1)*8,J=H-(Z-1)*8,X={value:0};let $=0;const ie=new Float32Array(64),he=new Uint16Array(64),ae=new Uint16Array(j*64);for(let de=0;de<Z;++de){let ne=8;de==Z-1&&(ne=J);for(let ee=0;ee<j;++ee)he.fill(0),he[0]=P[$++],Ri(X,v,he),vi(he,ie),Ci(ie),Ii(ie,ae,ee*64);for(let ee=8*de;ee<8*de+ne;++ee){let se=g[l][ee];for(let Ee=0;Ee<G;++Ee){const pe=Ee*64+(ee&7)*8;for(let ce=0;ce<8;++ce)M.setUint16(se+ce*2*V.type,ae[pe+ce],!0);se+=16*V.type}if(j!=G){const Ee=G*64+(ee&7)*8;for(let pe=0;pe<Y;++pe)M.setUint16(se+pe*2*V.type,ae[Ee+pe],!0)}}}V.decoded=!0}function Ri(l,g,y){let v,P=1;for(;P<64;)v=g[l.value],v==65280?P=64:v>>8==255?P+=v&255:(y[P]=v,P++),l.value++}function vi(l,g){g[0]=Q(l[0]),g[1]=Q(l[1]),g[2]=Q(l[5]),g[3]=Q(l[6]),g[4]=Q(l[14]),g[5]=Q(l[15]),g[6]=Q(l[27]),g[7]=Q(l[28]),g[8]=Q(l[2]),g[9]=Q(l[4]),g[10]=Q(l[7]),g[11]=Q(l[13]),g[12]=Q(l[16]),g[13]=Q(l[26]),g[14]=Q(l[29]),g[15]=Q(l[42]),g[16]=Q(l[3]),g[17]=Q(l[8]),g[18]=Q(l[12]),g[19]=Q(l[17]),g[20]=Q(l[25]),g[21]=Q(l[30]),g[22]=Q(l[41]),g[23]=Q(l[43]),g[24]=Q(l[9]),g[25]=Q(l[11]),g[26]=Q(l[18]),g[27]=Q(l[24]),g[28]=Q(l[31]),g[29]=Q(l[40]),g[30]=Q(l[44]),g[31]=Q(l[53]),g[32]=Q(l[10]),g[33]=Q(l[19]),g[34]=Q(l[23]),g[35]=Q(l[32]),g[36]=Q(l[39]),g[37]=Q(l[45]),g[38]=Q(l[52]),g[39]=Q(l[54]),g[40]=Q(l[20]),g[41]=Q(l[22]),g[42]=Q(l[33]),g[43]=Q(l[38]),g[44]=Q(l[46]),g[45]=Q(l[51]),g[46]=Q(l[55]),g[47]=Q(l[60]),g[48]=Q(l[21]),g[49]=Q(l[34]),g[50]=Q(l[37]),g[51]=Q(l[47]),g[52]=Q(l[50]),g[53]=Q(l[56]),g[54]=Q(l[59]),g[55]=Q(l[61]),g[56]=Q(l[35]),g[57]=Q(l[36]),g[58]=Q(l[48]),g[59]=Q(l[49]),g[60]=Q(l[57]),g[61]=Q(l[58]),g[62]=Q(l[62]),g[63]=Q(l[63])}function Ci(l){const g=.5*Math.cos(.7853975),y=.5*Math.cos(3.14159/16),v=.5*Math.cos(3.14159/8),P=.5*Math.cos(3*3.14159/16),U=.5*Math.cos(5*3.14159/16),M=.5*Math.cos(3*3.14159/8),V=.5*Math.cos(7*3.14159/16),F=new Array(4),H=new Array(4),j=new Array(4),Z=new Array(4);for(let G=0;G<8;++G){const Y=G*8;F[0]=v*l[Y+2],F[1]=M*l[Y+2],F[2]=v*l[Y+6],F[3]=M*l[Y+6],H[0]=y*l[Y+1]+P*l[Y+3]+U*l[Y+5]+V*l[Y+7],H[1]=P*l[Y+1]-V*l[Y+3]-y*l[Y+5]-U*l[Y+7],H[2]=U*l[Y+1]-y*l[Y+3]+V*l[Y+5]+P*l[Y+7],H[3]=V*l[Y+1]-U*l[Y+3]+P*l[Y+5]-y*l[Y+7],j[0]=g*(l[Y+0]+l[Y+4]),j[3]=g*(l[Y+0]-l[Y+4]),j[1]=F[0]+F[3],j[2]=F[1]-F[2],Z[0]=j[0]+j[1],Z[1]=j[3]+j[2],Z[2]=j[3]-j[2],Z[3]=j[0]-j[1],l[Y+0]=Z[0]+H[0],l[Y+1]=Z[1]+H[1],l[Y+2]=Z[2]+H[2],l[Y+3]=Z[3]+H[3],l[Y+4]=Z[3]-H[3],l[Y+5]=Z[2]-H[2],l[Y+6]=Z[1]-H[1],l[Y+7]=Z[0]-H[0]}for(let G=0;G<8;++G)F[0]=v*l[16+G],F[1]=M*l[16+G],F[2]=v*l[48+G],F[3]=M*l[48+G],H[0]=y*l[8+G]+P*l[24+G]+U*l[40+G]+V*l[56+G],H[1]=P*l[8+G]-V*l[24+G]-y*l[40+G]-U*l[56+G],H[2]=U*l[8+G]-y*l[24+G]+V*l[40+G]+P*l[56+G],H[3]=V*l[8+G]-U*l[24+G]+P*l[40+G]-y*l[56+G],j[0]=g*(l[G]+l[32+G]),j[3]=g*(l[G]-l[32+G]),j[1]=F[0]+F[3],j[2]=F[1]-F[2],Z[0]=j[0]+j[1],Z[1]=j[3]+j[2],Z[2]=j[3]-j[2],Z[3]=j[0]-j[1],l[0+G]=Z[0]+H[0],l[8+G]=Z[1]+H[1],l[16+G]=Z[2]+H[2],l[24+G]=Z[3]+H[3],l[32+G]=Z[3]-H[3],l[40+G]=Z[2]-H[2],l[48+G]=Z[1]-H[1],l[56+G]=Z[0]-H[0]}function lo(l){for(let g=0;g<64;++g){const y=l[0][g],v=l[1][g],P=l[2][g];l[0][g]=y+1.5747*P,l[1][g]=y-.1873*v-.4682*P,l[2][g]=y+1.8556*v}}function Ii(l,g,y){for(let v=0;v<64;++v)g[y+v]=p.DataUtils.toHalfFloat(ho(l[v]))}function ho(l){return l<=1?Math.sign(l)*Math.pow(Math.abs(l),2.2):Math.sign(l)*Math.pow(N,Math.abs(l)-1)}function On(l){return new DataView(l.array.buffer,l.offset.value,l.size)}function uo(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 fo(l){const g=l.viewer,y={value:l.offset.value},v=new Uint16Array(l.columns*l.lines*(l.inputChannels.length*l.type)),P=new Uint8Array(8192);let U=0;const M=new Array(l.inputChannels.length);for(let J=0,X=l.inputChannels.length;J<X;J++)M[J]={},M[J].start=U,M[J].end=M[J].start,M[J].nx=l.columns,M[J].ny=l.lines,M[J].size=l.type,U+=M[J].nx*M[J].ny*M[J].size;const V=an(g,y),F=an(g,y);if(F>=8192)throw new Error("THREE.EXRLoader: Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(V<=F)for(let J=0;J<F-V+1;J++)P[J+V]=At(g,y);const H=new Uint16Array(65536),j=k(P,H),Z=Je(g,y);Et(l.array,g,y,Z,v,U);for(let J=0;J<l.inputChannels.length;++J){const X=M[J];for(let $=0;$<M[J].size;++$)on(v,X.start+$,X.nx,X.size,X.ny,X.nx*X.size,j)}In(H,v,U);let G=0;const Y=new Uint8Array(v.buffer.byteLength);for(let J=0;J<l.lines;J++)for(let X=0;X<l.inputChannels.length;X++){const $=M[X],ie=$.nx*$.size,he=new Uint8Array(v.buffer,$.end*2,ie*2);Y.set(he,G),G+=ie*2,$.end+=ie}return new DataView(Y.buffer)}function po(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,P=new ArrayBuffer(v),U=new DataView(P);let M=0,V=0;const F=new Array(4);for(let H=0;H<l.lines;H++)for(let j=0;j<l.inputChannels.length;j++){let Z=0;switch(l.inputChannels[j].pixelType){case 1:F[0]=M,F[1]=F[0]+l.columns,M=F[1]+l.columns;for(let Y=0;Y<l.columns;++Y){const J=y[F[0]++]<<8|y[F[1]++];Z+=J,U.setUint16(V,Z,!0),V+=2}break;case 2:F[0]=M,F[1]=F[0]+l.columns,F[2]=F[1]+l.columns,M=F[2]+l.columns;for(let Y=0;Y<l.columns;++Y){const J=y[F[0]++]<<24|y[F[1]++]<<16|y[F[2]++]<<8;Z+=J,U.setUint32(V,Z,!0),V+=4}break}}return U}function mo(l){const g=l.array;let y=l.offset.value;const v=l.columns,P=l.lines,U=l.inputChannels,M=l.totalBytes,V=Ze.compression==="B44A_COMPRESSION",F=new Uint8Array(P*v*M),H=new Uint16Array(16);let j=0;for(let Z=0;Z<U.length;Z++){const G=U[Z],Y=G.pixelType*2,J=Math.ceil(v/G.xSampling),X=Math.ceil(P/G.ySampling),$=G.xSampling===1&&G.ySampling===1;if(G.pixelType!==1){for(let ae=0;ae<X;ae++)if($){const de=ae*v*M+j*v;for(let ne=0;ne<J*Y;ne++)F[de+ne]=g[y++]}else y+=J*Y;j+=Y;continue}const ie=Math.ceil(J/4),he=Math.ceil(X/4);for(let ae=0;ae<he;ae++)for(let de=0;de<ie;de++){if(V&&g[y+2]>=52){const ne=g[y]<<8|g[y+1],ee=ne&32768?ne&32767:~ne&65535;H.fill(ee),y+=3}else{const ne=g[y]<<8|g[y+1],ee=g[y+2]>>2,se=32<<ee,Ee=ne+((g[y+2]<<4|g[y+3]>>4)&63)*(1<<ee)-se&65535,pe=Ee+((g[y+3]<<2|g[y+4]>>6)&63)*(1<<ee)-se&65535,ce=pe+(g[y+4]&63)*(1<<ee)-se&65535,ue=ne+(g[y+5]>>2&63)*(1<<ee)-se&65535,ve=Ee+((g[y+5]<<4|g[y+6]>>4)&63)*(1<<ee)-se&65535,et=pe+((g[y+6]<<2|g[y+7]>>6)&63)*(1<<ee)-se&65535,Se=ce+(g[y+7]&63)*(1<<ee)-se&65535,pt=ue+(g[y+8]>>2&63)*(1<<ee)-se&65535,Vt=ve+((g[y+8]<<4|g[y+9]>>4)&63)*(1<<ee)-se&65535,cn=et+((g[y+9]<<2|g[y+10]>>6)&63)*(1<<ee)-se&65535,mt=Se+(g[y+10]&63)*(1<<ee)-se&65535,Dt=pt+(g[y+11]>>2&63)*(1<<ee)-se&65535,Bn=Vt+((g[y+11]<<4|g[y+12]>>4)&63)*(1<<ee)-se&65535,zn=cn+((g[y+12]<<2|g[y+13]>>6)&63)*(1<<ee)-se&65535,Un=mt+(g[y+13]&63)*(1<<ee)-se&65535,ln=[ne,ue,pt,Dt,Ee,ve,Vt,Bn,pe,et,cn,zn,ce,Se,mt,Un];for(let jt=0;jt<16;jt++)H[jt]=ln[jt]&32768?ln[jt]&32767:~ln[jt]&65535;y+=14}if(G.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 ee=Q(ne);I[ne]=ee<=0?0:p.DataUtils.toHalfFloat(8*Math.log(ee))}}for(let ne=0;ne<16;ne++)H[ne]=I[H[ne]]}for(let ne=0;ne<4;ne++){const ee=ae*4+ne;if(!(ee>=X))for(let se=0;se<4;se++){const Ee=de*4+se;if(Ee>=J)continue;const pe=H[ne*4+se];for(let ce=0;ce<G.ySampling;ce++){const ue=ee*G.ySampling+ce;if(!(ue>=P))for(let ve=0;ve<G.xSampling;ve++){const et=Ee*G.xSampling+ve;if(et>=v)continue;const Se=ue*v*M+j*v+et*2;F[Se]=pe&255,F[Se+1]=pe>>8&255}}}}}j+=2}return new DataView(F.buffer)}function Li(l){const g=l.viewer,y={value:l.offset.value},v=new Uint8Array(l.columns*l.lines*(l.inputChannels.length*l.type*2)),P={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(P.version<2)throw new Error("THREE.EXRLoader: "+Ze.compression+" version "+P.version+" is unsupported");const U=new Array;let M=an(g,y)-2;for(;M>0;){const X=Dn(g.buffer,y),$=At(g,y),ie=$>>2&3,he=($>>4)-1,ae=new Int8Array([he])[0],de=At(g,y);U.push({name:X,index:ae,type:de,compression:ie}),M-=X.length+3}const V=Ze.channels,F=new Array(l.inputChannels.length);for(let X=0;X<l.inputChannels.length;++X){const $=F[X]={},ie=V[X];$.name=ie.name,$.compression=0,$.decoded=!1,$.type=ie.pixelType,$.pLinear=ie.pLinear,$.width=l.columns,$.height=l.lines}const H={idx:new Array(3)};for(let X=0;X<l.inputChannels.length;++X){const $=F[X],ie=$.name.lastIndexOf("."),he=ie>=0?$.name.substring(ie+1):$.name;for(let ae=0;ae<U.length;++ae){const de=U[ae];he===de.name&&$.type===de.type&&($.compression=de.compression,de.index>=0&&(H.idx[de.index]=X),$.offset=X)}}let j,Z,G;if(P.acCompressedSize>0)switch(P.acCompression){case 0:j=new Uint16Array(P.totalAcUncompressedCount),Et(l.array,g,y,P.acCompressedSize,j,P.totalAcUncompressedCount);break;case 1:const X=l.array.slice(y.value,y.value+P.totalAcUncompressedCount),$=En(X);j=new Uint16Array($.buffer),y.value+=P.totalAcUncompressedCount;break}if(P.dcCompressedSize>0){const X={array:l.array,offset:y,size:P.dcCompressedSize};Z=new Uint16Array(Ms(X).buffer),y.value+=P.dcCompressedSize}if(P.rleRawSize>0){const X=l.array.slice(y.value,y.value+P.rleCompressedSize),$=En(X);G=As($.buffer),y.value+=P.rleCompressedSize}let Y=0;const J=new Array(F.length);for(let X=0;X<J.length;++X)J[X]=new Array;for(let X=0;X<l.lines;++X)for(let $=0;$<F.length;++$)J[$].push(Y),Y+=F[$].width*l.type*2;H.idx[0]!==void 0&&F[H.idx[0]]&&ao(H,J,F,j,Z,v);for(let X=0;X<F.length;++X){const $=F[X];if(!$.decoded)switch($.compression){case 2:let ie=0,he=0;for(let ae=0;ae<l.lines;++ae){let de=J[X][ie];for(let ne=0;ne<$.width;++ne){for(let ee=0;ee<2*$.type;++ee)v[de++]=G[he+ee*$.width*$.height];he++}ie++}break;case 1:co(X,J,F,j,Z,v);break;default:throw new Error("THREE.EXRLoader: unsupported channel compression")}}return new DataView(v.buffer)}function Dn(l,g){const y=new Uint8Array(l);let v=0;for(;y[g.value+v]!=0;)v+=1;const P=new TextDecoder().decode(y.slice(g.value,g.value+v));return g.value=g.value+v+1,P}function go(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 yo(l,g){const y=qe(l,g),v=Je(l,g);return[y,v]}function Eo(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 Pi(l,g){const y=l[g.value];return g.value=g.value+1,y}function At(l,g){const y=l.getUint8(g.value);return g.value=g.value+1,y}const ke=function(l,g){const y=Number(l.getBigInt64(g.value,!0));return g.value+=8,y};function We(l,g){const y=l.getFloat32(g.value,!0);return g.value+=4,y}function wo(l,g){return p.DataUtils.toHalfFloat(We(l,g))}function Q(l){const g=(l&31744)>>10,y=l&1023;return(l>>15?-1:1)*(g?g===31?y?NaN:1/0:Math.pow(2,g-15)*(1+y/1024):6103515625e-14*(y/1024))}function an(l,g){const y=l.getUint16(g.value,!0);return g.value+=2,y}function To(l,g){return Q(an(l,g))}function So(l,g,y,v){const P=y.value,U=[];for(;y.value<P+v-1;){const M=Dn(g,y),V=qe(l,y),F=At(l,y);y.value+=3;const H=qe(l,y),j=qe(l,y);U.push({name:M,pixelType:V,pLinear:F,xSampling:H,ySampling:j})}return y.value+=1,U}function _o(l,g){const y=We(l,g),v=We(l,g),P=We(l,g),U=We(l,g),M=We(l,g),V=We(l,g),F=We(l,g),H=We(l,g);return{redX:y,redY:v,greenX:P,greenY:U,blueX:M,blueY:V,whiteX:F,whiteY:H}}function bo(l,g){const y=["NO_COMPRESSION","RLE_COMPRESSION","ZIPS_COMPRESSION","ZIP_COMPRESSION","PIZ_COMPRESSION","PXR24_COMPRESSION","B44_COMPRESSION","B44A_COMPRESSION","DWAA_COMPRESSION","DWAB_COMPRESSION"],v=At(l,g);return y[v]}function xo(l,g){const y=qe(l,g),v=qe(l,g),P=qe(l,g),U=qe(l,g);return{xMin:y,yMin:v,xMax:P,yMax:U}}function Ao(l,g){const y=["INCREASING_Y","DECREASING_Y","RANDOM_Y"],v=At(l,g);return y[v]}function Mo(l,g){const y=["ENVMAP_LATLONG","ENVMAP_CUBE"],v=At(l,g);return y[v]}function Ro(l,g){const y=["ONE_LEVEL","MIPMAP_LEVELS","RIPMAP_LEVELS"],v=["ROUND_DOWN","ROUND_UP"],P=Je(l,g),U=Je(l,g),M=At(l,g);return{xSize:P,ySize:U,levelMode:y[M&15],roundingMode:v[M>>4]}}function vo(l,g){const y=We(l,g),v=We(l,g);return[y,v]}function Co(l,g){const y=We(l,g),v=We(l,g),P=We(l,g);return[y,v,P]}function Io(l,g,y,v,P){if(v==="string"||v==="stringvector"||v==="iccProfile")return go(g,y,P);if(v==="chlist")return So(l,g,y,P);if(v==="chromaticities")return _o(l,y);if(v==="compression")return bo(l,y);if(v==="box2i")return xo(l,y);if(v==="envmap")return Mo(l,y);if(v==="tiledesc")return Ro(l,y);if(v==="lineOrder")return Ao(l,y);if(v==="float")return We(l,y);if(v==="v2f")return vo(l,y);if(v==="v3f")return Co(l,y);if(v==="int")return qe(l,y);if(v==="rational")return yo(l,y);if(v==="timecode")return Eo(l,y);if(v==="preview"||v==="deepImageState"||v==="idmanifest")return y.value+=P,"skipped";y.value+=P}function Lo(l,g){const y=Math.log2(l);return g=="ROUND_DOWN"?Math.floor(y):Math.ceil(y)}function Po(l,g,y){let v=0;switch(l.levelMode){case"ONE_LEVEL":v=1;break;case"MIPMAP_LEVELS":v=Lo(Math.max(g,y),l.roundingMode)+1;break;case"RIPMAP_LEVELS":throw new Error("THREE.EXRLoader: RIPMAP_LEVELS tiles currently unsupported.")}return v}function Oi(l,g,y,v){const P=new Array(l);for(let U=0;U<l;U++){const M=1<<U;let V=g/M|0;v=="ROUND_UP"&&V*M<g&&(V+=1);const F=Math.max(V,1);P[U]=(F+y-1)/y|0}return P}function Oo(){const l=this,g=l.offset,y={value:0};for(let v=0;v<l.tileCount;v++){const P=qe(l.viewer,g),U=qe(l.viewer,g);g.value+=8,l.size=Je(l.viewer,g);const M=P*l.blockWidth,V=U*l.blockHeight;l.columns=M+l.blockWidth>l.width?l.width-M:l.blockWidth,l.lines=V+l.blockHeight>l.height?l.height-V:l.blockHeight;const F=l.columns*l.totalBytes,j=l.size<l.lines*F?l.uncompress(l):On(l);g.value+=l.size;for(let Z=0;Z<l.lines;Z++){const G=Z*l.columns*l.totalBytes;for(let Y=0;Y<l.inputChannels.length;Y++){const J=Ze.channels[Y].name,X=l.channelByteOffsets[J]*l.columns,$=l.decodeChannels[J];if($===void 0)continue;y.value=G+X;const ie=(l.height-(1+V+Z))*l.outLineWidth;for(let he=0;he<l.columns;he++){const ae=ie+(he+M)*l.outputChannels+$;l.byteArray[ae]=l.getter(j,y)}}}}}function Do(){const l=this,g=l.offset,y={value:0};for(let v=0;v<l.height/l.blockHeight;v++){const P=qe(l.viewer,g)-Ze.dataWindow.yMin;l.size=Je(l.viewer,g),l.lines=P+l.blockHeight>l.height?l.height-P:l.blockHeight;const U=l.columns*l.totalBytes,V=l.size<l.lines*U?l.uncompress(l):On(l);g.value+=l.size;for(let F=0;F<l.lines;F++){const H=P+F,j=F*U,Z=(l.height-1-H)*l.outLineWidth;for(let G=0;G<l.inputChannels.length;G++){const Y=Ze.channels[G].name,J=l.channelByteOffsets[Y]*l.columns,X=l.decodeChannels[Y];if(X!==void 0){y.value=j+J;for(let $=0;$<l.columns;$++){const ie=Z+$*l.outputChannels+X;l.byteArray[ie]=l.getter(V,y)}}}}}}function No(){const l=this,g=l.chunkOffsets,y={value:0};for(let v=0;v<g.length;v++){const P={value:g[v]};P.value+=4;const U=qe(l.viewer,P)-Ze.dataWindow.yMin;l.size=Je(l.viewer,P),l.lines=U+l.blockHeight>l.height?l.height-U:l.blockHeight;const M=l.columns*l.totalBytes,V=l.size<l.lines*M,F=l.offset;l.offset=P;const H=V?l.uncompress(l):On(l);l.offset=F;for(let j=0;j<l.lines;j++){const Z=U+j,G=j*M,Y=(l.height-1-Z)*l.outLineWidth;for(let J=0;J<l.inputChannels.length;J++){const X=Ze.channels[J].name,$=l.channelByteOffsets[X]*l.columns,ie=l.decodeChannels[X];if(ie!==void 0){y.value=G+$;for(let he=0;he<l.columns;he++){const ae=Y+he*l.outputChannels+ie;l.byteArray[ae]=l.getter(H,y)}}}}}}function Di(l,g,y,v){if(y===0)return null;const P=l.slice(g,g+y);switch(v){case"NO_COMPRESSION":return new DataView(P.buffer,P.byteOffset,P.byteLength);case"RLE_COMPRESSION":{const U=new Uint8Array(As(P.buffer.slice(P.byteOffset,P.byteOffset+P.byteLength))),M=new Uint8Array(U.length);return Ln(U),Pn(U,M),new DataView(M.buffer)}case"ZIPS_COMPRESSION":{const U=En(P),M=new Uint8Array(U.length);return Ln(U),Pn(U,M),new DataView(M.buffer)}default:throw new Error("THREE.EXRLoader: "+v+" is unsupported for deep data")}}function ko(){const l=this,g=l.chunkOffsets,y=l.width,v=l.height,P=l.deepChannels,U=Ze.compression,M=l.multiPart,V=l.decodeChannels,F=l.outputChannels,H=l.byteArray instanceof Uint16Array;let j=-1;for(let Z=0;Z<P.length;Z++)if(P[Z].name==="A"){j=Z;break}for(let Z=0;Z<g.length;Z++){const G={value:g[Z]};M&&(G.value+=4);const Y=qe(l.viewer,G)-Ze.dataWindow.yMin,J=ke(l.viewer,G),X=ke(l.viewer,G);ke(l.viewer,G);const $=Di(l.array,G.value,J,U);if(G.value+=J,$===null)continue;const ie=new Uint32Array(y);for(let se=0;se<y;se++)ie[se]=$.getUint32(se*4,!0);const he=ie[y-1];if(he===0){G.value+=X;continue}const ae=Di(l.array,G.value,X,U),de=[];let ne=0;for(let se=0;se<P.length;se++)de.push(ne),ne+=he*P[se].bytesPerSample;const ee=(v-1-Y)*l.outLineWidth;for(let se=0;se<y;se++){const Ee=se===0?0:ie[se-1],ce=ie[se]-Ee;if(ce===0)continue;const ue=new Float32Array(F);let ve=0;for(let Se=0;Se<ce;Se++){const pt=Ee+Se,Vt=1-ve;if(Vt<=0)break;let cn=1;if(j>=0){const mt=P[j].bytesPerSample,Dt=de[j]+pt*mt;cn=mt===2?Q(ae.getUint16(Dt,!0)):ae.getFloat32(Dt,!0)}for(let mt=0;mt<P.length;mt++){const Dt=P[mt],Bn=V[Dt.name];if(Bn===void 0)continue;const zn=Dt.bytesPerSample,Un=de[mt]+pt*zn,ln=zn===2?Q(ae.getUint16(Un,!0)):ae.getFloat32(Un,!0);ue[Bn]+=ln*Vt}ve+=cn*Vt}V.A!==void 0&&(ue[V.A]=ve);const et=ee+se*F;for(let Se=0;Se<F;Se++)l.byteArray[et+Se]=H?p.DataUtils.toHalfFloat(ue[Se]):ue[Se]}}}function Ni(l,g,y){const v={};let P=!1;for(;;){const U=Dn(g,y);if(U==="")break;P=!0;const M=Dn(g,y),V=Je(l,y),F=Io(l,g,y,M,V);F===void 0?console.warn(`THREE.EXRLoader: Skipped unknown header attribute type '${M}'.`):v[U]=F}return P?v:null}function Fo(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),P=l.getUint8(5),U={singleTile:!!(P&2),longName:!!(P&4),deepFormat:!!(P&8),multiPart:!!(P&16)};y.value=8;const M=[];if(U.multiPart){for(;;){const V=Ni(l,g,y);if(V===null)break;V.version=v,V.spec=U,M.push(V)}if(M.length===0)throw new Error("THREE.EXRLoader: No valid part headers found.")}else{const V=Ni(l,g,y);V.version=v,V.spec=U,M.push(V)}return M}function Bo(l,g,y,v,P,U){const M={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":M.blockHeight=1,M.uncompress=On;break;case"RLE_COMPRESSION":M.blockHeight=1,M.uncompress=uo;break;case"ZIPS_COMPRESSION":M.blockHeight=1,M.uncompress=Ms;break;case"ZIP_COMPRESSION":M.blockHeight=16,M.uncompress=Ms;break;case"PIZ_COMPRESSION":M.blockHeight=32,M.uncompress=fo;break;case"PXR24_COMPRESSION":M.blockHeight=16,M.uncompress=po;break;case"B44_COMPRESSION":case"B44A_COMPRESSION":M.blockHeight=32,M.uncompress=mo;break;case"DWAA_COMPRESSION":M.blockHeight=32,M.uncompress=Li;break;case"DWAB_COMPRESSION":M.blockHeight=256,M.uncompress=Li;break;default:throw new Error("THREE.EXRLoader: "+l.compression+" is unsupported")}const V={};for(const G of l.channels)switch(G.name){case"BY":case"RY":case"Y":case"R":case"G":case"B":case"A":V[G.name]=!0,M.type=G.pixelType}let F=!1,H=!1;if(V.Y&&V.RY&&V.BY)M.outputChannels=4,M.yCbCr=!0;else if(V.R&&V.G&&V.B)M.outputChannels=4;else if(V.Y)M.outputChannels=1;else throw new Error("THREE.EXRLoader: file contains unsupported data channels.");switch(M.outputChannels){case 4:U==p.RGBAFormat?(F=!V.A,M.format=p.RGBAFormat,M.colorSpace=p.LinearSRGBColorSpace,M.outputChannels=4,M.decodeChannels={R:0,G:1,B:2,A:3}):U==p.RGFormat?(M.format=p.RGFormat,M.colorSpace=p.LinearSRGBColorSpace,M.outputChannels=2,M.decodeChannels={R:0,G:1}):U==p.RedFormat?(M.format=p.RedFormat,M.colorSpace=p.LinearSRGBColorSpace,M.outputChannels=1,M.decodeChannels={R:0}):H=!0;break;case 1:U==p.RGBAFormat?(F=!0,M.format=p.RGBAFormat,M.colorSpace=p.LinearSRGBColorSpace,M.outputChannels=4,M.shouldExpand=!0,M.decodeChannels={Y:0}):U==p.RGFormat?(M.format=p.RGFormat,M.colorSpace=p.LinearSRGBColorSpace,M.outputChannels=2,M.shouldExpand=!0,M.decodeChannels={Y:0}):U==p.RedFormat?(M.format=p.RedFormat,M.colorSpace=p.LinearSRGBColorSpace,M.outputChannels=1,M.decodeChannels={Y:0}):H=!0;break;default:H=!0}if(H)throw new Error("THREE.EXRLoader: invalid output format for specified file.");if(M.yCbCr&&(M.format=p.RGBAFormat,M.outputChannels=4,M.decodeChannels={Y:0,RY:1,BY:2},F=!0),M.type==1)switch(P){case p.FloatType:M.getter=To;break;case p.HalfFloatType:M.getter=an;break}else if(M.type==2)switch(P){case p.FloatType:M.getter=We;break;case p.HalfFloatType:M.getter=wo}else throw new Error("THREE.EXRLoader: unsupported pixelType "+M.type+" for "+l.compression+".");M.columns=M.width;const j=M.width*M.height*M.outputChannels;switch(P){case p.FloatType:M.byteArray=new Float32Array(j),F&&M.byteArray.fill(1,0,j);break;case p.HalfFloatType:M.byteArray=new Uint16Array(j),F&&M.byteArray.fill(15360,0,j);break;default:console.error("THREE.EXRLoader: unsupported type: ",P);break}let Z=0;for(const G of l.channels)M.decodeChannels[G.name]!==void 0&&(M.channelByteOffsets[G.name]=Z),Z+=G.pixelType*2;if(M.totalBytes=Z,M.outLineWidth=M.width*M.outputChannels,l.spec.deepFormat){M.deepChannels=[];let G=0;for(const Y of l.channels){const J=Y.pixelType===0?4:Y.pixelType*2;M.deepChannels.push({name:Y.name,pixelType:Y.pixelType,bytesPerSample:J}),G+=J}M.deepBytesPerSample=G,M.chunkOffsets=l._chunkOffsets,M.multiPart=l.spec.multiPart,M.decode=ko.bind(M)}else if(l.spec.singleTile){M.blockHeight=l.tiles.ySize,M.blockWidth=l.tiles.xSize;const G=Po(l.tiles,M.width,M.height),Y=Oi(G,M.width,l.tiles.xSize,l.tiles.roundingMode),J=Oi(G,M.height,l.tiles.ySize,l.tiles.roundingMode);M.tileCount=Y[0]*J[0];for(let X=0;X<G;X++)for(let $=0;$<J[X];$++)for(let ie=0;ie<Y[X];ie++)ke(g,v);M.decode=Oo.bind(M)}else if(l.spec.multiPart)M.blockWidth=M.width,M.chunkOffsets=l._chunkOffsets,M.decode=No.bind(M);else{M.blockWidth=M.width;const G=Math.ceil(M.height/M.blockHeight);for(let Y=0;Y<G;Y++)ke(g,v);M.decode=Do.bind(M)}return M}const Nn={value:0},kn=new DataView(e),zo=new Uint8Array(e),Fn=Fo(kn,e,Nn),ki=Math.max(0,Math.min(this.part,Fn.length-1)),Ze=Fn[ki];if(Ze.spec.multiPart||Ze.spec.deepFormat)for(let l=0;l<Fn.length;l++){const g=Fn[l].chunkCount;if(l===ki){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=Bo(Ze,kn,zo,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,P=Q(l[v]),U=Q(l[v+1]),M=Q(l[v+2]),V=(1+U)*P,F=(1+M)*P,H=(P-V*.2126-F*.0722)/.7152;l[v]=p.DataUtils.toHalfFloat(Math.max(0,V)),l[v+1]=p.DataUtils.toHalfFloat(Math.max(0,H)),l[v+2]=p.DataUtils.toHalfFloat(Math.max(0,F))}else for(let y=0;y<g;y++){const v=y*4,P=l[v],U=l[v+1],M=l[v+2],V=(1+U)*P,F=(1+M)*P;l[v]=Math.max(0,V),l[v+1]=Math.max(0,(P-V*.2126-F*.0722)/.7152),l[v+2]=Math.max(0,F)}}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 Dl extends p.DataTextureLoader{constructor(e){super(e),this.type=p.HalfFloatType}parse(e){const o=function(C,N){switch(C){case 1:throw new Error("THREE.HDRLoader: Read Error: "+(N||""));case 2:throw new Error("THREE.HDRLoader: Write Error: "+(N||""));case 3:throw new Error("THREE.HDRLoader: Bad File Format: "+(N||""));default:case 4:throw new Error("THREE.HDRLoader: Memory Error: "+(N||""))}},h=function(C,N,I){N=N||1024;let D=C.pos,B=-1,W=0,te="",re=String.fromCharCode.apply(null,new Uint16Array(C.subarray(D,D+128)));for(;0>(B=re.indexOf(`
8
+ `))&&W<N&&D<C.byteLength;)te+=re,W+=re.length,D+=128,re=String.fromCharCode.apply(null,new Uint16Array(C.subarray(D,D+128)));return-1<B?(C.pos+=W+B+1,te+re.slice(0,B)):!1},f=function(C){const N=/^#\?(\S+)/,I=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,k=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,D=/^\s*FORMAT=(\S+)\s*$/,B=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,W={valid:0,string:"",comments:"",programtype:"RGBE",format:"",gamma:1,exposure:1,width:0,height:0};let te,re;for((C.pos>=C.byteLength||!(te=h(C)))&&o(1,"no header found"),(re=te.match(N))||o(3,"bad initial token"),W.valid|=1,W.programtype=re[1],W.string+=te+`
9
+ `;te=h(C),te!==!1;){if(W.string+=te+`
10
+ `,te.charAt(0)==="#"){W.comments+=te+`
11
+ `;continue}if((re=te.match(I))&&(W.gamma=parseFloat(re[1])),(re=te.match(k))&&(W.exposure=parseFloat(re[1])),(re=te.match(D))&&(W.valid|=2,W.format=re[1]),(re=te.match(B))&&(W.valid|=4,W.height=parseInt(re[1],10),W.width=parseInt(re[2],10)),W.valid&2&&W.valid&4)break}return W.valid&2||o(3,"missing format specifier"),W.valid&4||o(3,"missing image size specifier"),W},m=function(C,N,I){const k=N;if(k<8||k>32767||C[0]!==2||C[1]!==2||C[2]&128)return new Uint8Array(C);k!==(C[2]<<8|C[3])&&o(3,"wrong scanline width");const D=new Uint8Array(4*N*I);D.length||o(4,"unable to allocate buffer space");let B=0,W=0;const te=4*k,re=new Uint8Array(4),Ne=new Uint8Array(te);let ot=I;for(;ot>0&&W<C.byteLength;){W+4>C.byteLength&&o(1),re[0]=C[W++],re[1]=C[W++],re[2]=C[W++],re[3]=C[W++],(re[0]!=2||re[1]!=2||(re[2]<<8|re[3])!=k)&&o(3,"bad rgbe scanline format");let Re=0,ze;for(;Re<te&&W<C.byteLength;){ze=C[W++];const Ae=ze>128;if(Ae&&(ze-=128),(ze===0||Re+ze>te)&&o(3,"bad scanline data"),Ae){const ye=C[W++];for(let ft=0;ft<ze;ft++)Ne[Re++]=ye}else Ne.set(C.subarray(W,W+ze),Re),Re+=ze,W+=ze}const je=k;for(let Ae=0;Ae<je;Ae++){let ye=0;D[B]=Ne[Ae+ye],ye+=k,D[B+1]=Ne[Ae+ye],ye+=k,D[B+2]=Ne[Ae+ye],ye+=k,D[B+3]=Ne[Ae+ye],B+=4}ot--}return D},w=function(C,N,I,k){const D=C[N+3],B=Math.pow(2,D-128)/255;I[k+0]=C[N+0]*B,I[k+1]=C[N+1]*B,I[k+2]=C[N+2]*B,I[k+3]=1},_=function(C,N,I,k){const D=C[N+3],B=Math.pow(2,D-128)/255;I[k+0]=p.DataUtils.toHalfFloat(Math.min(C[N+0]*B,65504)),I[k+1]=p.DataUtils.toHalfFloat(Math.min(C[N+1]*B,65504)),I[k+2]=p.DataUtils.toHalfFloat(Math.min(C[N+2]*B,65504)),I[k+3]=p.DataUtils.toHalfFloat(1)},E=new Uint8Array(e);E.pos=0;const b=f(E),T=b.width,x=b.height,A=m(E.subarray(E.pos),T,x);let R,O,L;switch(this.type){case p.FloatType:L=A.length/4;const C=new Float32Array(L*4);for(let I=0;I<L;I++)w(A,I*4,C,I*4);R=C,O=p.FloatType;break;case p.HalfFloatType:L=A.length/4;const N=new Uint16Array(L*4);for(let I=0;I<L;I++)_(A,I*4,N,I*4);R=N,O=p.HalfFloatType;break;default:throw new Error("THREE.HDRLoader: Unsupported type: "+this.type)}return{width:T,height:x,data:R,header:b.string,gamma:b.gamma,exposure:b.exposure,type:O,colorSpace:p.LinearSRGBColorSpace,minFilter:p.LinearFilter,magFilter:p.LinearFilter,generateMipmaps:!1,flipY:!0}}setDataType(e){return this.type=e,this}}class Nl extends Dl{constructor(e){console.warn("RGBELoader has been deprecated. Please use HDRLoader instead."),super(e)}}class kl extends p.Scene{constructor(){super(),this.name="RoomEnvironment",this.position.y=-3.5;const e=new p.BoxGeometry;e.deleteAttribute("uv");const t=new p.MeshStandardMaterial({side:p.BackSide}),n=new p.MeshStandardMaterial,s=new p.PointLight(16777215,900,28,2);s.position.set(.418,16.199,.3),this.add(s);const r=new p.Mesh(e,t);r.position.set(-.757,13.219,.717),r.scale.set(31.713,28.305,28.591),this.add(r);const o=new p.InstancedMesh(e,n,6),a=new p.Object3D;a.position.set(-10.906,2.009,1.846),a.rotation.set(0,-.195,0),a.scale.set(2.328,7.905,4.651),a.updateMatrix(),o.setMatrixAt(0,a.matrix),a.position.set(-5.607,-.754,-.758),a.rotation.set(0,.994,0),a.scale.set(1.97,1.534,3.955),a.updateMatrix(),o.setMatrixAt(1,a.matrix),a.position.set(6.167,.857,7.803),a.rotation.set(0,.561,0),a.scale.set(3.927,6.285,3.687),a.updateMatrix(),o.setMatrixAt(2,a.matrix),a.position.set(-2.017,.018,6.124),a.rotation.set(0,.333,0),a.scale.set(2.002,4.566,2.064),a.updateMatrix(),o.setMatrixAt(3,a.matrix),a.position.set(2.291,-.756,-2.621),a.rotation.set(0,-.286,0),a.scale.set(1.546,1.552,1.496),a.updateMatrix(),o.setMatrixAt(4,a.matrix),a.position.set(-2.193,-.369,-5.547),a.rotation.set(0,.516,0),a.scale.set(3.875,3.487,2.986),a.updateMatrix(),o.setMatrixAt(5,a.matrix),this.add(o);const c=new p.Mesh(e,Jt(50));c.position.set(-16.116,14.37,8.208),c.scale.set(.1,2.428,2.739),this.add(c);const d=new p.Mesh(e,Jt(50));d.position.set(-16.109,18.021,-8.207),d.scale.set(.1,2.425,2.751),this.add(d);const u=new p.Mesh(e,Jt(17));u.position.set(14.904,12.198,-1.832),u.scale.set(.15,4.265,6.331),this.add(u);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 Fl{constructor(){this.pmremGenerator=null,this.loadedTextures=new Map,this.renderTargets=[],this.disposed=!1}async initialize(e){var t;try{const n=e.renderer;let s=n.renderer||((t=n.getThreeRenderer)==null?void 0:t.call(n));if(!s&&n.getDomElement){const r=n.getDomElement();if(r&&"parentElement"in r&&r.parentElement){const o=r.parentElement.renderer;o instanceof S.WebGLRenderer&&(s=o)}}return s?(this.pmremGenerator=new S.PMREMGenerator(s),this.pmremGenerator.compileEquirectangularShader(),z.ok(void 0)):z.err(new K("Could not access Three.js renderer",q.INITIALIZATION_FAILED))}catch(n){return z.err(new K("Failed to initialize environment service",q.INITIALIZATION_FAILED,{originalError:n}))}}async loadEnvironmentMap(e){var t;try{const n=this.loadedTextures.get(e);if(n)return z.ok(new en(n));const s=(t=e.split(".").pop())==null?void 0:t.toLowerCase();let r;switch(s){case"hdr":r=new Nl;break;case"exr":r=new Ol;break;case"jpg":case"jpeg":case"png":r=new S.TextureLoader;break;default:return z.err(new K(`Unsupported environment map format: ${s}`,q.UNSUPPORTED_FORMAT,{url:e,extension:s}))}const o=await new Promise((a,c)=>{r.load(e,d=>{a(d)},void 0,d=>c(d))});if(this.disposed)return o.dispose(),z.err(new K("Environment service was disposed during the load",q.INVALID_STATE,{url:e}));if(this.pmremGenerator){o.mapping=S.EquirectangularReflectionMapping;const a=this.pmremGenerator.fromEquirectangular(o);this.renderTargets.push(a);const c=a.texture;return this.loadedTextures.set(e,c),this.loadedTextures.set(e+"_original",o),z.ok(new en(c))}return this.loadedTextures.set(e,o),z.ok(new en(o))}catch(n){return z.err(new K("Failed to load environment map",q.TEXTURE_LOAD_FAILED,{url:e,originalError:n}))}}applyToScene(e,t,n){try{if(!(e instanceof St))return z.err(new K("Scene must be ThreeSceneAdapter",q.INVALID_PARAMETER));if(!(t instanceof en))return z.err(new K("Texture must be ThreeTextureAdapter",q.INVALID_PARAMETER));const s=e.getThreeScene(),r=t.getThreeTexture();if(s.environment=r,n&&(n.backgroundBlurriness!==void 0&&(s.backgroundBlurriness=n.backgroundBlurriness),n.backgroundIntensity!==void 0&&(s.backgroundIntensity=n.backgroundIntensity),n.environmentIntensity!==void 0&&(s.environmentIntensity=n.environmentIntensity)),r.mapping===S.CubeUVReflectionMapping){const a=Array.from(this.loadedTextures.entries()).find(([c,d])=>c.endsWith("_original")&&d.mapping===S.EquirectangularReflectionMapping);a&&(s.__originalEnvironmentTexture=a[1])}else r.mapping===S.EquirectangularReflectionMapping&&(s.__originalEnvironmentTexture=r);if((n==null?void 0:n.setBackground)??!0)if(r.mapping===S.EquirectangularReflectionMapping)s.background=r;else if(r.mapping===S.CubeUVReflectionMapping){const a=Array.from(this.loadedTextures.entries()).find(([c,d])=>c.endsWith("_original")&&d.mapping===S.EquirectangularReflectionMapping);a?s.background=a[1]:s.background=r}else s.background=r;return z.ok(void 0)}catch(s){return z.err(new K("Failed to apply environment to scene",q.SCENE_OPERATION_FAILED,{originalError:s}))}}getOriginalEnvironmentTexture(e){const t=this.loadedTextures.get(e+"_original");return t?new en(t):null}createStudioEnvironment(e={}){try{if(!this.pmremGenerator)return z.err(new K("Environment service not initialized",q.INITIALIZATION_FAILED));const t=new kl,n=this.pmremGenerator.fromScene(t);this.renderTargets.push(n);const s=n.texture;return t.dispose(),z.ok(new en(s))}catch(t){return z.err(new K("Failed to create studio environment",q.TEXTURE_LOAD_FAILED,{originalError:t}))}}dispose(){this.disposed=!0,this.loadedTextures.forEach(e=>e.dispose()),this.loadedTextures.clear(),this.renderTargets.forEach(e=>e.dispose()),this.renderTargets=[],this.pmremGenerator&&(this.pmremGenerator.dispose(),this.pmremGenerator=null)}}class en{constructor(e){this.texture=e}get id(){return this.texture.uuid}get image(){return this.texture.image}get needsUpdate(){return this.texture.needsUpdate}set needsUpdate(e){this.texture.needsUpdate=e}dispose(){this.texture.dispose()}getThreeTexture(){return this.texture}}class Bl{constructor(e){this.object=e,this.boundingBox=new S.Box3().setFromObject(this.object)}alignToFloor(){const e=this.calculateFloorOffset();this.applyOffset(e)}calculateFloorOffset(){const e=this.boundingBox.min.y,t=this.boundingBox.max.y-e,n=new S.Vector3;return t>0?n.y=-e:n.y=0,n}applyOffset(e){this.object.position.add(e)}}class zl{alignToFloor(e){try{let t=null;return"getThreeObject"in e&&typeof e.getThreeObject=="function"?t=e.getThreeObject():e instanceof S.Object3D&&(t=e),t?(new Bl(t).alignToFloor(),z.ok(void 0)):z.err(new K("Could not get Three.js object for floor alignment",q.INVALID_PARAMETER))}catch(t){return z.err(new K("Failed to align object to floor",q.OPERATION_FAILED,{originalError:t}))}}}const yr={touch:10,default:5};class Ul{constructor(){this.raycaster=new S.Raycaster,this.activePointers=new Set,this.options=null,this.pending=null,this.detach=null}initialize(e){this.dispose(),this.options=e;const{canvas:t}=e,n=o=>{this.activePointers.add(o.pointerId);try{t.setPointerCapture(o.pointerId)}catch{}if(this.activePointers.size>1||o.button!==0){this.pending=null;return}this.pending={pointerId:o.pointerId,x:o.clientX,y:o.clientY,threshold:o.pointerType==="touch"?yr.touch:yr.default}},s=o=>{this.activePointers.delete(o.pointerId);const a=this.pending;!a||a.pointerId!==o.pointerId||(this.pending=null,Math.hypot(o.clientX-a.x,o.clientY-a.y)>a.threshold)||this.pick(o.clientX,o.clientY)},r=o=>{this.activePointers.delete(o.pointerId),this.pending=null};t.addEventListener("pointerdown",n),t.addEventListener("pointerup",s),t.addEventListener("pointercancel",r),this.detach=()=>{t.removeEventListener("pointerdown",n),t.removeEventListener("pointerup",s),t.removeEventListener("pointercancel",r)}}pick(e,t){if(!this.options)return;const{canvas:n,camera:s,getPickRoot:r,onPick:o}=this.options,a=r(),c=zt(a),d=vn(s);if(!c||!d){o(null);return}const u=n.getBoundingClientRect();if(u.width===0||u.height===0){o(null);return}const h=new S.Vector2((e-u.left)/u.width*2-1,-((t-u.top)/u.height)*2+1);(this.options.bvh??!0)&&Dr(c),this.raycaster.setFromCamera(h,d),this.raycaster.firstHitOnly=!0;const f=this.raycaster.intersectObject(c,!0)[0];if(!f){o(null);return}o({object:new Oe(f.object),point:{x:f.point.x,y:f.point.y,z:f.point.z}})}dispose(){var e;(e=this.detach)==null||e.call(this),this.detach=null,this.options=null,this.pending=null,this.activePointers.clear()}}const Hl=.001,Er={visible:!1};class Vl{constructor(e){this.sources=e,this.anchor=new S.Vector3,this.projected=new S.Vector3,this.cameraPosition=new S.Vector3,this.toAnchor=new S.Vector3,this.raycaster=new S.Raycaster,this.lastCameraMatrix=new S.Matrix4,this.lastWidth=-1,this.lastHeight=-1,this.hasProjected=!1}invalidate(){this.hasProjected=!1}project(e,t){const n=vn(this.sources.camera),s=this.sources.getCanvas();if(!n||!s)return null;const r=s.clientWidth||s.width,o=s.clientHeight||s.height;return this.hasProjected&&r===this.lastWidth&&o===this.lastHeight&&this.lastCameraMatrix.equals(n.matrixWorld)?null:(this.lastCameraMatrix.copy(n.matrixWorld),this.lastWidth=r,this.lastHeight=o,this.hasProjected=!0,this.anchor.set(e.x,e.y,e.z),n.getWorldPosition(this.cameraPosition),this.projected.copy(this.anchor).applyMatrix4(n.matrixWorldInverse),this.projected.z>=0||t&&this.isOccluded(n)?Er:(this.projected.copy(this.anchor).project(n),{visible:!0,left:(this.projected.x+1)/2*r,top:(1-this.projected.y)/2*o}))}isOccluded(e){const t=zt(this.sources.getModel());if(!t)return!1;this.toAnchor.copy(this.anchor).sub(this.cameraPosition);const n=this.toAnchor.length();this.raycaster.set(this.cameraPosition,this.toAnchor.normalize()),this.raycaster.camera=e,this.raycaster.firstHitOnly=!0;const s=this.raycaster.intersectObject(t,!0)[0];return!!(s&&s.distance<n-Hl)}}class jl{createProjector(e){return new Vl(e)}}class Gl{constructor(){this.mixer=null,this.clips=[],this.activeActions=[],this.playing=!1,this.speed=1}attach(e){this.detach();const t=zt(e);if(!t)return;const n=Wl(t);n&&(this.clips=n.animations,this.mixer=new S.AnimationMixer(n),this.mixer.timeScale=this.speed)}getClipNames(){return this.clips.map(e=>e.name)}play(e){if(!this.mixer)return;if(!this.playing&&this.activeActions.length>0&&e===void 0){this.playing=!0;return}const t=e?this.clips.filter(s=>s.name===e):this.clips;if(t.length===0)return;const n=this.mixer;n.stopAllAction(),this.activeActions=t.map(s=>{const r=n.clipAction(s);return r.play(),r}),this.playing=!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 Wl(i){let e=null;return i.traverse(t=>{var n;!e&&(((n=t.animations)==null?void 0:n.length)??0)>0&&(e=t)}),e}var An=(i=>(i.MapControls="MapControls",i.OrbitControls="OrbitControls",i))(An||{});class Zl{static convertRendererOptions(e){const t={antialias:e.antialias,alpha:e.alpha,premultipliedAlpha:e.premultipliedAlpha,preserveDrawingBuffer:e.preserveDrawingBuffer,powerPreference:e.powerPreference,pixelRatio:e.pixelRatio};return(e.shadowMapEnabled!==void 0||e.shadowMapType!==void 0)&&(t.shadowMap={enabled:e.shadowMapEnabled??!0,type:this.convertShadowMapType(e.shadowMapType)}),(e.toneMapping!==void 0||e.toneMappingExposure!==void 0)&&(t.toneMapping={type:this.convertToneMappingType(e.toneMapping),exposure:e.toneMappingExposure??1}),t}static convertShadowMapType(e){if(typeof e=="number"){if(e===S.BasicShadowMap)return"basic";if(e===S.PCFShadowMap)return"pcf";if(e===S.PCFSoftShadowMap)return"pcfsoft";if(e===S.VSMShadowMap)return"vsm"}return typeof e=="string"?e:void 0}static convertToneMappingType(e){if(typeof e=="number"){if(e===S.NoToneMapping)return"none";if(e===S.LinearToneMapping)return"linear";if(e===S.ReinhardToneMapping)return"reinhard";if(e===S.CineonToneMapping)return"cineon";if(e===S.ACESFilmicToneMapping)return"aces"}return typeof e=="string"?e:"aces"}}class Kl{static createViewer(e,t){var T,x,A;const n=new lc(e),s=new St,r=this.createCamera(t),o=this.createControls(r.getThreeCamera(),e,t),a=new Xl().createDefaultLoader({renderer:n.getThreeRenderer()??void 0,bvh:(T=t.selection)==null?void 0:T.bvh,...t.loaders}),c=new gl,d=new Fl;let u;(((x=t.pathTracing)==null?void 0:x.enabled)??!1)&&(u=new yl);const f=new zl,m=new Ul,w=new jl,_=new Gl,E=Zl.convertRendererOptions(t.renderer||{});(t.replaceWithScreenshotOnComplete||(A=t.pathTracing)!=null&&A.enabled)&&(E.preserveDrawingBuffer=!0);const b={renderer:n,scene:s,camera:r,controls:o,modelLoader:a,options:t,rendererOptions:E,sceneSetupService:c,environmentService:d,pathTracingService:u,floorAlignmentService:f,selectionService:m,anchorProjectionService:w,animationService:_};return new ia(b)}static createCamera(e){const n=e.camera||{},s=n.fov||n.cameraFov||75,r=n.near||n.cameraNear||.1,o=n.far||n.cameraFar||1e5,a=n.position||n.cameraPosition,c=n.target||n.cameraTarget,d=Si.create(s,1,r,o);return a&&d.position.set(a[0],a[1],a[2]),c&&d.lookAt({x:c[0],y:c[1],z:c[2],set:()=>{},copy:()=>{},add:()=>{},multiply:()=>{},normalize:()=>{},length:()=>0}),d}static createControls(e,t,n){const s=n.controls||{},r=s.type||An.OrbitControls;let o;r===An.MapControls?o=new hl(e,t):o=new ll(e,t),o.enabled=s.enabled??!0,o.enableDamping=s.enableDamping??!0,o.dampingFactor=s.dampingFactor??.25,o.enableZoom=s.enableZoom??!0,o.enableRotate=s.enableRotate??!0,o.enablePan=s.enablePan??!0,o.autoRotate=s.autoRotate??!1,s.autoRotateSpeed!==void 0&&(o.autoRotateSpeed=s.autoRotateSpeed),s.minDistance!==void 0&&(o.minDistance=s.minDistance),s.maxDistance!==void 0&&(o.maxDistance=s.maxDistance),s.minPolarAngle!==void 0&&(o.minPolarAngle=s.minPolarAngle),s.maxPolarAngle!==void 0&&(o.maxPolarAngle=s.maxPolarAngle);const c=n.camera||{},d=c.target||c.cameraTarget;return d&&o.target&&(o.target.set(d[0],d[1],d[2]),o.update()),o}}class Xl extends dr{createDefaultLoader(e={}){return dr.createLoader("model.glb",e)}}const Yl=["toneMappingExposure"],ql=["environmentIntensity"],$l=["autoRotate","autoRotateSpeed"];function qr(i){var t,n,s,r,o,a,c,d,u,h;const e={backgroundColor:i.backgroundColor};return((t=i.renderer)==null?void 0:t.toneMappingExposure)!==void 0&&(e.renderer={toneMappingExposure:i.renderer.toneMappingExposure}),((n=i.environment)==null?void 0:n.environmentIntensity)!==void 0&&(e.environment={environmentIntensity:i.environment.environmentIntensity}),(((s=i.controls)==null?void 0:s.autoRotate)!==void 0||((r=i.controls)==null?void 0:r.autoRotateSpeed)!==void 0)&&(e.controls={autoRotate:(o=i.controls)==null?void 0:o.autoRotate,autoRotateSpeed:(a=i.controls)==null?void 0:a.autoRotateSpeed}),(((c=i.animations)==null?void 0:c.autoplay)!==void 0||((d=i.animations)==null?void 0:d.speed)!==void 0)&&(e.animations={autoplay:(u=i.animations)==null?void 0:u.autoplay,speed:(h=i.animations)==null?void 0:h.speed}),e}const ys={staticScene:!1,backgroundColor:"#f0f0f7",replaceWithScreenshotOnComplete:!0,animationLoop:null,units:"meters",pathTracing:{enabled:!1,maxSamples:16,bounces:16,transmissiveBounces:4,renderScale:.8,lowResScale:.25,dynamicLowRes:!0},camera:{position:[60,60,60],target:[0,0,0],fov:45,near:.1,far:1e5,autoFitToObject:!0},environment:{backgroundIntensity:1,environmentIntensity:.7},lighting:{ambientLight:{color:"#404040",intensity:.3},hemisphereLight:{skyColor:"#ffffbb",groundColor:"#080820",intensity:.3},directionalLight:{color:"#ffffff",intensity:2,position:[40,90,40],castShadow:!0,shadow:{mapSize:{width:4096,height:4096},camera:{near:.5,far:200,left:-50,right:50,top:50,bottom:-50},bias:-1e-4,radius:14}}},renderer:{antialias:!0,alpha:!1,shadowMapEnabled:!0,pixelRatio:typeof window<"u"?window.devicePixelRatio:1,shadowMapType:1,toneMapping:6,toneMappingExposure:1.1},controls:{type:An.OrbitControls,enabled:!0,enableDamping:!0,dampingFactor:.25,enableZoom:!0,enableRotate:!0,enablePan:!0},helpers:{grid:{type:"hexagonal_glass",size:20,divisions:20,colorGrid:"#a8a8a2",opacity:.5,styleOptions:{tileSize:.1173,metalness:0,roughness:.9,transmission:0}},axes:!1,stats:!1,gizmo:!1,studioEnvironment:!0,darkStudioMode:!1}},xi={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 $r(i){return i?xi[i]:{}}function mi(i,e){return ps(ps(i,$r(e.preset)),e)}const Zs=(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 Ql(i){const e=oe.useMemo(()=>{var s;return JSON.stringify({pathTracing:i.pathTracing,staticScene:i.staticScene,renderer:Zs(i.renderer,...Yl),camera:i.camera,controls:Zs(i.controls,...$l),environment:Zs(i.environment,...ql),lighting:i.lighting,helpers:i.helpers,rendering:i.rendering,replaceWithScreenshotOnComplete:i.replaceWithScreenshotOnComplete,loaders:i.loaders,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.selection]),t=oe.useMemo(()=>{const s=mi(ys,i);return JSON.stringify(qr(s))},[i.preset,i.backgroundColor,i.renderer,i.environment,i.controls,i.animations]);return{options:oe.useMemo(()=>i,[e,t]),structuralKey:e,runtimeKey:t}}function Jl(i,e){const t=oe.useRef(null),[n,s]=oe.useState(!1),{options:r,structuralKey:o,runtimeKey:a}=Ql(e);oe.useEffect(()=>{if(!i.current||t.current)return;const d=mi(ys,r),u=Kl.createViewer(i.current,d);t.current=u;let h=!1;return u.initialize().then(f=>{h||(f.ok?s(!0):console.error("Failed to initialize viewer:",f.error))}),()=>{h=!0,u.dispose(),t.current=null,s(!1)}},[i,o]),oe.useEffect(()=>{if(!t.current||!n)return;const d=mi(ys,r);t.current.updateOptions(qr(d))},[a,n]);const c=oe.useRef({width:0,height:0});return oe.useEffect(()=>{if(!t.current||!i.current)return;let d=null;const u=m=>{if(i.current&&t.current){const w=i.current.parentElement||i.current;let{clientWidth:_,clientHeight:E}=w;if(m&&m[0]){const{width:b,height:T}=m[0].contentRect;_=Math.floor(b),E=Math.floor(T)}if(c.current.width===_&&c.current.height===E)return;d!==null&&cancelAnimationFrame(d),d=requestAnimationFrame(()=>{t.current&&i.current&&(t.current.resize(_,E),c.current={width:_,height:E})})}};u();const h=()=>u();window.addEventListener("resize",h);let f=null;return typeof ResizeObserver<"u"&&i.current.parentElement&&(f=new ResizeObserver(u),f.observe(i.current.parentElement)),()=>{window.removeEventListener("resize",h),f==null||f.disconnect(),d!==null&&cancelAnimationFrame(d)}},[n,i]),{viewer:t.current,isInitialized:n}}function eh(i,e){const t=oe.useRef(e);t.current=e,oe.useEffect(()=>{if(!i)return;const n=i.getEvents(),s=[],r=o=>{const a=c=>{var d,u;(u=(d=t.current)[o])==null||u.call(d,c)};return n.on(o,a),()=>n.off(o,a)};return Object.keys(e).forEach(o=>{e[o]&&s.push(r(o))}),()=>{s.forEach(o=>o())}},[i])}function th(i,e){const[t,n]=oe.useState(null),s=oe.useRef(new Set);oe.useEffect(()=>{if(i!==void 0&&s.current.has(i)){s.current.delete(i),n(c=>c===i?null:c);return}s.current.clear(),n(null)},[i]);const r=!!(e!=null&&e.presets);oe.useEffect(()=>{r||(s.current.clear(),n(null))},[r]);const o=e==null?void 0:e.onPresetChange,a=oe.useCallback(c=>{n(c),o&&(s.current.add(c),o(c))},[o]);return{activePreset:t??i,pickerEnabled:r,selectPreset:a}}function nh(i,e,t,n,s){return oe.useMemo(()=>{var d,u,h;const r=i.preset!==e,o=t===!0&&((d=i.pathTracing)==null?void 0:d.enabled)===void 0,a=n!==void 0&&((u=i.controls)==null?void 0:u.autoRotate)===void 0,c=s!==void 0&&((h=i.animations)==null?void 0:h.autoplay)===void 0;return!r&&!o&&!a&&!c?i:{...i,...r?{preset:e}:{},...o?{pathTracing:{...i.pathTracing,enabled:!0}}:{},...a?{controls:{...i.controls,autoRotate:n}}:{},...c?{animations:{...i.animations,autoplay:s}}:{}}},[i,e,t,n,s])}function sh(i,e,t){const n=oe.useMemo(()=>{if(typeof t=="string")return t;if(t)return`object-${t.uuid||"no-uuid"}`},[t]),[s,r]=oe.useState(()=>({status:t?"loading":"idle"}));return oe.useEffect(()=>{r({status:t?"loading":"idle"})},[n]),oe.useEffect(()=>{if(!i||!e||!t)return;let o=!0;const a=typeof t=="string"?t:new Oe(t);return i.loadModel(a).then(c=>{o&&(c.ok?r({status:"loaded"}):(r({status:"error",error:c.error.message}),console.error("Failed to load model:",c.error)))}),()=>{o=!1}},[i,e,n]),s}class Ks{static toThreeObject(e){const t=zt(e);if(t)return t;const n=new S.Object3D;return n.position.set(e.position.x,e.position.y,e.position.z),n.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z),n.scale.set(e.scale.x,e.scale.y,e.scale.z),n}static toThreeCamera(e){return vn(e)??new S.PerspectiveCamera}static toThreeControls(e){return bi(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 ih(i){const e=oe.useRef(new ws),t=oe.useMemo(()=>({"model:loading":n=>e.current.emit("model:loading",n),"model:loaded":n=>e.current.emit("model:loaded",Ks.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",Ks.convertControlsChange(n)),"object:selected":n=>e.current.emit("object:selected",Ks.convertObjectSelected(n)),error:n=>e.current.emit("error",n)}),[]);return eh(i,t),e.current}const Qr=oe.createContext(null);function rh({viewer:i,canvasRef:e,children:t}){const n=oe.useMemo(()=>({viewer:i,canvasRef:e}),[i,e]);return me.jsx(Qr.Provider,{value:n,children:t})}function Jr(){const i=oe.useContext(Qr);if(!i)throw new Error("useViewerContext must be used within ViewerProvider");return i}function oh(){const{canvasRef:i}=Jr();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 ah=(i,e,t,n,s,r)=>{const o=performance.now(),a=()=>{const c=performance.now()-o,d=Math.min(c/s,1);i.position.lerpVectors(t,n,d),e==null||e.update(),r(),d<1&&requestAnimationFrame(a)};requestAnimationFrame(a)},wr={type:"change"},Ai={type:"start"},eo={type:"end"},as=new p.Ray,Tr=new p.Plane,ch=Math.cos(70*p.MathUtils.DEG2RAD),Pe=new p.Vector3,Qe=2*Math.PI,Te={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},Xs=1e-6;class to 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=hh.bind(this),this._onPointerDown=lh.bind(this),this._onPointerUp=uh.bind(this),this._onContextMenu=Eh.bind(this),this._onMouseWheel=ph.bind(this),this._onKeyDown=mh.bind(this),this._onTouchStart=gh.bind(this),this._onTouchMove=yh.bind(this),this._onMouseDown=dh.bind(this),this._onMouseMove=fh.bind(this),this._interceptControlDown=wh.bind(this),this._interceptControlUp=Th.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(wr),this.update(),this.state=Te.NONE}update(e=null){const t=this.object.position;Pe.copy(t).sub(this.target),Pe.applyQuaternion(this._quat),this._spherical.setFromVector3(Pe),this.autoRotate&&this.state===Te.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let n=this.minAzimuthAngle,s=this.maxAzimuthAngle;isFinite(n)&&isFinite(s)&&(n<-Math.PI?n+=Qe:n>Math.PI&&(n-=Qe),s<-Math.PI?s+=Qe:s>Math.PI&&(s-=Qe),n<=s?this._spherical.theta=Math.max(n,Math.min(s,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+s)/2?Math.max(n,this._spherical.theta):Math.min(s,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let r=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const o=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),r=o!=this._spherical.radius}if(Pe.setFromSpherical(this._spherical),Pe.applyQuaternion(this._quatInverse),t.copy(this.target).add(Pe),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let o=null;if(this.object.isPerspectiveCamera){const a=Pe.length();o=this._clampDistance(a*this._scale);const c=a-o;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),r=!!c}else if(this.object.isOrthographicCamera){const a=new p.Vector3(this._mouse.x,this._mouse.y,0);a.unproject(this.object);const c=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=c!==this.object.zoom;const d=new p.Vector3(this._mouse.x,this._mouse.y,0);d.unproject(this.object),this.object.position.sub(d).add(a),this.object.updateMatrixWorld(),o=Pe.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;o!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(o).add(this.object.position):(as.origin.copy(this.object.position),as.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(as.direction))<ch?this.object.lookAt(this.target):(Tr.setFromNormalAndCoplanarPoint(this.object.up,this.target),as.intersectPlane(Tr,this.target))))}else if(this.object.isOrthographicCamera){const o=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),o!==this.object.zoom&&(this.object.updateProjectionMatrix(),r=!0)}return this._scale=1,this._performCursorZoom=!1,r||this._lastPosition.distanceToSquared(this.object.position)>Xs||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Xs||this._lastTargetPosition.distanceToSquared(this.target)>Xs?(this.dispatchEvent(wr),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?Qe/60*this.autoRotateSpeed*e:Qe/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){Pe.setFromMatrixColumn(t,0),Pe.multiplyScalar(-e),this._panOffset.add(Pe)}_panUp(e,t){this.screenSpacePanning===!0?Pe.setFromMatrixColumn(t,1):(Pe.setFromMatrixColumn(t,0),Pe.crossVectors(this.object.up,Pe)),Pe.multiplyScalar(e),this._panOffset.add(Pe)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;Pe.copy(s).sub(this.target);let r=Pe.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/n.clientHeight,this.object.matrix),this._panUp(2*t*r/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const n=this.domElement.getBoundingClientRect(),s=e-n.left,r=t-n.top,o=n.width,a=n.height;this._mouse.x=s/o*2-1,this._mouse.y=-(r/a)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Qe*this._rotateDelta.x/t.clientHeight),this._rotateUp(Qe*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(Qe*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-Qe*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(Qe*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-Qe*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._rotateStart.set(n,s)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panStart.set(n,s)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,r=Math.sqrt(n*n+s*s);this._dollyStart.set(0,r)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),s=.5*(e.pageX+n.x),r=.5*(e.pageY+n.y);this._rotateEnd.set(s,r)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Qe*this._rotateDelta.x/t.clientHeight),this._rotateUp(Qe*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panEnd.set(n,s)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,r=Math.sqrt(n*n+s*s);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const o=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(o,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new p.Vector2,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(n.deltaY*=10),n}}function lh(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 hh(i){this.enabled!==!1&&(i.pointerType==="touch"?this._onTouchMove(i):this._onMouseMove(i))}function uh(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(eo),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 dh(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(Ai)}function fh(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 ph(i){this.enabled===!1||this.enableZoom===!1||this.state!==Te.NONE||(i.preventDefault(),this.dispatchEvent(Ai),this._handleMouseWheel(this._customWheelEvent(i)),this.dispatchEvent(eo))}function mh(i){this.enabled!==!1&&this._handleKeyDown(i)}function gh(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(Ai)}function yh(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 Eh(i){this.enabled!==!1&&i.preventDefault()}function wh(i){i.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function Th(i){i.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}class Sh extends to{constructor(e,t){super(e,t),this.screenSpacePanning=!1,this.mouseButtons={LEFT:p.MOUSE.PAN,MIDDLE:p.MOUSE.DOLLY,RIGHT:p.MOUSE.ROTATE},this.touches={ONE:p.TOUCH.PAN,TWO:p.TOUCH.DOLLY_ROTATE}}}const fe={CUBE_SIZE:1.8,EDGE_SECTION_SIZE:.35,FACE_THICKNESS:.35,CANVAS_SIZE:256,FONT_SIZE:"62px",TEXT_COLOR:"#000000",TEXT_ALIGN:"center",TEXT_BASELINE:"middle",FACE_COLOR:"#EFF3F2",EDGE_COLOR:"#EFF3F2",CORNER_COLOR:"#EFF3F2",LINE_COLOR:0};var It=(i=>(i.FRONT="FRONT",i.BACK="BACK",i.RIGHT="RIGHT",i.LEFT="LEFT",i.TOP="TOP",i.BOTTOM="BOTTOM",i))(It||{});new S.Vector3(0,1,0);const Mn="rotation-arrows-name",gi="left-rotation-arrow-name",Es="right-rotation-arrow-name",_h="gizmo-group-name",bh=[Es,gi],fs={GIZMO_DISTANCE:8,DEFAULT_UP:new S.Vector3(0,1,0),FORWARD:new S.Vector3(0,0,-1)},Ys=i=>fs.FORWARD.clone().applyQuaternion(i),Sr=(i,e,t=new S.Vector3)=>t.clone().add(i.multiplyScalar(-e));class xh{constructor(e,t=Mn){this.gizmoScene=e,this.gizmoArrowsName=t}syncGizmoWithMain(e,t){e.quaternion.copy(t.quaternion),e.up.copy(t.up);const n=Ys(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(),r=e.position.distanceTo(s),o=e.camera instanceof S.PerspectiveCamera;n instanceof Sh&&!o?this.syncMapControls(e,t,s,r):this.syncOrbitControls(e,t,s,r),e.camera.updateMatrix(),e.camera.updateMatrixWorld(!0),n.update()}syncMapControls(e,t,n,s){const r=e.position.y-n.y,o=Ys(t.quaternion);o.y=0,o.normalize();const a=n.clone();a.y+=r,a.add(o.multiplyScalar(-s)),e.position.copy(a),e.up.copy(fs.DEFAULT_UP),e.camera.lookAt(n)}syncOrbitControls(e,t,n,s){const r=Ys(t.quaternion),o=fs.DEFAULT_UP.clone().applyQuaternion(t.quaternion),a=Sr(r,s,n);e.position.copy(a),e.up.copy(o),e.camera.lookAt(n)}}const no=i=>new xh(i),_r=(i,e,t)=>{no(t).syncGizmoWithMain({camera:i,position:i.position,quaternion:i.quaternion,up:i.up},{camera:e,position:e.position,quaternion:e.quaternion,up:e.up})},Ah=(i,e,t)=>{no(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)},Mh=()=>{try{const i=document.createElement("canvas");return!!(window.WebGLRenderingContext&&(i.getContext("webgl")||i.getContext("experimental-webgl")))}catch{return!1}},Rh=()=>Mh()?new S.WebGLRenderer({alpha:!0,antialias:!1}):(console.error("WebGL is not supported in this environment."),null),vh=i=>{const e=new S.AmbientLight(16777215,1);i.add(e);const t=new S.DirectionalLight(16777215,1);t.position.set(5,10,5),i.add(t);const n=new S.DirectionalLight(16777215,1);n.position.set(-5,-10,5),i.add(n);const s=new S.PointLight(16777215,1,100);s.position.set(0,0,5),i.add(s),t.castShadow=!1,n.castShadow=!1,s.castShadow=!1};class Ch{static createTextTexture(e){const t=document.createElement("canvas"),n=t.getContext("2d");t.width=fe.CANVAS_SIZE,t.height=fe.CANVAS_SIZE,n&&(n.clearRect(0,0,t.width,t.height),n.font=`${fe.FONT_SIZE} Arial`,n.fillStyle=fe.TEXT_COLOR,n.textAlign=fe.TEXT_ALIGN,n.textBaseline=fe.TEXT_BASELINE,n.fillText(e,t.width/2,t.height/2));const s=new S.CanvasTexture(t);return s.needsUpdate=!0,s}}class cs{static createWireframe([e,t,n]){const s=new S.BoxGeometry(e,t,n),r=new S.EdgesGeometry(s),o=new S.LineBasicMaterial({color:fe.LINE_COLOR}),a=new S.LineSegments(r,o);return a.name="Wireframe",a}static createEdgeBox(e,t,n){const s=fe.CUBE_SIZE-fe.EDGE_SECTION_SIZE,r={x:fe.EDGE_SECTION_SIZE,y:fe.EDGE_SECTION_SIZE,z:fe.EDGE_SECTION_SIZE};r[t]=s;const o=new S.BoxGeometry(r.x,r.y,r.z),a=new S.MeshStandardMaterial({color:fe.EDGE_COLOR}),c=new S.Mesh(o,a);return c.position.copy(e),c.name=`Edge Box ${n}`,c}static createCornerCube(e,t){const n=new S.BoxGeometry(fe.EDGE_SECTION_SIZE,fe.EDGE_SECTION_SIZE,fe.EDGE_SECTION_SIZE),s=new S.MeshStandardMaterial({color:fe.CORNER_COLOR}),r=new S.Mesh(n,s);return r.position.copy(e),r.name=`Corner Cube ${t}`,r}static createFace(e,t,n){const s=new S.Group,r=new S.BoxGeometry(fe.CUBE_SIZE-fe.EDGE_SECTION_SIZE,fe.CUBE_SIZE-fe.EDGE_SECTION_SIZE,fe.FACE_THICKNESS),o=new S.MeshStandardMaterial({color:fe.FACE_COLOR}),a=new S.Mesh(r,o);a.name=`Face Box ${n}`,s.add(a);const c=new S.PlaneGeometry(fe.CUBE_SIZE-fe.EDGE_SECTION_SIZE,fe.CUBE_SIZE-fe.EDGE_SECTION_SIZE),d=new S.MeshStandardMaterial({map:Ch.createTextTexture(n),transparent:!0,depthWrite:!1}),u=new S.Mesh(c,d);return u.position.set(0,0,fe.FACE_THICKNESS/2+.01),s.add(u),s.position.copy(e),s.rotation.copy(t),s}}const Ih=(i,e)=>{const t=document.createElement("canvas");t.width=64,t.height=64;const n=t.getContext("2d");n.fillStyle="rgba(0, 0, 0, 0)",n.fillRect(0,0,t.width,t.height),n.font="Bold 48px Arial",n.fillStyle=`#${e.toString(16).padStart(6,"0")}`,n.textAlign="center",n.textBaseline="middle",n.fillText(i,t.width/2,t.height/2);const s=new S.CanvasTexture(t),r=new S.SpriteMaterial({map:s}),o=new S.Sprite(r);return o.scale.set(.5,.5,.5),o};class Lh{constructor(e){this.hoveredObject=null,this.originalColor=null,this.config=e}get vectorToCube(){var e;return(e=this.hoveredObject)==null?void 0:e.userData.vectorToCube}getInitialRotation(){switch(this.config.initialFace){case It.BACK:return new S.Euler(0,Math.PI,0);case It.RIGHT:return new S.Euler(0,-Math.PI/2,0);case It.LEFT:return new S.Euler(0,Math.PI/2,0);case It.TOP:return new S.Euler(Math.PI/2,0,0);case It.BOTTOM:return new S.Euler(-Math.PI/2,0,0);case It.FRONT:default:return new S.Euler(0,0,0)}}createWireframe(){const e=fe.CUBE_SIZE+fe.EDGE_SECTION_SIZE,t=cs.createWireframe([e,e,e]);return t.userData.gizmoCube=this,t}createEdgeBox(e,t,n){const s=cs.createEdgeBox(e,t,n);return s.userData.gizmoCube=this,s}createCornerCube(e,t){const n=cs.createCornerCube(e,t);return n.userData.gizmoCube=this,n}createFace(e,t,n){const s=cs.createFace(e,t,n),r=s.getObjectByName(`Face Box ${n}`);return r.userData.gizmoCube=this,s}createEdges(e){const t=fe.CUBE_SIZE/2;[{axis:"x",pos:new S.Vector3(0,t,-t)},{axis:"x",pos:new S.Vector3(0,t,t)},{axis:"x",pos:new S.Vector3(0,-t,-t)},{axis:"x",pos:new S.Vector3(0,-t,t)},{axis:"y",pos:new S.Vector3(t,0,-t)},{axis:"y",pos:new S.Vector3(t,0,t)},{axis:"y",pos:new S.Vector3(-t,0,-t)},{axis:"y",pos:new S.Vector3(-t,0,t)},{axis:"z",pos:new S.Vector3(t,t,0)},{axis:"z",pos:new S.Vector3(t,-t,0)},{axis:"z",pos:new S.Vector3(-t,t,0)},{axis:"z",pos:new S.Vector3(-t,-t,0)}].forEach(({axis:n,pos:s},r)=>{const o=this.createEdgeBox(s,n,r+1);e.add(o)})}createCorners(e){const t=fe.CUBE_SIZE/2;[new S.Vector3(-t,-t,-t),new S.Vector3(-t,-t,t),new S.Vector3(-t,t,-t),new S.Vector3(-t,t,t),new S.Vector3(t,-t,-t),new S.Vector3(t,-t,t),new S.Vector3(t,t,-t),new S.Vector3(t,t,t)].forEach((n,s)=>{const r=this.createCornerCube(n,s+1);e.add(r)})}createFaces(e){const t=fe.CUBE_SIZE/2;[{pos:new S.Vector3(0,0,t),rotation:new S.Euler(0,0,0),label:"FRONT"},{pos:new S.Vector3(0,0,-t),rotation:new S.Euler(0,Math.PI,0),label:"BACK"},{pos:new S.Vector3(t,0,0),rotation:new S.Euler(0,Math.PI/2,0),label:"RIGHT"},{pos:new S.Vector3(-t,0,0),rotation:new S.Euler(0,-Math.PI/2,0),label:"LEFT"},{pos:new S.Vector3(0,t,0),rotation:new S.Euler(-Math.PI/2,0,0),label:"TOP"},{pos:new S.Vector3(0,-t,0),rotation:new S.Euler(Math.PI/2,0,0),label:"BOTTOM"}].forEach(({pos:n,rotation:s,label:r})=>{const o=this.createFace(n,s,r);e.add(o)})}createAxis(e){const{color:t,direction:n,length:s,origin:r,lineWidth:o,label:a}=e,c=new S.Group,d=o/2,u=new S.CylinderGeometry(d,d,s,32),h=new S.MeshBasicMaterial({color:t}),f=new S.Mesh(u,h);if(f.position.copy(r).add(n.clone().multiplyScalar(s/2)),!n.equals(new S.Vector3(0,1,0))){const w=new S.Vector3(0,1,0).cross(n).normalize(),_=Math.acos(new S.Vector3(0,1,0).dot(n));f.setRotationFromAxisAngle(w,_)}c.add(f);const m=Ih(a,t);return m.position.copy(r).add(n.clone().multiplyScalar(s+.1)),c.add(m),c}createCoordinateAxes(){const e=new S.Group,t=fe.CUBE_SIZE,n=fe.EDGE_SECTION_SIZE,s=-1.075,r=a=>{const c=new S.Vector3(1,1,1);return new S.Vector3(a,a,a).add(c.clone().normalize().negate().multiplyScalar(.04))},o=t+1.25*n;return[{color:16711680,direction:new S.Vector3(1,0,0),length:o,origin:r(s),lineWidth:.04,label:"X"},{color:65280,direction:new S.Vector3(0,1,0),length:o,origin:r(s),lineWidth:.04,label:"Y"},{color:255,direction:new S.Vector3(0,0,1),length:o,origin:r(s),lineWidth:.04,label:"Z"}].forEach(a=>{const c=this.createAxis(a);e.add(c)}),e}create(){const e=new S.Group;e.name=_h;const t=this.createWireframe();e.add(t),this.createEdges(e),this.createCorners(e),this.createFaces(e);const n=this.createCoordinateAxes();e.add(n);const s=this.getInitialRotation();return e.setRotationFromEuler(s),e}highlightObject(e){if(this.hoveredObject!==e)if(this.hoveredObject&&this.originalColor&&this.hoveredObject.material.color.set(this.originalColor),e&&e instanceof S.Mesh){const t=e.material;this.hoveredObject=e,this.originalColor=t.color.clone(),t.color.set(11519973)}else this.hoveredObject=null,this.originalColor=null}handleClick(){if(this.hoveredObject){let e=new S.Vector3;e=this.hoveredObject.getWorldPosition(e).clone();const t=new S.Vector3(0,0,0),n=e.sub(t).normalize();this.hoveredObject.userData.vectorToCube=n}}}class Ph{constructor(e){this.onChangeMainControlsListener=()=>{},this.onChangeGizmoControlsListener=()=>{},this.animationId=0;const{gizmoParams:t,mainParams:n,syncFunctions:s,options:r}=e;this.gizmoDiv=t.gizmoDiv,this.gizmoScene=t.gizmoScene,this.gizmoRenderer=t.gizmoRenderer,this.gizmoCamera=t.gizmoCamera,this.mainCamera=n.mainCamera,this.mainControls=n.mainControls,this.renderGizmo=n.renderGizmo,this.syncFunctions=s,this.options=r,this.gizmoControls=new to(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 Lh({initialFace:((e=this.options)==null?void 0:e.initialFace)??It.FRONT}).create();this.gizmoScene.add(t),vh(this.gizmoScene)}initializeControls(){this.onChangeMainControlsListener=()=>this.syncFunctions.syncGizmoCameraWithMain(this.gizmoCamera,this.mainCamera,this.gizmoScene),this.mainControls.addEventListener("change",this.onChangeMainControlsListener),this.gizmoControls.enableZoom=!1,this.gizmoControls.enablePan=!1,this.gizmoControls.rotateSpeed=.5,this.gizmoControls.update(),this.onChangeGizmoControlsListener=()=>{const e=this.gizmoScene.getObjectByName(Mn);e==null||e.rotation.copy(this.gizmoCamera.rotation),this.syncFunctions.syncMainCameraWithGizmo(this.mainCamera,this.gizmoCamera,this.mainControls),this.renderGizmo()},this.gizmoControls.addEventListener("change",this.onChangeGizmoControlsListener)}startAnimationLoop(){const e=()=>{this.gizmoRenderer.render(this.gizmoScene,this.gizmoCamera)},t=()=>{this.animationId=requestAnimationFrame(t),e()};t()}dispose(){this.mainControls.removeEventListener("change",this.onChangeMainControlsListener),this.gizmoControls.removeEventListener("change",this.onChangeGizmoControlsListener),this.gizmoScene.clear(),cancelAnimationFrame(this.animationId)}}const Oh=(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 so=(i,e,t,n)=>(n.setFromCamera(i,e),n.intersectObjects(t.children,!0)),io=i=>{var e;const t=["Wireframe",""];return((e=i.find(n=>!t.includes(n.object.name)))==null?void 0:e.object)||null};function Dh(i,e,t,n){if(!e||!t)return null;const s=so(i,e,t,n);return io(s)}function Nh(i,e){const t=i==null?void 0:i.userData.gizmoCube;if(i&&t){t.handleClick();const n=t.vectorToCube;n&&e(n)}}const kh={radius:2.1,color:12369854,tubeRadius:.1,tubeSegments:8,numPoints:64,tubeOffset:1.5},Fh={size:.2,depth:.1,heightRatio:1.4,segments:1};class Bh{constructor(e={}){this.config={...kh,...e},this.material=new S.MeshBasicMaterial({color:this.config.color})}create(){const e=new S.Group,t=this.createQuarterCircleCurves();return e.add(...this.createTubes(t),...this.createArrowHeads(t)),e.name=Mn,e}createQuarterCircleCurves(){const e=this.generateQuarterCirclePoints(),t=Math.floor(e.length/2);return[new S.CatmullRomCurve3(e.slice(0,t-this.config.tubeOffset)),new S.CatmullRomCurve3(e.slice(t+this.config.tubeOffset))]}generateQuarterCirclePoints(){const e=Math.PI/2,t=e/2,n=e/4;return Array.from({length:this.config.numPoints+1},(s,r)=>{const o=r/this.config.numPoints,a=n+t*o,c=this.config.radius*Math.sin(a),d=this.config.radius*Math.cos(a);return new S.Vector3(c,d,0)})}createTubes([e,t]){const n=(s,r)=>{const o=new S.TubeGeometry(s,this.config.numPoints,this.config.tubeRadius,this.config.tubeSegments,!1),a=new S.Mesh(o,this.material);return a.name=r,a};return[n(e,gi),n(t,Es)]}createArrowHeads([e,t]){const{size:n,depth:s,heightRatio:r,segments:o}=Fh,a=this.createArrowShape(n,r),c=new S.ExtrudeGeometry(a,{steps:o,depth:s,bevelEnabled:!1}).center(),d=(u,h,f)=>{const m=new S.Mesh(c,this.material);return m.position.copy(u),m.rotation.z=h,m.name=f,m};return[d(e.getPoint(0),this.calculateArrowRotation(e.getTangent(0))+Math.PI/2,gi),d(t.getPoint(1),this.calculateArrowRotation(t.getTangent(1))-Math.PI/2,Es)]}createArrowShape(e,t){return new S.Shape().moveTo(0,0).lineTo(e,-e*t).lineTo(-e,-e*t).lineTo(0,0)}calculateArrowRotation(e){return Math.atan2(e.y,e.x)}}const zh=i=>{const e=i.rotation,t=.01,n=Math.PI,s=(Math.abs(e.x)%(2*n)+2*n)%(2*n),r=(Math.abs(e.y)%(2*n)+2*n)%(2*n),o=Math.abs(s-n/2)<t||Math.abs(s-3*n/2)<t||Math.abs(r-n/2)<t||Math.abs(r-3*n/2)<t,a=(Math.abs(s)<t||Math.abs(s-n)<t)&&(Math.abs(r)<t||Math.abs(r-n)<t);return!(o||a)},Uh=25,Hh=200;function Vh({gizmoRenderer:i,gizmoScene:e,gizmoCamera:t,alignCameraWithVector:n,gizmoControlRef:s}){const r=oe.useRef(null),o=oe.useRef(null),a=oe.useRef(new S.Raycaster).current,c=oe.useRef(new S.Vector2).current,d=oe.useCallback(()=>{const _=e.getObjectByName(Mn),E=zh(t);if(_&&E){e.remove(_);return}if(_||E)return;const b=new Bh().create();b.rotation.copy(t.rotation),e.add(b)},[e,t]),u=oe.useCallback(()=>{const _=e.getObjectByName(Mn);_&&e.remove(_)},[e]),h=oe.useCallback(Oh(_=>{if(!s.current||!i)return;br(_,i,c);const E=so(c,t,e,a),b=io(E);b!=null&&b.userData.gizmoCube?b.userData.gizmoCube.highlightObject(b):e.traverse(T=>{T.userData.gizmoCube&&T.userData.gizmoCube.highlightObject(null)}),E.length>0?d():u()},1e3/Uh),[s,i,t,e,a,c,d,u]),f=oe.useCallback(_=>{r.current=Date.now(),o.current={x:_.clientX,y:_.clientY}},[]),m=oe.useCallback(_=>{var E;const b=_.name===Es?1:-1,T=90*Math.PI/180,x=new S.Vector3(0,0,0),A=b*T,R=new S.Matrix4;R.makeRotationZ(A),t.up.applyMatrix4(R),t.lookAt(x),(E=s.current)==null||E.gizmoControls.update()},[t,s]),w=oe.useCallback(_=>{if((r.current?Date.now()-r.current:0)<Hh){br(_,i,c);const E=Dh(c,t,e,a);E!=null&&E.name&&bh.includes(E.name)?m(E):Nh(E,n)}r.current=null,o.current=null},[m,n,i,t,e,a,c]);return{onMouseDown:f,onMouseMove:h,onMouseUp:w,onMouseLeave:u}}const jh=({camera:i,controls:e,className:t,render:n,options:s})=>{const r=oe.useRef(null),o=oe.useRef(new S.Scene).current,[a]=oe.useState(()=>Rh()),c=30,d=1,u=.1,h=10,f=new S.PerspectiveCamera(c,d,u,h),m=oe.useRef(f).current,w=oe.useRef(null),_=oe.useCallback(()=>{a&&(n(),a.render(o,m))},[n,a,o,m]),E=oe.useCallback(R=>{if(!i||!e)return;const O=i.position.length(),L=R.clone().multiplyScalar(O),C=400,N=new S.Matrix4;N.lookAt(L,new S.Vector3(0,0,0),new S.Vector3(0,1,0));const I=new S.Quaternion;I.setFromRotationMatrix(N),i.quaternion.copy(I),ah(i,e,i.position.clone(),L,C,_),i.up.set(0,1,0),i.lookAt(new S.Vector3(0,0,0)),e.target.set(0,0,0),e.update()},[i,e,_,o]),{onMouseDown:b,onMouseMove:T,onMouseUp:x,onMouseLeave:A}=Vh({gizmoRenderer:a,gizmoScene:o,gizmoCamera:m,alignCameraWithVector:E,gizmoControlRef:w});return oe.useEffect(()=>{const R=r.current;if(!R||!i||!e||!a)return;w.current&&w.current.dispose();const O={gizmoDiv:R,gizmoScene:o,gizmoRenderer:a,gizmoCamera:m},L={mainCamera:i,mainControls:e,renderGizmo:_},C={syncGizmoCameraWithMain:_r,syncMainCameraWithGizmo:Ah};return w.current=new Ph({gizmoParams:O,mainParams:L,syncFunctions:C,options:s}),R.addEventListener("mousedown",b),R.addEventListener("mousemove",T),R.addEventListener("mouseup",x),R.addEventListener("mouseleave",A),()=>{w.current&&(w.current.dispose(),w.current=null),R.removeEventListener("mousedown",b),R.removeEventListener("mousemove",T),R.removeEventListener("mouseup",x),R.removeEventListener("mouseleave",A)}},[i,e,_,T,b,x]),oe.useEffect(()=>{i&&(_r(m,i,o),_())},[i,_]),me.jsx("div",{className:t?`${t}`:"gizmo-default",ref:r})},ls=10,Gh=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"}),Wh=({camera:i,controls:e,render:t,placement:n="top-right",size:s=128})=>{if(!i||!e)return null;const r=e;return me.jsx("div",{className:"viewer-gizmo-container",style:{position:"absolute",width:s,height:s,zIndex:1e3,...Gh(n)},children:me.jsx(jh,{camera:i,controls:r,render:t})})};class Zh extends oe.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 Kh({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 Xh='-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',Yh={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)"},qh=Object.keys(xi);function $h({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",...Yh},children:qh.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:Xh,fontSize:13,fontWeight:500,lineHeight:1,whiteSpace:"nowrap",flexShrink:0,cursor:"pointer",textTransform:"capitalize",transition:"background 120ms ease, color 120ms ease"},children:t},t))})}const wn={enabled:!0,label:"Loading…",color:"#ffffff",backdrop:"rgba(15,16,20,0.6)"};function Qh(i){return i===void 0||i===!0?wn:i===!1?{...wn,enabled:!1}:{enabled:i.enabled??!0,label:i.label??wn.label,errorLabel:i.errorLabel,color:i.color??wn.color,backdrop:i.backdrop??wn.backdrop}}const hs=()=>new K("Viewer is not ready yet",q.COMPONENT_NOT_MOUNTED),ro=oe.forwardRef(({object:i,options:e={},preset:t,pathTraced:n,turntable:s,animations:r,children:o},a)=>{var I,k;const c=oe.useRef(null),d=e.preset??t,{activePreset:u,pickerEnabled:h,selectPreset:f}=th(d,e.ui),m=nh(e,u,n,s,r),{viewer:w,isInitialized:_}=Jl(c,m),E=sh(w,_,i),b=ih(w),T=w?vn(w.getCamera()):null,x=w?bi(w.getControls()):null,A=w?jr(w.getRenderer()):null,R=oe.useCallback(()=>{w==null||w.requestRender()},[w]),O=((I=e.helpers)==null?void 0:I.gizmo)!==void 0&&e.helpers.gizmo!==!1,L=typeof((k=e.helpers)==null?void 0:k.gizmo)=="object"?e.helpers.gizmo:{},C=oe.useMemo(()=>Qh(e.loadingIndicator),[e.loadingIndicator]),N=C.enabled&&(E.status==="loading"||E.status==="error");return oe.useImperativeHandle(a,()=>({scene:w?ui(w.getScene()):null,camera:T,renderer:A,controls:x,events:b,loadModel:async D=>{if(!w)throw hs();const B=typeof D=="string"?D:new Oe(D),W=await w.loadModel(B);if(!W.ok)throw W.error},captureStill:async D=>{if(!w)throw hs();const B=await w.captureStill(D);if(!B.ok)throw B.error;return B.value},captureVideo:async D=>{if(!w)throw hs();const B=await w.captureVideo(D);if(!B.ok)throw B.error;return B.value},getAnimationNames:()=>(w==null?void 0:w.getAnimationNames())??[],playAnimations:D=>{if(!w)throw hs();w.playAnimations(D)},pauseAnimations:()=>{w==null||w.pauseAnimations()},dispose:()=>{w==null||w.dispose()}}),[w,T,A,x,b]),me.jsx(Zh,{children:me.jsx(rh,{viewer:w,canvasRef:c,children:me.jsxs("div",{style:{position:"relative",width:"100%",height:"100%"},children:[me.jsx(oh,{}),O&&_&&T&&x&&me.jsx(Wh,{camera:T,controls:x,render:R,placement:L.placement,size:L.size}),N&&me.jsx(Kh,{status:E.status==="error"?"error":"loading",label:E.status==="error"?C.errorLabel??E.error??"Failed to load model":C.label,color:C.color,backdrop:C.backdrop}),h&&me.jsx($h,{active:u??"studio",onSelect:f}),o]})})})});ro.displayName="SimpleViewer";const oo=oe.forwardRef((i,e)=>me.jsx(ro,{ref:e,...i}));oo.displayName="SimpleViewer";const Jh=()=>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 eu({position:i,occlude:e=!1,children:t}){const{viewer:n}=Jr(),s=oe.useRef(null),[r,o,a]=i;oe.useEffect(()=>{if(!n)return;const d=s.current;if(!d)return;const u=n.createAnchorProjector();if(!u)return;const h={x:r,y:o,z:a},f=()=>{const E=u.project(h,e);if(E){if(!E.visible){d.style.visibility="hidden";return}d.style.visibility="visible",d.style.left=`${E.left}px`,d.style.top=`${E.top}px`}},m=()=>{u.invalidate(),f()};f();const w=n.getEvents(),_=[w.on("render:complete",f),w.on("controls:change",f),w.on("model:loaded",m)];return window.addEventListener("resize",m),()=>{_.forEach(E=>E()),window.removeEventListener("resize",m)}},[n,r,o,a,e]);const c=t!=null&&t!==!1;return me.jsx("div",{ref:s,"data-testid":"viewer-hotspot",style:{position:"absolute",left:0,top:0,transform:"translate(-50%, -50%)",visibility:"hidden",zIndex:5,pointerEvents:c?"auto":"none"},children:c?t:me.jsx(Jh,{})})}exports.BOUNDING_DATA_INDEX=aa;exports.BYTES_PER_NODE=He;exports.COUNT=Xe;exports.ControlType=An;exports.DEFAULT_PATH_TRACING_SAMPLES=qs;exports.ErrorCode=q;exports.Hotspot=eu;exports.IS_LEAF=Ce;exports.LEAFNODE_MASK_32=oa;exports.MeshBVH=bn;exports.OFFSET=Ve;exports.Result=z;exports.SAH=Cr;exports.SPLIT_AXIS=Ts;exports.SimpleViewerWrapper=oo;exports.ThreeViewerError=K;exports.TypedEventEmitter=ws;exports.VIEWER_PRESETS=xi;exports.defaultOptions=ys;exports.getIndexArray=Or;exports.getVertexCount=Ss;exports.hasInternalRenderer=Mr;exports.resolvePreset=$r;