threedviewer 2.4.0 → 2.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/simple-viewer.es.js +970 -966
- package/dist/simple-viewer.umd.js +61 -61
- package/dist/utils/uuid.d.ts +10 -0
- package/package.json +1 -1
|
@@ -14,11 +14,11 @@
|
|
|
14
14
|
*
|
|
15
15
|
* This source code is licensed under the MIT license found in the
|
|
16
16
|
* LICENSE file in the root directory of this source tree.
|
|
17
|
-
*/var Yi;function Do(){return Yi||(Yi=1,process.env.NODE_ENV!=="production"&&function(){var s=ce,e=Symbol.for("react.element"),t=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),n=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),i=Symbol.for("react.provider"),a=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),u=Symbol.for("react.memo"),l=Symbol.for("react.lazy"),v=Symbol.for("react.offscreen"),
|
|
17
|
+
*/var Yi;function Do(){return Yi||(Yi=1,process.env.NODE_ENV!=="production"&&function(){var s=ce,e=Symbol.for("react.element"),t=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),n=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),i=Symbol.for("react.provider"),a=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),u=Symbol.for("react.memo"),l=Symbol.for("react.lazy"),v=Symbol.for("react.offscreen"),x=Symbol.iterator,S="@@iterator";function g(m){if(m===null||typeof m!="object")return null;var C=x&&m[x]||m[S];return typeof C=="function"?C:null}var b=s.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function w(m){{for(var C=arguments.length,N=new Array(C>1?C-1:0),q=1;q<C;q++)N[q-1]=arguments[q];T("error",m,N)}}function T(m,C,N){{var q=b.ReactDebugCurrentFrame,ie=q.getStackAddendum();ie!==""&&(C+="%s",N=N.concat([ie]));var ae=N.map(function(Q){return String(Q)});ae.unshift("Warning: "+C),Function.prototype.apply.call(console[m],console,ae)}}var A=!1,P=!1,D=!1,R=!1,O=!1,L;L=Symbol.for("react.module.reference");function E(m){return!!(typeof m=="string"||typeof m=="function"||m===r||m===o||O||m===n||m===h||m===d||R||m===v||A||P||D||typeof m=="object"&&m!==null&&(m.$$typeof===l||m.$$typeof===u||m.$$typeof===i||m.$$typeof===a||m.$$typeof===c||m.$$typeof===L||m.getModuleId!==void 0))}function G(m,C,N){var q=m.displayName;if(q)return q;var ie=C.displayName||C.name||"";return ie!==""?N+"("+ie+")":N}function z(m){return m.displayName||"Context"}function V(m){if(m==null)return null;if(typeof m.tag=="number"&&w("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof m=="function")return m.displayName||m.name||null;if(typeof m=="string")return m;switch(m){case r:return"Fragment";case t:return"Portal";case o:return"Profiler";case n:return"StrictMode";case h:return"Suspense";case d:return"SuspenseList"}if(typeof m=="object")switch(m.$$typeof){case a:var C=m;return z(C)+".Consumer";case i:var N=m;return z(N._context)+".Provider";case c:return G(m,m.render,"ForwardRef");case u:var q=m.displayName||null;return q!==null?q:V(m.type)||"Memo";case l:{var ie=m,ae=ie._payload,Q=ie._init;try{return V(Q(ae))}catch{return null}}}return null}var U=Object.assign,H=0,ne,ge,Pe,ve,ye,Ue,_e;function Te(){}Te.__reactDisabledLog=!0;function et(){{if(H===0){ne=console.log,ge=console.info,Pe=console.warn,ve=console.error,ye=console.group,Ue=console.groupCollapsed,_e=console.groupEnd;var m={configurable:!0,enumerable:!0,value:Te,writable:!0};Object.defineProperties(console,{info:m,log:m,warn:m,error:m,group:m,groupCollapsed:m,groupEnd:m})}H++}}function lt(){{if(H--,H===0){var m={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:U({},m,{value:ne}),info:U({},m,{value:ge}),warn:U({},m,{value:Pe}),error:U({},m,{value:ve}),group:U({},m,{value:ye}),groupCollapsed:U({},m,{value:Ue}),groupEnd:U({},m,{value:_e})})}H<0&&w("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var de=b.ReactCurrentDispatcher,ze;function ke(m,C,N){{if(ze===void 0)try{throw Error()}catch(ie){var q=ie.stack.trim().match(/\n( *(at )?)/);ze=q&&q[1]||""}return`
|
|
18
18
|
`+ze+m}}var ut=!1,tt;{var Dt=typeof WeakMap=="function"?WeakMap:Map;tt=new Dt}function _t(m,C){if(!m||ut)return"";{var N=tt.get(m);if(N!==void 0)return N}var q;ut=!0;var ie=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var ae;ae=de.current,de.current=null,et();try{if(C){var Q=function(){throw Error()};if(Object.defineProperty(Q.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Q,[])}catch(B){q=B}Reflect.construct(m,[],Q)}else{try{Q.call()}catch(B){q=B}m.call(Q.prototype)}}else{try{throw Error()}catch(B){q=B}m()}}catch(B){if(B&&q&&typeof B.stack=="string"){for(var $=B.stack.split(`
|
|
19
19
|
`),p=q.stack.split(`
|
|
20
20
|
`),y=$.length-1,_=p.length-1;y>=1&&_>=0&&$[y]!==p[_];)_--;for(;y>=1&&_>=0;y--,_--)if($[y]!==p[_]){if(y!==1||_!==1)do if(y--,_--,_<0||$[y]!==p[_]){var I=`
|
|
21
|
-
`+$[y].replace(" at new "," at ");return m.displayName&&I.includes("<anonymous>")&&(I=I.replace("<anonymous>",m.displayName)),typeof m=="function"&&tt.set(m,I),I}while(y>=1&&_>=0);break}}}finally{ut=!1,de.current=ae,lt(),Error.prepareStackTrace=ie}var k=m?m.displayName||m.name:"",F=k?ke(k):"";return typeof m=="function"&&tt.set(m,F),F}function Rt(m,C,N){return _t(m,!1)}function Fr(m){var C=m.prototype;return!!(C&&C.isReactComponent)}function ht(m,C,N){if(m==null)return"";if(typeof m=="function")return _t(m,Fr(m));if(typeof m=="string")return ke(m);switch(m){case h:return ke("Suspense");case d:return ke("SuspenseList")}if(typeof m=="object")switch(m.$$typeof){case c:return Rt(m.render);case u:return ht(m.type,C,N);case l:{var q=m,ie=q._payload,ae=q._init;try{return ht(ae(ie),C,N)}catch{}}}return""}var rt=Object.prototype.hasOwnProperty,Jt={},Ht=
|
|
21
|
+
`+$[y].replace(" at new "," at ");return m.displayName&&I.includes("<anonymous>")&&(I=I.replace("<anonymous>",m.displayName)),typeof m=="function"&&tt.set(m,I),I}while(y>=1&&_>=0);break}}}finally{ut=!1,de.current=ae,lt(),Error.prepareStackTrace=ie}var k=m?m.displayName||m.name:"",F=k?ke(k):"";return typeof m=="function"&&tt.set(m,F),F}function Rt(m,C,N){return _t(m,!1)}function Fr(m){var C=m.prototype;return!!(C&&C.isReactComponent)}function ht(m,C,N){if(m==null)return"";if(typeof m=="function")return _t(m,Fr(m));if(typeof m=="string")return ke(m);switch(m){case h:return ke("Suspense");case d:return ke("SuspenseList")}if(typeof m=="object")switch(m.$$typeof){case c:return Rt(m.render);case u:return ht(m.type,C,N);case l:{var q=m,ie=q._payload,ae=q._init;try{return ht(ae(ie),C,N)}catch{}}}return""}var rt=Object.prototype.hasOwnProperty,Jt={},Ht=b.ReactDebugCurrentFrame;function bt(m){if(m){var C=m._owner,N=ht(m.type,m._source,C?C.type:null);Ht.setExtraStackFrame(N)}else Ht.setExtraStackFrame(null)}function Jr(m,C,N,q,ie){{var ae=Function.call.bind(rt);for(var Q in m)if(ae(m,Q)){var $=void 0;try{if(typeof m[Q]!="function"){var p=Error((q||"React class")+": "+N+" type `"+Q+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof m[Q]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw p.name="Invariant Violation",p}$=m[Q](C,Q,q,N,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(y){$=y}$&&!($ instanceof Error)&&(bt(ie),w("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",q||"React class",N,Q,typeof $),bt(null)),$ instanceof Error&&!($.message in Jt)&&(Jt[$.message]=!0,bt(ie),w("Failed %s type: %s",N,$.message),bt(null))}}}var Hr=Array.isArray;function Ft(m){return Hr(m)}function er(m){{var C=typeof Symbol=="function"&&Symbol.toStringTag,N=C&&m[Symbol.toStringTag]||m.constructor.name||"Object";return N}}function en(m){try{return Ot(m),!1}catch{return!0}}function Ot(m){return""+m}function tr(m){if(en(m))return w("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",er(m)),Ot(m)}var rr=b.ReactCurrentOwner,Or={key:!0,ref:!0,__self:!0,__source:!0},St,nr;function tn(m){if(rt.call(m,"ref")){var C=Object.getOwnPropertyDescriptor(m,"ref").get;if(C&&C.isReactWarning)return!1}return m.ref!==void 0}function rn(m){if(rt.call(m,"key")){var C=Object.getOwnPropertyDescriptor(m,"key").get;if(C&&C.isReactWarning)return!1}return m.key!==void 0}function Ve(m,C){typeof m.ref=="string"&&rr.current}function je(m,C){{var N=function(){St||(St=!0,w("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",C))};N.isReactWarning=!0,Object.defineProperty(m,"key",{get:N,configurable:!0})}}function Lr(m,C){{var N=function(){nr||(nr=!0,w("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",C))};N.isReactWarning=!0,Object.defineProperty(m,"ref",{get:N,configurable:!0})}}var ft=function(m,C,N,q,ie,ae,Q){var $={$$typeof:e,type:m,key:C,ref:N,props:Q,_owner:ae};return $._store={},Object.defineProperty($._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty($,"_self",{configurable:!1,enumerable:!1,writable:!1,value:q}),Object.defineProperty($,"_source",{configurable:!1,enumerable:!1,writable:!1,value:ie}),Object.freeze&&(Object.freeze($.props),Object.freeze($)),$};function Ge(m,C,N,q,ie){{var ae,Q={},$=null,p=null;N!==void 0&&(tr(N),$=""+N),rn(C)&&(tr(C.key),$=""+C.key),tn(C)&&(p=C.ref,Ve(C,ie));for(ae in C)rt.call(C,ae)&&!Or.hasOwnProperty(ae)&&(Q[ae]=C[ae]);if(m&&m.defaultProps){var y=m.defaultProps;for(ae in y)Q[ae]===void 0&&(Q[ae]=y[ae])}if($||p){var _=typeof m=="function"?m.displayName||m.name||"Unknown":m;$&&je(Q,_),p&&Lr(Q,_)}return ft(m,$,p,ie,q,rr.current,Q)}}var De=b.ReactCurrentOwner,ir=b.ReactDebugCurrentFrame;function X(m){if(m){var C=m._owner,N=ht(m.type,m._source,C?C.type:null);ir.setExtraStackFrame(N)}else ir.setExtraStackFrame(null)}var nt;nt=!1;function Lt(m){return typeof m=="object"&&m!==null&&m.$$typeof===e}function sr(){{if(De.current){var m=V(De.current.type);if(m)return`
|
|
22
22
|
|
|
23
23
|
Check the render method of \``+m+"`."}return""}}function nn(m){return""}var or={};function sn(m){{var C=sr();if(!C){var N=typeof m=="string"?m:m.displayName||m.name;N&&(C=`
|
|
24
24
|
|
|
@@ -27,7 +27,7 @@ Check the top-level render call using <`+N+">.")}return C}}function ar(m,C){{if(
|
|
|
27
27
|
<%s {...props} />
|
|
28
28
|
React keys must be passed directly to JSX without using spread:
|
|
29
29
|
let props = %s;
|
|
30
|
-
<%s key={someKey} {...props} />`,Z,F,Y,F),lr[F+Z]=!0}}return m===r?an(_):on(_),_}}function cn(m,C,N){return ur(m,C,N,!0)}function ln(m,C,N){return ur(m,C,N,!1)}var Nr=ln,un=cn;Br.Fragment=r,Br.jsx=Nr,Br.jsxs=un}()),Br}var qi;function Ro(){return qi||(qi=1,process.env.NODE_ENV==="production"?fn.exports=Po():fn.exports=Do()),fn.exports}var Ze=Ro();class oe extends Error{constructor(e,t,r){super(e),this.code=t,this.context=r,this.name="ThreeViewerError",this.timestamp=new Date,Error.captureStackTrace&&Error.captureStackTrace(this,oe)}static fromError(e,t,r){if(e instanceof oe)return e;const n=e instanceof Error?e.message:String(e),o={...r,originalError:e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:e};return new oe(n,t,o)}}var ue=(s=>(s.SCENE_INIT_FAILED="SCENE_INIT_FAILED",s.RENDERER_INIT_FAILED="RENDERER_INIT_FAILED",s.RENDERER_NOT_INITIALIZED="RENDERER_NOT_INITIALIZED",s.CAMERA_INIT_FAILED="CAMERA_INIT_FAILED",s.WEBGL_NOT_SUPPORTED="WEBGL_NOT_SUPPORTED",s.INITIALIZATION_FAILED="INITIALIZATION_FAILED",s.PATH_TRACING_INIT_FAILED="PATH_TRACING_INIT_FAILED",s.MODEL_LOAD_FAILED="MODEL_LOAD_FAILED",s.TEXTURE_LOAD_FAILED="TEXTURE_LOAD_FAILED",s.RESOURCE_NOT_FOUND="RESOURCE_NOT_FOUND",s.UNSUPPORTED_FORMAT="UNSUPPORTED_FORMAT",s.INVALID_CONFIGURATION="INVALID_CONFIGURATION",s.RENDER_ERROR="RENDER_ERROR",s.RENDER_FAILED="RENDER_FAILED",s.SCENE_OPERATION_FAILED="SCENE_OPERATION_FAILED",s.COMPONENT_NOT_MOUNTED="COMPONENT_NOT_MOUNTED",s.INVALID_STATE="INVALID_STATE",s.INVALID_PARAMETER="INVALID_PARAMETER",s.OPERATION_FAILED="OPERATION_FAILED",s.UNKNOWN="UNKNOWN",s))(ue||{});const K={ok(s){return{ok:!0,value:s}},err(s){return{ok:!1,error:s}},wrap(s){try{return K.ok(s())}catch(e){return K.err(e instanceof oe?e:new oe(String(e),ue.UNKNOWN,{originalError:e}))}}};class dn{constructor(){this.listeners=new Map}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);const r=this.listeners.get(e);return r&&r.add(t),()=>{var n;(n=this.listeners.get(e))==null||n.delete(t)}}emit(e,t){var r;(r=this.listeners.get(e))==null||r.forEach(n=>{try{n(t)}catch(o){console.error(`Error in event listener for ${String(e)}:`,o)}})}once(e,t){const r=this.on(e,n=>{r(),t(n)});return r}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 r;(r=this.listeners.get(e))==null||r.delete(t)}removeListener(e,t){this.off(e,t)}}class Fo{constructor(e={}){this.animationFrameId=null,this.lastRenderTime=0,this.idleTimeout=null,this.isIdle=!1,this.needsRender=!0,this.continuousRenderingEnabled=!1,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()}enableContinuousRendering(){this.continuousRenderingEnabled=!0,this.wakeUp()}disableContinuousRendering(){this.continuousRenderingEnabled=!1}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=r=>{if(this.animationFrameId===null)return;const n=r-this.lastRenderTime;if(this.enableFrameRateLimiting&&n<this.frameInterval){this.animationFrameId=requestAnimationFrame(t);return}(this.alwaysRender||this.needsRender||this.continuousRenderingEnabled)&&(e(n),this.lastRenderTime=r,this.needsRender=!1,this.enableIdleDetection&&!this.alwaysRender&&(this.wakeUp(),this.continuousRenderingEnabled||(this.idleTimeout=window.setTimeout(()=>{this.isIdle=!0,console.log("[RenderLoopManager] Entering idle state")},this.idleDelay)))),this.alwaysRender||!this.enableIdleDetection||!this.isIdle||this.continuousRenderingEnabled||this.needsRender?this.animationFrameId=requestAnimationFrame(t):(console.log("[RenderLoopManager] Stopping render loop (idle)"),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.alwaysRender=!1}isRunning(){return this.animationFrameId!==null}getIsIdle(){return this.isIdle}getNeedsRender(){return this.needsRender||this.continuousRenderingEnabled||this.alwaysRender}}class Zi{static serialize(e,t,r,n){const o=t.position,i=r.target||{x:0,y:0,z:0};return{modelUrl:e,cameraPosition:{x:o.x,y:o.y,z:o.z},cameraTarget:{x:i.x,y:i.y,z:i.z},controlsTarget:{x:i.x,y:i.y,z:i.z},rendererSize:{width:n.clientWidth,height:n.clientHeight}}}static async restore(e,t,r,n){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}),r.target&&r.target.set(e.controlsTarget.x,e.controlsTarget.y,e.controlsTarget.z),r.update&&r.update(),e.modelUrl&&n&&await n(e.modelUrl)}}function At(s){return s!==null&&typeof s=="object"&&"getInternalRenderer"in s&&typeof s.getInternalRenderer=="function"}class pt{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 pt({...this.data,isInitialized:!0,status:"idle"})}startLoading(){return new pt({...this.data,status:"loading",loadProgress:0,error:null})}updateLoadProgress(e){return new pt({...this.data,loadProgress:Math.min(Math.max(0,e),1)})}setLoaded(e){return new pt({...this.data,status:"loaded",currentModel:e,loadProgress:1,error:null})}setError(e){return new pt({...this.data,status:"error",error:e,loadProgress:0})}startRendering(){return new pt({...this.data,status:"rendering"})}updateRenderInfo(e){return new pt({...this.data,renderInfo:{...this.data.renderInfo,...e}})}dispose(){return new pt({...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 Oo{constructor(){this.state=new pt,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(r){console.error("Error in state change callback:",r)}})}}class Lo{constructor(e){this.screenshotElement=null,this.isShowingScreenshot=!1,this.renderer=e.renderer,this.onRestore=e.onRestore}isActive(){return this.isShowingScreenshot}captureAndReplace(e,t,r,n){if(this.isShowingScreenshot)return;const o=this.renderer.getDomElement(),i=o.toDataURL("image/png"),a=document.createElement("img");a.src=i,a.style.position="absolute",a.style.top="0",a.style.left="0",a.style.width="100%",a.style.height="100%",a.style.pointerEvents="auto",a.style.cursor="grab";const c=o.parentElement;if(c){this.serializedSceneState=Zi.serialize(r,e,t,o),o.style.display="none",c.appendChild(a),this.screenshotElement=a,this.isShowingScreenshot=!0;const h=()=>{this.restore()};a.addEventListener("mousedown",h),a.addEventListener("touchstart",h);const d=()=>{this.isShowingScreenshot&&this.restore()};window.addEventListener("resize",d),this.screenshotResizeHandler=d,this.screenshotElement&&this.screenshotElement.src?n==null||n():console.warn("[ScreenshotManager] Screenshot capture failed, keeping scene resources")}}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.screenshotElement=null,this.isShowingScreenshot=!1,this.serializedSceneState=void 0}}class No{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.autoFitToObject=e.autoFitToObject??!1}getCurrentModel(){return this.currentModel}getLastModelUrl(){return this.lastModelUrl}async loadModel(e,t){const r=performance.now();try{let n;if(typeof e=="string"){this.lastModelUrl=e;const a=await this.modelLoader.load(e);if(!a.ok)throw a.error;n=a.value.scene}else n=e;this.currentModel&&(this.scene.remove(this.currentModel),this.disposeObject(this.currentModel));const o=this.scene.add(n);if(!o.ok)throw o.error;if(this.floorAlignmentService){const a=this.floorAlignmentService.alignToFloor(n);a.ok||console.warn("Failed to align model to floor:",a.error)}if(n.traverse(a=>{"castShadow"in a&&"receiveShadow"in a&&(a.castShadow=!0,a.receiveShadow=!0)}),this.currentModel=n,this.sceneSetupService){const a=this.sceneSetupService.addDynamicGrid(this.scene,n,2);a.ok||console.warn("Failed to add dynamic grid:",a.error)}if(this.autoFitToObject&&this.sceneSetupService){const a=this.sceneSetupService.fitCameraToObject(n,this.camera,this.controls);a.ok||console.warn("Failed to fit camera to object:",a.error)}const i=performance.now()-r;return t.emit("model:loaded",{model:n,loadTime:i}),K.ok(n)}catch(n){const o=n instanceof oe?n:new oe("Failed to load model",ue.MODEL_LOAD_FAILED,{originalError:n,source:e});return t.emit("model:error",{error:o,url:typeof e=="string"?e:void 0}),K.err(o)}}disposeCurrentModel(){this.currentModel&&(this.scene.remove(this.currentModel),this.disposeObject(this.currentModel),this.currentModel=null)}disposeObject(e){e.traverse(t=>{var r,n,o;if("geometry"in t&&((r=t.geometry)!=null&&r.dispose)&&((o=(n=t.geometry)==null?void 0:n.dispose)==null||o.call(n)),"material"in t&&t.material){const i=t.material;Array.isArray(i)?i.forEach(a=>{var c;(c=a.dispose)==null||c.call(a)}):i!=null&&i.dispose&&i.dispose()}}),e.dispose()}dispose(){this.disposeCurrentModel(),this.lastModelUrl=void 0}}class Zn{static getMemoryInfo(){const e=performance;return e.memory?{jsHeapUsed:Math.round(e.memory.usedJSHeapSize/1048576),jsHeapTotal:Math.round(e.memory.totalJSHeapSize/1048576),jsHeapLimit:Math.round(e.memory.jsHeapSizeLimit/1048576)}:null}static formatBytes(e){return e<1024?e+" B":e<1048576?(e/1024).toFixed(1)+" KB":e<1073741824?(e/1048576).toFixed(1)+" MB":(e/1073741824).toFixed(1)+" GB"}static logMemoryUsage(e="Memory"){const t=this.getMemoryInfo();t?(console.log(`[${e}] JS Heap: ${t.jsHeapUsed}MB / ${t.jsHeapTotal}MB (Limit: ${t.jsHeapLimit}MB)`),t.webglMemory&&console.log(`[${e}] WebGL - Programs: ${t.webglMemory.programs}, Geometries: ${t.webglMemory.geometries}, Textures: ${t.webglMemory.textures}`)):console.log(`[${e}] Memory info not available (use Chrome with --enable-precise-memory-info)`)}static startMonitoring(e=5e3,t="MemoryMonitor"){const r=setInterval(()=>{this.logMemoryUsage(t)},e);return()=>clearInterval(r)}}class ko{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){Zn.logMemoryUsage("Before scene disposal"),!e&&this.pathTracingService,this.environmentService&&this.environmentService.dispose(),this.scene.traverse&&this.scene.traverse(t=>{var r,n,o,i;"geometry"in t&&t.geometry&&((n=(r=t.geometry).dispose)==null||n.call(r)),"material"in t&&t.material&&(Array.isArray(t.material)?t.material.forEach(a=>{var c;(c=a.dispose)==null||c.call(a)}):(i=(o=t.material).dispose)==null||i.call(o))}),this.scene.clear&&this.scene.clear(),this.triggerGarbageCollection(),Zn.logMemoryUsage("After scene disposal"),setTimeout(()=>{Zn.logMemoryUsage("After GC delay")},2e3)}disposeServices(){this.pathTracingService&&(this.pathTracingService.dispose(),this.pathTracingService=void 0),this.environmentService&&(this.environmentService.dispose(),this.environmentService=void 0)}dispose(){this.disposeServices(),this.scene.clear&&this.scene.clear(),this.triggerGarbageCollection()}triggerGarbageCollection(){var e;globalThis.gc&&((e=globalThis.gc)==null||e.call(globalThis))}}class Bo{constructor(e){var n;this.lastFrameTime=0,this.frameCount=0,this.pathTracingCompleteHandled=!1,this.disposed=!1,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.pathTracingService=e.pathTracingService,this.stateManager=new Oo,this.screenshotManager=new Lo({renderer:this.renderer,onRestore:async()=>{await this.restoreFromScreenshot()}}),this.modelManager=new No({modelLoader:e.modelLoader,scene:this.scene,camera:this.camera,controls:this.controls,floorAlignmentService:e.floorAlignmentService,sceneSetupService:this.sceneSetupService,autoFitToObject:(n=this.options.camera)==null?void 0:n.autoFitToObject}),this.resourceManager=new ko({scene:this.scene,pathTracingService:this.pathTracingService,environmentService:this.environmentService}),this.events=new dn;const t=this.options.rendering||{},r=this.options.staticScene!==!1;this.renderLoopManager=new Fo({enableIdleDetection:t.enableIdleDetection??r,idleDelay:t.idleDelay,targetFPS:t.targetFPS,enableFrameRateLimiting:t.enableFrameRateLimiting,alwaysRender:!1})}async initialize(){var e,t,r,n,o,i,a,c,h,d,u,l;try{const v=this.rendererOptions||{},b=this.renderer.initialize(v);if(!b.ok)return b;if(this.sceneSetupService){if(this.options.helpers){const w={grid:this.options.helpers.grid,axes:this.options.helpers.axes,gridColor:"#AAAAAA"},T=this.sceneSetupService.addHelpers(this.scene,w);T.ok||console.warn("Failed to add helpers:",T.error)}const g=this.options.lighting;if(g){const w={ambient:g.ambientLight?{color:String(g.ambientLight.color),intensity:g.ambientLight.intensity}:void 0,hemisphere:g.hemisphereLight?{skyColor:String(g.hemisphereLight.skyColor),groundColor:String(g.hemisphereLight.groundColor),intensity:g.hemisphereLight.intensity}:void 0,directional:g.directionalLight?{color:String(g.directionalLight.color),intensity:g.directionalLight.intensity,position:Array.isArray(g.directionalLight.position)?g.directionalLight.position:void 0,castShadow:g.directionalLight.castShadow,shadow:g.directionalLight.shadow}:void 0},T=this.sceneSetupService.addLighting(this.scene,w);T.ok||console.warn("Failed to add lighting:",T.error)}const x=(e=this.options.environment)==null?void 0:e.url;if(this.options.backgroundColor&&!x&&this.sceneSetupService){const w=this.sceneSetupService.createGradientBackground(this.scene,{topColor:String(this.options.backgroundColor),bottomColor:String(this.options.backgroundColor)});w.ok||console.warn("Failed to set background:",w.error)}}if(this.environmentService){const g=await this.environmentService.initialize({renderer:this.renderer,autoDispose:!0});g.ok||console.warn("Failed to initialize environment service:",g.error);const x=(t=this.options.environment)==null?void 0:t.url;if(x){const w=await this.environmentService.loadEnvironmentMap(x);w.ok?this.environmentService.applyToScene(this.scene,w.value,{backgroundBlurriness:(r=this.options.environment)==null?void 0:r.backgroundBlurriness,backgroundIntensity:(n=this.options.environment)==null?void 0:n.backgroundIntensity,environmentIntensity:(o=this.options.environment)==null?void 0:o.environmentIntensity}):console.warn("Failed to load environment map:",w.error)}else if((i=this.options.helpers)!=null&&i.studioEnvironment){const w=this.environmentService.createStudioEnvironment();if(w.ok){if(this.environmentService.applyToScene(this.scene,w.value,{backgroundBlurriness:(a=this.options.environment)==null?void 0:a.backgroundBlurriness,backgroundIntensity:(c=this.options.environment)==null?void 0:c.backgroundIntensity,environmentIntensity:(h=this.options.environment)==null?void 0:h.environmentIntensity}),(d=this.options.helpers)!=null&&d.darkStudioMode&&this.sceneSetupService){const T="#1a1a1f",A=this.sceneSetupService.createGradientBackground(this.scene,{topColor:T,bottomColor:T});A.ok||console.warn("Failed to set dark studio background:",A.error)}}else console.warn("Failed to create studio environment:",w.error)}}const S=((u=this.options.pathTracing)==null?void 0:u.enabled)??!1;if(this.pathTracingService&&S){const g=await this.pathTracingService.initialize({enabled:!0,renderer:this.renderer});g.ok?(this.options.pathTracing&&this.pathTracingService.updateSettings({samples:this.options.pathTracing.maxSamples??300,bounces:this.options.pathTracing.bounces,transmissiveBounces:this.options.pathTracing.transmissiveBounces,renderScale:this.options.pathTracing.renderScale,lowResScale:this.options.pathTracing.lowResScale,dynamicLowRes:this.options.pathTracing.dynamicLowRes,enablePathTracing:this.options.pathTracing.enabled??S}),this.pathTracingService.events.on("pathtracing:paused",x=>{this.renderLoopManager.disableContinuousRendering(),this.options.staticScene||this.renderLoopManager.setAlwaysRender(!1),setTimeout(()=>{this.renderLoopManager.stop()},100)})):console.warn("Failed to initialize path tracing:",g.error)}if(this.stateManager.setInitialized(),this.startRenderLoop(),!this.options.staticScene)this.renderLoopManager.setAlwaysRender(!0);else{const g=((l=this.options.pathTracing)==null?void 0:l.enabled)??!1;this.pathTracingService&&g&&this.renderLoopManager.enableContinuousRendering()}return this.renderLoopManager.requestRender(),K.ok(void 0)}catch(v){const b=new oe("Failed to initialize viewer",ue.INITIALIZATION_FAILED,{originalError:v});return this.stateManager.setError(b),this.events.emit("error",{error:b}),K.err(b)}}async loadModel(e){var t;if(!this.stateManager.canLoad())return K.err(new oe("Cannot load model in current state",ue.INVALID_STATE,{currentState:this.stateManager.getStatus(),isInitialized:this.stateManager.isInitialized()}));try{this.stateManager.startLoading();const r=await this.modelManager.loadModel(e,this.events);if(r.ok){this.stateManager.setLoaded(r.value),this.renderLoopManager.requestRender();const n=((t=this.options.pathTracing)==null?void 0:t.enabled)??!1;return this.pathTracingService&&n&&(this.pathTracingService.reset(),this.pathTracingCompleteHandled=!1),K.ok(void 0)}else return this.stateManager.setError(r.error),r}catch(r){const n=r instanceof oe?r:new oe("Failed to load model",ue.MODEL_LOAD_FAILED,{originalError:r,source:e});return this.stateManager.setError(n),K.err(n)}}startRenderLoop(){this.renderLoopManager.start(e=>{var h,d,u,l,v;if(this.disposed){this.renderLoopManager.stop();return}if(!this.stateManager.isInitialized()||this.stateManager.getStatus()==="error")return;if(!this.renderer||this.renderer.renderer===null){this.renderLoopManager.stop();return}this.frameCount%60;const t=performance.now(),r=e>0?1e3/e:0;if(this.controls.update()){this.events.emit("controls:change",{controls:this.controls});const b=((h=this.options.pathTracing)==null?void 0:h.enabled)??!1;this.pathTracingService&&b&&(this.pathTracingService.reset(),this.pathTracingCompleteHandled=!1),this.renderLoopManager.requestRender()}const o=((d=this.pathTracingService)==null?void 0:d.isEnabled())||!1,i=((u=this.pathTracingService)==null?void 0:u.getSampleCount())||0,a=((l=this.options.pathTracing)==null?void 0:l.maxSamples)??300;if(this.renderFrame().catch(b=>{console.error("[ViewerCore] Render frame error:",b)}),(((v=this.pathTracingService)==null?void 0:v.getSampleCount())||0)>=a&&!this.pathTracingCompleteHandled&&o){if(this.pathTracingCompleteHandled=!0,this.renderLoopManager.disableContinuousRendering(),this.options.staticScene||this.renderLoopManager.setAlwaysRender(!1),this.events.emit("pathtracing:complete",{samples:i,totalTime:t-(this.pathTracingStartTime||0)}),this.options.replaceWithScreenshotOnComplete)setTimeout(()=>{this.replaceWithScreenshot(),setTimeout(()=>{this.renderLoopManager.stop()},200)},100);else if(this.renderLoopManager.requestRender(),setTimeout(()=>{this.renderLoopManager.stop()},100),At(this.renderer)){const b=this.renderer.getInternalRenderer();b&&(b.autoClear=!1)}}this.frameCount++,this.stateManager.updateRenderInfo({frameCount:this.frameCount,fps:Math.round(r),lastRenderTime:performance.now()-t}),this.lastFrameTime=t})}stopRenderLoop(){this.renderLoopManager.stop()}async renderFrame(){var h,d,u,l;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();let t;const r=((h=this.pathTracingService)==null?void 0:h.isEnabled())||!1,n=((d=this.pathTracingService)==null?void 0:d.getSampleCount())||0,o=((u=this.options.pathTracing)==null?void 0:u.maxSamples)??300;if(this.pathTracingService&&!this.pathTracingService.isPathTracerDisposed()&&(r||n>=o&&n>0)&&this.pathTracingService?(this.pathTracingService.getSampleCount()===0&&(this.pathTracingStartTime=performance.now()),t=await this.pathTracingService.render(this.scene,this.camera)):t=this.renderer.render(this.scene,this.camera),!t.ok){console.error("[ViewerCore] Render failed:",t.error),this.events.emit("error",{error:t.error});return}const a=performance.now()-e,c=((l=this.pathTracingService)==null?void 0:l.getSampleCount())||0;this.events.emit("render:complete",{frame:this.frameCount,renderTime:a,samples:c})}resize(e,t){var o;const r=this.renderer.getDomElement();if(r.width===e&&r.height===t)return;const n=(o=this.pathTracingService)==null?void 0:o.isEnabled();this.pathTracingService&&this.pathTracingService.hasImageOverlay()&&(this.pathTracingService.removeImageOverlay(),this.pathTracingService.reset()),this.camera.type==="perspective"&&"aspect"in this.camera&&(this.camera.aspect=e/t),this.camera.updateProjectionMatrix(),this.renderer.setSize(e,t);try{this.renderer.render(this.scene,this.camera)}catch{}n&&this.pathTracingService&&this.pathTracingService.setEnabled(!0),this.renderLoopManager.requestRender()}getState(){return this.stateManager.getState()}onStateChange(e){return this.stateManager.onStateChange(e)}getEvents(){return this.events}getDomElement(){return this.renderer.getDomElement()}replaceWithScreenshot(){const e=this.modelManager.getLastModelUrl();this.screenshotManager.captureAndReplace(this.camera,this.controls,e,()=>{this.modelManager.disposeCurrentModel(),this.resourceManager.disposeSceneResources(!0)})}async restoreFromScreenshot(){var t;const e=this.screenshotManager.getSerializedState();!this.pathTracingService&&((t=this.options.pathTracing)!=null&&t.enabled)&&console.warn("[ViewerCore] Cannot recreate path tracing service - feature disabled"),e&&await Zi.restore(e,this.camera,this.controls,async r=>{const n=await this.loadModel(r);n.ok||console.error("[ViewerCore] Failed to reload model:",n.error)}),this.renderLoopManager.isRunning()||this.startRenderLoop(),this.renderLoopManager.requestRender()}dispose(){this.disposed=!0,this.stopRenderLoop(),this.modelManager.dispose(),this.resourceManager.dispose(),this.screenshotManager.dispose(),this.scene.clear(),this.controls.dispose(),this.renderer.dispose(),this.stateManager.setDisposed(),this.events.removeAllListeners(),this.stateManager.clearCallbacks()}}class kt{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,r){this.vector.set(e,t,r)}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 kt(e)}static create(e=0,t=0,r=0){return new kt(new M.Vector3(e,t,r))}}class We{constructor(e){this.object=e,this.positionAdapter=kt.fromThreeVector(e.position),this.rotationAdapter=kt.fromThreeVector(e.rotation),this.scaleAdapter=kt.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 position(){return this.positionAdapter}get rotation(){return this.rotationAdapter}get scale(){return this.scaleAdapter}add(e){try{return e instanceof We?(this.object.add(e.getThreeObject()),K.ok(void 0)):K.err(new oe("Child must be a ThreeObject3DAdapter",ue.INVALID_PARAMETER))}catch(t){return K.err(new oe("Failed to add child object",ue.SCENE_OPERATION_FAILED,{originalError:t}))}}remove(e){try{return e instanceof We?(this.object.remove(e.getThreeObject()),K.ok(void 0)):K.err(new oe("Child must be a ThreeObject3DAdapter",ue.INVALID_PARAMETER))}catch(t){return K.err(new oe("Failed to remove child object",ue.SCENE_OPERATION_FAILED,{originalError:t}))}}traverse(e){this.object.traverse(t=>{e(new We(t))})}clone(){return new We(this.object.clone())}dispose(){this.object.traverse(e=>{var t;e instanceof M.Mesh&&((t=e.geometry)==null||t.dispose(),e.material&&(Array.isArray(e.material)?e.material.forEach(r=>r.dispose()):e.material.dispose()))})}getThreeObject(){return this.object}static fromThreeObject(e){return new We(e)}static create(){return new We(new M.Object3D)}}class Yt{constructor(e){this.scene=e||new M.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 We?(this.scene.add(e.getThreeObject()),K.ok(void 0)):K.err(new oe("Object must be a ThreeObject3DAdapter",ue.INVALID_PARAMETER))}catch(t){return K.err(new oe("Failed to add object to scene",ue.SCENE_OPERATION_FAILED,{originalError:t}))}}remove(e){try{return e instanceof We?(this.scene.remove(e.getThreeObject()),K.ok(void 0)):K.err(new oe("Object must be a ThreeObject3DAdapter",ue.INVALID_PARAMETER))}catch(t){return K.err(new oe("Failed to remove object from scene",ue.SCENE_OPERATION_FAILED,{originalError:t}))}}clear(){for(;this.scene.children.length>0;)this.scene.remove(this.scene.children[0])}traverse(e){this.scene.traverse(t=>{e(new We(t))})}get background(){return this.scene.background instanceof M.Color?new Kn(this.scene.background):this.scene.background instanceof M.Texture?new pn(this.scene.background):null}set background(e){e instanceof Kn?this.scene.background=e.getThreeColor():e instanceof pn?this.scene.background=e.getThreeTexture():this.scene.background=null}get fog(){return this.scene.fog?new Ki(this.scene.fog):null}set fog(e){e instanceof Ki?this.scene.fog=e.getThreeFog():this.scene.fog=null}get environment(){return this.scene.environment?new pn(this.scene.environment):null}set environment(e){e instanceof pn?this.scene.environment=e.getThreeTexture():this.scene.environment=null}getInternalRenderer(){return this.scene}getThreeScene(){return this.scene}}class Kn{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,r){this.color.setRGB(e,t,r)}getHex(){return this.color.getHex()}getThreeColor(){return this.color}}let pn=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 Ki{constructor(e){this.fog=e}get color(){return new Kn(this.fog.color)}get near(){return this.fog.near||0}get far(){return this.fog.far||1e3}getThreeFog(){return this.fog}}class Xn extends We{constructor(e){super(e),this.camera=e}get near(){return this.camera instanceof M.PerspectiveCamera||this.camera instanceof M.OrthographicCamera?this.camera.near:.1}set near(e){(this.camera instanceof M.PerspectiveCamera||this.camera instanceof M.OrthographicCamera)&&(this.camera.near=e)}get far(){return this.camera instanceof M.PerspectiveCamera||this.camera instanceof M.OrthographicCamera?this.camera.far:1e3}set far(e){(this.camera instanceof M.PerspectiveCamera||this.camera instanceof M.OrthographicCamera)&&(this.camera.far=e)}lookAt(e){e instanceof kt?this.camera.lookAt(e.getThreeVector()):this.camera.lookAt(e.x,e.y,e.z)}updateProjectionMatrix(){(this.camera instanceof M.PerspectiveCamera||this.camera instanceof M.OrthographicCamera)&&this.camera.updateProjectionMatrix()}getWorldDirection(e){const t=new M.Vector3;this.camera.getWorldDirection(t),e.set(t.x,t.y,t.z)}getInternalRenderer(){return this.camera}getThreeCamera(){return this.camera}}class $n extends Xn{constructor(e){const t=e||new M.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,r=.1,n=1e3){return new $n(new M.PerspectiveCamera(e,t,r,n))}}class zo{constructor(e){this.renderer=null,this._id=crypto.randomUUID(),this.canvas=e}get id(){return this._id}initialize(e){console.log("[ThreeRendererAdapter] initialize() called");try{if(this.renderer=new M.WebGLRenderer({canvas:this.canvas,antialias:e.antialias??!0,alpha:e.alpha??!1,premultipliedAlpha:e.premultipliedAlpha??!0,preserveDrawingBuffer:e.preserveDrawingBuffer??!1,powerPreference:e.powerPreference??"default"}),console.log("[ThreeRendererAdapter] WebGLRenderer created successfully"),e.shadowMap&&(this.renderer.shadowMap.enabled=e.shadowMap.enabled,this.renderer.shadowMap.autoUpdate=!0,e.shadowMap.type)){const t={basic:M.BasicShadowMap,pcf:M.PCFShadowMap,pcfsoft:M.PCFSoftShadowMap,vsm:M.VSMShadowMap};this.renderer.shadowMap.type=t[e.shadowMap.type]}if(e.toneMapping){const t={none:M.NoToneMapping,linear:M.LinearToneMapping,reinhard:M.ReinhardToneMapping,cineon:M.CineonToneMapping,aces:M.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:r}=this.canvas.parentElement||this.canvas;t&&r&&this.renderer.setSize(t,r)}return this.renderer.outputColorSpace=M.SRGBColorSpace,K.ok(void 0)}catch(t){return K.err(new oe("Failed to initialize renderer",ue.RENDERER_INIT_FAILED,{originalError:t,options:e}))}}render(e,t){if(!this.renderer)return K.err(new oe("Renderer not initialized",ue.RENDERER_NOT_INITIALIZED));try{if(!(e instanceof Yt))return K.err(new oe("Scene must be a ThreeSceneAdapter",ue.INVALID_PARAMETER));if(!(t instanceof Xn))return K.err(new oe("Camera must be a ThreeCameraAdapter",ue.INVALID_PARAMETER));const r=e.getThreeScene(),n=t.getThreeCamera();return this.renderer.__pathTracingActive?(console.log("[ThreeRenderer] Skipping standard render - path tracing is active"),K.ok(void 0)):(this.renderer.render(r,n),K.ok(void 0))}catch(r){return K.err(new oe("Failed to render frame",ue.RENDER_FAILED,{originalError:r}))}}setSize(e,t){if(this.renderer){this.renderer.setSize(e,t,!1);const r=this.renderer.domElement;r.style.width="100%",r.style.height="100%"}}setPixelRatio(e){this.renderer&&this.renderer.setPixelRatio(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)}getInternalRenderer(){return console.log("[ThreeRendererAdapter] getInternalRenderer called, renderer exists:",!!this.renderer),this.renderer}getThreeRenderer(){return this.getInternalRenderer()}}function Xi(s,e){if(e===f.TrianglesDrawMode)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),s;if(e===f.TriangleFanDrawMode||e===f.TriangleStripDrawMode){let t=s.getIndex();if(t===null){const i=[],a=s.getAttribute("position");if(a!==void 0){for(let c=0;c<a.count;c++)i.push(c);s.setIndex(i),t=s.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),s}const r=t.count-2,n=[];if(e===f.TriangleFanDrawMode)for(let i=1;i<=r;i++)n.push(t.getX(0)),n.push(t.getX(i)),n.push(t.getX(i+1));else for(let i=0;i<r;i++)i%2===0?(n.push(t.getX(i)),n.push(t.getX(i+1)),n.push(t.getX(i+2))):(n.push(t.getX(i+2)),n.push(t.getX(i+1)),n.push(t.getX(i)));n.length/3!==r&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const o=s.clone();return o.setIndex(n),o.clearGroups(),o}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),s}class Eo extends f.Loader{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new Wo(t)}),this.register(function(t){return new Yo(t)}),this.register(function(t){return new ea(t)}),this.register(function(t){return new ta(t)}),this.register(function(t){return new ra(t)}),this.register(function(t){return new Zo(t)}),this.register(function(t){return new Ko(t)}),this.register(function(t){return new Xo(t)}),this.register(function(t){return new $o(t)}),this.register(function(t){return new jo(t)}),this.register(function(t){return new Qo(t)}),this.register(function(t){return new qo(t)}),this.register(function(t){return new Ho(t)}),this.register(function(t){return new Jo(t)}),this.register(function(t){return new Go(t)}),this.register(function(t){return new na(t)}),this.register(function(t){return new ia(t)})}load(e,t,r,n){const o=this;let i;if(this.resourcePath!=="")i=this.resourcePath;else if(this.path!==""){const h=f.LoaderUtils.extractUrlBase(e);i=f.LoaderUtils.resolveURL(h,this.path)}else i=f.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const a=function(h){n?n(h):console.error(h),o.manager.itemError(e),o.manager.itemEnd(e)},c=new f.FileLoader(this.manager);c.setPath(this.path),c.setResponseType("arraybuffer"),c.setRequestHeader(this.requestHeader),c.setWithCredentials(this.withCredentials),c.load(e,function(h){try{o.parse(h,i,function(d){t(d),o.manager.itemEnd(e)},a)}catch(d){a(d)}},r,a)}setDRACOLoader(e){return this.dracoLoader=e,this}setDDSLoader(){throw new Error('THREE.GLTFLoader: "MSFT_texture_dds" no longer supported. Please update to "KHR_texture_basisu".')}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,r,n){let o;const i={},a={},c=new TextDecoder;if(typeof e=="string")o=JSON.parse(e);else if(e instanceof ArrayBuffer)if(c.decode(new Uint8Array(e,0,4))===$i){try{i[fe.KHR_BINARY_GLTF]=new sa(e)}catch(u){n&&n(u);return}o=JSON.parse(i[fe.KHR_BINARY_GLTF].content)}else o=JSON.parse(c.decode(e));else o=e;if(o.asset===void 0||o.asset.version[0]<2){n&&n(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const h=new ya(o,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});h.fileLoader.setRequestHeader(this.requestHeader);for(let d=0;d<this.pluginCallbacks.length;d++){const u=this.pluginCallbacks[d](h);u.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),a[u.name]=u,i[u.name]=!0}if(o.extensionsUsed)for(let d=0;d<o.extensionsUsed.length;++d){const u=o.extensionsUsed[d],l=o.extensionsRequired||[];switch(u){case fe.KHR_MATERIALS_UNLIT:i[u]=new Vo;break;case fe.KHR_DRACO_MESH_COMPRESSION:i[u]=new oa(o,this.dracoLoader);break;case fe.KHR_TEXTURE_TRANSFORM:i[u]=new aa;break;case fe.KHR_MESH_QUANTIZATION:i[u]=new ca;break;default:l.indexOf(u)>=0&&a[u]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+u+'".')}}h.setExtensions(i),h.setPlugins(a),h.parse(r,n)}parseAsync(e,t){const r=this;return new Promise(function(n,o){r.parse(e,t,n,o)})}}function Uo(){let s={};return{get:function(e){return s[e]},add:function(e,t){s[e]=t},remove:function(e){delete s[e]},removeAll:function(){s={}}}}const fe={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",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class Go{constructor(e){this.parser=e,this.name=fe.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let r=0,n=t.length;r<n;r++){const o=t[r];o.extensions&&o.extensions[this.name]&&o.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,o.extensions[this.name].light)}}_loadLight(e){const t=this.parser,r="light:"+e;let n=t.cache.get(r);if(n)return n;const o=t.json,c=((o.extensions&&o.extensions[this.name]||{}).lights||[])[e];let h;const d=new f.Color(16777215);c.color!==void 0&&d.setRGB(c.color[0],c.color[1],c.color[2],f.LinearSRGBColorSpace);const u=c.range!==void 0?c.range:0;switch(c.type){case"directional":h=new f.DirectionalLight(d),h.target.position.set(0,0,-1),h.add(h.target);break;case"point":h=new f.PointLight(d),h.distance=u;break;case"spot":h=new f.SpotLight(d),h.distance=u,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,h.angle=c.spot.outerConeAngle,h.penumbra=1-c.spot.innerConeAngle/c.spot.outerConeAngle,h.target.position.set(0,0,-1),h.add(h.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+c.type)}return h.position.set(0,0,0),h.decay=2,Mt(h,c),c.intensity!==void 0&&(h.intensity=c.intensity),h.name=t.createUniqueName(c.name||"light_"+e),n=Promise.resolve(h),t.cache.add(r,n),n}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,r=this.parser,o=r.json.nodes[e],a=(o.extensions&&o.extensions[this.name]||{}).light;return a===void 0?null:this._loadLight(a).then(function(c){return r._getNodeRef(t.cache,a,c)})}}class Vo{constructor(){this.name=fe.KHR_MATERIALS_UNLIT}getMaterialType(){return f.MeshBasicMaterial}extendParams(e,t,r){const n=[];e.color=new f.Color(1,1,1),e.opacity=1;const o=t.pbrMetallicRoughness;if(o){if(Array.isArray(o.baseColorFactor)){const i=o.baseColorFactor;e.color.setRGB(i[0],i[1],i[2],f.LinearSRGBColorSpace),e.opacity=i[3]}o.baseColorTexture!==void 0&&n.push(r.assignTexture(e,"map",o.baseColorTexture,f.SRGBColorSpace))}return Promise.all(n)}}class jo{constructor(e){this.parser=e,this.name=fe.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const o=n.extensions[this.name].emissiveStrength;return o!==void 0&&(t.emissiveIntensity=o),Promise.resolve()}}class Wo{constructor(e){this.parser=e,this.name=fe.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(e,t){const r=this.parser,n=r.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const o=[],i=n.extensions[this.name];if(i.clearcoatFactor!==void 0&&(t.clearcoat=i.clearcoatFactor),i.clearcoatTexture!==void 0&&o.push(r.assignTexture(t,"clearcoatMap",i.clearcoatTexture)),i.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=i.clearcoatRoughnessFactor),i.clearcoatRoughnessTexture!==void 0&&o.push(r.assignTexture(t,"clearcoatRoughnessMap",i.clearcoatRoughnessTexture)),i.clearcoatNormalTexture!==void 0&&(o.push(r.assignTexture(t,"clearcoatNormalMap",i.clearcoatNormalTexture)),i.clearcoatNormalTexture.scale!==void 0)){const a=i.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new f.Vector2(a,a)}return Promise.all(o)}}class Yo{constructor(e){this.parser=e,this.name=fe.KHR_MATERIALS_DISPERSION}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const o=n.extensions[this.name];return t.dispersion=o.dispersion!==void 0?o.dispersion:0,Promise.resolve()}}class qo{constructor(e){this.parser=e,this.name=fe.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(e,t){const r=this.parser,n=r.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const o=[],i=n.extensions[this.name];return i.iridescenceFactor!==void 0&&(t.iridescence=i.iridescenceFactor),i.iridescenceTexture!==void 0&&o.push(r.assignTexture(t,"iridescenceMap",i.iridescenceTexture)),i.iridescenceIor!==void 0&&(t.iridescenceIOR=i.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),i.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=i.iridescenceThicknessMinimum),i.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=i.iridescenceThicknessMaximum),i.iridescenceThicknessTexture!==void 0&&o.push(r.assignTexture(t,"iridescenceThicknessMap",i.iridescenceThicknessTexture)),Promise.all(o)}}class Zo{constructor(e){this.parser=e,this.name=fe.KHR_MATERIALS_SHEEN}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(e,t){const r=this.parser,n=r.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const o=[];t.sheenColor=new f.Color(0,0,0),t.sheenRoughness=0,t.sheen=1;const i=n.extensions[this.name];if(i.sheenColorFactor!==void 0){const a=i.sheenColorFactor;t.sheenColor.setRGB(a[0],a[1],a[2],f.LinearSRGBColorSpace)}return i.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=i.sheenRoughnessFactor),i.sheenColorTexture!==void 0&&o.push(r.assignTexture(t,"sheenColorMap",i.sheenColorTexture,f.SRGBColorSpace)),i.sheenRoughnessTexture!==void 0&&o.push(r.assignTexture(t,"sheenRoughnessMap",i.sheenRoughnessTexture)),Promise.all(o)}}class Ko{constructor(e){this.parser=e,this.name=fe.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(e,t){const r=this.parser,n=r.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const o=[],i=n.extensions[this.name];return i.transmissionFactor!==void 0&&(t.transmission=i.transmissionFactor),i.transmissionTexture!==void 0&&o.push(r.assignTexture(t,"transmissionMap",i.transmissionTexture)),Promise.all(o)}}class Xo{constructor(e){this.parser=e,this.name=fe.KHR_MATERIALS_VOLUME}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(e,t){const r=this.parser,n=r.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const o=[],i=n.extensions[this.name];t.thickness=i.thicknessFactor!==void 0?i.thicknessFactor:0,i.thicknessTexture!==void 0&&o.push(r.assignTexture(t,"thicknessMap",i.thicknessTexture)),t.attenuationDistance=i.attenuationDistance||1/0;const a=i.attenuationColor||[1,1,1];return t.attenuationColor=new f.Color().setRGB(a[0],a[1],a[2],f.LinearSRGBColorSpace),Promise.all(o)}}class $o{constructor(e){this.parser=e,this.name=fe.KHR_MATERIALS_IOR}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const o=n.extensions[this.name];return t.ior=o.ior!==void 0?o.ior:1.5,Promise.resolve()}}class Qo{constructor(e){this.parser=e,this.name=fe.KHR_MATERIALS_SPECULAR}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(e,t){const r=this.parser,n=r.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const o=[],i=n.extensions[this.name];t.specularIntensity=i.specularFactor!==void 0?i.specularFactor:1,i.specularTexture!==void 0&&o.push(r.assignTexture(t,"specularIntensityMap",i.specularTexture));const a=i.specularColorFactor||[1,1,1];return t.specularColor=new f.Color().setRGB(a[0],a[1],a[2],f.LinearSRGBColorSpace),i.specularColorTexture!==void 0&&o.push(r.assignTexture(t,"specularColorMap",i.specularColorTexture,f.SRGBColorSpace)),Promise.all(o)}}class Jo{constructor(e){this.parser=e,this.name=fe.EXT_MATERIALS_BUMP}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(e,t){const r=this.parser,n=r.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const o=[],i=n.extensions[this.name];return t.bumpScale=i.bumpFactor!==void 0?i.bumpFactor:1,i.bumpTexture!==void 0&&o.push(r.assignTexture(t,"bumpMap",i.bumpTexture)),Promise.all(o)}}class Ho{constructor(e){this.parser=e,this.name=fe.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(e,t){const r=this.parser,n=r.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const o=[],i=n.extensions[this.name];return i.anisotropyStrength!==void 0&&(t.anisotropy=i.anisotropyStrength),i.anisotropyRotation!==void 0&&(t.anisotropyRotation=i.anisotropyRotation),i.anisotropyTexture!==void 0&&o.push(r.assignTexture(t,"anisotropyMap",i.anisotropyTexture)),Promise.all(o)}}class ea{constructor(e){this.parser=e,this.name=fe.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,r=t.json,n=r.textures[e];if(!n.extensions||!n.extensions[this.name])return null;const o=n.extensions[this.name],i=t.options.ktx2Loader;if(!i){if(r.extensionsRequired&&r.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,o.source,i)}}class ta{constructor(e){this.parser=e,this.name=fe.EXT_TEXTURE_WEBP,this.isSupported=null}loadTexture(e){const t=this.name,r=this.parser,n=r.json,o=n.textures[e];if(!o.extensions||!o.extensions[t])return null;const i=o.extensions[t],a=n.images[i.source];let c=r.textureLoader;if(a.uri){const h=r.options.manager.getHandler(a.uri);h!==null&&(c=h)}return this.detectSupport().then(function(h){if(h)return r.loadTextureImage(e,i.source,c);if(n.extensionsRequired&&n.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported.");return r.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const t=new Image;t.src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}}class ra{constructor(e){this.parser=e,this.name=fe.EXT_TEXTURE_AVIF,this.isSupported=null}loadTexture(e){const t=this.name,r=this.parser,n=r.json,o=n.textures[e];if(!o.extensions||!o.extensions[t])return null;const i=o.extensions[t],a=n.images[i.source];let c=r.textureLoader;if(a.uri){const h=r.options.manager.getHandler(a.uri);h!==null&&(c=h)}return this.detectSupport().then(function(h){if(h)return r.loadTextureImage(e,i.source,c);if(n.extensionsRequired&&n.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported.");return r.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const t=new Image;t.src="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI=",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}}class na{constructor(e){this.name=fe.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,r=t.bufferViews[e];if(r.extensions&&r.extensions[this.name]){const n=r.extensions[this.name],o=this.parser.getDependency("buffer",n.buffer),i=this.parser.options.meshoptDecoder;if(!i||!i.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return o.then(function(a){const c=n.byteOffset||0,h=n.byteLength||0,d=n.count,u=n.byteStride,l=new Uint8Array(a,c,h);return i.decodeGltfBufferAsync?i.decodeGltfBufferAsync(d,u,l,n.mode,n.filter).then(function(v){return v.buffer}):i.ready.then(function(){const v=new ArrayBuffer(d*u);return i.decodeGltfBuffer(new Uint8Array(v),d,u,l,n.mode,n.filter),v})})}else return null}}class ia{constructor(e){this.name=fe.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,r=t.nodes[e];if(!r.extensions||!r.extensions[this.name]||r.mesh===void 0)return null;const n=t.meshes[r.mesh];for(const h of n.primitives)if(h.mode!==st.TRIANGLES&&h.mode!==st.TRIANGLE_STRIP&&h.mode!==st.TRIANGLE_FAN&&h.mode!==void 0)return null;const i=r.extensions[this.name].attributes,a=[],c={};for(const h in i)a.push(this.parser.getDependency("accessor",i[h]).then(d=>(c[h]=d,c[h])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(h=>{const d=h.pop(),u=d.isGroup?d.children:[d],l=h[0].count,v=[];for(const b of u){const S=new f.Matrix4,g=new f.Vector3,x=new f.Quaternion,w=new f.Vector3(1,1,1),T=new f.InstancedMesh(b.geometry,b.material,l);for(let A=0;A<l;A++)c.TRANSLATION&&g.fromBufferAttribute(c.TRANSLATION,A),c.ROTATION&&x.fromBufferAttribute(c.ROTATION,A),c.SCALE&&w.fromBufferAttribute(c.SCALE,A),T.setMatrixAt(A,S.compose(g,x,w));for(const A in c)if(A==="_COLOR_0"){const P=c[A];T.instanceColor=new f.InstancedBufferAttribute(P.array,P.itemSize,P.normalized)}else A!=="TRANSLATION"&&A!=="ROTATION"&&A!=="SCALE"&&b.geometry.setAttribute(A,c[A]);f.Object3D.prototype.copy.call(T,b),this.parser.assignFinalMaterial(T),v.push(T)}return d.isGroup?(d.clear(),d.add(...v),d):v[0]}))}}const $i="glTF",zr=12,Qi={JSON:1313821514,BIN:5130562};class sa{constructor(e){this.name=fe.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,zr),r=new TextDecoder;if(this.header={magic:r.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==$i)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const n=this.header.length-zr,o=new DataView(e,zr);let i=0;for(;i<n;){const a=o.getUint32(i,!0);i+=4;const c=o.getUint32(i,!0);if(i+=4,c===Qi.JSON){const h=new Uint8Array(e,zr+i,a);this.content=r.decode(h)}else if(c===Qi.BIN){const h=zr+i;this.body=e.slice(h,h+a)}i+=a}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class oa{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=fe.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const r=this.json,n=this.dracoLoader,o=e.extensions[this.name].bufferView,i=e.extensions[this.name].attributes,a={},c={},h={};for(const d in i){const u=Jn[d]||d.toLowerCase();a[u]=i[d]}for(const d in e.attributes){const u=Jn[d]||d.toLowerCase();if(i[d]!==void 0){const l=r.accessors[e.attributes[d]],v=hr[l.componentType];h[u]=v.name,c[u]=l.normalized===!0}}return t.getDependency("bufferView",o).then(function(d){return new Promise(function(u,l){n.decodeDracoFile(d,function(v){for(const b in v.attributes){const S=v.attributes[b],g=c[b];g!==void 0&&(S.normalized=g)}u(v)},a,h,f.LinearSRGBColorSpace,l)})})}}class aa{constructor(){this.name=fe.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 ca{constructor(){this.name=fe.KHR_MESH_QUANTIZATION}}class Ji extends f.Interpolant{constructor(e,t,r,n){super(e,t,r,n)}copySampleValue_(e){const t=this.resultBuffer,r=this.sampleValues,n=this.valueSize,o=e*n*3+n;for(let i=0;i!==n;i++)t[i]=r[o+i];return t}interpolate_(e,t,r,n){const o=this.resultBuffer,i=this.sampleValues,a=this.valueSize,c=a*2,h=a*3,d=n-t,u=(r-t)/d,l=u*u,v=l*u,b=e*h,S=b-h,g=-2*v+3*l,x=v-l,w=1-g,T=x-l+u;for(let A=0;A!==a;A++){const P=i[S+A+a],D=i[S+A+c]*d,R=i[b+A+a],O=i[b+A]*d;o[A]=w*P+T*D+g*R+x*O}return o}}const la=new f.Quaternion;class ua extends Ji{interpolate_(e,t,r,n){const o=super.interpolate_(e,t,r,n);return la.fromArray(o).normalize().toArray(o),o}}const st={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},hr={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},Hi={9728:f.NearestFilter,9729:f.LinearFilter,9984:f.NearestMipmapNearestFilter,9985:f.LinearMipmapNearestFilter,9986:f.NearestMipmapLinearFilter,9987:f.LinearMipmapLinearFilter},es={33071:f.ClampToEdgeWrapping,33648:f.MirroredRepeatWrapping,10497:f.RepeatWrapping},Qn={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Jn={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"},Bt={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},ha={CUBICSPLINE:void 0,LINEAR:f.InterpolateLinear,STEP:f.InterpolateDiscrete},Hn={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function fa(s){return s.DefaultMaterial===void 0&&(s.DefaultMaterial=new f.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:f.FrontSide})),s.DefaultMaterial}function qt(s,e,t){for(const r in t.extensions)s[r]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[r]=t.extensions[r])}function Mt(s,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(s.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function da(s,e,t){let r=!1,n=!1,o=!1;for(let h=0,d=e.length;h<d;h++){const u=e[h];if(u.POSITION!==void 0&&(r=!0),u.NORMAL!==void 0&&(n=!0),u.COLOR_0!==void 0&&(o=!0),r&&n&&o)break}if(!r&&!n&&!o)return Promise.resolve(s);const i=[],a=[],c=[];for(let h=0,d=e.length;h<d;h++){const u=e[h];if(r){const l=u.POSITION!==void 0?t.getDependency("accessor",u.POSITION):s.attributes.position;i.push(l)}if(n){const l=u.NORMAL!==void 0?t.getDependency("accessor",u.NORMAL):s.attributes.normal;a.push(l)}if(o){const l=u.COLOR_0!==void 0?t.getDependency("accessor",u.COLOR_0):s.attributes.color;c.push(l)}}return Promise.all([Promise.all(i),Promise.all(a),Promise.all(c)]).then(function(h){const d=h[0],u=h[1],l=h[2];return r&&(s.morphAttributes.position=d),n&&(s.morphAttributes.normal=u),o&&(s.morphAttributes.color=l),s.morphTargetsRelative=!0,s})}function pa(s,e){if(s.updateMorphTargets(),e.weights!==void 0)for(let t=0,r=e.weights.length;t<r;t++)s.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(s.morphTargetInfluences.length===t.length){s.morphTargetDictionary={};for(let r=0,n=t.length;r<n;r++)s.morphTargetDictionary[t[r]]=r}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function ma(s){let e;const t=s.extensions&&s.extensions[fe.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+ei(t.attributes):e=s.indices+":"+ei(s.attributes)+":"+s.mode,s.targets!==void 0)for(let r=0,n=s.targets.length;r<n;r++)e+=":"+ei(s.targets[r]);return e}function ei(s){let e="";const t=Object.keys(s).sort();for(let r=0,n=t.length;r<n;r++)e+=t[r]+":"+s[t[r]]+";";return e}function ti(s){switch(s){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 ga(s){return s.search(/\.jpe?g($|\?)/i)>0||s.search(/^data\:image\/jpeg/)===0?"image/jpeg":s.search(/\.webp($|\?)/i)>0||s.search(/^data\:image\/webp/)===0?"image/webp":"image/png"}const va=new f.Matrix4;class ya{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new Uo,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 r=!1,n=-1,o=!1,i=-1;if(typeof navigator<"u"){const a=navigator.userAgent;r=/^((?!chrome|android).)*safari/i.test(a)===!0;const c=a.match(/Version\/(\d+)/);n=r&&c?parseInt(c[1],10):-1,o=a.indexOf("Firefox")>-1,i=o?a.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||r&&n<17||o&&i<98?this.textureLoader=new f.TextureLoader(this.options.manager):this.textureLoader=new f.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new f.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 r=this,n=this.json,o=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(i){return i._markDefs&&i._markDefs()}),Promise.all(this._invokeAll(function(i){return i.beforeRoot&&i.beforeRoot()})).then(function(){return Promise.all([r.getDependencies("scene"),r.getDependencies("animation"),r.getDependencies("camera")])}).then(function(i){const a={scene:i[0][n.scene||0],scenes:i[0],animations:i[1],cameras:i[2],asset:n.asset,parser:r,userData:{}};return qt(o,a,n),Mt(a,n),Promise.all(r._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||[],r=this.json.meshes||[];for(let n=0,o=t.length;n<o;n++){const i=t[n].joints;for(let a=0,c=i.length;a<c;a++)e[i[a]].isBone=!0}for(let n=0,o=e.length;n<o;n++){const i=e[n];i.mesh!==void 0&&(this._addNodeRef(this.meshCache,i.mesh),i.skin!==void 0&&(r[i.mesh].isSkinnedMesh=!0)),i.camera!==void 0&&this._addNodeRef(this.cameraCache,i.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,r){if(e.refs[t]<=1)return r;const n=r.clone(),o=(i,a)=>{const c=this.associations.get(i);c!=null&&this.associations.set(a,c);for(const[h,d]of i.children.entries())o(d,a.children[h])};return o(r,n),n.name+="_instance_"+e.uses[t]++,n}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let r=0;r<t.length;r++){const n=e(t[r]);if(n)return n}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const r=[];for(let n=0;n<t.length;n++){const o=e(t[n]);o&&r.push(o)}return r}getDependency(e,t){const r=e+":"+t;let n=this.cache.get(r);if(!n){switch(e){case"scene":n=this.loadScene(t);break;case"node":n=this._invokeOne(function(o){return o.loadNode&&o.loadNode(t)});break;case"mesh":n=this._invokeOne(function(o){return o.loadMesh&&o.loadMesh(t)});break;case"accessor":n=this.loadAccessor(t);break;case"bufferView":n=this._invokeOne(function(o){return o.loadBufferView&&o.loadBufferView(t)});break;case"buffer":n=this.loadBuffer(t);break;case"material":n=this._invokeOne(function(o){return o.loadMaterial&&o.loadMaterial(t)});break;case"texture":n=this._invokeOne(function(o){return o.loadTexture&&o.loadTexture(t)});break;case"skin":n=this.loadSkin(t);break;case"animation":n=this._invokeOne(function(o){return o.loadAnimation&&o.loadAnimation(t)});break;case"camera":n=this.loadCamera(t);break;default:if(n=this._invokeOne(function(o){return o!=this&&o.getDependency&&o.getDependency(e,t)}),!n)throw new Error("Unknown type: "+e);break}this.cache.add(r,n)}return n}getDependencies(e){let t=this.cache.get(e);if(!t){const r=this,n=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(n.map(function(o,i){return r.getDependency(e,i)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],r=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[fe.KHR_BINARY_GLTF].body);const n=this.options;return new Promise(function(o,i){r.load(f.LoaderUtils.resolveURL(t.uri,n.path),o,void 0,function(){i(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(r){const n=t.byteLength||0,o=t.byteOffset||0;return r.slice(o,o+n)})}loadAccessor(e){const t=this,r=this.json,n=this.json.accessors[e];if(n.bufferView===void 0&&n.sparse===void 0){const i=Qn[n.type],a=hr[n.componentType],c=n.normalized===!0,h=new a(n.count*i);return Promise.resolve(new f.BufferAttribute(h,i,c))}const o=[];return n.bufferView!==void 0?o.push(this.getDependency("bufferView",n.bufferView)):o.push(null),n.sparse!==void 0&&(o.push(this.getDependency("bufferView",n.sparse.indices.bufferView)),o.push(this.getDependency("bufferView",n.sparse.values.bufferView))),Promise.all(o).then(function(i){const a=i[0],c=Qn[n.type],h=hr[n.componentType],d=h.BYTES_PER_ELEMENT,u=d*c,l=n.byteOffset||0,v=n.bufferView!==void 0?r.bufferViews[n.bufferView].byteStride:void 0,b=n.normalized===!0;let S,g;if(v&&v!==u){const x=Math.floor(l/v),w="InterleavedBuffer:"+n.bufferView+":"+n.componentType+":"+x+":"+n.count;let T=t.cache.get(w);T||(S=new h(a,x*v,n.count*v/d),T=new f.InterleavedBuffer(S,v/d),t.cache.add(w,T)),g=new f.InterleavedBufferAttribute(T,c,l%v/d,b)}else a===null?S=new h(n.count*c):S=new h(a,l,n.count*c),g=new f.BufferAttribute(S,c,b);if(n.sparse!==void 0){const x=Qn.SCALAR,w=hr[n.sparse.indices.componentType],T=n.sparse.indices.byteOffset||0,A=n.sparse.values.byteOffset||0,P=new w(i[1],T,n.sparse.count*x),D=new h(i[2],A,n.sparse.count*c);a!==null&&(g=new f.BufferAttribute(g.array.slice(),g.itemSize,g.normalized));for(let R=0,O=P.length;R<O;R++){const L=P[R];if(g.setX(L,D[R*c]),c>=2&&g.setY(L,D[R*c+1]),c>=3&&g.setZ(L,D[R*c+2]),c>=4&&g.setW(L,D[R*c+3]),c>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}}return g})}loadTexture(e){const t=this.json,r=this.options,o=t.textures[e].source,i=t.images[o];let a=this.textureLoader;if(i.uri){const c=r.manager.getHandler(i.uri);c!==null&&(a=c)}return this.loadTextureImage(e,o,a)}loadTextureImage(e,t,r){const n=this,o=this.json,i=o.textures[e],a=o.images[t],c=(a.uri||a.bufferView)+":"+i.sampler;if(this.textureCache[c])return this.textureCache[c];const h=this.loadImageSource(t,r).then(function(d){d.flipY=!1,d.name=i.name||a.name||"",d.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(d.name=a.uri);const l=(o.samplers||{})[i.sampler]||{};return d.magFilter=Hi[l.magFilter]||f.LinearFilter,d.minFilter=Hi[l.minFilter]||f.LinearMipmapLinearFilter,d.wrapS=es[l.wrapS]||f.RepeatWrapping,d.wrapT=es[l.wrapT]||f.RepeatWrapping,n.associations.set(d,{textures:e}),d}).catch(function(){return null});return this.textureCache[c]=h,h}loadImageSource(e,t){const r=this,n=this.json,o=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(u=>u.clone());const i=n.images[e],a=self.URL||self.webkitURL;let c=i.uri||"",h=!1;if(i.bufferView!==void 0)c=r.getDependency("bufferView",i.bufferView).then(function(u){h=!0;const l=new Blob([u],{type:i.mimeType});return c=a.createObjectURL(l),c});else if(i.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const d=Promise.resolve(c).then(function(u){return new Promise(function(l,v){let b=l;t.isImageBitmapLoader===!0&&(b=function(S){const g=new f.Texture(S);g.needsUpdate=!0,l(g)}),t.load(f.LoaderUtils.resolveURL(u,o.path),b,void 0,v)})}).then(function(u){return h===!0&&a.revokeObjectURL(c),Mt(u,i),u.userData.mimeType=i.mimeType||ga(i.uri),u}).catch(function(u){throw console.error("THREE.GLTFLoader: Couldn't load texture",c),u});return this.sourceCache[e]=d,d}assignTexture(e,t,r,n){const o=this;return this.getDependency("texture",r.index).then(function(i){if(!i)return null;if(r.texCoord!==void 0&&r.texCoord>0&&(i=i.clone(),i.channel=r.texCoord),o.extensions[fe.KHR_TEXTURE_TRANSFORM]){const a=r.extensions!==void 0?r.extensions[fe.KHR_TEXTURE_TRANSFORM]:void 0;if(a){const c=o.associations.get(i);i=o.extensions[fe.KHR_TEXTURE_TRANSFORM].extendTexture(i,a),o.associations.set(i,c)}}return n!==void 0&&(i.colorSpace=n),e[t]=i,i})}assignFinalMaterial(e){const t=e.geometry;let r=e.material;const n=t.attributes.tangent===void 0,o=t.attributes.color!==void 0,i=t.attributes.normal===void 0;if(e.isPoints){const a="PointsMaterial:"+r.uuid;let c=this.cache.get(a);c||(c=new f.PointsMaterial,f.Material.prototype.copy.call(c,r),c.color.copy(r.color),c.map=r.map,c.sizeAttenuation=!1,this.cache.add(a,c)),r=c}else if(e.isLine){const a="LineBasicMaterial:"+r.uuid;let c=this.cache.get(a);c||(c=new f.LineBasicMaterial,f.Material.prototype.copy.call(c,r),c.color.copy(r.color),c.map=r.map,this.cache.add(a,c)),r=c}if(n||o||i){let a="ClonedMaterial:"+r.uuid+":";n&&(a+="derivative-tangents:"),o&&(a+="vertex-colors:"),i&&(a+="flat-shading:");let c=this.cache.get(a);c||(c=r.clone(),o&&(c.vertexColors=!0),i&&(c.flatShading=!0),n&&(c.normalScale&&(c.normalScale.y*=-1),c.clearcoatNormalScale&&(c.clearcoatNormalScale.y*=-1)),this.cache.add(a,c),this.associations.set(c,this.associations.get(r))),r=c}e.material=r}getMaterialType(){return f.MeshStandardMaterial}loadMaterial(e){const t=this,r=this.json,n=this.extensions,o=r.materials[e];let i;const a={},c=o.extensions||{},h=[];if(c[fe.KHR_MATERIALS_UNLIT]){const u=n[fe.KHR_MATERIALS_UNLIT];i=u.getMaterialType(),h.push(u.extendParams(a,o,t))}else{const u=o.pbrMetallicRoughness||{};if(a.color=new f.Color(1,1,1),a.opacity=1,Array.isArray(u.baseColorFactor)){const l=u.baseColorFactor;a.color.setRGB(l[0],l[1],l[2],f.LinearSRGBColorSpace),a.opacity=l[3]}u.baseColorTexture!==void 0&&h.push(t.assignTexture(a,"map",u.baseColorTexture,f.SRGBColorSpace)),a.metalness=u.metallicFactor!==void 0?u.metallicFactor:1,a.roughness=u.roughnessFactor!==void 0?u.roughnessFactor:1,u.metallicRoughnessTexture!==void 0&&(h.push(t.assignTexture(a,"metalnessMap",u.metallicRoughnessTexture)),h.push(t.assignTexture(a,"roughnessMap",u.metallicRoughnessTexture))),i=this._invokeOne(function(l){return l.getMaterialType&&l.getMaterialType(e)}),h.push(Promise.all(this._invokeAll(function(l){return l.extendMaterialParams&&l.extendMaterialParams(e,a)})))}o.doubleSided===!0&&(a.side=f.DoubleSide);const d=o.alphaMode||Hn.OPAQUE;if(d===Hn.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,d===Hn.MASK&&(a.alphaTest=o.alphaCutoff!==void 0?o.alphaCutoff:.5)),o.normalTexture!==void 0&&i!==f.MeshBasicMaterial&&(h.push(t.assignTexture(a,"normalMap",o.normalTexture)),a.normalScale=new f.Vector2(1,1),o.normalTexture.scale!==void 0)){const u=o.normalTexture.scale;a.normalScale.set(u,u)}if(o.occlusionTexture!==void 0&&i!==f.MeshBasicMaterial&&(h.push(t.assignTexture(a,"aoMap",o.occlusionTexture)),o.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=o.occlusionTexture.strength)),o.emissiveFactor!==void 0&&i!==f.MeshBasicMaterial){const u=o.emissiveFactor;a.emissive=new f.Color().setRGB(u[0],u[1],u[2],f.LinearSRGBColorSpace)}return o.emissiveTexture!==void 0&&i!==f.MeshBasicMaterial&&h.push(t.assignTexture(a,"emissiveMap",o.emissiveTexture,f.SRGBColorSpace)),Promise.all(h).then(function(){const u=new i(a);return o.name&&(u.name=o.name),Mt(u,o),t.associations.set(u,{materials:e}),o.extensions&&qt(n,u,o),u})}createUniqueName(e){const t=f.PropertyBinding.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,r=this.extensions,n=this.primitiveCache;function o(a){return r[fe.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,t).then(function(c){return ts(c,a,t)})}const i=[];for(let a=0,c=e.length;a<c;a++){const h=e[a],d=ma(h),u=n[d];if(u)i.push(u.promise);else{let l;h.extensions&&h.extensions[fe.KHR_DRACO_MESH_COMPRESSION]?l=o(h):l=ts(new f.BufferGeometry,h,t),n[d]={primitive:h,promise:l},i.push(l)}}return Promise.all(i)}loadMesh(e){const t=this,r=this.json,n=this.extensions,o=r.meshes[e],i=o.primitives,a=[];for(let c=0,h=i.length;c<h;c++){const d=i[c].material===void 0?fa(this.cache):this.getDependency("material",i[c].material);a.push(d)}return a.push(t.loadGeometries(i)),Promise.all(a).then(function(c){const h=c.slice(0,c.length-1),d=c[c.length-1],u=[];for(let v=0,b=d.length;v<b;v++){const S=d[v],g=i[v];let x;const w=h[v];if(g.mode===st.TRIANGLES||g.mode===st.TRIANGLE_STRIP||g.mode===st.TRIANGLE_FAN||g.mode===void 0)x=o.isSkinnedMesh===!0?new f.SkinnedMesh(S,w):new f.Mesh(S,w),x.isSkinnedMesh===!0&&x.normalizeSkinWeights(),g.mode===st.TRIANGLE_STRIP?x.geometry=Xi(x.geometry,f.TriangleStripDrawMode):g.mode===st.TRIANGLE_FAN&&(x.geometry=Xi(x.geometry,f.TriangleFanDrawMode));else if(g.mode===st.LINES)x=new f.LineSegments(S,w);else if(g.mode===st.LINE_STRIP)x=new f.Line(S,w);else if(g.mode===st.LINE_LOOP)x=new f.LineLoop(S,w);else if(g.mode===st.POINTS)x=new f.Points(S,w);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+g.mode);Object.keys(x.geometry.morphAttributes).length>0&&pa(x,o),x.name=t.createUniqueName(o.name||"mesh_"+e),Mt(x,o),g.extensions&&qt(n,x,g),t.assignFinalMaterial(x),u.push(x)}for(let v=0,b=u.length;v<b;v++)t.associations.set(u[v],{meshes:e,primitives:v});if(u.length===1)return o.extensions&&qt(n,u[0],o),u[0];const l=new f.Group;o.extensions&&qt(n,l,o),t.associations.set(l,{meshes:e});for(let v=0,b=u.length;v<b;v++)l.add(u[v]);return l})}loadCamera(e){let t;const r=this.json.cameras[e],n=r[r.type];if(!n){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return r.type==="perspective"?t=new f.PerspectiveCamera(f.MathUtils.radToDeg(n.yfov),n.aspectRatio||1,n.znear||1,n.zfar||2e6):r.type==="orthographic"&&(t=new f.OrthographicCamera(-n.xmag,n.xmag,n.ymag,-n.ymag,n.znear,n.zfar)),r.name&&(t.name=this.createUniqueName(r.name)),Mt(t,r),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],r=[];for(let n=0,o=t.joints.length;n<o;n++)r.push(this._loadNodeShallow(t.joints[n]));return t.inverseBindMatrices!==void 0?r.push(this.getDependency("accessor",t.inverseBindMatrices)):r.push(null),Promise.all(r).then(function(n){const o=n.pop(),i=n,a=[],c=[];for(let h=0,d=i.length;h<d;h++){const u=i[h];if(u){a.push(u);const l=new f.Matrix4;o!==null&&l.fromArray(o.array,h*16),c.push(l)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[h])}return new f.Skeleton(a,c)})}loadAnimation(e){const t=this.json,r=this,n=t.animations[e],o=n.name?n.name:"animation_"+e,i=[],a=[],c=[],h=[],d=[];for(let u=0,l=n.channels.length;u<l;u++){const v=n.channels[u],b=n.samplers[v.sampler],S=v.target,g=S.node,x=n.parameters!==void 0?n.parameters[b.input]:b.input,w=n.parameters!==void 0?n.parameters[b.output]:b.output;S.node!==void 0&&(i.push(this.getDependency("node",g)),a.push(this.getDependency("accessor",x)),c.push(this.getDependency("accessor",w)),h.push(b),d.push(S))}return Promise.all([Promise.all(i),Promise.all(a),Promise.all(c),Promise.all(h),Promise.all(d)]).then(function(u){const l=u[0],v=u[1],b=u[2],S=u[3],g=u[4],x=[];for(let w=0,T=l.length;w<T;w++){const A=l[w],P=v[w],D=b[w],R=S[w],O=g[w];if(A===void 0)continue;A.updateMatrix&&A.updateMatrix();const L=r._createAnimationTracks(A,P,D,R,O);if(L)for(let E=0;E<L.length;E++)x.push(L[E])}return new f.AnimationClip(o,void 0,x)})}createNodeMesh(e){const t=this.json,r=this,n=t.nodes[e];return n.mesh===void 0?null:r.getDependency("mesh",n.mesh).then(function(o){const i=r._getNodeRef(r.meshCache,n.mesh,o);return n.weights!==void 0&&i.traverse(function(a){if(a.isMesh)for(let c=0,h=n.weights.length;c<h;c++)a.morphTargetInfluences[c]=n.weights[c]}),i})}loadNode(e){const t=this.json,r=this,n=t.nodes[e],o=r._loadNodeShallow(e),i=[],a=n.children||[];for(let h=0,d=a.length;h<d;h++)i.push(r.getDependency("node",a[h]));const c=n.skin===void 0?Promise.resolve(null):r.getDependency("skin",n.skin);return Promise.all([o,Promise.all(i),c]).then(function(h){const d=h[0],u=h[1],l=h[2];l!==null&&d.traverse(function(v){v.isSkinnedMesh&&v.bind(l,va)});for(let v=0,b=u.length;v<b;v++)d.add(u[v]);return d})}_loadNodeShallow(e){const t=this.json,r=this.extensions,n=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const o=t.nodes[e],i=o.name?n.createUniqueName(o.name):"",a=[],c=n._invokeOne(function(h){return h.createNodeMesh&&h.createNodeMesh(e)});return c&&a.push(c),o.camera!==void 0&&a.push(n.getDependency("camera",o.camera).then(function(h){return n._getNodeRef(n.cameraCache,o.camera,h)})),n._invokeAll(function(h){return h.createNodeAttachment&&h.createNodeAttachment(e)}).forEach(function(h){a.push(h)}),this.nodeCache[e]=Promise.all(a).then(function(h){let d;if(o.isBone===!0?d=new f.Bone:h.length>1?d=new f.Group:h.length===1?d=h[0]:d=new f.Object3D,d!==h[0])for(let u=0,l=h.length;u<l;u++)d.add(h[u]);if(o.name&&(d.userData.name=o.name,d.name=i),Mt(d,o),o.extensions&&qt(r,d,o),o.matrix!==void 0){const u=new f.Matrix4;u.fromArray(o.matrix),d.applyMatrix4(u)}else o.translation!==void 0&&d.position.fromArray(o.translation),o.rotation!==void 0&&d.quaternion.fromArray(o.rotation),o.scale!==void 0&&d.scale.fromArray(o.scale);return n.associations.has(d)||n.associations.set(d,{}),n.associations.get(d).nodes=e,d}),this.nodeCache[e]}loadScene(e){const t=this.extensions,r=this.json.scenes[e],n=this,o=new f.Group;r.name&&(o.name=n.createUniqueName(r.name)),Mt(o,r),r.extensions&&qt(t,o,r);const i=r.nodes||[],a=[];for(let c=0,h=i.length;c<h;c++)a.push(n.getDependency("node",i[c]));return Promise.all(a).then(function(c){for(let d=0,u=c.length;d<u;d++)o.add(c[d]);const h=d=>{const u=new Map;for(const[l,v]of n.associations)(l instanceof f.Material||l instanceof f.Texture)&&u.set(l,v);return d.traverse(l=>{const v=n.associations.get(l);v!=null&&u.set(l,v)}),u};return n.associations=h(o),o})}_createAnimationTracks(e,t,r,n,o){const i=[],a=e.name?e.name:e.uuid,c=[];Bt[o.path]===Bt.weights?e.traverse(function(l){l.morphTargetInfluences&&c.push(l.name?l.name:l.uuid)}):c.push(a);let h;switch(Bt[o.path]){case Bt.weights:h=f.NumberKeyframeTrack;break;case Bt.rotation:h=f.QuaternionKeyframeTrack;break;case Bt.position:case Bt.scale:h=f.VectorKeyframeTrack;break;default:switch(r.itemSize){case 1:h=f.NumberKeyframeTrack;break;case 2:case 3:default:h=f.VectorKeyframeTrack;break}break}const d=n.interpolation!==void 0?ha[n.interpolation]:f.InterpolateLinear,u=this._getArrayFromAccessor(r);for(let l=0,v=c.length;l<v;l++){const b=new h(c[l]+"."+Bt[o.path],t.array,u,d);n.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(b),i.push(b)}return i}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const r=ti(t.constructor),n=new Float32Array(t.length);for(let o=0,i=t.length;o<i;o++)n[o]=t[o]*r;t=n}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(r){const n=this instanceof f.QuaternionKeyframeTrack?ua:Ji;return new n(this.times,this.values,this.getValueSize()/3,r)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function ba(s,e,t){const r=e.attributes,n=new f.Box3;if(r.POSITION!==void 0){const a=t.json.accessors[r.POSITION],c=a.min,h=a.max;if(c!==void 0&&h!==void 0){if(n.set(new f.Vector3(c[0],c[1],c[2]),new f.Vector3(h[0],h[1],h[2])),a.normalized){const d=ti(hr[a.componentType]);n.min.multiplyScalar(d),n.max.multiplyScalar(d)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const o=e.targets;if(o!==void 0){const a=new f.Vector3,c=new f.Vector3;for(let h=0,d=o.length;h<d;h++){const u=o[h];if(u.POSITION!==void 0){const l=t.json.accessors[u.POSITION],v=l.min,b=l.max;if(v!==void 0&&b!==void 0){if(c.setX(Math.max(Math.abs(v[0]),Math.abs(b[0]))),c.setY(Math.max(Math.abs(v[1]),Math.abs(b[1]))),c.setZ(Math.max(Math.abs(v[2]),Math.abs(b[2]))),l.normalized){const S=ti(hr[l.componentType]);c.multiplyScalar(S)}a.max(c)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}n.expandByVector(a)}s.boundingBox=n;const i=new f.Sphere;n.getCenter(i.center),i.radius=n.min.distanceTo(n.max)/2,s.boundingSphere=i}function ts(s,e,t){const r=e.attributes,n=[];function o(i,a){return t.getDependency("accessor",i).then(function(c){s.setAttribute(a,c)})}for(const i in r){const a=Jn[i]||i.toLowerCase();a in s.attributes||n.push(o(r[i],a))}if(e.indices!==void 0&&!s.index){const i=t.getDependency("accessor",e.indices).then(function(a){s.setIndex(a)});n.push(i)}return f.ColorManagement.workingColorSpace!==f.LinearSRGBColorSpace&&"COLOR_0"in r&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${f.ColorManagement.workingColorSpace}" not supported.`),Mt(s,e),ba(s,e,t),Promise.all(n).then(function(){return e.targets!==void 0?da(s,e.targets,t):s})}class xa{constructor(){this.loadingManager=new M.LoadingManager,this.loader=new Eo(this.loadingManager)}async load(e){try{return new Promise(t=>{this.loader.load(e,r=>{var o;const n={scene:new We(r.scene),animations:this.convertAnimations(r.animations),cameras:(o=r.cameras)==null?void 0:o.map(i=>{const a=i instanceof M.PerspectiveCamera,c=i instanceof M.OrthographicCamera;return{name:i.name,type:i.type,fov:a?i.fov:void 0,aspect:a?i.aspect:void 0,near:a||c?i.near:.1,far:a||c?i.far:1e3}}),userData:r.userData};t(K.ok(n))},r=>{if(r.total>0){const n=r.loaded/r.total*100;console.log(`Loading: ${n.toFixed(0)}%`)}},r=>{t(K.err(new oe("Failed to load GLTF model",ue.MODEL_LOAD_FAILED,{url:e,originalError:r})))})})}catch(t){return K.err(new oe("Failed to initiate model loading",ue.MODEL_LOAD_FAILED,{url:e,originalError:t}))}}supports(e){var r;const t=(r=e.split(".").pop())==null?void 0:r.toLowerCase();return t==="gltf"||t==="glb"}convertAnimations(e){return e.map(t=>({name:t.name,duration:t.duration,tracks:t.tracks.map(r=>({name:r.name,type:this.getTrackType(r),times:r.times,values:r.values}))}))}getTrackType(e){return e instanceof M.VectorKeyframeTrack?"vector":e instanceof M.QuaternionKeyframeTrack?"quaternion":e instanceof M.NumberKeyframeTrack?"number":e instanceof M.BooleanKeyframeTrack?"boolean":"number"}}class rs{static createLoader(e){var r;const t=(r=e.split(".").pop())==null?void 0:r.toLowerCase();switch(t){case"gltf":case"glb":return new xa;default:throw new oe(`Unsupported file format: ${t}`,ue.UNSUPPORTED_FORMAT,{url:e,extension:t})}}}const ns={type:"change"},ri={type:"start"},is={type:"end"},mn=new f.Ray,ss=new f.Plane,wa=Math.cos(70*f.MathUtils.DEG2RAD),Le=new f.Vector3,Ke=2*Math.PI,xe={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},ni=1e-6;class os extends f.Controls{constructor(e,t=null){super(e,t),this.state=xe.NONE,this.enabled=!0,this.target=new f.Vector3,this.cursor=new f.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.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:f.MOUSE.ROTATE,MIDDLE:f.MOUSE.DOLLY,RIGHT:f.MOUSE.PAN},this.touches={ONE:f.TOUCH.ROTATE,TWO:f.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 f.Vector3,this._lastQuaternion=new f.Quaternion,this._lastTargetPosition=new f.Vector3,this._quat=new f.Quaternion().setFromUnitVectors(e.up,new f.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new f.Spherical,this._sphericalDelta=new f.Spherical,this._scale=1,this._panOffset=new f.Vector3,this._rotateStart=new f.Vector2,this._rotateEnd=new f.Vector2,this._rotateDelta=new f.Vector2,this._panStart=new f.Vector2,this._panEnd=new f.Vector2,this._panDelta=new f.Vector2,this._dollyStart=new f.Vector2,this._dollyEnd=new f.Vector2,this._dollyDelta=new f.Vector2,this._dollyDirection=new f.Vector3,this._mouse=new f.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=Sa.bind(this),this._onPointerDown=_a.bind(this),this._onPointerUp=Ta.bind(this),this._onContextMenu=Ra.bind(this),this._onMouseWheel=Ia.bind(this),this._onKeyDown=Ca.bind(this),this._onTouchStart=Pa.bind(this),this._onTouchMove=Da.bind(this),this._onMouseDown=Aa.bind(this),this._onMouseMove=Ma.bind(this),this._interceptControlDown=Fa.bind(this),this._interceptControlUp=Oa.bind(this),this.domElement!==null&&this.connect(),this.update()}connect(){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(ns),this.update(),this.state=xe.NONE}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===xe.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 r=this.minAzimuthAngle,n=this.maxAzimuthAngle;isFinite(r)&&isFinite(n)&&(r<-Math.PI?r+=Ke:r>Math.PI&&(r-=Ke),n<-Math.PI?n+=Ke:n>Math.PI&&(n-=Ke),r<=n?this._spherical.theta=Math.max(r,Math.min(n,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(r+n)/2?Math.max(r,this._spherical.theta):Math.min(n,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let o=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const i=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),o=i!=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 i=null;if(this.object.isPerspectiveCamera){const a=Le.length();i=this._clampDistance(a*this._scale);const c=a-i;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),o=!!c}else if(this.object.isOrthographicCamera){const a=new f.Vector3(this._mouse.x,this._mouse.y,0);a.unproject(this.object);const c=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),o=c!==this.object.zoom;const h=new f.Vector3(this._mouse.x,this._mouse.y,0);h.unproject(this.object),this.object.position.sub(h).add(a),this.object.updateMatrixWorld(),i=Le.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;i!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(i).add(this.object.position):(mn.origin.copy(this.object.position),mn.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(mn.direction))<wa?this.object.lookAt(this.target):(ss.setFromNormalAndCoplanarPoint(this.object.up,this.target),mn.intersectPlane(ss,this.target))))}else if(this.object.isOrthographicCamera){const i=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),i!==this.object.zoom&&(this.object.updateProjectionMatrix(),o=!0)}return this._scale=1,this._performCursorZoom=!1,o||this._lastPosition.distanceToSquared(this.object.position)>ni||8*(1-this._lastQuaternion.dot(this.object.quaternion))>ni||this._lastTargetPosition.distanceToSquared(this.target)>ni?(this.dispatchEvent(ns),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?Ke/60*this.autoRotateSpeed*e:Ke/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 r=this.domElement;if(this.object.isPerspectiveCamera){const n=this.object.position;Le.copy(n).sub(this.target);let o=Le.length();o*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*o/r.clientHeight,this.object.matrix),this._panUp(2*t*o/r.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/r.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/r.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 r=this.domElement.getBoundingClientRect(),n=e-r.left,o=t-r.top,i=r.width,a=r.height;this._mouse.x=n/i*2-1,this._mouse.y=-(o/a)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Ke*this._rotateDelta.x/t.clientHeight),this._rotateUp(Ke*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._rotateUp(Ke*this.rotateSpeed/this.domElement.clientHeight):this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this._rotateUp(-Ke*this.rotateSpeed/this.domElement.clientHeight):this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this._rotateLeft(Ke*this.rotateSpeed/this.domElement.clientHeight):this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this._rotateLeft(-Ke*this.rotateSpeed/this.domElement.clientHeight):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),r=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);this._rotateStart.set(r,n)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),r=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);this._panStart.set(r,n)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),r=e.pageX-t.x,n=e.pageY-t.y,o=Math.sqrt(r*r+n*n);this._dollyStart.set(0,o)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const r=this._getSecondPointerPosition(e),n=.5*(e.pageX+r.x),o=.5*(e.pageY+r.y);this._rotateEnd.set(n,o)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Ke*this._rotateDelta.x/t.clientHeight),this._rotateUp(Ke*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),r=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);this._panEnd.set(r,n)}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),r=e.pageX-t.x,n=e.pageY-t.y,o=Math.sqrt(r*r+n*n);this._dollyEnd.set(0,o),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const i=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(i,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 f.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,r={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:r.deltaY*=16;break;case 2:r.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(r.deltaY*=10),r}}function _a(s){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(s.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(s)&&(this._addPointer(s),s.pointerType==="touch"?this._onTouchStart(s):this._onMouseDown(s)))}function Sa(s){this.enabled!==!1&&(s.pointerType==="touch"?this._onTouchMove(s):this._onMouseMove(s))}function Ta(s){switch(this._removePointer(s),this._pointers.length){case 0:this.domElement.releasePointerCapture(s.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(is),this.state=xe.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 Aa(s){let e;switch(s.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 f.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(s),this.state=xe.DOLLY;break;case f.MOUSE.ROTATE:if(s.ctrlKey||s.metaKey||s.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(s),this.state=xe.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(s),this.state=xe.ROTATE}break;case f.MOUSE.PAN:if(s.ctrlKey||s.metaKey||s.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(s),this.state=xe.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(s),this.state=xe.PAN}break;default:this.state=xe.NONE}this.state!==xe.NONE&&this.dispatchEvent(ri)}function Ma(s){switch(this.state){case xe.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(s);break;case xe.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(s);break;case xe.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(s);break}}function Ia(s){this.enabled===!1||this.enableZoom===!1||this.state!==xe.NONE||(s.preventDefault(),this.dispatchEvent(ri),this._handleMouseWheel(this._customWheelEvent(s)),this.dispatchEvent(is))}function Ca(s){this.enabled===!1||this.enablePan===!1||this._handleKeyDown(s)}function Pa(s){switch(this._trackPointer(s),this._pointers.length){case 1:switch(this.touches.ONE){case f.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(s),this.state=xe.TOUCH_ROTATE;break;case f.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(s),this.state=xe.TOUCH_PAN;break;default:this.state=xe.NONE}break;case 2:switch(this.touches.TWO){case f.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(s),this.state=xe.TOUCH_DOLLY_PAN;break;case f.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(s),this.state=xe.TOUCH_DOLLY_ROTATE;break;default:this.state=xe.NONE}break;default:this.state=xe.NONE}this.state!==xe.NONE&&this.dispatchEvent(ri)}function Da(s){switch(this._trackPointer(s),this.state){case xe.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(s),this.update();break;case xe.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(s),this.update();break;case xe.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(s),this.update();break;case xe.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(s),this.update();break;default:this.state=xe.NONE}}function Ra(s){this.enabled!==!1&&s.preventDefault()}function Fa(s){s.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function Oa(s){s.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}class La extends os{constructor(e,t){super(e,t),this.screenSpacePanning=!1,this.mouseButtons={LEFT:f.MOUSE.PAN,MIDDLE:f.MOUSE.DOLLY,RIGHT:f.MOUSE.ROTATE},this.touches={ONE:f.TOUCH.PAN,TWO:f.TOUCH.DOLLY_ROTATE}}}class as{constructor(e){this.controls=e,this.targetAdapter=kt.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()}getThreeControls(){return this.controls}}class cs extends as{constructor(e,t){const r=new os(e,t);super(r),this.orbitControls=r}get type(){return"orbit"}get autoRotate(){return this.orbitControls.autoRotate}set autoRotate(e){this.orbitControls.autoRotate=e}get autoRotateSpeed(){return this.orbitControls.autoRotateSpeed}set autoRotateSpeed(e){this.orbitControls.autoRotateSpeed=e}}class ls extends as{constructor(e,t){const r=new La(e,t);super(r),r.screenSpacePanning=!0}get type(){return"map"}get screenSpacePanning(){return!0}set screenSpacePanning(e){}}const Qr=class Qr{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),r=this.getGapFactor();return{width:Math.sqrt(3)*t*r,height:2*t*r}}static getYPosition(e){return-(this.getHeight(e)+this.getBevelSize(e))}};Qr.HEIGHT_RATIO=.075,Qr.BEVEL_RATIO=.25,Qr.GAP_FACTOR=1.05;let Zt=Qr;var It=(s=>(s.SQUARE_WIRE="square_wire",s.HEXAGONAL_WIRE="hexagonal_wire",s.HEXAGONAL_GLASS="hexagonal_glass",s.STONE_TILES="stone_tiles",s.CUSTOM="custom",s))(It||{});class Na{constructor(){this.name="Square Wire Grid"}createGrid(e){const t=e.size||10,r=e.divisions||10,n=new M.Color(e.color||8947848),o=new M.Color(e.centerLineColor||e.color||4473924),i=new M.GridHelper(t,r,o,n);if(e.opacity!==void 0&&e.opacity<1){const a=i.material;a.transparent=!0,a.opacity=e.opacity}return i}dispose(){}}class ka{constructor(){this.name="Hexagonal Wire Grid"}createGrid(e){var d;const t=new M.Group,r=((d=e.styleOptions)==null?void 0:d.hexRadius)||Math.floor(e.divisions/2),n=e.size/(r*2),o=new M.Color(e.color||8947848),i=e.opacity||.4,a=new M.LineBasicMaterial({color:o,transparent:!0,opacity:i}),c=n*Math.sqrt(3),h=n*2;for(let u=-r;u<=r;u++){const l=Math.max(-r,-u-r),v=Math.min(r,-u+r);for(let b=l;b<=v;b++){const S=c*(u+b/2),g=h*.75*b,x=[],w=Math.PI*2/6;for(let P=0;P<=6;P++){const D=P*w+Math.PI/6,R=S+n*Math.cos(D),O=g+n*Math.sin(D);x.push(new M.Vector3(R,0,O))}const T=new M.BufferGeometry().setFromPoints(x),A=new M.Line(T,a);t.add(A)}}return t}dispose(){}}class Ba{constructor(e,t,r){this.position=e,this.size=t,this.color=r,this.height=Zt.getHeight(this.size),this.bevel=Zt.getBevelSize(this.size)}createMesh(){const e=new M.Shape,t=this.size+this.bevel,r=Math.PI*2/6;for(let h=0;h<6;h++){const d=t*Math.cos(h*r),u=t*Math.sin(h*r);h===0?e.moveTo(d,u):e.lineTo(d,u)}e.closePath();const n={depth:this.height,bevelEnabled:!0,bevelSize:this.bevel,bevelThickness:this.bevel,bevelSegments:128},o=new M.ExtrudeGeometry(e,n),i=new M.MeshPhysicalMaterial({color:new M.Color(16777215),metalness:0,roughness:.15,transparent:!0,transmission:1,thickness:.4,ior:1.5,opacity:1,clearcoat:1,clearcoatRoughness:.05,sheen:1,sheenColor:new M.Color(16777215),envMapIntensity:1}),a=new M.Mesh(o,i);a.receiveShadow=!0;const c=new M.Group;return c.add(a),c.position.set(this.position.x,this.position.y,this.position.z),c.rotation.x=Math.PI/2,c.rotation.z=Math.PI/6,c}}class za{constructor(){this.name="Hexagonal Glass Grid"}createGrid(e){var h,d;const t=new M.Group,r=((h=e.styleOptions)==null?void 0:h.hexRadius)||Math.floor(e.divisions/2),n=((d=e.styleOptions)==null?void 0:d.tileSize)||1,o=String(e.color||"#ffffff"),i=Zt.getGridSpacing(n),a=i.width,c=i.height;for(let u=-r;u<=r;u++){const l=Math.max(-r,-u-r),v=Math.min(r,-u+r);for(let b=l;b<=v;b++){const S=a*(u+b/2),g=c*.75*b,x=Zt.getYPosition(n),T=new Ba(new M.Vector3(S,x,g),n,o).createMesh();t.add(T)}}return t}dispose(){}}class Ea{constructor(){this.name="Stone Tile Grid",this.textureLoader=new M.TextureLoader,this.loadedTextures=new Map}createGrid(e){var v,b,S,g;const t=new M.Group,r=e.size,n=e.divisions,o=r/n,i=o*.02,a=o-i,c=((v=e.styleOptions)==null?void 0:v.height)||o*.05,h=((b=e.styleOptions)==null?void 0:b.bevelSize)||c*.2,d=((S=e.styleOptions)==null?void 0:S.randomHeight)||!1,u=((g=e.styleOptions)==null?void 0:g.randomRotation)||!1,l=this.createStoneMaterial(e);for(let x=0;x<n;x++)for(let w=0;w<n;w++){const T=(x-n/2)*o+o/2,A=(w-n/2)*o+o/2,P=d?c*(.8+Math.random()*.4):c,D=new M.Shape,R=a/2;D.moveTo(-R,-R),D.lineTo(R,-R),D.lineTo(R,R),D.lineTo(-R,R),D.closePath();const O={depth:P,bevelEnabled:!0,bevelSize:h,bevelThickness:h,bevelSegments:2},L=new M.ExtrudeGeometry(D,O);L.rotateX(-Math.PI/2);const E=new M.Mesh(L,l);E.position.set(T,-P/2,A),E.castShadow=!0,E.receiveShadow=!0,u&&(E.rotation.y=Math.floor(Math.random()*4)*(Math.PI/2)),t.add(E)}return t}createStoneMaterial(e){var i,a,c,h,d;const t=new M.Color(e.color||8421504),r=((i=e.styleOptions)==null?void 0:i.metalness)||0,n=((a=e.styleOptions)==null?void 0:a.roughness)||.8,o={color:t,metalness:r,roughness:n};if((c=e.styleOptions)!=null&&c.texture){const u=this.loadTexture(e.styleOptions.texture);u&&(o.map=u,u.wrapS=u.wrapT=M.RepeatWrapping,u.repeat.set(1,1))}if((h=e.styleOptions)!=null&&h.normalMap){const u=this.loadTexture(e.styleOptions.normalMap);u&&(o.normalMap=u,u.wrapS=u.wrapT=M.RepeatWrapping,u.repeat.set(1,1))}if((d=e.styleOptions)!=null&&d.roughnessMap){const u=this.loadTexture(e.styleOptions.roughnessMap);u&&(o.roughnessMap=u,u.wrapS=u.wrapT=M.RepeatWrapping,u.repeat.set(1,1))}return new M.MeshStandardMaterial(o)}loadTexture(e){if(this.loadedTextures.has(e))return this.loadedTextures.get(e)||null;try{const t=this.textureLoader.load(e);return this.loadedTextures.set(e,t),t}catch(t){return console.warn("Failed to load texture:",e,t),null}}dispose(){this.loadedTextures.forEach(e=>{e.dispose()}),this.loadedTextures.clear()}}const ji=class ji{static createGrid(e,t){const r=this.gridStyles.get(e);if(!r){console.warn(`Unknown grid type: ${e}, falling back to square wire grid`);const o=this.gridStyles.get(It.SQUARE_WIRE);if(!o)throw new Error("Square wire grid style not found");return o.createGrid(t)}const n=r.createGrid(t);return n.name=`Grid_${e}`,n}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()}};ji.gridStyles=new Map([[It.SQUARE_WIRE,new Na],[It.HEXAGONAL_WIRE,new ka],[It.HEXAGONAL_GLASS,new za],[It.STONE_TILES,new Ea]]);let gn=ji;class Ua{addHelpers(e,t){try{if(!(e instanceof Yt))return K.err(new oe("Scene must be ThreeSceneAdapter",ue.INVALID_PARAMETER));const r=e.getThreeScene();if(t.grid){const n=r.userData,o=typeof t.grid=="object"?t.grid:null,i={enabled:!0,color:(o==null?void 0:o.colorGrid)||t.gridColor||"#AAAAAA",type:o!=null&&o.type?o.type:It.HEXAGONAL_GLASS,opacity:o==null?void 0:o.opacity,styleOptions:o==null?void 0:o.styleOptions};if(r.userData={...n,gridOptions:i},o!=null&&o.size||o!=null&&o.divisions){const a=i.type||It.HEXAGONAL_GLASS,c=o.size||10,h=o.divisions||10,d={size:c,divisions:h,color:i.color,opacity:i.opacity,styleOptions:{hexRadius:Math.floor(h/2),tileSize:1,...i.styleOptions}},u=gn.createGrid(a,d);u.userData.isGrid=!0,u.userData.isDefaultGrid=!0,r.add(u)}}if(t.axes){const n=t.axesSize||5,o=new M.AxesHelper(n);r.add(o)}return K.ok(void 0)}catch(r){return K.err(new oe("Failed to add helpers to scene",ue.SCENE_OPERATION_FAILED,{originalError:r,options:t}))}}addDynamicGrid(e,t,r=1.2){try{if(!(e instanceof Yt))return K.err(new oe("Scene must be ThreeSceneAdapter",ue.INVALID_PARAMETER));const n=e.getThreeScene(),o=n.userData,i=o==null?void 0:o.gridOptions;if(!(i!=null&&i.enabled))return K.ok(void 0);const a=[];n.traverse(D=>{var R,O,L;((R=D.userData)!=null&&R.isGrid||(O=D.userData)!=null&&O.isHexGrid||(L=D.userData)!=null&&L.isDefaultGrid)&&a.push(D)}),a.forEach(D=>n.remove(D));let c;t instanceof We||"getThreeObject"in t&&typeof t.getThreeObject=="function"?c=t.getThreeObject():c=t;const d=new M.Box3().setFromObject(c).getSize(new M.Vector3);console.log("Object size:",d);const l=1,b=Zt.getGridSpacing(l).width,S=Math.max(d.x,d.z)*r;let g=0,x=b;for(;x<S&&g<20;)g++,x+=2*b;S<b*.8?g=0:g<3&&S>b*2&&(g=3),console.log("Grid parameters:",{tileSize:l,gridRadius:g,requiredWidth:S,hexWidth:b,actualCoverage:(2*g+1)*b});const w=i.type||It.HEXAGONAL_GLASS,A={size:Math.max(d.x,d.z)*r,divisions:g*2+1,color:i.color,opacity:i.opacity,styleOptions:{hexRadius:g,tileSize:l,...i.styleOptions}},P=gn.createGrid(w,A);return P.userData.isGrid=!0,P.userData.isHexGrid=!0,n.add(P),K.ok(void 0)}catch(n){return K.err(new oe("Failed to add dynamic grid",ue.SCENE_OPERATION_FAILED,{originalError:n}))}}addLighting(e,t){try{if(!(e instanceof Yt))return K.err(new oe("Scene must be ThreeSceneAdapter",ue.INVALID_PARAMETER));const r=e.getThreeScene();if(t.ambient){const n=new M.Color(t.ambient.color||"#404040"),o=t.ambient.intensity??Math.PI,i=new M.AmbientLight(n,o);r.add(i)}if(t.hemisphere){const n=new M.Color(t.hemisphere.skyColor||"#ffffbb"),o=new M.Color(t.hemisphere.groundColor||"#080820"),i=t.hemisphere.intensity??1,a=new M.HemisphereLight(n,o,i);r.add(a)}if(t.directional){const n=new M.Color(t.directional.color||"#ffffff"),o=t.directional.intensity??Math.PI,i=new M.DirectionalLight(n,o);if(t.directional.position){const a=t.directional.position;if(a instanceof M.Vector3)i.position.copy(a);else if(Array.isArray(a))i.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;i.position.set(c.x,c.y,c.z)}}else i.position.set(6,6,6);if(t.directional.castShadow&&(i.castShadow=!0,t.directional.shadow)){const a=t.directional.shadow;if(a.mapSize&&(i.shadow.mapSize.width=a.mapSize.width,i.shadow.mapSize.height=a.mapSize.height),a.camera){const c=i.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&&(i.shadow.bias=a.bias),a.radius!==void 0&&(i.shadow.radius=a.radius)}i.target.position.set(0,0,0),r.add(i),r.add(i.target),i.shadow&&i.shadow.camera.updateProjectionMatrix()}return K.ok(void 0)}catch(r){return K.err(new oe("Failed to add lighting to scene",ue.SCENE_OPERATION_FAILED,{originalError:r,options:t}))}}createGradientBackground(e,t){try{if(!(e instanceof Yt))return K.err(new oe("Scene must be ThreeSceneAdapter",ue.INVALID_PARAMETER));const r=e.getThreeScene(),n=document.createElement("canvas");n.width=2,n.height=512;const o=n.getContext("2d");if(!o)return K.err(new oe("Failed to create canvas context",ue.SCENE_OPERATION_FAILED));const i=o.createLinearGradient(0,0,0,n.height);i.addColorStop(0,t.topColor),i.addColorStop(1,t.bottomColor),o.fillStyle=i,o.fillRect(0,0,n.width,n.height);const a=new M.CanvasTexture(n);return a.needsUpdate=!0,r.background=a,K.ok(void 0)}catch(r){return K.err(new oe("Failed to create gradient background",ue.SCENE_OPERATION_FAILED,{originalError:r,options:t}))}}fitCameraToObject(e,t,r){try{let n;e instanceof We||"getThreeObject"in e&&typeof e.getThreeObject=="function"?n=e.getThreeObject():n=e;let o;t instanceof Xn||"getThreeCamera"in t&&typeof t.getThreeCamera=="function"?o=t.getThreeCamera():o=t;let i;r instanceof cs||r instanceof ls||"getThreeControls"in r&&typeof r.getThreeControls=="function"?i=r.getThreeControls():i=r;const a=new M.Box3().setFromObject(n),c=a.getCenter(new M.Vector3),h=a.getSize(new M.Vector3);console.log("Fitting camera to object:",{center:c,size:h,maxDimension:Math.max(h.x,h.y,h.z)});const d=Math.max(h.x,h.y,h.z);let u;"fov"in o?u=o.fov*(Math.PI/180):u=50*(Math.PI/180);let l=Math.abs(d/2/Math.tan(u/2));l*=2;const v=-Math.PI/4,b=Math.PI/8,S=c.x+l*Math.sin(v)*Math.cos(b),g=c.y+l*Math.sin(b),x=c.z+l*Math.cos(v)*Math.cos(b);return o.position.set(S,g,x),o.lookAt(c),o.updateProjectionMatrix(),i&&i.target&&(i.target.copy(c),i.update()),console.log("Camera positioned at:",{x:S,y:g,z:x}),console.log("Looking at:",c),K.ok(void 0)}catch(n){return K.err(new oe("Failed to fit camera to object",ue.CAMERA_INIT_FAILED,{originalError:n}))}}}const us=0,Ga=1,hs=2,fs=2,ii=1.25,ds=1,zt=6*4+4+4,vn=65535,Va=Math.pow(2,-24),si=Symbol("SKIP_GENERATION");function ps(s){return s.index?s.index.count:s.attributes.position.count}function fr(s){return ps(s)/3}function ms(s,e=ArrayBuffer){return s>65535?new Uint32Array(new e(4*s)):new Uint16Array(new e(2*s))}function ja(s,e){if(!s.index){const t=s.attributes.position.count,r=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=ms(t,r);s.setIndex(new f.BufferAttribute(n,1));for(let o=0;o<t;o++)n[o]=o}}function gs(s,e){const t=fr(s),r=e||s.drawRange,n=r.start/3,o=(r.start+r.count)/3,i=Math.max(0,n),a=Math.min(t,o)-i;return[{offset:Math.floor(i),count:Math.floor(a)}]}function vs(s,e){if(!s.groups||!s.groups.length)return gs(s,e);const t=[],r=new Set,n=e||s.drawRange,o=n.start/3,i=(n.start+n.count)/3;for(const c of s.groups){const h=c.start/3,d=(c.start+c.count)/3;r.add(Math.max(o,h)),r.add(Math.min(i,d))}const a=Array.from(r.values()).sort((c,h)=>c-h);for(let c=0;c<a.length-1;c++){const h=a[c],d=a[c+1];t.push({offset:Math.floor(h),count:Math.floor(d-h)})}return t}function Wa(s,e){const t=fr(s),r=vs(s,e).sort((i,a)=>i.offset-a.offset),n=r[r.length-1];n.count=Math.min(t-n.offset,n.count);let o=0;return r.forEach(({count:i})=>o+=i),t!==o}function oi(s,e,t,r,n){let o=1/0,i=1/0,a=1/0,c=-1/0,h=-1/0,d=-1/0,u=1/0,l=1/0,v=1/0,b=-1/0,S=-1/0,g=-1/0;for(let x=e*6,w=(e+t)*6;x<w;x+=6){const T=s[x+0],A=s[x+1],P=T-A,D=T+A;P<o&&(o=P),D>c&&(c=D),T<u&&(u=T),T>b&&(b=T);const R=s[x+2],O=s[x+3],L=R-O,E=R+O;L<i&&(i=L),E>h&&(h=E),R<l&&(l=R),R>S&&(S=R);const G=s[x+4],z=s[x+5],V=G-z,U=G+z;V<a&&(a=V),U>d&&(d=U),G<v&&(v=G),G>g&&(g=G)}r[0]=o,r[1]=i,r[2]=a,r[3]=c,r[4]=h,r[5]=d,n[0]=u,n[1]=l,n[2]=v,n[3]=b,n[4]=S,n[5]=g}function Ya(s,e=null,t=null,r=null){const n=s.attributes.position,o=s.index?s.index.array:null,i=fr(s),a=n.normalized;let c;e===null?(c=new Float32Array(i*6*4),t=0,r=i):(c=e,t=t||0,r=r||i);const h=n.array,d=n.offset||0;let u=3;n.isInterleavedBufferAttribute&&(u=n.data.stride);const l=["getX","getY","getZ"];for(let v=t;v<t+r;v++){const b=v*3,S=v*6;let g=b+0,x=b+1,w=b+2;o&&(g=o[g],x=o[x],w=o[w]),a||(g=g*u+d,x=x*u+d,w=w*u+d);for(let T=0;T<3;T++){let A,P,D;a?(A=n[l[T]](g),P=n[l[T]](x),D=n[l[T]](w)):(A=h[g+T],P=h[x+T],D=h[w+T]);let R=A;P<R&&(R=P),D<R&&(R=D);let O=A;P>O&&(O=P),D>O&&(O=D);const L=(O-R)/2,E=T*2;c[S+E+0]=R+L,c[S+E+1]=L+(Math.abs(R)+L)*Va}}return c}function Fe(s,e,t){return t.min.x=e[s],t.min.y=e[s+1],t.min.z=e[s+2],t.max.x=e[s+3],t.max.y=e[s+4],t.max.z=e[s+5],t}function ys(s){let e=-1,t=-1/0;for(let r=0;r<3;r++){const n=s[r+3]-s[r];n>t&&(t=n,e=r)}return e}function bs(s,e){e.set(s)}function xs(s,e,t){let r,n;for(let o=0;o<3;o++){const i=o+3;r=s[o],n=e[o],t[o]=r<n?r:n,r=s[i],n=e[i],t[i]=r>n?r:n}}function yn(s,e,t){for(let r=0;r<3;r++){const n=e[s+2*r],o=e[s+2*r+1],i=n-o,a=n+o;i<t[r]&&(t[r]=i),a>t[r+3]&&(t[r+3]=a)}}function Er(s){const e=s[3]-s[0],t=s[4]-s[1],r=s[5]-s[2];return 2*(e*t+t*r+r*e)}const Ct=32,qa=(s,e)=>s.candidate-e.candidate,Et=new Array(Ct).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),bn=new Float32Array(6);function Za(s,e,t,r,n,o){let i=-1,a=0;if(o===us)i=ys(e),i!==-1&&(a=(e[i]+e[i+3])/2);else if(o===Ga)i=ys(s),i!==-1&&(a=Ka(t,r,n,i));else if(o===hs){const c=Er(s);let h=ii*n;const d=r*6,u=(r+n)*6;for(let l=0;l<3;l++){const v=e[l],g=(e[l+3]-v)/Ct;if(n<Ct/4){const x=[...Et];x.length=n;let w=0;for(let A=d;A<u;A+=6,w++){const P=x[w];P.candidate=t[A+2*l],P.count=0;const{bounds:D,leftCacheBounds:R,rightCacheBounds:O}=P;for(let L=0;L<3;L++)O[L]=1/0,O[L+3]=-1/0,R[L]=1/0,R[L+3]=-1/0,D[L]=1/0,D[L+3]=-1/0;yn(A,t,D)}x.sort(qa);let T=n;for(let A=0;A<T;A++){const P=x[A];for(;A+1<T&&x[A+1].candidate===P.candidate;)x.splice(A+1,1),T--}for(let A=d;A<u;A+=6){const P=t[A+2*l];for(let D=0;D<T;D++){const R=x[D];P>=R.candidate?yn(A,t,R.rightCacheBounds):(yn(A,t,R.leftCacheBounds),R.count++)}}for(let A=0;A<T;A++){const P=x[A],D=P.count,R=n-P.count,O=P.leftCacheBounds,L=P.rightCacheBounds;let E=0;D!==0&&(E=Er(O)/c);let G=0;R!==0&&(G=Er(L)/c);const z=ds+ii*(E*D+G*R);z<h&&(i=l,h=z,a=P.candidate)}}else{for(let T=0;T<Ct;T++){const A=Et[T];A.count=0,A.candidate=v+g+T*g;const P=A.bounds;for(let D=0;D<3;D++)P[D]=1/0,P[D+3]=-1/0}for(let T=d;T<u;T+=6){let D=~~((t[T+2*l]-v)/g);D>=Ct&&(D=Ct-1);const R=Et[D];R.count++,yn(T,t,R.bounds)}const x=Et[Ct-1];bs(x.bounds,x.rightCacheBounds);for(let T=Ct-2;T>=0;T--){const A=Et[T],P=Et[T+1];xs(A.bounds,P.rightCacheBounds,A.rightCacheBounds)}let w=0;for(let T=0;T<Ct-1;T++){const A=Et[T],P=A.count,D=A.bounds,O=Et[T+1].rightCacheBounds;P!==0&&(w===0?bs(D,bn):xs(D,bn,bn)),w+=P;let L=0,E=0;w!==0&&(L=Er(bn)/c);const G=n-w;G!==0&&(E=Er(O)/c);const z=ds+ii*(L*w+E*G);z<h&&(i=l,h=z,a=A.candidate)}}}}else console.warn(`MeshBVH: Invalid build strategy value ${o} used.`);return{axis:i,pos:a}}function Ka(s,e,t,r){let n=0;for(let o=e,i=e+t;o<i;o++)n+=s[o*6+r*2];return n/t}class ai{constructor(){this.boundingData=new Float32Array(6)}}function Xa(s,e,t,r,n,o){let i=r,a=r+n-1;const c=o.pos,h=o.axis*2;for(;;){for(;i<=a&&t[i*6+h]<c;)i++;for(;i<=a&&t[a*6+h]>=c;)a--;if(i<a){for(let d=0;d<3;d++){let u=e[i*3+d];e[i*3+d]=e[a*3+d],e[a*3+d]=u}for(let d=0;d<6;d++){let u=t[i*6+d];t[i*6+d]=t[a*6+d],t[a*6+d]=u}i++,a--}else return i}}function $a(s,e,t,r,n,o){let i=r,a=r+n-1;const c=o.pos,h=o.axis*2;for(;;){for(;i<=a&&t[i*6+h]<c;)i++;for(;i<=a&&t[a*6+h]>=c;)a--;if(i<a){let d=s[i];s[i]=s[a],s[a]=d;for(let u=0;u<6;u++){let l=t[i*6+u];t[i*6+u]=t[a*6+u],t[a*6+u]=l}i++,a--}else return i}}function Ye(s,e){return e[s+15]===65535}function Xe(s,e){return e[s+6]}function Je(s,e){return e[s+14]}function ot(s){return s+8}function He(s,e){return e[s+6]}function ci(s,e){return e[s+7]}function qh(s){return s}let ws,Ur,xn,_s;const Qa=Math.pow(2,32);function li(s){return"count"in s?1:1+li(s.left)+li(s.right)}function Ja(s,e,t){return ws=new Float32Array(t),Ur=new Uint32Array(t),xn=new Uint16Array(t),_s=new Uint8Array(t),ui(s,e)}function ui(s,e){const t=s/4,r=s/2,n="count"in e,o=e.boundingData;for(let i=0;i<6;i++)ws[t+i]=o[i];if(n)if(e.buffer){const i=e.buffer;_s.set(new Uint8Array(i),s);for(let a=s,c=s+i.byteLength;a<c;a+=zt){const h=a/2;Ye(h,xn)||(Ur[a/4+6]+=t)}return s+i.byteLength}else{const i=e.offset,a=e.count;return Ur[t+6]=i,xn[r+14]=a,xn[r+15]=vn,s+zt}else{const i=e.left,a=e.right,c=e.splitAxis;let h;if(h=ui(s+zt,i),h/4>Qa)throw new Error("MeshBVH: Cannot store child pointer greater than 32 bits.");return Ur[t+6]=h/4,h=ui(h,a),Ur[t+7]=c,h}}function Ha(s,e){const t=(s.index?s.index.count:s.attributes.position.count)/3,r=t>2**16,n=r?4:2,o=e?new SharedArrayBuffer(t*n):new ArrayBuffer(t*n),i=r?new Uint32Array(o):new Uint16Array(o);for(let a=0,c=i.length;a<c;a++)i[a]=a;return i}function ec(s,e,t,r,n){const{maxDepth:o,verbose:i,maxLeafTris:a,strategy:c,onProgress:h,indirect:d}=n,u=s._indirectBuffer,l=s.geometry,v=l.index?l.index.array:null,b=d?$a:Xa,S=fr(l),g=new Float32Array(6);let x=!1;const w=new ai;return oi(e,t,r,w.boundingData,g),A(w,t,r,g),w;function T(P){h&&h(P/S)}function A(P,D,R,O=null,L=0){if(!x&&L>=o&&(x=!0,i&&(console.warn(`MeshBVH: Max depth of ${o} reached when generating BVH. Consider increasing maxDepth.`),console.warn(l))),R<=a||L>=o)return T(D+R),P.offset=D,P.count=R,P;const E=Za(P.boundingData,O,e,D,R,c);if(E.axis===-1)return T(D+R),P.offset=D,P.count=R,P;const G=b(u,v,e,D,R,E);if(G===D||G===D+R)T(D+R),P.offset=D,P.count=R;else{P.splitAxis=E.axis;const z=new ai,V=D,U=G-D;P.left=z,oi(e,V,U,z.boundingData,g),A(z,V,U,g,L+1);const H=new ai,ne=G,ge=R-U;P.right=H,oi(e,ne,ge,H.boundingData,g),A(H,ne,ge,g,L+1)}return P}}function tc(s,e){const t=s.geometry;e.indirect&&(s._indirectBuffer=Ha(t,e.useSharedArrayBuffer),Wa(t,e.range)&&!e.verbose&&console.warn('MeshBVH: Provided geometry contains groups or a range that do not fully span the vertex contents while using the "indirect" option. BVH may incorrectly report intersections on unrendered portions of the geometry.')),s._indirectBuffer||ja(t,e);const r=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=Ya(t),o=e.indirect?gs(t,e.range):vs(t,e.range);s._roots=o.map(i=>{const a=ec(s,n,i.offset,i.count,e),c=li(a),h=new r(zt*c);return Ja(0,a,h),h})}class Pt{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let r=1/0,n=-1/0;for(let o=0,i=e.length;o<i;o++){const c=e[o][t];r=c<r?c:r,n=c>n?c:n}this.min=r,this.max=n}setFromPoints(e,t){let r=1/0,n=-1/0;for(let o=0,i=t.length;o<i;o++){const a=t[o],c=e.dot(a);r=c<r?c:r,n=c>n?c:n}this.min=r,this.max=n}isSeparated(e){return this.min>e.max||e.min>this.max}}Pt.prototype.setFromBox=function(){const s=new f.Vector3;return function(t,r){const n=r.min,o=r.max;let i=1/0,a=-1/0;for(let c=0;c<=1;c++)for(let h=0;h<=1;h++)for(let d=0;d<=1;d++){s.x=n.x*c+o.x*(1-c),s.y=n.y*h+o.y*(1-h),s.z=n.z*d+o.z*(1-d);const u=t.dot(s);i=Math.min(u,i),a=Math.max(u,a)}this.min=i,this.max=a}}();const rc=function(){const s=new f.Vector3,e=new f.Vector3,t=new f.Vector3;return function(n,o,i){const a=n.start,c=s,h=o.start,d=e;t.subVectors(a,h),s.subVectors(n.end,n.start),e.subVectors(o.end,o.start);const u=t.dot(d),l=d.dot(c),v=d.dot(d),b=t.dot(c),g=c.dot(c)*v-l*l;let x,w;g!==0?x=(u*l-b*v)/g:x=0,w=(u+x*l)/v,i.x=x,i.y=w}}(),hi=function(){const s=new f.Vector2,e=new f.Vector3,t=new f.Vector3;return function(n,o,i,a){rc(n,o,s);let c=s.x,h=s.y;if(c>=0&&c<=1&&h>=0&&h<=1){n.at(c,i),o.at(h,a);return}else if(c>=0&&c<=1){h<0?o.at(0,a):o.at(1,a),n.closestPointToPoint(a,!0,i);return}else if(h>=0&&h<=1){c<0?n.at(0,i):n.at(1,i),o.closestPointToPoint(i,!0,a);return}else{let d;c<0?d=n.start:d=n.end;let u;h<0?u=o.start:u=o.end;const l=e,v=t;if(n.closestPointToPoint(u,!0,e),o.closestPointToPoint(d,!0,t),l.distanceToSquared(u)<=v.distanceToSquared(d)){i.copy(l),a.copy(u);return}else{i.copy(d),a.copy(v);return}}}}(),nc=function(){const s=new f.Vector3,e=new f.Vector3,t=new f.Plane,r=new f.Line3;return function(o,i){const{radius:a,center:c}=o,{a:h,b:d,c:u}=i;if(r.start=h,r.end=d,r.closestPointToPoint(c,!0,s).distanceTo(c)<=a||(r.start=h,r.end=u,r.closestPointToPoint(c,!0,s).distanceTo(c)<=a)||(r.start=d,r.end=u,r.closestPointToPoint(c,!0,s).distanceTo(c)<=a))return!0;const S=i.getPlane(t);if(Math.abs(S.distanceToPoint(c))<=a){const x=S.projectPoint(c,e);if(i.containsPoint(x))return!0}return!1}}(),ic=1e-15;function fi(s){return Math.abs(s)<ic}class mt extends f.Triangle{constructor(...e){super(...e),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new f.Vector3),this.satBounds=new Array(4).fill().map(()=>new Pt),this.points=[this.a,this.b,this.c],this.sphere=new f.Sphere,this.plane=new f.Plane,this.needsUpdate=!0}intersectsSphere(e){return nc(e,this)}update(){const e=this.a,t=this.b,r=this.c,n=this.points,o=this.satAxes,i=this.satBounds,a=o[0],c=i[0];this.getNormal(a),c.setFromPoints(a,n);const h=o[1],d=i[1];h.subVectors(e,t),d.setFromPoints(h,n);const u=o[2],l=i[2];u.subVectors(t,r),l.setFromPoints(u,n);const v=o[3],b=i[3];v.subVectors(r,e),b.setFromPoints(v,n),this.sphere.setFromPoints(this.points),this.plane.setFromNormalAndCoplanarPoint(a,e),this.needsUpdate=!1}}mt.prototype.closestPointToSegment=function(){const s=new f.Vector3,e=new f.Vector3,t=new f.Line3;return function(n,o=null,i=null){const{start:a,end:c}=n,h=this.points;let d,u=1/0;for(let l=0;l<3;l++){const v=(l+1)%3;t.start.copy(h[l]),t.end.copy(h[v]),hi(t,n,s,e),d=s.distanceToSquared(e),d<u&&(u=d,o&&o.copy(s),i&&i.copy(e))}return this.closestPointToPoint(a,s),d=a.distanceToSquared(s),d<u&&(u=d,o&&o.copy(s),i&&i.copy(a)),this.closestPointToPoint(c,s),d=c.distanceToSquared(s),d<u&&(u=d,o&&o.copy(s),i&&i.copy(c)),Math.sqrt(u)}}(),mt.prototype.intersectsTriangle=function(){const s=new mt,e=new Array(3),t=new Array(3),r=new Pt,n=new Pt,o=new f.Vector3,i=new f.Vector3,a=new f.Vector3,c=new f.Vector3,h=new f.Vector3,d=new f.Line3,u=new f.Line3,l=new f.Line3,v=new f.Vector3;function b(S,g,x){const w=S.points;let T=0,A=-1;for(let P=0;P<3;P++){const{start:D,end:R}=d;D.copy(w[P]),R.copy(w[(P+1)%3]),d.delta(i);const O=fi(g.distanceToPoint(D));if(fi(g.normal.dot(i))&&O){x.copy(d),T=2;break}const L=g.intersectLine(d,v);if(!L&&O&&v.copy(D),(L||O)&&!fi(v.distanceTo(R))){if(T<=1)(T===1?x.start:x.end).copy(v),O&&(A=T);else if(T>=2){(A===1?x.start:x.end).copy(v),T=2;break}if(T++,T===2&&A===-1)break}}return T}return function(g,x=null,w=!1){this.needsUpdate&&this.update(),g.isExtendedTriangle?g.needsUpdate&&g.update():(s.copy(g),s.update(),g=s);const T=this.plane,A=g.plane;if(Math.abs(T.normal.dot(A.normal))>1-1e-10){const P=this.satBounds,D=this.satAxes;t[0]=g.a,t[1]=g.b,t[2]=g.c;for(let L=0;L<4;L++){const E=P[L],G=D[L];if(r.setFromPoints(G,t),E.isSeparated(r))return!1}const R=g.satBounds,O=g.satAxes;e[0]=this.a,e[1]=this.b,e[2]=this.c;for(let L=0;L<4;L++){const E=R[L],G=O[L];if(r.setFromPoints(G,e),E.isSeparated(r))return!1}for(let L=0;L<4;L++){const E=D[L];for(let G=0;G<4;G++){const z=O[G];if(o.crossVectors(E,z),r.setFromPoints(o,e),n.setFromPoints(o,t),r.isSeparated(n))return!1}}return x&&(w||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),x.start.set(0,0,0),x.end.set(0,0,0)),!0}else{const P=b(this,A,u);if(P===1&&g.containsPoint(u.end))return x&&(x.start.copy(u.end),x.end.copy(u.end)),!0;if(P!==2)return!1;const D=b(g,T,l);if(D===1&&this.containsPoint(l.end))return x&&(x.start.copy(l.end),x.end.copy(l.end)),!0;if(D!==2)return!1;if(u.delta(a),l.delta(c),a.dot(c)<0){let V=l.start;l.start=l.end,l.end=V}const R=u.start.dot(a),O=u.end.dot(a),L=l.start.dot(a),E=l.end.dot(a),G=O<L,z=R<E;return R!==E&&L!==O&&G===z?!1:(x&&(h.subVectors(u.start,l.start),h.dot(a)>0?x.start.copy(u.start):x.start.copy(l.start),h.subVectors(u.end,l.end),h.dot(a)<0?x.end.copy(u.end):x.end.copy(l.end)),!0)}}}(),mt.prototype.distanceToPoint=function(){const s=new f.Vector3;return function(t){return this.closestPointToPoint(t,s),t.distanceTo(s)}}(),mt.prototype.distanceToTriangle=function(){const s=new f.Vector3,e=new f.Vector3,t=["a","b","c"],r=new f.Line3,n=new f.Line3;return function(i,a=null,c=null){const h=a||c?r:null;if(this.intersectsTriangle(i,h))return(a||c)&&(a&&h.getCenter(a),c&&h.getCenter(c)),0;let d=1/0;for(let u=0;u<3;u++){let l;const v=t[u],b=i[v];this.closestPointToPoint(b,s),l=b.distanceToSquared(s),l<d&&(d=l,a&&a.copy(s),c&&c.copy(b));const S=this[v];i.closestPointToPoint(S,s),l=S.distanceToSquared(s),l<d&&(d=l,a&&a.copy(S),c&&c.copy(s))}for(let u=0;u<3;u++){const l=t[u],v=t[(u+1)%3];r.set(this[l],this[v]);for(let b=0;b<3;b++){const S=t[b],g=t[(b+1)%3];n.set(i[S],i[g]),hi(r,n,s,e);const x=s.distanceToSquared(e);x<d&&(d=x,a&&a.copy(s),c&&c.copy(e))}}return Math.sqrt(d)}}();class qe{constructor(e,t,r){this.isOrientedBox=!0,this.min=new f.Vector3,this.max=new f.Vector3,this.matrix=new f.Matrix4,this.invMatrix=new f.Matrix4,this.points=new Array(8).fill().map(()=>new f.Vector3),this.satAxes=new Array(3).fill().map(()=>new f.Vector3),this.satBounds=new Array(3).fill().map(()=>new Pt),this.alignedSatBounds=new Array(3).fill().map(()=>new Pt),this.needsUpdate=!1,e&&this.min.copy(e),t&&this.max.copy(t),r&&this.matrix.copy(r)}set(e,t,r){this.min.copy(e),this.max.copy(t),this.matrix.copy(r),this.needsUpdate=!0}copy(e){this.min.copy(e.min),this.max.copy(e.max),this.matrix.copy(e.matrix),this.needsUpdate=!0}}qe.prototype.update=function(){return function(){const e=this.matrix,t=this.min,r=this.max,n=this.points;for(let h=0;h<=1;h++)for(let d=0;d<=1;d++)for(let u=0;u<=1;u++){const l=1*h|2*d|4*u,v=n[l];v.x=h?r.x:t.x,v.y=d?r.y:t.y,v.z=u?r.z:t.z,v.applyMatrix4(e)}const o=this.satBounds,i=this.satAxes,a=n[0];for(let h=0;h<3;h++){const d=i[h],u=o[h],l=1<<h,v=n[l];d.subVectors(a,v),u.setFromPoints(d,n)}const c=this.alignedSatBounds;c[0].setFromPointsField(n,"x"),c[1].setFromPointsField(n,"y"),c[2].setFromPointsField(n,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}}(),qe.prototype.intersectsBox=function(){const s=new Pt;return function(t){this.needsUpdate&&this.update();const r=t.min,n=t.max,o=this.satBounds,i=this.satAxes,a=this.alignedSatBounds;if(s.min=r.x,s.max=n.x,a[0].isSeparated(s)||(s.min=r.y,s.max=n.y,a[1].isSeparated(s))||(s.min=r.z,s.max=n.z,a[2].isSeparated(s)))return!1;for(let c=0;c<3;c++){const h=i[c],d=o[c];if(s.setFromBox(h,t),d.isSeparated(s))return!1}return!0}}(),qe.prototype.intersectsTriangle=function(){const s=new mt,e=new Array(3),t=new Pt,r=new Pt,n=new f.Vector3;return function(i){this.needsUpdate&&this.update(),i.isExtendedTriangle?i.needsUpdate&&i.update():(s.copy(i),s.update(),i=s);const a=this.satBounds,c=this.satAxes;e[0]=i.a,e[1]=i.b,e[2]=i.c;for(let l=0;l<3;l++){const v=a[l],b=c[l];if(t.setFromPoints(b,e),v.isSeparated(t))return!1}const h=i.satBounds,d=i.satAxes,u=this.points;for(let l=0;l<3;l++){const v=h[l],b=d[l];if(t.setFromPoints(b,u),v.isSeparated(t))return!1}for(let l=0;l<3;l++){const v=c[l];for(let b=0;b<4;b++){const S=d[b];if(n.crossVectors(v,S),t.setFromPoints(n,e),r.setFromPoints(n,u),t.isSeparated(r))return!1}}return!0}}(),qe.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}}(),qe.prototype.distanceToPoint=function(){const s=new f.Vector3;return function(t){return this.closestPointToPoint(t,s),t.distanceTo(s)}}(),qe.prototype.distanceToBox=function(){const s=["x","y","z"],e=new Array(12).fill().map(()=>new f.Line3),t=new Array(12).fill().map(()=>new f.Line3),r=new f.Vector3,n=new f.Vector3;return function(i,a=0,c=null,h=null){if(this.needsUpdate&&this.update(),this.intersectsBox(i))return(c||h)&&(i.getCenter(n),this.closestPointToPoint(n,r),i.closestPointToPoint(r,n),c&&c.copy(r),h&&h.copy(n)),0;const d=a*a,u=i.min,l=i.max,v=this.points;let b=1/0;for(let g=0;g<8;g++){const x=v[g];n.copy(x).clamp(u,l);const w=x.distanceToSquared(n);if(w<b&&(b=w,c&&c.copy(x),h&&h.copy(n),w<d))return Math.sqrt(w)}let S=0;for(let g=0;g<3;g++)for(let x=0;x<=1;x++)for(let w=0;w<=1;w++){const T=(g+1)%3,A=(g+2)%3,P=x<<T|w<<A,D=1<<g|x<<T|w<<A,R=v[P],O=v[D];e[S].set(R,O);const E=s[g],G=s[T],z=s[A],V=t[S],U=V.start,H=V.end;U[E]=u[E],U[G]=x?u[G]:l[G],U[z]=w?u[z]:l[G],H[E]=l[E],H[G]=x?u[G]:l[G],H[z]=w?u[z]:l[G],S++}for(let g=0;g<=1;g++)for(let x=0;x<=1;x++)for(let w=0;w<=1;w++){n.x=g?l.x:u.x,n.y=x?l.y:u.y,n.z=w?l.z:u.z,this.closestPointToPoint(n,r);const T=n.distanceToSquared(r);if(T<b&&(b=T,c&&c.copy(r),h&&h.copy(n),T<d))return Math.sqrt(T)}for(let g=0;g<12;g++){const x=e[g];for(let w=0;w<12;w++){const T=t[w];hi(x,T,r,n);const A=r.distanceToSquared(n);if(A<b&&(b=A,c&&c.copy(r),h&&h.copy(n),A<d))return Math.sqrt(A)}}return Math.sqrt(b)}}();class di{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 sc extends di{constructor(){super(()=>new mt)}}const at=new sc;class oc{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const e=[];let t=null;this.setBuffer=r=>{t&&e.push(t),t=r,this.float32Array=new Float32Array(r),this.uint16Array=new Uint16Array(r),this.uint32Array=new Uint32Array(r)},this.clearBuffer=()=>{t=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,e.length!==0&&this.setBuffer(e.pop())}}}const Me=new oc;let Ut,dr;const pr=[],wn=new di(()=>new f.Box3);function ac(s,e,t,r,n,o){Ut=wn.getPrimitive(),dr=wn.getPrimitive(),pr.push(Ut,dr),Me.setBuffer(s._roots[e]);const i=pi(0,s.geometry,t,r,n,o);Me.clearBuffer(),wn.releasePrimitive(Ut),wn.releasePrimitive(dr),pr.pop(),pr.pop();const a=pr.length;return a>0&&(dr=pr[a-1],Ut=pr[a-2]),i}function pi(s,e,t,r,n=null,o=0,i=0){const{float32Array:a,uint16Array:c,uint32Array:h}=Me;let d=s*2;if(Ye(d,c)){const l=Xe(s,h),v=Je(d,c);return Fe(s,a,Ut),r(l,v,!1,i,o+s,Ut)}else{let E=function(z){const{uint16Array:V,uint32Array:U}=Me;let H=z*2;for(;!Ye(H,V);)z=ot(z),H=z*2;return Xe(z,U)},G=function(z){const{uint16Array:V,uint32Array:U}=Me;let H=z*2;for(;!Ye(H,V);)z=He(z,U),H=z*2;return Xe(z,U)+Je(H,V)};const l=ot(s),v=He(s,h);let b=l,S=v,g,x,w,T;if(n&&(w=Ut,T=dr,Fe(b,a,w),Fe(S,a,T),g=n(w),x=n(T),x<g)){b=v,S=l;const z=g;g=x,x=z,w=T}w||(w=Ut,Fe(b,a,w));const A=Ye(b*2,c),P=t(w,A,g,i+1,o+b);let D;if(P===fs){const z=E(b),U=G(b)-z;D=r(z,U,!0,i+1,o+b,w)}else D=P&&pi(b,e,t,r,n,o,i+1);if(D)return!0;T=dr,Fe(S,a,T);const R=Ye(S*2,c),O=t(T,R,x,i+1,o+S);let L;if(O===fs){const z=E(S),U=G(S)-z;L=r(z,U,!0,i+1,o+S,T)}else L=O&&pi(S,e,t,r,n,o,i+1);return!!L}}const Gr=new f.Vector3,mi=new f.Vector3;function cc(s,e,t={},r=0,n=1/0){const o=r*r,i=n*n;let a=1/0,c=null;if(s.shapecast({boundsTraverseOrder:d=>(Gr.copy(e).clamp(d.min,d.max),Gr.distanceToSquared(e)),intersectsBounds:(d,u,l)=>l<a&&l<i,intersectsTriangle:(d,u)=>{d.closestPointToPoint(e,Gr);const l=e.distanceToSquared(Gr);return l<a&&(mi.copy(Gr),a=l,c=u),l<o}}),a===1/0)return null;const h=Math.sqrt(a);return t.point?t.point.copy(mi):t.point=mi.clone(),t.distance=h,t.faceIndex=c,t}const mr=new f.Vector3,gr=new f.Vector3,vr=new f.Vector3,_n=new f.Vector2,Sn=new f.Vector2,Tn=new f.Vector2,Ss=new f.Vector3,Ts=new f.Vector3,As=new f.Vector3,An=new f.Vector3;function lc(s,e,t,r,n,o,i,a){let c;if(o===f.BackSide?c=s.intersectTriangle(r,t,e,!0,n):c=s.intersectTriangle(e,t,r,o!==f.DoubleSide,n),c===null)return null;const h=s.origin.distanceTo(n);return h<i||h>a?null:{distance:h,point:n.clone()}}function uc(s,e,t,r,n,o,i,a,c,h,d){mr.fromBufferAttribute(e,o),gr.fromBufferAttribute(e,i),vr.fromBufferAttribute(e,a);const u=lc(s,mr,gr,vr,An,c,h,d);if(u){r&&(_n.fromBufferAttribute(r,o),Sn.fromBufferAttribute(r,i),Tn.fromBufferAttribute(r,a),u.uv=f.Triangle.getInterpolation(An,mr,gr,vr,_n,Sn,Tn,new f.Vector2)),n&&(_n.fromBufferAttribute(n,o),Sn.fromBufferAttribute(n,i),Tn.fromBufferAttribute(n,a),u.uv1=f.Triangle.getInterpolation(An,mr,gr,vr,_n,Sn,Tn,new f.Vector2)),t&&(Ss.fromBufferAttribute(t,o),Ts.fromBufferAttribute(t,i),As.fromBufferAttribute(t,a),u.normal=f.Triangle.getInterpolation(An,mr,gr,vr,Ss,Ts,As,new f.Vector3),u.normal.dot(s.direction)>0&&u.normal.multiplyScalar(-1));const l={a:o,b:i,c:a,normal:new f.Vector3,materialIndex:0};f.Triangle.getNormal(mr,gr,vr,l.normal),u.face=l,u.faceIndex=o}return u}function Mn(s,e,t,r,n,o,i){const a=r*3;let c=a+0,h=a+1,d=a+2;const u=s.index;s.index&&(c=u.getX(c),h=u.getX(h),d=u.getX(d));const{position:l,normal:v,uv:b,uv1:S}=s.attributes,g=uc(t,l,v,b,S,c,h,d,e,o,i);return g?(g.faceIndex=r,n&&n.push(g),g):null}function Oe(s,e,t,r){const n=s.a,o=s.b,i=s.c;let a=e,c=e+1,h=e+2;t&&(a=t.getX(a),c=t.getX(c),h=t.getX(h)),n.x=r.getX(a),n.y=r.getY(a),n.z=r.getZ(a),o.x=r.getX(c),o.y=r.getY(c),o.z=r.getZ(c),i.x=r.getX(h),i.y=r.getY(h),i.z=r.getZ(h)}function hc(s,e,t,r,n,o,i,a){const{geometry:c,_indirectBuffer:h}=s;for(let d=r,u=r+n;d<u;d++)Mn(c,e,t,d,o,i,a)}function fc(s,e,t,r,n,o,i){const{geometry:a,_indirectBuffer:c}=s;let h=1/0,d=null;for(let u=r,l=r+n;u<l;u++){let v;v=Mn(a,e,t,u,null,o,i),v&&v.distance<h&&(d=v,h=v.distance)}return d}function dc(s,e,t,r,n,o,i){const{geometry:a}=t,{index:c}=a,h=a.attributes.position;for(let d=s,u=e+s;d<u;d++){let l;if(l=d,Oe(i,l*3,c,h),i.needsUpdate=!0,r(i,l,n,o))return!0}return!1}function pc(s,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=s.geometry,r=t.index?t.index.array:null,n=t.attributes.position;let o,i,a,c,h=0;const d=s._roots;for(let l=0,v=d.length;l<v;l++)o=d[l],i=new Uint32Array(o),a=new Uint16Array(o),c=new Float32Array(o),u(0,h),h+=o.byteLength;function u(l,v,b=!1){const S=l*2;if(a[S+15]===vn){const x=i[l+6],w=a[S+14];let T=1/0,A=1/0,P=1/0,D=-1/0,R=-1/0,O=-1/0;for(let L=3*x,E=3*(x+w);L<E;L++){let G=r[L];const z=n.getX(G),V=n.getY(G),U=n.getZ(G);z<T&&(T=z),z>D&&(D=z),V<A&&(A=V),V>R&&(R=V),U<P&&(P=U),U>O&&(O=U)}return c[l+0]!==T||c[l+1]!==A||c[l+2]!==P||c[l+3]!==D||c[l+4]!==R||c[l+5]!==O?(c[l+0]=T,c[l+1]=A,c[l+2]=P,c[l+3]=D,c[l+4]=R,c[l+5]=O,!0):!1}else{const x=l+8,w=i[l+6],T=x+v,A=w+v;let P=b,D=!1,R=!1;e?P||(D=e.has(T),R=e.has(A),P=!D&&!R):(D=!0,R=!0);const O=P||D,L=P||R;let E=!1;O&&(E=u(x,v,P));let G=!1;L&&(G=u(w,v,P));const z=E||G;if(z)for(let V=0;V<3;V++){const U=x+V,H=w+V,ne=c[U],ge=c[U+3],Pe=c[H],ve=c[H+3];c[l+V]=ne<Pe?ne:Pe,c[l+V+3]=ge>ve?ge:ve}return z}}}function Gt(s,e,t,r,n){let o,i,a,c,h,d;const u=1/t.direction.x,l=1/t.direction.y,v=1/t.direction.z,b=t.origin.x,S=t.origin.y,g=t.origin.z;let x=e[s],w=e[s+3],T=e[s+1],A=e[s+3+1],P=e[s+2],D=e[s+3+2];return u>=0?(o=(x-b)*u,i=(w-b)*u):(o=(w-b)*u,i=(x-b)*u),l>=0?(a=(T-S)*l,c=(A-S)*l):(a=(A-S)*l,c=(T-S)*l),o>c||a>i||((a>o||isNaN(o))&&(o=a),(c<i||isNaN(i))&&(i=c),v>=0?(h=(P-g)*v,d=(D-g)*v):(h=(D-g)*v,d=(P-g)*v),o>d||h>i)?!1:((h>o||o!==o)&&(o=h),(d<i||i!==i)&&(i=d),o<=n&&i>=r)}function mc(s,e,t,r,n,o,i,a){const{geometry:c,_indirectBuffer:h}=s;for(let d=r,u=r+n;d<u;d++){let l=h?h[d]:d;Mn(c,e,t,l,o,i,a)}}function gc(s,e,t,r,n,o,i){const{geometry:a,_indirectBuffer:c}=s;let h=1/0,d=null;for(let u=r,l=r+n;u<l;u++){let v;v=Mn(a,e,t,c?c[u]:u,null,o,i),v&&v.distance<h&&(d=v,h=v.distance)}return d}function vc(s,e,t,r,n,o,i){const{geometry:a}=t,{index:c}=a,h=a.attributes.position;for(let d=s,u=e+s;d<u;d++){let l;if(l=t.resolveTriangleIndex(d),Oe(i,l*3,c,h),i.needsUpdate=!0,r(i,l,n,o))return!0}return!1}function yc(s,e,t,r,n,o,i){Me.setBuffer(s._roots[e]),gi(0,s,t,r,n,o,i),Me.clearBuffer()}function gi(s,e,t,r,n,o,i){const{float32Array:a,uint16Array:c,uint32Array:h}=Me,d=s*2;if(Ye(d,c)){const l=Xe(s,h),v=Je(d,c);hc(e,t,r,l,v,n,o,i)}else{const l=ot(s);Gt(l,a,r,o,i)&&gi(l,e,t,r,n,o,i);const v=He(s,h);Gt(v,a,r,o,i)&&gi(v,e,t,r,n,o,i)}}const bc=["x","y","z"];function xc(s,e,t,r,n,o){Me.setBuffer(s._roots[e]);const i=vi(0,s,t,r,n,o);return Me.clearBuffer(),i}function vi(s,e,t,r,n,o){const{float32Array:i,uint16Array:a,uint32Array:c}=Me;let h=s*2;if(Ye(h,a)){const u=Xe(s,c),l=Je(h,a);return fc(e,t,r,u,l,n,o)}else{const u=ci(s,c),l=bc[u],b=r.direction[l]>=0;let S,g;b?(S=ot(s),g=He(s,c)):(S=He(s,c),g=ot(s));const w=Gt(S,i,r,n,o)?vi(S,e,t,r,n,o):null;if(w){const P=w.point[l];if(b?P<=i[g+u]:P>=i[g+u+3])return w}const A=Gt(g,i,r,n,o)?vi(g,e,t,r,n,o):null;return w&&A?w.distance<=A.distance?w:A:w||A||null}}const In=new f.Box3,yr=new mt,br=new mt,Vr=new f.Matrix4,Ms=new qe,Cn=new qe;function wc(s,e,t,r){Me.setBuffer(s._roots[e]);const n=yi(0,s,t,r);return Me.clearBuffer(),n}function yi(s,e,t,r,n=null){const{float32Array:o,uint16Array:i,uint32Array:a}=Me;let c=s*2;if(n===null&&(t.boundingBox||t.computeBoundingBox(),Ms.set(t.boundingBox.min,t.boundingBox.max,r),n=Ms),Ye(c,i)){const d=e.geometry,u=d.index,l=d.attributes.position,v=t.index,b=t.attributes.position,S=Xe(s,a),g=Je(c,i);if(Vr.copy(r).invert(),t.boundsTree)return Fe(s,o,Cn),Cn.matrix.copy(Vr),Cn.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:w=>Cn.intersectsBox(w),intersectsTriangle:w=>{w.a.applyMatrix4(r),w.b.applyMatrix4(r),w.c.applyMatrix4(r),w.needsUpdate=!0;for(let T=S*3,A=(g+S)*3;T<A;T+=3)if(Oe(br,T,u,l),br.needsUpdate=!0,w.intersectsTriangle(br))return!0;return!1}});for(let x=S*3,w=(g+S)*3;x<w;x+=3){Oe(yr,x,u,l),yr.a.applyMatrix4(Vr),yr.b.applyMatrix4(Vr),yr.c.applyMatrix4(Vr),yr.needsUpdate=!0;for(let T=0,A=v.count;T<A;T+=3)if(Oe(br,T,v,b),br.needsUpdate=!0,yr.intersectsTriangle(br))return!0}}else{const d=s+8,u=a[s+6];return Fe(d,o,In),!!(n.intersectsBox(In)&&yi(d,e,t,r,n)||(Fe(u,o,In),n.intersectsBox(In)&&yi(u,e,t,r,n)))}}const Pn=new f.Matrix4,bi=new qe,jr=new qe,_c=new f.Vector3,Sc=new f.Vector3,Tc=new f.Vector3,Ac=new f.Vector3;function Mc(s,e,t,r={},n={},o=0,i=1/0){e.boundingBox||e.computeBoundingBox(),bi.set(e.boundingBox.min,e.boundingBox.max,t),bi.needsUpdate=!0;const a=s.geometry,c=a.attributes.position,h=a.index,d=e.attributes.position,u=e.index,l=at.getPrimitive(),v=at.getPrimitive();let b=_c,S=Sc,g=null,x=null;n&&(g=Tc,x=Ac);let w=1/0,T=null,A=null;return Pn.copy(t).invert(),jr.matrix.copy(Pn),s.shapecast({boundsTraverseOrder:P=>bi.distanceToBox(P),intersectsBounds:(P,D,R)=>R<w&&R<i?(D&&(jr.min.copy(P.min),jr.max.copy(P.max),jr.needsUpdate=!0),!0):!1,intersectsRange:(P,D)=>{if(e.boundsTree)return e.boundsTree.shapecast({boundsTraverseOrder:O=>jr.distanceToBox(O),intersectsBounds:(O,L,E)=>E<w&&E<i,intersectsRange:(O,L)=>{for(let E=O,G=O+L;E<G;E++){Oe(v,3*E,u,d),v.a.applyMatrix4(t),v.b.applyMatrix4(t),v.c.applyMatrix4(t),v.needsUpdate=!0;for(let z=P,V=P+D;z<V;z++){Oe(l,3*z,h,c),l.needsUpdate=!0;const U=l.distanceToTriangle(v,b,g);if(U<w&&(S.copy(b),x&&x.copy(g),w=U,T=z,A=E),U<o)return!0}}}});{const R=fr(e);for(let O=0,L=R;O<L;O++){Oe(v,3*O,u,d),v.a.applyMatrix4(t),v.b.applyMatrix4(t),v.c.applyMatrix4(t),v.needsUpdate=!0;for(let E=P,G=P+D;E<G;E++){Oe(l,3*E,h,c),l.needsUpdate=!0;const z=l.distanceToTriangle(v,b,g);if(z<w&&(S.copy(b),x&&x.copy(g),w=z,T=E,A=O),z<o)return!0}}}}}),at.releasePrimitive(l),at.releasePrimitive(v),w===1/0?null:(r.point?r.point.copy(S):r.point=S.clone(),r.distance=w,r.faceIndex=T,n&&(n.point?n.point.copy(x):n.point=x.clone(),n.point.applyMatrix4(Pn),S.applyMatrix4(Pn),n.distance=S.sub(n.point).length(),n.faceIndex=A),r)}function Ic(s,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=s.geometry,r=t.index?t.index.array:null,n=t.attributes.position;let o,i,a,c,h=0;const d=s._roots;for(let l=0,v=d.length;l<v;l++)o=d[l],i=new Uint32Array(o),a=new Uint16Array(o),c=new Float32Array(o),u(0,h),h+=o.byteLength;function u(l,v,b=!1){const S=l*2;if(a[S+15]===vn){const x=i[l+6],w=a[S+14];let T=1/0,A=1/0,P=1/0,D=-1/0,R=-1/0,O=-1/0;for(let L=x,E=x+w;L<E;L++){const G=3*s.resolveTriangleIndex(L);for(let z=0;z<3;z++){let V=G+z;V=r?r[V]:V;const U=n.getX(V),H=n.getY(V),ne=n.getZ(V);U<T&&(T=U),U>D&&(D=U),H<A&&(A=H),H>R&&(R=H),ne<P&&(P=ne),ne>O&&(O=ne)}}return c[l+0]!==T||c[l+1]!==A||c[l+2]!==P||c[l+3]!==D||c[l+4]!==R||c[l+5]!==O?(c[l+0]=T,c[l+1]=A,c[l+2]=P,c[l+3]=D,c[l+4]=R,c[l+5]=O,!0):!1}else{const x=l+8,w=i[l+6],T=x+v,A=w+v;let P=b,D=!1,R=!1;e?P||(D=e.has(T),R=e.has(A),P=!D&&!R):(D=!0,R=!0);const O=P||D,L=P||R;let E=!1;O&&(E=u(x,v,P));let G=!1;L&&(G=u(w,v,P));const z=E||G;if(z)for(let V=0;V<3;V++){const U=x+V,H=w+V,ne=c[U],ge=c[U+3],Pe=c[H],ve=c[H+3];c[l+V]=ne<Pe?ne:Pe,c[l+V+3]=ge>ve?ge:ve}return z}}}function Cc(s,e,t,r,n,o,i){Me.setBuffer(s._roots[e]),xi(0,s,t,r,n,o,i),Me.clearBuffer()}function xi(s,e,t,r,n,o,i){const{float32Array:a,uint16Array:c,uint32Array:h}=Me,d=s*2;if(Ye(d,c)){const l=Xe(s,h),v=Je(d,c);mc(e,t,r,l,v,n,o,i)}else{const l=ot(s);Gt(l,a,r,o,i)&&xi(l,e,t,r,n,o,i);const v=He(s,h);Gt(v,a,r,o,i)&&xi(v,e,t,r,n,o,i)}}const Pc=["x","y","z"];function Dc(s,e,t,r,n,o){Me.setBuffer(s._roots[e]);const i=wi(0,s,t,r,n,o);return Me.clearBuffer(),i}function wi(s,e,t,r,n,o){const{float32Array:i,uint16Array:a,uint32Array:c}=Me;let h=s*2;if(Ye(h,a)){const u=Xe(s,c),l=Je(h,a);return gc(e,t,r,u,l,n,o)}else{const u=ci(s,c),l=Pc[u],b=r.direction[l]>=0;let S,g;b?(S=ot(s),g=He(s,c)):(S=He(s,c),g=ot(s));const w=Gt(S,i,r,n,o)?wi(S,e,t,r,n,o):null;if(w){const P=w.point[l];if(b?P<=i[g+u]:P>=i[g+u+3])return w}const A=Gt(g,i,r,n,o)?wi(g,e,t,r,n,o):null;return w&&A?w.distance<=A.distance?w:A:w||A||null}}const Dn=new f.Box3,xr=new mt,wr=new mt,Wr=new f.Matrix4,Is=new qe,Rn=new qe;function Rc(s,e,t,r){Me.setBuffer(s._roots[e]);const n=_i(0,s,t,r);return Me.clearBuffer(),n}function _i(s,e,t,r,n=null){const{float32Array:o,uint16Array:i,uint32Array:a}=Me;let c=s*2;if(n===null&&(t.boundingBox||t.computeBoundingBox(),Is.set(t.boundingBox.min,t.boundingBox.max,r),n=Is),Ye(c,i)){const d=e.geometry,u=d.index,l=d.attributes.position,v=t.index,b=t.attributes.position,S=Xe(s,a),g=Je(c,i);if(Wr.copy(r).invert(),t.boundsTree)return Fe(s,o,Rn),Rn.matrix.copy(Wr),Rn.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:w=>Rn.intersectsBox(w),intersectsTriangle:w=>{w.a.applyMatrix4(r),w.b.applyMatrix4(r),w.c.applyMatrix4(r),w.needsUpdate=!0;for(let T=S,A=g+S;T<A;T++)if(Oe(wr,3*e.resolveTriangleIndex(T),u,l),wr.needsUpdate=!0,w.intersectsTriangle(wr))return!0;return!1}});for(let x=S,w=g+S;x<w;x++){const T=e.resolveTriangleIndex(x);Oe(xr,3*T,u,l),xr.a.applyMatrix4(Wr),xr.b.applyMatrix4(Wr),xr.c.applyMatrix4(Wr),xr.needsUpdate=!0;for(let A=0,P=v.count;A<P;A+=3)if(Oe(wr,A,v,b),wr.needsUpdate=!0,xr.intersectsTriangle(wr))return!0}}else{const d=s+8,u=a[s+6];return Fe(d,o,Dn),!!(n.intersectsBox(Dn)&&_i(d,e,t,r,n)||(Fe(u,o,Dn),n.intersectsBox(Dn)&&_i(u,e,t,r,n)))}}const Fn=new f.Matrix4,Si=new qe,Yr=new qe,Fc=new f.Vector3,Oc=new f.Vector3,Lc=new f.Vector3,Nc=new f.Vector3;function kc(s,e,t,r={},n={},o=0,i=1/0){e.boundingBox||e.computeBoundingBox(),Si.set(e.boundingBox.min,e.boundingBox.max,t),Si.needsUpdate=!0;const a=s.geometry,c=a.attributes.position,h=a.index,d=e.attributes.position,u=e.index,l=at.getPrimitive(),v=at.getPrimitive();let b=Fc,S=Oc,g=null,x=null;n&&(g=Lc,x=Nc);let w=1/0,T=null,A=null;return Fn.copy(t).invert(),Yr.matrix.copy(Fn),s.shapecast({boundsTraverseOrder:P=>Si.distanceToBox(P),intersectsBounds:(P,D,R)=>R<w&&R<i?(D&&(Yr.min.copy(P.min),Yr.max.copy(P.max),Yr.needsUpdate=!0),!0):!1,intersectsRange:(P,D)=>{if(e.boundsTree){const R=e.boundsTree;return R.shapecast({boundsTraverseOrder:O=>Yr.distanceToBox(O),intersectsBounds:(O,L,E)=>E<w&&E<i,intersectsRange:(O,L)=>{for(let E=O,G=O+L;E<G;E++){const z=R.resolveTriangleIndex(E);Oe(v,3*z,u,d),v.a.applyMatrix4(t),v.b.applyMatrix4(t),v.c.applyMatrix4(t),v.needsUpdate=!0;for(let V=P,U=P+D;V<U;V++){const H=s.resolveTriangleIndex(V);Oe(l,3*H,h,c),l.needsUpdate=!0;const ne=l.distanceToTriangle(v,b,g);if(ne<w&&(S.copy(b),x&&x.copy(g),w=ne,T=V,A=E),ne<o)return!0}}}})}else{const R=fr(e);for(let O=0,L=R;O<L;O++){Oe(v,3*O,u,d),v.a.applyMatrix4(t),v.b.applyMatrix4(t),v.c.applyMatrix4(t),v.needsUpdate=!0;for(let E=P,G=P+D;E<G;E++){const z=s.resolveTriangleIndex(E);Oe(l,3*z,h,c),l.needsUpdate=!0;const V=l.distanceToTriangle(v,b,g);if(V<w&&(S.copy(b),x&&x.copy(g),w=V,T=E,A=O),V<o)return!0}}}}}),at.releasePrimitive(l),at.releasePrimitive(v),w===1/0?null:(r.point?r.point.copy(S):r.point=S.clone(),r.distance=w,r.faceIndex=T,n&&(n.point?n.point.copy(x):n.point=x.clone(),n.point.applyMatrix4(Fn),S.applyMatrix4(Fn),n.distance=S.sub(n.point).length(),n.faceIndex=A),r)}function Bc(){return typeof SharedArrayBuffer<"u"}const qr=new Me.constructor,On=new Me.constructor,Vt=new di(()=>new f.Box3),_r=new f.Box3,Sr=new f.Box3,Ti=new f.Box3,Ai=new f.Box3;let Mi=!1;function zc(s,e,t,r){if(Mi)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");Mi=!0;const n=s._roots,o=e._roots;let i,a=0,c=0;const h=new f.Matrix4().copy(t).invert();for(let d=0,u=n.length;d<u;d++){qr.setBuffer(n[d]),c=0;const l=Vt.getPrimitive();Fe(0,qr.float32Array,l),l.applyMatrix4(h);for(let v=0,b=o.length;v<b&&(On.setBuffer(o[v]),i=gt(0,0,t,h,r,a,c,0,0,l),On.clearBuffer(),c+=o[v].length,!i);v++);if(Vt.releasePrimitive(l),qr.clearBuffer(),a+=n[d].length,i)break}return Mi=!1,i}function gt(s,e,t,r,n,o=0,i=0,a=0,c=0,h=null,d=!1){let u,l;d?(u=On,l=qr):(u=qr,l=On);const v=u.float32Array,b=u.uint32Array,S=u.uint16Array,g=l.float32Array,x=l.uint32Array,w=l.uint16Array,T=s*2,A=e*2,P=Ye(T,S),D=Ye(A,w);let R=!1;if(D&&P)d?R=n(Xe(e,x),Je(e*2,w),Xe(s,b),Je(s*2,S),c,i+e,a,o+s):R=n(Xe(s,b),Je(s*2,S),Xe(e,x),Je(e*2,w),a,o+s,c,i+e);else if(D){const O=Vt.getPrimitive();Fe(e,g,O),O.applyMatrix4(t);const L=ot(s),E=He(s,b);Fe(L,v,_r),Fe(E,v,Sr);const G=O.intersectsBox(_r),z=O.intersectsBox(Sr);R=G&>(e,L,r,t,n,i,o,c,a+1,O,!d)||z&>(e,E,r,t,n,i,o,c,a+1,O,!d),Vt.releasePrimitive(O)}else{const O=ot(e),L=He(e,x);Fe(O,g,Ti),Fe(L,g,Ai);const E=h.intersectsBox(Ti),G=h.intersectsBox(Ai);if(E&&G)R=gt(s,O,t,r,n,o,i,a,c+1,h,d)||gt(s,L,t,r,n,o,i,a,c+1,h,d);else if(E)if(P)R=gt(s,O,t,r,n,o,i,a,c+1,h,d);else{const z=Vt.getPrimitive();z.copy(Ti).applyMatrix4(t);const V=ot(s),U=He(s,b);Fe(V,v,_r),Fe(U,v,Sr);const H=z.intersectsBox(_r),ne=z.intersectsBox(Sr);R=H&>(O,V,r,t,n,i,o,c,a+1,z,!d)||ne&>(O,U,r,t,n,i,o,c,a+1,z,!d),Vt.releasePrimitive(z)}else if(G)if(P)R=gt(s,L,t,r,n,o,i,a,c+1,h,d);else{const z=Vt.getPrimitive();z.copy(Ai).applyMatrix4(t);const V=ot(s),U=He(s,b);Fe(V,v,_r),Fe(U,v,Sr);const H=z.intersectsBox(_r),ne=z.intersectsBox(Sr);R=H&>(L,V,r,t,n,i,o,c,a+1,z,!d)||ne&>(L,U,r,t,n,i,o,c,a+1,z,!d),Vt.releasePrimitive(z)}}return R}const Ln=new qe,Cs=new f.Box3,Ec={strategy:us,maxDepth:40,maxLeafTris:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null};class Ii{static serialize(e,t={}){t={cloneBuffers:!0,...t};const r=e.geometry,n=e._roots,o=e._indirectBuffer,i=r.getIndex();let a;return t.cloneBuffers?a={roots:n.map(c=>c.slice()),index:i?i.array.slice():null,indirectBuffer:o?o.slice():null}:a={roots:n,index:i?i.array:null,indirectBuffer:o},a}static deserialize(e,t,r={}){r={setIndex:!0,indirect:!!e.indirectBuffer,...r};const{index:n,roots:o,indirectBuffer:i}=e,a=new Ii(t,{...r,[si]:!0});if(a._roots=o,a._indirectBuffer=i||null,r.setIndex){const c=t.getIndex();if(c===null){const h=new f.BufferAttribute(e.index,1,!1);t.setIndex(h)}else c.array!==n&&(c.array.set(n),c.needsUpdate=!0)}return a}get indirect(){return!!this._indirectBuffer}constructor(e,t={}){if(e.isBufferGeometry){if(e.index&&e.index.isInterleavedBufferAttribute)throw new Error("MeshBVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("MeshBVH: Only BufferGeometries are supported.");if(t=Object.assign({...Ec,[si]:!1},t),t.useSharedArrayBuffer&&!Bc())throw new Error("MeshBVH: SharedArrayBuffer is not available.");this.geometry=e,this._roots=null,this._indirectBuffer=null,t[si]||(tc(this,t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new f.Box3))),this.resolveTriangleIndex=t.indirect?r=>this._indirectBuffer[r]:r=>r}refit(e=null){return(this.indirect?Ic:pc)(this,e)}traverse(e,t=0){const r=this._roots[t],n=new Uint32Array(r),o=new Uint16Array(r);i(0);function i(a,c=0){const h=a*2,d=o[h+15]===vn;if(d){const u=n[a+6],l=o[h+14];e(c,d,new Float32Array(r,a*4,6),u,l)}else{const u=a+zt/4,l=n[a+6],v=n[a+7];e(c,d,new Float32Array(r,a*4,6),v)||(i(u,c+1),i(l,c+1))}}}raycast(e,t=f.FrontSide,r=0,n=1/0){const o=this._roots,i=this.geometry,a=[],c=t.isMaterial,h=Array.isArray(t),d=i.groups,u=c?t.side:t,l=this.indirect?Cc:yc;for(let v=0,b=o.length;v<b;v++){const S=h?t[d[v].materialIndex].side:u,g=a.length;if(l(this,v,S,e,a,r,n),h){const x=d[v].materialIndex;for(let w=g,T=a.length;w<T;w++)a[w].face.materialIndex=x}}return a}raycastFirst(e,t=f.FrontSide,r=0,n=1/0){const o=this._roots,i=this.geometry,a=t.isMaterial,c=Array.isArray(t);let h=null;const d=i.groups,u=a?t.side:t,l=this.indirect?Dc:xc;for(let v=0,b=o.length;v<b;v++){const S=c?t[d[v].materialIndex].side:u,g=l(this,v,S,e,r,n);g!=null&&(h==null||g.distance<h.distance)&&(h=g,c&&(g.face.materialIndex=d[v].materialIndex))}return h}intersectsGeometry(e,t){let r=!1;const n=this._roots,o=this.indirect?Rc:wc;for(let i=0,a=n.length;i<a&&(r=o(this,i,e,t),!r);i++);return r}shapecast(e){const t=at.getPrimitive(),r=this.indirect?vc:dc;let{boundsTraverseOrder:n,intersectsBounds:o,intersectsRange:i,intersectsTriangle:a}=e;if(i&&a){const u=i;i=(l,v,b,S,g)=>u(l,v,b,S,g)?!0:r(l,v,this,a,b,S,t)}else i||(a?i=(u,l,v,b)=>r(u,l,this,a,v,b,t):i=(u,l,v)=>v);let c=!1,h=0;const d=this._roots;for(let u=0,l=d.length;u<l;u++){const v=d[u];if(c=ac(this,u,o,i,n,h),c)break;h+=v.byteLength}return at.releasePrimitive(t),c}bvhcast(e,t,r){let{intersectsRanges:n,intersectsTriangles:o}=r;const i=at.getPrimitive(),a=this.geometry.index,c=this.geometry.attributes.position,h=this.indirect?b=>{const S=this.resolveTriangleIndex(b);Oe(i,S*3,a,c)}:b=>{Oe(i,b*3,a,c)},d=at.getPrimitive(),u=e.geometry.index,l=e.geometry.attributes.position,v=e.indirect?b=>{const S=e.resolveTriangleIndex(b);Oe(d,S*3,u,l)}:b=>{Oe(d,b*3,u,l)};if(o){const b=(S,g,x,w,T,A,P,D)=>{for(let R=x,O=x+w;R<O;R++){v(R),d.a.applyMatrix4(t),d.b.applyMatrix4(t),d.c.applyMatrix4(t),d.needsUpdate=!0;for(let L=S,E=S+g;L<E;L++)if(h(L),i.needsUpdate=!0,o(i,d,L,R,T,A,P,D))return!0}return!1};if(n){const S=n;n=function(g,x,w,T,A,P,D,R){return S(g,x,w,T,A,P,D,R)?!0:b(g,x,w,T,A,P,D,R)}}else n=b}return zc(this,e,t,n)}intersectsBox(e,t){return Ln.set(e.min,e.max,t),Ln.needsUpdate=!0,this.shapecast({intersectsBounds:r=>Ln.intersectsBox(r),intersectsTriangle:r=>Ln.intersectsTriangle(r)})}intersectsSphere(e){return this.shapecast({intersectsBounds:t=>e.intersectsBox(t),intersectsTriangle:t=>t.intersectsSphere(e)})}closestPointToGeometry(e,t,r={},n={},o=0,i=1/0){return(this.indirect?kc:Mc)(this,e,t,r,n,o,i)}closestPointToPoint(e,t={},r=0,n=1/0){return cc(this,e,t,r,n)}getBoundingBox(e){return e.makeEmpty(),this._roots.forEach(r=>{Fe(0,new Float32Array(r),Cs),e.union(Cs)}),e}}function Uc(s){switch(s){case 1:return"R";case 2:return"RG";case 3:return"RGBA";case 4:return"RGBA"}throw new Error}function Gc(s){switch(s){case 1:return f.RedFormat;case 2:return f.RGFormat;case 3:return f.RGBAFormat;case 4:return f.RGBAFormat}}function Ps(s){switch(s){case 1:return f.RedIntegerFormat;case 2:return f.RGIntegerFormat;case 3:return f.RGBAIntegerFormat;case 4:return f.RGBAIntegerFormat}}class Ds extends f.DataTexture{constructor(){super(),this.minFilter=f.NearestFilter,this.magFilter=f.NearestFilter,this.generateMipmaps=!1,this.overrideItemSize=null,this._forcedType=null}updateFrom(e){const t=this.overrideItemSize,r=e.itemSize,n=e.count;if(t!==null){if(r*n%t!==0)throw new Error("VertexAttributeTexture: overrideItemSize must divide evenly into buffer length.");e.itemSize=t,e.count=n*r/t}const o=e.itemSize,i=e.count,a=e.normalized,c=e.array.constructor,h=c.BYTES_PER_ELEMENT;let d=this._forcedType,u=o;if(d===null)switch(c){case Float32Array:d=f.FloatType;break;case Uint8Array:case Uint16Array:case Uint32Array:d=f.UnsignedIntType;break;case Int8Array:case Int16Array:case Int32Array:d=f.IntType;break}let l,v,b,S,g=Uc(o);switch(d){case f.FloatType:b=1,v=Gc(o),a&&h===1?(S=c,g+="8",c===Uint8Array?l=f.UnsignedByteType:(l=f.ByteType,g+="_SNORM")):(S=Float32Array,g+="32F",l=f.FloatType);break;case f.IntType:g+=h*8+"I",b=a?Math.pow(2,c.BYTES_PER_ELEMENT*8-1):1,v=Ps(o),h===1?(S=Int8Array,l=f.ByteType):h===2?(S=Int16Array,l=f.ShortType):(S=Int32Array,l=f.IntType);break;case f.UnsignedIntType:g+=h*8+"UI",b=a?Math.pow(2,c.BYTES_PER_ELEMENT*8-1):1,v=Ps(o),h===1?(S=Uint8Array,l=f.UnsignedByteType):h===2?(S=Uint16Array,l=f.UnsignedShortType):(S=Uint32Array,l=f.UnsignedIntType);break}u===3&&(v===f.RGBAFormat||v===f.RGBAIntegerFormat)&&(u=4);const x=Math.ceil(Math.sqrt(i))||1,w=u*x*x,T=new S(w),A=e.normalized;e.normalized=!1;for(let P=0;P<i;P++){const D=u*P;T[D]=e.getX(P)/b,o>=2&&(T[D+1]=e.getY(P)/b),o>=3&&(T[D+2]=e.getZ(P)/b,u===4&&(T[D+3]=1)),o>=4&&(T[D+3]=e.getW(P)/b)}e.normalized=A,this.internalFormat=g,this.format=v,this.type=l,this.image.width=x,this.image.height=x,this.image.data=T,this.needsUpdate=!0,this.dispose(),e.itemSize=r,e.count=n}}class Rs extends Ds{constructor(){super(),this._forcedType=f.UnsignedIntType}}class Fs extends Ds{constructor(){super(),this._forcedType=f.FloatType}}class Vc{constructor(){this.index=new Rs,this.position=new Fs,this.bvhBounds=new f.DataTexture,this.bvhContents=new f.DataTexture,this._cachedIndexAttr=null,this.index.overrideItemSize=3}updateFrom(e){const{geometry:t}=e;if(Wc(e,this.bvhBounds,this.bvhContents),this.position.updateFrom(t.attributes.position),e.indirect){const r=e._indirectBuffer;if(this._cachedIndexAttr===null||this._cachedIndexAttr.count!==r.length)if(t.index)this._cachedIndexAttr=t.index.clone();else{const n=ms(ps(t));this._cachedIndexAttr=new f.BufferAttribute(n,1,!1)}jc(t,r,this._cachedIndexAttr),this.index.updateFrom(this._cachedIndexAttr)}else this.index.updateFrom(t.index)}dispose(){const{index:e,position:t,bvhBounds:r,bvhContents:n}=this;e&&e.dispose(),t&&t.dispose(),r&&r.dispose(),n&&n.dispose()}}function jc(s,e,t){const r=t.array,n=s.index?s.index.array:null;for(let o=0,i=e.length;o<i;o++){const a=3*o,c=3*e[o];for(let h=0;h<3;h++)r[a+h]=n?n[c+h]:c+h}}function Wc(s,e,t){const r=s._roots;if(r.length!==1)throw new Error("MeshBVHUniformStruct: Multi-root BVHs not supported.");const n=r[0],o=new Uint16Array(n),i=new Uint32Array(n),a=new Float32Array(n),c=n.byteLength/zt,h=2*Math.ceil(Math.sqrt(c/2)),d=new Float32Array(4*h*h),u=Math.ceil(Math.sqrt(c)),l=new Uint32Array(2*u*u);for(let v=0;v<c;v++){const b=v*zt/4,S=b*2,g=b;for(let x=0;x<3;x++)d[8*v+0+x]=a[g+0+x],d[8*v+4+x]=a[g+3+x];if(Ye(S,o)){const x=Je(S,o),w=Xe(b,i),T=4294901760|x;l[v*2+0]=T,l[v*2+1]=w}else{const x=4*He(b,i)/zt,w=ci(b,i);l[v*2+0]=w,l[v*2+1]=x}}e.image.data=d,e.image.width=h,e.image.height=h,e.format=f.RGBAFormat,e.type=f.FloatType,e.internalFormat="RGBA32F",e.minFilter=f.NearestFilter,e.magFilter=f.NearestFilter,e.generateMipmaps=!1,e.needsUpdate=!0,e.dispose(),t.image.data=l,t.image.width=u,t.image.height=u,t.format=f.RGIntegerFormat,t.type=f.UnsignedIntType,t.internalFormat="RG32UI",t.minFilter=f.NearestFilter,t.magFilter=f.NearestFilter,t.generateMipmaps=!1,t.needsUpdate=!0,t.dispose()}const Yc=`
|
|
30
|
+
<%s key={someKey} {...props} />`,Z,F,Y,F),lr[F+Z]=!0}}return m===r?an(_):on(_),_}}function cn(m,C,N){return ur(m,C,N,!0)}function ln(m,C,N){return ur(m,C,N,!1)}var Nr=ln,un=cn;Br.Fragment=r,Br.jsx=Nr,Br.jsxs=un}()),Br}var qi;function Ro(){return qi||(qi=1,process.env.NODE_ENV==="production"?fn.exports=Po():fn.exports=Do()),fn.exports}var Ze=Ro();class oe extends Error{constructor(e,t,r){super(e),this.code=t,this.context=r,this.name="ThreeViewerError",this.timestamp=new Date,Error.captureStackTrace&&Error.captureStackTrace(this,oe)}static fromError(e,t,r){if(e instanceof oe)return e;const n=e instanceof Error?e.message:String(e),o={...r,originalError:e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:e};return new oe(n,t,o)}}var ue=(s=>(s.SCENE_INIT_FAILED="SCENE_INIT_FAILED",s.RENDERER_INIT_FAILED="RENDERER_INIT_FAILED",s.RENDERER_NOT_INITIALIZED="RENDERER_NOT_INITIALIZED",s.CAMERA_INIT_FAILED="CAMERA_INIT_FAILED",s.WEBGL_NOT_SUPPORTED="WEBGL_NOT_SUPPORTED",s.INITIALIZATION_FAILED="INITIALIZATION_FAILED",s.PATH_TRACING_INIT_FAILED="PATH_TRACING_INIT_FAILED",s.MODEL_LOAD_FAILED="MODEL_LOAD_FAILED",s.TEXTURE_LOAD_FAILED="TEXTURE_LOAD_FAILED",s.RESOURCE_NOT_FOUND="RESOURCE_NOT_FOUND",s.UNSUPPORTED_FORMAT="UNSUPPORTED_FORMAT",s.INVALID_CONFIGURATION="INVALID_CONFIGURATION",s.RENDER_ERROR="RENDER_ERROR",s.RENDER_FAILED="RENDER_FAILED",s.SCENE_OPERATION_FAILED="SCENE_OPERATION_FAILED",s.COMPONENT_NOT_MOUNTED="COMPONENT_NOT_MOUNTED",s.INVALID_STATE="INVALID_STATE",s.INVALID_PARAMETER="INVALID_PARAMETER",s.OPERATION_FAILED="OPERATION_FAILED",s.UNKNOWN="UNKNOWN",s))(ue||{});const K={ok(s){return{ok:!0,value:s}},err(s){return{ok:!1,error:s}},wrap(s){try{return K.ok(s())}catch(e){return K.err(e instanceof oe?e:new oe(String(e),ue.UNKNOWN,{originalError:e}))}}};class dn{constructor(){this.listeners=new Map}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);const r=this.listeners.get(e);return r&&r.add(t),()=>{var n;(n=this.listeners.get(e))==null||n.delete(t)}}emit(e,t){var r;(r=this.listeners.get(e))==null||r.forEach(n=>{try{n(t)}catch(o){console.error(`Error in event listener for ${String(e)}:`,o)}})}once(e,t){const r=this.on(e,n=>{r(),t(n)});return r}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 r;(r=this.listeners.get(e))==null||r.delete(t)}removeListener(e,t){this.off(e,t)}}class Fo{constructor(e={}){this.animationFrameId=null,this.lastRenderTime=0,this.idleTimeout=null,this.isIdle=!1,this.needsRender=!0,this.continuousRenderingEnabled=!1,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()}enableContinuousRendering(){this.continuousRenderingEnabled=!0,this.wakeUp()}disableContinuousRendering(){this.continuousRenderingEnabled=!1}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=r=>{if(this.animationFrameId===null)return;const n=r-this.lastRenderTime;if(this.enableFrameRateLimiting&&n<this.frameInterval){this.animationFrameId=requestAnimationFrame(t);return}(this.alwaysRender||this.needsRender||this.continuousRenderingEnabled)&&(e(n),this.lastRenderTime=r,this.needsRender=!1,this.enableIdleDetection&&!this.alwaysRender&&(this.wakeUp(),this.continuousRenderingEnabled||(this.idleTimeout=window.setTimeout(()=>{this.isIdle=!0,console.log("[RenderLoopManager] Entering idle state")},this.idleDelay)))),this.alwaysRender||!this.enableIdleDetection||!this.isIdle||this.continuousRenderingEnabled||this.needsRender?this.animationFrameId=requestAnimationFrame(t):(console.log("[RenderLoopManager] Stopping render loop (idle)"),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.alwaysRender=!1}isRunning(){return this.animationFrameId!==null}getIsIdle(){return this.isIdle}getNeedsRender(){return this.needsRender||this.continuousRenderingEnabled||this.alwaysRender}}class Zi{static serialize(e,t,r,n){const o=t.position,i=r.target||{x:0,y:0,z:0};return{modelUrl:e,cameraPosition:{x:o.x,y:o.y,z:o.z},cameraTarget:{x:i.x,y:i.y,z:i.z},controlsTarget:{x:i.x,y:i.y,z:i.z},rendererSize:{width:n.clientWidth,height:n.clientHeight}}}static async restore(e,t,r,n){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}),r.target&&r.target.set(e.controlsTarget.x,e.controlsTarget.y,e.controlsTarget.z),r.update&&r.update(),e.modelUrl&&n&&await n(e.modelUrl)}}function At(s){return s!==null&&typeof s=="object"&&"getInternalRenderer"in s&&typeof s.getInternalRenderer=="function"}class pt{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 pt({...this.data,isInitialized:!0,status:"idle"})}startLoading(){return new pt({...this.data,status:"loading",loadProgress:0,error:null})}updateLoadProgress(e){return new pt({...this.data,loadProgress:Math.min(Math.max(0,e),1)})}setLoaded(e){return new pt({...this.data,status:"loaded",currentModel:e,loadProgress:1,error:null})}setError(e){return new pt({...this.data,status:"error",error:e,loadProgress:0})}startRendering(){return new pt({...this.data,status:"rendering"})}updateRenderInfo(e){return new pt({...this.data,renderInfo:{...this.data.renderInfo,...e}})}dispose(){return new pt({...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 Oo{constructor(){this.state=new pt,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(r){console.error("Error in state change callback:",r)}})}}class Lo{constructor(e){this.screenshotElement=null,this.isShowingScreenshot=!1,this.renderer=e.renderer,this.onRestore=e.onRestore}isActive(){return this.isShowingScreenshot}captureAndReplace(e,t,r,n){if(this.isShowingScreenshot)return;const o=this.renderer.getDomElement(),i=o.toDataURL("image/png"),a=document.createElement("img");a.src=i,a.style.position="absolute",a.style.top="0",a.style.left="0",a.style.width="100%",a.style.height="100%",a.style.pointerEvents="auto",a.style.cursor="grab";const c=o.parentElement;if(c){this.serializedSceneState=Zi.serialize(r,e,t,o),o.style.display="none",c.appendChild(a),this.screenshotElement=a,this.isShowingScreenshot=!0;const h=()=>{this.restore()};a.addEventListener("mousedown",h),a.addEventListener("touchstart",h);const d=()=>{this.isShowingScreenshot&&this.restore()};window.addEventListener("resize",d),this.screenshotResizeHandler=d,this.screenshotElement&&this.screenshotElement.src?n==null||n():console.warn("[ScreenshotManager] Screenshot capture failed, keeping scene resources")}}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.screenshotElement=null,this.isShowingScreenshot=!1,this.serializedSceneState=void 0}}class No{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.autoFitToObject=e.autoFitToObject??!1}getCurrentModel(){return this.currentModel}getLastModelUrl(){return this.lastModelUrl}async loadModel(e,t){const r=performance.now();try{let n;if(typeof e=="string"){this.lastModelUrl=e;const a=await this.modelLoader.load(e);if(!a.ok)throw a.error;n=a.value.scene}else n=e;this.currentModel&&(this.scene.remove(this.currentModel),this.disposeObject(this.currentModel));const o=this.scene.add(n);if(!o.ok)throw o.error;if(this.floorAlignmentService){const a=this.floorAlignmentService.alignToFloor(n);a.ok||console.warn("Failed to align model to floor:",a.error)}if(n.traverse(a=>{"castShadow"in a&&"receiveShadow"in a&&(a.castShadow=!0,a.receiveShadow=!0)}),this.currentModel=n,this.sceneSetupService){const a=this.sceneSetupService.addDynamicGrid(this.scene,n,2);a.ok||console.warn("Failed to add dynamic grid:",a.error)}if(this.autoFitToObject&&this.sceneSetupService){const a=this.sceneSetupService.fitCameraToObject(n,this.camera,this.controls);a.ok||console.warn("Failed to fit camera to object:",a.error)}const i=performance.now()-r;return t.emit("model:loaded",{model:n,loadTime:i}),K.ok(n)}catch(n){const o=n instanceof oe?n:new oe("Failed to load model",ue.MODEL_LOAD_FAILED,{originalError:n,source:e});return t.emit("model:error",{error:o,url:typeof e=="string"?e:void 0}),K.err(o)}}disposeCurrentModel(){this.currentModel&&(this.scene.remove(this.currentModel),this.disposeObject(this.currentModel),this.currentModel=null)}disposeObject(e){e.traverse(t=>{var r,n,o;if("geometry"in t&&((r=t.geometry)!=null&&r.dispose)&&((o=(n=t.geometry)==null?void 0:n.dispose)==null||o.call(n)),"material"in t&&t.material){const i=t.material;Array.isArray(i)?i.forEach(a=>{var c;(c=a.dispose)==null||c.call(a)}):i!=null&&i.dispose&&i.dispose()}}),e.dispose()}dispose(){this.disposeCurrentModel(),this.lastModelUrl=void 0}}class Zn{static getMemoryInfo(){const e=performance;return e.memory?{jsHeapUsed:Math.round(e.memory.usedJSHeapSize/1048576),jsHeapTotal:Math.round(e.memory.totalJSHeapSize/1048576),jsHeapLimit:Math.round(e.memory.jsHeapSizeLimit/1048576)}:null}static formatBytes(e){return e<1024?e+" B":e<1048576?(e/1024).toFixed(1)+" KB":e<1073741824?(e/1048576).toFixed(1)+" MB":(e/1073741824).toFixed(1)+" GB"}static logMemoryUsage(e="Memory"){const t=this.getMemoryInfo();t?(console.log(`[${e}] JS Heap: ${t.jsHeapUsed}MB / ${t.jsHeapTotal}MB (Limit: ${t.jsHeapLimit}MB)`),t.webglMemory&&console.log(`[${e}] WebGL - Programs: ${t.webglMemory.programs}, Geometries: ${t.webglMemory.geometries}, Textures: ${t.webglMemory.textures}`)):console.log(`[${e}] Memory info not available (use Chrome with --enable-precise-memory-info)`)}static startMonitoring(e=5e3,t="MemoryMonitor"){const r=setInterval(()=>{this.logMemoryUsage(t)},e);return()=>clearInterval(r)}}class ko{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){Zn.logMemoryUsage("Before scene disposal"),!e&&this.pathTracingService,this.environmentService&&this.environmentService.dispose(),this.scene.traverse&&this.scene.traverse(t=>{var r,n,o,i;"geometry"in t&&t.geometry&&((n=(r=t.geometry).dispose)==null||n.call(r)),"material"in t&&t.material&&(Array.isArray(t.material)?t.material.forEach(a=>{var c;(c=a.dispose)==null||c.call(a)}):(i=(o=t.material).dispose)==null||i.call(o))}),this.scene.clear&&this.scene.clear(),this.triggerGarbageCollection(),Zn.logMemoryUsage("After scene disposal"),setTimeout(()=>{Zn.logMemoryUsage("After GC delay")},2e3)}disposeServices(){this.pathTracingService&&(this.pathTracingService.dispose(),this.pathTracingService=void 0),this.environmentService&&(this.environmentService.dispose(),this.environmentService=void 0)}dispose(){this.disposeServices(),this.scene.clear&&this.scene.clear(),this.triggerGarbageCollection()}triggerGarbageCollection(){var e;globalThis.gc&&((e=globalThis.gc)==null||e.call(globalThis))}}class Bo{constructor(e){var n;this.lastFrameTime=0,this.frameCount=0,this.pathTracingCompleteHandled=!1,this.disposed=!1,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.pathTracingService=e.pathTracingService,this.stateManager=new Oo,this.screenshotManager=new Lo({renderer:this.renderer,onRestore:async()=>{await this.restoreFromScreenshot()}}),this.modelManager=new No({modelLoader:e.modelLoader,scene:this.scene,camera:this.camera,controls:this.controls,floorAlignmentService:e.floorAlignmentService,sceneSetupService:this.sceneSetupService,autoFitToObject:(n=this.options.camera)==null?void 0:n.autoFitToObject}),this.resourceManager=new ko({scene:this.scene,pathTracingService:this.pathTracingService,environmentService:this.environmentService}),this.events=new dn;const t=this.options.rendering||{},r=this.options.staticScene!==!1;this.renderLoopManager=new Fo({enableIdleDetection:t.enableIdleDetection??r,idleDelay:t.idleDelay,targetFPS:t.targetFPS,enableFrameRateLimiting:t.enableFrameRateLimiting,alwaysRender:!1})}async initialize(){var e,t,r,n,o,i,a,c,h,d,u,l;try{const v=this.rendererOptions||{},x=this.renderer.initialize(v);if(!x.ok)return x;if(this.sceneSetupService){if(this.options.helpers){const w={grid:this.options.helpers.grid,axes:this.options.helpers.axes,gridColor:"#AAAAAA"},T=this.sceneSetupService.addHelpers(this.scene,w);T.ok||console.warn("Failed to add helpers:",T.error)}const g=this.options.lighting;if(g){const w={ambient:g.ambientLight?{color:String(g.ambientLight.color),intensity:g.ambientLight.intensity}:void 0,hemisphere:g.hemisphereLight?{skyColor:String(g.hemisphereLight.skyColor),groundColor:String(g.hemisphereLight.groundColor),intensity:g.hemisphereLight.intensity}:void 0,directional:g.directionalLight?{color:String(g.directionalLight.color),intensity:g.directionalLight.intensity,position:Array.isArray(g.directionalLight.position)?g.directionalLight.position:void 0,castShadow:g.directionalLight.castShadow,shadow:g.directionalLight.shadow}:void 0},T=this.sceneSetupService.addLighting(this.scene,w);T.ok||console.warn("Failed to add lighting:",T.error)}const b=(e=this.options.environment)==null?void 0:e.url;if(this.options.backgroundColor&&!b&&this.sceneSetupService){const w=this.sceneSetupService.createGradientBackground(this.scene,{topColor:String(this.options.backgroundColor),bottomColor:String(this.options.backgroundColor)});w.ok||console.warn("Failed to set background:",w.error)}}if(this.environmentService){const g=await this.environmentService.initialize({renderer:this.renderer,autoDispose:!0});g.ok||console.warn("Failed to initialize environment service:",g.error);const b=(t=this.options.environment)==null?void 0:t.url;if(b){const w=await this.environmentService.loadEnvironmentMap(b);w.ok?this.environmentService.applyToScene(this.scene,w.value,{backgroundBlurriness:(r=this.options.environment)==null?void 0:r.backgroundBlurriness,backgroundIntensity:(n=this.options.environment)==null?void 0:n.backgroundIntensity,environmentIntensity:(o=this.options.environment)==null?void 0:o.environmentIntensity}):console.warn("Failed to load environment map:",w.error)}else if((i=this.options.helpers)!=null&&i.studioEnvironment){const w=this.environmentService.createStudioEnvironment();if(w.ok){if(this.environmentService.applyToScene(this.scene,w.value,{backgroundBlurriness:(a=this.options.environment)==null?void 0:a.backgroundBlurriness,backgroundIntensity:(c=this.options.environment)==null?void 0:c.backgroundIntensity,environmentIntensity:(h=this.options.environment)==null?void 0:h.environmentIntensity}),(d=this.options.helpers)!=null&&d.darkStudioMode&&this.sceneSetupService){const T="#1a1a1f",A=this.sceneSetupService.createGradientBackground(this.scene,{topColor:T,bottomColor:T});A.ok||console.warn("Failed to set dark studio background:",A.error)}}else console.warn("Failed to create studio environment:",w.error)}}const S=((u=this.options.pathTracing)==null?void 0:u.enabled)??!1;if(this.pathTracingService&&S){const g=await this.pathTracingService.initialize({enabled:!0,renderer:this.renderer});g.ok?(this.options.pathTracing&&this.pathTracingService.updateSettings({samples:this.options.pathTracing.maxSamples??300,bounces:this.options.pathTracing.bounces,transmissiveBounces:this.options.pathTracing.transmissiveBounces,renderScale:this.options.pathTracing.renderScale,lowResScale:this.options.pathTracing.lowResScale,dynamicLowRes:this.options.pathTracing.dynamicLowRes,enablePathTracing:this.options.pathTracing.enabled??S}),this.pathTracingService.events.on("pathtracing:paused",b=>{this.renderLoopManager.disableContinuousRendering(),this.options.staticScene||this.renderLoopManager.setAlwaysRender(!1),setTimeout(()=>{this.renderLoopManager.stop()},100)})):console.warn("Failed to initialize path tracing:",g.error)}if(this.stateManager.setInitialized(),this.startRenderLoop(),!this.options.staticScene)this.renderLoopManager.setAlwaysRender(!0);else{const g=((l=this.options.pathTracing)==null?void 0:l.enabled)??!1;this.pathTracingService&&g&&this.renderLoopManager.enableContinuousRendering()}return this.renderLoopManager.requestRender(),K.ok(void 0)}catch(v){const x=new oe("Failed to initialize viewer",ue.INITIALIZATION_FAILED,{originalError:v});return this.stateManager.setError(x),this.events.emit("error",{error:x}),K.err(x)}}async loadModel(e){var t;if(!this.stateManager.canLoad())return K.err(new oe("Cannot load model in current state",ue.INVALID_STATE,{currentState:this.stateManager.getStatus(),isInitialized:this.stateManager.isInitialized()}));try{this.stateManager.startLoading();const r=await this.modelManager.loadModel(e,this.events);if(r.ok){this.stateManager.setLoaded(r.value),this.renderLoopManager.requestRender();const n=((t=this.options.pathTracing)==null?void 0:t.enabled)??!1;return this.pathTracingService&&n&&(this.pathTracingService.reset(),this.pathTracingCompleteHandled=!1),K.ok(void 0)}else return this.stateManager.setError(r.error),r}catch(r){const n=r instanceof oe?r:new oe("Failed to load model",ue.MODEL_LOAD_FAILED,{originalError:r,source:e});return this.stateManager.setError(n),K.err(n)}}startRenderLoop(){this.renderLoopManager.start(e=>{var h,d,u,l,v;if(this.disposed){this.renderLoopManager.stop();return}if(!this.stateManager.isInitialized()||this.stateManager.getStatus()==="error")return;if(!this.renderer||this.renderer.renderer===null){this.renderLoopManager.stop();return}this.frameCount%60;const t=performance.now(),r=e>0?1e3/e:0;if(this.controls.update()){this.events.emit("controls:change",{controls:this.controls});const x=((h=this.options.pathTracing)==null?void 0:h.enabled)??!1;this.pathTracingService&&x&&(this.pathTracingService.reset(),this.pathTracingCompleteHandled=!1),this.renderLoopManager.requestRender()}const o=((d=this.pathTracingService)==null?void 0:d.isEnabled())||!1,i=((u=this.pathTracingService)==null?void 0:u.getSampleCount())||0,a=((l=this.options.pathTracing)==null?void 0:l.maxSamples)??300;if(this.renderFrame().catch(x=>{console.error("[ViewerCore] Render frame error:",x)}),(((v=this.pathTracingService)==null?void 0:v.getSampleCount())||0)>=a&&!this.pathTracingCompleteHandled&&o){if(this.pathTracingCompleteHandled=!0,this.renderLoopManager.disableContinuousRendering(),this.options.staticScene||this.renderLoopManager.setAlwaysRender(!1),this.events.emit("pathtracing:complete",{samples:i,totalTime:t-(this.pathTracingStartTime||0)}),this.options.replaceWithScreenshotOnComplete)setTimeout(()=>{this.replaceWithScreenshot(),setTimeout(()=>{this.renderLoopManager.stop()},200)},100);else if(this.renderLoopManager.requestRender(),setTimeout(()=>{this.renderLoopManager.stop()},100),At(this.renderer)){const x=this.renderer.getInternalRenderer();x&&(x.autoClear=!1)}}this.frameCount++,this.stateManager.updateRenderInfo({frameCount:this.frameCount,fps:Math.round(r),lastRenderTime:performance.now()-t}),this.lastFrameTime=t})}stopRenderLoop(){this.renderLoopManager.stop()}async renderFrame(){var h,d,u,l;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();let t;const r=((h=this.pathTracingService)==null?void 0:h.isEnabled())||!1,n=((d=this.pathTracingService)==null?void 0:d.getSampleCount())||0,o=((u=this.options.pathTracing)==null?void 0:u.maxSamples)??300;if(this.pathTracingService&&!this.pathTracingService.isPathTracerDisposed()&&(r||n>=o&&n>0)&&this.pathTracingService?(this.pathTracingService.getSampleCount()===0&&(this.pathTracingStartTime=performance.now()),t=await this.pathTracingService.render(this.scene,this.camera)):t=this.renderer.render(this.scene,this.camera),!t.ok){console.error("[ViewerCore] Render failed:",t.error),this.events.emit("error",{error:t.error});return}const a=performance.now()-e,c=((l=this.pathTracingService)==null?void 0:l.getSampleCount())||0;this.events.emit("render:complete",{frame:this.frameCount,renderTime:a,samples:c})}resize(e,t){var o;const r=this.renderer.getDomElement();if(r.width===e&&r.height===t)return;const n=(o=this.pathTracingService)==null?void 0:o.isEnabled();this.pathTracingService&&this.pathTracingService.hasImageOverlay()&&(this.pathTracingService.removeImageOverlay(),this.pathTracingService.reset()),this.camera.type==="perspective"&&"aspect"in this.camera&&(this.camera.aspect=e/t),this.camera.updateProjectionMatrix(),this.renderer.setSize(e,t);try{this.renderer.render(this.scene,this.camera)}catch{}n&&this.pathTracingService&&this.pathTracingService.setEnabled(!0),this.renderLoopManager.requestRender()}getState(){return this.stateManager.getState()}onStateChange(e){return this.stateManager.onStateChange(e)}getEvents(){return this.events}getDomElement(){return this.renderer.getDomElement()}replaceWithScreenshot(){const e=this.modelManager.getLastModelUrl();this.screenshotManager.captureAndReplace(this.camera,this.controls,e,()=>{this.modelManager.disposeCurrentModel(),this.resourceManager.disposeSceneResources(!0)})}async restoreFromScreenshot(){var t;const e=this.screenshotManager.getSerializedState();!this.pathTracingService&&((t=this.options.pathTracing)!=null&&t.enabled)&&console.warn("[ViewerCore] Cannot recreate path tracing service - feature disabled"),e&&await Zi.restore(e,this.camera,this.controls,async r=>{const n=await this.loadModel(r);n.ok||console.error("[ViewerCore] Failed to reload model:",n.error)}),this.renderLoopManager.isRunning()||this.startRenderLoop(),this.renderLoopManager.requestRender()}dispose(){this.disposed=!0,this.stopRenderLoop(),this.modelManager.dispose(),this.resourceManager.dispose(),this.screenshotManager.dispose(),this.scene.clear(),this.controls.dispose(),this.renderer.dispose(),this.stateManager.setDisposed(),this.events.removeAllListeners(),this.stateManager.clearCallbacks()}}class kt{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,r){this.vector.set(e,t,r)}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 kt(e)}static create(e=0,t=0,r=0){return new kt(new M.Vector3(e,t,r))}}class We{constructor(e){this.object=e,this.positionAdapter=kt.fromThreeVector(e.position),this.rotationAdapter=kt.fromThreeVector(e.rotation),this.scaleAdapter=kt.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 position(){return this.positionAdapter}get rotation(){return this.rotationAdapter}get scale(){return this.scaleAdapter}add(e){try{return e instanceof We?(this.object.add(e.getThreeObject()),K.ok(void 0)):K.err(new oe("Child must be a ThreeObject3DAdapter",ue.INVALID_PARAMETER))}catch(t){return K.err(new oe("Failed to add child object",ue.SCENE_OPERATION_FAILED,{originalError:t}))}}remove(e){try{return e instanceof We?(this.object.remove(e.getThreeObject()),K.ok(void 0)):K.err(new oe("Child must be a ThreeObject3DAdapter",ue.INVALID_PARAMETER))}catch(t){return K.err(new oe("Failed to remove child object",ue.SCENE_OPERATION_FAILED,{originalError:t}))}}traverse(e){this.object.traverse(t=>{e(new We(t))})}clone(){return new We(this.object.clone())}dispose(){this.object.traverse(e=>{var t;e instanceof M.Mesh&&((t=e.geometry)==null||t.dispose(),e.material&&(Array.isArray(e.material)?e.material.forEach(r=>r.dispose()):e.material.dispose()))})}getThreeObject(){return this.object}static fromThreeObject(e){return new We(e)}static create(){return new We(new M.Object3D)}}class Yt{constructor(e){this.scene=e||new M.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 We?(this.scene.add(e.getThreeObject()),K.ok(void 0)):K.err(new oe("Object must be a ThreeObject3DAdapter",ue.INVALID_PARAMETER))}catch(t){return K.err(new oe("Failed to add object to scene",ue.SCENE_OPERATION_FAILED,{originalError:t}))}}remove(e){try{return e instanceof We?(this.scene.remove(e.getThreeObject()),K.ok(void 0)):K.err(new oe("Object must be a ThreeObject3DAdapter",ue.INVALID_PARAMETER))}catch(t){return K.err(new oe("Failed to remove object from scene",ue.SCENE_OPERATION_FAILED,{originalError:t}))}}clear(){for(;this.scene.children.length>0;)this.scene.remove(this.scene.children[0])}traverse(e){this.scene.traverse(t=>{e(new We(t))})}get background(){return this.scene.background instanceof M.Color?new Kn(this.scene.background):this.scene.background instanceof M.Texture?new pn(this.scene.background):null}set background(e){e instanceof Kn?this.scene.background=e.getThreeColor():e instanceof pn?this.scene.background=e.getThreeTexture():this.scene.background=null}get fog(){return this.scene.fog?new Ki(this.scene.fog):null}set fog(e){e instanceof Ki?this.scene.fog=e.getThreeFog():this.scene.fog=null}get environment(){return this.scene.environment?new pn(this.scene.environment):null}set environment(e){e instanceof pn?this.scene.environment=e.getThreeTexture():this.scene.environment=null}getInternalRenderer(){return this.scene}getThreeScene(){return this.scene}}class Kn{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,r){this.color.setRGB(e,t,r)}getHex(){return this.color.getHex()}getThreeColor(){return this.color}}let pn=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 Ki{constructor(e){this.fog=e}get color(){return new Kn(this.fog.color)}get near(){return this.fog.near||0}get far(){return this.fog.far||1e3}getThreeFog(){return this.fog}}class Xn extends We{constructor(e){super(e),this.camera=e}get near(){return this.camera instanceof M.PerspectiveCamera||this.camera instanceof M.OrthographicCamera?this.camera.near:.1}set near(e){(this.camera instanceof M.PerspectiveCamera||this.camera instanceof M.OrthographicCamera)&&(this.camera.near=e)}get far(){return this.camera instanceof M.PerspectiveCamera||this.camera instanceof M.OrthographicCamera?this.camera.far:1e3}set far(e){(this.camera instanceof M.PerspectiveCamera||this.camera instanceof M.OrthographicCamera)&&(this.camera.far=e)}lookAt(e){e instanceof kt?this.camera.lookAt(e.getThreeVector()):this.camera.lookAt(e.x,e.y,e.z)}updateProjectionMatrix(){(this.camera instanceof M.PerspectiveCamera||this.camera instanceof M.OrthographicCamera)&&this.camera.updateProjectionMatrix()}getWorldDirection(e){const t=new M.Vector3;this.camera.getWorldDirection(t),e.set(t.x,t.y,t.z)}getInternalRenderer(){return this.camera}getThreeCamera(){return this.camera}}class $n extends Xn{constructor(e){const t=e||new M.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,r=.1,n=1e3){return new $n(new M.PerspectiveCamera(e,t,r,n))}}function zo(){const s="0123456789abcdef";return Array.from("xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx",t=>t==="x"?s[Math.floor(Math.random()*16)]:t==="y"?(Math.floor(Math.random()*16)&3|8).toString(16):t).join("")}class Eo{constructor(e){this.renderer=null,this._id=zo(),this.canvas=e}get id(){return this._id}initialize(e){console.log("[ThreeRendererAdapter] initialize() called");try{if(this.renderer=new M.WebGLRenderer({canvas:this.canvas,antialias:e.antialias??!0,alpha:e.alpha??!1,premultipliedAlpha:e.premultipliedAlpha??!0,preserveDrawingBuffer:e.preserveDrawingBuffer??!1,powerPreference:e.powerPreference??"default"}),console.log("[ThreeRendererAdapter] WebGLRenderer created successfully"),e.shadowMap&&(this.renderer.shadowMap.enabled=e.shadowMap.enabled,this.renderer.shadowMap.autoUpdate=!0,e.shadowMap.type)){const t={basic:M.BasicShadowMap,pcf:M.PCFShadowMap,pcfsoft:M.PCFSoftShadowMap,vsm:M.VSMShadowMap};this.renderer.shadowMap.type=t[e.shadowMap.type]}if(e.toneMapping){const t={none:M.NoToneMapping,linear:M.LinearToneMapping,reinhard:M.ReinhardToneMapping,cineon:M.CineonToneMapping,aces:M.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:r}=this.canvas.parentElement||this.canvas;t&&r&&this.renderer.setSize(t,r)}return this.renderer.outputColorSpace=M.SRGBColorSpace,K.ok(void 0)}catch(t){return K.err(new oe("Failed to initialize renderer",ue.RENDERER_INIT_FAILED,{originalError:t,options:e}))}}render(e,t){if(!this.renderer)return K.err(new oe("Renderer not initialized",ue.RENDERER_NOT_INITIALIZED));try{if(!(e instanceof Yt))return K.err(new oe("Scene must be a ThreeSceneAdapter",ue.INVALID_PARAMETER));if(!(t instanceof Xn))return K.err(new oe("Camera must be a ThreeCameraAdapter",ue.INVALID_PARAMETER));const r=e.getThreeScene(),n=t.getThreeCamera();return this.renderer.__pathTracingActive?(console.log("[ThreeRenderer] Skipping standard render - path tracing is active"),K.ok(void 0)):(this.renderer.render(r,n),K.ok(void 0))}catch(r){return K.err(new oe("Failed to render frame",ue.RENDER_FAILED,{originalError:r}))}}setSize(e,t){if(this.renderer){this.renderer.setSize(e,t,!1);const r=this.renderer.domElement;r.style.width="100%",r.style.height="100%"}}setPixelRatio(e){this.renderer&&this.renderer.setPixelRatio(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)}getInternalRenderer(){return console.log("[ThreeRendererAdapter] getInternalRenderer called, renderer exists:",!!this.renderer),this.renderer}getThreeRenderer(){return this.getInternalRenderer()}}function Xi(s,e){if(e===f.TrianglesDrawMode)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),s;if(e===f.TriangleFanDrawMode||e===f.TriangleStripDrawMode){let t=s.getIndex();if(t===null){const i=[],a=s.getAttribute("position");if(a!==void 0){for(let c=0;c<a.count;c++)i.push(c);s.setIndex(i),t=s.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),s}const r=t.count-2,n=[];if(e===f.TriangleFanDrawMode)for(let i=1;i<=r;i++)n.push(t.getX(0)),n.push(t.getX(i)),n.push(t.getX(i+1));else for(let i=0;i<r;i++)i%2===0?(n.push(t.getX(i)),n.push(t.getX(i+1)),n.push(t.getX(i+2))):(n.push(t.getX(i+2)),n.push(t.getX(i+1)),n.push(t.getX(i)));n.length/3!==r&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const o=s.clone();return o.setIndex(n),o.clearGroups(),o}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),s}class Uo extends f.Loader{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new Yo(t)}),this.register(function(t){return new qo(t)}),this.register(function(t){return new ta(t)}),this.register(function(t){return new ra(t)}),this.register(function(t){return new na(t)}),this.register(function(t){return new Ko(t)}),this.register(function(t){return new Xo(t)}),this.register(function(t){return new $o(t)}),this.register(function(t){return new Qo(t)}),this.register(function(t){return new Wo(t)}),this.register(function(t){return new Jo(t)}),this.register(function(t){return new Zo(t)}),this.register(function(t){return new ea(t)}),this.register(function(t){return new Ho(t)}),this.register(function(t){return new Vo(t)}),this.register(function(t){return new ia(t)}),this.register(function(t){return new sa(t)})}load(e,t,r,n){const o=this;let i;if(this.resourcePath!=="")i=this.resourcePath;else if(this.path!==""){const h=f.LoaderUtils.extractUrlBase(e);i=f.LoaderUtils.resolveURL(h,this.path)}else i=f.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const a=function(h){n?n(h):console.error(h),o.manager.itemError(e),o.manager.itemEnd(e)},c=new f.FileLoader(this.manager);c.setPath(this.path),c.setResponseType("arraybuffer"),c.setRequestHeader(this.requestHeader),c.setWithCredentials(this.withCredentials),c.load(e,function(h){try{o.parse(h,i,function(d){t(d),o.manager.itemEnd(e)},a)}catch(d){a(d)}},r,a)}setDRACOLoader(e){return this.dracoLoader=e,this}setDDSLoader(){throw new Error('THREE.GLTFLoader: "MSFT_texture_dds" no longer supported. Please update to "KHR_texture_basisu".')}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,r,n){let o;const i={},a={},c=new TextDecoder;if(typeof e=="string")o=JSON.parse(e);else if(e instanceof ArrayBuffer)if(c.decode(new Uint8Array(e,0,4))===$i){try{i[fe.KHR_BINARY_GLTF]=new oa(e)}catch(u){n&&n(u);return}o=JSON.parse(i[fe.KHR_BINARY_GLTF].content)}else o=JSON.parse(c.decode(e));else o=e;if(o.asset===void 0||o.asset.version[0]<2){n&&n(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const h=new xa(o,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});h.fileLoader.setRequestHeader(this.requestHeader);for(let d=0;d<this.pluginCallbacks.length;d++){const u=this.pluginCallbacks[d](h);u.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),a[u.name]=u,i[u.name]=!0}if(o.extensionsUsed)for(let d=0;d<o.extensionsUsed.length;++d){const u=o.extensionsUsed[d],l=o.extensionsRequired||[];switch(u){case fe.KHR_MATERIALS_UNLIT:i[u]=new jo;break;case fe.KHR_DRACO_MESH_COMPRESSION:i[u]=new aa(o,this.dracoLoader);break;case fe.KHR_TEXTURE_TRANSFORM:i[u]=new ca;break;case fe.KHR_MESH_QUANTIZATION:i[u]=new la;break;default:l.indexOf(u)>=0&&a[u]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+u+'".')}}h.setExtensions(i),h.setPlugins(a),h.parse(r,n)}parseAsync(e,t){const r=this;return new Promise(function(n,o){r.parse(e,t,n,o)})}}function Go(){let s={};return{get:function(e){return s[e]},add:function(e,t){s[e]=t},remove:function(e){delete s[e]},removeAll:function(){s={}}}}const fe={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",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class Vo{constructor(e){this.parser=e,this.name=fe.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let r=0,n=t.length;r<n;r++){const o=t[r];o.extensions&&o.extensions[this.name]&&o.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,o.extensions[this.name].light)}}_loadLight(e){const t=this.parser,r="light:"+e;let n=t.cache.get(r);if(n)return n;const o=t.json,c=((o.extensions&&o.extensions[this.name]||{}).lights||[])[e];let h;const d=new f.Color(16777215);c.color!==void 0&&d.setRGB(c.color[0],c.color[1],c.color[2],f.LinearSRGBColorSpace);const u=c.range!==void 0?c.range:0;switch(c.type){case"directional":h=new f.DirectionalLight(d),h.target.position.set(0,0,-1),h.add(h.target);break;case"point":h=new f.PointLight(d),h.distance=u;break;case"spot":h=new f.SpotLight(d),h.distance=u,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,h.angle=c.spot.outerConeAngle,h.penumbra=1-c.spot.innerConeAngle/c.spot.outerConeAngle,h.target.position.set(0,0,-1),h.add(h.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+c.type)}return h.position.set(0,0,0),h.decay=2,Mt(h,c),c.intensity!==void 0&&(h.intensity=c.intensity),h.name=t.createUniqueName(c.name||"light_"+e),n=Promise.resolve(h),t.cache.add(r,n),n}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,r=this.parser,o=r.json.nodes[e],a=(o.extensions&&o.extensions[this.name]||{}).light;return a===void 0?null:this._loadLight(a).then(function(c){return r._getNodeRef(t.cache,a,c)})}}class jo{constructor(){this.name=fe.KHR_MATERIALS_UNLIT}getMaterialType(){return f.MeshBasicMaterial}extendParams(e,t,r){const n=[];e.color=new f.Color(1,1,1),e.opacity=1;const o=t.pbrMetallicRoughness;if(o){if(Array.isArray(o.baseColorFactor)){const i=o.baseColorFactor;e.color.setRGB(i[0],i[1],i[2],f.LinearSRGBColorSpace),e.opacity=i[3]}o.baseColorTexture!==void 0&&n.push(r.assignTexture(e,"map",o.baseColorTexture,f.SRGBColorSpace))}return Promise.all(n)}}class Wo{constructor(e){this.parser=e,this.name=fe.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const o=n.extensions[this.name].emissiveStrength;return o!==void 0&&(t.emissiveIntensity=o),Promise.resolve()}}class Yo{constructor(e){this.parser=e,this.name=fe.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(e,t){const r=this.parser,n=r.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const o=[],i=n.extensions[this.name];if(i.clearcoatFactor!==void 0&&(t.clearcoat=i.clearcoatFactor),i.clearcoatTexture!==void 0&&o.push(r.assignTexture(t,"clearcoatMap",i.clearcoatTexture)),i.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=i.clearcoatRoughnessFactor),i.clearcoatRoughnessTexture!==void 0&&o.push(r.assignTexture(t,"clearcoatRoughnessMap",i.clearcoatRoughnessTexture)),i.clearcoatNormalTexture!==void 0&&(o.push(r.assignTexture(t,"clearcoatNormalMap",i.clearcoatNormalTexture)),i.clearcoatNormalTexture.scale!==void 0)){const a=i.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new f.Vector2(a,a)}return Promise.all(o)}}class qo{constructor(e){this.parser=e,this.name=fe.KHR_MATERIALS_DISPERSION}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const o=n.extensions[this.name];return t.dispersion=o.dispersion!==void 0?o.dispersion:0,Promise.resolve()}}class Zo{constructor(e){this.parser=e,this.name=fe.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(e,t){const r=this.parser,n=r.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const o=[],i=n.extensions[this.name];return i.iridescenceFactor!==void 0&&(t.iridescence=i.iridescenceFactor),i.iridescenceTexture!==void 0&&o.push(r.assignTexture(t,"iridescenceMap",i.iridescenceTexture)),i.iridescenceIor!==void 0&&(t.iridescenceIOR=i.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),i.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=i.iridescenceThicknessMinimum),i.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=i.iridescenceThicknessMaximum),i.iridescenceThicknessTexture!==void 0&&o.push(r.assignTexture(t,"iridescenceThicknessMap",i.iridescenceThicknessTexture)),Promise.all(o)}}class Ko{constructor(e){this.parser=e,this.name=fe.KHR_MATERIALS_SHEEN}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(e,t){const r=this.parser,n=r.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const o=[];t.sheenColor=new f.Color(0,0,0),t.sheenRoughness=0,t.sheen=1;const i=n.extensions[this.name];if(i.sheenColorFactor!==void 0){const a=i.sheenColorFactor;t.sheenColor.setRGB(a[0],a[1],a[2],f.LinearSRGBColorSpace)}return i.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=i.sheenRoughnessFactor),i.sheenColorTexture!==void 0&&o.push(r.assignTexture(t,"sheenColorMap",i.sheenColorTexture,f.SRGBColorSpace)),i.sheenRoughnessTexture!==void 0&&o.push(r.assignTexture(t,"sheenRoughnessMap",i.sheenRoughnessTexture)),Promise.all(o)}}class Xo{constructor(e){this.parser=e,this.name=fe.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(e,t){const r=this.parser,n=r.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const o=[],i=n.extensions[this.name];return i.transmissionFactor!==void 0&&(t.transmission=i.transmissionFactor),i.transmissionTexture!==void 0&&o.push(r.assignTexture(t,"transmissionMap",i.transmissionTexture)),Promise.all(o)}}class $o{constructor(e){this.parser=e,this.name=fe.KHR_MATERIALS_VOLUME}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(e,t){const r=this.parser,n=r.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const o=[],i=n.extensions[this.name];t.thickness=i.thicknessFactor!==void 0?i.thicknessFactor:0,i.thicknessTexture!==void 0&&o.push(r.assignTexture(t,"thicknessMap",i.thicknessTexture)),t.attenuationDistance=i.attenuationDistance||1/0;const a=i.attenuationColor||[1,1,1];return t.attenuationColor=new f.Color().setRGB(a[0],a[1],a[2],f.LinearSRGBColorSpace),Promise.all(o)}}class Qo{constructor(e){this.parser=e,this.name=fe.KHR_MATERIALS_IOR}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const o=n.extensions[this.name];return t.ior=o.ior!==void 0?o.ior:1.5,Promise.resolve()}}class Jo{constructor(e){this.parser=e,this.name=fe.KHR_MATERIALS_SPECULAR}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(e,t){const r=this.parser,n=r.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const o=[],i=n.extensions[this.name];t.specularIntensity=i.specularFactor!==void 0?i.specularFactor:1,i.specularTexture!==void 0&&o.push(r.assignTexture(t,"specularIntensityMap",i.specularTexture));const a=i.specularColorFactor||[1,1,1];return t.specularColor=new f.Color().setRGB(a[0],a[1],a[2],f.LinearSRGBColorSpace),i.specularColorTexture!==void 0&&o.push(r.assignTexture(t,"specularColorMap",i.specularColorTexture,f.SRGBColorSpace)),Promise.all(o)}}class Ho{constructor(e){this.parser=e,this.name=fe.EXT_MATERIALS_BUMP}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(e,t){const r=this.parser,n=r.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const o=[],i=n.extensions[this.name];return t.bumpScale=i.bumpFactor!==void 0?i.bumpFactor:1,i.bumpTexture!==void 0&&o.push(r.assignTexture(t,"bumpMap",i.bumpTexture)),Promise.all(o)}}class ea{constructor(e){this.parser=e,this.name=fe.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(e,t){const r=this.parser,n=r.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const o=[],i=n.extensions[this.name];return i.anisotropyStrength!==void 0&&(t.anisotropy=i.anisotropyStrength),i.anisotropyRotation!==void 0&&(t.anisotropyRotation=i.anisotropyRotation),i.anisotropyTexture!==void 0&&o.push(r.assignTexture(t,"anisotropyMap",i.anisotropyTexture)),Promise.all(o)}}class ta{constructor(e){this.parser=e,this.name=fe.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,r=t.json,n=r.textures[e];if(!n.extensions||!n.extensions[this.name])return null;const o=n.extensions[this.name],i=t.options.ktx2Loader;if(!i){if(r.extensionsRequired&&r.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,o.source,i)}}class ra{constructor(e){this.parser=e,this.name=fe.EXT_TEXTURE_WEBP,this.isSupported=null}loadTexture(e){const t=this.name,r=this.parser,n=r.json,o=n.textures[e];if(!o.extensions||!o.extensions[t])return null;const i=o.extensions[t],a=n.images[i.source];let c=r.textureLoader;if(a.uri){const h=r.options.manager.getHandler(a.uri);h!==null&&(c=h)}return this.detectSupport().then(function(h){if(h)return r.loadTextureImage(e,i.source,c);if(n.extensionsRequired&&n.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported.");return r.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const t=new Image;t.src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}}class na{constructor(e){this.parser=e,this.name=fe.EXT_TEXTURE_AVIF,this.isSupported=null}loadTexture(e){const t=this.name,r=this.parser,n=r.json,o=n.textures[e];if(!o.extensions||!o.extensions[t])return null;const i=o.extensions[t],a=n.images[i.source];let c=r.textureLoader;if(a.uri){const h=r.options.manager.getHandler(a.uri);h!==null&&(c=h)}return this.detectSupport().then(function(h){if(h)return r.loadTextureImage(e,i.source,c);if(n.extensionsRequired&&n.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported.");return r.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const t=new Image;t.src="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI=",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}}class ia{constructor(e){this.name=fe.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,r=t.bufferViews[e];if(r.extensions&&r.extensions[this.name]){const n=r.extensions[this.name],o=this.parser.getDependency("buffer",n.buffer),i=this.parser.options.meshoptDecoder;if(!i||!i.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return o.then(function(a){const c=n.byteOffset||0,h=n.byteLength||0,d=n.count,u=n.byteStride,l=new Uint8Array(a,c,h);return i.decodeGltfBufferAsync?i.decodeGltfBufferAsync(d,u,l,n.mode,n.filter).then(function(v){return v.buffer}):i.ready.then(function(){const v=new ArrayBuffer(d*u);return i.decodeGltfBuffer(new Uint8Array(v),d,u,l,n.mode,n.filter),v})})}else return null}}class sa{constructor(e){this.name=fe.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,r=t.nodes[e];if(!r.extensions||!r.extensions[this.name]||r.mesh===void 0)return null;const n=t.meshes[r.mesh];for(const h of n.primitives)if(h.mode!==st.TRIANGLES&&h.mode!==st.TRIANGLE_STRIP&&h.mode!==st.TRIANGLE_FAN&&h.mode!==void 0)return null;const i=r.extensions[this.name].attributes,a=[],c={};for(const h in i)a.push(this.parser.getDependency("accessor",i[h]).then(d=>(c[h]=d,c[h])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(h=>{const d=h.pop(),u=d.isGroup?d.children:[d],l=h[0].count,v=[];for(const x of u){const S=new f.Matrix4,g=new f.Vector3,b=new f.Quaternion,w=new f.Vector3(1,1,1),T=new f.InstancedMesh(x.geometry,x.material,l);for(let A=0;A<l;A++)c.TRANSLATION&&g.fromBufferAttribute(c.TRANSLATION,A),c.ROTATION&&b.fromBufferAttribute(c.ROTATION,A),c.SCALE&&w.fromBufferAttribute(c.SCALE,A),T.setMatrixAt(A,S.compose(g,b,w));for(const A in c)if(A==="_COLOR_0"){const P=c[A];T.instanceColor=new f.InstancedBufferAttribute(P.array,P.itemSize,P.normalized)}else A!=="TRANSLATION"&&A!=="ROTATION"&&A!=="SCALE"&&x.geometry.setAttribute(A,c[A]);f.Object3D.prototype.copy.call(T,x),this.parser.assignFinalMaterial(T),v.push(T)}return d.isGroup?(d.clear(),d.add(...v),d):v[0]}))}}const $i="glTF",zr=12,Qi={JSON:1313821514,BIN:5130562};class oa{constructor(e){this.name=fe.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,zr),r=new TextDecoder;if(this.header={magic:r.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==$i)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const n=this.header.length-zr,o=new DataView(e,zr);let i=0;for(;i<n;){const a=o.getUint32(i,!0);i+=4;const c=o.getUint32(i,!0);if(i+=4,c===Qi.JSON){const h=new Uint8Array(e,zr+i,a);this.content=r.decode(h)}else if(c===Qi.BIN){const h=zr+i;this.body=e.slice(h,h+a)}i+=a}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class aa{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=fe.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const r=this.json,n=this.dracoLoader,o=e.extensions[this.name].bufferView,i=e.extensions[this.name].attributes,a={},c={},h={};for(const d in i){const u=Jn[d]||d.toLowerCase();a[u]=i[d]}for(const d in e.attributes){const u=Jn[d]||d.toLowerCase();if(i[d]!==void 0){const l=r.accessors[e.attributes[d]],v=hr[l.componentType];h[u]=v.name,c[u]=l.normalized===!0}}return t.getDependency("bufferView",o).then(function(d){return new Promise(function(u,l){n.decodeDracoFile(d,function(v){for(const x in v.attributes){const S=v.attributes[x],g=c[x];g!==void 0&&(S.normalized=g)}u(v)},a,h,f.LinearSRGBColorSpace,l)})})}}class ca{constructor(){this.name=fe.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 la{constructor(){this.name=fe.KHR_MESH_QUANTIZATION}}class Ji extends f.Interpolant{constructor(e,t,r,n){super(e,t,r,n)}copySampleValue_(e){const t=this.resultBuffer,r=this.sampleValues,n=this.valueSize,o=e*n*3+n;for(let i=0;i!==n;i++)t[i]=r[o+i];return t}interpolate_(e,t,r,n){const o=this.resultBuffer,i=this.sampleValues,a=this.valueSize,c=a*2,h=a*3,d=n-t,u=(r-t)/d,l=u*u,v=l*u,x=e*h,S=x-h,g=-2*v+3*l,b=v-l,w=1-g,T=b-l+u;for(let A=0;A!==a;A++){const P=i[S+A+a],D=i[S+A+c]*d,R=i[x+A+a],O=i[x+A]*d;o[A]=w*P+T*D+g*R+b*O}return o}}const ua=new f.Quaternion;class ha extends Ji{interpolate_(e,t,r,n){const o=super.interpolate_(e,t,r,n);return ua.fromArray(o).normalize().toArray(o),o}}const st={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},hr={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},Hi={9728:f.NearestFilter,9729:f.LinearFilter,9984:f.NearestMipmapNearestFilter,9985:f.LinearMipmapNearestFilter,9986:f.NearestMipmapLinearFilter,9987:f.LinearMipmapLinearFilter},es={33071:f.ClampToEdgeWrapping,33648:f.MirroredRepeatWrapping,10497:f.RepeatWrapping},Qn={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Jn={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"},Bt={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},fa={CUBICSPLINE:void 0,LINEAR:f.InterpolateLinear,STEP:f.InterpolateDiscrete},Hn={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function da(s){return s.DefaultMaterial===void 0&&(s.DefaultMaterial=new f.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:f.FrontSide})),s.DefaultMaterial}function qt(s,e,t){for(const r in t.extensions)s[r]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[r]=t.extensions[r])}function Mt(s,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(s.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function pa(s,e,t){let r=!1,n=!1,o=!1;for(let h=0,d=e.length;h<d;h++){const u=e[h];if(u.POSITION!==void 0&&(r=!0),u.NORMAL!==void 0&&(n=!0),u.COLOR_0!==void 0&&(o=!0),r&&n&&o)break}if(!r&&!n&&!o)return Promise.resolve(s);const i=[],a=[],c=[];for(let h=0,d=e.length;h<d;h++){const u=e[h];if(r){const l=u.POSITION!==void 0?t.getDependency("accessor",u.POSITION):s.attributes.position;i.push(l)}if(n){const l=u.NORMAL!==void 0?t.getDependency("accessor",u.NORMAL):s.attributes.normal;a.push(l)}if(o){const l=u.COLOR_0!==void 0?t.getDependency("accessor",u.COLOR_0):s.attributes.color;c.push(l)}}return Promise.all([Promise.all(i),Promise.all(a),Promise.all(c)]).then(function(h){const d=h[0],u=h[1],l=h[2];return r&&(s.morphAttributes.position=d),n&&(s.morphAttributes.normal=u),o&&(s.morphAttributes.color=l),s.morphTargetsRelative=!0,s})}function ma(s,e){if(s.updateMorphTargets(),e.weights!==void 0)for(let t=0,r=e.weights.length;t<r;t++)s.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(s.morphTargetInfluences.length===t.length){s.morphTargetDictionary={};for(let r=0,n=t.length;r<n;r++)s.morphTargetDictionary[t[r]]=r}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function ga(s){let e;const t=s.extensions&&s.extensions[fe.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+ei(t.attributes):e=s.indices+":"+ei(s.attributes)+":"+s.mode,s.targets!==void 0)for(let r=0,n=s.targets.length;r<n;r++)e+=":"+ei(s.targets[r]);return e}function ei(s){let e="";const t=Object.keys(s).sort();for(let r=0,n=t.length;r<n;r++)e+=t[r]+":"+s[t[r]]+";";return e}function ti(s){switch(s){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 va(s){return s.search(/\.jpe?g($|\?)/i)>0||s.search(/^data\:image\/jpeg/)===0?"image/jpeg":s.search(/\.webp($|\?)/i)>0||s.search(/^data\:image\/webp/)===0?"image/webp":"image/png"}const ya=new f.Matrix4;class xa{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new Go,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 r=!1,n=-1,o=!1,i=-1;if(typeof navigator<"u"){const a=navigator.userAgent;r=/^((?!chrome|android).)*safari/i.test(a)===!0;const c=a.match(/Version\/(\d+)/);n=r&&c?parseInt(c[1],10):-1,o=a.indexOf("Firefox")>-1,i=o?a.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||r&&n<17||o&&i<98?this.textureLoader=new f.TextureLoader(this.options.manager):this.textureLoader=new f.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new f.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 r=this,n=this.json,o=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(i){return i._markDefs&&i._markDefs()}),Promise.all(this._invokeAll(function(i){return i.beforeRoot&&i.beforeRoot()})).then(function(){return Promise.all([r.getDependencies("scene"),r.getDependencies("animation"),r.getDependencies("camera")])}).then(function(i){const a={scene:i[0][n.scene||0],scenes:i[0],animations:i[1],cameras:i[2],asset:n.asset,parser:r,userData:{}};return qt(o,a,n),Mt(a,n),Promise.all(r._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||[],r=this.json.meshes||[];for(let n=0,o=t.length;n<o;n++){const i=t[n].joints;for(let a=0,c=i.length;a<c;a++)e[i[a]].isBone=!0}for(let n=0,o=e.length;n<o;n++){const i=e[n];i.mesh!==void 0&&(this._addNodeRef(this.meshCache,i.mesh),i.skin!==void 0&&(r[i.mesh].isSkinnedMesh=!0)),i.camera!==void 0&&this._addNodeRef(this.cameraCache,i.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,r){if(e.refs[t]<=1)return r;const n=r.clone(),o=(i,a)=>{const c=this.associations.get(i);c!=null&&this.associations.set(a,c);for(const[h,d]of i.children.entries())o(d,a.children[h])};return o(r,n),n.name+="_instance_"+e.uses[t]++,n}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let r=0;r<t.length;r++){const n=e(t[r]);if(n)return n}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const r=[];for(let n=0;n<t.length;n++){const o=e(t[n]);o&&r.push(o)}return r}getDependency(e,t){const r=e+":"+t;let n=this.cache.get(r);if(!n){switch(e){case"scene":n=this.loadScene(t);break;case"node":n=this._invokeOne(function(o){return o.loadNode&&o.loadNode(t)});break;case"mesh":n=this._invokeOne(function(o){return o.loadMesh&&o.loadMesh(t)});break;case"accessor":n=this.loadAccessor(t);break;case"bufferView":n=this._invokeOne(function(o){return o.loadBufferView&&o.loadBufferView(t)});break;case"buffer":n=this.loadBuffer(t);break;case"material":n=this._invokeOne(function(o){return o.loadMaterial&&o.loadMaterial(t)});break;case"texture":n=this._invokeOne(function(o){return o.loadTexture&&o.loadTexture(t)});break;case"skin":n=this.loadSkin(t);break;case"animation":n=this._invokeOne(function(o){return o.loadAnimation&&o.loadAnimation(t)});break;case"camera":n=this.loadCamera(t);break;default:if(n=this._invokeOne(function(o){return o!=this&&o.getDependency&&o.getDependency(e,t)}),!n)throw new Error("Unknown type: "+e);break}this.cache.add(r,n)}return n}getDependencies(e){let t=this.cache.get(e);if(!t){const r=this,n=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(n.map(function(o,i){return r.getDependency(e,i)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],r=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[fe.KHR_BINARY_GLTF].body);const n=this.options;return new Promise(function(o,i){r.load(f.LoaderUtils.resolveURL(t.uri,n.path),o,void 0,function(){i(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(r){const n=t.byteLength||0,o=t.byteOffset||0;return r.slice(o,o+n)})}loadAccessor(e){const t=this,r=this.json,n=this.json.accessors[e];if(n.bufferView===void 0&&n.sparse===void 0){const i=Qn[n.type],a=hr[n.componentType],c=n.normalized===!0,h=new a(n.count*i);return Promise.resolve(new f.BufferAttribute(h,i,c))}const o=[];return n.bufferView!==void 0?o.push(this.getDependency("bufferView",n.bufferView)):o.push(null),n.sparse!==void 0&&(o.push(this.getDependency("bufferView",n.sparse.indices.bufferView)),o.push(this.getDependency("bufferView",n.sparse.values.bufferView))),Promise.all(o).then(function(i){const a=i[0],c=Qn[n.type],h=hr[n.componentType],d=h.BYTES_PER_ELEMENT,u=d*c,l=n.byteOffset||0,v=n.bufferView!==void 0?r.bufferViews[n.bufferView].byteStride:void 0,x=n.normalized===!0;let S,g;if(v&&v!==u){const b=Math.floor(l/v),w="InterleavedBuffer:"+n.bufferView+":"+n.componentType+":"+b+":"+n.count;let T=t.cache.get(w);T||(S=new h(a,b*v,n.count*v/d),T=new f.InterleavedBuffer(S,v/d),t.cache.add(w,T)),g=new f.InterleavedBufferAttribute(T,c,l%v/d,x)}else a===null?S=new h(n.count*c):S=new h(a,l,n.count*c),g=new f.BufferAttribute(S,c,x);if(n.sparse!==void 0){const b=Qn.SCALAR,w=hr[n.sparse.indices.componentType],T=n.sparse.indices.byteOffset||0,A=n.sparse.values.byteOffset||0,P=new w(i[1],T,n.sparse.count*b),D=new h(i[2],A,n.sparse.count*c);a!==null&&(g=new f.BufferAttribute(g.array.slice(),g.itemSize,g.normalized));for(let R=0,O=P.length;R<O;R++){const L=P[R];if(g.setX(L,D[R*c]),c>=2&&g.setY(L,D[R*c+1]),c>=3&&g.setZ(L,D[R*c+2]),c>=4&&g.setW(L,D[R*c+3]),c>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}}return g})}loadTexture(e){const t=this.json,r=this.options,o=t.textures[e].source,i=t.images[o];let a=this.textureLoader;if(i.uri){const c=r.manager.getHandler(i.uri);c!==null&&(a=c)}return this.loadTextureImage(e,o,a)}loadTextureImage(e,t,r){const n=this,o=this.json,i=o.textures[e],a=o.images[t],c=(a.uri||a.bufferView)+":"+i.sampler;if(this.textureCache[c])return this.textureCache[c];const h=this.loadImageSource(t,r).then(function(d){d.flipY=!1,d.name=i.name||a.name||"",d.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(d.name=a.uri);const l=(o.samplers||{})[i.sampler]||{};return d.magFilter=Hi[l.magFilter]||f.LinearFilter,d.minFilter=Hi[l.minFilter]||f.LinearMipmapLinearFilter,d.wrapS=es[l.wrapS]||f.RepeatWrapping,d.wrapT=es[l.wrapT]||f.RepeatWrapping,n.associations.set(d,{textures:e}),d}).catch(function(){return null});return this.textureCache[c]=h,h}loadImageSource(e,t){const r=this,n=this.json,o=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(u=>u.clone());const i=n.images[e],a=self.URL||self.webkitURL;let c=i.uri||"",h=!1;if(i.bufferView!==void 0)c=r.getDependency("bufferView",i.bufferView).then(function(u){h=!0;const l=new Blob([u],{type:i.mimeType});return c=a.createObjectURL(l),c});else if(i.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const d=Promise.resolve(c).then(function(u){return new Promise(function(l,v){let x=l;t.isImageBitmapLoader===!0&&(x=function(S){const g=new f.Texture(S);g.needsUpdate=!0,l(g)}),t.load(f.LoaderUtils.resolveURL(u,o.path),x,void 0,v)})}).then(function(u){return h===!0&&a.revokeObjectURL(c),Mt(u,i),u.userData.mimeType=i.mimeType||va(i.uri),u}).catch(function(u){throw console.error("THREE.GLTFLoader: Couldn't load texture",c),u});return this.sourceCache[e]=d,d}assignTexture(e,t,r,n){const o=this;return this.getDependency("texture",r.index).then(function(i){if(!i)return null;if(r.texCoord!==void 0&&r.texCoord>0&&(i=i.clone(),i.channel=r.texCoord),o.extensions[fe.KHR_TEXTURE_TRANSFORM]){const a=r.extensions!==void 0?r.extensions[fe.KHR_TEXTURE_TRANSFORM]:void 0;if(a){const c=o.associations.get(i);i=o.extensions[fe.KHR_TEXTURE_TRANSFORM].extendTexture(i,a),o.associations.set(i,c)}}return n!==void 0&&(i.colorSpace=n),e[t]=i,i})}assignFinalMaterial(e){const t=e.geometry;let r=e.material;const n=t.attributes.tangent===void 0,o=t.attributes.color!==void 0,i=t.attributes.normal===void 0;if(e.isPoints){const a="PointsMaterial:"+r.uuid;let c=this.cache.get(a);c||(c=new f.PointsMaterial,f.Material.prototype.copy.call(c,r),c.color.copy(r.color),c.map=r.map,c.sizeAttenuation=!1,this.cache.add(a,c)),r=c}else if(e.isLine){const a="LineBasicMaterial:"+r.uuid;let c=this.cache.get(a);c||(c=new f.LineBasicMaterial,f.Material.prototype.copy.call(c,r),c.color.copy(r.color),c.map=r.map,this.cache.add(a,c)),r=c}if(n||o||i){let a="ClonedMaterial:"+r.uuid+":";n&&(a+="derivative-tangents:"),o&&(a+="vertex-colors:"),i&&(a+="flat-shading:");let c=this.cache.get(a);c||(c=r.clone(),o&&(c.vertexColors=!0),i&&(c.flatShading=!0),n&&(c.normalScale&&(c.normalScale.y*=-1),c.clearcoatNormalScale&&(c.clearcoatNormalScale.y*=-1)),this.cache.add(a,c),this.associations.set(c,this.associations.get(r))),r=c}e.material=r}getMaterialType(){return f.MeshStandardMaterial}loadMaterial(e){const t=this,r=this.json,n=this.extensions,o=r.materials[e];let i;const a={},c=o.extensions||{},h=[];if(c[fe.KHR_MATERIALS_UNLIT]){const u=n[fe.KHR_MATERIALS_UNLIT];i=u.getMaterialType(),h.push(u.extendParams(a,o,t))}else{const u=o.pbrMetallicRoughness||{};if(a.color=new f.Color(1,1,1),a.opacity=1,Array.isArray(u.baseColorFactor)){const l=u.baseColorFactor;a.color.setRGB(l[0],l[1],l[2],f.LinearSRGBColorSpace),a.opacity=l[3]}u.baseColorTexture!==void 0&&h.push(t.assignTexture(a,"map",u.baseColorTexture,f.SRGBColorSpace)),a.metalness=u.metallicFactor!==void 0?u.metallicFactor:1,a.roughness=u.roughnessFactor!==void 0?u.roughnessFactor:1,u.metallicRoughnessTexture!==void 0&&(h.push(t.assignTexture(a,"metalnessMap",u.metallicRoughnessTexture)),h.push(t.assignTexture(a,"roughnessMap",u.metallicRoughnessTexture))),i=this._invokeOne(function(l){return l.getMaterialType&&l.getMaterialType(e)}),h.push(Promise.all(this._invokeAll(function(l){return l.extendMaterialParams&&l.extendMaterialParams(e,a)})))}o.doubleSided===!0&&(a.side=f.DoubleSide);const d=o.alphaMode||Hn.OPAQUE;if(d===Hn.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,d===Hn.MASK&&(a.alphaTest=o.alphaCutoff!==void 0?o.alphaCutoff:.5)),o.normalTexture!==void 0&&i!==f.MeshBasicMaterial&&(h.push(t.assignTexture(a,"normalMap",o.normalTexture)),a.normalScale=new f.Vector2(1,1),o.normalTexture.scale!==void 0)){const u=o.normalTexture.scale;a.normalScale.set(u,u)}if(o.occlusionTexture!==void 0&&i!==f.MeshBasicMaterial&&(h.push(t.assignTexture(a,"aoMap",o.occlusionTexture)),o.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=o.occlusionTexture.strength)),o.emissiveFactor!==void 0&&i!==f.MeshBasicMaterial){const u=o.emissiveFactor;a.emissive=new f.Color().setRGB(u[0],u[1],u[2],f.LinearSRGBColorSpace)}return o.emissiveTexture!==void 0&&i!==f.MeshBasicMaterial&&h.push(t.assignTexture(a,"emissiveMap",o.emissiveTexture,f.SRGBColorSpace)),Promise.all(h).then(function(){const u=new i(a);return o.name&&(u.name=o.name),Mt(u,o),t.associations.set(u,{materials:e}),o.extensions&&qt(n,u,o),u})}createUniqueName(e){const t=f.PropertyBinding.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,r=this.extensions,n=this.primitiveCache;function o(a){return r[fe.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,t).then(function(c){return ts(c,a,t)})}const i=[];for(let a=0,c=e.length;a<c;a++){const h=e[a],d=ga(h),u=n[d];if(u)i.push(u.promise);else{let l;h.extensions&&h.extensions[fe.KHR_DRACO_MESH_COMPRESSION]?l=o(h):l=ts(new f.BufferGeometry,h,t),n[d]={primitive:h,promise:l},i.push(l)}}return Promise.all(i)}loadMesh(e){const t=this,r=this.json,n=this.extensions,o=r.meshes[e],i=o.primitives,a=[];for(let c=0,h=i.length;c<h;c++){const d=i[c].material===void 0?da(this.cache):this.getDependency("material",i[c].material);a.push(d)}return a.push(t.loadGeometries(i)),Promise.all(a).then(function(c){const h=c.slice(0,c.length-1),d=c[c.length-1],u=[];for(let v=0,x=d.length;v<x;v++){const S=d[v],g=i[v];let b;const w=h[v];if(g.mode===st.TRIANGLES||g.mode===st.TRIANGLE_STRIP||g.mode===st.TRIANGLE_FAN||g.mode===void 0)b=o.isSkinnedMesh===!0?new f.SkinnedMesh(S,w):new f.Mesh(S,w),b.isSkinnedMesh===!0&&b.normalizeSkinWeights(),g.mode===st.TRIANGLE_STRIP?b.geometry=Xi(b.geometry,f.TriangleStripDrawMode):g.mode===st.TRIANGLE_FAN&&(b.geometry=Xi(b.geometry,f.TriangleFanDrawMode));else if(g.mode===st.LINES)b=new f.LineSegments(S,w);else if(g.mode===st.LINE_STRIP)b=new f.Line(S,w);else if(g.mode===st.LINE_LOOP)b=new f.LineLoop(S,w);else if(g.mode===st.POINTS)b=new f.Points(S,w);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+g.mode);Object.keys(b.geometry.morphAttributes).length>0&&ma(b,o),b.name=t.createUniqueName(o.name||"mesh_"+e),Mt(b,o),g.extensions&&qt(n,b,g),t.assignFinalMaterial(b),u.push(b)}for(let v=0,x=u.length;v<x;v++)t.associations.set(u[v],{meshes:e,primitives:v});if(u.length===1)return o.extensions&&qt(n,u[0],o),u[0];const l=new f.Group;o.extensions&&qt(n,l,o),t.associations.set(l,{meshes:e});for(let v=0,x=u.length;v<x;v++)l.add(u[v]);return l})}loadCamera(e){let t;const r=this.json.cameras[e],n=r[r.type];if(!n){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return r.type==="perspective"?t=new f.PerspectiveCamera(f.MathUtils.radToDeg(n.yfov),n.aspectRatio||1,n.znear||1,n.zfar||2e6):r.type==="orthographic"&&(t=new f.OrthographicCamera(-n.xmag,n.xmag,n.ymag,-n.ymag,n.znear,n.zfar)),r.name&&(t.name=this.createUniqueName(r.name)),Mt(t,r),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],r=[];for(let n=0,o=t.joints.length;n<o;n++)r.push(this._loadNodeShallow(t.joints[n]));return t.inverseBindMatrices!==void 0?r.push(this.getDependency("accessor",t.inverseBindMatrices)):r.push(null),Promise.all(r).then(function(n){const o=n.pop(),i=n,a=[],c=[];for(let h=0,d=i.length;h<d;h++){const u=i[h];if(u){a.push(u);const l=new f.Matrix4;o!==null&&l.fromArray(o.array,h*16),c.push(l)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[h])}return new f.Skeleton(a,c)})}loadAnimation(e){const t=this.json,r=this,n=t.animations[e],o=n.name?n.name:"animation_"+e,i=[],a=[],c=[],h=[],d=[];for(let u=0,l=n.channels.length;u<l;u++){const v=n.channels[u],x=n.samplers[v.sampler],S=v.target,g=S.node,b=n.parameters!==void 0?n.parameters[x.input]:x.input,w=n.parameters!==void 0?n.parameters[x.output]:x.output;S.node!==void 0&&(i.push(this.getDependency("node",g)),a.push(this.getDependency("accessor",b)),c.push(this.getDependency("accessor",w)),h.push(x),d.push(S))}return Promise.all([Promise.all(i),Promise.all(a),Promise.all(c),Promise.all(h),Promise.all(d)]).then(function(u){const l=u[0],v=u[1],x=u[2],S=u[3],g=u[4],b=[];for(let w=0,T=l.length;w<T;w++){const A=l[w],P=v[w],D=x[w],R=S[w],O=g[w];if(A===void 0)continue;A.updateMatrix&&A.updateMatrix();const L=r._createAnimationTracks(A,P,D,R,O);if(L)for(let E=0;E<L.length;E++)b.push(L[E])}return new f.AnimationClip(o,void 0,b)})}createNodeMesh(e){const t=this.json,r=this,n=t.nodes[e];return n.mesh===void 0?null:r.getDependency("mesh",n.mesh).then(function(o){const i=r._getNodeRef(r.meshCache,n.mesh,o);return n.weights!==void 0&&i.traverse(function(a){if(a.isMesh)for(let c=0,h=n.weights.length;c<h;c++)a.morphTargetInfluences[c]=n.weights[c]}),i})}loadNode(e){const t=this.json,r=this,n=t.nodes[e],o=r._loadNodeShallow(e),i=[],a=n.children||[];for(let h=0,d=a.length;h<d;h++)i.push(r.getDependency("node",a[h]));const c=n.skin===void 0?Promise.resolve(null):r.getDependency("skin",n.skin);return Promise.all([o,Promise.all(i),c]).then(function(h){const d=h[0],u=h[1],l=h[2];l!==null&&d.traverse(function(v){v.isSkinnedMesh&&v.bind(l,ya)});for(let v=0,x=u.length;v<x;v++)d.add(u[v]);return d})}_loadNodeShallow(e){const t=this.json,r=this.extensions,n=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const o=t.nodes[e],i=o.name?n.createUniqueName(o.name):"",a=[],c=n._invokeOne(function(h){return h.createNodeMesh&&h.createNodeMesh(e)});return c&&a.push(c),o.camera!==void 0&&a.push(n.getDependency("camera",o.camera).then(function(h){return n._getNodeRef(n.cameraCache,o.camera,h)})),n._invokeAll(function(h){return h.createNodeAttachment&&h.createNodeAttachment(e)}).forEach(function(h){a.push(h)}),this.nodeCache[e]=Promise.all(a).then(function(h){let d;if(o.isBone===!0?d=new f.Bone:h.length>1?d=new f.Group:h.length===1?d=h[0]:d=new f.Object3D,d!==h[0])for(let u=0,l=h.length;u<l;u++)d.add(h[u]);if(o.name&&(d.userData.name=o.name,d.name=i),Mt(d,o),o.extensions&&qt(r,d,o),o.matrix!==void 0){const u=new f.Matrix4;u.fromArray(o.matrix),d.applyMatrix4(u)}else o.translation!==void 0&&d.position.fromArray(o.translation),o.rotation!==void 0&&d.quaternion.fromArray(o.rotation),o.scale!==void 0&&d.scale.fromArray(o.scale);return n.associations.has(d)||n.associations.set(d,{}),n.associations.get(d).nodes=e,d}),this.nodeCache[e]}loadScene(e){const t=this.extensions,r=this.json.scenes[e],n=this,o=new f.Group;r.name&&(o.name=n.createUniqueName(r.name)),Mt(o,r),r.extensions&&qt(t,o,r);const i=r.nodes||[],a=[];for(let c=0,h=i.length;c<h;c++)a.push(n.getDependency("node",i[c]));return Promise.all(a).then(function(c){for(let d=0,u=c.length;d<u;d++)o.add(c[d]);const h=d=>{const u=new Map;for(const[l,v]of n.associations)(l instanceof f.Material||l instanceof f.Texture)&&u.set(l,v);return d.traverse(l=>{const v=n.associations.get(l);v!=null&&u.set(l,v)}),u};return n.associations=h(o),o})}_createAnimationTracks(e,t,r,n,o){const i=[],a=e.name?e.name:e.uuid,c=[];Bt[o.path]===Bt.weights?e.traverse(function(l){l.morphTargetInfluences&&c.push(l.name?l.name:l.uuid)}):c.push(a);let h;switch(Bt[o.path]){case Bt.weights:h=f.NumberKeyframeTrack;break;case Bt.rotation:h=f.QuaternionKeyframeTrack;break;case Bt.position:case Bt.scale:h=f.VectorKeyframeTrack;break;default:switch(r.itemSize){case 1:h=f.NumberKeyframeTrack;break;case 2:case 3:default:h=f.VectorKeyframeTrack;break}break}const d=n.interpolation!==void 0?fa[n.interpolation]:f.InterpolateLinear,u=this._getArrayFromAccessor(r);for(let l=0,v=c.length;l<v;l++){const x=new h(c[l]+"."+Bt[o.path],t.array,u,d);n.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(x),i.push(x)}return i}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const r=ti(t.constructor),n=new Float32Array(t.length);for(let o=0,i=t.length;o<i;o++)n[o]=t[o]*r;t=n}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(r){const n=this instanceof f.QuaternionKeyframeTrack?ha:Ji;return new n(this.times,this.values,this.getValueSize()/3,r)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function ba(s,e,t){const r=e.attributes,n=new f.Box3;if(r.POSITION!==void 0){const a=t.json.accessors[r.POSITION],c=a.min,h=a.max;if(c!==void 0&&h!==void 0){if(n.set(new f.Vector3(c[0],c[1],c[2]),new f.Vector3(h[0],h[1],h[2])),a.normalized){const d=ti(hr[a.componentType]);n.min.multiplyScalar(d),n.max.multiplyScalar(d)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const o=e.targets;if(o!==void 0){const a=new f.Vector3,c=new f.Vector3;for(let h=0,d=o.length;h<d;h++){const u=o[h];if(u.POSITION!==void 0){const l=t.json.accessors[u.POSITION],v=l.min,x=l.max;if(v!==void 0&&x!==void 0){if(c.setX(Math.max(Math.abs(v[0]),Math.abs(x[0]))),c.setY(Math.max(Math.abs(v[1]),Math.abs(x[1]))),c.setZ(Math.max(Math.abs(v[2]),Math.abs(x[2]))),l.normalized){const S=ti(hr[l.componentType]);c.multiplyScalar(S)}a.max(c)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}n.expandByVector(a)}s.boundingBox=n;const i=new f.Sphere;n.getCenter(i.center),i.radius=n.min.distanceTo(n.max)/2,s.boundingSphere=i}function ts(s,e,t){const r=e.attributes,n=[];function o(i,a){return t.getDependency("accessor",i).then(function(c){s.setAttribute(a,c)})}for(const i in r){const a=Jn[i]||i.toLowerCase();a in s.attributes||n.push(o(r[i],a))}if(e.indices!==void 0&&!s.index){const i=t.getDependency("accessor",e.indices).then(function(a){s.setIndex(a)});n.push(i)}return f.ColorManagement.workingColorSpace!==f.LinearSRGBColorSpace&&"COLOR_0"in r&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${f.ColorManagement.workingColorSpace}" not supported.`),Mt(s,e),ba(s,e,t),Promise.all(n).then(function(){return e.targets!==void 0?pa(s,e.targets,t):s})}class wa{constructor(){this.loadingManager=new M.LoadingManager,this.loader=new Uo(this.loadingManager)}async load(e){try{return new Promise(t=>{this.loader.load(e,r=>{var o;const n={scene:new We(r.scene),animations:this.convertAnimations(r.animations),cameras:(o=r.cameras)==null?void 0:o.map(i=>{const a=i instanceof M.PerspectiveCamera,c=i instanceof M.OrthographicCamera;return{name:i.name,type:i.type,fov:a?i.fov:void 0,aspect:a?i.aspect:void 0,near:a||c?i.near:.1,far:a||c?i.far:1e3}}),userData:r.userData};t(K.ok(n))},r=>{if(r.total>0){const n=r.loaded/r.total*100;console.log(`Loading: ${n.toFixed(0)}%`)}},r=>{t(K.err(new oe("Failed to load GLTF model",ue.MODEL_LOAD_FAILED,{url:e,originalError:r})))})})}catch(t){return K.err(new oe("Failed to initiate model loading",ue.MODEL_LOAD_FAILED,{url:e,originalError:t}))}}supports(e){var r;const t=(r=e.split(".").pop())==null?void 0:r.toLowerCase();return t==="gltf"||t==="glb"}convertAnimations(e){return e.map(t=>({name:t.name,duration:t.duration,tracks:t.tracks.map(r=>({name:r.name,type:this.getTrackType(r),times:r.times,values:r.values}))}))}getTrackType(e){return e instanceof M.VectorKeyframeTrack?"vector":e instanceof M.QuaternionKeyframeTrack?"quaternion":e instanceof M.NumberKeyframeTrack?"number":e instanceof M.BooleanKeyframeTrack?"boolean":"number"}}class rs{static createLoader(e){var r;const t=(r=e.split(".").pop())==null?void 0:r.toLowerCase();switch(t){case"gltf":case"glb":return new wa;default:throw new oe(`Unsupported file format: ${t}`,ue.UNSUPPORTED_FORMAT,{url:e,extension:t})}}}const ns={type:"change"},ri={type:"start"},is={type:"end"},mn=new f.Ray,ss=new f.Plane,_a=Math.cos(70*f.MathUtils.DEG2RAD),Le=new f.Vector3,Ke=2*Math.PI,be={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},ni=1e-6;class os extends f.Controls{constructor(e,t=null){super(e,t),this.state=be.NONE,this.enabled=!0,this.target=new f.Vector3,this.cursor=new f.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.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:f.MOUSE.ROTATE,MIDDLE:f.MOUSE.DOLLY,RIGHT:f.MOUSE.PAN},this.touches={ONE:f.TOUCH.ROTATE,TWO:f.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 f.Vector3,this._lastQuaternion=new f.Quaternion,this._lastTargetPosition=new f.Vector3,this._quat=new f.Quaternion().setFromUnitVectors(e.up,new f.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new f.Spherical,this._sphericalDelta=new f.Spherical,this._scale=1,this._panOffset=new f.Vector3,this._rotateStart=new f.Vector2,this._rotateEnd=new f.Vector2,this._rotateDelta=new f.Vector2,this._panStart=new f.Vector2,this._panEnd=new f.Vector2,this._panDelta=new f.Vector2,this._dollyStart=new f.Vector2,this._dollyEnd=new f.Vector2,this._dollyDelta=new f.Vector2,this._dollyDirection=new f.Vector3,this._mouse=new f.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=Ta.bind(this),this._onPointerDown=Sa.bind(this),this._onPointerUp=Aa.bind(this),this._onContextMenu=Fa.bind(this),this._onMouseWheel=Ca.bind(this),this._onKeyDown=Pa.bind(this),this._onTouchStart=Da.bind(this),this._onTouchMove=Ra.bind(this),this._onMouseDown=Ma.bind(this),this._onMouseMove=Ia.bind(this),this._interceptControlDown=Oa.bind(this),this._interceptControlUp=La.bind(this),this.domElement!==null&&this.connect(),this.update()}connect(){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(ns),this.update(),this.state=be.NONE}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===be.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 r=this.minAzimuthAngle,n=this.maxAzimuthAngle;isFinite(r)&&isFinite(n)&&(r<-Math.PI?r+=Ke:r>Math.PI&&(r-=Ke),n<-Math.PI?n+=Ke:n>Math.PI&&(n-=Ke),r<=n?this._spherical.theta=Math.max(r,Math.min(n,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(r+n)/2?Math.max(r,this._spherical.theta):Math.min(n,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let o=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const i=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),o=i!=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 i=null;if(this.object.isPerspectiveCamera){const a=Le.length();i=this._clampDistance(a*this._scale);const c=a-i;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),o=!!c}else if(this.object.isOrthographicCamera){const a=new f.Vector3(this._mouse.x,this._mouse.y,0);a.unproject(this.object);const c=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),o=c!==this.object.zoom;const h=new f.Vector3(this._mouse.x,this._mouse.y,0);h.unproject(this.object),this.object.position.sub(h).add(a),this.object.updateMatrixWorld(),i=Le.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;i!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(i).add(this.object.position):(mn.origin.copy(this.object.position),mn.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(mn.direction))<_a?this.object.lookAt(this.target):(ss.setFromNormalAndCoplanarPoint(this.object.up,this.target),mn.intersectPlane(ss,this.target))))}else if(this.object.isOrthographicCamera){const i=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),i!==this.object.zoom&&(this.object.updateProjectionMatrix(),o=!0)}return this._scale=1,this._performCursorZoom=!1,o||this._lastPosition.distanceToSquared(this.object.position)>ni||8*(1-this._lastQuaternion.dot(this.object.quaternion))>ni||this._lastTargetPosition.distanceToSquared(this.target)>ni?(this.dispatchEvent(ns),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?Ke/60*this.autoRotateSpeed*e:Ke/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 r=this.domElement;if(this.object.isPerspectiveCamera){const n=this.object.position;Le.copy(n).sub(this.target);let o=Le.length();o*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*o/r.clientHeight,this.object.matrix),this._panUp(2*t*o/r.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/r.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/r.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 r=this.domElement.getBoundingClientRect(),n=e-r.left,o=t-r.top,i=r.width,a=r.height;this._mouse.x=n/i*2-1,this._mouse.y=-(o/a)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Ke*this._rotateDelta.x/t.clientHeight),this._rotateUp(Ke*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._rotateUp(Ke*this.rotateSpeed/this.domElement.clientHeight):this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this._rotateUp(-Ke*this.rotateSpeed/this.domElement.clientHeight):this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this._rotateLeft(Ke*this.rotateSpeed/this.domElement.clientHeight):this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this._rotateLeft(-Ke*this.rotateSpeed/this.domElement.clientHeight):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),r=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);this._rotateStart.set(r,n)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),r=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);this._panStart.set(r,n)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),r=e.pageX-t.x,n=e.pageY-t.y,o=Math.sqrt(r*r+n*n);this._dollyStart.set(0,o)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const r=this._getSecondPointerPosition(e),n=.5*(e.pageX+r.x),o=.5*(e.pageY+r.y);this._rotateEnd.set(n,o)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Ke*this._rotateDelta.x/t.clientHeight),this._rotateUp(Ke*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),r=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);this._panEnd.set(r,n)}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),r=e.pageX-t.x,n=e.pageY-t.y,o=Math.sqrt(r*r+n*n);this._dollyEnd.set(0,o),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const i=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(i,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 f.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,r={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:r.deltaY*=16;break;case 2:r.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(r.deltaY*=10),r}}function Sa(s){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(s.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(s)&&(this._addPointer(s),s.pointerType==="touch"?this._onTouchStart(s):this._onMouseDown(s)))}function Ta(s){this.enabled!==!1&&(s.pointerType==="touch"?this._onTouchMove(s):this._onMouseMove(s))}function Aa(s){switch(this._removePointer(s),this._pointers.length){case 0:this.domElement.releasePointerCapture(s.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(is),this.state=be.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 Ma(s){let e;switch(s.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 f.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(s),this.state=be.DOLLY;break;case f.MOUSE.ROTATE:if(s.ctrlKey||s.metaKey||s.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(s),this.state=be.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(s),this.state=be.ROTATE}break;case f.MOUSE.PAN:if(s.ctrlKey||s.metaKey||s.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(s),this.state=be.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(s),this.state=be.PAN}break;default:this.state=be.NONE}this.state!==be.NONE&&this.dispatchEvent(ri)}function Ia(s){switch(this.state){case be.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(s);break;case be.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(s);break;case be.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(s);break}}function Ca(s){this.enabled===!1||this.enableZoom===!1||this.state!==be.NONE||(s.preventDefault(),this.dispatchEvent(ri),this._handleMouseWheel(this._customWheelEvent(s)),this.dispatchEvent(is))}function Pa(s){this.enabled===!1||this.enablePan===!1||this._handleKeyDown(s)}function Da(s){switch(this._trackPointer(s),this._pointers.length){case 1:switch(this.touches.ONE){case f.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(s),this.state=be.TOUCH_ROTATE;break;case f.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(s),this.state=be.TOUCH_PAN;break;default:this.state=be.NONE}break;case 2:switch(this.touches.TWO){case f.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(s),this.state=be.TOUCH_DOLLY_PAN;break;case f.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(s),this.state=be.TOUCH_DOLLY_ROTATE;break;default:this.state=be.NONE}break;default:this.state=be.NONE}this.state!==be.NONE&&this.dispatchEvent(ri)}function Ra(s){switch(this._trackPointer(s),this.state){case be.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(s),this.update();break;case be.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(s),this.update();break;case be.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(s),this.update();break;case be.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(s),this.update();break;default:this.state=be.NONE}}function Fa(s){this.enabled!==!1&&s.preventDefault()}function Oa(s){s.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function La(s){s.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}class Na extends os{constructor(e,t){super(e,t),this.screenSpacePanning=!1,this.mouseButtons={LEFT:f.MOUSE.PAN,MIDDLE:f.MOUSE.DOLLY,RIGHT:f.MOUSE.ROTATE},this.touches={ONE:f.TOUCH.PAN,TWO:f.TOUCH.DOLLY_ROTATE}}}class as{constructor(e){this.controls=e,this.targetAdapter=kt.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()}getThreeControls(){return this.controls}}class cs extends as{constructor(e,t){const r=new os(e,t);super(r),this.orbitControls=r}get type(){return"orbit"}get autoRotate(){return this.orbitControls.autoRotate}set autoRotate(e){this.orbitControls.autoRotate=e}get autoRotateSpeed(){return this.orbitControls.autoRotateSpeed}set autoRotateSpeed(e){this.orbitControls.autoRotateSpeed=e}}class ls extends as{constructor(e,t){const r=new Na(e,t);super(r),r.screenSpacePanning=!0}get type(){return"map"}get screenSpacePanning(){return!0}set screenSpacePanning(e){}}const Qr=class Qr{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),r=this.getGapFactor();return{width:Math.sqrt(3)*t*r,height:2*t*r}}static getYPosition(e){return-(this.getHeight(e)+this.getBevelSize(e))}};Qr.HEIGHT_RATIO=.075,Qr.BEVEL_RATIO=.25,Qr.GAP_FACTOR=1.05;let Zt=Qr;var It=(s=>(s.SQUARE_WIRE="square_wire",s.HEXAGONAL_WIRE="hexagonal_wire",s.HEXAGONAL_GLASS="hexagonal_glass",s.STONE_TILES="stone_tiles",s.CUSTOM="custom",s))(It||{});class ka{constructor(){this.name="Square Wire Grid"}createGrid(e){const t=e.size||10,r=e.divisions||10,n=new M.Color(e.color||8947848),o=new M.Color(e.centerLineColor||e.color||4473924),i=new M.GridHelper(t,r,o,n);if(e.opacity!==void 0&&e.opacity<1){const a=i.material;a.transparent=!0,a.opacity=e.opacity}return i}dispose(){}}class Ba{constructor(){this.name="Hexagonal Wire Grid"}createGrid(e){var d;const t=new M.Group,r=((d=e.styleOptions)==null?void 0:d.hexRadius)||Math.floor(e.divisions/2),n=e.size/(r*2),o=new M.Color(e.color||8947848),i=e.opacity||.4,a=new M.LineBasicMaterial({color:o,transparent:!0,opacity:i}),c=n*Math.sqrt(3),h=n*2;for(let u=-r;u<=r;u++){const l=Math.max(-r,-u-r),v=Math.min(r,-u+r);for(let x=l;x<=v;x++){const S=c*(u+x/2),g=h*.75*x,b=[],w=Math.PI*2/6;for(let P=0;P<=6;P++){const D=P*w+Math.PI/6,R=S+n*Math.cos(D),O=g+n*Math.sin(D);b.push(new M.Vector3(R,0,O))}const T=new M.BufferGeometry().setFromPoints(b),A=new M.Line(T,a);t.add(A)}}return t}dispose(){}}class za{constructor(e,t,r){this.position=e,this.size=t,this.color=r,this.height=Zt.getHeight(this.size),this.bevel=Zt.getBevelSize(this.size)}createMesh(){const e=new M.Shape,t=this.size+this.bevel,r=Math.PI*2/6;for(let h=0;h<6;h++){const d=t*Math.cos(h*r),u=t*Math.sin(h*r);h===0?e.moveTo(d,u):e.lineTo(d,u)}e.closePath();const n={depth:this.height,bevelEnabled:!0,bevelSize:this.bevel,bevelThickness:this.bevel,bevelSegments:128},o=new M.ExtrudeGeometry(e,n),i=new M.MeshPhysicalMaterial({color:new M.Color(16777215),metalness:0,roughness:.15,transparent:!0,transmission:1,thickness:.4,ior:1.5,opacity:1,clearcoat:1,clearcoatRoughness:.05,sheen:1,sheenColor:new M.Color(16777215),envMapIntensity:1}),a=new M.Mesh(o,i);a.receiveShadow=!0;const c=new M.Group;return c.add(a),c.position.set(this.position.x,this.position.y,this.position.z),c.rotation.x=Math.PI/2,c.rotation.z=Math.PI/6,c}}class Ea{constructor(){this.name="Hexagonal Glass Grid"}createGrid(e){var h,d;const t=new M.Group,r=((h=e.styleOptions)==null?void 0:h.hexRadius)||Math.floor(e.divisions/2),n=((d=e.styleOptions)==null?void 0:d.tileSize)||1,o=String(e.color||"#ffffff"),i=Zt.getGridSpacing(n),a=i.width,c=i.height;for(let u=-r;u<=r;u++){const l=Math.max(-r,-u-r),v=Math.min(r,-u+r);for(let x=l;x<=v;x++){const S=a*(u+x/2),g=c*.75*x,b=Zt.getYPosition(n),T=new za(new M.Vector3(S,b,g),n,o).createMesh();t.add(T)}}return t}dispose(){}}class Ua{constructor(){this.name="Stone Tile Grid",this.textureLoader=new M.TextureLoader,this.loadedTextures=new Map}createGrid(e){var v,x,S,g;const t=new M.Group,r=e.size,n=e.divisions,o=r/n,i=o*.02,a=o-i,c=((v=e.styleOptions)==null?void 0:v.height)||o*.05,h=((x=e.styleOptions)==null?void 0:x.bevelSize)||c*.2,d=((S=e.styleOptions)==null?void 0:S.randomHeight)||!1,u=((g=e.styleOptions)==null?void 0:g.randomRotation)||!1,l=this.createStoneMaterial(e);for(let b=0;b<n;b++)for(let w=0;w<n;w++){const T=(b-n/2)*o+o/2,A=(w-n/2)*o+o/2,P=d?c*(.8+Math.random()*.4):c,D=new M.Shape,R=a/2;D.moveTo(-R,-R),D.lineTo(R,-R),D.lineTo(R,R),D.lineTo(-R,R),D.closePath();const O={depth:P,bevelEnabled:!0,bevelSize:h,bevelThickness:h,bevelSegments:2},L=new M.ExtrudeGeometry(D,O);L.rotateX(-Math.PI/2);const E=new M.Mesh(L,l);E.position.set(T,-P/2,A),E.castShadow=!0,E.receiveShadow=!0,u&&(E.rotation.y=Math.floor(Math.random()*4)*(Math.PI/2)),t.add(E)}return t}createStoneMaterial(e){var i,a,c,h,d;const t=new M.Color(e.color||8421504),r=((i=e.styleOptions)==null?void 0:i.metalness)||0,n=((a=e.styleOptions)==null?void 0:a.roughness)||.8,o={color:t,metalness:r,roughness:n};if((c=e.styleOptions)!=null&&c.texture){const u=this.loadTexture(e.styleOptions.texture);u&&(o.map=u,u.wrapS=u.wrapT=M.RepeatWrapping,u.repeat.set(1,1))}if((h=e.styleOptions)!=null&&h.normalMap){const u=this.loadTexture(e.styleOptions.normalMap);u&&(o.normalMap=u,u.wrapS=u.wrapT=M.RepeatWrapping,u.repeat.set(1,1))}if((d=e.styleOptions)!=null&&d.roughnessMap){const u=this.loadTexture(e.styleOptions.roughnessMap);u&&(o.roughnessMap=u,u.wrapS=u.wrapT=M.RepeatWrapping,u.repeat.set(1,1))}return new M.MeshStandardMaterial(o)}loadTexture(e){if(this.loadedTextures.has(e))return this.loadedTextures.get(e)||null;try{const t=this.textureLoader.load(e);return this.loadedTextures.set(e,t),t}catch(t){return console.warn("Failed to load texture:",e,t),null}}dispose(){this.loadedTextures.forEach(e=>{e.dispose()}),this.loadedTextures.clear()}}const ji=class ji{static createGrid(e,t){const r=this.gridStyles.get(e);if(!r){console.warn(`Unknown grid type: ${e}, falling back to square wire grid`);const o=this.gridStyles.get(It.SQUARE_WIRE);if(!o)throw new Error("Square wire grid style not found");return o.createGrid(t)}const n=r.createGrid(t);return n.name=`Grid_${e}`,n}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()}};ji.gridStyles=new Map([[It.SQUARE_WIRE,new ka],[It.HEXAGONAL_WIRE,new Ba],[It.HEXAGONAL_GLASS,new Ea],[It.STONE_TILES,new Ua]]);let gn=ji;class Ga{addHelpers(e,t){try{if(!(e instanceof Yt))return K.err(new oe("Scene must be ThreeSceneAdapter",ue.INVALID_PARAMETER));const r=e.getThreeScene();if(t.grid){const n=r.userData,o=typeof t.grid=="object"?t.grid:null,i={enabled:!0,color:(o==null?void 0:o.colorGrid)||t.gridColor||"#AAAAAA",type:o!=null&&o.type?o.type:It.HEXAGONAL_GLASS,opacity:o==null?void 0:o.opacity,styleOptions:o==null?void 0:o.styleOptions};if(r.userData={...n,gridOptions:i},o!=null&&o.size||o!=null&&o.divisions){const a=i.type||It.HEXAGONAL_GLASS,c=o.size||10,h=o.divisions||10,d={size:c,divisions:h,color:i.color,opacity:i.opacity,styleOptions:{hexRadius:Math.floor(h/2),tileSize:1,...i.styleOptions}},u=gn.createGrid(a,d);u.userData.isGrid=!0,u.userData.isDefaultGrid=!0,r.add(u)}}if(t.axes){const n=t.axesSize||5,o=new M.AxesHelper(n);r.add(o)}return K.ok(void 0)}catch(r){return K.err(new oe("Failed to add helpers to scene",ue.SCENE_OPERATION_FAILED,{originalError:r,options:t}))}}addDynamicGrid(e,t,r=1.2){try{if(!(e instanceof Yt))return K.err(new oe("Scene must be ThreeSceneAdapter",ue.INVALID_PARAMETER));const n=e.getThreeScene(),o=n.userData,i=o==null?void 0:o.gridOptions;if(!(i!=null&&i.enabled))return K.ok(void 0);const a=[];n.traverse(D=>{var R,O,L;((R=D.userData)!=null&&R.isGrid||(O=D.userData)!=null&&O.isHexGrid||(L=D.userData)!=null&&L.isDefaultGrid)&&a.push(D)}),a.forEach(D=>n.remove(D));let c;t instanceof We||"getThreeObject"in t&&typeof t.getThreeObject=="function"?c=t.getThreeObject():c=t;const d=new M.Box3().setFromObject(c).getSize(new M.Vector3);console.log("Object size:",d);const l=1,x=Zt.getGridSpacing(l).width,S=Math.max(d.x,d.z)*r;let g=0,b=x;for(;b<S&&g<20;)g++,b+=2*x;S<x*.8?g=0:g<3&&S>x*2&&(g=3),console.log("Grid parameters:",{tileSize:l,gridRadius:g,requiredWidth:S,hexWidth:x,actualCoverage:(2*g+1)*x});const w=i.type||It.HEXAGONAL_GLASS,A={size:Math.max(d.x,d.z)*r,divisions:g*2+1,color:i.color,opacity:i.opacity,styleOptions:{hexRadius:g,tileSize:l,...i.styleOptions}},P=gn.createGrid(w,A);return P.userData.isGrid=!0,P.userData.isHexGrid=!0,n.add(P),K.ok(void 0)}catch(n){return K.err(new oe("Failed to add dynamic grid",ue.SCENE_OPERATION_FAILED,{originalError:n}))}}addLighting(e,t){try{if(!(e instanceof Yt))return K.err(new oe("Scene must be ThreeSceneAdapter",ue.INVALID_PARAMETER));const r=e.getThreeScene();if(t.ambient){const n=new M.Color(t.ambient.color||"#404040"),o=t.ambient.intensity??Math.PI,i=new M.AmbientLight(n,o);r.add(i)}if(t.hemisphere){const n=new M.Color(t.hemisphere.skyColor||"#ffffbb"),o=new M.Color(t.hemisphere.groundColor||"#080820"),i=t.hemisphere.intensity??1,a=new M.HemisphereLight(n,o,i);r.add(a)}if(t.directional){const n=new M.Color(t.directional.color||"#ffffff"),o=t.directional.intensity??Math.PI,i=new M.DirectionalLight(n,o);if(t.directional.position){const a=t.directional.position;if(a instanceof M.Vector3)i.position.copy(a);else if(Array.isArray(a))i.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;i.position.set(c.x,c.y,c.z)}}else i.position.set(6,6,6);if(t.directional.castShadow&&(i.castShadow=!0,t.directional.shadow)){const a=t.directional.shadow;if(a.mapSize&&(i.shadow.mapSize.width=a.mapSize.width,i.shadow.mapSize.height=a.mapSize.height),a.camera){const c=i.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&&(i.shadow.bias=a.bias),a.radius!==void 0&&(i.shadow.radius=a.radius)}i.target.position.set(0,0,0),r.add(i),r.add(i.target),i.shadow&&i.shadow.camera.updateProjectionMatrix()}return K.ok(void 0)}catch(r){return K.err(new oe("Failed to add lighting to scene",ue.SCENE_OPERATION_FAILED,{originalError:r,options:t}))}}createGradientBackground(e,t){try{if(!(e instanceof Yt))return K.err(new oe("Scene must be ThreeSceneAdapter",ue.INVALID_PARAMETER));const r=e.getThreeScene(),n=document.createElement("canvas");n.width=2,n.height=512;const o=n.getContext("2d");if(!o)return K.err(new oe("Failed to create canvas context",ue.SCENE_OPERATION_FAILED));const i=o.createLinearGradient(0,0,0,n.height);i.addColorStop(0,t.topColor),i.addColorStop(1,t.bottomColor),o.fillStyle=i,o.fillRect(0,0,n.width,n.height);const a=new M.CanvasTexture(n);return a.needsUpdate=!0,r.background=a,K.ok(void 0)}catch(r){return K.err(new oe("Failed to create gradient background",ue.SCENE_OPERATION_FAILED,{originalError:r,options:t}))}}fitCameraToObject(e,t,r){try{let n;e instanceof We||"getThreeObject"in e&&typeof e.getThreeObject=="function"?n=e.getThreeObject():n=e;let o;t instanceof Xn||"getThreeCamera"in t&&typeof t.getThreeCamera=="function"?o=t.getThreeCamera():o=t;let i;r instanceof cs||r instanceof ls||"getThreeControls"in r&&typeof r.getThreeControls=="function"?i=r.getThreeControls():i=r;const a=new M.Box3().setFromObject(n),c=a.getCenter(new M.Vector3),h=a.getSize(new M.Vector3);console.log("Fitting camera to object:",{center:c,size:h,maxDimension:Math.max(h.x,h.y,h.z)});const d=Math.max(h.x,h.y,h.z);let u;"fov"in o?u=o.fov*(Math.PI/180):u=50*(Math.PI/180);let l=Math.abs(d/2/Math.tan(u/2));l*=2;const v=-Math.PI/4,x=Math.PI/8,S=c.x+l*Math.sin(v)*Math.cos(x),g=c.y+l*Math.sin(x),b=c.z+l*Math.cos(v)*Math.cos(x);return o.position.set(S,g,b),o.lookAt(c),o.updateProjectionMatrix(),i&&i.target&&(i.target.copy(c),i.update()),console.log("Camera positioned at:",{x:S,y:g,z:b}),console.log("Looking at:",c),K.ok(void 0)}catch(n){return K.err(new oe("Failed to fit camera to object",ue.CAMERA_INIT_FAILED,{originalError:n}))}}}const us=0,Va=1,hs=2,fs=2,ii=1.25,ds=1,zt=6*4+4+4,vn=65535,ja=Math.pow(2,-24),si=Symbol("SKIP_GENERATION");function ps(s){return s.index?s.index.count:s.attributes.position.count}function fr(s){return ps(s)/3}function ms(s,e=ArrayBuffer){return s>65535?new Uint32Array(new e(4*s)):new Uint16Array(new e(2*s))}function Wa(s,e){if(!s.index){const t=s.attributes.position.count,r=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=ms(t,r);s.setIndex(new f.BufferAttribute(n,1));for(let o=0;o<t;o++)n[o]=o}}function gs(s,e){const t=fr(s),r=e||s.drawRange,n=r.start/3,o=(r.start+r.count)/3,i=Math.max(0,n),a=Math.min(t,o)-i;return[{offset:Math.floor(i),count:Math.floor(a)}]}function vs(s,e){if(!s.groups||!s.groups.length)return gs(s,e);const t=[],r=new Set,n=e||s.drawRange,o=n.start/3,i=(n.start+n.count)/3;for(const c of s.groups){const h=c.start/3,d=(c.start+c.count)/3;r.add(Math.max(o,h)),r.add(Math.min(i,d))}const a=Array.from(r.values()).sort((c,h)=>c-h);for(let c=0;c<a.length-1;c++){const h=a[c],d=a[c+1];t.push({offset:Math.floor(h),count:Math.floor(d-h)})}return t}function Ya(s,e){const t=fr(s),r=vs(s,e).sort((i,a)=>i.offset-a.offset),n=r[r.length-1];n.count=Math.min(t-n.offset,n.count);let o=0;return r.forEach(({count:i})=>o+=i),t!==o}function oi(s,e,t,r,n){let o=1/0,i=1/0,a=1/0,c=-1/0,h=-1/0,d=-1/0,u=1/0,l=1/0,v=1/0,x=-1/0,S=-1/0,g=-1/0;for(let b=e*6,w=(e+t)*6;b<w;b+=6){const T=s[b+0],A=s[b+1],P=T-A,D=T+A;P<o&&(o=P),D>c&&(c=D),T<u&&(u=T),T>x&&(x=T);const R=s[b+2],O=s[b+3],L=R-O,E=R+O;L<i&&(i=L),E>h&&(h=E),R<l&&(l=R),R>S&&(S=R);const G=s[b+4],z=s[b+5],V=G-z,U=G+z;V<a&&(a=V),U>d&&(d=U),G<v&&(v=G),G>g&&(g=G)}r[0]=o,r[1]=i,r[2]=a,r[3]=c,r[4]=h,r[5]=d,n[0]=u,n[1]=l,n[2]=v,n[3]=x,n[4]=S,n[5]=g}function qa(s,e=null,t=null,r=null){const n=s.attributes.position,o=s.index?s.index.array:null,i=fr(s),a=n.normalized;let c;e===null?(c=new Float32Array(i*6*4),t=0,r=i):(c=e,t=t||0,r=r||i);const h=n.array,d=n.offset||0;let u=3;n.isInterleavedBufferAttribute&&(u=n.data.stride);const l=["getX","getY","getZ"];for(let v=t;v<t+r;v++){const x=v*3,S=v*6;let g=x+0,b=x+1,w=x+2;o&&(g=o[g],b=o[b],w=o[w]),a||(g=g*u+d,b=b*u+d,w=w*u+d);for(let T=0;T<3;T++){let A,P,D;a?(A=n[l[T]](g),P=n[l[T]](b),D=n[l[T]](w)):(A=h[g+T],P=h[b+T],D=h[w+T]);let R=A;P<R&&(R=P),D<R&&(R=D);let O=A;P>O&&(O=P),D>O&&(O=D);const L=(O-R)/2,E=T*2;c[S+E+0]=R+L,c[S+E+1]=L+(Math.abs(R)+L)*ja}}return c}function Fe(s,e,t){return t.min.x=e[s],t.min.y=e[s+1],t.min.z=e[s+2],t.max.x=e[s+3],t.max.y=e[s+4],t.max.z=e[s+5],t}function ys(s){let e=-1,t=-1/0;for(let r=0;r<3;r++){const n=s[r+3]-s[r];n>t&&(t=n,e=r)}return e}function xs(s,e){e.set(s)}function bs(s,e,t){let r,n;for(let o=0;o<3;o++){const i=o+3;r=s[o],n=e[o],t[o]=r<n?r:n,r=s[i],n=e[i],t[i]=r>n?r:n}}function yn(s,e,t){for(let r=0;r<3;r++){const n=e[s+2*r],o=e[s+2*r+1],i=n-o,a=n+o;i<t[r]&&(t[r]=i),a>t[r+3]&&(t[r+3]=a)}}function Er(s){const e=s[3]-s[0],t=s[4]-s[1],r=s[5]-s[2];return 2*(e*t+t*r+r*e)}const Ct=32,Za=(s,e)=>s.candidate-e.candidate,Et=new Array(Ct).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),xn=new Float32Array(6);function Ka(s,e,t,r,n,o){let i=-1,a=0;if(o===us)i=ys(e),i!==-1&&(a=(e[i]+e[i+3])/2);else if(o===Va)i=ys(s),i!==-1&&(a=Xa(t,r,n,i));else if(o===hs){const c=Er(s);let h=ii*n;const d=r*6,u=(r+n)*6;for(let l=0;l<3;l++){const v=e[l],g=(e[l+3]-v)/Ct;if(n<Ct/4){const b=[...Et];b.length=n;let w=0;for(let A=d;A<u;A+=6,w++){const P=b[w];P.candidate=t[A+2*l],P.count=0;const{bounds:D,leftCacheBounds:R,rightCacheBounds:O}=P;for(let L=0;L<3;L++)O[L]=1/0,O[L+3]=-1/0,R[L]=1/0,R[L+3]=-1/0,D[L]=1/0,D[L+3]=-1/0;yn(A,t,D)}b.sort(Za);let T=n;for(let A=0;A<T;A++){const P=b[A];for(;A+1<T&&b[A+1].candidate===P.candidate;)b.splice(A+1,1),T--}for(let A=d;A<u;A+=6){const P=t[A+2*l];for(let D=0;D<T;D++){const R=b[D];P>=R.candidate?yn(A,t,R.rightCacheBounds):(yn(A,t,R.leftCacheBounds),R.count++)}}for(let A=0;A<T;A++){const P=b[A],D=P.count,R=n-P.count,O=P.leftCacheBounds,L=P.rightCacheBounds;let E=0;D!==0&&(E=Er(O)/c);let G=0;R!==0&&(G=Er(L)/c);const z=ds+ii*(E*D+G*R);z<h&&(i=l,h=z,a=P.candidate)}}else{for(let T=0;T<Ct;T++){const A=Et[T];A.count=0,A.candidate=v+g+T*g;const P=A.bounds;for(let D=0;D<3;D++)P[D]=1/0,P[D+3]=-1/0}for(let T=d;T<u;T+=6){let D=~~((t[T+2*l]-v)/g);D>=Ct&&(D=Ct-1);const R=Et[D];R.count++,yn(T,t,R.bounds)}const b=Et[Ct-1];xs(b.bounds,b.rightCacheBounds);for(let T=Ct-2;T>=0;T--){const A=Et[T],P=Et[T+1];bs(A.bounds,P.rightCacheBounds,A.rightCacheBounds)}let w=0;for(let T=0;T<Ct-1;T++){const A=Et[T],P=A.count,D=A.bounds,O=Et[T+1].rightCacheBounds;P!==0&&(w===0?xs(D,xn):bs(D,xn,xn)),w+=P;let L=0,E=0;w!==0&&(L=Er(xn)/c);const G=n-w;G!==0&&(E=Er(O)/c);const z=ds+ii*(L*w+E*G);z<h&&(i=l,h=z,a=A.candidate)}}}}else console.warn(`MeshBVH: Invalid build strategy value ${o} used.`);return{axis:i,pos:a}}function Xa(s,e,t,r){let n=0;for(let o=e,i=e+t;o<i;o++)n+=s[o*6+r*2];return n/t}class ai{constructor(){this.boundingData=new Float32Array(6)}}function $a(s,e,t,r,n,o){let i=r,a=r+n-1;const c=o.pos,h=o.axis*2;for(;;){for(;i<=a&&t[i*6+h]<c;)i++;for(;i<=a&&t[a*6+h]>=c;)a--;if(i<a){for(let d=0;d<3;d++){let u=e[i*3+d];e[i*3+d]=e[a*3+d],e[a*3+d]=u}for(let d=0;d<6;d++){let u=t[i*6+d];t[i*6+d]=t[a*6+d],t[a*6+d]=u}i++,a--}else return i}}function Qa(s,e,t,r,n,o){let i=r,a=r+n-1;const c=o.pos,h=o.axis*2;for(;;){for(;i<=a&&t[i*6+h]<c;)i++;for(;i<=a&&t[a*6+h]>=c;)a--;if(i<a){let d=s[i];s[i]=s[a],s[a]=d;for(let u=0;u<6;u++){let l=t[i*6+u];t[i*6+u]=t[a*6+u],t[a*6+u]=l}i++,a--}else return i}}function Ye(s,e){return e[s+15]===65535}function Xe(s,e){return e[s+6]}function Je(s,e){return e[s+14]}function ot(s){return s+8}function He(s,e){return e[s+6]}function ci(s,e){return e[s+7]}function Zh(s){return s}let ws,Ur,bn,_s;const Ja=Math.pow(2,32);function li(s){return"count"in s?1:1+li(s.left)+li(s.right)}function Ha(s,e,t){return ws=new Float32Array(t),Ur=new Uint32Array(t),bn=new Uint16Array(t),_s=new Uint8Array(t),ui(s,e)}function ui(s,e){const t=s/4,r=s/2,n="count"in e,o=e.boundingData;for(let i=0;i<6;i++)ws[t+i]=o[i];if(n)if(e.buffer){const i=e.buffer;_s.set(new Uint8Array(i),s);for(let a=s,c=s+i.byteLength;a<c;a+=zt){const h=a/2;Ye(h,bn)||(Ur[a/4+6]+=t)}return s+i.byteLength}else{const i=e.offset,a=e.count;return Ur[t+6]=i,bn[r+14]=a,bn[r+15]=vn,s+zt}else{const i=e.left,a=e.right,c=e.splitAxis;let h;if(h=ui(s+zt,i),h/4>Ja)throw new Error("MeshBVH: Cannot store child pointer greater than 32 bits.");return Ur[t+6]=h/4,h=ui(h,a),Ur[t+7]=c,h}}function ec(s,e){const t=(s.index?s.index.count:s.attributes.position.count)/3,r=t>2**16,n=r?4:2,o=e?new SharedArrayBuffer(t*n):new ArrayBuffer(t*n),i=r?new Uint32Array(o):new Uint16Array(o);for(let a=0,c=i.length;a<c;a++)i[a]=a;return i}function tc(s,e,t,r,n){const{maxDepth:o,verbose:i,maxLeafTris:a,strategy:c,onProgress:h,indirect:d}=n,u=s._indirectBuffer,l=s.geometry,v=l.index?l.index.array:null,x=d?Qa:$a,S=fr(l),g=new Float32Array(6);let b=!1;const w=new ai;return oi(e,t,r,w.boundingData,g),A(w,t,r,g),w;function T(P){h&&h(P/S)}function A(P,D,R,O=null,L=0){if(!b&&L>=o&&(b=!0,i&&(console.warn(`MeshBVH: Max depth of ${o} reached when generating BVH. Consider increasing maxDepth.`),console.warn(l))),R<=a||L>=o)return T(D+R),P.offset=D,P.count=R,P;const E=Ka(P.boundingData,O,e,D,R,c);if(E.axis===-1)return T(D+R),P.offset=D,P.count=R,P;const G=x(u,v,e,D,R,E);if(G===D||G===D+R)T(D+R),P.offset=D,P.count=R;else{P.splitAxis=E.axis;const z=new ai,V=D,U=G-D;P.left=z,oi(e,V,U,z.boundingData,g),A(z,V,U,g,L+1);const H=new ai,ne=G,ge=R-U;P.right=H,oi(e,ne,ge,H.boundingData,g),A(H,ne,ge,g,L+1)}return P}}function rc(s,e){const t=s.geometry;e.indirect&&(s._indirectBuffer=ec(t,e.useSharedArrayBuffer),Ya(t,e.range)&&!e.verbose&&console.warn('MeshBVH: Provided geometry contains groups or a range that do not fully span the vertex contents while using the "indirect" option. BVH may incorrectly report intersections on unrendered portions of the geometry.')),s._indirectBuffer||Wa(t,e);const r=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=qa(t),o=e.indirect?gs(t,e.range):vs(t,e.range);s._roots=o.map(i=>{const a=tc(s,n,i.offset,i.count,e),c=li(a),h=new r(zt*c);return Ha(0,a,h),h})}class Pt{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let r=1/0,n=-1/0;for(let o=0,i=e.length;o<i;o++){const c=e[o][t];r=c<r?c:r,n=c>n?c:n}this.min=r,this.max=n}setFromPoints(e,t){let r=1/0,n=-1/0;for(let o=0,i=t.length;o<i;o++){const a=t[o],c=e.dot(a);r=c<r?c:r,n=c>n?c:n}this.min=r,this.max=n}isSeparated(e){return this.min>e.max||e.min>this.max}}Pt.prototype.setFromBox=function(){const s=new f.Vector3;return function(t,r){const n=r.min,o=r.max;let i=1/0,a=-1/0;for(let c=0;c<=1;c++)for(let h=0;h<=1;h++)for(let d=0;d<=1;d++){s.x=n.x*c+o.x*(1-c),s.y=n.y*h+o.y*(1-h),s.z=n.z*d+o.z*(1-d);const u=t.dot(s);i=Math.min(u,i),a=Math.max(u,a)}this.min=i,this.max=a}}();const nc=function(){const s=new f.Vector3,e=new f.Vector3,t=new f.Vector3;return function(n,o,i){const a=n.start,c=s,h=o.start,d=e;t.subVectors(a,h),s.subVectors(n.end,n.start),e.subVectors(o.end,o.start);const u=t.dot(d),l=d.dot(c),v=d.dot(d),x=t.dot(c),g=c.dot(c)*v-l*l;let b,w;g!==0?b=(u*l-x*v)/g:b=0,w=(u+b*l)/v,i.x=b,i.y=w}}(),hi=function(){const s=new f.Vector2,e=new f.Vector3,t=new f.Vector3;return function(n,o,i,a){nc(n,o,s);let c=s.x,h=s.y;if(c>=0&&c<=1&&h>=0&&h<=1){n.at(c,i),o.at(h,a);return}else if(c>=0&&c<=1){h<0?o.at(0,a):o.at(1,a),n.closestPointToPoint(a,!0,i);return}else if(h>=0&&h<=1){c<0?n.at(0,i):n.at(1,i),o.closestPointToPoint(i,!0,a);return}else{let d;c<0?d=n.start:d=n.end;let u;h<0?u=o.start:u=o.end;const l=e,v=t;if(n.closestPointToPoint(u,!0,e),o.closestPointToPoint(d,!0,t),l.distanceToSquared(u)<=v.distanceToSquared(d)){i.copy(l),a.copy(u);return}else{i.copy(d),a.copy(v);return}}}}(),ic=function(){const s=new f.Vector3,e=new f.Vector3,t=new f.Plane,r=new f.Line3;return function(o,i){const{radius:a,center:c}=o,{a:h,b:d,c:u}=i;if(r.start=h,r.end=d,r.closestPointToPoint(c,!0,s).distanceTo(c)<=a||(r.start=h,r.end=u,r.closestPointToPoint(c,!0,s).distanceTo(c)<=a)||(r.start=d,r.end=u,r.closestPointToPoint(c,!0,s).distanceTo(c)<=a))return!0;const S=i.getPlane(t);if(Math.abs(S.distanceToPoint(c))<=a){const b=S.projectPoint(c,e);if(i.containsPoint(b))return!0}return!1}}(),sc=1e-15;function fi(s){return Math.abs(s)<sc}class mt extends f.Triangle{constructor(...e){super(...e),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new f.Vector3),this.satBounds=new Array(4).fill().map(()=>new Pt),this.points=[this.a,this.b,this.c],this.sphere=new f.Sphere,this.plane=new f.Plane,this.needsUpdate=!0}intersectsSphere(e){return ic(e,this)}update(){const e=this.a,t=this.b,r=this.c,n=this.points,o=this.satAxes,i=this.satBounds,a=o[0],c=i[0];this.getNormal(a),c.setFromPoints(a,n);const h=o[1],d=i[1];h.subVectors(e,t),d.setFromPoints(h,n);const u=o[2],l=i[2];u.subVectors(t,r),l.setFromPoints(u,n);const v=o[3],x=i[3];v.subVectors(r,e),x.setFromPoints(v,n),this.sphere.setFromPoints(this.points),this.plane.setFromNormalAndCoplanarPoint(a,e),this.needsUpdate=!1}}mt.prototype.closestPointToSegment=function(){const s=new f.Vector3,e=new f.Vector3,t=new f.Line3;return function(n,o=null,i=null){const{start:a,end:c}=n,h=this.points;let d,u=1/0;for(let l=0;l<3;l++){const v=(l+1)%3;t.start.copy(h[l]),t.end.copy(h[v]),hi(t,n,s,e),d=s.distanceToSquared(e),d<u&&(u=d,o&&o.copy(s),i&&i.copy(e))}return this.closestPointToPoint(a,s),d=a.distanceToSquared(s),d<u&&(u=d,o&&o.copy(s),i&&i.copy(a)),this.closestPointToPoint(c,s),d=c.distanceToSquared(s),d<u&&(u=d,o&&o.copy(s),i&&i.copy(c)),Math.sqrt(u)}}(),mt.prototype.intersectsTriangle=function(){const s=new mt,e=new Array(3),t=new Array(3),r=new Pt,n=new Pt,o=new f.Vector3,i=new f.Vector3,a=new f.Vector3,c=new f.Vector3,h=new f.Vector3,d=new f.Line3,u=new f.Line3,l=new f.Line3,v=new f.Vector3;function x(S,g,b){const w=S.points;let T=0,A=-1;for(let P=0;P<3;P++){const{start:D,end:R}=d;D.copy(w[P]),R.copy(w[(P+1)%3]),d.delta(i);const O=fi(g.distanceToPoint(D));if(fi(g.normal.dot(i))&&O){b.copy(d),T=2;break}const L=g.intersectLine(d,v);if(!L&&O&&v.copy(D),(L||O)&&!fi(v.distanceTo(R))){if(T<=1)(T===1?b.start:b.end).copy(v),O&&(A=T);else if(T>=2){(A===1?b.start:b.end).copy(v),T=2;break}if(T++,T===2&&A===-1)break}}return T}return function(g,b=null,w=!1){this.needsUpdate&&this.update(),g.isExtendedTriangle?g.needsUpdate&&g.update():(s.copy(g),s.update(),g=s);const T=this.plane,A=g.plane;if(Math.abs(T.normal.dot(A.normal))>1-1e-10){const P=this.satBounds,D=this.satAxes;t[0]=g.a,t[1]=g.b,t[2]=g.c;for(let L=0;L<4;L++){const E=P[L],G=D[L];if(r.setFromPoints(G,t),E.isSeparated(r))return!1}const R=g.satBounds,O=g.satAxes;e[0]=this.a,e[1]=this.b,e[2]=this.c;for(let L=0;L<4;L++){const E=R[L],G=O[L];if(r.setFromPoints(G,e),E.isSeparated(r))return!1}for(let L=0;L<4;L++){const E=D[L];for(let G=0;G<4;G++){const z=O[G];if(o.crossVectors(E,z),r.setFromPoints(o,e),n.setFromPoints(o,t),r.isSeparated(n))return!1}}return b&&(w||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),b.start.set(0,0,0),b.end.set(0,0,0)),!0}else{const P=x(this,A,u);if(P===1&&g.containsPoint(u.end))return b&&(b.start.copy(u.end),b.end.copy(u.end)),!0;if(P!==2)return!1;const D=x(g,T,l);if(D===1&&this.containsPoint(l.end))return b&&(b.start.copy(l.end),b.end.copy(l.end)),!0;if(D!==2)return!1;if(u.delta(a),l.delta(c),a.dot(c)<0){let V=l.start;l.start=l.end,l.end=V}const R=u.start.dot(a),O=u.end.dot(a),L=l.start.dot(a),E=l.end.dot(a),G=O<L,z=R<E;return R!==E&&L!==O&&G===z?!1:(b&&(h.subVectors(u.start,l.start),h.dot(a)>0?b.start.copy(u.start):b.start.copy(l.start),h.subVectors(u.end,l.end),h.dot(a)<0?b.end.copy(u.end):b.end.copy(l.end)),!0)}}}(),mt.prototype.distanceToPoint=function(){const s=new f.Vector3;return function(t){return this.closestPointToPoint(t,s),t.distanceTo(s)}}(),mt.prototype.distanceToTriangle=function(){const s=new f.Vector3,e=new f.Vector3,t=["a","b","c"],r=new f.Line3,n=new f.Line3;return function(i,a=null,c=null){const h=a||c?r:null;if(this.intersectsTriangle(i,h))return(a||c)&&(a&&h.getCenter(a),c&&h.getCenter(c)),0;let d=1/0;for(let u=0;u<3;u++){let l;const v=t[u],x=i[v];this.closestPointToPoint(x,s),l=x.distanceToSquared(s),l<d&&(d=l,a&&a.copy(s),c&&c.copy(x));const S=this[v];i.closestPointToPoint(S,s),l=S.distanceToSquared(s),l<d&&(d=l,a&&a.copy(S),c&&c.copy(s))}for(let u=0;u<3;u++){const l=t[u],v=t[(u+1)%3];r.set(this[l],this[v]);for(let x=0;x<3;x++){const S=t[x],g=t[(x+1)%3];n.set(i[S],i[g]),hi(r,n,s,e);const b=s.distanceToSquared(e);b<d&&(d=b,a&&a.copy(s),c&&c.copy(e))}}return Math.sqrt(d)}}();class qe{constructor(e,t,r){this.isOrientedBox=!0,this.min=new f.Vector3,this.max=new f.Vector3,this.matrix=new f.Matrix4,this.invMatrix=new f.Matrix4,this.points=new Array(8).fill().map(()=>new f.Vector3),this.satAxes=new Array(3).fill().map(()=>new f.Vector3),this.satBounds=new Array(3).fill().map(()=>new Pt),this.alignedSatBounds=new Array(3).fill().map(()=>new Pt),this.needsUpdate=!1,e&&this.min.copy(e),t&&this.max.copy(t),r&&this.matrix.copy(r)}set(e,t,r){this.min.copy(e),this.max.copy(t),this.matrix.copy(r),this.needsUpdate=!0}copy(e){this.min.copy(e.min),this.max.copy(e.max),this.matrix.copy(e.matrix),this.needsUpdate=!0}}qe.prototype.update=function(){return function(){const e=this.matrix,t=this.min,r=this.max,n=this.points;for(let h=0;h<=1;h++)for(let d=0;d<=1;d++)for(let u=0;u<=1;u++){const l=1*h|2*d|4*u,v=n[l];v.x=h?r.x:t.x,v.y=d?r.y:t.y,v.z=u?r.z:t.z,v.applyMatrix4(e)}const o=this.satBounds,i=this.satAxes,a=n[0];for(let h=0;h<3;h++){const d=i[h],u=o[h],l=1<<h,v=n[l];d.subVectors(a,v),u.setFromPoints(d,n)}const c=this.alignedSatBounds;c[0].setFromPointsField(n,"x"),c[1].setFromPointsField(n,"y"),c[2].setFromPointsField(n,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}}(),qe.prototype.intersectsBox=function(){const s=new Pt;return function(t){this.needsUpdate&&this.update();const r=t.min,n=t.max,o=this.satBounds,i=this.satAxes,a=this.alignedSatBounds;if(s.min=r.x,s.max=n.x,a[0].isSeparated(s)||(s.min=r.y,s.max=n.y,a[1].isSeparated(s))||(s.min=r.z,s.max=n.z,a[2].isSeparated(s)))return!1;for(let c=0;c<3;c++){const h=i[c],d=o[c];if(s.setFromBox(h,t),d.isSeparated(s))return!1}return!0}}(),qe.prototype.intersectsTriangle=function(){const s=new mt,e=new Array(3),t=new Pt,r=new Pt,n=new f.Vector3;return function(i){this.needsUpdate&&this.update(),i.isExtendedTriangle?i.needsUpdate&&i.update():(s.copy(i),s.update(),i=s);const a=this.satBounds,c=this.satAxes;e[0]=i.a,e[1]=i.b,e[2]=i.c;for(let l=0;l<3;l++){const v=a[l],x=c[l];if(t.setFromPoints(x,e),v.isSeparated(t))return!1}const h=i.satBounds,d=i.satAxes,u=this.points;for(let l=0;l<3;l++){const v=h[l],x=d[l];if(t.setFromPoints(x,u),v.isSeparated(t))return!1}for(let l=0;l<3;l++){const v=c[l];for(let x=0;x<4;x++){const S=d[x];if(n.crossVectors(v,S),t.setFromPoints(n,e),r.setFromPoints(n,u),t.isSeparated(r))return!1}}return!0}}(),qe.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}}(),qe.prototype.distanceToPoint=function(){const s=new f.Vector3;return function(t){return this.closestPointToPoint(t,s),t.distanceTo(s)}}(),qe.prototype.distanceToBox=function(){const s=["x","y","z"],e=new Array(12).fill().map(()=>new f.Line3),t=new Array(12).fill().map(()=>new f.Line3),r=new f.Vector3,n=new f.Vector3;return function(i,a=0,c=null,h=null){if(this.needsUpdate&&this.update(),this.intersectsBox(i))return(c||h)&&(i.getCenter(n),this.closestPointToPoint(n,r),i.closestPointToPoint(r,n),c&&c.copy(r),h&&h.copy(n)),0;const d=a*a,u=i.min,l=i.max,v=this.points;let x=1/0;for(let g=0;g<8;g++){const b=v[g];n.copy(b).clamp(u,l);const w=b.distanceToSquared(n);if(w<x&&(x=w,c&&c.copy(b),h&&h.copy(n),w<d))return Math.sqrt(w)}let S=0;for(let g=0;g<3;g++)for(let b=0;b<=1;b++)for(let w=0;w<=1;w++){const T=(g+1)%3,A=(g+2)%3,P=b<<T|w<<A,D=1<<g|b<<T|w<<A,R=v[P],O=v[D];e[S].set(R,O);const E=s[g],G=s[T],z=s[A],V=t[S],U=V.start,H=V.end;U[E]=u[E],U[G]=b?u[G]:l[G],U[z]=w?u[z]:l[G],H[E]=l[E],H[G]=b?u[G]:l[G],H[z]=w?u[z]:l[G],S++}for(let g=0;g<=1;g++)for(let b=0;b<=1;b++)for(let w=0;w<=1;w++){n.x=g?l.x:u.x,n.y=b?l.y:u.y,n.z=w?l.z:u.z,this.closestPointToPoint(n,r);const T=n.distanceToSquared(r);if(T<x&&(x=T,c&&c.copy(r),h&&h.copy(n),T<d))return Math.sqrt(T)}for(let g=0;g<12;g++){const b=e[g];for(let w=0;w<12;w++){const T=t[w];hi(b,T,r,n);const A=r.distanceToSquared(n);if(A<x&&(x=A,c&&c.copy(r),h&&h.copy(n),A<d))return Math.sqrt(A)}}return Math.sqrt(x)}}();class di{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 oc extends di{constructor(){super(()=>new mt)}}const at=new oc;class ac{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const e=[];let t=null;this.setBuffer=r=>{t&&e.push(t),t=r,this.float32Array=new Float32Array(r),this.uint16Array=new Uint16Array(r),this.uint32Array=new Uint32Array(r)},this.clearBuffer=()=>{t=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,e.length!==0&&this.setBuffer(e.pop())}}}const Me=new ac;let Ut,dr;const pr=[],wn=new di(()=>new f.Box3);function cc(s,e,t,r,n,o){Ut=wn.getPrimitive(),dr=wn.getPrimitive(),pr.push(Ut,dr),Me.setBuffer(s._roots[e]);const i=pi(0,s.geometry,t,r,n,o);Me.clearBuffer(),wn.releasePrimitive(Ut),wn.releasePrimitive(dr),pr.pop(),pr.pop();const a=pr.length;return a>0&&(dr=pr[a-1],Ut=pr[a-2]),i}function pi(s,e,t,r,n=null,o=0,i=0){const{float32Array:a,uint16Array:c,uint32Array:h}=Me;let d=s*2;if(Ye(d,c)){const l=Xe(s,h),v=Je(d,c);return Fe(s,a,Ut),r(l,v,!1,i,o+s,Ut)}else{let E=function(z){const{uint16Array:V,uint32Array:U}=Me;let H=z*2;for(;!Ye(H,V);)z=ot(z),H=z*2;return Xe(z,U)},G=function(z){const{uint16Array:V,uint32Array:U}=Me;let H=z*2;for(;!Ye(H,V);)z=He(z,U),H=z*2;return Xe(z,U)+Je(H,V)};const l=ot(s),v=He(s,h);let x=l,S=v,g,b,w,T;if(n&&(w=Ut,T=dr,Fe(x,a,w),Fe(S,a,T),g=n(w),b=n(T),b<g)){x=v,S=l;const z=g;g=b,b=z,w=T}w||(w=Ut,Fe(x,a,w));const A=Ye(x*2,c),P=t(w,A,g,i+1,o+x);let D;if(P===fs){const z=E(x),U=G(x)-z;D=r(z,U,!0,i+1,o+x,w)}else D=P&&pi(x,e,t,r,n,o,i+1);if(D)return!0;T=dr,Fe(S,a,T);const R=Ye(S*2,c),O=t(T,R,b,i+1,o+S);let L;if(O===fs){const z=E(S),U=G(S)-z;L=r(z,U,!0,i+1,o+S,T)}else L=O&&pi(S,e,t,r,n,o,i+1);return!!L}}const Gr=new f.Vector3,mi=new f.Vector3;function lc(s,e,t={},r=0,n=1/0){const o=r*r,i=n*n;let a=1/0,c=null;if(s.shapecast({boundsTraverseOrder:d=>(Gr.copy(e).clamp(d.min,d.max),Gr.distanceToSquared(e)),intersectsBounds:(d,u,l)=>l<a&&l<i,intersectsTriangle:(d,u)=>{d.closestPointToPoint(e,Gr);const l=e.distanceToSquared(Gr);return l<a&&(mi.copy(Gr),a=l,c=u),l<o}}),a===1/0)return null;const h=Math.sqrt(a);return t.point?t.point.copy(mi):t.point=mi.clone(),t.distance=h,t.faceIndex=c,t}const mr=new f.Vector3,gr=new f.Vector3,vr=new f.Vector3,_n=new f.Vector2,Sn=new f.Vector2,Tn=new f.Vector2,Ss=new f.Vector3,Ts=new f.Vector3,As=new f.Vector3,An=new f.Vector3;function uc(s,e,t,r,n,o,i,a){let c;if(o===f.BackSide?c=s.intersectTriangle(r,t,e,!0,n):c=s.intersectTriangle(e,t,r,o!==f.DoubleSide,n),c===null)return null;const h=s.origin.distanceTo(n);return h<i||h>a?null:{distance:h,point:n.clone()}}function hc(s,e,t,r,n,o,i,a,c,h,d){mr.fromBufferAttribute(e,o),gr.fromBufferAttribute(e,i),vr.fromBufferAttribute(e,a);const u=uc(s,mr,gr,vr,An,c,h,d);if(u){r&&(_n.fromBufferAttribute(r,o),Sn.fromBufferAttribute(r,i),Tn.fromBufferAttribute(r,a),u.uv=f.Triangle.getInterpolation(An,mr,gr,vr,_n,Sn,Tn,new f.Vector2)),n&&(_n.fromBufferAttribute(n,o),Sn.fromBufferAttribute(n,i),Tn.fromBufferAttribute(n,a),u.uv1=f.Triangle.getInterpolation(An,mr,gr,vr,_n,Sn,Tn,new f.Vector2)),t&&(Ss.fromBufferAttribute(t,o),Ts.fromBufferAttribute(t,i),As.fromBufferAttribute(t,a),u.normal=f.Triangle.getInterpolation(An,mr,gr,vr,Ss,Ts,As,new f.Vector3),u.normal.dot(s.direction)>0&&u.normal.multiplyScalar(-1));const l={a:o,b:i,c:a,normal:new f.Vector3,materialIndex:0};f.Triangle.getNormal(mr,gr,vr,l.normal),u.face=l,u.faceIndex=o}return u}function Mn(s,e,t,r,n,o,i){const a=r*3;let c=a+0,h=a+1,d=a+2;const u=s.index;s.index&&(c=u.getX(c),h=u.getX(h),d=u.getX(d));const{position:l,normal:v,uv:x,uv1:S}=s.attributes,g=hc(t,l,v,x,S,c,h,d,e,o,i);return g?(g.faceIndex=r,n&&n.push(g),g):null}function Oe(s,e,t,r){const n=s.a,o=s.b,i=s.c;let a=e,c=e+1,h=e+2;t&&(a=t.getX(a),c=t.getX(c),h=t.getX(h)),n.x=r.getX(a),n.y=r.getY(a),n.z=r.getZ(a),o.x=r.getX(c),o.y=r.getY(c),o.z=r.getZ(c),i.x=r.getX(h),i.y=r.getY(h),i.z=r.getZ(h)}function fc(s,e,t,r,n,o,i,a){const{geometry:c,_indirectBuffer:h}=s;for(let d=r,u=r+n;d<u;d++)Mn(c,e,t,d,o,i,a)}function dc(s,e,t,r,n,o,i){const{geometry:a,_indirectBuffer:c}=s;let h=1/0,d=null;for(let u=r,l=r+n;u<l;u++){let v;v=Mn(a,e,t,u,null,o,i),v&&v.distance<h&&(d=v,h=v.distance)}return d}function pc(s,e,t,r,n,o,i){const{geometry:a}=t,{index:c}=a,h=a.attributes.position;for(let d=s,u=e+s;d<u;d++){let l;if(l=d,Oe(i,l*3,c,h),i.needsUpdate=!0,r(i,l,n,o))return!0}return!1}function mc(s,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=s.geometry,r=t.index?t.index.array:null,n=t.attributes.position;let o,i,a,c,h=0;const d=s._roots;for(let l=0,v=d.length;l<v;l++)o=d[l],i=new Uint32Array(o),a=new Uint16Array(o),c=new Float32Array(o),u(0,h),h+=o.byteLength;function u(l,v,x=!1){const S=l*2;if(a[S+15]===vn){const b=i[l+6],w=a[S+14];let T=1/0,A=1/0,P=1/0,D=-1/0,R=-1/0,O=-1/0;for(let L=3*b,E=3*(b+w);L<E;L++){let G=r[L];const z=n.getX(G),V=n.getY(G),U=n.getZ(G);z<T&&(T=z),z>D&&(D=z),V<A&&(A=V),V>R&&(R=V),U<P&&(P=U),U>O&&(O=U)}return c[l+0]!==T||c[l+1]!==A||c[l+2]!==P||c[l+3]!==D||c[l+4]!==R||c[l+5]!==O?(c[l+0]=T,c[l+1]=A,c[l+2]=P,c[l+3]=D,c[l+4]=R,c[l+5]=O,!0):!1}else{const b=l+8,w=i[l+6],T=b+v,A=w+v;let P=x,D=!1,R=!1;e?P||(D=e.has(T),R=e.has(A),P=!D&&!R):(D=!0,R=!0);const O=P||D,L=P||R;let E=!1;O&&(E=u(b,v,P));let G=!1;L&&(G=u(w,v,P));const z=E||G;if(z)for(let V=0;V<3;V++){const U=b+V,H=w+V,ne=c[U],ge=c[U+3],Pe=c[H],ve=c[H+3];c[l+V]=ne<Pe?ne:Pe,c[l+V+3]=ge>ve?ge:ve}return z}}}function Gt(s,e,t,r,n){let o,i,a,c,h,d;const u=1/t.direction.x,l=1/t.direction.y,v=1/t.direction.z,x=t.origin.x,S=t.origin.y,g=t.origin.z;let b=e[s],w=e[s+3],T=e[s+1],A=e[s+3+1],P=e[s+2],D=e[s+3+2];return u>=0?(o=(b-x)*u,i=(w-x)*u):(o=(w-x)*u,i=(b-x)*u),l>=0?(a=(T-S)*l,c=(A-S)*l):(a=(A-S)*l,c=(T-S)*l),o>c||a>i||((a>o||isNaN(o))&&(o=a),(c<i||isNaN(i))&&(i=c),v>=0?(h=(P-g)*v,d=(D-g)*v):(h=(D-g)*v,d=(P-g)*v),o>d||h>i)?!1:((h>o||o!==o)&&(o=h),(d<i||i!==i)&&(i=d),o<=n&&i>=r)}function gc(s,e,t,r,n,o,i,a){const{geometry:c,_indirectBuffer:h}=s;for(let d=r,u=r+n;d<u;d++){let l=h?h[d]:d;Mn(c,e,t,l,o,i,a)}}function vc(s,e,t,r,n,o,i){const{geometry:a,_indirectBuffer:c}=s;let h=1/0,d=null;for(let u=r,l=r+n;u<l;u++){let v;v=Mn(a,e,t,c?c[u]:u,null,o,i),v&&v.distance<h&&(d=v,h=v.distance)}return d}function yc(s,e,t,r,n,o,i){const{geometry:a}=t,{index:c}=a,h=a.attributes.position;for(let d=s,u=e+s;d<u;d++){let l;if(l=t.resolveTriangleIndex(d),Oe(i,l*3,c,h),i.needsUpdate=!0,r(i,l,n,o))return!0}return!1}function xc(s,e,t,r,n,o,i){Me.setBuffer(s._roots[e]),gi(0,s,t,r,n,o,i),Me.clearBuffer()}function gi(s,e,t,r,n,o,i){const{float32Array:a,uint16Array:c,uint32Array:h}=Me,d=s*2;if(Ye(d,c)){const l=Xe(s,h),v=Je(d,c);fc(e,t,r,l,v,n,o,i)}else{const l=ot(s);Gt(l,a,r,o,i)&&gi(l,e,t,r,n,o,i);const v=He(s,h);Gt(v,a,r,o,i)&&gi(v,e,t,r,n,o,i)}}const bc=["x","y","z"];function wc(s,e,t,r,n,o){Me.setBuffer(s._roots[e]);const i=vi(0,s,t,r,n,o);return Me.clearBuffer(),i}function vi(s,e,t,r,n,o){const{float32Array:i,uint16Array:a,uint32Array:c}=Me;let h=s*2;if(Ye(h,a)){const u=Xe(s,c),l=Je(h,a);return dc(e,t,r,u,l,n,o)}else{const u=ci(s,c),l=bc[u],x=r.direction[l]>=0;let S,g;x?(S=ot(s),g=He(s,c)):(S=He(s,c),g=ot(s));const w=Gt(S,i,r,n,o)?vi(S,e,t,r,n,o):null;if(w){const P=w.point[l];if(x?P<=i[g+u]:P>=i[g+u+3])return w}const A=Gt(g,i,r,n,o)?vi(g,e,t,r,n,o):null;return w&&A?w.distance<=A.distance?w:A:w||A||null}}const In=new f.Box3,yr=new mt,xr=new mt,Vr=new f.Matrix4,Ms=new qe,Cn=new qe;function _c(s,e,t,r){Me.setBuffer(s._roots[e]);const n=yi(0,s,t,r);return Me.clearBuffer(),n}function yi(s,e,t,r,n=null){const{float32Array:o,uint16Array:i,uint32Array:a}=Me;let c=s*2;if(n===null&&(t.boundingBox||t.computeBoundingBox(),Ms.set(t.boundingBox.min,t.boundingBox.max,r),n=Ms),Ye(c,i)){const d=e.geometry,u=d.index,l=d.attributes.position,v=t.index,x=t.attributes.position,S=Xe(s,a),g=Je(c,i);if(Vr.copy(r).invert(),t.boundsTree)return Fe(s,o,Cn),Cn.matrix.copy(Vr),Cn.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:w=>Cn.intersectsBox(w),intersectsTriangle:w=>{w.a.applyMatrix4(r),w.b.applyMatrix4(r),w.c.applyMatrix4(r),w.needsUpdate=!0;for(let T=S*3,A=(g+S)*3;T<A;T+=3)if(Oe(xr,T,u,l),xr.needsUpdate=!0,w.intersectsTriangle(xr))return!0;return!1}});for(let b=S*3,w=(g+S)*3;b<w;b+=3){Oe(yr,b,u,l),yr.a.applyMatrix4(Vr),yr.b.applyMatrix4(Vr),yr.c.applyMatrix4(Vr),yr.needsUpdate=!0;for(let T=0,A=v.count;T<A;T+=3)if(Oe(xr,T,v,x),xr.needsUpdate=!0,yr.intersectsTriangle(xr))return!0}}else{const d=s+8,u=a[s+6];return Fe(d,o,In),!!(n.intersectsBox(In)&&yi(d,e,t,r,n)||(Fe(u,o,In),n.intersectsBox(In)&&yi(u,e,t,r,n)))}}const Pn=new f.Matrix4,xi=new qe,jr=new qe,Sc=new f.Vector3,Tc=new f.Vector3,Ac=new f.Vector3,Mc=new f.Vector3;function Ic(s,e,t,r={},n={},o=0,i=1/0){e.boundingBox||e.computeBoundingBox(),xi.set(e.boundingBox.min,e.boundingBox.max,t),xi.needsUpdate=!0;const a=s.geometry,c=a.attributes.position,h=a.index,d=e.attributes.position,u=e.index,l=at.getPrimitive(),v=at.getPrimitive();let x=Sc,S=Tc,g=null,b=null;n&&(g=Ac,b=Mc);let w=1/0,T=null,A=null;return Pn.copy(t).invert(),jr.matrix.copy(Pn),s.shapecast({boundsTraverseOrder:P=>xi.distanceToBox(P),intersectsBounds:(P,D,R)=>R<w&&R<i?(D&&(jr.min.copy(P.min),jr.max.copy(P.max),jr.needsUpdate=!0),!0):!1,intersectsRange:(P,D)=>{if(e.boundsTree)return e.boundsTree.shapecast({boundsTraverseOrder:O=>jr.distanceToBox(O),intersectsBounds:(O,L,E)=>E<w&&E<i,intersectsRange:(O,L)=>{for(let E=O,G=O+L;E<G;E++){Oe(v,3*E,u,d),v.a.applyMatrix4(t),v.b.applyMatrix4(t),v.c.applyMatrix4(t),v.needsUpdate=!0;for(let z=P,V=P+D;z<V;z++){Oe(l,3*z,h,c),l.needsUpdate=!0;const U=l.distanceToTriangle(v,x,g);if(U<w&&(S.copy(x),b&&b.copy(g),w=U,T=z,A=E),U<o)return!0}}}});{const R=fr(e);for(let O=0,L=R;O<L;O++){Oe(v,3*O,u,d),v.a.applyMatrix4(t),v.b.applyMatrix4(t),v.c.applyMatrix4(t),v.needsUpdate=!0;for(let E=P,G=P+D;E<G;E++){Oe(l,3*E,h,c),l.needsUpdate=!0;const z=l.distanceToTriangle(v,x,g);if(z<w&&(S.copy(x),b&&b.copy(g),w=z,T=E,A=O),z<o)return!0}}}}}),at.releasePrimitive(l),at.releasePrimitive(v),w===1/0?null:(r.point?r.point.copy(S):r.point=S.clone(),r.distance=w,r.faceIndex=T,n&&(n.point?n.point.copy(b):n.point=b.clone(),n.point.applyMatrix4(Pn),S.applyMatrix4(Pn),n.distance=S.sub(n.point).length(),n.faceIndex=A),r)}function Cc(s,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=s.geometry,r=t.index?t.index.array:null,n=t.attributes.position;let o,i,a,c,h=0;const d=s._roots;for(let l=0,v=d.length;l<v;l++)o=d[l],i=new Uint32Array(o),a=new Uint16Array(o),c=new Float32Array(o),u(0,h),h+=o.byteLength;function u(l,v,x=!1){const S=l*2;if(a[S+15]===vn){const b=i[l+6],w=a[S+14];let T=1/0,A=1/0,P=1/0,D=-1/0,R=-1/0,O=-1/0;for(let L=b,E=b+w;L<E;L++){const G=3*s.resolveTriangleIndex(L);for(let z=0;z<3;z++){let V=G+z;V=r?r[V]:V;const U=n.getX(V),H=n.getY(V),ne=n.getZ(V);U<T&&(T=U),U>D&&(D=U),H<A&&(A=H),H>R&&(R=H),ne<P&&(P=ne),ne>O&&(O=ne)}}return c[l+0]!==T||c[l+1]!==A||c[l+2]!==P||c[l+3]!==D||c[l+4]!==R||c[l+5]!==O?(c[l+0]=T,c[l+1]=A,c[l+2]=P,c[l+3]=D,c[l+4]=R,c[l+5]=O,!0):!1}else{const b=l+8,w=i[l+6],T=b+v,A=w+v;let P=x,D=!1,R=!1;e?P||(D=e.has(T),R=e.has(A),P=!D&&!R):(D=!0,R=!0);const O=P||D,L=P||R;let E=!1;O&&(E=u(b,v,P));let G=!1;L&&(G=u(w,v,P));const z=E||G;if(z)for(let V=0;V<3;V++){const U=b+V,H=w+V,ne=c[U],ge=c[U+3],Pe=c[H],ve=c[H+3];c[l+V]=ne<Pe?ne:Pe,c[l+V+3]=ge>ve?ge:ve}return z}}}function Pc(s,e,t,r,n,o,i){Me.setBuffer(s._roots[e]),bi(0,s,t,r,n,o,i),Me.clearBuffer()}function bi(s,e,t,r,n,o,i){const{float32Array:a,uint16Array:c,uint32Array:h}=Me,d=s*2;if(Ye(d,c)){const l=Xe(s,h),v=Je(d,c);gc(e,t,r,l,v,n,o,i)}else{const l=ot(s);Gt(l,a,r,o,i)&&bi(l,e,t,r,n,o,i);const v=He(s,h);Gt(v,a,r,o,i)&&bi(v,e,t,r,n,o,i)}}const Dc=["x","y","z"];function Rc(s,e,t,r,n,o){Me.setBuffer(s._roots[e]);const i=wi(0,s,t,r,n,o);return Me.clearBuffer(),i}function wi(s,e,t,r,n,o){const{float32Array:i,uint16Array:a,uint32Array:c}=Me;let h=s*2;if(Ye(h,a)){const u=Xe(s,c),l=Je(h,a);return vc(e,t,r,u,l,n,o)}else{const u=ci(s,c),l=Dc[u],x=r.direction[l]>=0;let S,g;x?(S=ot(s),g=He(s,c)):(S=He(s,c),g=ot(s));const w=Gt(S,i,r,n,o)?wi(S,e,t,r,n,o):null;if(w){const P=w.point[l];if(x?P<=i[g+u]:P>=i[g+u+3])return w}const A=Gt(g,i,r,n,o)?wi(g,e,t,r,n,o):null;return w&&A?w.distance<=A.distance?w:A:w||A||null}}const Dn=new f.Box3,br=new mt,wr=new mt,Wr=new f.Matrix4,Is=new qe,Rn=new qe;function Fc(s,e,t,r){Me.setBuffer(s._roots[e]);const n=_i(0,s,t,r);return Me.clearBuffer(),n}function _i(s,e,t,r,n=null){const{float32Array:o,uint16Array:i,uint32Array:a}=Me;let c=s*2;if(n===null&&(t.boundingBox||t.computeBoundingBox(),Is.set(t.boundingBox.min,t.boundingBox.max,r),n=Is),Ye(c,i)){const d=e.geometry,u=d.index,l=d.attributes.position,v=t.index,x=t.attributes.position,S=Xe(s,a),g=Je(c,i);if(Wr.copy(r).invert(),t.boundsTree)return Fe(s,o,Rn),Rn.matrix.copy(Wr),Rn.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:w=>Rn.intersectsBox(w),intersectsTriangle:w=>{w.a.applyMatrix4(r),w.b.applyMatrix4(r),w.c.applyMatrix4(r),w.needsUpdate=!0;for(let T=S,A=g+S;T<A;T++)if(Oe(wr,3*e.resolveTriangleIndex(T),u,l),wr.needsUpdate=!0,w.intersectsTriangle(wr))return!0;return!1}});for(let b=S,w=g+S;b<w;b++){const T=e.resolveTriangleIndex(b);Oe(br,3*T,u,l),br.a.applyMatrix4(Wr),br.b.applyMatrix4(Wr),br.c.applyMatrix4(Wr),br.needsUpdate=!0;for(let A=0,P=v.count;A<P;A+=3)if(Oe(wr,A,v,x),wr.needsUpdate=!0,br.intersectsTriangle(wr))return!0}}else{const d=s+8,u=a[s+6];return Fe(d,o,Dn),!!(n.intersectsBox(Dn)&&_i(d,e,t,r,n)||(Fe(u,o,Dn),n.intersectsBox(Dn)&&_i(u,e,t,r,n)))}}const Fn=new f.Matrix4,Si=new qe,Yr=new qe,Oc=new f.Vector3,Lc=new f.Vector3,Nc=new f.Vector3,kc=new f.Vector3;function Bc(s,e,t,r={},n={},o=0,i=1/0){e.boundingBox||e.computeBoundingBox(),Si.set(e.boundingBox.min,e.boundingBox.max,t),Si.needsUpdate=!0;const a=s.geometry,c=a.attributes.position,h=a.index,d=e.attributes.position,u=e.index,l=at.getPrimitive(),v=at.getPrimitive();let x=Oc,S=Lc,g=null,b=null;n&&(g=Nc,b=kc);let w=1/0,T=null,A=null;return Fn.copy(t).invert(),Yr.matrix.copy(Fn),s.shapecast({boundsTraverseOrder:P=>Si.distanceToBox(P),intersectsBounds:(P,D,R)=>R<w&&R<i?(D&&(Yr.min.copy(P.min),Yr.max.copy(P.max),Yr.needsUpdate=!0),!0):!1,intersectsRange:(P,D)=>{if(e.boundsTree){const R=e.boundsTree;return R.shapecast({boundsTraverseOrder:O=>Yr.distanceToBox(O),intersectsBounds:(O,L,E)=>E<w&&E<i,intersectsRange:(O,L)=>{for(let E=O,G=O+L;E<G;E++){const z=R.resolveTriangleIndex(E);Oe(v,3*z,u,d),v.a.applyMatrix4(t),v.b.applyMatrix4(t),v.c.applyMatrix4(t),v.needsUpdate=!0;for(let V=P,U=P+D;V<U;V++){const H=s.resolveTriangleIndex(V);Oe(l,3*H,h,c),l.needsUpdate=!0;const ne=l.distanceToTriangle(v,x,g);if(ne<w&&(S.copy(x),b&&b.copy(g),w=ne,T=V,A=E),ne<o)return!0}}}})}else{const R=fr(e);for(let O=0,L=R;O<L;O++){Oe(v,3*O,u,d),v.a.applyMatrix4(t),v.b.applyMatrix4(t),v.c.applyMatrix4(t),v.needsUpdate=!0;for(let E=P,G=P+D;E<G;E++){const z=s.resolveTriangleIndex(E);Oe(l,3*z,h,c),l.needsUpdate=!0;const V=l.distanceToTriangle(v,x,g);if(V<w&&(S.copy(x),b&&b.copy(g),w=V,T=E,A=O),V<o)return!0}}}}}),at.releasePrimitive(l),at.releasePrimitive(v),w===1/0?null:(r.point?r.point.copy(S):r.point=S.clone(),r.distance=w,r.faceIndex=T,n&&(n.point?n.point.copy(b):n.point=b.clone(),n.point.applyMatrix4(Fn),S.applyMatrix4(Fn),n.distance=S.sub(n.point).length(),n.faceIndex=A),r)}function zc(){return typeof SharedArrayBuffer<"u"}const qr=new Me.constructor,On=new Me.constructor,Vt=new di(()=>new f.Box3),_r=new f.Box3,Sr=new f.Box3,Ti=new f.Box3,Ai=new f.Box3;let Mi=!1;function Ec(s,e,t,r){if(Mi)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");Mi=!0;const n=s._roots,o=e._roots;let i,a=0,c=0;const h=new f.Matrix4().copy(t).invert();for(let d=0,u=n.length;d<u;d++){qr.setBuffer(n[d]),c=0;const l=Vt.getPrimitive();Fe(0,qr.float32Array,l),l.applyMatrix4(h);for(let v=0,x=o.length;v<x&&(On.setBuffer(o[v]),i=gt(0,0,t,h,r,a,c,0,0,l),On.clearBuffer(),c+=o[v].length,!i);v++);if(Vt.releasePrimitive(l),qr.clearBuffer(),a+=n[d].length,i)break}return Mi=!1,i}function gt(s,e,t,r,n,o=0,i=0,a=0,c=0,h=null,d=!1){let u,l;d?(u=On,l=qr):(u=qr,l=On);const v=u.float32Array,x=u.uint32Array,S=u.uint16Array,g=l.float32Array,b=l.uint32Array,w=l.uint16Array,T=s*2,A=e*2,P=Ye(T,S),D=Ye(A,w);let R=!1;if(D&&P)d?R=n(Xe(e,b),Je(e*2,w),Xe(s,x),Je(s*2,S),c,i+e,a,o+s):R=n(Xe(s,x),Je(s*2,S),Xe(e,b),Je(e*2,w),a,o+s,c,i+e);else if(D){const O=Vt.getPrimitive();Fe(e,g,O),O.applyMatrix4(t);const L=ot(s),E=He(s,x);Fe(L,v,_r),Fe(E,v,Sr);const G=O.intersectsBox(_r),z=O.intersectsBox(Sr);R=G&>(e,L,r,t,n,i,o,c,a+1,O,!d)||z&>(e,E,r,t,n,i,o,c,a+1,O,!d),Vt.releasePrimitive(O)}else{const O=ot(e),L=He(e,b);Fe(O,g,Ti),Fe(L,g,Ai);const E=h.intersectsBox(Ti),G=h.intersectsBox(Ai);if(E&&G)R=gt(s,O,t,r,n,o,i,a,c+1,h,d)||gt(s,L,t,r,n,o,i,a,c+1,h,d);else if(E)if(P)R=gt(s,O,t,r,n,o,i,a,c+1,h,d);else{const z=Vt.getPrimitive();z.copy(Ti).applyMatrix4(t);const V=ot(s),U=He(s,x);Fe(V,v,_r),Fe(U,v,Sr);const H=z.intersectsBox(_r),ne=z.intersectsBox(Sr);R=H&>(O,V,r,t,n,i,o,c,a+1,z,!d)||ne&>(O,U,r,t,n,i,o,c,a+1,z,!d),Vt.releasePrimitive(z)}else if(G)if(P)R=gt(s,L,t,r,n,o,i,a,c+1,h,d);else{const z=Vt.getPrimitive();z.copy(Ai).applyMatrix4(t);const V=ot(s),U=He(s,x);Fe(V,v,_r),Fe(U,v,Sr);const H=z.intersectsBox(_r),ne=z.intersectsBox(Sr);R=H&>(L,V,r,t,n,i,o,c,a+1,z,!d)||ne&>(L,U,r,t,n,i,o,c,a+1,z,!d),Vt.releasePrimitive(z)}}return R}const Ln=new qe,Cs=new f.Box3,Uc={strategy:us,maxDepth:40,maxLeafTris:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null};class Ii{static serialize(e,t={}){t={cloneBuffers:!0,...t};const r=e.geometry,n=e._roots,o=e._indirectBuffer,i=r.getIndex();let a;return t.cloneBuffers?a={roots:n.map(c=>c.slice()),index:i?i.array.slice():null,indirectBuffer:o?o.slice():null}:a={roots:n,index:i?i.array:null,indirectBuffer:o},a}static deserialize(e,t,r={}){r={setIndex:!0,indirect:!!e.indirectBuffer,...r};const{index:n,roots:o,indirectBuffer:i}=e,a=new Ii(t,{...r,[si]:!0});if(a._roots=o,a._indirectBuffer=i||null,r.setIndex){const c=t.getIndex();if(c===null){const h=new f.BufferAttribute(e.index,1,!1);t.setIndex(h)}else c.array!==n&&(c.array.set(n),c.needsUpdate=!0)}return a}get indirect(){return!!this._indirectBuffer}constructor(e,t={}){if(e.isBufferGeometry){if(e.index&&e.index.isInterleavedBufferAttribute)throw new Error("MeshBVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("MeshBVH: Only BufferGeometries are supported.");if(t=Object.assign({...Uc,[si]:!1},t),t.useSharedArrayBuffer&&!zc())throw new Error("MeshBVH: SharedArrayBuffer is not available.");this.geometry=e,this._roots=null,this._indirectBuffer=null,t[si]||(rc(this,t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new f.Box3))),this.resolveTriangleIndex=t.indirect?r=>this._indirectBuffer[r]:r=>r}refit(e=null){return(this.indirect?Cc:mc)(this,e)}traverse(e,t=0){const r=this._roots[t],n=new Uint32Array(r),o=new Uint16Array(r);i(0);function i(a,c=0){const h=a*2,d=o[h+15]===vn;if(d){const u=n[a+6],l=o[h+14];e(c,d,new Float32Array(r,a*4,6),u,l)}else{const u=a+zt/4,l=n[a+6],v=n[a+7];e(c,d,new Float32Array(r,a*4,6),v)||(i(u,c+1),i(l,c+1))}}}raycast(e,t=f.FrontSide,r=0,n=1/0){const o=this._roots,i=this.geometry,a=[],c=t.isMaterial,h=Array.isArray(t),d=i.groups,u=c?t.side:t,l=this.indirect?Pc:xc;for(let v=0,x=o.length;v<x;v++){const S=h?t[d[v].materialIndex].side:u,g=a.length;if(l(this,v,S,e,a,r,n),h){const b=d[v].materialIndex;for(let w=g,T=a.length;w<T;w++)a[w].face.materialIndex=b}}return a}raycastFirst(e,t=f.FrontSide,r=0,n=1/0){const o=this._roots,i=this.geometry,a=t.isMaterial,c=Array.isArray(t);let h=null;const d=i.groups,u=a?t.side:t,l=this.indirect?Rc:wc;for(let v=0,x=o.length;v<x;v++){const S=c?t[d[v].materialIndex].side:u,g=l(this,v,S,e,r,n);g!=null&&(h==null||g.distance<h.distance)&&(h=g,c&&(g.face.materialIndex=d[v].materialIndex))}return h}intersectsGeometry(e,t){let r=!1;const n=this._roots,o=this.indirect?Fc:_c;for(let i=0,a=n.length;i<a&&(r=o(this,i,e,t),!r);i++);return r}shapecast(e){const t=at.getPrimitive(),r=this.indirect?yc:pc;let{boundsTraverseOrder:n,intersectsBounds:o,intersectsRange:i,intersectsTriangle:a}=e;if(i&&a){const u=i;i=(l,v,x,S,g)=>u(l,v,x,S,g)?!0:r(l,v,this,a,x,S,t)}else i||(a?i=(u,l,v,x)=>r(u,l,this,a,v,x,t):i=(u,l,v)=>v);let c=!1,h=0;const d=this._roots;for(let u=0,l=d.length;u<l;u++){const v=d[u];if(c=cc(this,u,o,i,n,h),c)break;h+=v.byteLength}return at.releasePrimitive(t),c}bvhcast(e,t,r){let{intersectsRanges:n,intersectsTriangles:o}=r;const i=at.getPrimitive(),a=this.geometry.index,c=this.geometry.attributes.position,h=this.indirect?x=>{const S=this.resolveTriangleIndex(x);Oe(i,S*3,a,c)}:x=>{Oe(i,x*3,a,c)},d=at.getPrimitive(),u=e.geometry.index,l=e.geometry.attributes.position,v=e.indirect?x=>{const S=e.resolveTriangleIndex(x);Oe(d,S*3,u,l)}:x=>{Oe(d,x*3,u,l)};if(o){const x=(S,g,b,w,T,A,P,D)=>{for(let R=b,O=b+w;R<O;R++){v(R),d.a.applyMatrix4(t),d.b.applyMatrix4(t),d.c.applyMatrix4(t),d.needsUpdate=!0;for(let L=S,E=S+g;L<E;L++)if(h(L),i.needsUpdate=!0,o(i,d,L,R,T,A,P,D))return!0}return!1};if(n){const S=n;n=function(g,b,w,T,A,P,D,R){return S(g,b,w,T,A,P,D,R)?!0:x(g,b,w,T,A,P,D,R)}}else n=x}return Ec(this,e,t,n)}intersectsBox(e,t){return Ln.set(e.min,e.max,t),Ln.needsUpdate=!0,this.shapecast({intersectsBounds:r=>Ln.intersectsBox(r),intersectsTriangle:r=>Ln.intersectsTriangle(r)})}intersectsSphere(e){return this.shapecast({intersectsBounds:t=>e.intersectsBox(t),intersectsTriangle:t=>t.intersectsSphere(e)})}closestPointToGeometry(e,t,r={},n={},o=0,i=1/0){return(this.indirect?Bc:Ic)(this,e,t,r,n,o,i)}closestPointToPoint(e,t={},r=0,n=1/0){return lc(this,e,t,r,n)}getBoundingBox(e){return e.makeEmpty(),this._roots.forEach(r=>{Fe(0,new Float32Array(r),Cs),e.union(Cs)}),e}}function Gc(s){switch(s){case 1:return"R";case 2:return"RG";case 3:return"RGBA";case 4:return"RGBA"}throw new Error}function Vc(s){switch(s){case 1:return f.RedFormat;case 2:return f.RGFormat;case 3:return f.RGBAFormat;case 4:return f.RGBAFormat}}function Ps(s){switch(s){case 1:return f.RedIntegerFormat;case 2:return f.RGIntegerFormat;case 3:return f.RGBAIntegerFormat;case 4:return f.RGBAIntegerFormat}}class Ds extends f.DataTexture{constructor(){super(),this.minFilter=f.NearestFilter,this.magFilter=f.NearestFilter,this.generateMipmaps=!1,this.overrideItemSize=null,this._forcedType=null}updateFrom(e){const t=this.overrideItemSize,r=e.itemSize,n=e.count;if(t!==null){if(r*n%t!==0)throw new Error("VertexAttributeTexture: overrideItemSize must divide evenly into buffer length.");e.itemSize=t,e.count=n*r/t}const o=e.itemSize,i=e.count,a=e.normalized,c=e.array.constructor,h=c.BYTES_PER_ELEMENT;let d=this._forcedType,u=o;if(d===null)switch(c){case Float32Array:d=f.FloatType;break;case Uint8Array:case Uint16Array:case Uint32Array:d=f.UnsignedIntType;break;case Int8Array:case Int16Array:case Int32Array:d=f.IntType;break}let l,v,x,S,g=Gc(o);switch(d){case f.FloatType:x=1,v=Vc(o),a&&h===1?(S=c,g+="8",c===Uint8Array?l=f.UnsignedByteType:(l=f.ByteType,g+="_SNORM")):(S=Float32Array,g+="32F",l=f.FloatType);break;case f.IntType:g+=h*8+"I",x=a?Math.pow(2,c.BYTES_PER_ELEMENT*8-1):1,v=Ps(o),h===1?(S=Int8Array,l=f.ByteType):h===2?(S=Int16Array,l=f.ShortType):(S=Int32Array,l=f.IntType);break;case f.UnsignedIntType:g+=h*8+"UI",x=a?Math.pow(2,c.BYTES_PER_ELEMENT*8-1):1,v=Ps(o),h===1?(S=Uint8Array,l=f.UnsignedByteType):h===2?(S=Uint16Array,l=f.UnsignedShortType):(S=Uint32Array,l=f.UnsignedIntType);break}u===3&&(v===f.RGBAFormat||v===f.RGBAIntegerFormat)&&(u=4);const b=Math.ceil(Math.sqrt(i))||1,w=u*b*b,T=new S(w),A=e.normalized;e.normalized=!1;for(let P=0;P<i;P++){const D=u*P;T[D]=e.getX(P)/x,o>=2&&(T[D+1]=e.getY(P)/x),o>=3&&(T[D+2]=e.getZ(P)/x,u===4&&(T[D+3]=1)),o>=4&&(T[D+3]=e.getW(P)/x)}e.normalized=A,this.internalFormat=g,this.format=v,this.type=l,this.image.width=b,this.image.height=b,this.image.data=T,this.needsUpdate=!0,this.dispose(),e.itemSize=r,e.count=n}}class Rs extends Ds{constructor(){super(),this._forcedType=f.UnsignedIntType}}class Fs extends Ds{constructor(){super(),this._forcedType=f.FloatType}}class jc{constructor(){this.index=new Rs,this.position=new Fs,this.bvhBounds=new f.DataTexture,this.bvhContents=new f.DataTexture,this._cachedIndexAttr=null,this.index.overrideItemSize=3}updateFrom(e){const{geometry:t}=e;if(Yc(e,this.bvhBounds,this.bvhContents),this.position.updateFrom(t.attributes.position),e.indirect){const r=e._indirectBuffer;if(this._cachedIndexAttr===null||this._cachedIndexAttr.count!==r.length)if(t.index)this._cachedIndexAttr=t.index.clone();else{const n=ms(ps(t));this._cachedIndexAttr=new f.BufferAttribute(n,1,!1)}Wc(t,r,this._cachedIndexAttr),this.index.updateFrom(this._cachedIndexAttr)}else this.index.updateFrom(t.index)}dispose(){const{index:e,position:t,bvhBounds:r,bvhContents:n}=this;e&&e.dispose(),t&&t.dispose(),r&&r.dispose(),n&&n.dispose()}}function Wc(s,e,t){const r=t.array,n=s.index?s.index.array:null;for(let o=0,i=e.length;o<i;o++){const a=3*o,c=3*e[o];for(let h=0;h<3;h++)r[a+h]=n?n[c+h]:c+h}}function Yc(s,e,t){const r=s._roots;if(r.length!==1)throw new Error("MeshBVHUniformStruct: Multi-root BVHs not supported.");const n=r[0],o=new Uint16Array(n),i=new Uint32Array(n),a=new Float32Array(n),c=n.byteLength/zt,h=2*Math.ceil(Math.sqrt(c/2)),d=new Float32Array(4*h*h),u=Math.ceil(Math.sqrt(c)),l=new Uint32Array(2*u*u);for(let v=0;v<c;v++){const x=v*zt/4,S=x*2,g=x;for(let b=0;b<3;b++)d[8*v+0+b]=a[g+0+b],d[8*v+4+b]=a[g+3+b];if(Ye(S,o)){const b=Je(S,o),w=Xe(x,i),T=4294901760|b;l[v*2+0]=T,l[v*2+1]=w}else{const b=4*He(x,i)/zt,w=ci(x,i);l[v*2+0]=w,l[v*2+1]=b}}e.image.data=d,e.image.width=h,e.image.height=h,e.format=f.RGBAFormat,e.type=f.FloatType,e.internalFormat="RGBA32F",e.minFilter=f.NearestFilter,e.magFilter=f.NearestFilter,e.generateMipmaps=!1,e.needsUpdate=!0,e.dispose(),t.image.data=l,t.image.width=u,t.image.height=u,t.format=f.RGIntegerFormat,t.type=f.UnsignedIntType,t.internalFormat="RG32UI",t.minFilter=f.NearestFilter,t.magFilter=f.NearestFilter,t.generateMipmaps=!1,t.needsUpdate=!0,t.dispose()}const qc=`
|
|
31
31
|
|
|
32
32
|
// A stack of uint32 indices can can store the indices for
|
|
33
33
|
// a perfectly balanced tree with a depth up to 31. Lower stack
|
|
@@ -109,7 +109,7 @@ void ndcToCameraRay(
|
|
|
109
109
|
rayDirection = direction.xyz;
|
|
110
110
|
|
|
111
111
|
}
|
|
112
|
-
`,
|
|
112
|
+
`,Zc=`
|
|
113
113
|
|
|
114
114
|
#ifndef TRI_INTERSECT_EPSILON
|
|
115
115
|
#define TRI_INTERSECT_EPSILON 1e-5
|
|
@@ -313,7 +313,7 @@ bool _bvhIntersectFirstHit(
|
|
|
313
313
|
return found;
|
|
314
314
|
|
|
315
315
|
}
|
|
316
|
-
`,
|
|
316
|
+
`,Kc=`
|
|
317
317
|
struct BVH {
|
|
318
318
|
|
|
319
319
|
usampler2D index;
|
|
@@ -323,7 +323,7 @@ struct BVH {
|
|
|
323
323
|
usampler2D bvhContents;
|
|
324
324
|
|
|
325
325
|
};
|
|
326
|
-
`;function Os(s,e,t=0){if(s.isInterleavedBufferAttribute){const r=s.itemSize;for(let n=0,o=s.count;n<o;n++){const i=n+t;e.setX(i,s.getX(n)),r>=2&&e.setY(i,s.getY(n)),r>=3&&e.setZ(i,s.getZ(n)),r>=4&&e.setW(i,s.getW(n))}}else{const r=e.array,n=r.constructor,o=r.BYTES_PER_ELEMENT*s.itemSize*t;new n(r.buffer,o,s.array.length).set(s.array)}}function Zr(s,e=null){const t=s.array.constructor,r=s.normalized,n=s.itemSize,o=e===null?s.count:e;return new f.BufferAttribute(new t(n*o),n,r)}function Tr(s,e){if(!s&&!e)return!0;if(!!s!=!!e)return!1;const t=s.count===e.count,r=s.normalized===e.normalized,n=s.array.constructor===e.array.constructor,o=s.itemSize===e.itemSize;return!(!t||!r||!n||!o)}function Kc(s){const e=s[0].index!==null,t=new Set(Object.keys(s[0].attributes));if(!s[0].getAttribute("position"))throw new Error("StaticGeometryGenerator: position attribute is required.");for(let r=0;r<s.length;++r){const n=s[r];let o=0;if(e!==(n.index!==null))throw new Error("StaticGeometryGenerator: All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.");for(const i in n.attributes){if(!t.has(i))throw new Error('StaticGeometryGenerator: All geometries must have compatible attributes; make sure "'+i+'" attribute exists among all geometries, or in none of them.');o++}if(o!==t.size)throw new Error("StaticGeometryGenerator: All geometries must have the same number of attributes.")}}function Xc(s){let e=0;for(let t=0,r=s.length;t<r;t++)e+=s[t].getIndex().count;return e}function $c(s){let e=0;for(let t=0,r=s.length;t<r;t++)e+=s[t].getAttribute("position").count;return e}function Qc(s,e,t){s.index&&s.index.count!==e&&s.setIndex(null);const r=s.attributes;for(const n in r)r[n].count!==t&&s.deleteAttribute(n)}function Jc(s,e={},t=new f.BufferGeometry){const{useGroups:r=!1,forceUpdate:n=!1,skipAssigningAttributes:o=[],overwriteIndex:i=!0}=e;Kc(s);const a=s[0].index!==null,c=a?Xc(s):-1,h=$c(s);if(Qc(t,c,h),r){let u=0;for(let l=0,v=s.length;l<v;l++){const b=s[l];let S;a?S=b.getIndex().count:S=b.getAttribute("position").count,t.addGroup(u,S,l),u+=S}}if(a){let u=!1;if(t.index||(t.setIndex(new f.BufferAttribute(new Uint32Array(c),1,!1)),u=!0),u||i){let l=0,v=0;const b=t.getIndex();for(let S=0,g=s.length;S<g;S++){const x=s[S],w=x.getIndex();if(!(!n&&!u&&o[S]))for(let A=0;A<w.count;++A)b.setX(l+A,w.getX(A)+v);l+=w.count,v+=x.getAttribute("position").count}}}const d=Object.keys(s[0].attributes);for(let u=0,l=d.length;u<l;u++){let v=!1;const b=d[u];if(!t.getAttribute(b)){const x=s[0].getAttribute(b);t.setAttribute(b,Zr(x,h)),v=!0}let S=0;const g=t.getAttribute(b);for(let x=0,w=s.length;x<w;x++){const T=s[x],A=!n&&!v&&o[x],P=T.getAttribute(b);A||Os(P,g,S),S+=P.count}}}function Hc(s,e,t){const r=s.index,o=s.attributes.position.count,i=r?r.count:o;let a=s.groups;a.length===0&&(a=[{count:i,start:0,materialIndex:0}]);let c=s.getAttribute("materialIndex");if(!c||c.count!==o){let d;t.length<=255?d=new Uint8Array(o):d=new Uint16Array(o),c=new f.BufferAttribute(d,1,!1),s.deleteAttribute("materialIndex"),s.setAttribute("materialIndex",c)}const h=c.array;for(let d=0;d<a.length;d++){const u=a[d],l=u.start,v=u.count,b=Math.min(v,i-l),S=Array.isArray(e)?e[u.materialIndex]:e,g=t.indexOf(S);for(let x=0;x<b;x++){let w=l+x;r&&(w=r.getX(w)),h[w]=g}}}function el(s,e){if(!s.index){const t=s.attributes.position.count,r=new Array(t);for(let n=0;n<t;n++)r[n]=n;s.setIndex(r)}if(!s.attributes.normal&&e&&e.includes("normal")&&s.computeVertexNormals(),!s.attributes.uv&&e&&e.includes("uv")){const t=s.attributes.position.count;s.setAttribute("uv",new f.BufferAttribute(new Float32Array(t*2),2,!1))}if(!s.attributes.uv2&&e&&e.includes("uv2")){const t=s.attributes.position.count;s.setAttribute("uv2",new f.BufferAttribute(new Float32Array(t*2),2,!1))}if(!s.attributes.tangent&&e&&e.includes("tangent"))if(s.attributes.uv&&s.attributes.normal)s.computeTangents();else{const t=s.attributes.position.count;s.setAttribute("tangent",new f.BufferAttribute(new Float32Array(t*4),4,!1))}if(!s.attributes.color&&e&&e.includes("color")){const t=s.attributes.position.count,r=new Float32Array(t*4);r.fill(1),s.setAttribute("color",new f.BufferAttribute(r,4))}}function Ci(s){let e=0;if(s.byteLength!==0){const t=new Uint8Array(s);for(let r=0;r<s.byteLength;r++){const n=t[r];e=(e<<5)-e+n,e|=0}}return e}function Ls(s){let e=s.uuid;const t=Object.values(s.attributes);s.index&&(t.push(s.index),e+=`index|${s.index.version}`);const r=Object.keys(t).sort();for(const n of r){const o=t[n];e+=`${n}_${o.version}|`}return e}function Ns(s){const e=s.skeleton;return e?(e.boneTexture||e.computeBoneTexture(),`${Ci(e.boneTexture.image.data.buffer)}_${e.boneTexture.uuid}`):null}class tl{constructor(e=null){this.matrixWorld=new f.Matrix4,this.geometryHash=null,this.skeletonHash=null,this.primitiveCount=-1,e!==null&&this.updateFrom(e)}updateFrom(e){const t=e.geometry,r=(t.index?t.index.count:t.attributes.position.count)/3;this.matrixWorld.copy(e.matrixWorld),this.geometryHash=Ls(t),this.primitiveCount=r,this.skeletonHash=Ns(e)}didChange(e){const t=e.geometry,r=(t.index?t.index.count:t.attributes.position.count)/3;return!(this.matrixWorld.equals(e.matrixWorld)&&this.geometryHash===Ls(t)&&this.skeletonHash===Ns(e)&&this.primitiveCount===r)}}const Kt=new f.Vector3,Xt=new f.Vector3,$t=new f.Vector3,ks=new f.Vector4,Nn=new f.Vector3,Pi=new f.Vector3,Bs=new f.Vector4,zs=new f.Vector4,kn=new f.Matrix4,Es=new f.Matrix4;function Us(s,e,t){const r=s.skeleton,n=s.geometry,o=r.bones,i=r.boneInverses;Bs.fromBufferAttribute(n.attributes.skinIndex,e),zs.fromBufferAttribute(n.attributes.skinWeight,e),kn.elements.fill(0);for(let a=0;a<4;a++){const c=zs.getComponent(a);if(c!==0){const h=Bs.getComponent(a);Es.multiplyMatrices(o[h].matrixWorld,i[h]),rl(kn,Es,c)}}return kn.multiply(s.bindMatrix).premultiply(s.bindMatrixInverse),t.transformDirection(kn),t}function Di(s,e,t,r,n){Nn.set(0,0,0);for(let o=0,i=s.length;o<i;o++){const a=e[o],c=s[o];a!==0&&(Pi.fromBufferAttribute(c,r),t?Nn.addScaledVector(Pi,a):Nn.addScaledVector(Pi.sub(n),a))}n.add(Nn)}function rl(s,e,t){const r=s.elements,n=e.elements;for(let o=0,i=n.length;o<i;o++)r[o]+=n[o]*t}function nl(s){const{index:e,attributes:t}=s;if(e)for(let r=0,n=e.count;r<n;r+=3){const o=e.getX(r),i=e.getX(r+2);e.setX(r,i),e.setX(r+2,o)}else for(const r in t){const n=t[r],o=n.itemSize;for(let i=0,a=n.count;i<a;i+=3)for(let c=0;c<o;c++){const h=n.getComponent(i,c),d=n.getComponent(i+2,c);n.setComponent(i,c,d),n.setComponent(i+2,c,h)}}return s}function il(s,e={},t=new f.BufferGeometry){e={applyWorldTransforms:!0,attributes:[],...e};const r=s.geometry,n=e.applyWorldTransforms,o=e.attributes.includes("normal"),i=e.attributes.includes("tangent"),a=r.attributes,c=t.attributes;for(const w in t.attributes)(!e.attributes.includes(w)||!(w in r.attributes))&&t.deleteAttribute(w);!t.index&&r.index&&(t.index=r.index.clone()),c.position||t.setAttribute("position",Zr(a.position)),o&&!c.normal&&a.normal&&t.setAttribute("normal",Zr(a.normal)),i&&!c.tangent&&a.tangent&&t.setAttribute("tangent",Zr(a.tangent)),Tr(r.index,t.index),Tr(a.position,c.position),o&&Tr(a.normal,c.normal),i&&Tr(a.tangent,c.tangent);const h=a.position,d=o?a.normal:null,u=i?a.tangent:null,l=r.morphAttributes.position,v=r.morphAttributes.normal,b=r.morphAttributes.tangent,S=r.morphTargetsRelative,g=s.morphTargetInfluences,x=new f.Matrix3;x.getNormalMatrix(s.matrixWorld),r.index&&t.index.array.set(r.index.array);for(let w=0,T=a.position.count;w<T;w++)Kt.fromBufferAttribute(h,w),d&&Xt.fromBufferAttribute(d,w),u&&(ks.fromBufferAttribute(u,w),$t.fromBufferAttribute(u,w)),g&&(l&&Di(l,g,S,w,Kt),v&&Di(v,g,S,w,Xt),b&&Di(b,g,S,w,$t)),s.isSkinnedMesh&&(s.applyBoneTransform(w,Kt),d&&Us(s,w,Xt),u&&Us(s,w,$t)),n&&Kt.applyMatrix4(s.matrixWorld),c.position.setXYZ(w,Kt.x,Kt.y,Kt.z),d&&(n&&Xt.applyNormalMatrix(x),c.normal.setXYZ(w,Xt.x,Xt.y,Xt.z)),u&&(n&&$t.transformDirection(s.matrixWorld),c.tangent.setXYZW(w,$t.x,$t.y,$t.z,ks.w));for(const w in e.attributes){const T=e.attributes[w];T==="position"||T==="tangent"||T==="normal"||!(T in a)||(c[T]||t.setAttribute(T,Zr(a[T])),Tr(a[T],c[T]),Os(a[T],c[T]))}return s.matrixWorld.determinant()<0&&nl(t),t}class sl extends f.BufferGeometry{constructor(){super(),this.version=0,this.hash=null,this._diff=new tl}isCompatible(e,t){const r=e.geometry;for(let n=0;n<t.length;n++){const o=t[n],i=r.attributes[o],a=this.attributes[o];if(i&&!Tr(i,a))return!1}return!0}updateFrom(e,t){const r=this._diff;return r.didChange(e)?(il(e,t,this),r.updateFrom(e),this.version++,this.hash=`${this.uuid}_${this.version}`,!0):!1}}const Ri=0,Gs=1,Vs=2;function ol(s,e){for(let t=0,r=s.length;t<r;t++)s[t].traverseVisible(o=>{o.isMesh&&e(o)})}function al(s){const e=[];for(let t=0,r=s.length;t<r;t++){const n=s[t];Array.isArray(n.material)?e.push(...n.material):e.push(n.material)}return e}function cl(s,e,t){if(s.length===0){e.setIndex(null);const r=e.attributes;for(const n in r)e.deleteAttribute(n);for(const n in t.attributes)e.setAttribute(t.attributes[n],new f.BufferAttribute(new Float32Array(0),4,!1))}else Jc(s,t,e);for(const r in e.attributes)e.attributes[r].needsUpdate=!0}class ll{constructor(e){this.objects=null,this.useGroups=!0,this.applyWorldTransforms=!0,this.generateMissingAttributes=!0,this.overwriteIndex=!0,this.attributes=["position","normal","color","tangent","uv","uv2"],this._intermediateGeometry=new Map,this._geometryMergeSets=new WeakMap,this._mergeOrder=[],this._dummyMesh=null,this.setObjects(e||[])}_getDummyMesh(){if(!this._dummyMesh){const e=new f.MeshBasicMaterial,t=new f.BufferGeometry;t.setAttribute("position",new f.BufferAttribute(new Float32Array(9),3)),this._dummyMesh=new f.Mesh(t,e)}return this._dummyMesh}_getMeshes(){const e=[];return ol(this.objects,t=>{e.push(t)}),e.sort((t,r)=>t.uuid>r.uuid?1:t.uuid<r.uuid?-1:0),e.length===0&&e.push(this._getDummyMesh()),e}_updateIntermediateGeometries(){const{_intermediateGeometry:e}=this,t=this._getMeshes(),r=new Set(e.keys()),n={attributes:this.attributes,applyWorldTransforms:this.applyWorldTransforms};for(let o=0,i=t.length;o<i;o++){const a=t[o],c=a.uuid;r.delete(c);let h=e.get(c);(!h||!h.isCompatible(a,this.attributes))&&(h&&h.dispose(),h=new sl,e.set(c,h)),h.updateFrom(a,n)&&this.generateMissingAttributes&&el(h,this.attributes)}r.forEach(o=>{e.delete(o)})}setObjects(e){Array.isArray(e)?this.objects=[...e]:this.objects=[e]}generate(e=new f.BufferGeometry){const{useGroups:t,overwriteIndex:r,_intermediateGeometry:n,_geometryMergeSets:o}=this,i=this._getMeshes(),a=[],c=[],h=o.get(e)||[];this._updateIntermediateGeometries();let d=!1;i.length!==h.length&&(d=!0);for(let l=0,v=i.length;l<v;l++){const b=i[l],S=n.get(b.uuid);c.push(S);const g=h[l];!g||g.uuid!==S.uuid?(a.push(!1),d=!0):g.version!==S.version?a.push(!1):a.push(!0)}cl(c,e,{useGroups:t,forceUpdate:d,skipAssigningAttributes:a,overwriteIndex:r}),d&&e.dispose(),o.set(e,c.map(l=>({version:l.version,uuid:l.uuid})));let u=Ri;return d?u=Vs:a.includes(!1)&&(u=Gs),{changeType:u,materials:al(i),geometry:e}}}function ul(s){const e=new Set;for(let t=0,r=s.length;t<r;t++){const n=s[t];for(const o in n){const i=n[o];i&&i.isTexture&&e.add(i)}}return Array.from(e)}function hl(s){const e=[],t=new Set;for(let n=0,o=s.length;n<o;n++)s[n].traverse(i=>{i.visible&&(i.isRectAreaLight||i.isSpotLight||i.isPointLight||i.isDirectionalLight)&&(e.push(i),i.iesMap&&t.add(i.iesMap))});const r=Array.from(t).sort((n,o)=>n.uuid<o.uuid?1:n.uuid>o.uuid?-1:0);return{lights:e,iesTextures:r}}class fl{get initialized(){return!!this.bvh}constructor(e){this.bvhOptions={},this.attributes=["position","normal","tangent","color","uv","uv2"],this.generateBVH=!0,this.bvh=null,this.geometry=new f.BufferGeometry,this.staticGeometryGenerator=new ll(e),this._bvhWorker=null,this._pendingGenerate=null,this._buildAsync=!1}setObjects(e){this.staticGeometryGenerator.setObjects(e)}setBVHWorker(e){this._bvhWorker=e}async generateAsync(e=null){if(!this._bvhWorker)throw new Error('PathTracingSceneGenerator: "setBVHWorker" must be called before "generateAsync" can be called.');if(this.bvh instanceof Promise)return this._pendingGenerate||(this._pendingGenerate=new Promise(async()=>(await this.bvh,this._pendingGenerate=null,this.generateAsync(e)))),this._pendingGenerate;{this._buildAsync=!0;const t=this.generate(e);return this._buildAsync=!1,t.bvh=this.bvh=await t.bvh,t}}generate(e=null){const{staticGeometryGenerator:t,geometry:r,attributes:n}=this,o=t.objects;t.attributes=n,o.forEach(u=>{u.traverse(l=>{l.isSkinnedMesh&&l.skeleton&&l.skeleton.update()})});const i=t.generate(r),a=i.materials,c=ul(a),{lights:h,iesTextures:d}=hl(o);if(i.changeType!==Ri&&Hc(r,a,a),this.generateBVH){if(this.bvh instanceof Promise)throw new Error("PathTracingSceneGenerator: BVH is already building asynchronously.");if(i.changeType===Vs){const u={strategy:hs,maxLeafTris:1,indirect:!0,onProgress:e,...this.bvhOptions};this._buildAsync?this.bvh=this._bvhWorker.generate(r,u):this.bvh=new Ii(r,u)}else i.changeType===Gs&&this.bvh.refit()}return{bvhChanged:i.changeType!==Ri,bvh:this.bvh,lights:h,iesTextures:d,geometry:r,materials:a,textures:c,objects:o}}}const dl=new f.OrthographicCamera(-1,1,1,-1,0,1);class pl extends f.BufferGeometry{constructor(){super(),this.setAttribute("position",new f.Float32BufferAttribute([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new f.Float32BufferAttribute([0,2,0,0,2,0],2))}}const ml=new pl;class Ar{constructor(e){this._mesh=new f.Mesh(ml,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,dl)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class Fi extends f.ShaderMaterial{set needsUpdate(e){super.needsUpdate=!0,this.dispatchEvent({type:"recompilation"})}constructor(e){super(e);for(const t in this.uniforms)Object.defineProperty(this,t,{get(){return this.uniforms[t].value},set(r){this.uniforms[t].value=r}})}setDefine(e,t=void 0){if(t==null){if(e in this.defines)return delete this.defines[e],this.needsUpdate=!0,!0}else if(this.defines[e]!==t)return this.defines[e]=t,this.needsUpdate=!0,!0;return!1}}class gl extends Fi{constructor(e){super({blending:f.NoBlending,uniforms:{target1:{value:null},target2:{value:null},opacity:{value:1}},vertexShader:`
|
|
326
|
+
`;function Os(s,e,t=0){if(s.isInterleavedBufferAttribute){const r=s.itemSize;for(let n=0,o=s.count;n<o;n++){const i=n+t;e.setX(i,s.getX(n)),r>=2&&e.setY(i,s.getY(n)),r>=3&&e.setZ(i,s.getZ(n)),r>=4&&e.setW(i,s.getW(n))}}else{const r=e.array,n=r.constructor,o=r.BYTES_PER_ELEMENT*s.itemSize*t;new n(r.buffer,o,s.array.length).set(s.array)}}function Zr(s,e=null){const t=s.array.constructor,r=s.normalized,n=s.itemSize,o=e===null?s.count:e;return new f.BufferAttribute(new t(n*o),n,r)}function Tr(s,e){if(!s&&!e)return!0;if(!!s!=!!e)return!1;const t=s.count===e.count,r=s.normalized===e.normalized,n=s.array.constructor===e.array.constructor,o=s.itemSize===e.itemSize;return!(!t||!r||!n||!o)}function Xc(s){const e=s[0].index!==null,t=new Set(Object.keys(s[0].attributes));if(!s[0].getAttribute("position"))throw new Error("StaticGeometryGenerator: position attribute is required.");for(let r=0;r<s.length;++r){const n=s[r];let o=0;if(e!==(n.index!==null))throw new Error("StaticGeometryGenerator: All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.");for(const i in n.attributes){if(!t.has(i))throw new Error('StaticGeometryGenerator: All geometries must have compatible attributes; make sure "'+i+'" attribute exists among all geometries, or in none of them.');o++}if(o!==t.size)throw new Error("StaticGeometryGenerator: All geometries must have the same number of attributes.")}}function $c(s){let e=0;for(let t=0,r=s.length;t<r;t++)e+=s[t].getIndex().count;return e}function Qc(s){let e=0;for(let t=0,r=s.length;t<r;t++)e+=s[t].getAttribute("position").count;return e}function Jc(s,e,t){s.index&&s.index.count!==e&&s.setIndex(null);const r=s.attributes;for(const n in r)r[n].count!==t&&s.deleteAttribute(n)}function Hc(s,e={},t=new f.BufferGeometry){const{useGroups:r=!1,forceUpdate:n=!1,skipAssigningAttributes:o=[],overwriteIndex:i=!0}=e;Xc(s);const a=s[0].index!==null,c=a?$c(s):-1,h=Qc(s);if(Jc(t,c,h),r){let u=0;for(let l=0,v=s.length;l<v;l++){const x=s[l];let S;a?S=x.getIndex().count:S=x.getAttribute("position").count,t.addGroup(u,S,l),u+=S}}if(a){let u=!1;if(t.index||(t.setIndex(new f.BufferAttribute(new Uint32Array(c),1,!1)),u=!0),u||i){let l=0,v=0;const x=t.getIndex();for(let S=0,g=s.length;S<g;S++){const b=s[S],w=b.getIndex();if(!(!n&&!u&&o[S]))for(let A=0;A<w.count;++A)x.setX(l+A,w.getX(A)+v);l+=w.count,v+=b.getAttribute("position").count}}}const d=Object.keys(s[0].attributes);for(let u=0,l=d.length;u<l;u++){let v=!1;const x=d[u];if(!t.getAttribute(x)){const b=s[0].getAttribute(x);t.setAttribute(x,Zr(b,h)),v=!0}let S=0;const g=t.getAttribute(x);for(let b=0,w=s.length;b<w;b++){const T=s[b],A=!n&&!v&&o[b],P=T.getAttribute(x);A||Os(P,g,S),S+=P.count}}}function el(s,e,t){const r=s.index,o=s.attributes.position.count,i=r?r.count:o;let a=s.groups;a.length===0&&(a=[{count:i,start:0,materialIndex:0}]);let c=s.getAttribute("materialIndex");if(!c||c.count!==o){let d;t.length<=255?d=new Uint8Array(o):d=new Uint16Array(o),c=new f.BufferAttribute(d,1,!1),s.deleteAttribute("materialIndex"),s.setAttribute("materialIndex",c)}const h=c.array;for(let d=0;d<a.length;d++){const u=a[d],l=u.start,v=u.count,x=Math.min(v,i-l),S=Array.isArray(e)?e[u.materialIndex]:e,g=t.indexOf(S);for(let b=0;b<x;b++){let w=l+b;r&&(w=r.getX(w)),h[w]=g}}}function tl(s,e){if(!s.index){const t=s.attributes.position.count,r=new Array(t);for(let n=0;n<t;n++)r[n]=n;s.setIndex(r)}if(!s.attributes.normal&&e&&e.includes("normal")&&s.computeVertexNormals(),!s.attributes.uv&&e&&e.includes("uv")){const t=s.attributes.position.count;s.setAttribute("uv",new f.BufferAttribute(new Float32Array(t*2),2,!1))}if(!s.attributes.uv2&&e&&e.includes("uv2")){const t=s.attributes.position.count;s.setAttribute("uv2",new f.BufferAttribute(new Float32Array(t*2),2,!1))}if(!s.attributes.tangent&&e&&e.includes("tangent"))if(s.attributes.uv&&s.attributes.normal)s.computeTangents();else{const t=s.attributes.position.count;s.setAttribute("tangent",new f.BufferAttribute(new Float32Array(t*4),4,!1))}if(!s.attributes.color&&e&&e.includes("color")){const t=s.attributes.position.count,r=new Float32Array(t*4);r.fill(1),s.setAttribute("color",new f.BufferAttribute(r,4))}}function Ci(s){let e=0;if(s.byteLength!==0){const t=new Uint8Array(s);for(let r=0;r<s.byteLength;r++){const n=t[r];e=(e<<5)-e+n,e|=0}}return e}function Ls(s){let e=s.uuid;const t=Object.values(s.attributes);s.index&&(t.push(s.index),e+=`index|${s.index.version}`);const r=Object.keys(t).sort();for(const n of r){const o=t[n];e+=`${n}_${o.version}|`}return e}function Ns(s){const e=s.skeleton;return e?(e.boneTexture||e.computeBoneTexture(),`${Ci(e.boneTexture.image.data.buffer)}_${e.boneTexture.uuid}`):null}class rl{constructor(e=null){this.matrixWorld=new f.Matrix4,this.geometryHash=null,this.skeletonHash=null,this.primitiveCount=-1,e!==null&&this.updateFrom(e)}updateFrom(e){const t=e.geometry,r=(t.index?t.index.count:t.attributes.position.count)/3;this.matrixWorld.copy(e.matrixWorld),this.geometryHash=Ls(t),this.primitiveCount=r,this.skeletonHash=Ns(e)}didChange(e){const t=e.geometry,r=(t.index?t.index.count:t.attributes.position.count)/3;return!(this.matrixWorld.equals(e.matrixWorld)&&this.geometryHash===Ls(t)&&this.skeletonHash===Ns(e)&&this.primitiveCount===r)}}const Kt=new f.Vector3,Xt=new f.Vector3,$t=new f.Vector3,ks=new f.Vector4,Nn=new f.Vector3,Pi=new f.Vector3,Bs=new f.Vector4,zs=new f.Vector4,kn=new f.Matrix4,Es=new f.Matrix4;function Us(s,e,t){const r=s.skeleton,n=s.geometry,o=r.bones,i=r.boneInverses;Bs.fromBufferAttribute(n.attributes.skinIndex,e),zs.fromBufferAttribute(n.attributes.skinWeight,e),kn.elements.fill(0);for(let a=0;a<4;a++){const c=zs.getComponent(a);if(c!==0){const h=Bs.getComponent(a);Es.multiplyMatrices(o[h].matrixWorld,i[h]),nl(kn,Es,c)}}return kn.multiply(s.bindMatrix).premultiply(s.bindMatrixInverse),t.transformDirection(kn),t}function Di(s,e,t,r,n){Nn.set(0,0,0);for(let o=0,i=s.length;o<i;o++){const a=e[o],c=s[o];a!==0&&(Pi.fromBufferAttribute(c,r),t?Nn.addScaledVector(Pi,a):Nn.addScaledVector(Pi.sub(n),a))}n.add(Nn)}function nl(s,e,t){const r=s.elements,n=e.elements;for(let o=0,i=n.length;o<i;o++)r[o]+=n[o]*t}function il(s){const{index:e,attributes:t}=s;if(e)for(let r=0,n=e.count;r<n;r+=3){const o=e.getX(r),i=e.getX(r+2);e.setX(r,i),e.setX(r+2,o)}else for(const r in t){const n=t[r],o=n.itemSize;for(let i=0,a=n.count;i<a;i+=3)for(let c=0;c<o;c++){const h=n.getComponent(i,c),d=n.getComponent(i+2,c);n.setComponent(i,c,d),n.setComponent(i+2,c,h)}}return s}function sl(s,e={},t=new f.BufferGeometry){e={applyWorldTransforms:!0,attributes:[],...e};const r=s.geometry,n=e.applyWorldTransforms,o=e.attributes.includes("normal"),i=e.attributes.includes("tangent"),a=r.attributes,c=t.attributes;for(const w in t.attributes)(!e.attributes.includes(w)||!(w in r.attributes))&&t.deleteAttribute(w);!t.index&&r.index&&(t.index=r.index.clone()),c.position||t.setAttribute("position",Zr(a.position)),o&&!c.normal&&a.normal&&t.setAttribute("normal",Zr(a.normal)),i&&!c.tangent&&a.tangent&&t.setAttribute("tangent",Zr(a.tangent)),Tr(r.index,t.index),Tr(a.position,c.position),o&&Tr(a.normal,c.normal),i&&Tr(a.tangent,c.tangent);const h=a.position,d=o?a.normal:null,u=i?a.tangent:null,l=r.morphAttributes.position,v=r.morphAttributes.normal,x=r.morphAttributes.tangent,S=r.morphTargetsRelative,g=s.morphTargetInfluences,b=new f.Matrix3;b.getNormalMatrix(s.matrixWorld),r.index&&t.index.array.set(r.index.array);for(let w=0,T=a.position.count;w<T;w++)Kt.fromBufferAttribute(h,w),d&&Xt.fromBufferAttribute(d,w),u&&(ks.fromBufferAttribute(u,w),$t.fromBufferAttribute(u,w)),g&&(l&&Di(l,g,S,w,Kt),v&&Di(v,g,S,w,Xt),x&&Di(x,g,S,w,$t)),s.isSkinnedMesh&&(s.applyBoneTransform(w,Kt),d&&Us(s,w,Xt),u&&Us(s,w,$t)),n&&Kt.applyMatrix4(s.matrixWorld),c.position.setXYZ(w,Kt.x,Kt.y,Kt.z),d&&(n&&Xt.applyNormalMatrix(b),c.normal.setXYZ(w,Xt.x,Xt.y,Xt.z)),u&&(n&&$t.transformDirection(s.matrixWorld),c.tangent.setXYZW(w,$t.x,$t.y,$t.z,ks.w));for(const w in e.attributes){const T=e.attributes[w];T==="position"||T==="tangent"||T==="normal"||!(T in a)||(c[T]||t.setAttribute(T,Zr(a[T])),Tr(a[T],c[T]),Os(a[T],c[T]))}return s.matrixWorld.determinant()<0&&il(t),t}class ol extends f.BufferGeometry{constructor(){super(),this.version=0,this.hash=null,this._diff=new rl}isCompatible(e,t){const r=e.geometry;for(let n=0;n<t.length;n++){const o=t[n],i=r.attributes[o],a=this.attributes[o];if(i&&!Tr(i,a))return!1}return!0}updateFrom(e,t){const r=this._diff;return r.didChange(e)?(sl(e,t,this),r.updateFrom(e),this.version++,this.hash=`${this.uuid}_${this.version}`,!0):!1}}const Ri=0,Gs=1,Vs=2;function al(s,e){for(let t=0,r=s.length;t<r;t++)s[t].traverseVisible(o=>{o.isMesh&&e(o)})}function cl(s){const e=[];for(let t=0,r=s.length;t<r;t++){const n=s[t];Array.isArray(n.material)?e.push(...n.material):e.push(n.material)}return e}function ll(s,e,t){if(s.length===0){e.setIndex(null);const r=e.attributes;for(const n in r)e.deleteAttribute(n);for(const n in t.attributes)e.setAttribute(t.attributes[n],new f.BufferAttribute(new Float32Array(0),4,!1))}else Hc(s,t,e);for(const r in e.attributes)e.attributes[r].needsUpdate=!0}class ul{constructor(e){this.objects=null,this.useGroups=!0,this.applyWorldTransforms=!0,this.generateMissingAttributes=!0,this.overwriteIndex=!0,this.attributes=["position","normal","color","tangent","uv","uv2"],this._intermediateGeometry=new Map,this._geometryMergeSets=new WeakMap,this._mergeOrder=[],this._dummyMesh=null,this.setObjects(e||[])}_getDummyMesh(){if(!this._dummyMesh){const e=new f.MeshBasicMaterial,t=new f.BufferGeometry;t.setAttribute("position",new f.BufferAttribute(new Float32Array(9),3)),this._dummyMesh=new f.Mesh(t,e)}return this._dummyMesh}_getMeshes(){const e=[];return al(this.objects,t=>{e.push(t)}),e.sort((t,r)=>t.uuid>r.uuid?1:t.uuid<r.uuid?-1:0),e.length===0&&e.push(this._getDummyMesh()),e}_updateIntermediateGeometries(){const{_intermediateGeometry:e}=this,t=this._getMeshes(),r=new Set(e.keys()),n={attributes:this.attributes,applyWorldTransforms:this.applyWorldTransforms};for(let o=0,i=t.length;o<i;o++){const a=t[o],c=a.uuid;r.delete(c);let h=e.get(c);(!h||!h.isCompatible(a,this.attributes))&&(h&&h.dispose(),h=new ol,e.set(c,h)),h.updateFrom(a,n)&&this.generateMissingAttributes&&tl(h,this.attributes)}r.forEach(o=>{e.delete(o)})}setObjects(e){Array.isArray(e)?this.objects=[...e]:this.objects=[e]}generate(e=new f.BufferGeometry){const{useGroups:t,overwriteIndex:r,_intermediateGeometry:n,_geometryMergeSets:o}=this,i=this._getMeshes(),a=[],c=[],h=o.get(e)||[];this._updateIntermediateGeometries();let d=!1;i.length!==h.length&&(d=!0);for(let l=0,v=i.length;l<v;l++){const x=i[l],S=n.get(x.uuid);c.push(S);const g=h[l];!g||g.uuid!==S.uuid?(a.push(!1),d=!0):g.version!==S.version?a.push(!1):a.push(!0)}ll(c,e,{useGroups:t,forceUpdate:d,skipAssigningAttributes:a,overwriteIndex:r}),d&&e.dispose(),o.set(e,c.map(l=>({version:l.version,uuid:l.uuid})));let u=Ri;return d?u=Vs:a.includes(!1)&&(u=Gs),{changeType:u,materials:cl(i),geometry:e}}}function hl(s){const e=new Set;for(let t=0,r=s.length;t<r;t++){const n=s[t];for(const o in n){const i=n[o];i&&i.isTexture&&e.add(i)}}return Array.from(e)}function fl(s){const e=[],t=new Set;for(let n=0,o=s.length;n<o;n++)s[n].traverse(i=>{i.visible&&(i.isRectAreaLight||i.isSpotLight||i.isPointLight||i.isDirectionalLight)&&(e.push(i),i.iesMap&&t.add(i.iesMap))});const r=Array.from(t).sort((n,o)=>n.uuid<o.uuid?1:n.uuid>o.uuid?-1:0);return{lights:e,iesTextures:r}}class dl{get initialized(){return!!this.bvh}constructor(e){this.bvhOptions={},this.attributes=["position","normal","tangent","color","uv","uv2"],this.generateBVH=!0,this.bvh=null,this.geometry=new f.BufferGeometry,this.staticGeometryGenerator=new ul(e),this._bvhWorker=null,this._pendingGenerate=null,this._buildAsync=!1}setObjects(e){this.staticGeometryGenerator.setObjects(e)}setBVHWorker(e){this._bvhWorker=e}async generateAsync(e=null){if(!this._bvhWorker)throw new Error('PathTracingSceneGenerator: "setBVHWorker" must be called before "generateAsync" can be called.');if(this.bvh instanceof Promise)return this._pendingGenerate||(this._pendingGenerate=new Promise(async()=>(await this.bvh,this._pendingGenerate=null,this.generateAsync(e)))),this._pendingGenerate;{this._buildAsync=!0;const t=this.generate(e);return this._buildAsync=!1,t.bvh=this.bvh=await t.bvh,t}}generate(e=null){const{staticGeometryGenerator:t,geometry:r,attributes:n}=this,o=t.objects;t.attributes=n,o.forEach(u=>{u.traverse(l=>{l.isSkinnedMesh&&l.skeleton&&l.skeleton.update()})});const i=t.generate(r),a=i.materials,c=hl(a),{lights:h,iesTextures:d}=fl(o);if(i.changeType!==Ri&&el(r,a,a),this.generateBVH){if(this.bvh instanceof Promise)throw new Error("PathTracingSceneGenerator: BVH is already building asynchronously.");if(i.changeType===Vs){const u={strategy:hs,maxLeafTris:1,indirect:!0,onProgress:e,...this.bvhOptions};this._buildAsync?this.bvh=this._bvhWorker.generate(r,u):this.bvh=new Ii(r,u)}else i.changeType===Gs&&this.bvh.refit()}return{bvhChanged:i.changeType!==Ri,bvh:this.bvh,lights:h,iesTextures:d,geometry:r,materials:a,textures:c,objects:o}}}const pl=new f.OrthographicCamera(-1,1,1,-1,0,1);class ml extends f.BufferGeometry{constructor(){super(),this.setAttribute("position",new f.Float32BufferAttribute([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new f.Float32BufferAttribute([0,2,0,0,2,0],2))}}const gl=new ml;class Ar{constructor(e){this._mesh=new f.Mesh(gl,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,pl)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class Fi extends f.ShaderMaterial{set needsUpdate(e){super.needsUpdate=!0,this.dispatchEvent({type:"recompilation"})}constructor(e){super(e);for(const t in this.uniforms)Object.defineProperty(this,t,{get(){return this.uniforms[t].value},set(r){this.uniforms[t].value=r}})}setDefine(e,t=void 0){if(t==null){if(e in this.defines)return delete this.defines[e],this.needsUpdate=!0,!0}else if(this.defines[e]!==t)return this.defines[e]=t,this.needsUpdate=!0,!0;return!1}}class vl extends Fi{constructor(e){super({blending:f.NoBlending,uniforms:{target1:{value:null},target2:{value:null},opacity:{value:1}},vertexShader:`
|
|
327
327
|
|
|
328
328
|
varying vec2 vUv;
|
|
329
329
|
|
|
@@ -436,7 +436,7 @@ struct BVH {
|
|
|
436
436
|
|
|
437
437
|
}
|
|
438
438
|
|
|
439
|
-
`,
|
|
439
|
+
`,yl=`
|
|
440
440
|
|
|
441
441
|
const uint SOBOL_DIRECTIONS_1[ 32 ] = uint[ 32 ](
|
|
442
442
|
0x80000000u, 0xc0000000u, 0xa0000000u, 0xf0000000u,
|
|
@@ -514,7 +514,7 @@ struct BVH {
|
|
|
514
514
|
|
|
515
515
|
}
|
|
516
516
|
|
|
517
|
-
`,
|
|
517
|
+
`,xl=`
|
|
518
518
|
|
|
519
519
|
// Seeds
|
|
520
520
|
uniform sampler2D sobolTexture;
|
|
@@ -569,7 +569,7 @@ struct BVH {
|
|
|
569
569
|
`,fragmentShader:`
|
|
570
570
|
|
|
571
571
|
${js}
|
|
572
|
-
${
|
|
572
|
+
${yl}
|
|
573
573
|
|
|
574
574
|
varying vec2 vUv;
|
|
575
575
|
uniform vec2 resolution;
|
|
@@ -579,7 +579,7 @@ struct BVH {
|
|
|
579
579
|
gl_FragColor = generateSobolPoint( index );
|
|
580
580
|
|
|
581
581
|
}
|
|
582
|
-
`})}}class xl{generate(e,t=256){const r=new f.WebGLRenderTarget(t,t,{type:f.FloatType,format:f.RGBAFormat,minFilter:f.NearestFilter,magFilter:f.NearestFilter,generateMipmaps:!1}),n=e.getRenderTarget();e.setRenderTarget(r);const o=new Ar(new bl);return o.material.resolution.set(t,t),o.render(e),e.setRenderTarget(n),o.dispose(),r}}class wl extends f.PerspectiveCamera{set bokehSize(e){this.fStop=this.getFocalLength()/e}get bokehSize(){return this.getFocalLength()/this.fStop}constructor(...e){super(...e),this.fStop=1.4,this.apertureBlades=0,this.apertureRotation=0,this.focusDistance=25,this.anamorphicRatio=1}copy(e,t){return super.copy(e,t),this.fStop=e.fStop,this.apertureBlades=e.apertureBlades,this.apertureRotation=e.apertureRotation,this.focusDistance=e.focusDistance,this.anamorphicRatio=e.anamorphicRatio,this}}class _l{constructor(){this.bokehSize=0,this.apertureBlades=0,this.apertureRotation=0,this.focusDistance=10,this.anamorphicRatio=1}updateFrom(e){e instanceof wl?(this.bokehSize=e.bokehSize,this.apertureBlades=e.apertureBlades,this.apertureRotation=e.apertureRotation,this.focusDistance=e.focusDistance,this.anamorphicRatio=e.anamorphicRatio):(this.bokehSize=0,this.apertureRotation=0,this.apertureBlades=0,this.focusDistance=10,this.anamorphicRatio=1)}}function Oi(s){const e=new Uint16Array(s.length);for(let t=0,r=s.length;t<r;++t)e[t]=f.DataUtils.toHalfFloat(s[t]);return e}function Ws(s,e,t=0,r=s.length){let n=t,o=t+r-1;for(;n<o;){const i=n+o>>1;s[i]<e?n=i+1:o=i}return n-t}function Sl(s,e,t){return .2126*s+.7152*e+.0722*t}function Tl(s,e=f.HalfFloatType){const t=s.clone();t.source=new f.Source({...t.image});const{width:r,height:n,data:o}=t.image;let i=o;if(t.type!==e){e===f.HalfFloatType?i=new Uint16Array(o.length):i=new Float32Array(o.length);let a;o instanceof Int8Array||o instanceof Int16Array||o instanceof Int32Array?a=2**(8*o.BYTES_PER_ELEMENT-1)-1:a=2**(8*o.BYTES_PER_ELEMENT)-1;for(let c=0,h=o.length;c<h;c++){let d=o[c];t.type===f.HalfFloatType&&(d=f.DataUtils.fromHalfFloat(o[c])),t.type!==f.FloatType&&t.type!==f.HalfFloatType&&(d/=a),e===f.HalfFloatType&&(i[c]=f.DataUtils.toHalfFloat(d))}t.image.data=i,t.type=e}if(t.flipY){const a=i;i=i.slice();for(let c=0;c<n;c++)for(let h=0;h<r;h++){const d=n-c-1,u=4*(c*r+h),l=4*(d*r+h);i[l+0]=a[u+0],i[l+1]=a[u+1],i[l+2]=a[u+2],i[l+3]=a[u+3]}t.flipY=!1,t.image.data=i}return t}class Al{constructor(){const e=new f.DataTexture(Oi(new Float32Array([0,0,0,0])),1,1);e.type=f.HalfFloatType,e.format=f.RGBAFormat,e.minFilter=f.LinearFilter,e.magFilter=f.LinearFilter,e.wrapS=f.RepeatWrapping,e.wrapT=f.RepeatWrapping,e.generateMipmaps=!1,e.needsUpdate=!0;const t=new f.DataTexture(Oi(new Float32Array([0,1])),1,2);t.type=f.HalfFloatType,t.format=f.RedFormat,t.minFilter=f.LinearFilter,t.magFilter=f.LinearFilter,t.generateMipmaps=!1,t.needsUpdate=!0;const r=new f.DataTexture(Oi(new Float32Array([0,0,1,1])),2,2);r.type=f.HalfFloatType,r.format=f.RedFormat,r.minFilter=f.LinearFilter,r.magFilter=f.LinearFilter,r.generateMipmaps=!1,r.needsUpdate=!0,this.map=e,this.marginalWeights=t,this.conditionalWeights=r,this.totalSum=0}dispose(){this.marginalWeights.dispose(),this.conditionalWeights.dispose(),this.map.dispose()}updateFrom(e){const t=Tl(e);t.wrapS=f.RepeatWrapping,t.wrapT=f.ClampToEdgeWrapping;const{width:r,height:n,data:o}=t.image,i=new Float32Array(r*n),a=new Float32Array(r*n),c=new Float32Array(n),h=new Float32Array(n);let d=0,u=0;for(let g=0;g<n;g++){let x=0;for(let w=0;w<r;w++){const T=g*r+w,A=f.DataUtils.fromHalfFloat(o[4*T+0]),P=f.DataUtils.fromHalfFloat(o[4*T+1]),D=f.DataUtils.fromHalfFloat(o[4*T+2]),R=Sl(A,P,D);x+=R,d+=R,i[T]=R,a[T]=x}if(x!==0)for(let w=g*r,T=g*r+r;w<T;w++)i[w]/=x,a[w]/=x;u+=x,c[g]=x,h[g]=u}if(u!==0)for(let g=0,x=c.length;g<x;g++)c[g]/=u,h[g]/=u;const l=new Uint16Array(n),v=new Uint16Array(r*n);for(let g=0;g<n;g++){const x=(g+1)/n,w=Ws(h,x);l[g]=f.DataUtils.toHalfFloat((w+.5)/n)}for(let g=0;g<n;g++)for(let x=0;x<r;x++){const w=g*r+x,T=(x+1)/r,A=Ws(a,T,g*r,r);v[w]=f.DataUtils.toHalfFloat((A+.5)/r)}this.dispose();const{marginalWeights:b,conditionalWeights:S}=this;b.image={width:n,height:1,data:l},b.needsUpdate=!0,S.image={width:r,height:n,data:v},S.needsUpdate=!0,this.totalSum=d,this.map=t}}const Li=6,Ml=0,Il=1,Cl=2,Pl=3,Dl=4,vt=new f.Vector3,$e=new f.Vector3,Ys=new f.Matrix4,Mr=new f.Quaternion,qs=new f.Vector3,Ir=new f.Vector3,Rl=new f.Vector3(0,1,0);class Fl{constructor(){const e=new f.DataTexture(new Float32Array(4),1,1);e.format=f.RGBAFormat,e.type=f.FloatType,e.wrapS=f.ClampToEdgeWrapping,e.wrapT=f.ClampToEdgeWrapping,e.generateMipmaps=!1,e.minFilter=f.NearestFilter,e.magFilter=f.NearestFilter,this.tex=e,this.count=0}updateFrom(e,t=[]){const r=this.tex,n=Math.max(e.length*Li,1),o=Math.ceil(Math.sqrt(n));r.image.width!==o&&(r.dispose(),r.image.data=new Float32Array(o*o*4),r.image.width=o,r.image.height=o);const i=r.image.data;for(let c=0,h=e.length;c<h;c++){const d=e[c],u=c*Li*4;let l=0;for(let b=0;b<Li*4;b++)i[u+b]=0;d.getWorldPosition($e),i[u+l++]=$e.x,i[u+l++]=$e.y,i[u+l++]=$e.z;let v=Ml;if(d.isRectAreaLight&&d.isCircular?v=Il:d.isSpotLight?v=Cl:d.isDirectionalLight?v=Pl:d.isPointLight&&(v=Dl),i[u+l++]=v,i[u+l++]=d.color.r,i[u+l++]=d.color.g,i[u+l++]=d.color.b,i[u+l++]=d.intensity,d.getWorldQuaternion(Mr),d.isRectAreaLight)vt.set(d.width,0,0).applyQuaternion(Mr),i[u+l++]=vt.x,i[u+l++]=vt.y,i[u+l++]=vt.z,l++,$e.set(0,d.height,0).applyQuaternion(Mr),i[u+l++]=$e.x,i[u+l++]=$e.y,i[u+l++]=$e.z,i[u+l++]=vt.cross($e).length()*(d.isCircular?Math.PI/4:1);else if(d.isSpotLight){const b=d.radius||0;qs.setFromMatrixPosition(d.matrixWorld),Ir.setFromMatrixPosition(d.target.matrixWorld),Ys.lookAt(qs,Ir,Rl),Mr.setFromRotationMatrix(Ys),vt.set(1,0,0).applyQuaternion(Mr),i[u+l++]=vt.x,i[u+l++]=vt.y,i[u+l++]=vt.z,l++,$e.set(0,1,0).applyQuaternion(Mr),i[u+l++]=$e.x,i[u+l++]=$e.y,i[u+l++]=$e.z,i[u+l++]=Math.PI*b*b,i[u+l++]=b,i[u+l++]=d.decay,i[u+l++]=d.distance,i[u+l++]=Math.cos(d.angle),i[u+l++]=Math.cos(d.angle*(1-d.penumbra)),i[u+l++]=d.iesMap?t.indexOf(d.iesMap):-1}else if(d.isPointLight){const b=vt.setFromMatrixPosition(d.matrixWorld);i[u+l++]=b.x,i[u+l++]=b.y,i[u+l++]=b.z,l++,l+=4,l+=1,i[u+l++]=d.decay,i[u+l++]=d.distance}else if(d.isDirectionalLight){const b=vt.setFromMatrixPosition(d.matrixWorld),S=$e.setFromMatrixPosition(d.target.matrixWorld);Ir.subVectors(b,S).normalize(),i[u+l++]=Ir.x,i[u+l++]=Ir.y,i[u+l++]=Ir.z}}this.count=e.length;const a=Ci(i.buffer);return this.hash!==a?(this.hash=a,r.needsUpdate=!0,!0):!1}}function Zs(s,e,t,r,n){if(e>r)throw new Error;const o=s.length/e,i=s.constructor.BYTES_PER_ELEMENT*8;let a=1;switch(s.constructor){case Uint8Array:case Uint16Array:case Uint32Array:a=2**i-1;break;case Int8Array:case Int16Array:case Int32Array:a=2**(i-1)-1;break}for(let c=0;c<o;c++){const h=4*c,d=e*c;for(let u=0;u<r;u++)t[n+h+u]=e>=u+1?s[d+u]/a:0}}class Ol extends f.DataArrayTexture{constructor(){super(),this._textures=[],this.type=f.FloatType,this.format=f.RGBAFormat,this.internalFormat="RGBA32F"}updateAttribute(e,t){const r=this._textures[e];r.updateFrom(t);const n=r.image,o=this.image;if(n.width!==o.width||n.height!==o.height)throw new Error("FloatAttributeTextureArray: Attribute must be the same dimensions when updating single layer.");const{width:i,height:a,data:c}=o,d=i*a*4*e;let u=t.itemSize;u===3&&(u=4),Zs(r.image.data,u,c,4,d),this.dispose(),this.needsUpdate=!0}setAttributes(e){const t=e[0].count,r=e.length;for(let u=0,l=r;u<l;u++)if(e[u].count!==t)throw new Error("FloatAttributeTextureArray: All attributes must have the same item count.");const n=this._textures;for(;n.length<r;){const u=new Fs;n.push(u)}for(;n.length>r;)n.pop();for(let u=0,l=r;u<l;u++)n[u].updateFrom(e[u]);const i=n[0].image,a=this.image;(i.width!==a.width||i.height!==a.height||i.depth!==r)&&(a.width=i.width,a.height=i.height,a.depth=r,a.data=new Float32Array(a.width*a.height*a.depth*4));const{data:c,width:h,height:d}=a;for(let u=0,l=r;u<l;u++){const v=n[u],S=h*d*4*u;let g=e[u].itemSize;g===3&&(g=4),Zs(v.image.data,g,c,4,S)}this.dispose(),this.needsUpdate=!0}}class Ll extends Ol{updateNormalAttribute(e){this.updateAttribute(0,e)}updateTangentAttribute(e){this.updateAttribute(1,e)}updateUvAttribute(e){this.updateAttribute(2,e)}updateColorAttribute(e){this.updateAttribute(3,e)}updateFrom(e,t,r,n){this.setAttributes([e,t,r,n])}}function Ni(s,e){return s.uuid<e.uuid?1:s.uuid>e.uuid?-1:0}function ki(s){return`${s.source.uuid}:${s.colorSpace}`}function Nl(s){const e=new Set,t=[];for(let r=0,n=s.length;r<n;r++){const o=s[r],i=ki(o);e.has(i)||(e.add(i),t.push(o))}return t}function kl(s){const e=s.map(r=>r.iesMap||null).filter(r=>r),t=new Set(e);return Array.from(t).sort(Ni)}function Bl(s){const e=new Set;for(let r=0,n=s.length;r<n;r++){const o=s[r];for(const i in o){const a=o[i];a&&a.isTexture&&e.add(a)}}const t=Array.from(e);return Nl(t).sort(Ni)}function zl(s){const e=[];return s.traverse(t=>{t.visible&&(t.isRectAreaLight||t.isSpotLight||t.isPointLight||t.isDirectionalLight)&&e.push(t)}),e.sort(Ni)}const Ks=45,Xs=Ks*4;class El{constructor(){this._features={}}isUsed(e){return e in this._features}setUsed(e,t=!0){t===!1?delete this._features[e]:this._features[e]=!0}reset(){this._features={}}}class Ul extends f.DataTexture{constructor(){super(new Float32Array(4),1,1),this.format=f.RGBAFormat,this.type=f.FloatType,this.wrapS=f.ClampToEdgeWrapping,this.wrapT=f.ClampToEdgeWrapping,this.minFilter=f.NearestFilter,this.magFilter=f.NearestFilter,this.generateMipmaps=!1,this.features=new El}updateFrom(e,t){function r(b,S,g=-1){if(S in b&&b[S]){const x=ki(b[S]);return u[x]}else return g}function n(b,S,g){return S in b?b[S]:g}function o(b,S,g,x){const w=b[S]&&b[S].isTexture?b[S]:null;if(w){w.matrixAutoUpdate&&w.updateMatrix();const T=w.matrix.elements;let A=0;g[x+A++]=T[0],g[x+A++]=T[3],g[x+A++]=T[6],A++,g[x+A++]=T[1],g[x+A++]=T[4],g[x+A++]=T[7],A++}return 8}let i=0;const a=e.length*Ks,c=Math.ceil(Math.sqrt(a))||1,{image:h,features:d}=this,u={};for(let b=0,S=t.length;b<S;b++)u[ki(t[b])]=b;h.width!==c&&(this.dispose(),h.data=new Float32Array(c*c*4),h.width=c,h.height=c);const l=h.data;d.reset();for(let b=0,S=e.length;b<S;b++){const g=e[b];if(g.isFogVolumeMaterial){d.setUsed("FOG");for(let T=0;T<Xs;T++)l[i+T]=0;l[i+0*4+0]=g.color.r,l[i+0*4+1]=g.color.g,l[i+0*4+2]=g.color.b,l[i+2*4+3]=n(g,"emissiveIntensity",0),l[i+3*4+0]=g.emissive.r,l[i+3*4+1]=g.emissive.g,l[i+3*4+2]=g.emissive.b,l[i+13*4+1]=g.density,l[i+13*4+3]=0,l[i+14*4+2]=4,i+=Xs;continue}l[i++]=g.color.r,l[i++]=g.color.g,l[i++]=g.color.b,l[i++]=r(g,"map"),l[i++]=n(g,"metalness",0),l[i++]=r(g,"metalnessMap"),l[i++]=n(g,"roughness",0),l[i++]=r(g,"roughnessMap"),l[i++]=n(g,"ior",1.5),l[i++]=n(g,"transmission",0),l[i++]=r(g,"transmissionMap"),l[i++]=n(g,"emissiveIntensity",0),"emissive"in g?(l[i++]=g.emissive.r,l[i++]=g.emissive.g,l[i++]=g.emissive.b):(l[i++]=0,l[i++]=0,l[i++]=0),l[i++]=r(g,"emissiveMap"),l[i++]=r(g,"normalMap"),"normalScale"in g?(l[i++]=g.normalScale.x,l[i++]=g.normalScale.y):(l[i++]=1,l[i++]=1),l[i++]=n(g,"clearcoat",0),l[i++]=r(g,"clearcoatMap"),l[i++]=n(g,"clearcoatRoughness",0),l[i++]=r(g,"clearcoatRoughnessMap"),l[i++]=r(g,"clearcoatNormalMap"),"clearcoatNormalScale"in g?(l[i++]=g.clearcoatNormalScale.x,l[i++]=g.clearcoatNormalScale.y):(l[i++]=1,l[i++]=1),i++,l[i++]=n(g,"sheen",0),"sheenColor"in g?(l[i++]=g.sheenColor.r,l[i++]=g.sheenColor.g,l[i++]=g.sheenColor.b):(l[i++]=0,l[i++]=0,l[i++]=0),l[i++]=r(g,"sheenColorMap"),l[i++]=n(g,"sheenRoughness",0),l[i++]=r(g,"sheenRoughnessMap"),l[i++]=r(g,"iridescenceMap"),l[i++]=r(g,"iridescenceThicknessMap"),l[i++]=n(g,"iridescence",0),l[i++]=n(g,"iridescenceIOR",1.3);const x=n(g,"iridescenceThicknessRange",[100,400]);l[i++]=x[0],l[i++]=x[1],"specularColor"in g?(l[i++]=g.specularColor.r,l[i++]=g.specularColor.g,l[i++]=g.specularColor.b):(l[i++]=1,l[i++]=1,l[i++]=1),l[i++]=r(g,"specularColorMap"),l[i++]=n(g,"specularIntensity",1),l[i++]=r(g,"specularIntensityMap");const w=n(g,"thickness",0)===0&&n(g,"attenuationDistance",1/0)===1/0;if(l[i++]=Number(w),i++,"attenuationColor"in g?(l[i++]=g.attenuationColor.r,l[i++]=g.attenuationColor.g,l[i++]=g.attenuationColor.b):(l[i++]=1,l[i++]=1,l[i++]=1),l[i++]=n(g,"attenuationDistance",1/0),l[i++]=r(g,"alphaMap"),l[i++]=g.opacity,l[i++]=g.alphaTest,!w&&g.transmission>0)l[i++]=0;else switch(g.side){case f.FrontSide:l[i++]=1;break;case f.BackSide:l[i++]=-1;break;case f.DoubleSide:l[i++]=0;break}l[i++]=Number(n(g,"matte",!1)),l[i++]=Number(n(g,"castShadow",!0)),l[i++]=Number(g.vertexColors)|Number(g.flatShading)<<1,l[i++]=Number(g.transparent),i+=o(g,"map",l,i),i+=o(g,"metalnessMap",l,i),i+=o(g,"roughnessMap",l,i),i+=o(g,"transmissionMap",l,i),i+=o(g,"emissiveMap",l,i),i+=o(g,"normalMap",l,i),i+=o(g,"clearcoatMap",l,i),i+=o(g,"clearcoatNormalMap",l,i),i+=o(g,"clearcoatRoughnessMap",l,i),i+=o(g,"sheenColorMap",l,i),i+=o(g,"sheenRoughnessMap",l,i),i+=o(g,"iridescenceMap",l,i),i+=o(g,"iridescenceThicknessMap",l,i),i+=o(g,"specularColorMap",l,i),i+=o(g,"specularIntensityMap",l,i)}const v=Ci(l.buffer);return this.hash!==v?(this.hash=v,this.needsUpdate=!0,!0):!1}}const $s=new f.Color;function Gl(s){return s?`${s.uuid}:${s.version}`:null}function Vl(s,e){for(const t in e)t in s&&(s[t]=e[t])}class Qs extends f.WebGLArrayRenderTarget{constructor(e,t,r){const n={format:f.RGBAFormat,type:f.UnsignedByteType,minFilter:f.LinearFilter,magFilter:f.LinearFilter,wrapS:f.RepeatWrapping,wrapT:f.RepeatWrapping,generateMipmaps:!1,...r};super(e,t,1,n),Vl(this.texture,n),this.texture.setTextures=(...i)=>{this.setTextures(...i)},this.hashes=[null];const o=new Ar(new jl);this.fsQuad=o}setTextures(e,t,r=this.width,n=this.height){const o=e.getRenderTarget(),i=e.toneMapping,a=e.getClearAlpha();e.getClearColor($s);const c=t.length||1;(r!==this.width||n!==this.height||this.depth!==c)&&(this.setSize(r,n,c),this.hashes=new Array(c).fill(null)),e.setClearColor(0,0),e.toneMapping=f.NoToneMapping;const h=this.fsQuad,d=this.hashes;let u=!1;for(let l=0,v=c;l<v;l++){const b=t[l],S=Gl(b);b&&(d[l]!==S||b.isWebGLRenderTarget)&&(b.matrixAutoUpdate=!1,b.matrix.identity(),h.material.map=b,e.setRenderTarget(this,l),h.render(e),b.updateMatrix(),b.matrixAutoUpdate=!0,d[l]=S,u=!0)}return h.material.map=null,e.setClearColor($s,a),e.setRenderTarget(o),e.toneMapping=i,u}dispose(){super.dispose(),this.fsQuad.dispose()}}class jl extends f.ShaderMaterial{get map(){return this.uniforms.map.value}set map(e){this.uniforms.map.value=e}constructor(){super({uniforms:{map:{value:null}},vertexShader:`
|
|
582
|
+
`})}}class wl{generate(e,t=256){const r=new f.WebGLRenderTarget(t,t,{type:f.FloatType,format:f.RGBAFormat,minFilter:f.NearestFilter,magFilter:f.NearestFilter,generateMipmaps:!1}),n=e.getRenderTarget();e.setRenderTarget(r);const o=new Ar(new bl);return o.material.resolution.set(t,t),o.render(e),e.setRenderTarget(n),o.dispose(),r}}class _l extends f.PerspectiveCamera{set bokehSize(e){this.fStop=this.getFocalLength()/e}get bokehSize(){return this.getFocalLength()/this.fStop}constructor(...e){super(...e),this.fStop=1.4,this.apertureBlades=0,this.apertureRotation=0,this.focusDistance=25,this.anamorphicRatio=1}copy(e,t){return super.copy(e,t),this.fStop=e.fStop,this.apertureBlades=e.apertureBlades,this.apertureRotation=e.apertureRotation,this.focusDistance=e.focusDistance,this.anamorphicRatio=e.anamorphicRatio,this}}class Sl{constructor(){this.bokehSize=0,this.apertureBlades=0,this.apertureRotation=0,this.focusDistance=10,this.anamorphicRatio=1}updateFrom(e){e instanceof _l?(this.bokehSize=e.bokehSize,this.apertureBlades=e.apertureBlades,this.apertureRotation=e.apertureRotation,this.focusDistance=e.focusDistance,this.anamorphicRatio=e.anamorphicRatio):(this.bokehSize=0,this.apertureRotation=0,this.apertureBlades=0,this.focusDistance=10,this.anamorphicRatio=1)}}function Oi(s){const e=new Uint16Array(s.length);for(let t=0,r=s.length;t<r;++t)e[t]=f.DataUtils.toHalfFloat(s[t]);return e}function Ws(s,e,t=0,r=s.length){let n=t,o=t+r-1;for(;n<o;){const i=n+o>>1;s[i]<e?n=i+1:o=i}return n-t}function Tl(s,e,t){return .2126*s+.7152*e+.0722*t}function Al(s,e=f.HalfFloatType){const t=s.clone();t.source=new f.Source({...t.image});const{width:r,height:n,data:o}=t.image;let i=o;if(t.type!==e){e===f.HalfFloatType?i=new Uint16Array(o.length):i=new Float32Array(o.length);let a;o instanceof Int8Array||o instanceof Int16Array||o instanceof Int32Array?a=2**(8*o.BYTES_PER_ELEMENT-1)-1:a=2**(8*o.BYTES_PER_ELEMENT)-1;for(let c=0,h=o.length;c<h;c++){let d=o[c];t.type===f.HalfFloatType&&(d=f.DataUtils.fromHalfFloat(o[c])),t.type!==f.FloatType&&t.type!==f.HalfFloatType&&(d/=a),e===f.HalfFloatType&&(i[c]=f.DataUtils.toHalfFloat(d))}t.image.data=i,t.type=e}if(t.flipY){const a=i;i=i.slice();for(let c=0;c<n;c++)for(let h=0;h<r;h++){const d=n-c-1,u=4*(c*r+h),l=4*(d*r+h);i[l+0]=a[u+0],i[l+1]=a[u+1],i[l+2]=a[u+2],i[l+3]=a[u+3]}t.flipY=!1,t.image.data=i}return t}class Ml{constructor(){const e=new f.DataTexture(Oi(new Float32Array([0,0,0,0])),1,1);e.type=f.HalfFloatType,e.format=f.RGBAFormat,e.minFilter=f.LinearFilter,e.magFilter=f.LinearFilter,e.wrapS=f.RepeatWrapping,e.wrapT=f.RepeatWrapping,e.generateMipmaps=!1,e.needsUpdate=!0;const t=new f.DataTexture(Oi(new Float32Array([0,1])),1,2);t.type=f.HalfFloatType,t.format=f.RedFormat,t.minFilter=f.LinearFilter,t.magFilter=f.LinearFilter,t.generateMipmaps=!1,t.needsUpdate=!0;const r=new f.DataTexture(Oi(new Float32Array([0,0,1,1])),2,2);r.type=f.HalfFloatType,r.format=f.RedFormat,r.minFilter=f.LinearFilter,r.magFilter=f.LinearFilter,r.generateMipmaps=!1,r.needsUpdate=!0,this.map=e,this.marginalWeights=t,this.conditionalWeights=r,this.totalSum=0}dispose(){this.marginalWeights.dispose(),this.conditionalWeights.dispose(),this.map.dispose()}updateFrom(e){const t=Al(e);t.wrapS=f.RepeatWrapping,t.wrapT=f.ClampToEdgeWrapping;const{width:r,height:n,data:o}=t.image,i=new Float32Array(r*n),a=new Float32Array(r*n),c=new Float32Array(n),h=new Float32Array(n);let d=0,u=0;for(let g=0;g<n;g++){let b=0;for(let w=0;w<r;w++){const T=g*r+w,A=f.DataUtils.fromHalfFloat(o[4*T+0]),P=f.DataUtils.fromHalfFloat(o[4*T+1]),D=f.DataUtils.fromHalfFloat(o[4*T+2]),R=Tl(A,P,D);b+=R,d+=R,i[T]=R,a[T]=b}if(b!==0)for(let w=g*r,T=g*r+r;w<T;w++)i[w]/=b,a[w]/=b;u+=b,c[g]=b,h[g]=u}if(u!==0)for(let g=0,b=c.length;g<b;g++)c[g]/=u,h[g]/=u;const l=new Uint16Array(n),v=new Uint16Array(r*n);for(let g=0;g<n;g++){const b=(g+1)/n,w=Ws(h,b);l[g]=f.DataUtils.toHalfFloat((w+.5)/n)}for(let g=0;g<n;g++)for(let b=0;b<r;b++){const w=g*r+b,T=(b+1)/r,A=Ws(a,T,g*r,r);v[w]=f.DataUtils.toHalfFloat((A+.5)/r)}this.dispose();const{marginalWeights:x,conditionalWeights:S}=this;x.image={width:n,height:1,data:l},x.needsUpdate=!0,S.image={width:r,height:n,data:v},S.needsUpdate=!0,this.totalSum=d,this.map=t}}const Li=6,Il=0,Cl=1,Pl=2,Dl=3,Rl=4,vt=new f.Vector3,$e=new f.Vector3,Ys=new f.Matrix4,Mr=new f.Quaternion,qs=new f.Vector3,Ir=new f.Vector3,Fl=new f.Vector3(0,1,0);class Ol{constructor(){const e=new f.DataTexture(new Float32Array(4),1,1);e.format=f.RGBAFormat,e.type=f.FloatType,e.wrapS=f.ClampToEdgeWrapping,e.wrapT=f.ClampToEdgeWrapping,e.generateMipmaps=!1,e.minFilter=f.NearestFilter,e.magFilter=f.NearestFilter,this.tex=e,this.count=0}updateFrom(e,t=[]){const r=this.tex,n=Math.max(e.length*Li,1),o=Math.ceil(Math.sqrt(n));r.image.width!==o&&(r.dispose(),r.image.data=new Float32Array(o*o*4),r.image.width=o,r.image.height=o);const i=r.image.data;for(let c=0,h=e.length;c<h;c++){const d=e[c],u=c*Li*4;let l=0;for(let x=0;x<Li*4;x++)i[u+x]=0;d.getWorldPosition($e),i[u+l++]=$e.x,i[u+l++]=$e.y,i[u+l++]=$e.z;let v=Il;if(d.isRectAreaLight&&d.isCircular?v=Cl:d.isSpotLight?v=Pl:d.isDirectionalLight?v=Dl:d.isPointLight&&(v=Rl),i[u+l++]=v,i[u+l++]=d.color.r,i[u+l++]=d.color.g,i[u+l++]=d.color.b,i[u+l++]=d.intensity,d.getWorldQuaternion(Mr),d.isRectAreaLight)vt.set(d.width,0,0).applyQuaternion(Mr),i[u+l++]=vt.x,i[u+l++]=vt.y,i[u+l++]=vt.z,l++,$e.set(0,d.height,0).applyQuaternion(Mr),i[u+l++]=$e.x,i[u+l++]=$e.y,i[u+l++]=$e.z,i[u+l++]=vt.cross($e).length()*(d.isCircular?Math.PI/4:1);else if(d.isSpotLight){const x=d.radius||0;qs.setFromMatrixPosition(d.matrixWorld),Ir.setFromMatrixPosition(d.target.matrixWorld),Ys.lookAt(qs,Ir,Fl),Mr.setFromRotationMatrix(Ys),vt.set(1,0,0).applyQuaternion(Mr),i[u+l++]=vt.x,i[u+l++]=vt.y,i[u+l++]=vt.z,l++,$e.set(0,1,0).applyQuaternion(Mr),i[u+l++]=$e.x,i[u+l++]=$e.y,i[u+l++]=$e.z,i[u+l++]=Math.PI*x*x,i[u+l++]=x,i[u+l++]=d.decay,i[u+l++]=d.distance,i[u+l++]=Math.cos(d.angle),i[u+l++]=Math.cos(d.angle*(1-d.penumbra)),i[u+l++]=d.iesMap?t.indexOf(d.iesMap):-1}else if(d.isPointLight){const x=vt.setFromMatrixPosition(d.matrixWorld);i[u+l++]=x.x,i[u+l++]=x.y,i[u+l++]=x.z,l++,l+=4,l+=1,i[u+l++]=d.decay,i[u+l++]=d.distance}else if(d.isDirectionalLight){const x=vt.setFromMatrixPosition(d.matrixWorld),S=$e.setFromMatrixPosition(d.target.matrixWorld);Ir.subVectors(x,S).normalize(),i[u+l++]=Ir.x,i[u+l++]=Ir.y,i[u+l++]=Ir.z}}this.count=e.length;const a=Ci(i.buffer);return this.hash!==a?(this.hash=a,r.needsUpdate=!0,!0):!1}}function Zs(s,e,t,r,n){if(e>r)throw new Error;const o=s.length/e,i=s.constructor.BYTES_PER_ELEMENT*8;let a=1;switch(s.constructor){case Uint8Array:case Uint16Array:case Uint32Array:a=2**i-1;break;case Int8Array:case Int16Array:case Int32Array:a=2**(i-1)-1;break}for(let c=0;c<o;c++){const h=4*c,d=e*c;for(let u=0;u<r;u++)t[n+h+u]=e>=u+1?s[d+u]/a:0}}class Ll extends f.DataArrayTexture{constructor(){super(),this._textures=[],this.type=f.FloatType,this.format=f.RGBAFormat,this.internalFormat="RGBA32F"}updateAttribute(e,t){const r=this._textures[e];r.updateFrom(t);const n=r.image,o=this.image;if(n.width!==o.width||n.height!==o.height)throw new Error("FloatAttributeTextureArray: Attribute must be the same dimensions when updating single layer.");const{width:i,height:a,data:c}=o,d=i*a*4*e;let u=t.itemSize;u===3&&(u=4),Zs(r.image.data,u,c,4,d),this.dispose(),this.needsUpdate=!0}setAttributes(e){const t=e[0].count,r=e.length;for(let u=0,l=r;u<l;u++)if(e[u].count!==t)throw new Error("FloatAttributeTextureArray: All attributes must have the same item count.");const n=this._textures;for(;n.length<r;){const u=new Fs;n.push(u)}for(;n.length>r;)n.pop();for(let u=0,l=r;u<l;u++)n[u].updateFrom(e[u]);const i=n[0].image,a=this.image;(i.width!==a.width||i.height!==a.height||i.depth!==r)&&(a.width=i.width,a.height=i.height,a.depth=r,a.data=new Float32Array(a.width*a.height*a.depth*4));const{data:c,width:h,height:d}=a;for(let u=0,l=r;u<l;u++){const v=n[u],S=h*d*4*u;let g=e[u].itemSize;g===3&&(g=4),Zs(v.image.data,g,c,4,S)}this.dispose(),this.needsUpdate=!0}}class Nl extends Ll{updateNormalAttribute(e){this.updateAttribute(0,e)}updateTangentAttribute(e){this.updateAttribute(1,e)}updateUvAttribute(e){this.updateAttribute(2,e)}updateColorAttribute(e){this.updateAttribute(3,e)}updateFrom(e,t,r,n){this.setAttributes([e,t,r,n])}}function Ni(s,e){return s.uuid<e.uuid?1:s.uuid>e.uuid?-1:0}function ki(s){return`${s.source.uuid}:${s.colorSpace}`}function kl(s){const e=new Set,t=[];for(let r=0,n=s.length;r<n;r++){const o=s[r],i=ki(o);e.has(i)||(e.add(i),t.push(o))}return t}function Bl(s){const e=s.map(r=>r.iesMap||null).filter(r=>r),t=new Set(e);return Array.from(t).sort(Ni)}function zl(s){const e=new Set;for(let r=0,n=s.length;r<n;r++){const o=s[r];for(const i in o){const a=o[i];a&&a.isTexture&&e.add(a)}}const t=Array.from(e);return kl(t).sort(Ni)}function El(s){const e=[];return s.traverse(t=>{t.visible&&(t.isRectAreaLight||t.isSpotLight||t.isPointLight||t.isDirectionalLight)&&e.push(t)}),e.sort(Ni)}const Ks=45,Xs=Ks*4;class Ul{constructor(){this._features={}}isUsed(e){return e in this._features}setUsed(e,t=!0){t===!1?delete this._features[e]:this._features[e]=!0}reset(){this._features={}}}class Gl extends f.DataTexture{constructor(){super(new Float32Array(4),1,1),this.format=f.RGBAFormat,this.type=f.FloatType,this.wrapS=f.ClampToEdgeWrapping,this.wrapT=f.ClampToEdgeWrapping,this.minFilter=f.NearestFilter,this.magFilter=f.NearestFilter,this.generateMipmaps=!1,this.features=new Ul}updateFrom(e,t){function r(x,S,g=-1){if(S in x&&x[S]){const b=ki(x[S]);return u[b]}else return g}function n(x,S,g){return S in x?x[S]:g}function o(x,S,g,b){const w=x[S]&&x[S].isTexture?x[S]:null;if(w){w.matrixAutoUpdate&&w.updateMatrix();const T=w.matrix.elements;let A=0;g[b+A++]=T[0],g[b+A++]=T[3],g[b+A++]=T[6],A++,g[b+A++]=T[1],g[b+A++]=T[4],g[b+A++]=T[7],A++}return 8}let i=0;const a=e.length*Ks,c=Math.ceil(Math.sqrt(a))||1,{image:h,features:d}=this,u={};for(let x=0,S=t.length;x<S;x++)u[ki(t[x])]=x;h.width!==c&&(this.dispose(),h.data=new Float32Array(c*c*4),h.width=c,h.height=c);const l=h.data;d.reset();for(let x=0,S=e.length;x<S;x++){const g=e[x];if(g.isFogVolumeMaterial){d.setUsed("FOG");for(let T=0;T<Xs;T++)l[i+T]=0;l[i+0*4+0]=g.color.r,l[i+0*4+1]=g.color.g,l[i+0*4+2]=g.color.b,l[i+2*4+3]=n(g,"emissiveIntensity",0),l[i+3*4+0]=g.emissive.r,l[i+3*4+1]=g.emissive.g,l[i+3*4+2]=g.emissive.b,l[i+13*4+1]=g.density,l[i+13*4+3]=0,l[i+14*4+2]=4,i+=Xs;continue}l[i++]=g.color.r,l[i++]=g.color.g,l[i++]=g.color.b,l[i++]=r(g,"map"),l[i++]=n(g,"metalness",0),l[i++]=r(g,"metalnessMap"),l[i++]=n(g,"roughness",0),l[i++]=r(g,"roughnessMap"),l[i++]=n(g,"ior",1.5),l[i++]=n(g,"transmission",0),l[i++]=r(g,"transmissionMap"),l[i++]=n(g,"emissiveIntensity",0),"emissive"in g?(l[i++]=g.emissive.r,l[i++]=g.emissive.g,l[i++]=g.emissive.b):(l[i++]=0,l[i++]=0,l[i++]=0),l[i++]=r(g,"emissiveMap"),l[i++]=r(g,"normalMap"),"normalScale"in g?(l[i++]=g.normalScale.x,l[i++]=g.normalScale.y):(l[i++]=1,l[i++]=1),l[i++]=n(g,"clearcoat",0),l[i++]=r(g,"clearcoatMap"),l[i++]=n(g,"clearcoatRoughness",0),l[i++]=r(g,"clearcoatRoughnessMap"),l[i++]=r(g,"clearcoatNormalMap"),"clearcoatNormalScale"in g?(l[i++]=g.clearcoatNormalScale.x,l[i++]=g.clearcoatNormalScale.y):(l[i++]=1,l[i++]=1),i++,l[i++]=n(g,"sheen",0),"sheenColor"in g?(l[i++]=g.sheenColor.r,l[i++]=g.sheenColor.g,l[i++]=g.sheenColor.b):(l[i++]=0,l[i++]=0,l[i++]=0),l[i++]=r(g,"sheenColorMap"),l[i++]=n(g,"sheenRoughness",0),l[i++]=r(g,"sheenRoughnessMap"),l[i++]=r(g,"iridescenceMap"),l[i++]=r(g,"iridescenceThicknessMap"),l[i++]=n(g,"iridescence",0),l[i++]=n(g,"iridescenceIOR",1.3);const b=n(g,"iridescenceThicknessRange",[100,400]);l[i++]=b[0],l[i++]=b[1],"specularColor"in g?(l[i++]=g.specularColor.r,l[i++]=g.specularColor.g,l[i++]=g.specularColor.b):(l[i++]=1,l[i++]=1,l[i++]=1),l[i++]=r(g,"specularColorMap"),l[i++]=n(g,"specularIntensity",1),l[i++]=r(g,"specularIntensityMap");const w=n(g,"thickness",0)===0&&n(g,"attenuationDistance",1/0)===1/0;if(l[i++]=Number(w),i++,"attenuationColor"in g?(l[i++]=g.attenuationColor.r,l[i++]=g.attenuationColor.g,l[i++]=g.attenuationColor.b):(l[i++]=1,l[i++]=1,l[i++]=1),l[i++]=n(g,"attenuationDistance",1/0),l[i++]=r(g,"alphaMap"),l[i++]=g.opacity,l[i++]=g.alphaTest,!w&&g.transmission>0)l[i++]=0;else switch(g.side){case f.FrontSide:l[i++]=1;break;case f.BackSide:l[i++]=-1;break;case f.DoubleSide:l[i++]=0;break}l[i++]=Number(n(g,"matte",!1)),l[i++]=Number(n(g,"castShadow",!0)),l[i++]=Number(g.vertexColors)|Number(g.flatShading)<<1,l[i++]=Number(g.transparent),i+=o(g,"map",l,i),i+=o(g,"metalnessMap",l,i),i+=o(g,"roughnessMap",l,i),i+=o(g,"transmissionMap",l,i),i+=o(g,"emissiveMap",l,i),i+=o(g,"normalMap",l,i),i+=o(g,"clearcoatMap",l,i),i+=o(g,"clearcoatNormalMap",l,i),i+=o(g,"clearcoatRoughnessMap",l,i),i+=o(g,"sheenColorMap",l,i),i+=o(g,"sheenRoughnessMap",l,i),i+=o(g,"iridescenceMap",l,i),i+=o(g,"iridescenceThicknessMap",l,i),i+=o(g,"specularColorMap",l,i),i+=o(g,"specularIntensityMap",l,i)}const v=Ci(l.buffer);return this.hash!==v?(this.hash=v,this.needsUpdate=!0,!0):!1}}const $s=new f.Color;function Vl(s){return s?`${s.uuid}:${s.version}`:null}function jl(s,e){for(const t in e)t in s&&(s[t]=e[t])}class Qs extends f.WebGLArrayRenderTarget{constructor(e,t,r){const n={format:f.RGBAFormat,type:f.UnsignedByteType,minFilter:f.LinearFilter,magFilter:f.LinearFilter,wrapS:f.RepeatWrapping,wrapT:f.RepeatWrapping,generateMipmaps:!1,...r};super(e,t,1,n),jl(this.texture,n),this.texture.setTextures=(...i)=>{this.setTextures(...i)},this.hashes=[null];const o=new Ar(new Wl);this.fsQuad=o}setTextures(e,t,r=this.width,n=this.height){const o=e.getRenderTarget(),i=e.toneMapping,a=e.getClearAlpha();e.getClearColor($s);const c=t.length||1;(r!==this.width||n!==this.height||this.depth!==c)&&(this.setSize(r,n,c),this.hashes=new Array(c).fill(null)),e.setClearColor(0,0),e.toneMapping=f.NoToneMapping;const h=this.fsQuad,d=this.hashes;let u=!1;for(let l=0,v=c;l<v;l++){const x=t[l],S=Vl(x);x&&(d[l]!==S||x.isWebGLRenderTarget)&&(x.matrixAutoUpdate=!1,x.matrix.identity(),h.material.map=x,e.setRenderTarget(this,l),h.render(e),x.updateMatrix(),x.matrixAutoUpdate=!0,d[l]=S,u=!0)}return h.material.map=null,e.setClearColor($s,a),e.setRenderTarget(o),e.toneMapping=i,u}dispose(){super.dispose(),this.fsQuad.dispose()}}class Wl extends f.ShaderMaterial{get map(){return this.uniforms.map.value}set map(e){this.uniforms.map.value=e}constructor(){super({uniforms:{map:{value:null}},vertexShader:`
|
|
583
583
|
varying vec2 vUv;
|
|
584
584
|
void main() {
|
|
585
585
|
|
|
@@ -595,7 +595,7 @@ struct BVH {
|
|
|
595
595
|
gl_FragColor = texture2D( map, vUv );
|
|
596
596
|
|
|
597
597
|
}
|
|
598
|
-
`})}}function
|
|
598
|
+
`})}}function Yl(s,e=Math.random()){for(let t=s.length-1;t>0;t--){const r=Math.floor(e()*(t+1)),n=s[t];s[t]=s[r],s[r]=n}return s}class ql{constructor(e,t,r=Math.random){const n=e**t,o=new Uint16Array(n);let i=n;for(let a=0;a<n;a++)o[a]=a;this.samples=new Float32Array(t),this.strataCount=e,this.reset=function(){for(let a=0;a<n;a++)o[a]=a;i=0},this.reshuffle=function(){i=0},this.next=function(){const{samples:a}=this;i>=o.length&&(Yl(o,r),this.reshuffle());let c=o[i++];for(let h=0;h<t;h++)a[h]=(c%e+r())/e,c=Math.floor(c/e);return a}}}class Zl{constructor(e,t,r=Math.random){let n=0;for(const c of t)n+=c;const o=new Float32Array(n),i=[];let a=0;for(const c of t){const h=new ql(e,c,r);h.samples=new Float32Array(o.buffer,a,h.samples.length),a+=h.samples.length*4,i.push(h)}this.samples=o,this.strataCount=e,this.next=function(){for(const c of i)c.next();return o},this.reshuffle=function(){for(const c of i)c.reshuffle()},this.reset=function(){for(const c of i)c.reset()}}}class Kl{constructor(e=0){this.m=2147483648,this.a=1103515245,this.c=12345,this.seed=e}nextInt(){return this.seed=(this.a*this.seed+this.c)%this.m,this.seed}nextFloat(){return this.nextInt()/(this.m-1)}}class Xl extends f.DataTexture{constructor(e=1,t=1,r=8){super(new Float32Array(1),1,1,f.RGBAFormat,f.FloatType),this.minFilter=f.NearestFilter,this.magFilter=f.NearestFilter,this.strata=r,this.sampler=null,this.generator=new Kl,this.stableNoise=!1,this.random=()=>this.stableNoise?this.generator.nextFloat():Math.random(),this.init(e,t,r)}init(e=this.image.height,t=this.image.width,r=this.strata){const{image:n}=this;if(n.width===t&&n.height===e&&this.sampler!==null)return;const o=new Array(e*t).fill(4),i=new Zl(r,o,this.random);n.width=t,n.height=e,n.data=i.samples,this.sampler=i,this.dispose(),this.next()}next(){this.sampler.next(),this.needsUpdate=!0}reset(){this.sampler.reset(),this.generator.seed=0}}function $l(s,e=Math.random){for(let t=s.length-1;t>0;t--){const r=~~((e()-1e-6)*t),n=s[t];s[t]=s[r],s[r]=n}}function Ql(s,e){s.fill(0);for(let t=0;t<e;t++)s[t]=1}class Js{constructor(e){this.count=0,this.size=-1,this.sigma=-1,this.radius=-1,this.lookupTable=null,this.score=null,this.binaryPattern=null,this.resize(e),this.setSigma(1.5)}findVoid(){const{score:e,binaryPattern:t}=this;let r=1/0,n=-1;for(let o=0,i=t.length;o<i;o++){if(t[o]!==0)continue;const a=e[o];a<r&&(r=a,n=o)}return n}findCluster(){const{score:e,binaryPattern:t}=this;let r=-1/0,n=-1;for(let o=0,i=t.length;o<i;o++){if(t[o]!==1)continue;const a=e[o];a>r&&(r=a,n=o)}return n}setSigma(e){if(e===this.sigma)return;const t=~~(Math.sqrt(10*2*e**2)+1),r=2*t+1,n=new Float32Array(r*r),o=e*e;for(let i=-t;i<=t;i++)for(let a=-t;a<=t;a++){const c=(t+a)*r+i+t,h=i*i+a*a;n[c]=Math.E**(-h/(2*o))}this.lookupTable=n,this.sigma=e,this.radius=t}resize(e){this.size!==e&&(this.size=e,this.score=new Float32Array(e*e),this.binaryPattern=new Uint8Array(e*e))}invert(){const{binaryPattern:e,score:t,size:r}=this;t.fill(0);for(let n=0,o=e.length;n<o;n++)if(e[n]===0){const i=~~(n/r),a=n-i*r;this.updateScore(a,i,1),e[n]=1}else e[n]=0}updateScore(e,t,r){const{size:n,score:o,lookupTable:i}=this,a=this.radius,c=2*a+1;for(let h=-a;h<=a;h++)for(let d=-a;d<=a;d++){const u=(a+d)*c+h+a,l=i[u];let v=e+h;v=v<0?n+v:v%n;let x=t+d;x=x<0?n+x:x%n;const S=x*n+v;o[S]+=r*l}}addPointIndex(e){this.binaryPattern[e]=1;const t=this.size,r=~~(e/t),n=e-r*t;this.updateScore(n,r,1),this.count++}removePointIndex(e){this.binaryPattern[e]=0;const t=this.size,r=~~(e/t),n=e-r*t;this.updateScore(n,r,-1),this.count--}copy(e){this.resize(e.size),this.score.set(e.score),this.binaryPattern.set(e.binaryPattern),this.setSigma(e.sigma),this.count=e.count}}class Jl{constructor(){this.random=Math.random,this.sigma=1.5,this.size=64,this.majorityPointsRatio=.1,this.samples=new Js(1),this.savedSamples=new Js(1)}generate(){const{samples:e,savedSamples:t,sigma:r,majorityPointsRatio:n,size:o}=this;e.resize(o),e.setSigma(r);const i=Math.floor(o*o*n),a=e.binaryPattern;Ql(a,i),$l(a,this.random);for(let u=0,l=a.length;u<l;u++)a[u]===1&&e.addPointIndex(u);for(;;){const u=e.findCluster();e.removePointIndex(u);const l=e.findVoid();if(u===l){e.addPointIndex(u);break}e.addPointIndex(l)}const c=new Uint32Array(o*o);t.copy(e);let h;for(h=e.count-1;h>=0;){const u=e.findCluster();e.removePointIndex(u),c[u]=h,h--}const d=o*o;for(h=t.count;h<d/2;){const u=t.findVoid();t.addPointIndex(u),c[u]=h,h++}for(t.invert();h<d;){const u=t.findCluster();t.removePointIndex(u),c[u]=h,h++}return{data:c,maxValue:d}}}function Hl(s){return s>=3?4:s}function eu(s){switch(s){case 1:return f.RedFormat;case 2:return f.RGFormat;default:return f.RGBAFormat}}class tu extends f.DataTexture{constructor(e=64,t=1){super(new Float32Array(4),1,1,f.RGBAFormat,f.FloatType),this.minFilter=f.NearestFilter,this.magFilter=f.NearestFilter,this.size=e,this.channels=t,this.update()}update(){const e=this.channels,t=this.size,r=new Jl;r.channels=e,r.size=t;const n=Hl(e),o=eu(n);(this.image.width!==t||o!==this.format)&&(this.image.width=t,this.image.height=t,this.image.data=new Float32Array(t**2*n),this.format=o,this.dispose());const i=this.image.data;for(let a=0,c=e;a<c;a++){const h=r.generate(),d=h.data,u=h.maxValue;for(let l=0,v=d.length;l<v;l++){const x=d[l]/u;i[l*n+a]=x}}this.needsUpdate=!0}}const ru=`
|
|
599
599
|
|
|
600
600
|
struct PhysicalCamera {
|
|
601
601
|
|
|
@@ -607,7 +607,7 @@ struct BVH {
|
|
|
607
607
|
|
|
608
608
|
};
|
|
609
609
|
|
|
610
|
-
`,
|
|
610
|
+
`,nu=`
|
|
611
611
|
|
|
612
612
|
struct EquirectHdrInfo {
|
|
613
613
|
|
|
@@ -619,7 +619,7 @@ struct BVH {
|
|
|
619
619
|
|
|
620
620
|
};
|
|
621
621
|
|
|
622
|
-
`,
|
|
622
|
+
`,iu=`
|
|
623
623
|
|
|
624
624
|
#define RECT_AREA_LIGHT_TYPE 0
|
|
625
625
|
#define CIRC_AREA_LIGHT_TYPE 1
|
|
@@ -705,7 +705,7 @@ struct BVH {
|
|
|
705
705
|
|
|
706
706
|
}
|
|
707
707
|
|
|
708
|
-
`,
|
|
708
|
+
`,su=`
|
|
709
709
|
|
|
710
710
|
struct Material {
|
|
711
711
|
|
|
@@ -912,7 +912,7 @@ struct BVH {
|
|
|
912
912
|
|
|
913
913
|
}
|
|
914
914
|
|
|
915
|
-
`,
|
|
915
|
+
`,ou=`
|
|
916
916
|
|
|
917
917
|
struct SurfaceRecord {
|
|
918
918
|
|
|
@@ -974,7 +974,7 @@ struct BVH {
|
|
|
974
974
|
vec3 color;
|
|
975
975
|
};
|
|
976
976
|
|
|
977
|
-
`,
|
|
977
|
+
`,au=`
|
|
978
978
|
|
|
979
979
|
// samples the the given environment map in the given direction
|
|
980
980
|
vec3 sampleEquirectColor( sampler2D envMap, vec3 direction ) {
|
|
@@ -1041,7 +1041,7 @@ struct BVH {
|
|
|
1041
1041
|
return float( resolution.x * resolution.y ) * pdf * equirectDirectionPdf( direction );
|
|
1042
1042
|
|
|
1043
1043
|
}
|
|
1044
|
-
`,
|
|
1044
|
+
`,cu=`
|
|
1045
1045
|
|
|
1046
1046
|
float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
|
|
1047
1047
|
|
|
@@ -1256,7 +1256,7 @@ struct BVH {
|
|
|
1256
1256
|
|
|
1257
1257
|
}
|
|
1258
1258
|
|
|
1259
|
-
`,
|
|
1259
|
+
`,lu=`
|
|
1260
1260
|
|
|
1261
1261
|
vec3 sampleHemisphere( vec3 n, vec2 uv ) {
|
|
1262
1262
|
|
|
@@ -1341,7 +1341,7 @@ struct BVH {
|
|
|
1341
1341
|
}
|
|
1342
1342
|
|
|
1343
1343
|
|
|
1344
|
-
`,
|
|
1344
|
+
`,uu=`
|
|
1345
1345
|
|
|
1346
1346
|
bool totalInternalReflection( float cosTheta, float eta ) {
|
|
1347
1347
|
|
|
@@ -1444,7 +1444,7 @@ struct BVH {
|
|
|
1444
1444
|
|
|
1445
1445
|
}
|
|
1446
1446
|
|
|
1447
|
-
`,
|
|
1447
|
+
`,hu=`
|
|
1448
1448
|
|
|
1449
1449
|
// Fast arccos approximation used to remove banding artifacts caused by numerical errors in acos.
|
|
1450
1450
|
// This is a cubic Lagrange interpolating polynomial for x = [-1, -1/2, 0, 1/2, 1].
|
|
@@ -1524,7 +1524,7 @@ struct BVH {
|
|
|
1524
1524
|
|
|
1525
1525
|
}
|
|
1526
1526
|
|
|
1527
|
-
`,
|
|
1527
|
+
`,fu=`
|
|
1528
1528
|
|
|
1529
1529
|
// Finds the point where the ray intersects the plane defined by u and v and checks if this point
|
|
1530
1530
|
// falls in the bounds of the rectangle on that same plane.
|
|
@@ -1585,7 +1585,7 @@ struct BVH {
|
|
|
1585
1585
|
|
|
1586
1586
|
}
|
|
1587
1587
|
|
|
1588
|
-
`,
|
|
1588
|
+
`,du=`
|
|
1589
1589
|
|
|
1590
1590
|
// add texel fetch functions for texture arrays
|
|
1591
1591
|
vec4 texelFetch1D( sampler2DArray tex, int layer, uint index ) {
|
|
@@ -1779,7 +1779,7 @@ struct BVH {
|
|
|
1779
1779
|
return vec4( WHITE_NOISE_SEED ) / float( 0xffffffffu );
|
|
1780
1780
|
|
|
1781
1781
|
}
|
|
1782
|
-
`,
|
|
1782
|
+
`,pu=`
|
|
1783
1783
|
|
|
1784
1784
|
uniform sampler2D stratifiedTexture;
|
|
1785
1785
|
uniform sampler2D stratifiedOffsetTexture;
|
|
@@ -1828,7 +1828,7 @@ struct BVH {
|
|
|
1828
1828
|
|
|
1829
1829
|
}
|
|
1830
1830
|
|
|
1831
|
-
`,
|
|
1831
|
+
`,mu=`
|
|
1832
1832
|
|
|
1833
1833
|
// diffuse
|
|
1834
1834
|
float diffuseEval( vec3 wo, vec3 wi, vec3 wh, SurfaceRecord surf, inout vec3 color ) {
|
|
@@ -2266,7 +2266,7 @@ struct BVH {
|
|
|
2266
2266
|
|
|
2267
2267
|
}
|
|
2268
2268
|
|
|
2269
|
-
`,
|
|
2269
|
+
`,gu=`
|
|
2270
2270
|
|
|
2271
2271
|
// returns the hit distance given the material density
|
|
2272
2272
|
float intersectFogVolume( Material material, float u ) {
|
|
@@ -2287,7 +2287,7 @@ struct BVH {
|
|
|
2287
2287
|
|
|
2288
2288
|
}
|
|
2289
2289
|
|
|
2290
|
-
`,
|
|
2290
|
+
`,vu=`
|
|
2291
2291
|
|
|
2292
2292
|
// The GGX functions provide sampling and distribution information for normals as output so
|
|
2293
2293
|
// in order to get probability of scatter direction the half vector must be computed and provided.
|
|
@@ -2388,7 +2388,7 @@ struct BVH {
|
|
|
2388
2388
|
|
|
2389
2389
|
}
|
|
2390
2390
|
|
|
2391
|
-
`,
|
|
2391
|
+
`,yu=`
|
|
2392
2392
|
|
|
2393
2393
|
// XYZ to sRGB color space
|
|
2394
2394
|
const mat3 XYZ_TO_REC709 = mat3(
|
|
@@ -2522,7 +2522,7 @@ struct BVH {
|
|
|
2522
2522
|
|
|
2523
2523
|
}
|
|
2524
2524
|
|
|
2525
|
-
`,
|
|
2525
|
+
`,xu=`
|
|
2526
2526
|
|
|
2527
2527
|
// See equation (2) in http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf
|
|
2528
2528
|
float velvetD( float cosThetaH, float roughness ) {
|
|
@@ -2680,7 +2680,7 @@ bool bvhIntersectFogVolumeHit(
|
|
|
2680
2680
|
|
|
2681
2681
|
}
|
|
2682
2682
|
|
|
2683
|
-
`,
|
|
2683
|
+
`,wu=`
|
|
2684
2684
|
|
|
2685
2685
|
// step through multiple surface hits and accumulate color attenuation based on transmissive surfaces
|
|
2686
2686
|
// returns true if a solid surface was hit
|
|
@@ -2857,7 +2857,7 @@ bool bvhIntersectFogVolumeHit(
|
|
|
2857
2857
|
|
|
2858
2858
|
}
|
|
2859
2859
|
|
|
2860
|
-
`,
|
|
2860
|
+
`,_u=`
|
|
2861
2861
|
|
|
2862
2862
|
vec3 ndcToRayOrigin( vec2 coord ) {
|
|
2863
2863
|
|
|
@@ -2940,7 +2940,7 @@ bool bvhIntersectFogVolumeHit(
|
|
|
2940
2940
|
|
|
2941
2941
|
}
|
|
2942
2942
|
|
|
2943
|
-
`,
|
|
2943
|
+
`,Su=`
|
|
2944
2944
|
|
|
2945
2945
|
vec3 directLightContribution( vec3 worldWo, SurfaceRecord surf, RenderState state, vec3 rayOrigin ) {
|
|
2946
2946
|
|
|
@@ -3036,7 +3036,7 @@ bool bvhIntersectFogVolumeHit(
|
|
|
3036
3036
|
|
|
3037
3037
|
}
|
|
3038
3038
|
|
|
3039
|
-
`,
|
|
3039
|
+
`,Tu=`
|
|
3040
3040
|
|
|
3041
3041
|
#define SKIP_SURFACE 0
|
|
3042
3042
|
#define HIT_SURFACE 1
|
|
@@ -3358,7 +3358,7 @@ bool bvhIntersectFogVolumeHit(
|
|
|
3358
3358
|
return HIT_SURFACE;
|
|
3359
3359
|
|
|
3360
3360
|
}
|
|
3361
|
-
`,
|
|
3361
|
+
`,Au=`
|
|
3362
3362
|
|
|
3363
3363
|
struct Ray {
|
|
3364
3364
|
|
|
@@ -3407,7 +3407,7 @@ bool bvhIntersectFogVolumeHit(
|
|
|
3407
3407
|
|
|
3408
3408
|
}
|
|
3409
3409
|
|
|
3410
|
-
`,
|
|
3410
|
+
`,Mu=`
|
|
3411
3411
|
|
|
3412
3412
|
#define NO_HIT 0
|
|
3413
3413
|
#define SURFACE_HIT 1
|
|
@@ -3454,7 +3454,7 @@ bool bvhIntersectFogVolumeHit(
|
|
|
3454
3454
|
|
|
3455
3455
|
}
|
|
3456
3456
|
|
|
3457
|
-
`;class
|
|
3457
|
+
`;class Iu extends Fi{onBeforeRender(){this.setDefine("FEATURE_DOF",this.physicalCamera.bokehSize===0?0:1),this.setDefine("FEATURE_BACKGROUND_MAP",this.backgroundMap?1:0),this.setDefine("FEATURE_FOG",this.materials.features.isUsed("FOG")?1:0)}constructor(e){super({transparent:!0,depthWrite:!1,defines:{FEATURE_MIS:1,FEATURE_RUSSIAN_ROULETTE:1,FEATURE_DOF:1,FEATURE_BACKGROUND_MAP:0,FEATURE_FOG:1,RANDOM_TYPE:2,CAMERA_TYPE:0,DEBUG_MODE:0,ATTR_NORMAL:0,ATTR_TANGENT:1,ATTR_UV:2,ATTR_COLOR:3},uniforms:{resolution:{value:new f.Vector2},opacity:{value:1},bounces:{value:10},transmissiveBounces:{value:10},filterGlossyFactor:{value:0},physicalCamera:{value:new Sl},cameraWorldMatrix:{value:new f.Matrix4},invProjectionMatrix:{value:new f.Matrix4},bvh:{value:new jc},attributesArray:{value:new Nl},materialIndexAttribute:{value:new Rs},materials:{value:new Gl},textures:{value:new Qs().texture},lights:{value:new Ol},iesProfiles:{value:new Qs(360,180,{type:f.HalfFloatType,wrapS:f.ClampToEdgeWrapping,wrapT:f.ClampToEdgeWrapping}).texture},environmentIntensity:{value:1},environmentRotation:{value:new f.Matrix4},envMapInfo:{value:new Ml},backgroundBlur:{value:0},backgroundMap:{value:null},backgroundAlpha:{value:1},backgroundIntensity:{value:1},backgroundRotation:{value:new f.Matrix4},seed:{value:0},sobolTexture:{value:null},stratifiedTexture:{value:new Xl},stratifiedOffsetTexture:{value:new tu(64,1)}},vertexShader:`
|
|
3458
3458
|
|
|
3459
3459
|
varying vec2 vUv;
|
|
3460
3460
|
void main() {
|
|
@@ -3478,27 +3478,27 @@ bool bvhIntersectFogVolumeHit(
|
|
|
3478
3478
|
#include <common>
|
|
3479
3479
|
|
|
3480
3480
|
// bvh intersection
|
|
3481
|
-
${Yc}
|
|
3482
|
-
${Zc}
|
|
3483
3481
|
${qc}
|
|
3482
|
+
${Kc}
|
|
3483
|
+
${Zc}
|
|
3484
3484
|
|
|
3485
3485
|
// uniform structs
|
|
3486
|
-
${tu}
|
|
3487
|
-
${nu}
|
|
3488
3486
|
${ru}
|
|
3489
3487
|
${iu}
|
|
3488
|
+
${nu}
|
|
3490
3489
|
${su}
|
|
3490
|
+
${ou}
|
|
3491
3491
|
|
|
3492
3492
|
// random
|
|
3493
3493
|
#if RANDOM_TYPE == 2 // Stratified List
|
|
3494
3494
|
|
|
3495
|
-
${
|
|
3495
|
+
${pu}
|
|
3496
3496
|
|
|
3497
3497
|
#elif RANDOM_TYPE == 1 // Sobol
|
|
3498
3498
|
|
|
3499
3499
|
${eo}
|
|
3500
3500
|
${js}
|
|
3501
|
-
${
|
|
3501
|
+
${xl}
|
|
3502
3502
|
|
|
3503
3503
|
#define rand(v) sobol(v)
|
|
3504
3504
|
#define rand2(v) sobol2(v)
|
|
@@ -3523,11 +3523,11 @@ bool bvhIntersectFogVolumeHit(
|
|
|
3523
3523
|
#endif
|
|
3524
3524
|
|
|
3525
3525
|
// common
|
|
3526
|
-
${
|
|
3527
|
-
${lu}
|
|
3528
|
-
${Hs}
|
|
3526
|
+
${du}
|
|
3529
3527
|
${uu}
|
|
3528
|
+
${Hs}
|
|
3530
3529
|
${hu}
|
|
3530
|
+
${fu}
|
|
3531
3531
|
|
|
3532
3532
|
// environment
|
|
3533
3533
|
uniform EquirectHdrInfo envMapInfo;
|
|
@@ -3583,16 +3583,16 @@ bool bvhIntersectFogVolumeHit(
|
|
|
3583
3583
|
float lightsDenom;
|
|
3584
3584
|
|
|
3585
3585
|
// sampling
|
|
3586
|
-
${
|
|
3587
|
-
${ou}
|
|
3586
|
+
${lu}
|
|
3588
3587
|
${au}
|
|
3588
|
+
${cu}
|
|
3589
3589
|
|
|
3590
3590
|
${bu}
|
|
3591
|
-
${gu}
|
|
3592
|
-
${yu}
|
|
3593
3591
|
${vu}
|
|
3592
|
+
${xu}
|
|
3593
|
+
${yu}
|
|
3594
|
+
${gu}
|
|
3594
3595
|
${mu}
|
|
3595
|
-
${pu}
|
|
3596
3596
|
|
|
3597
3597
|
float applyFilteredGlossy( float roughness, float accumulatedRoughness ) {
|
|
3598
3598
|
|
|
@@ -3624,12 +3624,12 @@ bool bvhIntersectFogVolumeHit(
|
|
|
3624
3624
|
|
|
3625
3625
|
}
|
|
3626
3626
|
|
|
3627
|
-
${Tu}
|
|
3628
|
-
${wu}
|
|
3629
3627
|
${Au}
|
|
3630
|
-
${xu}
|
|
3631
3628
|
${_u}
|
|
3629
|
+
${Mu}
|
|
3630
|
+
${wu}
|
|
3632
3631
|
${Su}
|
|
3632
|
+
${Tu}
|
|
3633
3633
|
|
|
3634
3634
|
void main() {
|
|
3635
3635
|
|
|
@@ -3921,7 +3921,7 @@ bool bvhIntersectFogVolumeHit(
|
|
|
3921
3921
|
|
|
3922
3922
|
}
|
|
3923
3923
|
|
|
3924
|
-
`}),this.setValues(e)}}function*
|
|
3924
|
+
`}),this.setValues(e)}}function*Cu(){const{_renderer:s,_fsQuad:e,_blendQuad:t,_primaryTarget:r,_blendTargets:n,_sobolTarget:o,_subframe:i,alpha:a,material:c}=this,h=new f.Vector4,d=new f.Vector4,u=t.material;let[l,v]=n;for(;;){a?(u.opacity=this._opacityFactor/(this.samples+1),c.blending=f.NoBlending,c.opacity=1):(c.opacity=this._opacityFactor/(this.samples+1),c.blending=f.NormalBlending);const[x,S,g,b]=i,w=r.width,T=r.height;c.resolution.set(w*g,T*b),c.sobolTexture=o.texture,c.stratifiedTexture.init(20,c.bounces+c.transmissiveBounces+5),c.stratifiedTexture.next(),c.seed++;const A=this.tiles.x||1,P=this.tiles.y||1,D=A*P,R=Math.ceil(w*g),O=Math.ceil(T*b),L=Math.floor(x*w),E=Math.floor(S*T),G=Math.ceil(R/A),z=Math.ceil(O/P);for(let V=0;V<P;V++)for(let U=0;U<A;U++){const H=s.getRenderTarget(),ne=s.autoClear,ge=s.getScissorTest();s.getScissor(h),s.getViewport(d);let Pe=U,ve=V;if(!this.stableTiles){const Ue=this._currentTile%(A*P);Pe=Ue%A,ve=~~(Ue/A),this._currentTile=Ue+1}const ye=P-ve-1;r.scissor.set(L+Pe*G,E+ye*z,Math.min(G,R-Pe*G),Math.min(z,O-ye*z)),r.viewport.set(L,E,R,O),s.setRenderTarget(r),s.setScissorTest(!0),s.autoClear=!1,e.render(s),s.setViewport(d),s.setScissor(h),s.setScissorTest(ge),s.setRenderTarget(H),s.autoClear=ne,a&&(u.target1=l.texture,u.target2=r.texture,s.setRenderTarget(v),t.render(s),s.setRenderTarget(H)),this.samples+=1/D,U===A-1&&V===P-1&&(this.samples=Math.round(this.samples)),yield}[l,v]=[v,l]}}const to=new f.Color;class ro{get material(){return this._fsQuad.material}set material(e){this._fsQuad.material.removeEventListener("recompilation",this._compileFunction),e.addEventListener("recompilation",this._compileFunction),this._fsQuad.material=e}get target(){return this._alpha?this._blendTargets[1]:this._primaryTarget}set alpha(e){this._alpha!==e&&(e||(this._blendTargets[0].dispose(),this._blendTargets[1].dispose()),this._alpha=e,this.reset())}get alpha(){return this._alpha}get isCompiling(){return!!this._compilePromise}constructor(e){this.camera=null,this.tiles=new f.Vector2(3,3),this.stableNoise=!1,this.stableTiles=!0,this.samples=0,this._subframe=new f.Vector4(0,0,1,1),this._opacityFactor=1,this._renderer=e,this._alpha=!1,this._fsQuad=new Ar(new Iu),this._blendQuad=new Ar(new vl),this._task=null,this._currentTile=0,this._compilePromise=null,this._sobolTarget=new wl().generate(e),this._primaryTarget=new f.WebGLRenderTarget(1,1,{format:f.RGBAFormat,type:f.FloatType,magFilter:f.NearestFilter,minFilter:f.NearestFilter}),this._blendTargets=[new f.WebGLRenderTarget(1,1,{format:f.RGBAFormat,type:f.FloatType,magFilter:f.NearestFilter,minFilter:f.NearestFilter}),new f.WebGLRenderTarget(1,1,{format:f.RGBAFormat,type:f.FloatType,magFilter:f.NearestFilter,minFilter:f.NearestFilter})],this._compileFunction=()=>{const t=this.compileMaterial(this._fsQuad._mesh);t.then(()=>{this._compilePromise===t&&(this._compilePromise=null)}),this._compilePromise=t},this.material.addEventListener("recompilation",this._compileFunction)}compileMaterial(){return this._renderer.compileAsync(this._fsQuad._mesh)}setCamera(e){const{material:t}=this;t.cameraWorldMatrix.copy(e.matrixWorld),t.invProjectionMatrix.copy(e.projectionMatrixInverse),t.physicalCamera.updateFrom(e);let r=0;e.projectionMatrix.elements[15]>0&&(r=1),e.isEquirectCamera&&(r=2),t.setDefine("CAMERA_TYPE",r),this.camera=e}setSize(e,t){e=Math.ceil(e),t=Math.ceil(t),!(this._primaryTarget.width===e&&this._primaryTarget.height===t)&&(this._primaryTarget.setSize(e,t),this._blendTargets[0].setSize(e,t),this._blendTargets[1].setSize(e,t),this.reset())}getSize(e){e.x=this._primaryTarget.width,e.y=this._primaryTarget.height}dispose(){this._primaryTarget.dispose(),this._blendTargets[0].dispose(),this._blendTargets[1].dispose(),this._sobolTarget.dispose(),this._fsQuad.dispose(),this._blendQuad.dispose(),this._task=null}reset(){const{_renderer:e,_primaryTarget:t,_blendTargets:r}=this,n=e.getRenderTarget(),o=e.getClearAlpha();e.getClearColor(to),e.setRenderTarget(t),e.setClearColor(0,0),e.clearColor(),e.setRenderTarget(r[0]),e.setClearColor(0,0),e.clearColor(),e.setRenderTarget(r[1]),e.setClearColor(0,0),e.clearColor(),e.setClearColor(to,o),e.setRenderTarget(n),this.samples=0,this._task=null,this.material.stratifiedTexture.stableNoise=this.stableNoise,this.stableNoise&&(this.material.seed=0,this.material.stratifiedTexture.reset())}update(){this.material.onBeforeRender(),!this.isCompiling&&(this._task||(this._task=Cu.call(this)),this._task.next())}}const Qt=new f.Vector2,no=new f.Vector2,En=new f.Spherical,Un=new f.Color;class Pu extends f.DataTexture{constructor(e=512,t=512){super(new Float32Array(e*t*4),e,t,f.RGBAFormat,f.FloatType,f.EquirectangularReflectionMapping,f.RepeatWrapping,f.ClampToEdgeWrapping,f.LinearFilter,f.LinearFilter),this.generationCallback=null}update(){this.dispose(),this.needsUpdate=!0;const{data:e,width:t,height:r}=this.image;for(let n=0;n<t;n++)for(let o=0;o<r;o++){no.set(t,r),Qt.set(n/t,o/r),Qt.x-=.5,Qt.y=1-Qt.y,En.theta=Qt.x*2*Math.PI,En.phi=Qt.y*Math.PI,En.radius=1,this.generationCallback(En,Qt,no,Un);const a=4*(o*t+n);e[a+0]=Un.r,e[a+1]=Un.g,e[a+2]=Un.b,e[a+3]=1}}copy(e){return super.copy(e),this.generationCallback=e.generationCallback,this}}const io=new f.Vector3;class Du extends Pu{constructor(e=512){super(e,e),this.topColor=new f.Color().set(16777215),this.bottomColor=new f.Color().set(0),this.exponent=2,this.generationCallback=(t,r,n,o)=>{io.setFromSpherical(t);const i=io.y*.5+.5;o.lerpColors(this.bottomColor,this.topColor,i**this.exponent)}}copy(e){return super.copy(e),this.topColor.copy(e.topColor),this.bottomColor.copy(e.bottomColor),this}}class Ru extends f.ShaderMaterial{get map(){return this.uniforms.map.value}set map(e){this.uniforms.map.value=e}get opacity(){return this.uniforms.opacity.value}set opacity(e){this.uniforms&&(this.uniforms.opacity.value=e)}constructor(e){super({uniforms:{map:{value:null},opacity:{value:1}},vertexShader:`
|
|
3925
3925
|
varying vec2 vUv;
|
|
3926
3926
|
void main() {
|
|
3927
3927
|
|
|
@@ -3978,7 +3978,7 @@ bool bvhIntersectFogVolumeHit(
|
|
|
3978
3978
|
#include <premultiplied_alpha_fragment>
|
|
3979
3979
|
|
|
3980
3980
|
}
|
|
3981
|
-
`}),this.setValues(e)}}class
|
|
3981
|
+
`}),this.setValues(e)}}class Fu extends f.ShaderMaterial{constructor(){super({uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:`
|
|
3982
3982
|
varying vec2 vUv;
|
|
3983
3983
|
void main() {
|
|
3984
3984
|
|
|
@@ -4003,16 +4003,16 @@ bool bvhIntersectFogVolumeHit(
|
|
|
4003
4003
|
rayDirection.x *= flipEnvMap;
|
|
4004
4004
|
gl_FragColor = textureCube( envMap, rayDirection );
|
|
4005
4005
|
|
|
4006
|
-
}`}),this.depthWrite=!1,this.depthTest=!1}}class so{constructor(e){this._renderer=e,this._quad=new Ar(new Ru)}generate(e,t=null,r=null){if(!e.isCubeTexture)throw new Error("CubeToEquirectMaterial: Source can only be cube textures.");const n=e.images[0],o=this._renderer,i=this._quad;t===null&&(t=4*n.height),r===null&&(r=2*n.height);const a=new f.WebGLRenderTarget(t,r,{type:f.FloatType,colorSpace:n.colorSpace}),c=n.height,h=Math.log2(c)-2,d=1/c,u=1/(3*Math.max(Math.pow(2,h),7*16));i.material.defines.CUBEUV_MAX_MIP=`${h}.0`,i.material.defines.CUBEUV_TEXEL_WIDTH=u,i.material.defines.CUBEUV_TEXEL_HEIGHT=d,i.material.uniforms.envMap.value=e,i.material.uniforms.flipEnvMap.value=e.isRenderTargetTexture?1:-1,i.material.needsUpdate=!0;const l=o.getRenderTarget(),v=o.autoClear;o.autoClear=!0,o.setRenderTarget(a),i.render(o),o.setRenderTarget(l),o.autoClear=v;const b=new Uint16Array(t*r*4),S=new Float32Array(t*r*4);o.readRenderTargetPixels(a,0,0,t,r,S),a.dispose();for(let x=0,w=S.length;x<w;x++)b[x]=f.DataUtils.toHalfFloat(S[x]);const g=new f.DataTexture(b,t,r,f.RGBAFormat,f.HalfFloatType);return g.minFilter=f.LinearMipMapLinearFilter,g.magFilter=f.LinearFilter,g.wrapS=f.RepeatWrapping,g.wrapT=f.RepeatWrapping,g.mapping=f.EquirectangularReflectionMapping,g.needsUpdate=!0,g}dispose(){this._quad.dispose()}}function Fu(s){return s.extensions.get("EXT_float_blend")}const Cr=new f.Vector2;class Ou{get multipleImportanceSampling(){return!!this._pathTracer.material.defines.FEATURE_MIS}set multipleImportanceSampling(e){this._pathTracer.material.setDefine("FEATURE_MIS",e?1:0)}get transmissiveBounces(){return this._pathTracer.material.transmissiveBounces}set transmissiveBounces(e){this._pathTracer.material.transmissiveBounces=e}get bounces(){return this._pathTracer.material.bounces}set bounces(e){this._pathTracer.material.bounces=e}get filterGlossyFactor(){return this._pathTracer.material.filterGlossyFactor}set filterGlossyFactor(e){this._pathTracer.material.filterGlossyFactor=e}get samples(){return this._pathTracer.samples}get target(){return this._pathTracer.target}get tiles(){return this._pathTracer.tiles}get stableNoise(){return this._pathTracer.stableNoise}set stableNoise(e){this._pathTracer.stableNoise=e}get isCompiling(){return!!this._pathTracer.isCompiling}constructor(e){this._renderer=e,this._generator=new fl,this._pathTracer=new ro(e),this._queueReset=!1,this._clock=new f.Clock,this._compilePromise=null,this._lowResPathTracer=new ro(e),this._lowResPathTracer.tiles.set(1,1),this._quad=new Ar(new Du({map:null,transparent:!0,blending:f.NoBlending,premultipliedAlpha:e.getContextAttributes().premultipliedAlpha})),this._materials=null,this._previousEnvironment=null,this._previousBackground=null,this._internalBackground=null,this.renderDelay=100,this.minSamples=5,this.fadeDuration=500,this.enablePathTracing=!0,this.pausePathTracing=!1,this.dynamicLowRes=!1,this.lowResScale=.25,this.renderScale=1,this.synchronizeRenderSize=!0,this.rasterizeScene=!0,this.renderToCanvas=!0,this.textureSize=new f.Vector2(1024,1024),this.rasterizeSceneCallback=(t,r)=>{this._renderer.render(t,r)},this.renderToCanvasCallback=(t,r,n)=>{const o=r.autoClear;r.autoClear=!1,n.render(r),r.autoClear=o},this.setScene(new f.Scene,new f.PerspectiveCamera)}setBVHWorker(e){this._generator.setBVHWorker(e)}setScene(e,t,r={}){e.updateMatrixWorld(!0),t.updateMatrixWorld();const n=this._generator;if(n.setObjects(e),this._buildAsync)return n.generateAsync(r.onProgress).then(o=>this._updateFromResults(e,t,o));{const o=n.generate();return this._updateFromResults(e,t,o)}}setSceneAsync(...e){this._buildAsync=!0;const t=this.setScene(...e);return this._buildAsync=!1,t}setCamera(e){this.camera=e,this.updateCamera()}updateCamera(){const e=this.camera;e.updateMatrixWorld(),this._pathTracer.setCamera(e),this._lowResPathTracer.setCamera(e),this.reset()}updateMaterials(){const e=this._pathTracer.material,t=this._renderer,r=this._materials,n=this.textureSize,o=Bl(r);e.textures.setTextures(t,o,n.x,n.y),e.materials.updateFrom(r,o),this.reset()}updateLights(){const e=this.scene,t=this._renderer,r=this._pathTracer.material,n=zl(e),o=kl(n);r.lights.updateFrom(n,o),r.iesProfiles.setTextures(t,o),this.reset()}updateEnvironment(){const e=this.scene,t=this._pathTracer.material;if(this._internalBackground&&(this._internalBackground.dispose(),this._internalBackground=null),t.backgroundBlur=e.backgroundBlurriness,t.backgroundIntensity=e.backgroundIntensity??1,t.backgroundRotation.makeRotationFromEuler(e.backgroundRotation).invert(),e.background===null)t.backgroundMap=null,t.backgroundAlpha=0;else if(e.background.isColor){this._colorBackground=this._colorBackground||new Pu(16);const r=this._colorBackground;r.topColor.equals(e.background)||(r.topColor.set(e.background),r.bottomColor.set(e.background),r.update()),t.backgroundMap=r,t.backgroundAlpha=1}else if(e.background.isCubeTexture){if(e.background!==this._previousBackground){const r=new so(this._renderer).generate(e.background);this._internalBackground=r,t.backgroundMap=r,t.backgroundAlpha=1}}else t.backgroundMap=e.background,t.backgroundAlpha=1;if(t.environmentIntensity=e.environmentIntensity??1,t.environmentRotation.makeRotationFromEuler(e.environmentRotation).invert(),this._previousEnvironment!==e.environment)if(e.environment!==null)if(e.environment.isCubeTexture){const r=new so(this._renderer).generate(e.environment);t.envMapInfo.updateFrom(r)}else t.envMapInfo.updateFrom(e.environment);else t.environmentIntensity=0;this._previousEnvironment=e.environment,this._previousBackground=e.background,this.reset()}_updateFromResults(e,t,r){const{materials:n,geometry:o,bvh:i,bvhChanged:a}=r;this._materials=n;const h=this._pathTracer.material;return a&&(h.bvh.updateFrom(i),h.attributesArray.updateFrom(o.attributes.normal,o.attributes.tangent,o.attributes.uv,o.attributes.color),h.materialIndexAttribute.updateFrom(o.attributes.materialIndex)),this._previousScene=e,this.scene=e,this.camera=t,this.updateCamera(),this.updateMaterials(),this.updateEnvironment(),this.updateLights(),r}renderSample(){const e=this._lowResPathTracer,t=this._pathTracer,r=this._renderer,n=this._clock,o=this._quad;this._updateScale(),this._queueReset&&(t.reset(),e.reset(),this._queueReset=!1,o.material.opacity=0,n.start());const i=n.getDelta()*1e3,a=n.getElapsedTime()*1e3;if(!this.pausePathTracing&&this.enablePathTracing&&this.renderDelay<=a&&!this.isCompiling&&t.update(),t.alpha=t.material.backgroundAlpha!==1||!Fu(r),e.alpha=t.alpha,this.renderToCanvas){const c=this._renderer,h=this.minSamples;if(a>=this.renderDelay&&this.samples>=this.minSamples&&(this.fadeDuration!==0?o.material.opacity=Math.min(o.material.opacity+i/this.fadeDuration,1):o.material.opacity=1),!this.enablePathTracing||this.samples<h||o.material.opacity<1){if(this.dynamicLowRes&&!this.isCompiling){e.samples<1&&(e.material=t.material,e.update());const d=o.material.opacity;o.material.opacity=1-o.material.opacity,o.material.map=e.target.texture,o.render(c),o.material.opacity=d}(!this.dynamicLowRes&&this.rasterizeScene||this.dynamicLowRes&&this.isCompiling)&&this.rasterizeSceneCallback(this.scene,this.camera)}this.enablePathTracing&&o.material.opacity>0&&(o.material.opacity<1&&(o.material.blending=this.dynamicLowRes?f.AdditiveBlending:f.NormalBlending),o.material.map=t.target.texture,this.renderToCanvasCallback(t.target,c,o),o.material.blending=f.NoBlending)}}reset(){this._queueReset=!0,this._pathTracer.samples=0}dispose(){this._renderQuad.dispose(),this._renderQuad.material.dispose(),this._pathTracer.dispose()}_updateScale(){if(this.synchronizeRenderSize){this._renderer.getDrawingBufferSize(Cr);const e=Math.floor(this.renderScale*Cr.x),t=Math.floor(this.renderScale*Cr.y);if(this._pathTracer.getSize(Cr),Cr.x!==e||Cr.y!==t){const r=this.lowResScale;this._pathTracer.setSize(e,t),this._lowResPathTracer.setSize(Math.floor(e*r),Math.floor(t*r))}}}}function oo(s){return typeof s=="object"&&s!==null&&"getInternalRenderer"in s&&typeof s.getInternalRenderer=="function"}let Lu=0;const ao=new Set;class Nu{constructor(){this.pathTracer=null,this.enabled=!1,this.renderer=null,this.sampleCount=0,this.createAttempts=0,this.maxCreateAttempts=10,this.sceneInitialized=!1,this.environmentWaitFrames=0,this.maxEnvironmentWaitFrames=300,this.disposed=!1,this.convertedEnvTexture=null,this.lastResetTime=0,this.pausedFrameBase64=null,this.imageOverlay=null,this.events=new dn,this.instanceId=++Lu,ao.add(this),this.settings={samples:300,bounces:4,transmissiveBounces:2,renderScale:.5,lowResScale:.5,dynamicLowRes:!0,enablePathTracing:!0}}convertToDataTexture(e){if(!e.image||!(e.image instanceof HTMLImageElement))return null;const t=e.image,r=document.createElement("canvas");r.width=t.width,r.height=t.height;const n=r.getContext("2d");if(!n)return null;n.drawImage(t,0,0);const o=n.getImageData(0,0,r.width,r.height),i=new Float32Array(o.data.length);for(let c=0;c<o.data.length;c++)i[c]=o.data[c]/255;const a=new M.DataTexture(i,r.width,r.height,M.RGBAFormat,M.FloatType);return a.mapping=e.mapping,a.wrapS=e.wrapS,a.wrapT=e.wrapT,a.magFilter=e.magFilter,a.minFilter=e.minFilter,a.anisotropy=e.anisotropy,a.needsUpdate=!0,a}async initialize(e){try{return this.renderer=e.renderer,this.enabled=e.enabled,this.isSupported()?K.ok(void 0):K.err(new oe("Path tracing is not supported in this environment",ue.PATH_TRACING_INIT_FAILED,{reason:"WebGL2 or required extensions not available"}))}catch(t){return K.err(new oe("Failed to initialize path tracing",ue.PATH_TRACING_INIT_FAILED,{originalError:t}))}}createPathTracer(){if(this.disposed)return K.err(new oe("Instance is disposed",ue.INVALID_STATE));try{let e=null,t=0;for(;!e&&t<3;){if(At(this.renderer)&&(e=this.renderer.getInternalRenderer()),!e&&t<2)return K.err(new oe("Renderer not ready, will retry",ue.RENDERER_NOT_INITIALIZED));t++}return e?(this.pathTracer=new Ou(e),this.pathTracer.tiles&&"set"in this.pathTracer.tiles&&this.pathTracer.tiles.set(1,1),this.pathTracer.bounces=this.settings.bounces,this.settings.transmissiveBounces!==void 0&&(this.pathTracer.transmissiveBounces=this.settings.transmissiveBounces),this.pathTracer.renderScale=this.settings.renderScale,this.pathTracer.dynamicLowRes=this.settings.dynamicLowRes,this.pathTracer.lowResScale=this.settings.lowResScale,this.pathTracer.environmentIntensity!==void 0&&(this.pathTracer.environmentIntensity=2),e.toneMapping!==M.ACESFilmicToneMapping&&(e.toneMapping=M.ACESFilmicToneMapping,e.toneMappingExposure=1.5),e.autoClear=!1,e.setRenderTarget(null),K.ok(void 0)):K.err(new oe("Three.js renderer not available",ue.RENDERER_NOT_INITIALIZED))}catch(e){return K.err(new oe("Failed to create path tracer",ue.PATH_TRACING_INIT_FAILED,{originalError:e}))}}setEnabled(e){if(this.enabled!==e&&(this.enabled=e,!e)){this.reset(),this.sceneInitialized=!1;const t=At(this.renderer)?this.renderer.getInternalRenderer():null;t&&(t.__pathTracingActive=!1,t.autoClear=!0)}}updateSettings(e){this.settings={...this.settings,...e},e.enablePathTracing!==void 0&&this.setEnabled(e.enablePathTracing),this.pathTracer&&(e.bounces!==void 0&&(this.pathTracer.bounces=e.bounces),e.transmissiveBounces!==void 0&&(this.pathTracer.transmissiveBounces=e.transmissiveBounces),e.renderScale!==void 0&&(this.pathTracer.renderScale=e.renderScale),e.lowResScale!==void 0&&(this.pathTracer.lowResScale=e.lowResScale),e.dynamicLowRes!==void 0&&(this.pathTracer.dynamicLowRes=e.dynamicLowRes))}async render(e,t){var r,n;if(this.disposed||!this.renderer)return K.ok(void 0);if(!this.enabled){if(this.sampleCount>=this.settings.samples&&this.sampleCount>0)return this.pathTracer&&At(this.renderer)&&this.renderer.getInternalRenderer().setRenderTarget(null),K.ok(void 0);const o=this.renderer.render(e,t);return o.ok,o}if(!this.pathTracer){this.createAttempts++;const o=this.createPathTracer();if(!o.ok){if(this.createAttempts<this.maxCreateAttempts&&((r=o.error)==null?void 0:r.message)==="Renderer not ready, will retry")return this.renderer.render(e,t);{this.enabled=!1,this.createAttempts=0;const i=this.renderer.render(e,t);return i.ok,i}}this.createAttempts=0}try{let o=null,i=null;if(e&&oo(e)&&(o=e.getInternalRenderer()),t&&oo(t)&&(i=t.getInternalRenderer()),!o||!i)return K.err(new oe("Could not extract Three.js scene or camera",ue.INVALID_PARAMETER));if(!this.sceneInitialized)try{const a=o.__originalEnvironmentTexture;if(!o.environment&&!a)return this.environmentWaitFrames++,this.environmentWaitFrames>=this.maxEnvironmentWaitFrames&&(this.enabled=!1,this.environmentWaitFrames=0),this.renderer.render(e,t);this.environmentWaitFrames=0;let c=null;if(a&&a.mapping===M.EquirectangularReflectionMapping){if(c=a,a.image instanceof HTMLImageElement)if(this.convertedEnvTexture)c=this.convertedEnvTexture;else{const d=this.convertToDataTexture(a);if(d)this.convertedEnvTexture=d,c=d;else throw new Error("Failed to convert environment texture to DataTexture")}const h=o.environment;o.environment=c;try{a.image&&!a.image.data&&a.image instanceof HTMLImageElement&&!a.image.complete&&await new Promise(d=>{a.image.onload=()=>{a.needsUpdate=!0,d()},a.image.onerror=u=>{d()},a.image.complete&&d()}),this.pathTracer&&this.pathTracer.setScene(o,i),this.sceneInitialized=!0,o.environment=h}catch(d){throw o.environment=h,d}}else if(((n=o.environment)==null?void 0:n.mapping)===M.EquirectangularReflectionMapping)this.pathTracer&&this.pathTracer.setScene(o,i),this.sceneInitialized=!0;else return this.enabled=!1,this.renderer.render(e,t)}catch(a){return console.warn("Scene initialization error:",a),this.renderer.render(e,t)}if(this.sceneInitialized){if(this.sampleCount===0)try{this.pathTracer&&this.pathTracer.updateLights()}catch(h){console.warn("Failed to update lights for path tracing:",h)}const a=this.renderer.render(e,t);if(!a.ok)return a;const c=At(this.renderer)?this.renderer.getInternalRenderer():null;if(c){const h=c.autoClear,d=c.getRenderTarget();c.autoClear=!1,this.pathTracer&&this.pathTracer.renderSample(),c.autoClear=h,c.setRenderTarget(d)}else throw new Error("Three.js renderer not available");if(this.sampleCount++,this.sampleCount===this.settings.samples){const h=At(this.renderer)?this.renderer.getInternalRenderer():null;if(h&&this.pathTracer)try{const d=h.autoClear;h.autoClear=!0,h.setRenderTarget(null),h.clear(!0,!0,!0);const u=this.pathTracer.copyQuad;u&&typeof u.render=="function"?u.render(h):(h.autoClear=!1,this.pathTracer.renderSample());const l=h.domElement,v=l.toDataURL("image/png");this.pausedFrameBase64=v,this.createImageOverlay(l,v),h.autoClear=d}catch(d){console.warn("Failed to capture path traced result:",d)}return this.enabled=!1,this.events.emit("pathtracing:paused",{samples:this.sampleCount}),setTimeout(()=>{this.disposePathTracingResources()},100),K.ok(void 0)}}else return this.renderer.render(e,t);return K.ok(void 0)}catch(o){return K.err(new oe("Failed to render with path tracing",ue.RENDER_FAILED,{originalError:o}))}}getSampleCount(){return this.sampleCount}isEnabled(){return this.enabled}isPathTracerDisposed(){return this.disposed}reset(){const e=performance.now();e-this.lastResetTime<50||(this.lastResetTime=e,this.sampleCount=0,this.pathTracer&&(this.pathTracer.reset(),this.sceneInitialized=!1))}createImageOverlay(e,t){const r=document.createElement("img");r.src=t,r.style.position="absolute",r.style.top="0",r.style.left="0",r.style.width="100%",r.style.height="100%",r.style.pointerEvents="none",r.style.zIndex="1000",this.imageOverlay=r;const n=e.parentElement;n?(window.getComputedStyle(n).position==="static"&&(n.style.position="relative"),r.onload=()=>{n.appendChild(r),e.style.visibility="hidden"},r.onerror=i=>{console.error("Failed to load path traced image overlay")}):console.warn("Cannot create image overlay: canvas has no parent element")}disposePathTracingResources(){if(this.pathTracer){try{this.pathTracer.dispose()}catch(e){console.warn("Failed to dispose path tracer:",e)}this.pathTracer=null}if(this.convertedEnvTexture&&(this.convertedEnvTexture.dispose(),this.convertedEnvTexture=null),this.renderer){const e=At(this.renderer)?this.renderer.getInternalRenderer():null;e&&(e.__pathTracingActive=!1,e.autoClear=!0)}this.sceneInitialized=!1,this.createAttempts=0}dispose(){if(this.disposed=!0,ao.delete(this),this.imageOverlay&&this.imageOverlay.parentElement&&(this.imageOverlay.parentElement.removeChild(this.imageOverlay),this.imageOverlay=null),this.renderer){const e=At(this.renderer)?this.renderer.getInternalRenderer():null;e&&(e.__pathTracingActive=!1)}if(this.pathTracer){try{this.pathTracer.dispose()}catch(e){console.warn("Failed to dispose path tracer during service disposal:",e)}this.pathTracer=null}this.convertedEnvTexture&&(this.convertedEnvTexture.dispose(),this.convertedEnvTexture=null),this.sampleCount=0,this.sceneInitialized=!1,this.createAttempts=0,this.renderer=null}isSupported(){return document.createElement("canvas").getContext("webgl2")!==null}getPausedFrameBase64(){return this.pausedFrameBase64}hasImageOverlay(){return this.imageOverlay!==null}removeImageOverlay(){if(this.imageOverlay&&this.imageOverlay.parentElement){if(this.imageOverlay.parentElement.removeChild(this.imageOverlay),this.imageOverlay=null,this.renderer){const e=At(this.renderer)?this.renderer.getInternalRenderer():null;e&&e.domElement&&(e.domElement.style.visibility="visible")}this.pausedFrameBase64=null}}}/*!
|
|
4006
|
+
}`}),this.depthWrite=!1,this.depthTest=!1}}class so{constructor(e){this._renderer=e,this._quad=new Ar(new Fu)}generate(e,t=null,r=null){if(!e.isCubeTexture)throw new Error("CubeToEquirectMaterial: Source can only be cube textures.");const n=e.images[0],o=this._renderer,i=this._quad;t===null&&(t=4*n.height),r===null&&(r=2*n.height);const a=new f.WebGLRenderTarget(t,r,{type:f.FloatType,colorSpace:n.colorSpace}),c=n.height,h=Math.log2(c)-2,d=1/c,u=1/(3*Math.max(Math.pow(2,h),7*16));i.material.defines.CUBEUV_MAX_MIP=`${h}.0`,i.material.defines.CUBEUV_TEXEL_WIDTH=u,i.material.defines.CUBEUV_TEXEL_HEIGHT=d,i.material.uniforms.envMap.value=e,i.material.uniforms.flipEnvMap.value=e.isRenderTargetTexture?1:-1,i.material.needsUpdate=!0;const l=o.getRenderTarget(),v=o.autoClear;o.autoClear=!0,o.setRenderTarget(a),i.render(o),o.setRenderTarget(l),o.autoClear=v;const x=new Uint16Array(t*r*4),S=new Float32Array(t*r*4);o.readRenderTargetPixels(a,0,0,t,r,S),a.dispose();for(let b=0,w=S.length;b<w;b++)x[b]=f.DataUtils.toHalfFloat(S[b]);const g=new f.DataTexture(x,t,r,f.RGBAFormat,f.HalfFloatType);return g.minFilter=f.LinearMipMapLinearFilter,g.magFilter=f.LinearFilter,g.wrapS=f.RepeatWrapping,g.wrapT=f.RepeatWrapping,g.mapping=f.EquirectangularReflectionMapping,g.needsUpdate=!0,g}dispose(){this._quad.dispose()}}function Ou(s){return s.extensions.get("EXT_float_blend")}const Cr=new f.Vector2;class Lu{get multipleImportanceSampling(){return!!this._pathTracer.material.defines.FEATURE_MIS}set multipleImportanceSampling(e){this._pathTracer.material.setDefine("FEATURE_MIS",e?1:0)}get transmissiveBounces(){return this._pathTracer.material.transmissiveBounces}set transmissiveBounces(e){this._pathTracer.material.transmissiveBounces=e}get bounces(){return this._pathTracer.material.bounces}set bounces(e){this._pathTracer.material.bounces=e}get filterGlossyFactor(){return this._pathTracer.material.filterGlossyFactor}set filterGlossyFactor(e){this._pathTracer.material.filterGlossyFactor=e}get samples(){return this._pathTracer.samples}get target(){return this._pathTracer.target}get tiles(){return this._pathTracer.tiles}get stableNoise(){return this._pathTracer.stableNoise}set stableNoise(e){this._pathTracer.stableNoise=e}get isCompiling(){return!!this._pathTracer.isCompiling}constructor(e){this._renderer=e,this._generator=new dl,this._pathTracer=new ro(e),this._queueReset=!1,this._clock=new f.Clock,this._compilePromise=null,this._lowResPathTracer=new ro(e),this._lowResPathTracer.tiles.set(1,1),this._quad=new Ar(new Ru({map:null,transparent:!0,blending:f.NoBlending,premultipliedAlpha:e.getContextAttributes().premultipliedAlpha})),this._materials=null,this._previousEnvironment=null,this._previousBackground=null,this._internalBackground=null,this.renderDelay=100,this.minSamples=5,this.fadeDuration=500,this.enablePathTracing=!0,this.pausePathTracing=!1,this.dynamicLowRes=!1,this.lowResScale=.25,this.renderScale=1,this.synchronizeRenderSize=!0,this.rasterizeScene=!0,this.renderToCanvas=!0,this.textureSize=new f.Vector2(1024,1024),this.rasterizeSceneCallback=(t,r)=>{this._renderer.render(t,r)},this.renderToCanvasCallback=(t,r,n)=>{const o=r.autoClear;r.autoClear=!1,n.render(r),r.autoClear=o},this.setScene(new f.Scene,new f.PerspectiveCamera)}setBVHWorker(e){this._generator.setBVHWorker(e)}setScene(e,t,r={}){e.updateMatrixWorld(!0),t.updateMatrixWorld();const n=this._generator;if(n.setObjects(e),this._buildAsync)return n.generateAsync(r.onProgress).then(o=>this._updateFromResults(e,t,o));{const o=n.generate();return this._updateFromResults(e,t,o)}}setSceneAsync(...e){this._buildAsync=!0;const t=this.setScene(...e);return this._buildAsync=!1,t}setCamera(e){this.camera=e,this.updateCamera()}updateCamera(){const e=this.camera;e.updateMatrixWorld(),this._pathTracer.setCamera(e),this._lowResPathTracer.setCamera(e),this.reset()}updateMaterials(){const e=this._pathTracer.material,t=this._renderer,r=this._materials,n=this.textureSize,o=zl(r);e.textures.setTextures(t,o,n.x,n.y),e.materials.updateFrom(r,o),this.reset()}updateLights(){const e=this.scene,t=this._renderer,r=this._pathTracer.material,n=El(e),o=Bl(n);r.lights.updateFrom(n,o),r.iesProfiles.setTextures(t,o),this.reset()}updateEnvironment(){const e=this.scene,t=this._pathTracer.material;if(this._internalBackground&&(this._internalBackground.dispose(),this._internalBackground=null),t.backgroundBlur=e.backgroundBlurriness,t.backgroundIntensity=e.backgroundIntensity??1,t.backgroundRotation.makeRotationFromEuler(e.backgroundRotation).invert(),e.background===null)t.backgroundMap=null,t.backgroundAlpha=0;else if(e.background.isColor){this._colorBackground=this._colorBackground||new Du(16);const r=this._colorBackground;r.topColor.equals(e.background)||(r.topColor.set(e.background),r.bottomColor.set(e.background),r.update()),t.backgroundMap=r,t.backgroundAlpha=1}else if(e.background.isCubeTexture){if(e.background!==this._previousBackground){const r=new so(this._renderer).generate(e.background);this._internalBackground=r,t.backgroundMap=r,t.backgroundAlpha=1}}else t.backgroundMap=e.background,t.backgroundAlpha=1;if(t.environmentIntensity=e.environmentIntensity??1,t.environmentRotation.makeRotationFromEuler(e.environmentRotation).invert(),this._previousEnvironment!==e.environment)if(e.environment!==null)if(e.environment.isCubeTexture){const r=new so(this._renderer).generate(e.environment);t.envMapInfo.updateFrom(r)}else t.envMapInfo.updateFrom(e.environment);else t.environmentIntensity=0;this._previousEnvironment=e.environment,this._previousBackground=e.background,this.reset()}_updateFromResults(e,t,r){const{materials:n,geometry:o,bvh:i,bvhChanged:a}=r;this._materials=n;const h=this._pathTracer.material;return a&&(h.bvh.updateFrom(i),h.attributesArray.updateFrom(o.attributes.normal,o.attributes.tangent,o.attributes.uv,o.attributes.color),h.materialIndexAttribute.updateFrom(o.attributes.materialIndex)),this._previousScene=e,this.scene=e,this.camera=t,this.updateCamera(),this.updateMaterials(),this.updateEnvironment(),this.updateLights(),r}renderSample(){const e=this._lowResPathTracer,t=this._pathTracer,r=this._renderer,n=this._clock,o=this._quad;this._updateScale(),this._queueReset&&(t.reset(),e.reset(),this._queueReset=!1,o.material.opacity=0,n.start());const i=n.getDelta()*1e3,a=n.getElapsedTime()*1e3;if(!this.pausePathTracing&&this.enablePathTracing&&this.renderDelay<=a&&!this.isCompiling&&t.update(),t.alpha=t.material.backgroundAlpha!==1||!Ou(r),e.alpha=t.alpha,this.renderToCanvas){const c=this._renderer,h=this.minSamples;if(a>=this.renderDelay&&this.samples>=this.minSamples&&(this.fadeDuration!==0?o.material.opacity=Math.min(o.material.opacity+i/this.fadeDuration,1):o.material.opacity=1),!this.enablePathTracing||this.samples<h||o.material.opacity<1){if(this.dynamicLowRes&&!this.isCompiling){e.samples<1&&(e.material=t.material,e.update());const d=o.material.opacity;o.material.opacity=1-o.material.opacity,o.material.map=e.target.texture,o.render(c),o.material.opacity=d}(!this.dynamicLowRes&&this.rasterizeScene||this.dynamicLowRes&&this.isCompiling)&&this.rasterizeSceneCallback(this.scene,this.camera)}this.enablePathTracing&&o.material.opacity>0&&(o.material.opacity<1&&(o.material.blending=this.dynamicLowRes?f.AdditiveBlending:f.NormalBlending),o.material.map=t.target.texture,this.renderToCanvasCallback(t.target,c,o),o.material.blending=f.NoBlending)}}reset(){this._queueReset=!0,this._pathTracer.samples=0}dispose(){this._renderQuad.dispose(),this._renderQuad.material.dispose(),this._pathTracer.dispose()}_updateScale(){if(this.synchronizeRenderSize){this._renderer.getDrawingBufferSize(Cr);const e=Math.floor(this.renderScale*Cr.x),t=Math.floor(this.renderScale*Cr.y);if(this._pathTracer.getSize(Cr),Cr.x!==e||Cr.y!==t){const r=this.lowResScale;this._pathTracer.setSize(e,t),this._lowResPathTracer.setSize(Math.floor(e*r),Math.floor(t*r))}}}}function oo(s){return typeof s=="object"&&s!==null&&"getInternalRenderer"in s&&typeof s.getInternalRenderer=="function"}let Nu=0;const ao=new Set;class ku{constructor(){this.pathTracer=null,this.enabled=!1,this.renderer=null,this.sampleCount=0,this.createAttempts=0,this.maxCreateAttempts=10,this.sceneInitialized=!1,this.environmentWaitFrames=0,this.maxEnvironmentWaitFrames=300,this.disposed=!1,this.convertedEnvTexture=null,this.lastResetTime=0,this.pausedFrameBase64=null,this.imageOverlay=null,this.events=new dn,this.instanceId=++Nu,ao.add(this),this.settings={samples:300,bounces:4,transmissiveBounces:2,renderScale:.5,lowResScale:.5,dynamicLowRes:!0,enablePathTracing:!0}}convertToDataTexture(e){if(!e.image||!(e.image instanceof HTMLImageElement))return null;const t=e.image,r=document.createElement("canvas");r.width=t.width,r.height=t.height;const n=r.getContext("2d");if(!n)return null;n.drawImage(t,0,0);const o=n.getImageData(0,0,r.width,r.height),i=new Float32Array(o.data.length);for(let c=0;c<o.data.length;c++)i[c]=o.data[c]/255;const a=new M.DataTexture(i,r.width,r.height,M.RGBAFormat,M.FloatType);return a.mapping=e.mapping,a.wrapS=e.wrapS,a.wrapT=e.wrapT,a.magFilter=e.magFilter,a.minFilter=e.minFilter,a.anisotropy=e.anisotropy,a.needsUpdate=!0,a}async initialize(e){try{return this.renderer=e.renderer,this.enabled=e.enabled,this.isSupported()?K.ok(void 0):K.err(new oe("Path tracing is not supported in this environment",ue.PATH_TRACING_INIT_FAILED,{reason:"WebGL2 or required extensions not available"}))}catch(t){return K.err(new oe("Failed to initialize path tracing",ue.PATH_TRACING_INIT_FAILED,{originalError:t}))}}createPathTracer(){if(this.disposed)return K.err(new oe("Instance is disposed",ue.INVALID_STATE));try{let e=null,t=0;for(;!e&&t<3;){if(At(this.renderer)&&(e=this.renderer.getInternalRenderer()),!e&&t<2)return K.err(new oe("Renderer not ready, will retry",ue.RENDERER_NOT_INITIALIZED));t++}return e?(this.pathTracer=new Lu(e),this.pathTracer.tiles&&"set"in this.pathTracer.tiles&&this.pathTracer.tiles.set(1,1),this.pathTracer.bounces=this.settings.bounces,this.settings.transmissiveBounces!==void 0&&(this.pathTracer.transmissiveBounces=this.settings.transmissiveBounces),this.pathTracer.renderScale=this.settings.renderScale,this.pathTracer.dynamicLowRes=this.settings.dynamicLowRes,this.pathTracer.lowResScale=this.settings.lowResScale,this.pathTracer.environmentIntensity!==void 0&&(this.pathTracer.environmentIntensity=2),e.toneMapping!==M.ACESFilmicToneMapping&&(e.toneMapping=M.ACESFilmicToneMapping,e.toneMappingExposure=1.5),e.autoClear=!1,e.setRenderTarget(null),K.ok(void 0)):K.err(new oe("Three.js renderer not available",ue.RENDERER_NOT_INITIALIZED))}catch(e){return K.err(new oe("Failed to create path tracer",ue.PATH_TRACING_INIT_FAILED,{originalError:e}))}}setEnabled(e){if(this.enabled!==e&&(this.enabled=e,!e)){this.reset(),this.sceneInitialized=!1;const t=At(this.renderer)?this.renderer.getInternalRenderer():null;t&&(t.__pathTracingActive=!1,t.autoClear=!0)}}updateSettings(e){this.settings={...this.settings,...e},e.enablePathTracing!==void 0&&this.setEnabled(e.enablePathTracing),this.pathTracer&&(e.bounces!==void 0&&(this.pathTracer.bounces=e.bounces),e.transmissiveBounces!==void 0&&(this.pathTracer.transmissiveBounces=e.transmissiveBounces),e.renderScale!==void 0&&(this.pathTracer.renderScale=e.renderScale),e.lowResScale!==void 0&&(this.pathTracer.lowResScale=e.lowResScale),e.dynamicLowRes!==void 0&&(this.pathTracer.dynamicLowRes=e.dynamicLowRes))}async render(e,t){var r,n;if(this.disposed||!this.renderer)return K.ok(void 0);if(!this.enabled){if(this.sampleCount>=this.settings.samples&&this.sampleCount>0)return this.pathTracer&&At(this.renderer)&&this.renderer.getInternalRenderer().setRenderTarget(null),K.ok(void 0);const o=this.renderer.render(e,t);return o.ok,o}if(!this.pathTracer){this.createAttempts++;const o=this.createPathTracer();if(!o.ok){if(this.createAttempts<this.maxCreateAttempts&&((r=o.error)==null?void 0:r.message)==="Renderer not ready, will retry")return this.renderer.render(e,t);{this.enabled=!1,this.createAttempts=0;const i=this.renderer.render(e,t);return i.ok,i}}this.createAttempts=0}try{let o=null,i=null;if(e&&oo(e)&&(o=e.getInternalRenderer()),t&&oo(t)&&(i=t.getInternalRenderer()),!o||!i)return K.err(new oe("Could not extract Three.js scene or camera",ue.INVALID_PARAMETER));if(!this.sceneInitialized)try{const a=o.__originalEnvironmentTexture;if(!o.environment&&!a)return this.environmentWaitFrames++,this.environmentWaitFrames>=this.maxEnvironmentWaitFrames&&(this.enabled=!1,this.environmentWaitFrames=0),this.renderer.render(e,t);this.environmentWaitFrames=0;let c=null;if(a&&a.mapping===M.EquirectangularReflectionMapping){if(c=a,a.image instanceof HTMLImageElement)if(this.convertedEnvTexture)c=this.convertedEnvTexture;else{const d=this.convertToDataTexture(a);if(d)this.convertedEnvTexture=d,c=d;else throw new Error("Failed to convert environment texture to DataTexture")}const h=o.environment;o.environment=c;try{a.image&&!a.image.data&&a.image instanceof HTMLImageElement&&!a.image.complete&&await new Promise(d=>{a.image.onload=()=>{a.needsUpdate=!0,d()},a.image.onerror=u=>{d()},a.image.complete&&d()}),this.pathTracer&&this.pathTracer.setScene(o,i),this.sceneInitialized=!0,o.environment=h}catch(d){throw o.environment=h,d}}else if(((n=o.environment)==null?void 0:n.mapping)===M.EquirectangularReflectionMapping)this.pathTracer&&this.pathTracer.setScene(o,i),this.sceneInitialized=!0;else return this.enabled=!1,this.renderer.render(e,t)}catch(a){return console.warn("Scene initialization error:",a),this.renderer.render(e,t)}if(this.sceneInitialized){if(this.sampleCount===0)try{this.pathTracer&&this.pathTracer.updateLights()}catch(h){console.warn("Failed to update lights for path tracing:",h)}const a=this.renderer.render(e,t);if(!a.ok)return a;const c=At(this.renderer)?this.renderer.getInternalRenderer():null;if(c){const h=c.autoClear,d=c.getRenderTarget();c.autoClear=!1,this.pathTracer&&this.pathTracer.renderSample(),c.autoClear=h,c.setRenderTarget(d)}else throw new Error("Three.js renderer not available");if(this.sampleCount++,this.sampleCount===this.settings.samples){const h=At(this.renderer)?this.renderer.getInternalRenderer():null;if(h&&this.pathTracer)try{const d=h.autoClear;h.autoClear=!0,h.setRenderTarget(null),h.clear(!0,!0,!0);const u=this.pathTracer.copyQuad;u&&typeof u.render=="function"?u.render(h):(h.autoClear=!1,this.pathTracer.renderSample());const l=h.domElement,v=l.toDataURL("image/png");this.pausedFrameBase64=v,this.createImageOverlay(l,v),h.autoClear=d}catch(d){console.warn("Failed to capture path traced result:",d)}return this.enabled=!1,this.events.emit("pathtracing:paused",{samples:this.sampleCount}),setTimeout(()=>{this.disposePathTracingResources()},100),K.ok(void 0)}}else return this.renderer.render(e,t);return K.ok(void 0)}catch(o){return K.err(new oe("Failed to render with path tracing",ue.RENDER_FAILED,{originalError:o}))}}getSampleCount(){return this.sampleCount}isEnabled(){return this.enabled}isPathTracerDisposed(){return this.disposed}reset(){const e=performance.now();e-this.lastResetTime<50||(this.lastResetTime=e,this.sampleCount=0,this.pathTracer&&(this.pathTracer.reset(),this.sceneInitialized=!1))}createImageOverlay(e,t){const r=document.createElement("img");r.src=t,r.style.position="absolute",r.style.top="0",r.style.left="0",r.style.width="100%",r.style.height="100%",r.style.pointerEvents="none",r.style.zIndex="1000",this.imageOverlay=r;const n=e.parentElement;n?(window.getComputedStyle(n).position==="static"&&(n.style.position="relative"),r.onload=()=>{n.appendChild(r),e.style.visibility="hidden"},r.onerror=i=>{console.error("Failed to load path traced image overlay")}):console.warn("Cannot create image overlay: canvas has no parent element")}disposePathTracingResources(){if(this.pathTracer){try{this.pathTracer.dispose()}catch(e){console.warn("Failed to dispose path tracer:",e)}this.pathTracer=null}if(this.convertedEnvTexture&&(this.convertedEnvTexture.dispose(),this.convertedEnvTexture=null),this.renderer){const e=At(this.renderer)?this.renderer.getInternalRenderer():null;e&&(e.__pathTracingActive=!1,e.autoClear=!0)}this.sceneInitialized=!1,this.createAttempts=0}dispose(){if(this.disposed=!0,ao.delete(this),this.imageOverlay&&this.imageOverlay.parentElement&&(this.imageOverlay.parentElement.removeChild(this.imageOverlay),this.imageOverlay=null),this.renderer){const e=At(this.renderer)?this.renderer.getInternalRenderer():null;e&&(e.__pathTracingActive=!1)}if(this.pathTracer){try{this.pathTracer.dispose()}catch(e){console.warn("Failed to dispose path tracer during service disposal:",e)}this.pathTracer=null}this.convertedEnvTexture&&(this.convertedEnvTexture.dispose(),this.convertedEnvTexture=null),this.sampleCount=0,this.sceneInitialized=!1,this.createAttempts=0,this.renderer=null}isSupported(){return document.createElement("canvas").getContext("webgl2")!==null}getPausedFrameBase64(){return this.pausedFrameBase64}hasImageOverlay(){return this.imageOverlay!==null}removeImageOverlay(){if(this.imageOverlay&&this.imageOverlay.parentElement){if(this.imageOverlay.parentElement.removeChild(this.imageOverlay),this.imageOverlay=null,this.renderer){const e=At(this.renderer)?this.renderer.getInternalRenderer():null;e&&e.domElement&&(e.domElement.style.visibility="visible")}this.pausedFrameBase64=null}}}/*!
|
|
4007
4007
|
fflate - fast JavaScript compression/decompression
|
|
4008
4008
|
<https://101arrowz.github.io/fflate>
|
|
4009
4009
|
Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSE
|
|
4010
4010
|
version 0.8.2
|
|
4011
|
-
*/var ct=Uint8Array,Pr=Uint16Array,ku=Int32Array,co=new ct([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]),lo=new ct([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]),Bu=new ct([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),uo=function(s,e){for(var t=new Pr(31),r=0;r<31;++r)t[r]=e+=1<<s[r-1];for(var n=new ku(t[30]),r=1;r<30;++r)for(var o=t[r];o<t[r+1];++o)n[o]=o-t[r]<<5|r;return{b:t,r:n}},ho=uo(co,2),fo=ho.b,zu=ho.r;fo[28]=258,zu[258]=28;for(var Eu=uo(lo,0),Uu=Eu.b,Bi=new Pr(32768),Ie=0;Ie<32768;++Ie){var jt=(Ie&43690)>>1|(Ie&21845)<<1;jt=(jt&52428)>>2|(jt&13107)<<2,jt=(jt&61680)>>4|(jt&3855)<<4,Bi[Ie]=((jt&65280)>>8|(jt&255)<<8)>>1}for(var Kr=function(s,e,t){for(var r=s.length,n=0,o=new Pr(e);n<r;++n)s[n]&&++o[s[n]-1];var i=new Pr(e);for(n=1;n<e;++n)i[n]=i[n-1]+o[n-1]<<1;var a;if(t){a=new Pr(1<<e);var c=15-e;for(n=0;n<r;++n)if(s[n])for(var h=n<<4|s[n],d=e-s[n],u=i[s[n]-1]++<<d,l=u|(1<<d)-1;u<=l;++u)a[Bi[u]>>c]=h}else for(a=new Pr(r),n=0;n<r;++n)s[n]&&(a[n]=Bi[i[s[n]-1]++]>>15-s[n]);return a},Xr=new ct(288),Ie=0;Ie<144;++Ie)Xr[Ie]=8;for(var Ie=144;Ie<256;++Ie)Xr[Ie]=9;for(var Ie=256;Ie<280;++Ie)Xr[Ie]=7;for(var Ie=280;Ie<288;++Ie)Xr[Ie]=8;for(var po=new ct(32),Ie=0;Ie<32;++Ie)po[Ie]=5;var Gu=Kr(Xr,9,1),Vu=Kr(po,5,1),zi=function(s){for(var e=s[0],t=1;t<s.length;++t)s[t]>e&&(e=s[t]);return e},yt=function(s,e,t){var r=e/8|0;return(s[r]|s[r+1]<<8)>>(e&7)&t},Ei=function(s,e){var t=e/8|0;return(s[t]|s[t+1]<<8|s[t+2]<<16)>>(e&7)},ju=function(s){return(s+7)/8|0},Wu=function(s,e,t){return(t==null||t>s.length)&&(t=s.length),new ct(s.subarray(e,t))},Yu=["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"],bt=function(s,e,t){var r=new Error(e||Yu[s]);if(r.code=s,Error.captureStackTrace&&Error.captureStackTrace(r,bt),!t)throw r;return r},qu=function(s,e,t,r){var n=s.length,o=0;if(!n||e.f&&!e.l)return t||new ct(0);var i=!t,a=i||e.i!=2,c=e.i;i&&(t=new ct(n*3));var h=function(Dt){var _t=t.length;if(Dt>_t){var Rt=new ct(Math.max(_t*2,Dt));Rt.set(t),t=Rt}},d=e.f||0,u=e.p||0,l=e.b||0,v=e.l,b=e.d,S=e.m,g=e.n,x=n*8;do{if(!v){d=yt(s,u,1);var w=yt(s,u+1,3);if(u+=3,w)if(w==1)v=Gu,b=Vu,S=9,g=5;else if(w==2){var D=yt(s,u,31)+257,R=yt(s,u+10,15)+4,O=D+yt(s,u+5,31)+1;u+=14;for(var L=new ct(O),E=new ct(19),G=0;G<R;++G)E[Bu[G]]=yt(s,u+G*3,7);u+=R*3;for(var z=zi(E),V=(1<<z)-1,U=Kr(E,z,1),G=0;G<O;){var H=U[yt(s,u,V)];u+=H&15;var T=H>>4;if(T<16)L[G++]=T;else{var ne=0,ge=0;for(T==16?(ge=3+yt(s,u,3),u+=2,ne=L[G-1]):T==17?(ge=3+yt(s,u,7),u+=3):T==18&&(ge=11+yt(s,u,127),u+=7);ge--;)L[G++]=ne}}var Pe=L.subarray(0,D),ve=L.subarray(D);S=zi(Pe),g=zi(ve),v=Kr(Pe,S,1),b=Kr(ve,g,1)}else bt(1);else{var T=ju(u)+4,A=s[T-4]|s[T-3]<<8,P=T+A;if(P>n){c&&bt(0);break}a&&h(l+A),t.set(s.subarray(T,P),l),e.b=l+=A,e.p=u=P*8,e.f=d;continue}if(u>x){c&&bt(0);break}}a&&h(l+131072);for(var ye=(1<<S)-1,Ue=(1<<g)-1,_e=u;;_e=u){var ne=v[Ei(s,u)&ye],Te=ne>>4;if(u+=ne&15,u>x){c&&bt(0);break}if(ne||bt(2),Te<256)t[l++]=Te;else if(Te==256){_e=u,v=null;break}else{var et=Te-254;if(Te>264){var G=Te-257,lt=co[G];et=yt(s,u,(1<<lt)-1)+fo[G],u+=lt}var de=b[Ei(s,u)&Ue],ze=de>>4;de||bt(3),u+=de&15;var ve=Uu[ze];if(ze>3){var lt=lo[ze];ve+=Ei(s,u)&(1<<lt)-1,u+=lt}if(u>x){c&&bt(0);break}a&&h(l+131072);var ke=l+et;if(l<ve){var ut=o-ve,tt=Math.min(ve,ke);for(ut+l<0&&bt(3);l<tt;++l)t[l]=r[ut+l]}for(;l<ke;++l)t[l]=t[l-ve]}}e.l=v,e.p=_e,e.b=l,e.f=d,v&&(d=1,e.m=S,e.d=b,e.n=g)}while(!d);return l!=t.length&&i?Wu(t,0,l):t.subarray(0,l)},Zu=new ct(0),Ku=function(s,e){return((s[0]&15)!=8||s[0]>>4>7||(s[0]<<8|s[1])%31)&&bt(6,"invalid zlib data"),(s[1]>>5&1)==1&&bt(6,"invalid zlib data: "+(s[1]&32?"need":"unexpected")+" dictionary"),(s[1]>>3&4)+2};function Gn(s,e){return qu(s.subarray(Ku(s),-4),{i:2},e,e)}var Xu=typeof TextDecoder<"u"&&new TextDecoder,$u=0;try{Xu.decode(Zu,{stream:!0}),$u=1}catch{}class Qu extends f.DataTextureLoader{constructor(e){super(e),this.type=f.HalfFloatType}parse(e){const L=Math.pow(2.7182818,2.2);function E(p,y){let _=0;for(let k=0;k<65536;++k)(k==0||p[k>>3]&1<<(k&7))&&(y[_++]=k);const I=_-1;for(;_<65536;)y[_++]=0;return I}function G(p){for(let y=0;y<16384;y++)p[y]={},p[y].len=0,p[y].lit=0,p[y].p=null}const z={l:0,c:0,lc:0};function V(p,y,_,I,k){for(;_<p;)y=y<<8|Lr(I,k),_+=8;_-=p,z.l=y>>_&(1<<p)-1,z.c=y,z.lc=_}const U=new Array(59);function H(p){for(let _=0;_<=58;++_)U[_]=0;for(let _=0;_<65537;++_)U[p[_]]+=1;let y=0;for(let _=58;_>0;--_){const I=y+U[_]>>1;U[_]=y,y=I}for(let _=0;_<65537;++_){const I=p[_];I>0&&(p[_]=I|U[I]++<<6)}}function ne(p,y,_,I,k,F){const B=y;let Z=0,Y=0;for(;I<=k;I++){if(B.value-y.value>_)return!1;V(6,Z,Y,p,B);const j=z.l;if(Z=z.c,Y=z.lc,F[I]=j,j==63){if(B.value-y.value>_)throw new Error("Something wrong with hufUnpackEncTable");V(8,Z,Y,p,B);let W=z.l+6;if(Z=z.c,Y=z.lc,I+W>k+1)throw new Error("Something wrong with hufUnpackEncTable");for(;W--;)F[I++]=0;I--}else if(j>=59){let W=j-59+2;if(I+W>k+1)throw new Error("Something wrong with hufUnpackEncTable");for(;W--;)F[I++]=0;I--}}H(F)}function ge(p){return p&63}function Pe(p){return p>>6}function ve(p,y,_,I){for(;y<=_;y++){const k=Pe(p[y]),F=ge(p[y]);if(k>>F)throw new Error("Invalid table entry");if(F>14){const B=I[k>>F-14];if(B.len)throw new Error("Invalid table entry");if(B.lit++,B.p){const Z=B.p;B.p=new Array(B.lit);for(let Y=0;Y<B.lit-1;++Y)B.p[Y]=Z[Y]}else B.p=new Array(1);B.p[B.lit-1]=y}else if(F){let B=0;for(let Z=1<<14-F;Z>0;Z--){const Y=I[(k<<14-F)+B];if(Y.len||Y.p)throw new Error("Invalid table entry");Y.len=F,Y.lit=y,B++}}}return!0}const ye={c:0,lc:0};function Ue(p,y,_,I){p=p<<8|Lr(_,I),y+=8,ye.c=p,ye.lc=y}const _e={c:0,lc:0};function Te(p,y,_,I,k,F,B,Z,Y){if(p==y){I<8&&(Ue(_,I,k,F),_=ye.c,I=ye.lc),I-=8;let j=_>>I;if(j=new Uint8Array([j])[0],Z.value+j>Y)return!1;const W=B[Z.value-1];for(;j-- >0;)B[Z.value++]=W}else if(Z.value<Y)B[Z.value++]=p;else return!1;_e.c=_,_e.lc=I}function et(p){return p&65535}function lt(p){const y=et(p);return y>32767?y-65536:y}const de={a:0,b:0};function ze(p,y){const _=lt(p),k=lt(y),F=_+(k&1)+(k>>1),B=F,Z=F-k;de.a=B,de.b=Z}function ke(p,y){const _=et(p),I=et(y),k=_-(I>>1)&65535,F=I+k-32768&65535;de.a=F,de.b=k}function ut(p,y,_,I,k,F,B){const Z=B<16384,Y=_>k?k:_;let j=1,W,J;for(;j<=Y;)j<<=1;for(j>>=1,W=j,j>>=1;j>=1;){J=0;const re=J+F*(k-W),ee=F*j,le=F*W,te=I*j,se=I*W;let he,Se,Re,it;for(;J<=re;J+=le){let Ce=J;const me=J+I*(_-W);for(;Ce<=me;Ce+=se){const Be=Ce+te,dt=Ce+ee,Ee=dt+te;Z?(ze(p[Ce+y],p[dt+y]),he=de.a,Re=de.b,ze(p[Be+y],p[Ee+y]),Se=de.a,it=de.b,ze(he,Se),p[Ce+y]=de.a,p[Be+y]=de.b,ze(Re,it),p[dt+y]=de.a,p[Ee+y]=de.b):(ke(p[Ce+y],p[dt+y]),he=de.a,Re=de.b,ke(p[Be+y],p[Ee+y]),Se=de.a,it=de.b,ke(he,Se),p[Ce+y]=de.a,p[Be+y]=de.b,ke(Re,it),p[dt+y]=de.a,p[Ee+y]=de.b)}if(_&j){const Be=Ce+ee;Z?ze(p[Ce+y],p[Be+y]):ke(p[Ce+y],p[Be+y]),he=de.a,p[Be+y]=de.b,p[Ce+y]=he}}if(k&j){let Ce=J;const me=J+I*(_-W);for(;Ce<=me;Ce+=se){const Be=Ce+te;Z?ze(p[Ce+y],p[Be+y]):ke(p[Ce+y],p[Be+y]),he=de.a,p[Be+y]=de.b,p[Ce+y]=he}}W=j,j>>=1}return J}function tt(p,y,_,I,k,F,B,Z,Y){let j=0,W=0;const J=B,re=Math.trunc(I.value+(k+7)/8);for(;I.value<re;)for(Ue(j,W,_,I),j=ye.c,W=ye.lc;W>=14;){const le=j>>W-14&16383,te=y[le];if(te.len)W-=te.len,Te(te.lit,F,j,W,_,I,Z,Y,J),j=_e.c,W=_e.lc;else{if(!te.p)throw new Error("hufDecode issues");let se;for(se=0;se<te.lit;se++){const he=ge(p[te.p[se]]);for(;W<he&&I.value<re;)Ue(j,W,_,I),j=ye.c,W=ye.lc;if(W>=he&&Pe(p[te.p[se]])==(j>>W-he&(1<<he)-1)){W-=he,Te(te.p[se],F,j,W,_,I,Z,Y,J),j=_e.c,W=_e.lc;break}}if(se==te.lit)throw new Error("hufDecode issues")}}const ee=8-k&7;for(j>>=ee,W-=ee;W>0;){const le=y[j<<14-W&16383];if(le.len)W-=le.len,Te(le.lit,F,j,W,_,I,Z,Y,J),j=_e.c,W=_e.lc;else throw new Error("hufDecode issues")}return!0}function Dt(p,y,_,I,k,F){const B={value:0},Z=_.value,Y=je(y,_),j=je(y,_);_.value+=4;const W=je(y,_);if(_.value+=4,Y<0||Y>=65537||j<0||j>=65537)throw new Error("Something wrong with HUF_ENCSIZE");const J=new Array(65537),re=new Array(16384);G(re);const ee=I-(_.value-Z);if(ne(p,_,ee,Y,j,J),W>8*(I-(_.value-Z)))throw new Error("Something wrong with hufUncompress");ve(J,Y,j,re),tt(J,re,p,_,W,j,F,k,B)}function _t(p,y,_){for(let I=0;I<_;++I)y[I]=p[y[I]]}function Rt(p){for(let y=1;y<p.length;y++){const _=p[y-1]+p[y]-128;p[y]=_}}function Fr(p,y){let _=0,I=Math.floor((p.length+1)/2),k=0;const F=p.length-1;for(;!(k>F||(y[k++]=p[_++],k>F));)y[k++]=p[I++]}function ht(p){let y=p.byteLength;const _=new Array;let I=0;const k=new DataView(p);for(;y>0;){const F=k.getInt8(I++);if(F<0){const B=-F;y-=B+1;for(let Z=0;Z<B;Z++)_.push(k.getUint8(I++))}else{const B=F;y-=2;const Z=k.getUint8(I++);for(let Y=0;Y<B+1;Y++)_.push(Z)}}return _}function rt(p,y,_,I,k,F){let B=new DataView(F.buffer);const Z=_[p.idx[0]].width,Y=_[p.idx[0]].height,j=3,W=Math.floor(Z/8),J=Math.ceil(Z/8),re=Math.ceil(Y/8),ee=Z-(J-1)*8,le=Y-(re-1)*8,te={value:0},se=new Array(j),he=new Array(j),Se=new Array(j),Re=new Array(j),it=new Array(j);for(let me=0;me<j;++me)it[me]=y[p.idx[me]],se[me]=me<1?0:se[me-1]+J*re,he[me]=new Float32Array(64),Se[me]=new Uint16Array(64),Re[me]=new Uint16Array(J*64);for(let me=0;me<re;++me){let Be=8;me==re-1&&(Be=le);let dt=8;for(let be=0;be<J;++be){be==J-1&&(dt=ee);for(let Ae=0;Ae<j;++Ae)Se[Ae].fill(0),Se[Ae][0]=k[se[Ae]++],Jt(te,I,Se[Ae]),Ht(Se[Ae],he[Ae]),xt(he[Ae]);Jr(he);for(let Ae=0;Ae<j;++Ae)Hr(he[Ae],Re[Ae],be*64)}let Ee=0;for(let be=0;be<j;++be){const Ae=_[p.idx[be]].type;for(let Nt=8*me;Nt<8*me+Be;++Nt){Ee=it[be][Nt];for(let hn=0;hn<W;++hn){const Tt=hn*64+(Nt&7)*8;B.setUint16(Ee+0*2*Ae,Re[be][Tt+0],!0),B.setUint16(Ee+1*2*Ae,Re[be][Tt+1],!0),B.setUint16(Ee+2*2*Ae,Re[be][Tt+2],!0),B.setUint16(Ee+3*2*Ae,Re[be][Tt+3],!0),B.setUint16(Ee+4*2*Ae,Re[be][Tt+4],!0),B.setUint16(Ee+5*2*Ae,Re[be][Tt+5],!0),B.setUint16(Ee+6*2*Ae,Re[be][Tt+6],!0),B.setUint16(Ee+7*2*Ae,Re[be][Tt+7],!0),Ee+=8*2*Ae}}if(W!=J)for(let Nt=8*me;Nt<8*me+Be;++Nt){const hn=it[be][Nt]+8*W*2*Ae,Tt=W*64+(Nt&7)*8;for(let qn=0;qn<dt;++qn)B.setUint16(hn+qn*2*Ae,Re[be][Tt+qn],!0)}}}const Ce=new Uint16Array(Z);B=new DataView(F.buffer);for(let me=0;me<j;++me){_[p.idx[me]].decoded=!0;const Be=_[p.idx[me]].type;if(_[me].type==2)for(let dt=0;dt<Y;++dt){const Ee=it[me][dt];for(let be=0;be<Z;++be)Ce[be]=B.getUint16(Ee+be*2*Be,!0);for(let be=0;be<Z;++be)B.setFloat32(Ee+be*2*Be,X(Ce[be]),!0)}}}function Jt(p,y,_){let I,k=1;for(;k<64;)I=y[p.value],I==65280?k=64:I>>8==255?k+=I&255:(_[k]=I,k++),p.value++}function Ht(p,y){y[0]=X(p[0]),y[1]=X(p[1]),y[2]=X(p[5]),y[3]=X(p[6]),y[4]=X(p[14]),y[5]=X(p[15]),y[6]=X(p[27]),y[7]=X(p[28]),y[8]=X(p[2]),y[9]=X(p[4]),y[10]=X(p[7]),y[11]=X(p[13]),y[12]=X(p[16]),y[13]=X(p[26]),y[14]=X(p[29]),y[15]=X(p[42]),y[16]=X(p[3]),y[17]=X(p[8]),y[18]=X(p[12]),y[19]=X(p[17]),y[20]=X(p[25]),y[21]=X(p[30]),y[22]=X(p[41]),y[23]=X(p[43]),y[24]=X(p[9]),y[25]=X(p[11]),y[26]=X(p[18]),y[27]=X(p[24]),y[28]=X(p[31]),y[29]=X(p[40]),y[30]=X(p[44]),y[31]=X(p[53]),y[32]=X(p[10]),y[33]=X(p[19]),y[34]=X(p[23]),y[35]=X(p[32]),y[36]=X(p[39]),y[37]=X(p[45]),y[38]=X(p[52]),y[39]=X(p[54]),y[40]=X(p[20]),y[41]=X(p[22]),y[42]=X(p[33]),y[43]=X(p[38]),y[44]=X(p[46]),y[45]=X(p[51]),y[46]=X(p[55]),y[47]=X(p[60]),y[48]=X(p[21]),y[49]=X(p[34]),y[50]=X(p[37]),y[51]=X(p[47]),y[52]=X(p[50]),y[53]=X(p[56]),y[54]=X(p[59]),y[55]=X(p[61]),y[56]=X(p[35]),y[57]=X(p[36]),y[58]=X(p[48]),y[59]=X(p[49]),y[60]=X(p[57]),y[61]=X(p[58]),y[62]=X(p[62]),y[63]=X(p[63])}function xt(p){const y=.5*Math.cos(.7853975),_=.5*Math.cos(3.14159/16),I=.5*Math.cos(3.14159/8),k=.5*Math.cos(3*3.14159/16),F=.5*Math.cos(5*3.14159/16),B=.5*Math.cos(3*3.14159/8),Z=.5*Math.cos(7*3.14159/16),Y=new Array(4),j=new Array(4),W=new Array(4),J=new Array(4);for(let re=0;re<8;++re){const ee=re*8;Y[0]=I*p[ee+2],Y[1]=B*p[ee+2],Y[2]=I*p[ee+6],Y[3]=B*p[ee+6],j[0]=_*p[ee+1]+k*p[ee+3]+F*p[ee+5]+Z*p[ee+7],j[1]=k*p[ee+1]-Z*p[ee+3]-_*p[ee+5]-F*p[ee+7],j[2]=F*p[ee+1]-_*p[ee+3]+Z*p[ee+5]+k*p[ee+7],j[3]=Z*p[ee+1]-F*p[ee+3]+k*p[ee+5]-_*p[ee+7],W[0]=y*(p[ee+0]+p[ee+4]),W[3]=y*(p[ee+0]-p[ee+4]),W[1]=Y[0]+Y[3],W[2]=Y[1]-Y[2],J[0]=W[0]+W[1],J[1]=W[3]+W[2],J[2]=W[3]-W[2],J[3]=W[0]-W[1],p[ee+0]=J[0]+j[0],p[ee+1]=J[1]+j[1],p[ee+2]=J[2]+j[2],p[ee+3]=J[3]+j[3],p[ee+4]=J[3]-j[3],p[ee+5]=J[2]-j[2],p[ee+6]=J[1]-j[1],p[ee+7]=J[0]-j[0]}for(let re=0;re<8;++re)Y[0]=I*p[16+re],Y[1]=B*p[16+re],Y[2]=I*p[48+re],Y[3]=B*p[48+re],j[0]=_*p[8+re]+k*p[24+re]+F*p[40+re]+Z*p[56+re],j[1]=k*p[8+re]-Z*p[24+re]-_*p[40+re]-F*p[56+re],j[2]=F*p[8+re]-_*p[24+re]+Z*p[40+re]+k*p[56+re],j[3]=Z*p[8+re]-F*p[24+re]+k*p[40+re]-_*p[56+re],W[0]=y*(p[re]+p[32+re]),W[3]=y*(p[re]-p[32+re]),W[1]=Y[0]+Y[3],W[2]=Y[1]-Y[2],J[0]=W[0]+W[1],J[1]=W[3]+W[2],J[2]=W[3]-W[2],J[3]=W[0]-W[1],p[0+re]=J[0]+j[0],p[8+re]=J[1]+j[1],p[16+re]=J[2]+j[2],p[24+re]=J[3]+j[3],p[32+re]=J[3]-j[3],p[40+re]=J[2]-j[2],p[48+re]=J[1]-j[1],p[56+re]=J[0]-j[0]}function Jr(p){for(let y=0;y<64;++y){const _=p[0][y],I=p[1][y],k=p[2][y];p[0][y]=_+1.5747*k,p[1][y]=_-.1873*I-.4682*k,p[2][y]=_+1.8556*I}}function Hr(p,y,_){for(let I=0;I<64;++I)y[_+I]=f.DataUtils.toHalfFloat(Ft(p[I]))}function Ft(p){return p<=1?Math.sign(p)*Math.pow(Math.abs(p),2.2):Math.sign(p)*Math.pow(L,Math.abs(p)-1)}function er(p){return new DataView(p.array.buffer,p.offset.value,p.size)}function en(p){const y=p.viewer.buffer.slice(p.offset.value,p.offset.value+p.size),_=new Uint8Array(ht(y)),I=new Uint8Array(_.length);return Rt(_),Fr(_,I),new DataView(I.buffer)}function Ot(p){const y=p.array.slice(p.offset.value,p.offset.value+p.size),_=Gn(y),I=new Uint8Array(_.length);return Rt(_),Fr(_,I),new DataView(I.buffer)}function tr(p){const y=p.viewer,_={value:p.offset.value},I=new Uint16Array(p.columns*p.lines*(p.inputChannels.length*p.type)),k=new Uint8Array(8192);let F=0;const B=new Array(p.inputChannels.length);for(let le=0,te=p.inputChannels.length;le<te;le++)B[le]={},B[le].start=F,B[le].end=B[le].start,B[le].nx=p.columns,B[le].ny=p.lines,B[le].size=p.type,F+=B[le].nx*B[le].ny*B[le].size;const Z=nt(y,_),Y=nt(y,_);if(Y>=8192)throw new Error("Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(Z<=Y)for(let le=0;le<Y-Z+1;le++)k[le+Z]=ft(y,_);const j=new Uint16Array(65536),W=E(k,j),J=je(y,_);Dt(p.array,y,_,J,I,F);for(let le=0;le<p.inputChannels.length;++le){const te=B[le];for(let se=0;se<B[le].size;++se)ut(I,te.start+se,te.nx,te.size,te.ny,te.nx*te.size,W)}_t(j,I,F);let re=0;const ee=new Uint8Array(I.buffer.byteLength);for(let le=0;le<p.lines;le++)for(let te=0;te<p.inputChannels.length;te++){const se=B[te],he=se.nx*se.size,Se=new Uint8Array(I.buffer,se.end*2,he*2);ee.set(Se,re),re+=he*2,se.end+=he}return new DataView(ee.buffer)}function rr(p){const y=p.array.slice(p.offset.value,p.offset.value+p.size),_=Gn(y),I=p.inputChannels.length*p.lines*p.columns*p.totalBytes,k=new ArrayBuffer(I),F=new DataView(k);let B=0,Z=0;const Y=new Array(4);for(let j=0;j<p.lines;j++)for(let W=0;W<p.inputChannels.length;W++){let J=0;switch(p.inputChannels[W].pixelType){case 1:Y[0]=B,Y[1]=Y[0]+p.columns,B=Y[1]+p.columns;for(let ee=0;ee<p.columns;++ee){const le=_[Y[0]++]<<8|_[Y[1]++];J+=le,F.setUint16(Z,J,!0),Z+=2}break;case 2:Y[0]=B,Y[1]=Y[0]+p.columns,Y[2]=Y[1]+p.columns,B=Y[2]+p.columns;for(let ee=0;ee<p.columns;++ee){const le=_[Y[0]++]<<24|_[Y[1]++]<<16|_[Y[2]++]<<8;J+=le,F.setUint32(Z,J,!0),Z+=4}break}}return F}function Or(p){const y=p.viewer,_={value:p.offset.value},I=new Uint8Array(p.columns*p.lines*(p.inputChannels.length*p.type*2)),k={version:Ge(y,_),unknownUncompressedSize:Ge(y,_),unknownCompressedSize:Ge(y,_),acCompressedSize:Ge(y,_),dcCompressedSize:Ge(y,_),rleCompressedSize:Ge(y,_),rleUncompressedSize:Ge(y,_),rleRawSize:Ge(y,_),totalAcUncompressedCount:Ge(y,_),totalDcUncompressedCount:Ge(y,_),acCompression:Ge(y,_)};if(k.version<2)throw new Error("EXRLoader.parse: "+Q.compression+" version "+k.version+" is unsupported");const F=new Array;let B=nt(y,_)-2;for(;B>0;){const te=St(y.buffer,_),se=ft(y,_),he=se>>2&3,Se=(se>>4)-1,Re=new Int8Array([Se])[0],it=ft(y,_);F.push({name:te,index:Re,type:it,compression:he}),B-=te.length+3}const Z=Q.channels,Y=new Array(p.inputChannels.length);for(let te=0;te<p.inputChannels.length;++te){const se=Y[te]={},he=Z[te];se.name=he.name,se.compression=0,se.decoded=!1,se.type=he.pixelType,se.pLinear=he.pLinear,se.width=p.columns,se.height=p.lines}const j={idx:new Array(3)};for(let te=0;te<p.inputChannels.length;++te){const se=Y[te];for(let he=0;he<F.length;++he){const Se=F[he];se.name==Se.name&&(se.compression=Se.compression,Se.index>=0&&(j.idx[Se.index]=te),se.offset=te)}}let W,J,re;if(k.acCompressedSize>0)switch(k.acCompression){case 0:W=new Uint16Array(k.totalAcUncompressedCount),Dt(p.array,y,_,k.acCompressedSize,W,k.totalAcUncompressedCount);break;case 1:const te=p.array.slice(_.value,_.value+k.totalAcUncompressedCount),se=Gn(te);W=new Uint16Array(se.buffer),_.value+=k.totalAcUncompressedCount;break}if(k.dcCompressedSize>0){const te={array:p.array,offset:_,size:k.dcCompressedSize};J=new Uint16Array(Ot(te).buffer),_.value+=k.dcCompressedSize}if(k.rleRawSize>0){const te=p.array.slice(_.value,_.value+k.rleCompressedSize),se=Gn(te);re=ht(se.buffer),_.value+=k.rleCompressedSize}let ee=0;const le=new Array(Y.length);for(let te=0;te<le.length;++te)le[te]=new Array;for(let te=0;te<p.lines;++te)for(let se=0;se<Y.length;++se)le[se].push(ee),ee+=Y[se].width*p.type*2;rt(j,le,Y,W,J,I);for(let te=0;te<Y.length;++te){const se=Y[te];if(!se.decoded)switch(se.compression){case 2:let he=0,Se=0;for(let Re=0;Re<p.lines;++Re){let it=le[te][he];for(let Ce=0;Ce<se.width;++Ce){for(let me=0;me<2*se.type;++me)I[it++]=re[Se+me*se.width*se.height];Se++}he++}break;case 1:default:throw new Error("EXRLoader.parse: unsupported channel compression")}}return new DataView(I.buffer)}function St(p,y){const _=new Uint8Array(p);let I=0;for(;_[y.value+I]!=0;)I+=1;const k=new TextDecoder().decode(_.slice(y.value,y.value+I));return y.value=y.value+I+1,k}function nr(p,y,_){const I=new TextDecoder().decode(new Uint8Array(p).slice(y.value,y.value+_));return y.value=y.value+_,I}function tn(p,y){const _=Ve(p,y),I=je(p,y);return[_,I]}function rn(p,y){const _=je(p,y),I=je(p,y);return[_,I]}function Ve(p,y){const _=p.getInt32(y.value,!0);return y.value=y.value+4,_}function je(p,y){const _=p.getUint32(y.value,!0);return y.value=y.value+4,_}function Lr(p,y){const _=p[y.value];return y.value=y.value+1,_}function ft(p,y){const _=p.getUint8(y.value);return y.value=y.value+1,_}const Ge=function(p,y){let _;return"getBigInt64"in DataView.prototype?_=Number(p.getBigInt64(y.value,!0)):_=p.getUint32(y.value+4,!0)+Number(p.getUint32(y.value,!0)<<32),y.value+=8,_};function De(p,y){const _=p.getFloat32(y.value,!0);return y.value+=4,_}function ir(p,y){return f.DataUtils.toHalfFloat(De(p,y))}function X(p){const y=(p&31744)>>10,_=p&1023;return(p>>15?-1:1)*(y?y===31?_?NaN:1/0:Math.pow(2,y-15)*(1+_/1024):6103515625e-14*(_/1024))}function nt(p,y){const _=p.getUint16(y.value,!0);return y.value+=2,_}function Lt(p,y){return X(nt(p,y))}function sr(p,y,_,I){const k=_.value,F=[];for(;_.value<k+I-1;){const B=St(y,_),Z=Ve(p,_),Y=ft(p,_);_.value+=3;const j=Ve(p,_),W=Ve(p,_);F.push({name:B,pixelType:Z,pLinear:Y,xSampling:j,ySampling:W})}return _.value+=1,F}function nn(p,y){const _=De(p,y),I=De(p,y),k=De(p,y),F=De(p,y),B=De(p,y),Z=De(p,y),Y=De(p,y),j=De(p,y);return{redX:_,redY:I,greenX:k,greenY:F,blueX:B,blueY:Z,whiteX:Y,whiteY:j}}function or(p,y){const _=["NO_COMPRESSION","RLE_COMPRESSION","ZIPS_COMPRESSION","ZIP_COMPRESSION","PIZ_COMPRESSION","PXR24_COMPRESSION","B44_COMPRESSION","B44A_COMPRESSION","DWAA_COMPRESSION","DWAB_COMPRESSION"],I=ft(p,y);return _[I]}function sn(p,y){const _=Ve(p,y),I=Ve(p,y),k=Ve(p,y),F=Ve(p,y);return{xMin:_,yMin:I,xMax:k,yMax:F}}function ar(p,y){const _=["INCREASING_Y","DECREASING_Y","RANDOM_Y"],I=ft(p,y);return _[I]}function cr(p,y){const _=["ENVMAP_LATLONG","ENVMAP_CUBE"],I=ft(p,y);return _[I]}function on(p,y){const _=["ONE_LEVEL","MIPMAP_LEVELS","RIPMAP_LEVELS"],I=["ROUND_DOWN","ROUND_UP"],k=je(p,y),F=je(p,y),B=ft(p,y);return{xSize:k,ySize:F,levelMode:_[B&15],roundingMode:I[B>>4]}}function an(p,y){const _=De(p,y),I=De(p,y);return[_,I]}function lr(p,y){const _=De(p,y),I=De(p,y),k=De(p,y);return[_,I,k]}function ur(p,y,_,I,k){if(I==="string"||I==="stringvector"||I==="iccProfile")return nr(y,_,k);if(I==="chlist")return sr(p,y,_,k);if(I==="chromaticities")return nn(p,_);if(I==="compression")return or(p,_);if(I==="box2i")return sn(p,_);if(I==="envmap")return cr(p,_);if(I==="tiledesc")return on(p,_);if(I==="lineOrder")return ar(p,_);if(I==="float")return De(p,_);if(I==="v2f")return an(p,_);if(I==="v3f")return lr(p,_);if(I==="int")return Ve(p,_);if(I==="rational")return tn(p,_);if(I==="timecode")return rn(p,_);if(I==="preview")return _.value+=k,"skipped";_.value+=k}function cn(p,y){const _=Math.log2(p);return y=="ROUND_DOWN"?Math.floor(_):Math.ceil(_)}function ln(p,y,_){let I=0;switch(p.levelMode){case"ONE_LEVEL":I=1;break;case"MIPMAP_LEVELS":I=cn(Math.max(y,_),p.roundingMode)+1;break;case"RIPMAP_LEVELS":throw new Error("THREE.EXRLoader: RIPMAP_LEVELS tiles currently unsupported.")}return I}function Nr(p,y,_,I){const k=new Array(p);for(let F=0;F<p;F++){const B=1<<F;let Z=y/B|0;I=="ROUND_UP"&&Z*B<y&&(Z+=1);const Y=Math.max(Z,1);k[F]=(Y+_-1)/_|0}return k}function un(){const p=this,y=p.offset,_={value:0};for(let I=0;I<p.tileCount;I++){const k=Ve(p.viewer,y),F=Ve(p.viewer,y);y.value+=8,p.size=je(p.viewer,y);const B=k*p.blockWidth,Z=F*p.blockHeight;p.columns=B+p.blockWidth>p.width?p.width-B:p.blockWidth,p.lines=Z+p.blockHeight>p.height?p.height-Z:p.blockHeight;const Y=p.columns*p.totalBytes,W=p.size<p.lines*Y?p.uncompress(p):er(p);y.value+=p.size;for(let J=0;J<p.lines;J++){const re=J*p.columns*p.totalBytes;for(let ee=0;ee<p.inputChannels.length;ee++){const le=Q.channels[ee].name,te=p.channelByteOffsets[le]*p.columns,se=p.decodeChannels[le];if(se===void 0)continue;_.value=re+te;const he=(p.height-(1+Z+J))*p.outLineWidth;for(let Se=0;Se<p.columns;Se++){const Re=he+(Se+B)*p.outputChannels+se;p.byteArray[Re]=p.getter(W,_)}}}}}function m(){const p=this,y=p.offset,_={value:0};for(let I=0;I<p.height/p.blockHeight;I++){const k=Ve(p.viewer,y)-Q.dataWindow.yMin;p.size=je(p.viewer,y),p.lines=k+p.blockHeight>p.height?p.height-k:p.blockHeight;const F=p.columns*p.totalBytes,Z=p.size<p.lines*F?p.uncompress(p):er(p);y.value+=p.size;for(let Y=0;Y<p.blockHeight;Y++){const j=I*p.blockHeight,W=Y+p.scanOrder(j);if(W>=p.height)continue;const J=Y*F,re=(p.height-1-W)*p.outLineWidth;for(let ee=0;ee<p.inputChannels.length;ee++){const le=Q.channels[ee].name,te=p.channelByteOffsets[le]*p.columns,se=p.decodeChannels[le];if(se!==void 0){_.value=J+te;for(let he=0;he<p.columns;he++){const Se=re+he*p.outputChannels+se;p.byteArray[Se]=p.getter(Z,_)}}}}}}function C(p,y,_){const I={};if(p.getUint32(0,!0)!=20000630)throw new Error("THREE.EXRLoader: Provided file doesn't appear to be in OpenEXR format.");I.version=p.getUint8(4);const k=p.getUint8(5);I.spec={singleTile:!!(k&2),longName:!!(k&4),deepFormat:!!(k&8),multiPart:!!(k&16)},_.value=8;let F=!0;for(;F;){const B=St(y,_);if(B==0)F=!1;else{const Z=St(y,_),Y=je(p,_),j=ur(p,y,_,Z,Y);j===void 0?console.warn(`THREE.EXRLoader: Skipped unknown header attribute type '${Z}'.`):I[B]=j}}if((k&-7)!=0)throw console.error("THREE.EXRHeader:",I),new Error("THREE.EXRLoader: Provided file is currently unsupported.");return I}function N(p,y,_,I,k){const F={size:0,viewer:y,array:_,offset:I,width:p.dataWindow.xMax-p.dataWindow.xMin+1,height:p.dataWindow.yMax-p.dataWindow.yMin+1,inputChannels:p.channels,channelByteOffsets:{},scanOrder:null,totalBytes:null,columns:null,lines:null,type:null,uncompress:null,getter:null,format:null,colorSpace:f.LinearSRGBColorSpace};switch(p.compression){case"NO_COMPRESSION":F.blockHeight=1,F.uncompress=er;break;case"RLE_COMPRESSION":F.blockHeight=1,F.uncompress=en;break;case"ZIPS_COMPRESSION":F.blockHeight=1,F.uncompress=Ot;break;case"ZIP_COMPRESSION":F.blockHeight=16,F.uncompress=Ot;break;case"PIZ_COMPRESSION":F.blockHeight=32,F.uncompress=tr;break;case"PXR24_COMPRESSION":F.blockHeight=16,F.uncompress=rr;break;case"DWAA_COMPRESSION":F.blockHeight=32,F.uncompress=Or;break;case"DWAB_COMPRESSION":F.blockHeight=256,F.uncompress=Or;break;default:throw new Error("EXRLoader.parse: "+p.compression+" is unsupported")}const B={};for(const W of p.channels)switch(W.name){case"Y":case"R":case"G":case"B":case"A":B[W.name]=!0,F.type=W.pixelType}let Z=!1;if(B.R&&B.G&&B.B)Z=!B.A,F.outputChannels=4,F.decodeChannels={R:0,G:1,B:2,A:3};else if(B.Y)F.outputChannels=1,F.decodeChannels={Y:0};else throw new Error("EXRLoader.parse: file contains unsupported data channels.");if(F.type==1)switch(k){case f.FloatType:F.getter=Lt;break;case f.HalfFloatType:F.getter=nt;break}else if(F.type==2)switch(k){case f.FloatType:F.getter=De;break;case f.HalfFloatType:F.getter=ir}else throw new Error("EXRLoader.parse: unsupported pixelType "+F.type+" for "+p.compression+".");F.columns=F.width;const Y=F.width*F.height*F.outputChannels;switch(k){case f.FloatType:F.byteArray=new Float32Array(Y),Z&&F.byteArray.fill(1,0,Y);break;case f.HalfFloatType:F.byteArray=new Uint16Array(Y),Z&&F.byteArray.fill(15360,0,Y);break;default:console.error("THREE.EXRLoader: unsupported type: ",k);break}let j=0;for(const W of p.channels)F.decodeChannels[W.name]!==void 0&&(F.channelByteOffsets[W.name]=j),j+=W.pixelType*2;if(F.totalBytes=j,F.outLineWidth=F.width*F.outputChannels,p.lineOrder==="INCREASING_Y"?F.scanOrder=W=>W:F.scanOrder=W=>F.height-1-W,F.outputChannels==4?(F.format=f.RGBAFormat,F.colorSpace=f.LinearSRGBColorSpace):(F.format=f.RedFormat,F.colorSpace=f.NoColorSpace),p.spec.singleTile){F.blockHeight=p.tiles.ySize,F.blockWidth=p.tiles.xSize;const W=ln(p.tiles,F.width,F.height),J=Nr(W,F.width,p.tiles.xSize,p.tiles.roundingMode),re=Nr(W,F.height,p.tiles.ySize,p.tiles.roundingMode);F.tileCount=J[0]*re[0];for(let ee=0;ee<W;ee++)for(let le=0;le<re[ee];le++)for(let te=0;te<J[ee];te++)Ge(y,I);F.decode=un.bind(F)}else{F.blockWidth=F.width;const W=Math.ceil(F.height/F.blockHeight);for(let J=0;J<W;J++)Ge(y,I);F.decode=m.bind(F)}return F}const q={value:0},ie=new DataView(e),ae=new Uint8Array(e),Q=C(ie,e,q),$=N(Q,ie,ae,q,this.type);return $.decode(),{header:Q,width:$.width,height:$.height,data:$.byteArray,format:$.format,colorSpace:$.colorSpace,type:this.type}}setDataType(e){return this.type=e,this}load(e,t,r,n){function o(i,a){i.colorSpace=a.colorSpace,i.minFilter=f.LinearFilter,i.magFilter=f.LinearFilter,i.generateMipmaps=!1,i.flipY=!1,t&&t(i,a)}return super.load(e,o,r,n)}}class Ju extends f.DataTextureLoader{constructor(e){super(e),this.type=f.HalfFloatType}parse(e){const i=function(O,L){switch(O){case 1:throw new Error("THREE.RGBELoader: Read Error: "+(L||""));case 2:throw new Error("THREE.RGBELoader: Write Error: "+(L||""));case 3:throw new Error("THREE.RGBELoader: Bad File Format: "+(L||""));default:case 4:throw new Error("THREE.RGBELoader: Memory Error: "+(L||""))}},d=`
|
|
4011
|
+
*/var ct=Uint8Array,Pr=Uint16Array,Bu=Int32Array,co=new ct([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]),lo=new ct([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]),zu=new ct([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),uo=function(s,e){for(var t=new Pr(31),r=0;r<31;++r)t[r]=e+=1<<s[r-1];for(var n=new Bu(t[30]),r=1;r<30;++r)for(var o=t[r];o<t[r+1];++o)n[o]=o-t[r]<<5|r;return{b:t,r:n}},ho=uo(co,2),fo=ho.b,Eu=ho.r;fo[28]=258,Eu[258]=28;for(var Uu=uo(lo,0),Gu=Uu.b,Bi=new Pr(32768),Ie=0;Ie<32768;++Ie){var jt=(Ie&43690)>>1|(Ie&21845)<<1;jt=(jt&52428)>>2|(jt&13107)<<2,jt=(jt&61680)>>4|(jt&3855)<<4,Bi[Ie]=((jt&65280)>>8|(jt&255)<<8)>>1}for(var Kr=function(s,e,t){for(var r=s.length,n=0,o=new Pr(e);n<r;++n)s[n]&&++o[s[n]-1];var i=new Pr(e);for(n=1;n<e;++n)i[n]=i[n-1]+o[n-1]<<1;var a;if(t){a=new Pr(1<<e);var c=15-e;for(n=0;n<r;++n)if(s[n])for(var h=n<<4|s[n],d=e-s[n],u=i[s[n]-1]++<<d,l=u|(1<<d)-1;u<=l;++u)a[Bi[u]>>c]=h}else for(a=new Pr(r),n=0;n<r;++n)s[n]&&(a[n]=Bi[i[s[n]-1]++]>>15-s[n]);return a},Xr=new ct(288),Ie=0;Ie<144;++Ie)Xr[Ie]=8;for(var Ie=144;Ie<256;++Ie)Xr[Ie]=9;for(var Ie=256;Ie<280;++Ie)Xr[Ie]=7;for(var Ie=280;Ie<288;++Ie)Xr[Ie]=8;for(var po=new ct(32),Ie=0;Ie<32;++Ie)po[Ie]=5;var Vu=Kr(Xr,9,1),ju=Kr(po,5,1),zi=function(s){for(var e=s[0],t=1;t<s.length;++t)s[t]>e&&(e=s[t]);return e},yt=function(s,e,t){var r=e/8|0;return(s[r]|s[r+1]<<8)>>(e&7)&t},Ei=function(s,e){var t=e/8|0;return(s[t]|s[t+1]<<8|s[t+2]<<16)>>(e&7)},Wu=function(s){return(s+7)/8|0},Yu=function(s,e,t){return(t==null||t>s.length)&&(t=s.length),new ct(s.subarray(e,t))},qu=["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"],xt=function(s,e,t){var r=new Error(e||qu[s]);if(r.code=s,Error.captureStackTrace&&Error.captureStackTrace(r,xt),!t)throw r;return r},Zu=function(s,e,t,r){var n=s.length,o=0;if(!n||e.f&&!e.l)return t||new ct(0);var i=!t,a=i||e.i!=2,c=e.i;i&&(t=new ct(n*3));var h=function(Dt){var _t=t.length;if(Dt>_t){var Rt=new ct(Math.max(_t*2,Dt));Rt.set(t),t=Rt}},d=e.f||0,u=e.p||0,l=e.b||0,v=e.l,x=e.d,S=e.m,g=e.n,b=n*8;do{if(!v){d=yt(s,u,1);var w=yt(s,u+1,3);if(u+=3,w)if(w==1)v=Vu,x=ju,S=9,g=5;else if(w==2){var D=yt(s,u,31)+257,R=yt(s,u+10,15)+4,O=D+yt(s,u+5,31)+1;u+=14;for(var L=new ct(O),E=new ct(19),G=0;G<R;++G)E[zu[G]]=yt(s,u+G*3,7);u+=R*3;for(var z=zi(E),V=(1<<z)-1,U=Kr(E,z,1),G=0;G<O;){var H=U[yt(s,u,V)];u+=H&15;var T=H>>4;if(T<16)L[G++]=T;else{var ne=0,ge=0;for(T==16?(ge=3+yt(s,u,3),u+=2,ne=L[G-1]):T==17?(ge=3+yt(s,u,7),u+=3):T==18&&(ge=11+yt(s,u,127),u+=7);ge--;)L[G++]=ne}}var Pe=L.subarray(0,D),ve=L.subarray(D);S=zi(Pe),g=zi(ve),v=Kr(Pe,S,1),x=Kr(ve,g,1)}else xt(1);else{var T=Wu(u)+4,A=s[T-4]|s[T-3]<<8,P=T+A;if(P>n){c&&xt(0);break}a&&h(l+A),t.set(s.subarray(T,P),l),e.b=l+=A,e.p=u=P*8,e.f=d;continue}if(u>b){c&&xt(0);break}}a&&h(l+131072);for(var ye=(1<<S)-1,Ue=(1<<g)-1,_e=u;;_e=u){var ne=v[Ei(s,u)&ye],Te=ne>>4;if(u+=ne&15,u>b){c&&xt(0);break}if(ne||xt(2),Te<256)t[l++]=Te;else if(Te==256){_e=u,v=null;break}else{var et=Te-254;if(Te>264){var G=Te-257,lt=co[G];et=yt(s,u,(1<<lt)-1)+fo[G],u+=lt}var de=x[Ei(s,u)&Ue],ze=de>>4;de||xt(3),u+=de&15;var ve=Gu[ze];if(ze>3){var lt=lo[ze];ve+=Ei(s,u)&(1<<lt)-1,u+=lt}if(u>b){c&&xt(0);break}a&&h(l+131072);var ke=l+et;if(l<ve){var ut=o-ve,tt=Math.min(ve,ke);for(ut+l<0&&xt(3);l<tt;++l)t[l]=r[ut+l]}for(;l<ke;++l)t[l]=t[l-ve]}}e.l=v,e.p=_e,e.b=l,e.f=d,v&&(d=1,e.m=S,e.d=x,e.n=g)}while(!d);return l!=t.length&&i?Yu(t,0,l):t.subarray(0,l)},Ku=new ct(0),Xu=function(s,e){return((s[0]&15)!=8||s[0]>>4>7||(s[0]<<8|s[1])%31)&&xt(6,"invalid zlib data"),(s[1]>>5&1)==1&&xt(6,"invalid zlib data: "+(s[1]&32?"need":"unexpected")+" dictionary"),(s[1]>>3&4)+2};function Gn(s,e){return Zu(s.subarray(Xu(s),-4),{i:2},e,e)}var $u=typeof TextDecoder<"u"&&new TextDecoder,Qu=0;try{$u.decode(Ku,{stream:!0}),Qu=1}catch{}class Ju extends f.DataTextureLoader{constructor(e){super(e),this.type=f.HalfFloatType}parse(e){const L=Math.pow(2.7182818,2.2);function E(p,y){let _=0;for(let k=0;k<65536;++k)(k==0||p[k>>3]&1<<(k&7))&&(y[_++]=k);const I=_-1;for(;_<65536;)y[_++]=0;return I}function G(p){for(let y=0;y<16384;y++)p[y]={},p[y].len=0,p[y].lit=0,p[y].p=null}const z={l:0,c:0,lc:0};function V(p,y,_,I,k){for(;_<p;)y=y<<8|Lr(I,k),_+=8;_-=p,z.l=y>>_&(1<<p)-1,z.c=y,z.lc=_}const U=new Array(59);function H(p){for(let _=0;_<=58;++_)U[_]=0;for(let _=0;_<65537;++_)U[p[_]]+=1;let y=0;for(let _=58;_>0;--_){const I=y+U[_]>>1;U[_]=y,y=I}for(let _=0;_<65537;++_){const I=p[_];I>0&&(p[_]=I|U[I]++<<6)}}function ne(p,y,_,I,k,F){const B=y;let Z=0,Y=0;for(;I<=k;I++){if(B.value-y.value>_)return!1;V(6,Z,Y,p,B);const j=z.l;if(Z=z.c,Y=z.lc,F[I]=j,j==63){if(B.value-y.value>_)throw new Error("Something wrong with hufUnpackEncTable");V(8,Z,Y,p,B);let W=z.l+6;if(Z=z.c,Y=z.lc,I+W>k+1)throw new Error("Something wrong with hufUnpackEncTable");for(;W--;)F[I++]=0;I--}else if(j>=59){let W=j-59+2;if(I+W>k+1)throw new Error("Something wrong with hufUnpackEncTable");for(;W--;)F[I++]=0;I--}}H(F)}function ge(p){return p&63}function Pe(p){return p>>6}function ve(p,y,_,I){for(;y<=_;y++){const k=Pe(p[y]),F=ge(p[y]);if(k>>F)throw new Error("Invalid table entry");if(F>14){const B=I[k>>F-14];if(B.len)throw new Error("Invalid table entry");if(B.lit++,B.p){const Z=B.p;B.p=new Array(B.lit);for(let Y=0;Y<B.lit-1;++Y)B.p[Y]=Z[Y]}else B.p=new Array(1);B.p[B.lit-1]=y}else if(F){let B=0;for(let Z=1<<14-F;Z>0;Z--){const Y=I[(k<<14-F)+B];if(Y.len||Y.p)throw new Error("Invalid table entry");Y.len=F,Y.lit=y,B++}}}return!0}const ye={c:0,lc:0};function Ue(p,y,_,I){p=p<<8|Lr(_,I),y+=8,ye.c=p,ye.lc=y}const _e={c:0,lc:0};function Te(p,y,_,I,k,F,B,Z,Y){if(p==y){I<8&&(Ue(_,I,k,F),_=ye.c,I=ye.lc),I-=8;let j=_>>I;if(j=new Uint8Array([j])[0],Z.value+j>Y)return!1;const W=B[Z.value-1];for(;j-- >0;)B[Z.value++]=W}else if(Z.value<Y)B[Z.value++]=p;else return!1;_e.c=_,_e.lc=I}function et(p){return p&65535}function lt(p){const y=et(p);return y>32767?y-65536:y}const de={a:0,b:0};function ze(p,y){const _=lt(p),k=lt(y),F=_+(k&1)+(k>>1),B=F,Z=F-k;de.a=B,de.b=Z}function ke(p,y){const _=et(p),I=et(y),k=_-(I>>1)&65535,F=I+k-32768&65535;de.a=F,de.b=k}function ut(p,y,_,I,k,F,B){const Z=B<16384,Y=_>k?k:_;let j=1,W,J;for(;j<=Y;)j<<=1;for(j>>=1,W=j,j>>=1;j>=1;){J=0;const re=J+F*(k-W),ee=F*j,le=F*W,te=I*j,se=I*W;let he,Se,Re,it;for(;J<=re;J+=le){let Ce=J;const me=J+I*(_-W);for(;Ce<=me;Ce+=se){const Be=Ce+te,dt=Ce+ee,Ee=dt+te;Z?(ze(p[Ce+y],p[dt+y]),he=de.a,Re=de.b,ze(p[Be+y],p[Ee+y]),Se=de.a,it=de.b,ze(he,Se),p[Ce+y]=de.a,p[Be+y]=de.b,ze(Re,it),p[dt+y]=de.a,p[Ee+y]=de.b):(ke(p[Ce+y],p[dt+y]),he=de.a,Re=de.b,ke(p[Be+y],p[Ee+y]),Se=de.a,it=de.b,ke(he,Se),p[Ce+y]=de.a,p[Be+y]=de.b,ke(Re,it),p[dt+y]=de.a,p[Ee+y]=de.b)}if(_&j){const Be=Ce+ee;Z?ze(p[Ce+y],p[Be+y]):ke(p[Ce+y],p[Be+y]),he=de.a,p[Be+y]=de.b,p[Ce+y]=he}}if(k&j){let Ce=J;const me=J+I*(_-W);for(;Ce<=me;Ce+=se){const Be=Ce+te;Z?ze(p[Ce+y],p[Be+y]):ke(p[Ce+y],p[Be+y]),he=de.a,p[Be+y]=de.b,p[Ce+y]=he}}W=j,j>>=1}return J}function tt(p,y,_,I,k,F,B,Z,Y){let j=0,W=0;const J=B,re=Math.trunc(I.value+(k+7)/8);for(;I.value<re;)for(Ue(j,W,_,I),j=ye.c,W=ye.lc;W>=14;){const le=j>>W-14&16383,te=y[le];if(te.len)W-=te.len,Te(te.lit,F,j,W,_,I,Z,Y,J),j=_e.c,W=_e.lc;else{if(!te.p)throw new Error("hufDecode issues");let se;for(se=0;se<te.lit;se++){const he=ge(p[te.p[se]]);for(;W<he&&I.value<re;)Ue(j,W,_,I),j=ye.c,W=ye.lc;if(W>=he&&Pe(p[te.p[se]])==(j>>W-he&(1<<he)-1)){W-=he,Te(te.p[se],F,j,W,_,I,Z,Y,J),j=_e.c,W=_e.lc;break}}if(se==te.lit)throw new Error("hufDecode issues")}}const ee=8-k&7;for(j>>=ee,W-=ee;W>0;){const le=y[j<<14-W&16383];if(le.len)W-=le.len,Te(le.lit,F,j,W,_,I,Z,Y,J),j=_e.c,W=_e.lc;else throw new Error("hufDecode issues")}return!0}function Dt(p,y,_,I,k,F){const B={value:0},Z=_.value,Y=je(y,_),j=je(y,_);_.value+=4;const W=je(y,_);if(_.value+=4,Y<0||Y>=65537||j<0||j>=65537)throw new Error("Something wrong with HUF_ENCSIZE");const J=new Array(65537),re=new Array(16384);G(re);const ee=I-(_.value-Z);if(ne(p,_,ee,Y,j,J),W>8*(I-(_.value-Z)))throw new Error("Something wrong with hufUncompress");ve(J,Y,j,re),tt(J,re,p,_,W,j,F,k,B)}function _t(p,y,_){for(let I=0;I<_;++I)y[I]=p[y[I]]}function Rt(p){for(let y=1;y<p.length;y++){const _=p[y-1]+p[y]-128;p[y]=_}}function Fr(p,y){let _=0,I=Math.floor((p.length+1)/2),k=0;const F=p.length-1;for(;!(k>F||(y[k++]=p[_++],k>F));)y[k++]=p[I++]}function ht(p){let y=p.byteLength;const _=new Array;let I=0;const k=new DataView(p);for(;y>0;){const F=k.getInt8(I++);if(F<0){const B=-F;y-=B+1;for(let Z=0;Z<B;Z++)_.push(k.getUint8(I++))}else{const B=F;y-=2;const Z=k.getUint8(I++);for(let Y=0;Y<B+1;Y++)_.push(Z)}}return _}function rt(p,y,_,I,k,F){let B=new DataView(F.buffer);const Z=_[p.idx[0]].width,Y=_[p.idx[0]].height,j=3,W=Math.floor(Z/8),J=Math.ceil(Z/8),re=Math.ceil(Y/8),ee=Z-(J-1)*8,le=Y-(re-1)*8,te={value:0},se=new Array(j),he=new Array(j),Se=new Array(j),Re=new Array(j),it=new Array(j);for(let me=0;me<j;++me)it[me]=y[p.idx[me]],se[me]=me<1?0:se[me-1]+J*re,he[me]=new Float32Array(64),Se[me]=new Uint16Array(64),Re[me]=new Uint16Array(J*64);for(let me=0;me<re;++me){let Be=8;me==re-1&&(Be=le);let dt=8;for(let xe=0;xe<J;++xe){xe==J-1&&(dt=ee);for(let Ae=0;Ae<j;++Ae)Se[Ae].fill(0),Se[Ae][0]=k[se[Ae]++],Jt(te,I,Se[Ae]),Ht(Se[Ae],he[Ae]),bt(he[Ae]);Jr(he);for(let Ae=0;Ae<j;++Ae)Hr(he[Ae],Re[Ae],xe*64)}let Ee=0;for(let xe=0;xe<j;++xe){const Ae=_[p.idx[xe]].type;for(let Nt=8*me;Nt<8*me+Be;++Nt){Ee=it[xe][Nt];for(let hn=0;hn<W;++hn){const Tt=hn*64+(Nt&7)*8;B.setUint16(Ee+0*2*Ae,Re[xe][Tt+0],!0),B.setUint16(Ee+1*2*Ae,Re[xe][Tt+1],!0),B.setUint16(Ee+2*2*Ae,Re[xe][Tt+2],!0),B.setUint16(Ee+3*2*Ae,Re[xe][Tt+3],!0),B.setUint16(Ee+4*2*Ae,Re[xe][Tt+4],!0),B.setUint16(Ee+5*2*Ae,Re[xe][Tt+5],!0),B.setUint16(Ee+6*2*Ae,Re[xe][Tt+6],!0),B.setUint16(Ee+7*2*Ae,Re[xe][Tt+7],!0),Ee+=8*2*Ae}}if(W!=J)for(let Nt=8*me;Nt<8*me+Be;++Nt){const hn=it[xe][Nt]+8*W*2*Ae,Tt=W*64+(Nt&7)*8;for(let qn=0;qn<dt;++qn)B.setUint16(hn+qn*2*Ae,Re[xe][Tt+qn],!0)}}}const Ce=new Uint16Array(Z);B=new DataView(F.buffer);for(let me=0;me<j;++me){_[p.idx[me]].decoded=!0;const Be=_[p.idx[me]].type;if(_[me].type==2)for(let dt=0;dt<Y;++dt){const Ee=it[me][dt];for(let xe=0;xe<Z;++xe)Ce[xe]=B.getUint16(Ee+xe*2*Be,!0);for(let xe=0;xe<Z;++xe)B.setFloat32(Ee+xe*2*Be,X(Ce[xe]),!0)}}}function Jt(p,y,_){let I,k=1;for(;k<64;)I=y[p.value],I==65280?k=64:I>>8==255?k+=I&255:(_[k]=I,k++),p.value++}function Ht(p,y){y[0]=X(p[0]),y[1]=X(p[1]),y[2]=X(p[5]),y[3]=X(p[6]),y[4]=X(p[14]),y[5]=X(p[15]),y[6]=X(p[27]),y[7]=X(p[28]),y[8]=X(p[2]),y[9]=X(p[4]),y[10]=X(p[7]),y[11]=X(p[13]),y[12]=X(p[16]),y[13]=X(p[26]),y[14]=X(p[29]),y[15]=X(p[42]),y[16]=X(p[3]),y[17]=X(p[8]),y[18]=X(p[12]),y[19]=X(p[17]),y[20]=X(p[25]),y[21]=X(p[30]),y[22]=X(p[41]),y[23]=X(p[43]),y[24]=X(p[9]),y[25]=X(p[11]),y[26]=X(p[18]),y[27]=X(p[24]),y[28]=X(p[31]),y[29]=X(p[40]),y[30]=X(p[44]),y[31]=X(p[53]),y[32]=X(p[10]),y[33]=X(p[19]),y[34]=X(p[23]),y[35]=X(p[32]),y[36]=X(p[39]),y[37]=X(p[45]),y[38]=X(p[52]),y[39]=X(p[54]),y[40]=X(p[20]),y[41]=X(p[22]),y[42]=X(p[33]),y[43]=X(p[38]),y[44]=X(p[46]),y[45]=X(p[51]),y[46]=X(p[55]),y[47]=X(p[60]),y[48]=X(p[21]),y[49]=X(p[34]),y[50]=X(p[37]),y[51]=X(p[47]),y[52]=X(p[50]),y[53]=X(p[56]),y[54]=X(p[59]),y[55]=X(p[61]),y[56]=X(p[35]),y[57]=X(p[36]),y[58]=X(p[48]),y[59]=X(p[49]),y[60]=X(p[57]),y[61]=X(p[58]),y[62]=X(p[62]),y[63]=X(p[63])}function bt(p){const y=.5*Math.cos(.7853975),_=.5*Math.cos(3.14159/16),I=.5*Math.cos(3.14159/8),k=.5*Math.cos(3*3.14159/16),F=.5*Math.cos(5*3.14159/16),B=.5*Math.cos(3*3.14159/8),Z=.5*Math.cos(7*3.14159/16),Y=new Array(4),j=new Array(4),W=new Array(4),J=new Array(4);for(let re=0;re<8;++re){const ee=re*8;Y[0]=I*p[ee+2],Y[1]=B*p[ee+2],Y[2]=I*p[ee+6],Y[3]=B*p[ee+6],j[0]=_*p[ee+1]+k*p[ee+3]+F*p[ee+5]+Z*p[ee+7],j[1]=k*p[ee+1]-Z*p[ee+3]-_*p[ee+5]-F*p[ee+7],j[2]=F*p[ee+1]-_*p[ee+3]+Z*p[ee+5]+k*p[ee+7],j[3]=Z*p[ee+1]-F*p[ee+3]+k*p[ee+5]-_*p[ee+7],W[0]=y*(p[ee+0]+p[ee+4]),W[3]=y*(p[ee+0]-p[ee+4]),W[1]=Y[0]+Y[3],W[2]=Y[1]-Y[2],J[0]=W[0]+W[1],J[1]=W[3]+W[2],J[2]=W[3]-W[2],J[3]=W[0]-W[1],p[ee+0]=J[0]+j[0],p[ee+1]=J[1]+j[1],p[ee+2]=J[2]+j[2],p[ee+3]=J[3]+j[3],p[ee+4]=J[3]-j[3],p[ee+5]=J[2]-j[2],p[ee+6]=J[1]-j[1],p[ee+7]=J[0]-j[0]}for(let re=0;re<8;++re)Y[0]=I*p[16+re],Y[1]=B*p[16+re],Y[2]=I*p[48+re],Y[3]=B*p[48+re],j[0]=_*p[8+re]+k*p[24+re]+F*p[40+re]+Z*p[56+re],j[1]=k*p[8+re]-Z*p[24+re]-_*p[40+re]-F*p[56+re],j[2]=F*p[8+re]-_*p[24+re]+Z*p[40+re]+k*p[56+re],j[3]=Z*p[8+re]-F*p[24+re]+k*p[40+re]-_*p[56+re],W[0]=y*(p[re]+p[32+re]),W[3]=y*(p[re]-p[32+re]),W[1]=Y[0]+Y[3],W[2]=Y[1]-Y[2],J[0]=W[0]+W[1],J[1]=W[3]+W[2],J[2]=W[3]-W[2],J[3]=W[0]-W[1],p[0+re]=J[0]+j[0],p[8+re]=J[1]+j[1],p[16+re]=J[2]+j[2],p[24+re]=J[3]+j[3],p[32+re]=J[3]-j[3],p[40+re]=J[2]-j[2],p[48+re]=J[1]-j[1],p[56+re]=J[0]-j[0]}function Jr(p){for(let y=0;y<64;++y){const _=p[0][y],I=p[1][y],k=p[2][y];p[0][y]=_+1.5747*k,p[1][y]=_-.1873*I-.4682*k,p[2][y]=_+1.8556*I}}function Hr(p,y,_){for(let I=0;I<64;++I)y[_+I]=f.DataUtils.toHalfFloat(Ft(p[I]))}function Ft(p){return p<=1?Math.sign(p)*Math.pow(Math.abs(p),2.2):Math.sign(p)*Math.pow(L,Math.abs(p)-1)}function er(p){return new DataView(p.array.buffer,p.offset.value,p.size)}function en(p){const y=p.viewer.buffer.slice(p.offset.value,p.offset.value+p.size),_=new Uint8Array(ht(y)),I=new Uint8Array(_.length);return Rt(_),Fr(_,I),new DataView(I.buffer)}function Ot(p){const y=p.array.slice(p.offset.value,p.offset.value+p.size),_=Gn(y),I=new Uint8Array(_.length);return Rt(_),Fr(_,I),new DataView(I.buffer)}function tr(p){const y=p.viewer,_={value:p.offset.value},I=new Uint16Array(p.columns*p.lines*(p.inputChannels.length*p.type)),k=new Uint8Array(8192);let F=0;const B=new Array(p.inputChannels.length);for(let le=0,te=p.inputChannels.length;le<te;le++)B[le]={},B[le].start=F,B[le].end=B[le].start,B[le].nx=p.columns,B[le].ny=p.lines,B[le].size=p.type,F+=B[le].nx*B[le].ny*B[le].size;const Z=nt(y,_),Y=nt(y,_);if(Y>=8192)throw new Error("Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(Z<=Y)for(let le=0;le<Y-Z+1;le++)k[le+Z]=ft(y,_);const j=new Uint16Array(65536),W=E(k,j),J=je(y,_);Dt(p.array,y,_,J,I,F);for(let le=0;le<p.inputChannels.length;++le){const te=B[le];for(let se=0;se<B[le].size;++se)ut(I,te.start+se,te.nx,te.size,te.ny,te.nx*te.size,W)}_t(j,I,F);let re=0;const ee=new Uint8Array(I.buffer.byteLength);for(let le=0;le<p.lines;le++)for(let te=0;te<p.inputChannels.length;te++){const se=B[te],he=se.nx*se.size,Se=new Uint8Array(I.buffer,se.end*2,he*2);ee.set(Se,re),re+=he*2,se.end+=he}return new DataView(ee.buffer)}function rr(p){const y=p.array.slice(p.offset.value,p.offset.value+p.size),_=Gn(y),I=p.inputChannels.length*p.lines*p.columns*p.totalBytes,k=new ArrayBuffer(I),F=new DataView(k);let B=0,Z=0;const Y=new Array(4);for(let j=0;j<p.lines;j++)for(let W=0;W<p.inputChannels.length;W++){let J=0;switch(p.inputChannels[W].pixelType){case 1:Y[0]=B,Y[1]=Y[0]+p.columns,B=Y[1]+p.columns;for(let ee=0;ee<p.columns;++ee){const le=_[Y[0]++]<<8|_[Y[1]++];J+=le,F.setUint16(Z,J,!0),Z+=2}break;case 2:Y[0]=B,Y[1]=Y[0]+p.columns,Y[2]=Y[1]+p.columns,B=Y[2]+p.columns;for(let ee=0;ee<p.columns;++ee){const le=_[Y[0]++]<<24|_[Y[1]++]<<16|_[Y[2]++]<<8;J+=le,F.setUint32(Z,J,!0),Z+=4}break}}return F}function Or(p){const y=p.viewer,_={value:p.offset.value},I=new Uint8Array(p.columns*p.lines*(p.inputChannels.length*p.type*2)),k={version:Ge(y,_),unknownUncompressedSize:Ge(y,_),unknownCompressedSize:Ge(y,_),acCompressedSize:Ge(y,_),dcCompressedSize:Ge(y,_),rleCompressedSize:Ge(y,_),rleUncompressedSize:Ge(y,_),rleRawSize:Ge(y,_),totalAcUncompressedCount:Ge(y,_),totalDcUncompressedCount:Ge(y,_),acCompression:Ge(y,_)};if(k.version<2)throw new Error("EXRLoader.parse: "+Q.compression+" version "+k.version+" is unsupported");const F=new Array;let B=nt(y,_)-2;for(;B>0;){const te=St(y.buffer,_),se=ft(y,_),he=se>>2&3,Se=(se>>4)-1,Re=new Int8Array([Se])[0],it=ft(y,_);F.push({name:te,index:Re,type:it,compression:he}),B-=te.length+3}const Z=Q.channels,Y=new Array(p.inputChannels.length);for(let te=0;te<p.inputChannels.length;++te){const se=Y[te]={},he=Z[te];se.name=he.name,se.compression=0,se.decoded=!1,se.type=he.pixelType,se.pLinear=he.pLinear,se.width=p.columns,se.height=p.lines}const j={idx:new Array(3)};for(let te=0;te<p.inputChannels.length;++te){const se=Y[te];for(let he=0;he<F.length;++he){const Se=F[he];se.name==Se.name&&(se.compression=Se.compression,Se.index>=0&&(j.idx[Se.index]=te),se.offset=te)}}let W,J,re;if(k.acCompressedSize>0)switch(k.acCompression){case 0:W=new Uint16Array(k.totalAcUncompressedCount),Dt(p.array,y,_,k.acCompressedSize,W,k.totalAcUncompressedCount);break;case 1:const te=p.array.slice(_.value,_.value+k.totalAcUncompressedCount),se=Gn(te);W=new Uint16Array(se.buffer),_.value+=k.totalAcUncompressedCount;break}if(k.dcCompressedSize>0){const te={array:p.array,offset:_,size:k.dcCompressedSize};J=new Uint16Array(Ot(te).buffer),_.value+=k.dcCompressedSize}if(k.rleRawSize>0){const te=p.array.slice(_.value,_.value+k.rleCompressedSize),se=Gn(te);re=ht(se.buffer),_.value+=k.rleCompressedSize}let ee=0;const le=new Array(Y.length);for(let te=0;te<le.length;++te)le[te]=new Array;for(let te=0;te<p.lines;++te)for(let se=0;se<Y.length;++se)le[se].push(ee),ee+=Y[se].width*p.type*2;rt(j,le,Y,W,J,I);for(let te=0;te<Y.length;++te){const se=Y[te];if(!se.decoded)switch(se.compression){case 2:let he=0,Se=0;for(let Re=0;Re<p.lines;++Re){let it=le[te][he];for(let Ce=0;Ce<se.width;++Ce){for(let me=0;me<2*se.type;++me)I[it++]=re[Se+me*se.width*se.height];Se++}he++}break;case 1:default:throw new Error("EXRLoader.parse: unsupported channel compression")}}return new DataView(I.buffer)}function St(p,y){const _=new Uint8Array(p);let I=0;for(;_[y.value+I]!=0;)I+=1;const k=new TextDecoder().decode(_.slice(y.value,y.value+I));return y.value=y.value+I+1,k}function nr(p,y,_){const I=new TextDecoder().decode(new Uint8Array(p).slice(y.value,y.value+_));return y.value=y.value+_,I}function tn(p,y){const _=Ve(p,y),I=je(p,y);return[_,I]}function rn(p,y){const _=je(p,y),I=je(p,y);return[_,I]}function Ve(p,y){const _=p.getInt32(y.value,!0);return y.value=y.value+4,_}function je(p,y){const _=p.getUint32(y.value,!0);return y.value=y.value+4,_}function Lr(p,y){const _=p[y.value];return y.value=y.value+1,_}function ft(p,y){const _=p.getUint8(y.value);return y.value=y.value+1,_}const Ge=function(p,y){let _;return"getBigInt64"in DataView.prototype?_=Number(p.getBigInt64(y.value,!0)):_=p.getUint32(y.value+4,!0)+Number(p.getUint32(y.value,!0)<<32),y.value+=8,_};function De(p,y){const _=p.getFloat32(y.value,!0);return y.value+=4,_}function ir(p,y){return f.DataUtils.toHalfFloat(De(p,y))}function X(p){const y=(p&31744)>>10,_=p&1023;return(p>>15?-1:1)*(y?y===31?_?NaN:1/0:Math.pow(2,y-15)*(1+_/1024):6103515625e-14*(_/1024))}function nt(p,y){const _=p.getUint16(y.value,!0);return y.value+=2,_}function Lt(p,y){return X(nt(p,y))}function sr(p,y,_,I){const k=_.value,F=[];for(;_.value<k+I-1;){const B=St(y,_),Z=Ve(p,_),Y=ft(p,_);_.value+=3;const j=Ve(p,_),W=Ve(p,_);F.push({name:B,pixelType:Z,pLinear:Y,xSampling:j,ySampling:W})}return _.value+=1,F}function nn(p,y){const _=De(p,y),I=De(p,y),k=De(p,y),F=De(p,y),B=De(p,y),Z=De(p,y),Y=De(p,y),j=De(p,y);return{redX:_,redY:I,greenX:k,greenY:F,blueX:B,blueY:Z,whiteX:Y,whiteY:j}}function or(p,y){const _=["NO_COMPRESSION","RLE_COMPRESSION","ZIPS_COMPRESSION","ZIP_COMPRESSION","PIZ_COMPRESSION","PXR24_COMPRESSION","B44_COMPRESSION","B44A_COMPRESSION","DWAA_COMPRESSION","DWAB_COMPRESSION"],I=ft(p,y);return _[I]}function sn(p,y){const _=Ve(p,y),I=Ve(p,y),k=Ve(p,y),F=Ve(p,y);return{xMin:_,yMin:I,xMax:k,yMax:F}}function ar(p,y){const _=["INCREASING_Y","DECREASING_Y","RANDOM_Y"],I=ft(p,y);return _[I]}function cr(p,y){const _=["ENVMAP_LATLONG","ENVMAP_CUBE"],I=ft(p,y);return _[I]}function on(p,y){const _=["ONE_LEVEL","MIPMAP_LEVELS","RIPMAP_LEVELS"],I=["ROUND_DOWN","ROUND_UP"],k=je(p,y),F=je(p,y),B=ft(p,y);return{xSize:k,ySize:F,levelMode:_[B&15],roundingMode:I[B>>4]}}function an(p,y){const _=De(p,y),I=De(p,y);return[_,I]}function lr(p,y){const _=De(p,y),I=De(p,y),k=De(p,y);return[_,I,k]}function ur(p,y,_,I,k){if(I==="string"||I==="stringvector"||I==="iccProfile")return nr(y,_,k);if(I==="chlist")return sr(p,y,_,k);if(I==="chromaticities")return nn(p,_);if(I==="compression")return or(p,_);if(I==="box2i")return sn(p,_);if(I==="envmap")return cr(p,_);if(I==="tiledesc")return on(p,_);if(I==="lineOrder")return ar(p,_);if(I==="float")return De(p,_);if(I==="v2f")return an(p,_);if(I==="v3f")return lr(p,_);if(I==="int")return Ve(p,_);if(I==="rational")return tn(p,_);if(I==="timecode")return rn(p,_);if(I==="preview")return _.value+=k,"skipped";_.value+=k}function cn(p,y){const _=Math.log2(p);return y=="ROUND_DOWN"?Math.floor(_):Math.ceil(_)}function ln(p,y,_){let I=0;switch(p.levelMode){case"ONE_LEVEL":I=1;break;case"MIPMAP_LEVELS":I=cn(Math.max(y,_),p.roundingMode)+1;break;case"RIPMAP_LEVELS":throw new Error("THREE.EXRLoader: RIPMAP_LEVELS tiles currently unsupported.")}return I}function Nr(p,y,_,I){const k=new Array(p);for(let F=0;F<p;F++){const B=1<<F;let Z=y/B|0;I=="ROUND_UP"&&Z*B<y&&(Z+=1);const Y=Math.max(Z,1);k[F]=(Y+_-1)/_|0}return k}function un(){const p=this,y=p.offset,_={value:0};for(let I=0;I<p.tileCount;I++){const k=Ve(p.viewer,y),F=Ve(p.viewer,y);y.value+=8,p.size=je(p.viewer,y);const B=k*p.blockWidth,Z=F*p.blockHeight;p.columns=B+p.blockWidth>p.width?p.width-B:p.blockWidth,p.lines=Z+p.blockHeight>p.height?p.height-Z:p.blockHeight;const Y=p.columns*p.totalBytes,W=p.size<p.lines*Y?p.uncompress(p):er(p);y.value+=p.size;for(let J=0;J<p.lines;J++){const re=J*p.columns*p.totalBytes;for(let ee=0;ee<p.inputChannels.length;ee++){const le=Q.channels[ee].name,te=p.channelByteOffsets[le]*p.columns,se=p.decodeChannels[le];if(se===void 0)continue;_.value=re+te;const he=(p.height-(1+Z+J))*p.outLineWidth;for(let Se=0;Se<p.columns;Se++){const Re=he+(Se+B)*p.outputChannels+se;p.byteArray[Re]=p.getter(W,_)}}}}}function m(){const p=this,y=p.offset,_={value:0};for(let I=0;I<p.height/p.blockHeight;I++){const k=Ve(p.viewer,y)-Q.dataWindow.yMin;p.size=je(p.viewer,y),p.lines=k+p.blockHeight>p.height?p.height-k:p.blockHeight;const F=p.columns*p.totalBytes,Z=p.size<p.lines*F?p.uncompress(p):er(p);y.value+=p.size;for(let Y=0;Y<p.blockHeight;Y++){const j=I*p.blockHeight,W=Y+p.scanOrder(j);if(W>=p.height)continue;const J=Y*F,re=(p.height-1-W)*p.outLineWidth;for(let ee=0;ee<p.inputChannels.length;ee++){const le=Q.channels[ee].name,te=p.channelByteOffsets[le]*p.columns,se=p.decodeChannels[le];if(se!==void 0){_.value=J+te;for(let he=0;he<p.columns;he++){const Se=re+he*p.outputChannels+se;p.byteArray[Se]=p.getter(Z,_)}}}}}}function C(p,y,_){const I={};if(p.getUint32(0,!0)!=20000630)throw new Error("THREE.EXRLoader: Provided file doesn't appear to be in OpenEXR format.");I.version=p.getUint8(4);const k=p.getUint8(5);I.spec={singleTile:!!(k&2),longName:!!(k&4),deepFormat:!!(k&8),multiPart:!!(k&16)},_.value=8;let F=!0;for(;F;){const B=St(y,_);if(B==0)F=!1;else{const Z=St(y,_),Y=je(p,_),j=ur(p,y,_,Z,Y);j===void 0?console.warn(`THREE.EXRLoader: Skipped unknown header attribute type '${Z}'.`):I[B]=j}}if((k&-7)!=0)throw console.error("THREE.EXRHeader:",I),new Error("THREE.EXRLoader: Provided file is currently unsupported.");return I}function N(p,y,_,I,k){const F={size:0,viewer:y,array:_,offset:I,width:p.dataWindow.xMax-p.dataWindow.xMin+1,height:p.dataWindow.yMax-p.dataWindow.yMin+1,inputChannels:p.channels,channelByteOffsets:{},scanOrder:null,totalBytes:null,columns:null,lines:null,type:null,uncompress:null,getter:null,format:null,colorSpace:f.LinearSRGBColorSpace};switch(p.compression){case"NO_COMPRESSION":F.blockHeight=1,F.uncompress=er;break;case"RLE_COMPRESSION":F.blockHeight=1,F.uncompress=en;break;case"ZIPS_COMPRESSION":F.blockHeight=1,F.uncompress=Ot;break;case"ZIP_COMPRESSION":F.blockHeight=16,F.uncompress=Ot;break;case"PIZ_COMPRESSION":F.blockHeight=32,F.uncompress=tr;break;case"PXR24_COMPRESSION":F.blockHeight=16,F.uncompress=rr;break;case"DWAA_COMPRESSION":F.blockHeight=32,F.uncompress=Or;break;case"DWAB_COMPRESSION":F.blockHeight=256,F.uncompress=Or;break;default:throw new Error("EXRLoader.parse: "+p.compression+" is unsupported")}const B={};for(const W of p.channels)switch(W.name){case"Y":case"R":case"G":case"B":case"A":B[W.name]=!0,F.type=W.pixelType}let Z=!1;if(B.R&&B.G&&B.B)Z=!B.A,F.outputChannels=4,F.decodeChannels={R:0,G:1,B:2,A:3};else if(B.Y)F.outputChannels=1,F.decodeChannels={Y:0};else throw new Error("EXRLoader.parse: file contains unsupported data channels.");if(F.type==1)switch(k){case f.FloatType:F.getter=Lt;break;case f.HalfFloatType:F.getter=nt;break}else if(F.type==2)switch(k){case f.FloatType:F.getter=De;break;case f.HalfFloatType:F.getter=ir}else throw new Error("EXRLoader.parse: unsupported pixelType "+F.type+" for "+p.compression+".");F.columns=F.width;const Y=F.width*F.height*F.outputChannels;switch(k){case f.FloatType:F.byteArray=new Float32Array(Y),Z&&F.byteArray.fill(1,0,Y);break;case f.HalfFloatType:F.byteArray=new Uint16Array(Y),Z&&F.byteArray.fill(15360,0,Y);break;default:console.error("THREE.EXRLoader: unsupported type: ",k);break}let j=0;for(const W of p.channels)F.decodeChannels[W.name]!==void 0&&(F.channelByteOffsets[W.name]=j),j+=W.pixelType*2;if(F.totalBytes=j,F.outLineWidth=F.width*F.outputChannels,p.lineOrder==="INCREASING_Y"?F.scanOrder=W=>W:F.scanOrder=W=>F.height-1-W,F.outputChannels==4?(F.format=f.RGBAFormat,F.colorSpace=f.LinearSRGBColorSpace):(F.format=f.RedFormat,F.colorSpace=f.NoColorSpace),p.spec.singleTile){F.blockHeight=p.tiles.ySize,F.blockWidth=p.tiles.xSize;const W=ln(p.tiles,F.width,F.height),J=Nr(W,F.width,p.tiles.xSize,p.tiles.roundingMode),re=Nr(W,F.height,p.tiles.ySize,p.tiles.roundingMode);F.tileCount=J[0]*re[0];for(let ee=0;ee<W;ee++)for(let le=0;le<re[ee];le++)for(let te=0;te<J[ee];te++)Ge(y,I);F.decode=un.bind(F)}else{F.blockWidth=F.width;const W=Math.ceil(F.height/F.blockHeight);for(let J=0;J<W;J++)Ge(y,I);F.decode=m.bind(F)}return F}const q={value:0},ie=new DataView(e),ae=new Uint8Array(e),Q=C(ie,e,q),$=N(Q,ie,ae,q,this.type);return $.decode(),{header:Q,width:$.width,height:$.height,data:$.byteArray,format:$.format,colorSpace:$.colorSpace,type:this.type}}setDataType(e){return this.type=e,this}load(e,t,r,n){function o(i,a){i.colorSpace=a.colorSpace,i.minFilter=f.LinearFilter,i.magFilter=f.LinearFilter,i.generateMipmaps=!1,i.flipY=!1,t&&t(i,a)}return super.load(e,o,r,n)}}class Hu extends f.DataTextureLoader{constructor(e){super(e),this.type=f.HalfFloatType}parse(e){const i=function(O,L){switch(O){case 1:throw new Error("THREE.RGBELoader: Read Error: "+(L||""));case 2:throw new Error("THREE.RGBELoader: Write Error: "+(L||""));case 3:throw new Error("THREE.RGBELoader: Bad File Format: "+(L||""));default:case 4:throw new Error("THREE.RGBELoader: Memory Error: "+(L||""))}},d=`
|
|
4012
4012
|
`,u=function(O,L,E){L=L||1024;let z=O.pos,V=-1,U=0,H="",ne=String.fromCharCode.apply(null,new Uint16Array(O.subarray(z,z+128)));for(;0>(V=ne.indexOf(d))&&U<L&&z<O.byteLength;)H+=ne,U+=ne.length,z+=128,ne+=String.fromCharCode.apply(null,new Uint16Array(O.subarray(z,z+128)));return-1<V?(O.pos+=U+V+1,H+ne.slice(0,V)):!1},l=function(O){const L=/^#\?(\S+)/,E=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,G=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,z=/^\s*FORMAT=(\S+)\s*$/,V=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,U={valid:0,string:"",comments:"",programtype:"RGBE",format:"",gamma:1,exposure:1,width:0,height:0};let H,ne;for((O.pos>=O.byteLength||!(H=u(O)))&&i(1,"no header found"),(ne=H.match(L))||i(3,"bad initial token"),U.valid|=1,U.programtype=ne[1],U.string+=H+`
|
|
4013
4013
|
`;H=u(O),H!==!1;){if(U.string+=H+`
|
|
4014
4014
|
`,H.charAt(0)==="#"){U.comments+=H+`
|
|
4015
|
-
`;continue}if((ne=H.match(E))&&(U.gamma=parseFloat(ne[1])),(ne=H.match(G))&&(U.exposure=parseFloat(ne[1])),(ne=H.match(z))&&(U.valid|=2,U.format=ne[1]),(ne=H.match(V))&&(U.valid|=4,U.height=parseInt(ne[1],10),U.width=parseInt(ne[2],10)),U.valid&2&&U.valid&4)break}return U.valid&2||i(3,"missing format specifier"),U.valid&4||i(3,"missing image size specifier"),U},v=function(O,L,E){const G=L;if(G<8||G>32767||O[0]!==2||O[1]!==2||O[2]&128)return new Uint8Array(O);G!==(O[2]<<8|O[3])&&i(3,"wrong scanline width");const z=new Uint8Array(4*L*E);z.length||i(4,"unable to allocate buffer space");let V=0,U=0;const H=4*G,ne=new Uint8Array(4),ge=new Uint8Array(H);let Pe=E;for(;Pe>0&&U<O.byteLength;){U+4>O.byteLength&&i(1),ne[0]=O[U++],ne[1]=O[U++],ne[2]=O[U++],ne[3]=O[U++],(ne[0]!=2||ne[1]!=2||(ne[2]<<8|ne[3])!=G)&&i(3,"bad rgbe scanline format");let ve=0,ye;for(;ve<H&&U<O.byteLength;){ye=O[U++];const _e=ye>128;if(_e&&(ye-=128),(ye===0||ve+ye>H)&&i(3,"bad scanline data"),_e){const Te=O[U++];for(let et=0;et<ye;et++)ge[ve++]=Te}else ge.set(O.subarray(U,U+ye),ve),ve+=ye,U+=ye}const Ue=G;for(let _e=0;_e<Ue;_e++){let Te=0;z[V]=ge[_e+Te],Te+=G,z[V+1]=ge[_e+Te],Te+=G,z[V+2]=ge[_e+Te],Te+=G,z[V+3]=ge[_e+Te],V+=4}Pe--}return z},b=function(O,L,E,G){const z=O[L+3],V=Math.pow(2,z-128)/255;E[G+0]=O[L+0]*V,E[G+1]=O[L+1]*V,E[G+2]=O[L+2]*V,E[G+3]=1},S=function(O,L,E,G){const z=O[L+3],V=Math.pow(2,z-128)/255;E[G+0]=f.DataUtils.toHalfFloat(Math.min(O[L+0]*V,65504)),E[G+1]=f.DataUtils.toHalfFloat(Math.min(O[L+1]*V,65504)),E[G+2]=f.DataUtils.toHalfFloat(Math.min(O[L+2]*V,65504)),E[G+3]=f.DataUtils.toHalfFloat(1)},g=new Uint8Array(e);g.pos=0;const x=l(g),w=x.width,T=x.height,A=v(g.subarray(g.pos),w,T);let P,D,R;switch(this.type){case f.FloatType:R=A.length/4;const O=new Float32Array(R*4);for(let E=0;E<R;E++)b(A,E*4,O,E*4);P=O,D=f.FloatType;break;case f.HalfFloatType:R=A.length/4;const L=new Uint16Array(R*4);for(let E=0;E<R;E++)S(A,E*4,L,E*4);P=L,D=f.HalfFloatType;break;default:throw new Error("THREE.RGBELoader: Unsupported type: "+this.type)}return{width:w,height:T,data:P,header:x.string,gamma:x.gamma,exposure:x.exposure,type:D}}setDataType(e){return this.type=e,this}load(e,t,r,n){function o(i,a){switch(i.type){case f.FloatType:case f.HalfFloatType:i.colorSpace=f.LinearSRGBColorSpace,i.minFilter=f.LinearFilter,i.magFilter=f.LinearFilter,i.generateMipmaps=!1,i.flipY=!0;break}t&&t(i,a)}return super.load(e,o,r,n)}}class Hu extends f.Scene{constructor(){super();const e=new f.BoxGeometry;e.deleteAttribute("uv");const t=new f.MeshStandardMaterial({side:f.BackSide}),r=new f.MeshStandardMaterial,n=new f.PointLight(16777215,900,28,2);n.position.set(.418,16.199,.3),this.add(n);const o=new f.Mesh(e,t);o.position.set(-.757,13.219,.717),o.scale.set(31.713,28.305,28.591),this.add(o);const i=new f.Mesh(e,r);i.position.set(-10.906,2.009,1.846),i.rotation.set(0,-.195,0),i.scale.set(2.328,7.905,4.651),this.add(i);const a=new f.Mesh(e,r);a.position.set(-5.607,-.754,-.758),a.rotation.set(0,.994,0),a.scale.set(1.97,1.534,3.955),this.add(a);const c=new f.Mesh(e,r);c.position.set(6.167,.857,7.803),c.rotation.set(0,.561,0),c.scale.set(3.927,6.285,3.687),this.add(c);const h=new f.Mesh(e,r);h.position.set(-2.017,.018,6.124),h.rotation.set(0,.333,0),h.scale.set(2.002,4.566,2.064),this.add(h);const d=new f.Mesh(e,r);d.position.set(2.291,-.756,-2.621),d.rotation.set(0,-.286,0),d.scale.set(1.546,1.552,1.496),this.add(d);const u=new f.Mesh(e,r);u.position.set(-2.193,-.369,-5.547),u.rotation.set(0,.516,0),u.scale.set(3.875,3.487,2.986),this.add(u);const l=new f.Mesh(e,Dr(50));l.position.set(-16.116,14.37,8.208),l.scale.set(.1,2.428,2.739),this.add(l);const v=new f.Mesh(e,Dr(50));v.position.set(-16.109,18.021,-8.207),v.scale.set(.1,2.425,2.751),this.add(v);const b=new f.Mesh(e,Dr(17));b.position.set(14.904,12.198,-1.832),b.scale.set(.15,4.265,6.331),this.add(b);const S=new f.Mesh(e,Dr(43));S.position.set(-.462,8.89,14.52),S.scale.set(4.38,5.441,.088),this.add(S);const g=new f.Mesh(e,Dr(20));g.position.set(3.235,11.486,-12.541),g.scale.set(2.5,2,.1),this.add(g);const x=new f.Mesh(e,Dr(100));x.position.set(0,20,0),x.scale.set(1,.1,1),this.add(x)}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 Dr(s){const e=new f.MeshBasicMaterial;return e.color.setScalar(s),e}class eh{constructor(){this.pmremGenerator=null,this.loadedTextures=new Map}async initialize(e){var t;try{const r=e.renderer;let n=r.renderer||((t=r.getThreeRenderer)==null?void 0:t.call(r));if(!n&&r.getDomElement){const o=r.getDomElement();if(o&&"parentElement"in o&&o.parentElement){const i=o.parentElement.renderer;i instanceof M.WebGLRenderer&&(n=i)}}return n?(this.pmremGenerator=new M.PMREMGenerator(n),this.pmremGenerator.compileEquirectangularShader(),K.ok(void 0)):K.err(new oe("Could not access Three.js renderer",ue.INITIALIZATION_FAILED))}catch(r){return K.err(new oe("Failed to initialize environment service",ue.INITIALIZATION_FAILED,{originalError:r}))}}async loadEnvironmentMap(e){var t,r,n,o;try{const i=this.loadedTextures.get(e);if(i)return K.ok(new Rr(i));const a=(t=e.split(".").pop())==null?void 0:t.toLowerCase();let c;switch(a){case"hdr":c=new Ju;break;case"exr":c=new Qu;break;case"jpg":case"jpeg":case"png":c=new M.TextureLoader;break;default:return K.err(new oe(`Unsupported environment map format: ${a}`,ue.UNSUPPORTED_FORMAT,{url:e,extension:a}))}const h=await new Promise((d,u)=>{c.load(e,l=>{var v,b,S,g,x;console.log("[ThreeEnvironmentService] Texture loaded:",{url:e,format:l.format,type:l.type,mapping:l.mapping,hasImage:!!l.image,imageType:(b=(v=l.image)==null?void 0:v.constructor)==null?void 0:b.name,imageData:(S=l.image)!=null&&S.data?"has data":"no data",imageWidth:(g=l.image)==null?void 0:g.width,imageHeight:(x=l.image)==null?void 0:x.height}),d(l)},void 0,l=>u(l))});if(this.pmremGenerator){h.mapping=M.EquirectangularReflectionMapping;const d=this.pmremGenerator.fromEquirectangular(h).texture;return this.loadedTextures.set(e,d),this.loadedTextures.set(e+"_original",h),console.log("[ThreeEnvironmentService] Stored original texture for path tracing:",{url:e+"_original",format:h.format,mapping:h.mapping,hasImage:!!h.image,imageComplete:(r=h.image)==null?void 0:r.complete,imageNaturalWidth:(n=h.image)==null?void 0:n.naturalWidth,imageNaturalHeight:(o=h.image)==null?void 0:o.naturalHeight}),K.ok(new Rr(d))}return this.loadedTextures.set(e,h),K.ok(new Rr(h))}catch(i){return K.err(new oe("Failed to load environment map",ue.TEXTURE_LOAD_FAILED,{url:e,originalError:i}))}}applyToScene(e,t,r){try{if(!(e instanceof Yt))return K.err(new oe("Scene must be ThreeSceneAdapter",ue.INVALID_PARAMETER));if(!(t instanceof Rr))return K.err(new oe("Texture must be ThreeTextureAdapter",ue.INVALID_PARAMETER));const n=e.getThreeScene(),o=t.getThreeTexture();if(n.environment=o,r&&(r.backgroundBlurriness!==void 0&&(n.backgroundBlurriness=r.backgroundBlurriness),r.backgroundIntensity!==void 0&&(n.backgroundIntensity=r.backgroundIntensity),r.environmentIntensity!==void 0&&(n.environmentIntensity=r.environmentIntensity)),o.mapping===M.CubeUVReflectionMapping){const a=Array.from(this.loadedTextures.entries()).find(([c,h])=>c.endsWith("_original")&&h.mapping===M.EquirectangularReflectionMapping);a&&(n.__originalEnvironmentTexture=a[1])}else o.mapping===M.EquirectangularReflectionMapping&&(n.__originalEnvironmentTexture=o);if(o.mapping===M.EquirectangularReflectionMapping)n.background=o;else if(o.mapping===M.CubeUVReflectionMapping){const a=Array.from(this.loadedTextures.entries()).find(([c,h])=>c.endsWith("_original")&&h.mapping===M.EquirectangularReflectionMapping);a?n.background=a[1]:n.background=o}else n.background=o;return K.ok(void 0)}catch(n){return K.err(new oe("Failed to apply environment to scene",ue.SCENE_OPERATION_FAILED,{originalError:n}))}}getOriginalEnvironmentTexture(e){const t=this.loadedTextures.get(e+"_original");return t?new Rr(t):null}createStudioEnvironment(e={}){try{if(!this.pmremGenerator)return K.err(new oe("Environment service not initialized",ue.INITIALIZATION_FAILED));const t=new Hu,r=this.pmremGenerator.fromScene(t).texture;return t.dispose(),K.ok(new Rr(r))}catch(t){return K.err(new oe("Failed to create studio environment",ue.TEXTURE_LOAD_FAILED,{originalError:t}))}}dispose(){this.loadedTextures.forEach(e=>e.dispose()),this.loadedTextures.clear(),this.pmremGenerator&&(this.pmremGenerator.dispose(),this.pmremGenerator=null)}}class Rr{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 th{constructor(e){this.object=e,this.boundingBox=new M.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,r=new M.Vector3;return t>0?r.y=-e:r.y=0,r}applyOffset(e){this.object.position.add(e)}}class rh{alignToFloor(e){try{let t=null;return"getThreeObject"in e&&typeof e.getThreeObject=="function"?t=e.getThreeObject():e instanceof M.Object3D&&(t=e),t?(new th(t).alignToFloor(),K.ok(void 0)):K.err(new oe("Could not get Three.js object for floor alignment",ue.INVALID_PARAMETER))}catch(t){return K.err(new oe("Failed to align object to floor",ue.OPERATION_FAILED,{originalError:t}))}}}var Vn=(s=>(s.MapControls="MapControls",s.OrbitControls="OrbitControls",s))(Vn||{});class nh{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===M.BasicShadowMap)return"basic";if(e===M.PCFShadowMap)return"pcf";if(e===M.PCFSoftShadowMap)return"pcfsoft";if(e===M.VSMShadowMap)return"vsm"}return typeof e=="string"?e:void 0}static convertToneMappingType(e){if(typeof e=="number"){if(e===M.NoToneMapping)return"none";if(e===M.LinearToneMapping)return"linear";if(e===M.ReinhardToneMapping)return"reinhard";if(e===M.CineonToneMapping)return"cineon";if(e===M.ACESFilmicToneMapping)return"aces"}return typeof e=="string"?e:"aces"}}class ih{static createViewer(e,t){var S;const r=new zo(e),n=new Yt,o=this.createCamera(t),i=this.createControls(o.getThreeCamera(),e,t),a=new sh().createDefaultLoader(),c=new Ua,h=new eh;let d;(((S=t.pathTracing)==null?void 0:S.enabled)??!1)&&(d=new Nu);const l=new rh,v=nh.convertRendererOptions(t.renderer||{}),b={renderer:r,scene:n,camera:o,controls:i,modelLoader:a,options:t,rendererOptions:v,sceneSetupService:c,environmentService:h,pathTracingService:d,floorAlignmentService:l};return new Bo(b)}static createCamera(e){const r=e.camera||{},n=r.fov||r.cameraFov||75,o=r.near||r.cameraNear||.1,i=r.far||r.cameraFar||1e5,a=r.position||r.cameraPosition,c=r.target||r.cameraTarget,h=$n.create(n,1,o,i);return a&&h.position.set(a[0],a[1],a[2]),c&&h.lookAt({x:c[0],y:c[1],z:c[2],set:()=>{},copy:()=>{},add:()=>{},multiply:()=>{},normalize:()=>{},length:()=>0}),h}static createControls(e,t,r){const n=r.controls||{},o=n.type||Vn.OrbitControls;let i;o===Vn.MapControls?i=new ls(e,t):i=new cs(e,t),i.enabled=n.enabled??!0,i.enableDamping=n.enableDamping??!0,i.dampingFactor=n.dampingFactor??.25,i.enableZoom=n.enableZoom??!0,i.enableRotate=n.enableRotate??!0,i.enablePan=n.enablePan??!0,n.minDistance!==void 0&&(i.minDistance=n.minDistance),n.maxDistance!==void 0&&(i.maxDistance=n.maxDistance),n.minPolarAngle!==void 0&&(i.minPolarAngle=n.minPolarAngle),n.maxPolarAngle!==void 0&&(i.maxPolarAngle=n.maxPolarAngle);const c=r.camera||{},h=c.target||c.cameraTarget;return h&&i.target&&(i.target.set(h[0],h[1],h[2]),i.update()),i}}class sh extends rs{createDefaultLoader(){return rs.createLoader("model.glb")}}const mo={staticScene:!1,backgroundColor:"#f0f0f7",replaceWithScreenshotOnComplete:!0,animationLoop:null,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:75,near:.1,far:1e5,autoFitToObject:!0},environment:{backgroundBlurriness:.5,backgroundIntensity:1,environmentIntensity:1},lighting:{ambientLight:{color:"#404040",intensity:Math.PI},hemisphereLight:{skyColor:"#ffffbb",groundColor:"#080820",intensity:1},directionalLight:{color:"#ffffff",intensity:Math.PI,position:[72,72,72],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:1}}},renderer:{antialias:!0,alpha:!1,shadowMapEnabled:!0,pixelRatio:window.devicePixelRatio,shadowMapType:2,toneMapping:6,toneMappingExposure:1.5},controls:{type:Vn.OrbitControls,enabled:!0,enableDamping:!0,dampingFactor:.25,enableZoom:!0,enableRotate:!0,enablePan:!0},helpers:{grid:{type:"hexagonal_wire",size:20,divisions:20,colorGrid:4473924,opacity:.5,styleOptions:{}},axes:!1,stats:!1,gizmo:!1,studioEnvironment:!0,darkStudioMode:!1}};function oh(s){const e=ce.useRef(s),t=ce.useMemo(()=>JSON.stringify({pathTracing:s.pathTracing,staticScene:s.staticScene,renderer:s.renderer,camera:s.camera,controls:s.controls,backgroundColor:s.backgroundColor,environment:s.environment,lighting:s.lighting,helpers:s.helpers}),[s.pathTracing,s.staticScene,s.renderer,s.camera,s.controls,s.backgroundColor,s.environment,s.lighting,s.helpers]);return ce.useMemo(()=>{e.current=s},[t,s]),e.current}function ah(s,e){const t=ce.useRef(null),[r,n]=ce.useState(new pt),[o,i]=ce.useState(!1),a=oh(e);ce.useEffect(()=>{var l;if(!s.current||t.current)return;const h={...mo,...a};console.log("[useViewerCore] Creating viewer with options:",{pathTracingEnabled:(l=h.pathTracing)==null?void 0:l.enabled,staticScene:h.staticScene,pathTracing:h.pathTracing});const d=ih.createViewer(s.current,h);t.current=d;const u=d.onStateChange(v=>{n(v)});return d.initialize().then(v=>{v.ok?i(!0):console.error("Failed to initialize viewer:",v.error)}),()=>{u(),d.dispose(),t.current=null,i(!1)}},[s,a]);const c=ce.useRef({width:0,height:0});return ce.useEffect(()=>{if(!t.current||!s.current)return;let h=null;const d=v=>{if(s.current&&t.current){const b=s.current.parentElement||s.current;let{clientWidth:S,clientHeight:g}=b;if(v&&v[0]){const{width:x,height:w}=v[0].contentRect;S=Math.floor(x),g=Math.floor(w)}if(c.current.width===S&&c.current.height===g)return;h!==null&&cancelAnimationFrame(h),h=requestAnimationFrame(()=>{t.current&&s.current&&(t.current.resize(S,g),c.current={width:S,height:g})})}};d();const u=()=>d();window.addEventListener("resize",u);let l=null;return typeof ResizeObserver<"u"&&s.current.parentElement&&(l=new ResizeObserver(d),l.observe(s.current.parentElement)),()=>{window.removeEventListener("resize",u),l==null||l.disconnect(),h!==null&&cancelAnimationFrame(h)}},[o,s]),{viewer:t.current,state:r,isInitialized:o}}function ch(s,e){const t=ce.useRef(e);t.current=e,ce.useEffect(()=>{if(!s)return;const r=s.getEvents(),n=[];return Object.keys(e).forEach(o=>{if(e[o]){const a=c=>{const h=t.current[o];h&&h(c)};r.on(o,a),n.push(()=>r.off(o,a))}}),()=>{n.forEach(o=>o())}},[s])}const go=ce.createContext(null);function lh({viewer:s,canvasRef:e,children:t}){return Ze.jsx(go.Provider,{value:{viewer:s,canvasRef:e},children:t})}function uh(){const s=ce.useContext(go);if(!s)throw new Error("useViewerContext must be used within ViewerProvider");return s}function hh(){const{canvasRef:s}=uh();return Ze.jsx("canvas",{ref:s,style:{width:"100%",height:"100%",display:"block",imageRendering:"auto",background:"transparent"}})}(function(){try{if(typeof document<"u"){var s=document.createElement("style");s.appendChild(document.createTextNode(".gizmo-default{width:100px;height:100px;position:absolute;top:0;right:0;z-index:2;cursor:pointer}")),document.head.appendChild(s)}}catch(e){console.error("vite-plugin-css-injected-by-js",e)}})();var Ui={exports:{}},$r={};/**
|
|
4015
|
+
`;continue}if((ne=H.match(E))&&(U.gamma=parseFloat(ne[1])),(ne=H.match(G))&&(U.exposure=parseFloat(ne[1])),(ne=H.match(z))&&(U.valid|=2,U.format=ne[1]),(ne=H.match(V))&&(U.valid|=4,U.height=parseInt(ne[1],10),U.width=parseInt(ne[2],10)),U.valid&2&&U.valid&4)break}return U.valid&2||i(3,"missing format specifier"),U.valid&4||i(3,"missing image size specifier"),U},v=function(O,L,E){const G=L;if(G<8||G>32767||O[0]!==2||O[1]!==2||O[2]&128)return new Uint8Array(O);G!==(O[2]<<8|O[3])&&i(3,"wrong scanline width");const z=new Uint8Array(4*L*E);z.length||i(4,"unable to allocate buffer space");let V=0,U=0;const H=4*G,ne=new Uint8Array(4),ge=new Uint8Array(H);let Pe=E;for(;Pe>0&&U<O.byteLength;){U+4>O.byteLength&&i(1),ne[0]=O[U++],ne[1]=O[U++],ne[2]=O[U++],ne[3]=O[U++],(ne[0]!=2||ne[1]!=2||(ne[2]<<8|ne[3])!=G)&&i(3,"bad rgbe scanline format");let ve=0,ye;for(;ve<H&&U<O.byteLength;){ye=O[U++];const _e=ye>128;if(_e&&(ye-=128),(ye===0||ve+ye>H)&&i(3,"bad scanline data"),_e){const Te=O[U++];for(let et=0;et<ye;et++)ge[ve++]=Te}else ge.set(O.subarray(U,U+ye),ve),ve+=ye,U+=ye}const Ue=G;for(let _e=0;_e<Ue;_e++){let Te=0;z[V]=ge[_e+Te],Te+=G,z[V+1]=ge[_e+Te],Te+=G,z[V+2]=ge[_e+Te],Te+=G,z[V+3]=ge[_e+Te],V+=4}Pe--}return z},x=function(O,L,E,G){const z=O[L+3],V=Math.pow(2,z-128)/255;E[G+0]=O[L+0]*V,E[G+1]=O[L+1]*V,E[G+2]=O[L+2]*V,E[G+3]=1},S=function(O,L,E,G){const z=O[L+3],V=Math.pow(2,z-128)/255;E[G+0]=f.DataUtils.toHalfFloat(Math.min(O[L+0]*V,65504)),E[G+1]=f.DataUtils.toHalfFloat(Math.min(O[L+1]*V,65504)),E[G+2]=f.DataUtils.toHalfFloat(Math.min(O[L+2]*V,65504)),E[G+3]=f.DataUtils.toHalfFloat(1)},g=new Uint8Array(e);g.pos=0;const b=l(g),w=b.width,T=b.height,A=v(g.subarray(g.pos),w,T);let P,D,R;switch(this.type){case f.FloatType:R=A.length/4;const O=new Float32Array(R*4);for(let E=0;E<R;E++)x(A,E*4,O,E*4);P=O,D=f.FloatType;break;case f.HalfFloatType:R=A.length/4;const L=new Uint16Array(R*4);for(let E=0;E<R;E++)S(A,E*4,L,E*4);P=L,D=f.HalfFloatType;break;default:throw new Error("THREE.RGBELoader: Unsupported type: "+this.type)}return{width:w,height:T,data:P,header:b.string,gamma:b.gamma,exposure:b.exposure,type:D}}setDataType(e){return this.type=e,this}load(e,t,r,n){function o(i,a){switch(i.type){case f.FloatType:case f.HalfFloatType:i.colorSpace=f.LinearSRGBColorSpace,i.minFilter=f.LinearFilter,i.magFilter=f.LinearFilter,i.generateMipmaps=!1,i.flipY=!0;break}t&&t(i,a)}return super.load(e,o,r,n)}}class eh extends f.Scene{constructor(){super();const e=new f.BoxGeometry;e.deleteAttribute("uv");const t=new f.MeshStandardMaterial({side:f.BackSide}),r=new f.MeshStandardMaterial,n=new f.PointLight(16777215,900,28,2);n.position.set(.418,16.199,.3),this.add(n);const o=new f.Mesh(e,t);o.position.set(-.757,13.219,.717),o.scale.set(31.713,28.305,28.591),this.add(o);const i=new f.Mesh(e,r);i.position.set(-10.906,2.009,1.846),i.rotation.set(0,-.195,0),i.scale.set(2.328,7.905,4.651),this.add(i);const a=new f.Mesh(e,r);a.position.set(-5.607,-.754,-.758),a.rotation.set(0,.994,0),a.scale.set(1.97,1.534,3.955),this.add(a);const c=new f.Mesh(e,r);c.position.set(6.167,.857,7.803),c.rotation.set(0,.561,0),c.scale.set(3.927,6.285,3.687),this.add(c);const h=new f.Mesh(e,r);h.position.set(-2.017,.018,6.124),h.rotation.set(0,.333,0),h.scale.set(2.002,4.566,2.064),this.add(h);const d=new f.Mesh(e,r);d.position.set(2.291,-.756,-2.621),d.rotation.set(0,-.286,0),d.scale.set(1.546,1.552,1.496),this.add(d);const u=new f.Mesh(e,r);u.position.set(-2.193,-.369,-5.547),u.rotation.set(0,.516,0),u.scale.set(3.875,3.487,2.986),this.add(u);const l=new f.Mesh(e,Dr(50));l.position.set(-16.116,14.37,8.208),l.scale.set(.1,2.428,2.739),this.add(l);const v=new f.Mesh(e,Dr(50));v.position.set(-16.109,18.021,-8.207),v.scale.set(.1,2.425,2.751),this.add(v);const x=new f.Mesh(e,Dr(17));x.position.set(14.904,12.198,-1.832),x.scale.set(.15,4.265,6.331),this.add(x);const S=new f.Mesh(e,Dr(43));S.position.set(-.462,8.89,14.52),S.scale.set(4.38,5.441,.088),this.add(S);const g=new f.Mesh(e,Dr(20));g.position.set(3.235,11.486,-12.541),g.scale.set(2.5,2,.1),this.add(g);const b=new f.Mesh(e,Dr(100));b.position.set(0,20,0),b.scale.set(1,.1,1),this.add(b)}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 Dr(s){const e=new f.MeshBasicMaterial;return e.color.setScalar(s),e}class th{constructor(){this.pmremGenerator=null,this.loadedTextures=new Map}async initialize(e){var t;try{const r=e.renderer;let n=r.renderer||((t=r.getThreeRenderer)==null?void 0:t.call(r));if(!n&&r.getDomElement){const o=r.getDomElement();if(o&&"parentElement"in o&&o.parentElement){const i=o.parentElement.renderer;i instanceof M.WebGLRenderer&&(n=i)}}return n?(this.pmremGenerator=new M.PMREMGenerator(n),this.pmremGenerator.compileEquirectangularShader(),K.ok(void 0)):K.err(new oe("Could not access Three.js renderer",ue.INITIALIZATION_FAILED))}catch(r){return K.err(new oe("Failed to initialize environment service",ue.INITIALIZATION_FAILED,{originalError:r}))}}async loadEnvironmentMap(e){var t,r,n,o;try{const i=this.loadedTextures.get(e);if(i)return K.ok(new Rr(i));const a=(t=e.split(".").pop())==null?void 0:t.toLowerCase();let c;switch(a){case"hdr":c=new Hu;break;case"exr":c=new Ju;break;case"jpg":case"jpeg":case"png":c=new M.TextureLoader;break;default:return K.err(new oe(`Unsupported environment map format: ${a}`,ue.UNSUPPORTED_FORMAT,{url:e,extension:a}))}const h=await new Promise((d,u)=>{c.load(e,l=>{var v,x,S,g,b;console.log("[ThreeEnvironmentService] Texture loaded:",{url:e,format:l.format,type:l.type,mapping:l.mapping,hasImage:!!l.image,imageType:(x=(v=l.image)==null?void 0:v.constructor)==null?void 0:x.name,imageData:(S=l.image)!=null&&S.data?"has data":"no data",imageWidth:(g=l.image)==null?void 0:g.width,imageHeight:(b=l.image)==null?void 0:b.height}),d(l)},void 0,l=>u(l))});if(this.pmremGenerator){h.mapping=M.EquirectangularReflectionMapping;const d=this.pmremGenerator.fromEquirectangular(h).texture;return this.loadedTextures.set(e,d),this.loadedTextures.set(e+"_original",h),console.log("[ThreeEnvironmentService] Stored original texture for path tracing:",{url:e+"_original",format:h.format,mapping:h.mapping,hasImage:!!h.image,imageComplete:(r=h.image)==null?void 0:r.complete,imageNaturalWidth:(n=h.image)==null?void 0:n.naturalWidth,imageNaturalHeight:(o=h.image)==null?void 0:o.naturalHeight}),K.ok(new Rr(d))}return this.loadedTextures.set(e,h),K.ok(new Rr(h))}catch(i){return K.err(new oe("Failed to load environment map",ue.TEXTURE_LOAD_FAILED,{url:e,originalError:i}))}}applyToScene(e,t,r){try{if(!(e instanceof Yt))return K.err(new oe("Scene must be ThreeSceneAdapter",ue.INVALID_PARAMETER));if(!(t instanceof Rr))return K.err(new oe("Texture must be ThreeTextureAdapter",ue.INVALID_PARAMETER));const n=e.getThreeScene(),o=t.getThreeTexture();if(n.environment=o,r&&(r.backgroundBlurriness!==void 0&&(n.backgroundBlurriness=r.backgroundBlurriness),r.backgroundIntensity!==void 0&&(n.backgroundIntensity=r.backgroundIntensity),r.environmentIntensity!==void 0&&(n.environmentIntensity=r.environmentIntensity)),o.mapping===M.CubeUVReflectionMapping){const a=Array.from(this.loadedTextures.entries()).find(([c,h])=>c.endsWith("_original")&&h.mapping===M.EquirectangularReflectionMapping);a&&(n.__originalEnvironmentTexture=a[1])}else o.mapping===M.EquirectangularReflectionMapping&&(n.__originalEnvironmentTexture=o);if(o.mapping===M.EquirectangularReflectionMapping)n.background=o;else if(o.mapping===M.CubeUVReflectionMapping){const a=Array.from(this.loadedTextures.entries()).find(([c,h])=>c.endsWith("_original")&&h.mapping===M.EquirectangularReflectionMapping);a?n.background=a[1]:n.background=o}else n.background=o;return K.ok(void 0)}catch(n){return K.err(new oe("Failed to apply environment to scene",ue.SCENE_OPERATION_FAILED,{originalError:n}))}}getOriginalEnvironmentTexture(e){const t=this.loadedTextures.get(e+"_original");return t?new Rr(t):null}createStudioEnvironment(e={}){try{if(!this.pmremGenerator)return K.err(new oe("Environment service not initialized",ue.INITIALIZATION_FAILED));const t=new eh,r=this.pmremGenerator.fromScene(t).texture;return t.dispose(),K.ok(new Rr(r))}catch(t){return K.err(new oe("Failed to create studio environment",ue.TEXTURE_LOAD_FAILED,{originalError:t}))}}dispose(){this.loadedTextures.forEach(e=>e.dispose()),this.loadedTextures.clear(),this.pmremGenerator&&(this.pmremGenerator.dispose(),this.pmremGenerator=null)}}class Rr{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 rh{constructor(e){this.object=e,this.boundingBox=new M.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,r=new M.Vector3;return t>0?r.y=-e:r.y=0,r}applyOffset(e){this.object.position.add(e)}}class nh{alignToFloor(e){try{let t=null;return"getThreeObject"in e&&typeof e.getThreeObject=="function"?t=e.getThreeObject():e instanceof M.Object3D&&(t=e),t?(new rh(t).alignToFloor(),K.ok(void 0)):K.err(new oe("Could not get Three.js object for floor alignment",ue.INVALID_PARAMETER))}catch(t){return K.err(new oe("Failed to align object to floor",ue.OPERATION_FAILED,{originalError:t}))}}}var Vn=(s=>(s.MapControls="MapControls",s.OrbitControls="OrbitControls",s))(Vn||{});class ih{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===M.BasicShadowMap)return"basic";if(e===M.PCFShadowMap)return"pcf";if(e===M.PCFSoftShadowMap)return"pcfsoft";if(e===M.VSMShadowMap)return"vsm"}return typeof e=="string"?e:void 0}static convertToneMappingType(e){if(typeof e=="number"){if(e===M.NoToneMapping)return"none";if(e===M.LinearToneMapping)return"linear";if(e===M.ReinhardToneMapping)return"reinhard";if(e===M.CineonToneMapping)return"cineon";if(e===M.ACESFilmicToneMapping)return"aces"}return typeof e=="string"?e:"aces"}}class sh{static createViewer(e,t){var S;const r=new Eo(e),n=new Yt,o=this.createCamera(t),i=this.createControls(o.getThreeCamera(),e,t),a=new oh().createDefaultLoader(),c=new Ga,h=new th;let d;(((S=t.pathTracing)==null?void 0:S.enabled)??!1)&&(d=new ku);const l=new nh,v=ih.convertRendererOptions(t.renderer||{}),x={renderer:r,scene:n,camera:o,controls:i,modelLoader:a,options:t,rendererOptions:v,sceneSetupService:c,environmentService:h,pathTracingService:d,floorAlignmentService:l};return new Bo(x)}static createCamera(e){const r=e.camera||{},n=r.fov||r.cameraFov||75,o=r.near||r.cameraNear||.1,i=r.far||r.cameraFar||1e5,a=r.position||r.cameraPosition,c=r.target||r.cameraTarget,h=$n.create(n,1,o,i);return a&&h.position.set(a[0],a[1],a[2]),c&&h.lookAt({x:c[0],y:c[1],z:c[2],set:()=>{},copy:()=>{},add:()=>{},multiply:()=>{},normalize:()=>{},length:()=>0}),h}static createControls(e,t,r){const n=r.controls||{},o=n.type||Vn.OrbitControls;let i;o===Vn.MapControls?i=new ls(e,t):i=new cs(e,t),i.enabled=n.enabled??!0,i.enableDamping=n.enableDamping??!0,i.dampingFactor=n.dampingFactor??.25,i.enableZoom=n.enableZoom??!0,i.enableRotate=n.enableRotate??!0,i.enablePan=n.enablePan??!0,n.minDistance!==void 0&&(i.minDistance=n.minDistance),n.maxDistance!==void 0&&(i.maxDistance=n.maxDistance),n.minPolarAngle!==void 0&&(i.minPolarAngle=n.minPolarAngle),n.maxPolarAngle!==void 0&&(i.maxPolarAngle=n.maxPolarAngle);const c=r.camera||{},h=c.target||c.cameraTarget;return h&&i.target&&(i.target.set(h[0],h[1],h[2]),i.update()),i}}class oh extends rs{createDefaultLoader(){return rs.createLoader("model.glb")}}const mo={staticScene:!1,backgroundColor:"#f0f0f7",replaceWithScreenshotOnComplete:!0,animationLoop:null,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:75,near:.1,far:1e5,autoFitToObject:!0},environment:{backgroundBlurriness:.5,backgroundIntensity:1,environmentIntensity:1},lighting:{ambientLight:{color:"#404040",intensity:Math.PI},hemisphereLight:{skyColor:"#ffffbb",groundColor:"#080820",intensity:1},directionalLight:{color:"#ffffff",intensity:Math.PI,position:[72,72,72],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:1}}},renderer:{antialias:!0,alpha:!1,shadowMapEnabled:!0,pixelRatio:window.devicePixelRatio,shadowMapType:2,toneMapping:6,toneMappingExposure:1.5},controls:{type:Vn.OrbitControls,enabled:!0,enableDamping:!0,dampingFactor:.25,enableZoom:!0,enableRotate:!0,enablePan:!0},helpers:{grid:{type:"hexagonal_wire",size:20,divisions:20,colorGrid:4473924,opacity:.5,styleOptions:{}},axes:!1,stats:!1,gizmo:!1,studioEnvironment:!0,darkStudioMode:!1}};function ah(s){const e=ce.useRef(s),t=ce.useMemo(()=>JSON.stringify({pathTracing:s.pathTracing,staticScene:s.staticScene,renderer:s.renderer,camera:s.camera,controls:s.controls,backgroundColor:s.backgroundColor,environment:s.environment,lighting:s.lighting,helpers:s.helpers}),[s.pathTracing,s.staticScene,s.renderer,s.camera,s.controls,s.backgroundColor,s.environment,s.lighting,s.helpers]);return ce.useMemo(()=>{e.current=s},[t,s]),e.current}function ch(s,e){const t=ce.useRef(null),[r,n]=ce.useState(new pt),[o,i]=ce.useState(!1),a=ah(e);ce.useEffect(()=>{var l;if(!s.current||t.current)return;const h={...mo,...a};console.log("[useViewerCore] Creating viewer with options:",{pathTracingEnabled:(l=h.pathTracing)==null?void 0:l.enabled,staticScene:h.staticScene,pathTracing:h.pathTracing});const d=sh.createViewer(s.current,h);t.current=d;const u=d.onStateChange(v=>{n(v)});return d.initialize().then(v=>{v.ok?i(!0):console.error("Failed to initialize viewer:",v.error)}),()=>{u(),d.dispose(),t.current=null,i(!1)}},[s,a]);const c=ce.useRef({width:0,height:0});return ce.useEffect(()=>{if(!t.current||!s.current)return;let h=null;const d=v=>{if(s.current&&t.current){const x=s.current.parentElement||s.current;let{clientWidth:S,clientHeight:g}=x;if(v&&v[0]){const{width:b,height:w}=v[0].contentRect;S=Math.floor(b),g=Math.floor(w)}if(c.current.width===S&&c.current.height===g)return;h!==null&&cancelAnimationFrame(h),h=requestAnimationFrame(()=>{t.current&&s.current&&(t.current.resize(S,g),c.current={width:S,height:g})})}};d();const u=()=>d();window.addEventListener("resize",u);let l=null;return typeof ResizeObserver<"u"&&s.current.parentElement&&(l=new ResizeObserver(d),l.observe(s.current.parentElement)),()=>{window.removeEventListener("resize",u),l==null||l.disconnect(),h!==null&&cancelAnimationFrame(h)}},[o,s]),{viewer:t.current,state:r,isInitialized:o}}function lh(s,e){const t=ce.useRef(e);t.current=e,ce.useEffect(()=>{if(!s)return;const r=s.getEvents(),n=[];return Object.keys(e).forEach(o=>{if(e[o]){const a=c=>{const h=t.current[o];h&&h(c)};r.on(o,a),n.push(()=>r.off(o,a))}}),()=>{n.forEach(o=>o())}},[s])}const go=ce.createContext(null);function uh({viewer:s,canvasRef:e,children:t}){return Ze.jsx(go.Provider,{value:{viewer:s,canvasRef:e},children:t})}function hh(){const s=ce.useContext(go);if(!s)throw new Error("useViewerContext must be used within ViewerProvider");return s}function fh(){const{canvasRef:s}=hh();return Ze.jsx("canvas",{ref:s,style:{width:"100%",height:"100%",display:"block",imageRendering:"auto",background:"transparent"}})}(function(){try{if(typeof document<"u"){var s=document.createElement("style");s.appendChild(document.createTextNode(".gizmo-default{width:100px;height:100px;position:absolute;top:0;right:0;z-index:2;cursor:pointer}")),document.head.appendChild(s)}}catch(e){console.error("vite-plugin-css-injected-by-js",e)}})();var Ui={exports:{}},$r={};/**
|
|
4016
4016
|
* @license React
|
|
4017
4017
|
* react-jsx-runtime.production.min.js
|
|
4018
4018
|
*
|
|
@@ -4020,7 +4020,7 @@ version 0.8.2
|
|
|
4020
4020
|
*
|
|
4021
4021
|
* This source code is licensed under the MIT license found in the
|
|
4022
4022
|
* LICENSE file in the root directory of this source tree.
|
|
4023
|
-
*/var vo;function
|
|
4023
|
+
*/var vo;function dh(){if(vo)return $r;vo=1;var s=ce,e=Symbol.for("react.element"),t=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,n=s.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,o={key:!0,ref:!0,__self:!0,__source:!0};function i(a,c,h){var d,u={},l=null,v=null;h!==void 0&&(l=""+h),c.key!==void 0&&(l=""+c.key),c.ref!==void 0&&(v=c.ref);for(d in c)r.call(c,d)&&!o.hasOwnProperty(d)&&(u[d]=c[d]);if(a&&a.defaultProps)for(d in c=a.defaultProps,c)u[d]===void 0&&(u[d]=c[d]);return{$$typeof:e,type:a,key:l,ref:v,props:u,_owner:n.current}}return $r.Fragment=t,$r.jsx=i,$r.jsxs=i,$r}var jn={};/**
|
|
4024
4024
|
* @license React
|
|
4025
4025
|
* react-jsx-runtime.development.js
|
|
4026
4026
|
*
|
|
@@ -4028,11 +4028,11 @@ version 0.8.2
|
|
|
4028
4028
|
*
|
|
4029
4029
|
* This source code is licensed under the MIT license found in the
|
|
4030
4030
|
* LICENSE file in the root directory of this source tree.
|
|
4031
|
-
*/var yo;function
|
|
4031
|
+
*/var yo;function ph(){return yo||(yo=1,process.env.NODE_ENV!=="production"&&function(){var s=ce,e=Symbol.for("react.element"),t=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),n=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),i=Symbol.for("react.provider"),a=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),u=Symbol.for("react.memo"),l=Symbol.for("react.lazy"),v=Symbol.for("react.offscreen"),x=Symbol.iterator,S="@@iterator";function g(m){if(m===null||typeof m!="object")return null;var C=x&&m[x]||m[S];return typeof C=="function"?C:null}var b=s.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function w(m){{for(var C=arguments.length,N=new Array(C>1?C-1:0),q=1;q<C;q++)N[q-1]=arguments[q];T("error",m,N)}}function T(m,C,N){{var q=b.ReactDebugCurrentFrame,ie=q.getStackAddendum();ie!==""&&(C+="%s",N=N.concat([ie]));var ae=N.map(function(Q){return String(Q)});ae.unshift("Warning: "+C),Function.prototype.apply.call(console[m],console,ae)}}var A=!1,P=!1,D=!1,R=!1,O=!1,L;L=Symbol.for("react.module.reference");function E(m){return!!(typeof m=="string"||typeof m=="function"||m===r||m===o||O||m===n||m===h||m===d||R||m===v||A||P||D||typeof m=="object"&&m!==null&&(m.$$typeof===l||m.$$typeof===u||m.$$typeof===i||m.$$typeof===a||m.$$typeof===c||m.$$typeof===L||m.getModuleId!==void 0))}function G(m,C,N){var q=m.displayName;if(q)return q;var ie=C.displayName||C.name||"";return ie!==""?N+"("+ie+")":N}function z(m){return m.displayName||"Context"}function V(m){if(m==null)return null;if(typeof m.tag=="number"&&w("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof m=="function")return m.displayName||m.name||null;if(typeof m=="string")return m;switch(m){case r:return"Fragment";case t:return"Portal";case o:return"Profiler";case n:return"StrictMode";case h:return"Suspense";case d:return"SuspenseList"}if(typeof m=="object")switch(m.$$typeof){case a:var C=m;return z(C)+".Consumer";case i:var N=m;return z(N._context)+".Provider";case c:return G(m,m.render,"ForwardRef");case u:var q=m.displayName||null;return q!==null?q:V(m.type)||"Memo";case l:{var ie=m,ae=ie._payload,Q=ie._init;try{return V(Q(ae))}catch{return null}}}return null}var U=Object.assign,H=0,ne,ge,Pe,ve,ye,Ue,_e;function Te(){}Te.__reactDisabledLog=!0;function et(){{if(H===0){ne=console.log,ge=console.info,Pe=console.warn,ve=console.error,ye=console.group,Ue=console.groupCollapsed,_e=console.groupEnd;var m={configurable:!0,enumerable:!0,value:Te,writable:!0};Object.defineProperties(console,{info:m,log:m,warn:m,error:m,group:m,groupCollapsed:m,groupEnd:m})}H++}}function lt(){{if(H--,H===0){var m={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:U({},m,{value:ne}),info:U({},m,{value:ge}),warn:U({},m,{value:Pe}),error:U({},m,{value:ve}),group:U({},m,{value:ye}),groupCollapsed:U({},m,{value:Ue}),groupEnd:U({},m,{value:_e})})}H<0&&w("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var de=b.ReactCurrentDispatcher,ze;function ke(m,C,N){{if(ze===void 0)try{throw Error()}catch(ie){var q=ie.stack.trim().match(/\n( *(at )?)/);ze=q&&q[1]||""}return`
|
|
4032
4032
|
`+ze+m}}var ut=!1,tt;{var Dt=typeof WeakMap=="function"?WeakMap:Map;tt=new Dt}function _t(m,C){if(!m||ut)return"";{var N=tt.get(m);if(N!==void 0)return N}var q;ut=!0;var ie=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var ae;ae=de.current,de.current=null,et();try{if(C){var Q=function(){throw Error()};if(Object.defineProperty(Q.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Q,[])}catch(B){q=B}Reflect.construct(m,[],Q)}else{try{Q.call()}catch(B){q=B}m.call(Q.prototype)}}else{try{throw Error()}catch(B){q=B}m()}}catch(B){if(B&&q&&typeof B.stack=="string"){for(var $=B.stack.split(`
|
|
4033
4033
|
`),p=q.stack.split(`
|
|
4034
4034
|
`),y=$.length-1,_=p.length-1;y>=1&&_>=0&&$[y]!==p[_];)_--;for(;y>=1&&_>=0;y--,_--)if($[y]!==p[_]){if(y!==1||_!==1)do if(y--,_--,_<0||$[y]!==p[_]){var I=`
|
|
4035
|
-
`+$[y].replace(" at new "," at ");return m.displayName&&I.includes("<anonymous>")&&(I=I.replace("<anonymous>",m.displayName)),typeof m=="function"&&tt.set(m,I),I}while(y>=1&&_>=0);break}}}finally{ut=!1,de.current=ae,lt(),Error.prepareStackTrace=ie}var k=m?m.displayName||m.name:"",F=k?ke(k):"";return typeof m=="function"&&tt.set(m,F),F}function Rt(m,C,N){return _t(m,!1)}function Fr(m){var C=m.prototype;return!!(C&&C.isReactComponent)}function ht(m,C,N){if(m==null)return"";if(typeof m=="function")return _t(m,Fr(m));if(typeof m=="string")return ke(m);switch(m){case h:return ke("Suspense");case d:return ke("SuspenseList")}if(typeof m=="object")switch(m.$$typeof){case c:return Rt(m.render);case u:return ht(m.type,C,N);case l:{var q=m,ie=q._payload,ae=q._init;try{return ht(ae(ie),C,N)}catch{}}}return""}var rt=Object.prototype.hasOwnProperty,Jt={},Ht=
|
|
4035
|
+
`+$[y].replace(" at new "," at ");return m.displayName&&I.includes("<anonymous>")&&(I=I.replace("<anonymous>",m.displayName)),typeof m=="function"&&tt.set(m,I),I}while(y>=1&&_>=0);break}}}finally{ut=!1,de.current=ae,lt(),Error.prepareStackTrace=ie}var k=m?m.displayName||m.name:"",F=k?ke(k):"";return typeof m=="function"&&tt.set(m,F),F}function Rt(m,C,N){return _t(m,!1)}function Fr(m){var C=m.prototype;return!!(C&&C.isReactComponent)}function ht(m,C,N){if(m==null)return"";if(typeof m=="function")return _t(m,Fr(m));if(typeof m=="string")return ke(m);switch(m){case h:return ke("Suspense");case d:return ke("SuspenseList")}if(typeof m=="object")switch(m.$$typeof){case c:return Rt(m.render);case u:return ht(m.type,C,N);case l:{var q=m,ie=q._payload,ae=q._init;try{return ht(ae(ie),C,N)}catch{}}}return""}var rt=Object.prototype.hasOwnProperty,Jt={},Ht=b.ReactDebugCurrentFrame;function bt(m){if(m){var C=m._owner,N=ht(m.type,m._source,C?C.type:null);Ht.setExtraStackFrame(N)}else Ht.setExtraStackFrame(null)}function Jr(m,C,N,q,ie){{var ae=Function.call.bind(rt);for(var Q in m)if(ae(m,Q)){var $=void 0;try{if(typeof m[Q]!="function"){var p=Error((q||"React class")+": "+N+" type `"+Q+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof m[Q]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw p.name="Invariant Violation",p}$=m[Q](C,Q,q,N,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(y){$=y}$&&!($ instanceof Error)&&(bt(ie),w("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",q||"React class",N,Q,typeof $),bt(null)),$ instanceof Error&&!($.message in Jt)&&(Jt[$.message]=!0,bt(ie),w("Failed %s type: %s",N,$.message),bt(null))}}}var Hr=Array.isArray;function Ft(m){return Hr(m)}function er(m){{var C=typeof Symbol=="function"&&Symbol.toStringTag,N=C&&m[Symbol.toStringTag]||m.constructor.name||"Object";return N}}function en(m){try{return Ot(m),!1}catch{return!0}}function Ot(m){return""+m}function tr(m){if(en(m))return w("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",er(m)),Ot(m)}var rr=b.ReactCurrentOwner,Or={key:!0,ref:!0,__self:!0,__source:!0},St,nr;function tn(m){if(rt.call(m,"ref")){var C=Object.getOwnPropertyDescriptor(m,"ref").get;if(C&&C.isReactWarning)return!1}return m.ref!==void 0}function rn(m){if(rt.call(m,"key")){var C=Object.getOwnPropertyDescriptor(m,"key").get;if(C&&C.isReactWarning)return!1}return m.key!==void 0}function Ve(m,C){typeof m.ref=="string"&&rr.current}function je(m,C){{var N=function(){St||(St=!0,w("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",C))};N.isReactWarning=!0,Object.defineProperty(m,"key",{get:N,configurable:!0})}}function Lr(m,C){{var N=function(){nr||(nr=!0,w("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",C))};N.isReactWarning=!0,Object.defineProperty(m,"ref",{get:N,configurable:!0})}}var ft=function(m,C,N,q,ie,ae,Q){var $={$$typeof:e,type:m,key:C,ref:N,props:Q,_owner:ae};return $._store={},Object.defineProperty($._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty($,"_self",{configurable:!1,enumerable:!1,writable:!1,value:q}),Object.defineProperty($,"_source",{configurable:!1,enumerable:!1,writable:!1,value:ie}),Object.freeze&&(Object.freeze($.props),Object.freeze($)),$};function Ge(m,C,N,q,ie){{var ae,Q={},$=null,p=null;N!==void 0&&(tr(N),$=""+N),rn(C)&&(tr(C.key),$=""+C.key),tn(C)&&(p=C.ref,Ve(C,ie));for(ae in C)rt.call(C,ae)&&!Or.hasOwnProperty(ae)&&(Q[ae]=C[ae]);if(m&&m.defaultProps){var y=m.defaultProps;for(ae in y)Q[ae]===void 0&&(Q[ae]=y[ae])}if($||p){var _=typeof m=="function"?m.displayName||m.name||"Unknown":m;$&&je(Q,_),p&&Lr(Q,_)}return ft(m,$,p,ie,q,rr.current,Q)}}var De=b.ReactCurrentOwner,ir=b.ReactDebugCurrentFrame;function X(m){if(m){var C=m._owner,N=ht(m.type,m._source,C?C.type:null);ir.setExtraStackFrame(N)}else ir.setExtraStackFrame(null)}var nt;nt=!1;function Lt(m){return typeof m=="object"&&m!==null&&m.$$typeof===e}function sr(){{if(De.current){var m=V(De.current.type);if(m)return`
|
|
4036
4036
|
|
|
4037
4037
|
Check the render method of \``+m+"`."}return""}}function nn(m){return""}var or={};function sn(m){{var C=sr();if(!C){var N=typeof m=="string"?m:m.displayName||m.name;N&&(C=`
|
|
4038
4038
|
|
|
@@ -4041,4 +4041,4 @@ Check the top-level render call using <`+N+">.")}return C}}function ar(m,C){{if(
|
|
|
4041
4041
|
<%s {...props} />
|
|
4042
4042
|
React keys must be passed directly to JSX without using spread:
|
|
4043
4043
|
let props = %s;
|
|
4044
|
-
<%s key={someKey} {...props} />`,Z,F,Y,F),lr[F+Z]=!0}}return m===r?an(_):on(_),_}}function cn(m,C,N){return ur(m,C,N,!0)}function ln(m,C,N){return ur(m,C,N,!1)}var Nr=ln,un=cn;jn.Fragment=r,jn.jsx=Nr,jn.jsxs=un}()),jn}process.env.NODE_ENV==="production"?Ui.exports=fh():Ui.exports=dh();var ph=Ui.exports;const mh=(s,e,t,r,n,o)=>{const i=performance.now(),a=()=>{const c=performance.now()-i,h=Math.min(c/n,1);s.position.lerpVectors(t,r,h),e==null||e.update(),o(),h<1&&requestAnimationFrame(a)};requestAnimationFrame(a)},bo=(s,e)=>{s.quaternion.copy(e.quaternion);const t=new M.Vector3(0,0,-1).applyQuaternion(s.quaternion).normalize();s.position.copy(t.multiplyScalar(-8)),s.lookAt(new M.Vector3(0,0,0)),s.updateMatrixWorld(!0)},gh=(s,e,t)=>{const r=t.target.clone(),n=s.position.clone().sub(r).length(),o=new M.Vector3(0,0,-1).applyQuaternion(e.quaternion).normalize().multiplyScalar(-n);s.position.copy(r).add(o),s.quaternion.copy(e.quaternion),s.updateMatrixWorld(!0),t.update()},vh=()=>{try{const s=document.createElement("canvas");return!!(window.WebGLRenderingContext&&(s.getContext("webgl")||s.getContext("experimental-webgl")))}catch{return!1}},yh=()=>vh()?new M.WebGLRenderer({alpha:!0,antialias:!1}):(console.error("WebGL is not supported in this environment."),null),xo={type:"change"},Gi={type:"start"},wo={type:"end"},Wn=new f.Ray,_o=new f.Plane,bh=Math.cos(70*f.MathUtils.DEG2RAD),Ne=new f.Vector3,Qe=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},Vi=1e-6;class xh extends f.Controls{constructor(e,t=null){super(e,t),this.state=we.NONE,this.enabled=!0,this.target=new f.Vector3,this.cursor=new f.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.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:f.MOUSE.ROTATE,MIDDLE:f.MOUSE.DOLLY,RIGHT:f.MOUSE.PAN},this.touches={ONE:f.TOUCH.ROTATE,TWO:f.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 f.Vector3,this._lastQuaternion=new f.Quaternion,this._lastTargetPosition=new f.Vector3,this._quat=new f.Quaternion().setFromUnitVectors(e.up,new f.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new f.Spherical,this._sphericalDelta=new f.Spherical,this._scale=1,this._panOffset=new f.Vector3,this._rotateStart=new f.Vector2,this._rotateEnd=new f.Vector2,this._rotateDelta=new f.Vector2,this._panStart=new f.Vector2,this._panEnd=new f.Vector2,this._panDelta=new f.Vector2,this._dollyStart=new f.Vector2,this._dollyEnd=new f.Vector2,this._dollyDelta=new f.Vector2,this._dollyDirection=new f.Vector3,this._mouse=new f.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=_h.bind(this),this._onPointerDown=wh.bind(this),this._onPointerUp=Sh.bind(this),this._onContextMenu=Dh.bind(this),this._onMouseWheel=Mh.bind(this),this._onKeyDown=Ih.bind(this),this._onTouchStart=Ch.bind(this),this._onTouchMove=Ph.bind(this),this._onMouseDown=Th.bind(this),this._onMouseMove=Ah.bind(this),this._interceptControlDown=Rh.bind(this),this._interceptControlUp=Fh.bind(this),this.domElement!==null&&this.connect(),this.update()}connect(){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(xo),this.update(),this.state=we.NONE}update(e=null){const t=this.object.position;Ne.copy(t).sub(this.target),Ne.applyQuaternion(this._quat),this._spherical.setFromVector3(Ne),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 r=this.minAzimuthAngle,n=this.maxAzimuthAngle;isFinite(r)&&isFinite(n)&&(r<-Math.PI?r+=Qe:r>Math.PI&&(r-=Qe),n<-Math.PI?n+=Qe:n>Math.PI&&(n-=Qe),r<=n?this._spherical.theta=Math.max(r,Math.min(n,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(r+n)/2?Math.max(r,this._spherical.theta):Math.min(n,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let o=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const i=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),o=i!=this._spherical.radius}if(Ne.setFromSpherical(this._spherical),Ne.applyQuaternion(this._quatInverse),t.copy(this.target).add(Ne),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 i=null;if(this.object.isPerspectiveCamera){const a=Ne.length();i=this._clampDistance(a*this._scale);const c=a-i;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),o=!!c}else if(this.object.isOrthographicCamera){const a=new f.Vector3(this._mouse.x,this._mouse.y,0);a.unproject(this.object);const c=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),o=c!==this.object.zoom;const h=new f.Vector3(this._mouse.x,this._mouse.y,0);h.unproject(this.object),this.object.position.sub(h).add(a),this.object.updateMatrixWorld(),i=Ne.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;i!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(i).add(this.object.position):(Wn.origin.copy(this.object.position),Wn.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Wn.direction))<bh?this.object.lookAt(this.target):(_o.setFromNormalAndCoplanarPoint(this.object.up,this.target),Wn.intersectPlane(_o,this.target))))}else if(this.object.isOrthographicCamera){const i=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),i!==this.object.zoom&&(this.object.updateProjectionMatrix(),o=!0)}return this._scale=1,this._performCursorZoom=!1,o||this._lastPosition.distanceToSquared(this.object.position)>Vi||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Vi||this._lastTargetPosition.distanceToSquared(this.target)>Vi?(this.dispatchEvent(xo),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){Ne.setFromMatrixColumn(t,0),Ne.multiplyScalar(-e),this._panOffset.add(Ne)}_panUp(e,t){this.screenSpacePanning===!0?Ne.setFromMatrixColumn(t,1):(Ne.setFromMatrixColumn(t,0),Ne.crossVectors(this.object.up,Ne)),Ne.multiplyScalar(e),this._panOffset.add(Ne)}_pan(e,t){const r=this.domElement;if(this.object.isPerspectiveCamera){const n=this.object.position;Ne.copy(n).sub(this.target);let o=Ne.length();o*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*o/r.clientHeight,this.object.matrix),this._panUp(2*t*o/r.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/r.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/r.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 r=this.domElement.getBoundingClientRect(),n=e-r.left,o=t-r.top,i=r.width,a=r.height;this._mouse.x=n/i*2-1,this._mouse.y=-(o/a)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Qe*this._rotateDelta.x/t.clientHeight),this._rotateUp(Qe*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this._rotateUp(Qe*this.rotateSpeed/this.domElement.clientHeight):this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this._rotateUp(-Qe*this.rotateSpeed/this.domElement.clientHeight):this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this._rotateLeft(Qe*this.rotateSpeed/this.domElement.clientHeight):this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this._rotateLeft(-Qe*this.rotateSpeed/this.domElement.clientHeight):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),r=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);this._rotateStart.set(r,n)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),r=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);this._panStart.set(r,n)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),r=e.pageX-t.x,n=e.pageY-t.y,o=Math.sqrt(r*r+n*n);this._dollyStart.set(0,o)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const r=this._getSecondPointerPosition(e),n=.5*(e.pageX+r.x),o=.5*(e.pageY+r.y);this._rotateEnd.set(n,o)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Qe*this._rotateDelta.x/t.clientHeight),this._rotateUp(Qe*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),r=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);this._panEnd.set(r,n)}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),r=e.pageX-t.x,n=e.pageY-t.y,o=Math.sqrt(r*r+n*n);this._dollyEnd.set(0,o),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const i=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(i,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 f.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,r={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:r.deltaY*=16;break;case 2:r.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(r.deltaY*=10),r}}function wh(s){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(s.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(s)&&(this._addPointer(s),s.pointerType==="touch"?this._onTouchStart(s):this._onMouseDown(s)))}function _h(s){this.enabled!==!1&&(s.pointerType==="touch"?this._onTouchMove(s):this._onMouseMove(s))}function Sh(s){switch(this._removePointer(s),this._pointers.length){case 0:this.domElement.releasePointerCapture(s.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(wo),this.state=we.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 Th(s){let e;switch(s.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 f.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(s),this.state=we.DOLLY;break;case f.MOUSE.ROTATE:if(s.ctrlKey||s.metaKey||s.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(s),this.state=we.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(s),this.state=we.ROTATE}break;case f.MOUSE.PAN:if(s.ctrlKey||s.metaKey||s.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(s),this.state=we.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(s),this.state=we.PAN}break;default:this.state=we.NONE}this.state!==we.NONE&&this.dispatchEvent(Gi)}function Ah(s){switch(this.state){case we.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(s);break;case we.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(s);break;case we.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(s);break}}function Mh(s){this.enabled===!1||this.enableZoom===!1||this.state!==we.NONE||(s.preventDefault(),this.dispatchEvent(Gi),this._handleMouseWheel(this._customWheelEvent(s)),this.dispatchEvent(wo))}function Ih(s){this.enabled===!1||this.enablePan===!1||this._handleKeyDown(s)}function Ch(s){switch(this._trackPointer(s),this._pointers.length){case 1:switch(this.touches.ONE){case f.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(s),this.state=we.TOUCH_ROTATE;break;case f.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(s),this.state=we.TOUCH_PAN;break;default:this.state=we.NONE}break;case 2:switch(this.touches.TWO){case f.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(s),this.state=we.TOUCH_DOLLY_PAN;break;case f.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(s),this.state=we.TOUCH_DOLLY_ROTATE;break;default:this.state=we.NONE}break;default:this.state=we.NONE}this.state!==we.NONE&&this.dispatchEvent(Gi)}function Ph(s){switch(this._trackPointer(s),this.state){case we.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(s),this.update();break;case we.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(s),this.update();break;case we.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(s),this.update();break;case we.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(s),this.update();break;default:this.state=we.NONE}}function Dh(s){this.enabled!==!1&&s.preventDefault()}function Rh(s){s.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function Fh(s){s.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}const Oh=s=>{const e=new M.AmbientLight(16777215,1);s.add(e);const t=new M.DirectionalLight(16777215,1);t.position.set(5,10,5),s.add(t);const r=new M.DirectionalLight(16777215,1);r.position.set(-5,-10,5),s.add(r);const n=new M.PointLight(16777215,1,100);n.position.set(0,0,5),s.add(n),t.castShadow=!1,r.castShadow=!1,n.castShadow=!1},pe={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 Wt=(s=>(s.FRONT="FRONT",s.BACK="BACK",s.RIGHT="RIGHT",s.LEFT="LEFT",s.TOP="TOP",s.BOTTOM="BOTTOM",s))(Wt||{});new M.Vector3(0,1,0);class Lh{static createTextTexture(e){const t=document.createElement("canvas"),r=t.getContext("2d");t.width=pe.CANVAS_SIZE,t.height=pe.CANVAS_SIZE,r&&(r.clearRect(0,0,t.width,t.height),r.font=`${pe.FONT_SIZE} Arial`,r.fillStyle=pe.TEXT_COLOR,r.textAlign=pe.TEXT_ALIGN,r.textBaseline=pe.TEXT_BASELINE,r.fillText(e,t.width/2,t.height/2));const n=new M.CanvasTexture(t);return n.needsUpdate=!0,n}}class Yn{static createWireframe([e,t,r]){const n=new M.BoxGeometry(e,t,r),o=new M.EdgesGeometry(n),i=new M.LineBasicMaterial({color:pe.LINE_COLOR}),a=new M.LineSegments(o,i);return a.name="Wireframe",a}static createEdgeBox(e,t,r){const n=pe.CUBE_SIZE-pe.EDGE_SECTION_SIZE,o={x:pe.EDGE_SECTION_SIZE,y:pe.EDGE_SECTION_SIZE,z:pe.EDGE_SECTION_SIZE};o[t]=n;const i=new M.BoxGeometry(o.x,o.y,o.z),a=new M.MeshStandardMaterial({color:pe.EDGE_COLOR}),c=new M.Mesh(i,a);return c.position.copy(e),c.name=`Edge Box ${r}`,c}static createCornerCube(e,t){const r=new M.BoxGeometry(pe.EDGE_SECTION_SIZE,pe.EDGE_SECTION_SIZE,pe.EDGE_SECTION_SIZE),n=new M.MeshStandardMaterial({color:pe.CORNER_COLOR}),o=new M.Mesh(r,n);return o.position.copy(e),o.name=`Corner Cube ${t}`,o}static createFace(e,t,r){const n=new M.Group,o=new M.BoxGeometry(pe.CUBE_SIZE-pe.EDGE_SECTION_SIZE,pe.CUBE_SIZE-pe.EDGE_SECTION_SIZE,pe.FACE_THICKNESS),i=new M.MeshStandardMaterial({color:pe.FACE_COLOR}),a=new M.Mesh(o,i);a.name=`Face Box ${r}`,n.add(a);const c=new M.PlaneGeometry(pe.CUBE_SIZE-pe.EDGE_SECTION_SIZE,pe.CUBE_SIZE-pe.EDGE_SECTION_SIZE),h=new M.MeshStandardMaterial({map:Lh.createTextTexture(r),transparent:!0,depthWrite:!1}),d=new M.Mesh(c,h);return d.position.set(0,0,pe.FACE_THICKNESS/2+.01),n.add(d),n.position.copy(e),n.rotation.copy(t),n}}const Nh=(s,e)=>{const t=document.createElement("canvas");t.width=64,t.height=64;const r=t.getContext("2d");r.fillStyle="rgba(0, 0, 0, 0)",r.fillRect(0,0,t.width,t.height),r.font="Bold 48px Arial",r.fillStyle=`#${e.toString(16).padStart(6,"0")}`,r.textAlign="center",r.textBaseline="middle",r.fillText(s,t.width/2,t.height/2);const n=new M.CanvasTexture(t),o=new M.SpriteMaterial({map:n}),i=new M.Sprite(o);return i.scale.set(.5,.5,.5),i};class kh{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 Wt.BACK:return new M.Euler(0,Math.PI,0);case Wt.RIGHT:return new M.Euler(0,-Math.PI/2,0);case Wt.LEFT:return new M.Euler(0,Math.PI/2,0);case Wt.TOP:return new M.Euler(Math.PI/2,0,0);case Wt.BOTTOM:return new M.Euler(-Math.PI/2,0,0);case Wt.FRONT:default:return new M.Euler(0,0,0)}}createWireframe(){const e=pe.CUBE_SIZE+pe.EDGE_SECTION_SIZE,t=Yn.createWireframe([e,e,e]);return t.userData.gizmoCube=this,t}createEdgeBox(e,t,r){const n=Yn.createEdgeBox(e,t,r);return n.userData.gizmoCube=this,n}createCornerCube(e,t){const r=Yn.createCornerCube(e,t);return r.userData.gizmoCube=this,r}createFace(e,t,r){const n=Yn.createFace(e,t,r),o=n.getObjectByName(`Face Box ${r}`);return o.userData.gizmoCube=this,n}createEdges(e){const t=pe.CUBE_SIZE/2;[{axis:"x",pos:new M.Vector3(0,t,-t)},{axis:"x",pos:new M.Vector3(0,t,t)},{axis:"x",pos:new M.Vector3(0,-t,-t)},{axis:"x",pos:new M.Vector3(0,-t,t)},{axis:"y",pos:new M.Vector3(t,0,-t)},{axis:"y",pos:new M.Vector3(t,0,t)},{axis:"y",pos:new M.Vector3(-t,0,-t)},{axis:"y",pos:new M.Vector3(-t,0,t)},{axis:"z",pos:new M.Vector3(t,t,0)},{axis:"z",pos:new M.Vector3(t,-t,0)},{axis:"z",pos:new M.Vector3(-t,t,0)},{axis:"z",pos:new M.Vector3(-t,-t,0)}].forEach(({axis:r,pos:n},o)=>{const i=this.createEdgeBox(n,r,o+1);e.add(i)})}createCorners(e){const t=pe.CUBE_SIZE/2;[new M.Vector3(-t,-t,-t),new M.Vector3(-t,-t,t),new M.Vector3(-t,t,-t),new M.Vector3(-t,t,t),new M.Vector3(t,-t,-t),new M.Vector3(t,-t,t),new M.Vector3(t,t,-t),new M.Vector3(t,t,t)].forEach((r,n)=>{const o=this.createCornerCube(r,n+1);e.add(o)})}createFaces(e){const t=pe.CUBE_SIZE/2;[{pos:new M.Vector3(0,0,t),rotation:new M.Euler(0,0,0),label:"FRONT"},{pos:new M.Vector3(0,0,-t),rotation:new M.Euler(0,Math.PI,0),label:"BACK"},{pos:new M.Vector3(t,0,0),rotation:new M.Euler(0,Math.PI/2,0),label:"RIGHT"},{pos:new M.Vector3(-t,0,0),rotation:new M.Euler(0,-Math.PI/2,0),label:"LEFT"},{pos:new M.Vector3(0,t,0),rotation:new M.Euler(-Math.PI/2,0,0),label:"TOP"},{pos:new M.Vector3(0,-t,0),rotation:new M.Euler(Math.PI/2,0,0),label:"BOTTOM"}].forEach(({pos:r,rotation:n,label:o})=>{const i=this.createFace(r,n,o);e.add(i)})}createAxis(e){const{color:t,direction:r,length:n,origin:o,lineWidth:i,label:a}=e,c=new M.Group,h=i/2,d=new M.CylinderGeometry(h,h,n,32),u=new M.MeshBasicMaterial({color:t}),l=new M.Mesh(d,u);if(l.position.copy(o).add(r.clone().multiplyScalar(n/2)),!r.equals(new M.Vector3(0,1,0))){const b=new M.Vector3(0,1,0).cross(r).normalize(),S=Math.acos(new M.Vector3(0,1,0).dot(r));l.setRotationFromAxisAngle(b,S)}c.add(l);const v=Nh(a,t);return v.position.copy(o).add(r.clone().multiplyScalar(n+.1)),c.add(v),c}createCoordinateAxes(){const e=new M.Group,t=pe.CUBE_SIZE,r=pe.EDGE_SECTION_SIZE,n=-1.075,o=a=>{const c=new M.Vector3(1,1,1);return new M.Vector3(a,a,a).add(c.clone().normalize().negate().multiplyScalar(.04))},i=t+1.25*r;return[{color:16711680,direction:new M.Vector3(1,0,0),length:i,origin:o(n),lineWidth:.04,label:"X"},{color:65280,direction:new M.Vector3(0,1,0),length:i,origin:o(n),lineWidth:.04,label:"Y"},{color:255,direction:new M.Vector3(0,0,1),length:i,origin:o(n),lineWidth:.04,label:"Z"}].forEach(a=>{const c=this.createAxis(a);e.add(c)}),e}create(){const e=new M.Group;e.name="Gizmo Group";const t=this.createWireframe();e.add(t),this.createEdges(e),this.createCorners(e),this.createFaces(e);const r=this.createCoordinateAxes();e.add(r);const n=this.getInitialRotation();return e.setRotationFromEuler(n),e}highlightObject(e){if(this.hoveredObject!==e)if(this.hoveredObject&&this.originalColor&&this.hoveredObject.material.color.set(this.originalColor),e&&e instanceof M.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 M.Vector3;e=this.hoveredObject.getWorldPosition(e).clone();const t=new M.Vector3(0,0,0),r=e.sub(t).normalize();this.hoveredObject.userData.vectorToCube=r}}}class Bh{constructor(e){this.onChangeMainControlsListener=()=>{},this.onChangeGizmoControlsListener=()=>{},this.animationId=0;const{gizmoParams:t,mainParams:r,syncFunctions:n,options:o}=e;this.gizmoDiv=t.gizmoDiv,this.gizmoScene=t.gizmoScene,this.gizmoRenderer=t.gizmoRenderer,this.gizmoCamera=t.gizmoCamera,this.mainCamera=r.mainCamera,this.mainControls=r.mainControls,this.renderGizmo=r.renderGizmo,this.syncFunctions=n,this.options=o,this.gizmoControls=new xh(this.gizmoCamera,this.gizmoRenderer.domElement),this.initializeRenderer(),this.initializeScene(),this.initializeControls(),this.startAnimationLoop()}initializeRenderer(){this.gizmoRenderer.setPixelRatio(window.devicePixelRatio),this.gizmoRenderer.setSize(this.gizmoDiv.clientWidth,this.gizmoDiv.clientHeight),this.gizmoDiv.appendChild(this.gizmoRenderer.domElement)}initializeScene(){var e;const t=new kh({initialFace:((e=this.options)==null?void 0:e.initialFace)??Wt.FRONT}).create();t&&this.gizmoScene.add(t),Oh(this.gizmoScene)}initializeControls(){this.onChangeMainControlsListener=()=>this.syncFunctions.syncGizmoCameraWithMain(this.gizmoCamera,this.mainCamera),this.mainControls.addEventListener("change",this.onChangeMainControlsListener),this.gizmoControls.enableZoom=!1,this.gizmoControls.enablePan=!1,this.gizmoControls.rotateSpeed=.5,this.gizmoControls.update(),this.onChangeGizmoControlsListener=()=>{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 zh=(s,e)=>{let t;return function(...r){t||(s.apply(this,r),t=!0,setTimeout(()=>t=!1,e))}};function So(s,e,t){if(!e)return;const r=e.domElement.getBoundingClientRect();t.x=(s.clientX-r.left)/r.width*2-1,t.y=-((s.clientY-r.top)/r.height)*2+1}function To(s,e,t,r){var n;if(!e||!t)return null;r.setFromCamera(s,e);const o=r.intersectObjects(t.children,!0),i=["Wireframe",""];return((n=o.find(a=>!i.includes(a.object.name)))==null?void 0:n.object)||null}function Eh(s,e){const t=s==null?void 0:s.userData.gizmoCube;if(s&&t){t.handleClick();const r=t.vectorToCube;r&&e(r)}}const Uh=25,Gh=200;function Vh({gizmoRenderer:s,gizmoScene:e,gizmoCamera:t,alignCameraWithVector:r,gizmoControlRef:n}){const o=ce.useRef(null),i=ce.useRef(null),a=ce.useRef(new M.Raycaster).current,c=ce.useRef(new M.Vector2).current,h=ce.useCallback(zh(l=>{if(!n.current||!s)return;So(l,s,c);const v=To(c,t,e,a);v!=null&&v.userData.gizmoCube?v.userData.gizmoCube.highlightObject(v):e.traverse(b=>{b.userData.gizmoCube&&b.userData.gizmoCube.highlightObject(null)})},1e3/Uh),[n,s,t,e,a,c]),d=ce.useCallback(l=>{o.current=Date.now(),i.current={x:l.clientX,y:l.clientY}},[]),u=ce.useCallback(l=>{if((o.current?Date.now()-o.current:0)<Gh){So(l,s,c);const v=To(c,t,e,a);Eh(v,r)}o.current=null,i.current=null},[r,s,t,e,a,c]);return{onMouseDown:d,onMouseMove:h,onMouseUp:u}}const jh=({camera:s,controls:e,className:t,render:r,options:n})=>{const o=ce.useRef(null),i=ce.useRef(new M.Scene).current,[a]=ce.useState(()=>yh()),c=30,h=1,d=.1,u=10,l=new M.PerspectiveCamera(c,h,d,u),v=ce.useRef(l).current,b=ce.useRef(null),S=ce.useCallback(()=>{a&&(r(),a.render(i,v))},[r,a,i,v]),g=ce.useCallback(A=>{if(!s||!e)return;const P=s.position.length(),D=A.clone().multiplyScalar(P);mh(s,e,s.position.clone(),D,400,S),s.lookAt(new M.Vector3(0,0,0)),s.up.set(0,1,0),e.target.set(0,0,0)},[s,e,S]),{onMouseDown:x,onMouseMove:w,onMouseUp:T}=Vh({gizmoRenderer:a,gizmoScene:i,gizmoCamera:v,alignCameraWithVector:g,gizmoControlRef:b});return ce.useEffect(()=>{const A=o.current;if(!A||!s||!e||!a)return;b.current&&b.current.dispose();const P={gizmoDiv:A,gizmoScene:i,gizmoRenderer:a,gizmoCamera:v},D={mainCamera:s,mainControls:e,renderGizmo:S},R={syncGizmoCameraWithMain:bo,syncMainCameraWithGizmo:gh};return b.current=new Bh({gizmoParams:P,mainParams:D,syncFunctions:R,options:n}),A.addEventListener("mousedown",x),A.addEventListener("mousemove",w),A.addEventListener("mouseup",T),()=>{b.current&&(b.current.dispose(),b.current=null),A.removeEventListener("mousedown",x),A.removeEventListener("mousemove",w),A.removeEventListener("mouseup",T)}},[s,e,S,w,x,T]),ce.useEffect(()=>{s&&(bo(v,s),S())},[s,S]),ph.jsx("div",{className:t?`${t}`:"gizmo-default",ref:o})},Wh=({camera:s,controls:e,render:t,placement:r="top-right",size:n=128})=>{const o=ce.useRef(null);if(ce.useEffect(()=>{if(!o.current)return;const a=o.current;a.style.position="absolute",a.style.width=`${n}px`,a.style.height=`${n}px`,a.style.zIndex="1000",a.style.top="auto",a.style.bottom="auto",a.style.left="auto",a.style.right="auto";const c="10px";switch(r){case"top-left":a.style.top=c,a.style.left=c;break;case"top-right":a.style.top=c,a.style.right=c;break;case"bottom-left":a.style.bottom=c,a.style.left=c;break;case"bottom-right":a.style.bottom=c,a.style.right=c;break}},[r,n]),!s||!e)return null;const i=e;return Ze.jsx("div",{ref:o,className:"viewer-gizmo-container",children:Ze.jsx(jh,{camera:s,controls:i,render:t})})};class Yh extends ce.Component{constructor(e){super(e),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:Ze.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:Ze.jsxs("div",{children:[Ze.jsx("h3",{children:"Error Loading 3D Viewer"}),Ze.jsx("p",{children:((e=this.state.error)==null?void 0:e.message)||"An unexpected error occurred"})]})}):this.props.children}}class Ao{static toThreeObject(e){if("getThreeObject"in e&&typeof e.getThreeObject=="function")return e.getThreeObject();if(e instanceof M.Object3D)return e;const t=new M.Object3D;return t.position.set(e.position.x,e.position.y,e.position.z),t.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z),t.scale.set(e.scale.x,e.scale.y,e.scale.z),t}static toThreeCamera(e){return"getThreeCamera"in e&&typeof e.getThreeCamera=="function"?e.getThreeCamera():e instanceof M.Camera?e:new M.PerspectiveCamera}static toThreeControls(e){return"getThreeControls"in e&&typeof e.getThreeControls=="function"?e.getThreeControls():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)}}static convertInitialized(e,t){return{viewer:t}}static convertDisposed(e,t){return{viewer:t}}}const Mo=ce.forwardRef(({object:s,options:e={}},t)=>{var A,P;const r=ce.useRef(null),{viewer:n,isInitialized:o}=ah(r,e),i=ce.useRef(new dn),a=ce.useRef(void 0),c=ce.useMemo(()=>{if(typeof s=="string")return s;if(s)return`object-${s.uuid||"no-uuid"}`},[s]);ce.useMemo(()=>{a.current=s},[c,s]),ce.useEffect(()=>{if(!n||!o||!a.current)return;const D=typeof a.current=="string"?a.current:new We(a.current);n.loadModel(D).then(R=>{R.ok||console.error("Failed to load model:",R.error)})},[n,o,c]);const h=ce.useMemo(()=>({"model:loaded":D=>i.current.emit("model:loaded",Ao.convertModelLoaded(D)),"model:error":D=>i.current.emit("model:error",D),"render:complete":D=>i.current.emit("render:complete",D),"controls:change":D=>i.current.emit("controls:change",Ao.convertControlsChange(D)),error:D=>i.current.emit("error",D)}),[]);ch(n,h);const d=ce.useCallback(D=>{if(D&&typeof D=="object"){const R=D;if(typeof R.getThreeScene=="function")return R.getThreeScene()}return null},[]),u=ce.useCallback(D=>{if(D&&typeof D=="object"){const R=D;if(typeof R.getThreeCamera=="function")return R.getThreeCamera()}return null},[]),l=ce.useCallback(D=>{if(D&&typeof D=="object"){const R=D;if(typeof R.getThreeRenderer=="function")return R.getThreeRenderer()}return null},[]),v=ce.useCallback(D=>{if(D&&typeof D=="object"){const R=D;if(typeof R.getThreeControls=="function")return R.getThreeControls()}return null},[]),b=n?u(n.camera):null,S=n?v(n.controls):null,g=n?l(n.renderer):null,x=ce.useCallback(()=>{if(g&&n){const D=n;D.renderLoopManager&&typeof D.renderLoopManager.requestRender=="function"&&D.renderLoopManager.requestRender()}},[n,g]),w=((A=e.helpers)==null?void 0:A.gizmo)!==void 0&&e.helpers.gizmo!==!1,T=typeof((P=e.helpers)==null?void 0:P.gizmo)=="object"?e.helpers.gizmo:{};return ce.useImperativeHandle(t,()=>({scene:n?d(n.scene):null,camera:b,renderer:g,controls:S,events:i.current}),[n,b,g,S,d]),Ze.jsx(Yh,{children:Ze.jsx(lh,{viewer:n,canvasRef:r,children:Ze.jsxs("div",{style:{position:"relative",width:"100%",height:"100%"},children:[Ze.jsx(hh,{}),w&&o&&b&&S&&Ze.jsx(Wh,{camera:b,controls:S,render:x,placement:T.placement,size:T.size})]})})})});Mo.displayName="SimpleViewer";const Io=ce.forwardRef((s,e)=>Ze.jsx(Mo,{ref:e,...s}));Io.displayName="SimpleViewer",wt.SimpleViewer=Io,wt.TypedEventEmitter=dn,wt.defaultOptions=mo,Object.defineProperty(wt,Symbol.toStringTag,{value:"Module"})});
|
|
4044
|
+
<%s key={someKey} {...props} />`,Z,F,Y,F),lr[F+Z]=!0}}return m===r?an(_):on(_),_}}function cn(m,C,N){return ur(m,C,N,!0)}function ln(m,C,N){return ur(m,C,N,!1)}var Nr=ln,un=cn;jn.Fragment=r,jn.jsx=Nr,jn.jsxs=un}()),jn}process.env.NODE_ENV==="production"?Ui.exports=dh():Ui.exports=ph();var mh=Ui.exports;const gh=(s,e,t,r,n,o)=>{const i=performance.now(),a=()=>{const c=performance.now()-i,h=Math.min(c/n,1);s.position.lerpVectors(t,r,h),e==null||e.update(),o(),h<1&&requestAnimationFrame(a)};requestAnimationFrame(a)},xo=(s,e)=>{s.quaternion.copy(e.quaternion);const t=new M.Vector3(0,0,-1).applyQuaternion(s.quaternion).normalize();s.position.copy(t.multiplyScalar(-8)),s.lookAt(new M.Vector3(0,0,0)),s.updateMatrixWorld(!0)},vh=(s,e,t)=>{const r=t.target.clone(),n=s.position.clone().sub(r).length(),o=new M.Vector3(0,0,-1).applyQuaternion(e.quaternion).normalize().multiplyScalar(-n);s.position.copy(r).add(o),s.quaternion.copy(e.quaternion),s.updateMatrixWorld(!0),t.update()},yh=()=>{try{const s=document.createElement("canvas");return!!(window.WebGLRenderingContext&&(s.getContext("webgl")||s.getContext("experimental-webgl")))}catch{return!1}},xh=()=>yh()?new M.WebGLRenderer({alpha:!0,antialias:!1}):(console.error("WebGL is not supported in this environment."),null),bo={type:"change"},Gi={type:"start"},wo={type:"end"},Wn=new f.Ray,_o=new f.Plane,bh=Math.cos(70*f.MathUtils.DEG2RAD),Ne=new f.Vector3,Qe=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},Vi=1e-6;class wh extends f.Controls{constructor(e,t=null){super(e,t),this.state=we.NONE,this.enabled=!0,this.target=new f.Vector3,this.cursor=new f.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.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:f.MOUSE.ROTATE,MIDDLE:f.MOUSE.DOLLY,RIGHT:f.MOUSE.PAN},this.touches={ONE:f.TOUCH.ROTATE,TWO:f.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 f.Vector3,this._lastQuaternion=new f.Quaternion,this._lastTargetPosition=new f.Vector3,this._quat=new f.Quaternion().setFromUnitVectors(e.up,new f.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new f.Spherical,this._sphericalDelta=new f.Spherical,this._scale=1,this._panOffset=new f.Vector3,this._rotateStart=new f.Vector2,this._rotateEnd=new f.Vector2,this._rotateDelta=new f.Vector2,this._panStart=new f.Vector2,this._panEnd=new f.Vector2,this._panDelta=new f.Vector2,this._dollyStart=new f.Vector2,this._dollyEnd=new f.Vector2,this._dollyDelta=new f.Vector2,this._dollyDirection=new f.Vector3,this._mouse=new f.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=Sh.bind(this),this._onPointerDown=_h.bind(this),this._onPointerUp=Th.bind(this),this._onContextMenu=Rh.bind(this),this._onMouseWheel=Ih.bind(this),this._onKeyDown=Ch.bind(this),this._onTouchStart=Ph.bind(this),this._onTouchMove=Dh.bind(this),this._onMouseDown=Ah.bind(this),this._onMouseMove=Mh.bind(this),this._interceptControlDown=Fh.bind(this),this._interceptControlUp=Oh.bind(this),this.domElement!==null&&this.connect(),this.update()}connect(){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(bo),this.update(),this.state=we.NONE}update(e=null){const t=this.object.position;Ne.copy(t).sub(this.target),Ne.applyQuaternion(this._quat),this._spherical.setFromVector3(Ne),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 r=this.minAzimuthAngle,n=this.maxAzimuthAngle;isFinite(r)&&isFinite(n)&&(r<-Math.PI?r+=Qe:r>Math.PI&&(r-=Qe),n<-Math.PI?n+=Qe:n>Math.PI&&(n-=Qe),r<=n?this._spherical.theta=Math.max(r,Math.min(n,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(r+n)/2?Math.max(r,this._spherical.theta):Math.min(n,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let o=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const i=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),o=i!=this._spherical.radius}if(Ne.setFromSpherical(this._spherical),Ne.applyQuaternion(this._quatInverse),t.copy(this.target).add(Ne),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 i=null;if(this.object.isPerspectiveCamera){const a=Ne.length();i=this._clampDistance(a*this._scale);const c=a-i;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),o=!!c}else if(this.object.isOrthographicCamera){const a=new f.Vector3(this._mouse.x,this._mouse.y,0);a.unproject(this.object);const c=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),o=c!==this.object.zoom;const h=new f.Vector3(this._mouse.x,this._mouse.y,0);h.unproject(this.object),this.object.position.sub(h).add(a),this.object.updateMatrixWorld(),i=Ne.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;i!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(i).add(this.object.position):(Wn.origin.copy(this.object.position),Wn.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Wn.direction))<bh?this.object.lookAt(this.target):(_o.setFromNormalAndCoplanarPoint(this.object.up,this.target),Wn.intersectPlane(_o,this.target))))}else if(this.object.isOrthographicCamera){const i=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),i!==this.object.zoom&&(this.object.updateProjectionMatrix(),o=!0)}return this._scale=1,this._performCursorZoom=!1,o||this._lastPosition.distanceToSquared(this.object.position)>Vi||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Vi||this._lastTargetPosition.distanceToSquared(this.target)>Vi?(this.dispatchEvent(bo),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){Ne.setFromMatrixColumn(t,0),Ne.multiplyScalar(-e),this._panOffset.add(Ne)}_panUp(e,t){this.screenSpacePanning===!0?Ne.setFromMatrixColumn(t,1):(Ne.setFromMatrixColumn(t,0),Ne.crossVectors(this.object.up,Ne)),Ne.multiplyScalar(e),this._panOffset.add(Ne)}_pan(e,t){const r=this.domElement;if(this.object.isPerspectiveCamera){const n=this.object.position;Ne.copy(n).sub(this.target);let o=Ne.length();o*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*o/r.clientHeight,this.object.matrix),this._panUp(2*t*o/r.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/r.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/r.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 r=this.domElement.getBoundingClientRect(),n=e-r.left,o=t-r.top,i=r.width,a=r.height;this._mouse.x=n/i*2-1,this._mouse.y=-(o/a)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Qe*this._rotateDelta.x/t.clientHeight),this._rotateUp(Qe*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this._rotateUp(Qe*this.rotateSpeed/this.domElement.clientHeight):this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this._rotateUp(-Qe*this.rotateSpeed/this.domElement.clientHeight):this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this._rotateLeft(Qe*this.rotateSpeed/this.domElement.clientHeight):this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this._rotateLeft(-Qe*this.rotateSpeed/this.domElement.clientHeight):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),r=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);this._rotateStart.set(r,n)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),r=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);this._panStart.set(r,n)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),r=e.pageX-t.x,n=e.pageY-t.y,o=Math.sqrt(r*r+n*n);this._dollyStart.set(0,o)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const r=this._getSecondPointerPosition(e),n=.5*(e.pageX+r.x),o=.5*(e.pageY+r.y);this._rotateEnd.set(n,o)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Qe*this._rotateDelta.x/t.clientHeight),this._rotateUp(Qe*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),r=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);this._panEnd.set(r,n)}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),r=e.pageX-t.x,n=e.pageY-t.y,o=Math.sqrt(r*r+n*n);this._dollyEnd.set(0,o),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const i=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(i,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 f.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,r={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:r.deltaY*=16;break;case 2:r.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(r.deltaY*=10),r}}function _h(s){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(s.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(s)&&(this._addPointer(s),s.pointerType==="touch"?this._onTouchStart(s):this._onMouseDown(s)))}function Sh(s){this.enabled!==!1&&(s.pointerType==="touch"?this._onTouchMove(s):this._onMouseMove(s))}function Th(s){switch(this._removePointer(s),this._pointers.length){case 0:this.domElement.releasePointerCapture(s.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(wo),this.state=we.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 Ah(s){let e;switch(s.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 f.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(s),this.state=we.DOLLY;break;case f.MOUSE.ROTATE:if(s.ctrlKey||s.metaKey||s.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(s),this.state=we.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(s),this.state=we.ROTATE}break;case f.MOUSE.PAN:if(s.ctrlKey||s.metaKey||s.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(s),this.state=we.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(s),this.state=we.PAN}break;default:this.state=we.NONE}this.state!==we.NONE&&this.dispatchEvent(Gi)}function Mh(s){switch(this.state){case we.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(s);break;case we.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(s);break;case we.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(s);break}}function Ih(s){this.enabled===!1||this.enableZoom===!1||this.state!==we.NONE||(s.preventDefault(),this.dispatchEvent(Gi),this._handleMouseWheel(this._customWheelEvent(s)),this.dispatchEvent(wo))}function Ch(s){this.enabled===!1||this.enablePan===!1||this._handleKeyDown(s)}function Ph(s){switch(this._trackPointer(s),this._pointers.length){case 1:switch(this.touches.ONE){case f.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(s),this.state=we.TOUCH_ROTATE;break;case f.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(s),this.state=we.TOUCH_PAN;break;default:this.state=we.NONE}break;case 2:switch(this.touches.TWO){case f.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(s),this.state=we.TOUCH_DOLLY_PAN;break;case f.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(s),this.state=we.TOUCH_DOLLY_ROTATE;break;default:this.state=we.NONE}break;default:this.state=we.NONE}this.state!==we.NONE&&this.dispatchEvent(Gi)}function Dh(s){switch(this._trackPointer(s),this.state){case we.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(s),this.update();break;case we.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(s),this.update();break;case we.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(s),this.update();break;case we.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(s),this.update();break;default:this.state=we.NONE}}function Rh(s){this.enabled!==!1&&s.preventDefault()}function Fh(s){s.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function Oh(s){s.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}const Lh=s=>{const e=new M.AmbientLight(16777215,1);s.add(e);const t=new M.DirectionalLight(16777215,1);t.position.set(5,10,5),s.add(t);const r=new M.DirectionalLight(16777215,1);r.position.set(-5,-10,5),s.add(r);const n=new M.PointLight(16777215,1,100);n.position.set(0,0,5),s.add(n),t.castShadow=!1,r.castShadow=!1,n.castShadow=!1},pe={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 Wt=(s=>(s.FRONT="FRONT",s.BACK="BACK",s.RIGHT="RIGHT",s.LEFT="LEFT",s.TOP="TOP",s.BOTTOM="BOTTOM",s))(Wt||{});new M.Vector3(0,1,0);class Nh{static createTextTexture(e){const t=document.createElement("canvas"),r=t.getContext("2d");t.width=pe.CANVAS_SIZE,t.height=pe.CANVAS_SIZE,r&&(r.clearRect(0,0,t.width,t.height),r.font=`${pe.FONT_SIZE} Arial`,r.fillStyle=pe.TEXT_COLOR,r.textAlign=pe.TEXT_ALIGN,r.textBaseline=pe.TEXT_BASELINE,r.fillText(e,t.width/2,t.height/2));const n=new M.CanvasTexture(t);return n.needsUpdate=!0,n}}class Yn{static createWireframe([e,t,r]){const n=new M.BoxGeometry(e,t,r),o=new M.EdgesGeometry(n),i=new M.LineBasicMaterial({color:pe.LINE_COLOR}),a=new M.LineSegments(o,i);return a.name="Wireframe",a}static createEdgeBox(e,t,r){const n=pe.CUBE_SIZE-pe.EDGE_SECTION_SIZE,o={x:pe.EDGE_SECTION_SIZE,y:pe.EDGE_SECTION_SIZE,z:pe.EDGE_SECTION_SIZE};o[t]=n;const i=new M.BoxGeometry(o.x,o.y,o.z),a=new M.MeshStandardMaterial({color:pe.EDGE_COLOR}),c=new M.Mesh(i,a);return c.position.copy(e),c.name=`Edge Box ${r}`,c}static createCornerCube(e,t){const r=new M.BoxGeometry(pe.EDGE_SECTION_SIZE,pe.EDGE_SECTION_SIZE,pe.EDGE_SECTION_SIZE),n=new M.MeshStandardMaterial({color:pe.CORNER_COLOR}),o=new M.Mesh(r,n);return o.position.copy(e),o.name=`Corner Cube ${t}`,o}static createFace(e,t,r){const n=new M.Group,o=new M.BoxGeometry(pe.CUBE_SIZE-pe.EDGE_SECTION_SIZE,pe.CUBE_SIZE-pe.EDGE_SECTION_SIZE,pe.FACE_THICKNESS),i=new M.MeshStandardMaterial({color:pe.FACE_COLOR}),a=new M.Mesh(o,i);a.name=`Face Box ${r}`,n.add(a);const c=new M.PlaneGeometry(pe.CUBE_SIZE-pe.EDGE_SECTION_SIZE,pe.CUBE_SIZE-pe.EDGE_SECTION_SIZE),h=new M.MeshStandardMaterial({map:Nh.createTextTexture(r),transparent:!0,depthWrite:!1}),d=new M.Mesh(c,h);return d.position.set(0,0,pe.FACE_THICKNESS/2+.01),n.add(d),n.position.copy(e),n.rotation.copy(t),n}}const kh=(s,e)=>{const t=document.createElement("canvas");t.width=64,t.height=64;const r=t.getContext("2d");r.fillStyle="rgba(0, 0, 0, 0)",r.fillRect(0,0,t.width,t.height),r.font="Bold 48px Arial",r.fillStyle=`#${e.toString(16).padStart(6,"0")}`,r.textAlign="center",r.textBaseline="middle",r.fillText(s,t.width/2,t.height/2);const n=new M.CanvasTexture(t),o=new M.SpriteMaterial({map:n}),i=new M.Sprite(o);return i.scale.set(.5,.5,.5),i};class Bh{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 Wt.BACK:return new M.Euler(0,Math.PI,0);case Wt.RIGHT:return new M.Euler(0,-Math.PI/2,0);case Wt.LEFT:return new M.Euler(0,Math.PI/2,0);case Wt.TOP:return new M.Euler(Math.PI/2,0,0);case Wt.BOTTOM:return new M.Euler(-Math.PI/2,0,0);case Wt.FRONT:default:return new M.Euler(0,0,0)}}createWireframe(){const e=pe.CUBE_SIZE+pe.EDGE_SECTION_SIZE,t=Yn.createWireframe([e,e,e]);return t.userData.gizmoCube=this,t}createEdgeBox(e,t,r){const n=Yn.createEdgeBox(e,t,r);return n.userData.gizmoCube=this,n}createCornerCube(e,t){const r=Yn.createCornerCube(e,t);return r.userData.gizmoCube=this,r}createFace(e,t,r){const n=Yn.createFace(e,t,r),o=n.getObjectByName(`Face Box ${r}`);return o.userData.gizmoCube=this,n}createEdges(e){const t=pe.CUBE_SIZE/2;[{axis:"x",pos:new M.Vector3(0,t,-t)},{axis:"x",pos:new M.Vector3(0,t,t)},{axis:"x",pos:new M.Vector3(0,-t,-t)},{axis:"x",pos:new M.Vector3(0,-t,t)},{axis:"y",pos:new M.Vector3(t,0,-t)},{axis:"y",pos:new M.Vector3(t,0,t)},{axis:"y",pos:new M.Vector3(-t,0,-t)},{axis:"y",pos:new M.Vector3(-t,0,t)},{axis:"z",pos:new M.Vector3(t,t,0)},{axis:"z",pos:new M.Vector3(t,-t,0)},{axis:"z",pos:new M.Vector3(-t,t,0)},{axis:"z",pos:new M.Vector3(-t,-t,0)}].forEach(({axis:r,pos:n},o)=>{const i=this.createEdgeBox(n,r,o+1);e.add(i)})}createCorners(e){const t=pe.CUBE_SIZE/2;[new M.Vector3(-t,-t,-t),new M.Vector3(-t,-t,t),new M.Vector3(-t,t,-t),new M.Vector3(-t,t,t),new M.Vector3(t,-t,-t),new M.Vector3(t,-t,t),new M.Vector3(t,t,-t),new M.Vector3(t,t,t)].forEach((r,n)=>{const o=this.createCornerCube(r,n+1);e.add(o)})}createFaces(e){const t=pe.CUBE_SIZE/2;[{pos:new M.Vector3(0,0,t),rotation:new M.Euler(0,0,0),label:"FRONT"},{pos:new M.Vector3(0,0,-t),rotation:new M.Euler(0,Math.PI,0),label:"BACK"},{pos:new M.Vector3(t,0,0),rotation:new M.Euler(0,Math.PI/2,0),label:"RIGHT"},{pos:new M.Vector3(-t,0,0),rotation:new M.Euler(0,-Math.PI/2,0),label:"LEFT"},{pos:new M.Vector3(0,t,0),rotation:new M.Euler(-Math.PI/2,0,0),label:"TOP"},{pos:new M.Vector3(0,-t,0),rotation:new M.Euler(Math.PI/2,0,0),label:"BOTTOM"}].forEach(({pos:r,rotation:n,label:o})=>{const i=this.createFace(r,n,o);e.add(i)})}createAxis(e){const{color:t,direction:r,length:n,origin:o,lineWidth:i,label:a}=e,c=new M.Group,h=i/2,d=new M.CylinderGeometry(h,h,n,32),u=new M.MeshBasicMaterial({color:t}),l=new M.Mesh(d,u);if(l.position.copy(o).add(r.clone().multiplyScalar(n/2)),!r.equals(new M.Vector3(0,1,0))){const x=new M.Vector3(0,1,0).cross(r).normalize(),S=Math.acos(new M.Vector3(0,1,0).dot(r));l.setRotationFromAxisAngle(x,S)}c.add(l);const v=kh(a,t);return v.position.copy(o).add(r.clone().multiplyScalar(n+.1)),c.add(v),c}createCoordinateAxes(){const e=new M.Group,t=pe.CUBE_SIZE,r=pe.EDGE_SECTION_SIZE,n=-1.075,o=a=>{const c=new M.Vector3(1,1,1);return new M.Vector3(a,a,a).add(c.clone().normalize().negate().multiplyScalar(.04))},i=t+1.25*r;return[{color:16711680,direction:new M.Vector3(1,0,0),length:i,origin:o(n),lineWidth:.04,label:"X"},{color:65280,direction:new M.Vector3(0,1,0),length:i,origin:o(n),lineWidth:.04,label:"Y"},{color:255,direction:new M.Vector3(0,0,1),length:i,origin:o(n),lineWidth:.04,label:"Z"}].forEach(a=>{const c=this.createAxis(a);e.add(c)}),e}create(){const e=new M.Group;e.name="Gizmo Group";const t=this.createWireframe();e.add(t),this.createEdges(e),this.createCorners(e),this.createFaces(e);const r=this.createCoordinateAxes();e.add(r);const n=this.getInitialRotation();return e.setRotationFromEuler(n),e}highlightObject(e){if(this.hoveredObject!==e)if(this.hoveredObject&&this.originalColor&&this.hoveredObject.material.color.set(this.originalColor),e&&e instanceof M.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 M.Vector3;e=this.hoveredObject.getWorldPosition(e).clone();const t=new M.Vector3(0,0,0),r=e.sub(t).normalize();this.hoveredObject.userData.vectorToCube=r}}}class zh{constructor(e){this.onChangeMainControlsListener=()=>{},this.onChangeGizmoControlsListener=()=>{},this.animationId=0;const{gizmoParams:t,mainParams:r,syncFunctions:n,options:o}=e;this.gizmoDiv=t.gizmoDiv,this.gizmoScene=t.gizmoScene,this.gizmoRenderer=t.gizmoRenderer,this.gizmoCamera=t.gizmoCamera,this.mainCamera=r.mainCamera,this.mainControls=r.mainControls,this.renderGizmo=r.renderGizmo,this.syncFunctions=n,this.options=o,this.gizmoControls=new wh(this.gizmoCamera,this.gizmoRenderer.domElement),this.initializeRenderer(),this.initializeScene(),this.initializeControls(),this.startAnimationLoop()}initializeRenderer(){this.gizmoRenderer.setPixelRatio(window.devicePixelRatio),this.gizmoRenderer.setSize(this.gizmoDiv.clientWidth,this.gizmoDiv.clientHeight),this.gizmoDiv.appendChild(this.gizmoRenderer.domElement)}initializeScene(){var e;const t=new Bh({initialFace:((e=this.options)==null?void 0:e.initialFace)??Wt.FRONT}).create();t&&this.gizmoScene.add(t),Lh(this.gizmoScene)}initializeControls(){this.onChangeMainControlsListener=()=>this.syncFunctions.syncGizmoCameraWithMain(this.gizmoCamera,this.mainCamera),this.mainControls.addEventListener("change",this.onChangeMainControlsListener),this.gizmoControls.enableZoom=!1,this.gizmoControls.enablePan=!1,this.gizmoControls.rotateSpeed=.5,this.gizmoControls.update(),this.onChangeGizmoControlsListener=()=>{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 Eh=(s,e)=>{let t;return function(...r){t||(s.apply(this,r),t=!0,setTimeout(()=>t=!1,e))}};function So(s,e,t){if(!e)return;const r=e.domElement.getBoundingClientRect();t.x=(s.clientX-r.left)/r.width*2-1,t.y=-((s.clientY-r.top)/r.height)*2+1}function To(s,e,t,r){var n;if(!e||!t)return null;r.setFromCamera(s,e);const o=r.intersectObjects(t.children,!0),i=["Wireframe",""];return((n=o.find(a=>!i.includes(a.object.name)))==null?void 0:n.object)||null}function Uh(s,e){const t=s==null?void 0:s.userData.gizmoCube;if(s&&t){t.handleClick();const r=t.vectorToCube;r&&e(r)}}const Gh=25,Vh=200;function jh({gizmoRenderer:s,gizmoScene:e,gizmoCamera:t,alignCameraWithVector:r,gizmoControlRef:n}){const o=ce.useRef(null),i=ce.useRef(null),a=ce.useRef(new M.Raycaster).current,c=ce.useRef(new M.Vector2).current,h=ce.useCallback(Eh(l=>{if(!n.current||!s)return;So(l,s,c);const v=To(c,t,e,a);v!=null&&v.userData.gizmoCube?v.userData.gizmoCube.highlightObject(v):e.traverse(x=>{x.userData.gizmoCube&&x.userData.gizmoCube.highlightObject(null)})},1e3/Gh),[n,s,t,e,a,c]),d=ce.useCallback(l=>{o.current=Date.now(),i.current={x:l.clientX,y:l.clientY}},[]),u=ce.useCallback(l=>{if((o.current?Date.now()-o.current:0)<Vh){So(l,s,c);const v=To(c,t,e,a);Uh(v,r)}o.current=null,i.current=null},[r,s,t,e,a,c]);return{onMouseDown:d,onMouseMove:h,onMouseUp:u}}const Wh=({camera:s,controls:e,className:t,render:r,options:n})=>{const o=ce.useRef(null),i=ce.useRef(new M.Scene).current,[a]=ce.useState(()=>xh()),c=30,h=1,d=.1,u=10,l=new M.PerspectiveCamera(c,h,d,u),v=ce.useRef(l).current,x=ce.useRef(null),S=ce.useCallback(()=>{a&&(r(),a.render(i,v))},[r,a,i,v]),g=ce.useCallback(A=>{if(!s||!e)return;const P=s.position.length(),D=A.clone().multiplyScalar(P);gh(s,e,s.position.clone(),D,400,S),s.lookAt(new M.Vector3(0,0,0)),s.up.set(0,1,0),e.target.set(0,0,0)},[s,e,S]),{onMouseDown:b,onMouseMove:w,onMouseUp:T}=jh({gizmoRenderer:a,gizmoScene:i,gizmoCamera:v,alignCameraWithVector:g,gizmoControlRef:x});return ce.useEffect(()=>{const A=o.current;if(!A||!s||!e||!a)return;x.current&&x.current.dispose();const P={gizmoDiv:A,gizmoScene:i,gizmoRenderer:a,gizmoCamera:v},D={mainCamera:s,mainControls:e,renderGizmo:S},R={syncGizmoCameraWithMain:xo,syncMainCameraWithGizmo:vh};return x.current=new zh({gizmoParams:P,mainParams:D,syncFunctions:R,options:n}),A.addEventListener("mousedown",b),A.addEventListener("mousemove",w),A.addEventListener("mouseup",T),()=>{x.current&&(x.current.dispose(),x.current=null),A.removeEventListener("mousedown",b),A.removeEventListener("mousemove",w),A.removeEventListener("mouseup",T)}},[s,e,S,w,b,T]),ce.useEffect(()=>{s&&(xo(v,s),S())},[s,S]),mh.jsx("div",{className:t?`${t}`:"gizmo-default",ref:o})},Yh=({camera:s,controls:e,render:t,placement:r="top-right",size:n=128})=>{const o=ce.useRef(null);if(ce.useEffect(()=>{if(!o.current)return;const a=o.current;a.style.position="absolute",a.style.width=`${n}px`,a.style.height=`${n}px`,a.style.zIndex="1000",a.style.top="auto",a.style.bottom="auto",a.style.left="auto",a.style.right="auto";const c="10px";switch(r){case"top-left":a.style.top=c,a.style.left=c;break;case"top-right":a.style.top=c,a.style.right=c;break;case"bottom-left":a.style.bottom=c,a.style.left=c;break;case"bottom-right":a.style.bottom=c,a.style.right=c;break}},[r,n]),!s||!e)return null;const i=e;return Ze.jsx("div",{ref:o,className:"viewer-gizmo-container",children:Ze.jsx(Wh,{camera:s,controls:i,render:t})})};class qh extends ce.Component{constructor(e){super(e),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:Ze.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:Ze.jsxs("div",{children:[Ze.jsx("h3",{children:"Error Loading 3D Viewer"}),Ze.jsx("p",{children:((e=this.state.error)==null?void 0:e.message)||"An unexpected error occurred"})]})}):this.props.children}}class Ao{static toThreeObject(e){if("getThreeObject"in e&&typeof e.getThreeObject=="function")return e.getThreeObject();if(e instanceof M.Object3D)return e;const t=new M.Object3D;return t.position.set(e.position.x,e.position.y,e.position.z),t.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z),t.scale.set(e.scale.x,e.scale.y,e.scale.z),t}static toThreeCamera(e){return"getThreeCamera"in e&&typeof e.getThreeCamera=="function"?e.getThreeCamera():e instanceof M.Camera?e:new M.PerspectiveCamera}static toThreeControls(e){return"getThreeControls"in e&&typeof e.getThreeControls=="function"?e.getThreeControls():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)}}static convertInitialized(e,t){return{viewer:t}}static convertDisposed(e,t){return{viewer:t}}}const Mo=ce.forwardRef(({object:s,options:e={}},t)=>{var A,P;const r=ce.useRef(null),{viewer:n,isInitialized:o}=ch(r,e),i=ce.useRef(new dn),a=ce.useRef(void 0),c=ce.useMemo(()=>{if(typeof s=="string")return s;if(s)return`object-${s.uuid||"no-uuid"}`},[s]);ce.useMemo(()=>{a.current=s},[c,s]),ce.useEffect(()=>{if(!n||!o||!a.current)return;const D=typeof a.current=="string"?a.current:new We(a.current);n.loadModel(D).then(R=>{R.ok||console.error("Failed to load model:",R.error)})},[n,o,c]);const h=ce.useMemo(()=>({"model:loaded":D=>i.current.emit("model:loaded",Ao.convertModelLoaded(D)),"model:error":D=>i.current.emit("model:error",D),"render:complete":D=>i.current.emit("render:complete",D),"controls:change":D=>i.current.emit("controls:change",Ao.convertControlsChange(D)),error:D=>i.current.emit("error",D)}),[]);lh(n,h);const d=ce.useCallback(D=>{if(D&&typeof D=="object"){const R=D;if(typeof R.getThreeScene=="function")return R.getThreeScene()}return null},[]),u=ce.useCallback(D=>{if(D&&typeof D=="object"){const R=D;if(typeof R.getThreeCamera=="function")return R.getThreeCamera()}return null},[]),l=ce.useCallback(D=>{if(D&&typeof D=="object"){const R=D;if(typeof R.getThreeRenderer=="function")return R.getThreeRenderer()}return null},[]),v=ce.useCallback(D=>{if(D&&typeof D=="object"){const R=D;if(typeof R.getThreeControls=="function")return R.getThreeControls()}return null},[]),x=n?u(n.camera):null,S=n?v(n.controls):null,g=n?l(n.renderer):null,b=ce.useCallback(()=>{if(g&&n){const D=n;D.renderLoopManager&&typeof D.renderLoopManager.requestRender=="function"&&D.renderLoopManager.requestRender()}},[n,g]),w=((A=e.helpers)==null?void 0:A.gizmo)!==void 0&&e.helpers.gizmo!==!1,T=typeof((P=e.helpers)==null?void 0:P.gizmo)=="object"?e.helpers.gizmo:{};return ce.useImperativeHandle(t,()=>({scene:n?d(n.scene):null,camera:x,renderer:g,controls:S,events:i.current}),[n,x,g,S,d]),Ze.jsx(qh,{children:Ze.jsx(uh,{viewer:n,canvasRef:r,children:Ze.jsxs("div",{style:{position:"relative",width:"100%",height:"100%"},children:[Ze.jsx(fh,{}),w&&o&&x&&S&&Ze.jsx(Yh,{camera:x,controls:S,render:b,placement:T.placement,size:T.size})]})})})});Mo.displayName="SimpleViewer";const Io=ce.forwardRef((s,e)=>Ze.jsx(Mo,{ref:e,...s}));Io.displayName="SimpleViewer",wt.SimpleViewer=Io,wt.TypedEventEmitter=dn,wt.defaultOptions=mo,Object.defineProperty(wt,Symbol.toStringTag,{value:"Module"})});
|