threedviewer 2.1.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- (function(wt,ae){typeof exports=="object"&&typeof module<"u"?ae(exports,require("react"),require("three")):typeof define=="function"&&define.amd?define(["exports","react","three"],ae):(wt=typeof globalThis<"u"?globalThis:wt||self,ae(wt.SimpleViewer={},wt.React,wt.THREE))})(this,function(wt,ae,f){"use strict";function Ao(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const C=Ao(f);var hn={exports:{}},Nr={};/**
1
+ (function(wt,ae){typeof exports=="object"&&typeof module<"u"?ae(exports,require("react"),require("three")):typeof define=="function"&&define.amd?define(["exports","react","three"],ae):(wt=typeof globalThis<"u"?globalThis:wt||self,ae(wt.SimpleViewer={},wt.React,wt.THREE))})(this,function(wt,ae,f){"use strict";function Co(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const M=Co(f);var fn={exports:{}},kr={};/**
2
2
  * @license React
3
3
  * react-jsx-runtime.production.min.js
4
4
  *
@@ -6,7 +6,7 @@
6
6
  *
7
7
  * This source code is licensed under the MIT license found in the
8
8
  * LICENSE file in the root directory of this source tree.
9
- */var Vi;function Mo(){if(Vi)return Nr;Vi=1;var s=ae,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,u){var d,h={},l=null,v=null;u!==void 0&&(l=""+u),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)&&(h[d]=c[d]);if(a&&a.defaultProps)for(d in c=a.defaultProps,c)h[d]===void 0&&(h[d]=c[d]);return{$$typeof:e,type:a,key:l,ref:v,props:h,_owner:n.current}}return Nr.Fragment=t,Nr.jsx=i,Nr.jsxs=i,Nr}var kr={};/**
9
+ */var Wi;function Po(){if(Wi)return kr;Wi=1;var s=ae,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,u){var d,h={},l=null,v=null;u!==void 0&&(l=""+u),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)&&(h[d]=c[d]);if(a&&a.defaultProps)for(d in c=a.defaultProps,c)h[d]===void 0&&(h[d]=c[d]);return{$$typeof:e,type:a,key:l,ref:v,props:h,_owner:n.current}}return kr.Fragment=t,kr.jsx=i,kr.jsxs=i,kr}var Br={};/**
10
10
  * @license React
11
11
  * react-jsx-runtime.development.js
12
12
  *
@@ -14,20 +14,20 @@
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 Gi;function Io(){return Gi||(Gi=1,process.env.NODE_ENV!=="production"&&function(){var s=ae,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"),u=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),h=Symbol.for("react.memo"),l=Symbol.for("react.lazy"),v=Symbol.for("react.offscreen"),b=Symbol.iterator,T="@@iterator";function g(m){if(m===null||typeof m!="object")return null;var I=b&&m[b]||m[T];return typeof I=="function"?I:null}var x=s.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function w(m){{for(var I=arguments.length,N=new Array(I>1?I-1:0),Z=1;Z<I;Z++)N[Z-1]=arguments[Z];S("error",m,N)}}function S(m,I,N){{var Z=x.ReactDebugCurrentFrame,ie=Z.getStackAddendum();ie!==""&&(I+="%s",N=N.concat([ie]));var oe=N.map(function(Q){return String(Q)});oe.unshift("Warning: "+I),Function.prototype.apply.call(console[m],console,oe)}}var A=!1,P=!1,D=!1,F=!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===u||m===d||F||m===v||A||P||D||typeof m=="object"&&m!==null&&(m.$$typeof===l||m.$$typeof===h||m.$$typeof===i||m.$$typeof===a||m.$$typeof===c||m.$$typeof===L||m.getModuleId!==void 0))}function V(m,I,N){var Z=m.displayName;if(Z)return Z;var ie=I.displayName||I.name||"";return ie!==""?N+"("+ie+")":N}function z(m){return m.displayName||"Context"}function G(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 u:return"Suspense";case d:return"SuspenseList"}if(typeof m=="object")switch(m.$$typeof){case a:var I=m;return z(I)+".Consumer";case i:var N=m;return z(N._context)+".Provider";case c:return V(m,m.render,"ForwardRef");case h:var Z=m.displayName||null;return Z!==null?Z:G(m.type)||"Memo";case l:{var ie=m,oe=ie._payload,Q=ie._init;try{return G(Q(oe))}catch{return null}}}return null}var U=Object.assign,H=0,ne,ge,Pe,ve,ye,Ue,_e;function Se(){}Se.__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:Se,writable:!0};Object.defineProperties(console,{info:m,log:m,warn:m,error:m,group:m,groupCollapsed:m,groupEnd:m})}H++}}function ut(){{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=x.ReactCurrentDispatcher,ze;function ke(m,I,N){{if(ze===void 0)try{throw Error()}catch(ie){var Z=ie.stack.trim().match(/\n( *(at )?)/);ze=Z&&Z[1]||""}return`
18
- `+ze+m}}var ht=!1,tt;{var Pt=typeof WeakMap=="function"?WeakMap:Map;tt=new Pt}function _t(m,I){if(!m||ht)return"";{var N=tt.get(m);if(N!==void 0)return N}var Z;ht=!0;var ie=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var oe;oe=de.current,de.current=null,et();try{if(I){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){Z=B}Reflect.construct(m,[],Q)}else{try{Q.call()}catch(B){Z=B}m.call(Q.prototype)}}else{try{throw Error()}catch(B){Z=B}m()}}catch(B){if(B&&Z&&typeof B.stack=="string"){for(var $=B.stack.split(`
19
- `),p=Z.stack.split(`
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 M=`
21
- `+$[y].replace(" at new "," at ");return m.displayName&&M.includes("<anonymous>")&&(M=M.replace("<anonymous>",m.displayName)),typeof m=="function"&&tt.set(m,M),M}while(y>=1&&_>=0);break}}}finally{ht=!1,de.current=oe,ut(),Error.prepareStackTrace=ie}var k=m?m.displayName||m.name:"",R=k?ke(k):"";return typeof m=="function"&&tt.set(m,R),R}function Dt(m,I,N){return _t(m,!1)}function Rr(m){var I=m.prototype;return!!(I&&I.isReactComponent)}function ft(m,I,N){if(m==null)return"";if(typeof m=="function")return _t(m,Rr(m));if(typeof m=="string")return ke(m);switch(m){case u:return ke("Suspense");case d:return ke("SuspenseList")}if(typeof m=="object")switch(m.$$typeof){case c:return Dt(m.render);case h:return ft(m.type,I,N);case l:{var Z=m,ie=Z._payload,oe=Z._init;try{return ft(oe(ie),I,N)}catch{}}}return""}var rt=Object.prototype.hasOwnProperty,Qt={},Jt=x.ReactDebugCurrentFrame;function xt(m){if(m){var I=m._owner,N=ft(m.type,m._source,I?I.type:null);Jt.setExtraStackFrame(N)}else Jt.setExtraStackFrame(null)}function Qr(m,I,N,Z,ie){{var oe=Function.call.bind(rt);for(var Q in m)if(oe(m,Q)){var $=void 0;try{if(typeof m[Q]!="function"){var p=Error((Z||"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](I,Q,Z,N,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(y){$=y}$&&!($ instanceof Error)&&(xt(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).",Z||"React class",N,Q,typeof $),xt(null)),$ instanceof Error&&!($.message in Qt)&&(Qt[$.message]=!0,xt(ie),w("Failed %s type: %s",N,$.message),xt(null))}}}var Jr=Array.isArray;function Rt(m){return Jr(m)}function Ht(m){{var I=typeof Symbol=="function"&&Symbol.toStringTag,N=I&&m[Symbol.toStringTag]||m.constructor.name||"Object";return N}}function Hr(m){try{return Ft(m),!1}catch{return!0}}function Ft(m){return""+m}function er(m){if(Hr(m))return w("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",Ht(m)),Ft(m)}var tr=x.ReactCurrentOwner,Fr={key:!0,ref:!0,__self:!0,__source:!0},Tt,rr;function en(m){if(rt.call(m,"ref")){var I=Object.getOwnPropertyDescriptor(m,"ref").get;if(I&&I.isReactWarning)return!1}return m.ref!==void 0}function tn(m){if(rt.call(m,"key")){var I=Object.getOwnPropertyDescriptor(m,"key").get;if(I&&I.isReactWarning)return!1}return m.key!==void 0}function Ge(m,I){typeof m.ref=="string"&&tr.current}function je(m,I){{var N=function(){Tt||(Tt=!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)",I))};N.isReactWarning=!0,Object.defineProperty(m,"key",{get:N,configurable:!0})}}function Or(m,I){{var N=function(){rr||(rr=!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)",I))};N.isReactWarning=!0,Object.defineProperty(m,"ref",{get:N,configurable:!0})}}var dt=function(m,I,N,Z,ie,oe,Q){var $={$$typeof:e,type:m,key:I,ref:N,props:Q,_owner:oe};return $._store={},Object.defineProperty($._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty($,"_self",{configurable:!1,enumerable:!1,writable:!1,value:Z}),Object.defineProperty($,"_source",{configurable:!1,enumerable:!1,writable:!1,value:ie}),Object.freeze&&(Object.freeze($.props),Object.freeze($)),$};function Ve(m,I,N,Z,ie){{var oe,Q={},$=null,p=null;N!==void 0&&(er(N),$=""+N),tn(I)&&(er(I.key),$=""+I.key),en(I)&&(p=I.ref,Ge(I,ie));for(oe in I)rt.call(I,oe)&&!Fr.hasOwnProperty(oe)&&(Q[oe]=I[oe]);if(m&&m.defaultProps){var y=m.defaultProps;for(oe in y)Q[oe]===void 0&&(Q[oe]=y[oe])}if($||p){var _=typeof m=="function"?m.displayName||m.name||"Unknown":m;$&&je(Q,_),p&&Or(Q,_)}return dt(m,$,p,ie,Z,tr.current,Q)}}var De=x.ReactCurrentOwner,nr=x.ReactDebugCurrentFrame;function K(m){if(m){var I=m._owner,N=ft(m.type,m._source,I?I.type:null);nr.setExtraStackFrame(N)}else nr.setExtraStackFrame(null)}var nt;nt=!1;function Ot(m){return typeof m=="object"&&m!==null&&m.$$typeof===e}function ir(){{if(De.current){var m=G(De.current.type);if(m)return`
17
+ */var Yi;function Do(){return Yi||(Yi=1,process.env.NODE_ENV!=="production"&&function(){var s=ae,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"),u=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),h=Symbol.for("react.memo"),l=Symbol.for("react.lazy"),v=Symbol.for("react.offscreen"),x=Symbol.iterator,_="@@iterator";function g(m){if(m===null||typeof m!="object")return null;var C=x&&m[x]||m[_];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];S("error",m,N)}}function S(m,C,N){{var q=b.ReactDebugCurrentFrame,ie=q.getStackAddendum();ie!==""&&(C+="%s",N=N.concat([ie]));var oe=N.map(function(Q){return String(Q)});oe.unshift("Warning: "+C),Function.prototype.apply.call(console[m],console,oe)}}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===u||m===d||R||m===v||A||P||D||typeof m=="object"&&m!==null&&(m.$$typeof===l||m.$$typeof===h||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 u: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 h:var q=m.displayName||null;return q!==null?q:V(m.type)||"Memo";case l:{var ie=m,oe=ie._payload,Q=ie._init;try{return V(Q(oe))}catch{return null}}}return null}var U=Object.assign,H=0,ne,ge,Pe,ve,ye,Ue,_e;function Se(){}Se.__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:Se,writable:!0};Object.defineProperties(console,{info:m,log:m,warn:m,error:m,group:m,groupCollapsed:m,groupEnd:m})}H++}}function ut(){{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
+ `+ze+m}}var ht=!1,tt;{var Dt=typeof WeakMap=="function"?WeakMap:Map;tt=new Dt}function _t(m,C){if(!m||ht)return"";{var N=tt.get(m);if(N!==void 0)return N}var q;ht=!0;var ie=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var oe;oe=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
+ `),p=q.stack.split(`
20
+ `),y=$.length-1,T=p.length-1;y>=1&&T>=0&&$[y]!==p[T];)T--;for(;y>=1&&T>=0;y--,T--)if($[y]!==p[T]){if(y!==1||T!==1)do if(y--,T--,T<0||$[y]!==p[T]){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&&T>=0);break}}}finally{ht=!1,de.current=oe,ut(),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 ft(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 u:return ke("Suspense");case d:return ke("SuspenseList")}if(typeof m=="object")switch(m.$$typeof){case c:return Rt(m.render);case h:return ft(m.type,C,N);case l:{var q=m,ie=q._payload,oe=q._init;try{return ft(oe(ie),C,N)}catch{}}}return""}var rt=Object.prototype.hasOwnProperty,Jt={},Ht=b.ReactDebugCurrentFrame;function bt(m){if(m){var C=m._owner,N=ft(m.type,m._source,C?C.type:null);Ht.setExtraStackFrame(N)}else Ht.setExtraStackFrame(null)}function Jr(m,C,N,q,ie){{var oe=Function.call.bind(rt);for(var Q in m)if(oe(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},Tt,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(){Tt||(Tt=!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 dt=function(m,C,N,q,ie,oe,Q){var $={$$typeof:e,type:m,key:C,ref:N,props:Q,_owner:oe};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 oe,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(oe in C)rt.call(C,oe)&&!Or.hasOwnProperty(oe)&&(Q[oe]=C[oe]);if(m&&m.defaultProps){var y=m.defaultProps;for(oe in y)Q[oe]===void 0&&(Q[oe]=y[oe])}if($||p){var T=typeof m=="function"?m.displayName||m.name||"Unknown":m;$&&je(Q,T),p&&Lr(Q,T)}return dt(m,$,p,ie,q,rr.current,Q)}}var De=b.ReactCurrentOwner,ir=b.ReactDebugCurrentFrame;function K(m){if(m){var C=m._owner,N=ft(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
- Check the render method of \``+m+"`."}return""}}function rn(m){return""}var sr={};function nn(m){{var I=ir();if(!I){var N=typeof m=="string"?m:m.displayName||m.name;N&&(I=`
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
 
25
- Check the top-level render call using <`+N+">.")}return I}}function or(m,I){{if(!m._store||m._store.validated||m.key!=null)return;m._store.validated=!0;var N=nn(I);if(sr[N])return;sr[N]=!0;var Z="";m&&m._owner&&m._owner!==De.current&&(Z=" It was passed a child from "+G(m._owner.type)+"."),K(m),w('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',N,Z),K(null)}}function ar(m,I){{if(typeof m!="object")return;if(Rt(m))for(var N=0;N<m.length;N++){var Z=m[N];Ot(Z)&&or(Z,I)}else if(Ot(m))m._store&&(m._store.validated=!0);else if(m){var ie=g(m);if(typeof ie=="function"&&ie!==m.entries)for(var oe=ie.call(m),Q;!(Q=oe.next()).done;)Ot(Q.value)&&or(Q.value,I)}}}function sn(m){{var I=m.type;if(I==null||typeof I=="string")return;var N;if(typeof I=="function")N=I.propTypes;else if(typeof I=="object"&&(I.$$typeof===c||I.$$typeof===h))N=I.propTypes;else return;if(N){var Z=G(I);Qr(N,m.props,"prop",Z,m)}else if(I.PropTypes!==void 0&&!nt){nt=!0;var ie=G(I);w("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",ie||"Unknown")}typeof I.getDefaultProps=="function"&&!I.getDefaultProps.isReactClassApproved&&w("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function on(m){{for(var I=Object.keys(m.props),N=0;N<I.length;N++){var Z=I[N];if(Z!=="children"&&Z!=="key"){K(m),w("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",Z),K(null);break}}m.ref!==null&&(K(m),w("Invalid attribute `ref` supplied to `React.Fragment`."),K(null))}}var cr={};function lr(m,I,N,Z,ie,oe){{var Q=E(m);if(!Q){var $="";(m===void 0||typeof m=="object"&&m!==null&&Object.keys(m).length===0)&&($+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var p=rn();p?$+=p:$+=ir();var y;m===null?y="null":Rt(m)?y="array":m!==void 0&&m.$$typeof===e?(y="<"+(G(m.type)||"Unknown")+" />",$=" Did you accidentally export a JSX literal instead of a component?"):y=typeof m,w("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",y,$)}var _=Ve(m,I,N,ie,oe);if(_==null)return _;if(Q){var M=I.children;if(M!==void 0)if(Z)if(Rt(M)){for(var k=0;k<M.length;k++)ar(M[k],m);Object.freeze&&Object.freeze(M)}else w("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else ar(M,m)}if(rt.call(I,"key")){var R=G(m),B=Object.keys(I).filter(function(j){return j!=="key"}),q=B.length>0?"{key: someKey, "+B.join(": ..., ")+": ...}":"{key: someKey}";if(!cr[R+q]){var Y=B.length>0?"{"+B.join(": ..., ")+": ...}":"{}";w(`A props object containing a "key" prop is being spread into JSX:
25
+ Check the top-level render call using <`+N+">.")}return C}}function ar(m,C){{if(!m._store||m._store.validated||m.key!=null)return;m._store.validated=!0;var N=sn(C);if(or[N])return;or[N]=!0;var q="";m&&m._owner&&m._owner!==De.current&&(q=" It was passed a child from "+V(m._owner.type)+"."),K(m),w('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',N,q),K(null)}}function cr(m,C){{if(typeof m!="object")return;if(Ft(m))for(var N=0;N<m.length;N++){var q=m[N];Lt(q)&&ar(q,C)}else if(Lt(m))m._store&&(m._store.validated=!0);else if(m){var ie=g(m);if(typeof ie=="function"&&ie!==m.entries)for(var oe=ie.call(m),Q;!(Q=oe.next()).done;)Lt(Q.value)&&ar(Q.value,C)}}}function on(m){{var C=m.type;if(C==null||typeof C=="string")return;var N;if(typeof C=="function")N=C.propTypes;else if(typeof C=="object"&&(C.$$typeof===c||C.$$typeof===h))N=C.propTypes;else return;if(N){var q=V(C);Jr(N,m.props,"prop",q,m)}else if(C.PropTypes!==void 0&&!nt){nt=!0;var ie=V(C);w("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",ie||"Unknown")}typeof C.getDefaultProps=="function"&&!C.getDefaultProps.isReactClassApproved&&w("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function an(m){{for(var C=Object.keys(m.props),N=0;N<C.length;N++){var q=C[N];if(q!=="children"&&q!=="key"){K(m),w("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",q),K(null);break}}m.ref!==null&&(K(m),w("Invalid attribute `ref` supplied to `React.Fragment`."),K(null))}}var lr={};function ur(m,C,N,q,ie,oe){{var Q=E(m);if(!Q){var $="";(m===void 0||typeof m=="object"&&m!==null&&Object.keys(m).length===0)&&($+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var p=nn();p?$+=p:$+=sr();var y;m===null?y="null":Ft(m)?y="array":m!==void 0&&m.$$typeof===e?(y="<"+(V(m.type)||"Unknown")+" />",$=" Did you accidentally export a JSX literal instead of a component?"):y=typeof m,w("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",y,$)}var T=Ge(m,C,N,ie,oe);if(T==null)return T;if(Q){var I=C.children;if(I!==void 0)if(q)if(Ft(I)){for(var k=0;k<I.length;k++)cr(I[k],m);Object.freeze&&Object.freeze(I)}else w("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else cr(I,m)}if(rt.call(C,"key")){var F=V(m),B=Object.keys(C).filter(function(j){return j!=="key"}),Z=B.length>0?"{key: someKey, "+B.join(": ..., ")+": ...}":"{key: someKey}";if(!lr[F+Z]){var Y=B.length>0?"{"+B.join(": ..., ")+": ...}":"{}";w(`A props object containing a "key" prop is being spread into JSX:
26
26
  let props = %s;
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} />`,q,R,Y,R),cr[R+q]=!0}}return m===r?on(_):sn(_),_}}function an(m,I,N){return lr(m,I,N,!0)}function cn(m,I,N){return lr(m,I,N,!1)}var Lr=cn,ln=an;kr.Fragment=r,kr.jsx=Lr,kr.jsxs=ln}()),kr}var ji;function Co(){return ji||(ji=1,process.env.NODE_ENV==="production"?hn.exports=Mo():hn.exports=Io()),hn.exports}var qe=Co();class ce 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,ce)}static fromError(e,t,r){if(e instanceof ce)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 ce(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 X={ok(s){return{ok:!0,value:s}},err(s){return{ok:!1,error:s}},wrap(s){try{return X.ok(s())}catch(e){return X.err(e instanceof ce?e:new ce(String(e),ue.UNKNOWN,{originalError:e}))}}};class st{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 st({...this.data,isInitialized:!0,status:"idle"})}startLoading(){return new st({...this.data,status:"loading",loadProgress:0,error:null})}updateLoadProgress(e){return new st({...this.data,loadProgress:Math.min(Math.max(0,e),1)})}setLoaded(e){return new st({...this.data,status:"loaded",currentModel:e,loadProgress:1,error:null})}setError(e){return new st({...this.data,status:"error",error:e,loadProgress:0})}startRendering(){return new st({...this.data,status:"rendering"})}updateRenderInfo(e){return new st({...this.data,renderInfo:{...this.data.renderInfo,...e}})}dispose(){return new st({...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 fn{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 Po{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 Wi{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)}}class Yn{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)}}function At(s){return s!==null&&typeof s=="object"&&"getInternalRenderer"in s&&typeof s.getInternalRenderer=="function"}class Do{constructor(e){this.lastFrameTime=0,this.frameCount=0,this.screenshotElement=null,this.isShowingScreenshot=!1,this.pathTracingCompleteHandled=!1,this.disposed=!1,this.renderer=e.renderer,this.scene=e.scene,this.camera=e.camera,this.controls=e.controls,this.modelLoader=e.modelLoader,this.options=e.options,this.rendererOptions=e.rendererOptions,this.sceneSetupService=e.sceneSetupService,this.environmentService=e.environmentService,this.pathTracingService=e.pathTracingService,this.floorAlignmentService=e.floorAlignmentService,this.state=new st,this.events=new fn;const t=this.options.rendering||{},r=this.options.staticScene!==!1;this.renderLoopManager=new Po({enableIdleDetection:t.enableIdleDetection??r,idleDelay:t.idleDelay,targetFPS:t.targetFPS,enableFrameRateLimiting:t.enableFrameRateLimiting,alwaysRender:!1})}async initialize(){var e,t,r,n,o;try{const i=this.rendererOptions||{},a=this.renderer.initialize(i);if(!a.ok)return a;if(this.sceneSetupService){if(this.options.helpers){const h={grid:typeof this.options.helpers.grid=="boolean"?this.options.helpers.grid:!!this.options.helpers.grid,axes:typeof this.options.helpers.axes=="boolean"?this.options.helpers.axes:!!this.options.helpers.axes,gridColor:"#AAAAAA"},l=this.sceneSetupService.addHelpers(this.scene,h);l.ok||console.warn("Failed to add helpers:",l.error)}const u=this.options.lighting;if(u){const h={ambient:u.ambientLight?{color:String(u.ambientLight.color),intensity:u.ambientLight.intensity}:void 0,hemisphere:u.hemisphereLight?{skyColor:String(u.hemisphereLight.skyColor),groundColor:String(u.hemisphereLight.groundColor),intensity:u.hemisphereLight.intensity}:void 0,directional:u.directionalLight?{color:String(u.directionalLight.color),intensity:u.directionalLight.intensity,position:Array.isArray(u.directionalLight.position)?u.directionalLight.position:void 0,castShadow:u.directionalLight.castShadow,shadow:u.directionalLight.shadow}:void 0},l=this.sceneSetupService.addLighting(this.scene,h);l.ok||console.warn("Failed to add lighting:",l.error)}const d=(e=this.options.environment)==null?void 0:e.url;if(this.options.backgroundColor&&!d&&this.sceneSetupService){const h=this.sceneSetupService.createGradientBackground(this.scene,{topColor:String(this.options.backgroundColor),bottomColor:String(this.options.backgroundColor)});h.ok||console.warn("Failed to set background:",h.error)}}if(this.environmentService){const u=await this.environmentService.initialize({renderer:this.renderer,autoDispose:!0});u.ok||console.warn("Failed to initialize environment service:",u.error);const d=(t=this.options.environment)==null?void 0:t.url;if(d){const h=await this.environmentService.loadEnvironmentMap(d);h.ok?this.environmentService.applyToScene(this.scene,h.value):console.warn("Failed to load environment map:",h.error)}else if((r=this.options.helpers)!=null&&r.studioEnvironment){const h=this.environmentService.createStudioEnvironment();h.ok?this.environmentService.applyToScene(this.scene,h.value):console.warn("Failed to create studio environment:",h.error)}}const c=((n=this.options.pathTracing)==null?void 0:n.enabled)??!1;if(this.pathTracingService&&c){const u=await this.pathTracingService.initialize({enabled:!0,renderer:this.renderer});u.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??c}),this.pathTracingService.events.on("pathtracing:paused",d=>{this.renderLoopManager.disableContinuousRendering(),this.options.staticScene||this.renderLoopManager.setAlwaysRender(!1),setTimeout(()=>{this.renderLoopManager.stop()},100)})):console.warn("Failed to initialize path tracing:",u.error)}if(this.state=this.state.setInitialized(),this.startRenderLoop(),!this.options.staticScene)this.renderLoopManager.setAlwaysRender(!0);else{const u=((o=this.options.pathTracing)==null?void 0:o.enabled)??!1;this.pathTracingService&&u&&this.renderLoopManager.enableContinuousRendering()}return this.renderLoopManager.requestRender(),X.ok(void 0)}catch(i){const a=new ce("Failed to initialize viewer",ue.INITIALIZATION_FAILED,{originalError:i});return this.state=this.state.setError(a),this.events.emit("error",{error:a}),X.err(a)}}async loadModel(e){var t,r;if(!this.state.canLoad())return X.err(new ce("Cannot load model in current state",ue.INVALID_STATE,{currentState:this.state.status,isInitialized:this.state.isInitialized}));try{this.state=this.state.startLoading();const n=performance.now();let o;if(typeof e=="string"){this.lastModelUrl=e;const u=await this.modelLoader.load(e);if(!u.ok)throw u.error;o=u.value.scene}else o=e;this.state.currentModel&&(this.scene.remove(this.state.currentModel),this.state.currentModel.dispose());const i=this.scene.add(o);if(!i.ok)throw i.error;if(this.floorAlignmentService){const u=this.floorAlignmentService.alignToFloor(o);u.ok||console.warn("Failed to align model to floor:",u.error)}if(o.traverse(u=>{"castShadow"in u&&"receiveShadow"in u&&(u.castShadow=!0,u.receiveShadow=!0)}),this.state=this.state.setLoaded(o),this.sceneSetupService){const u=this.sceneSetupService.addDynamicGrid(this.scene,o,2);u.ok||console.warn("Failed to add dynamic grid:",u.error)}if((t=this.options.camera)!=null&&t.autoFitToObject&&this.sceneSetupService){const u=this.sceneSetupService.fitCameraToObject(o,this.camera,this.controls);u.ok||console.warn("Failed to fit camera to object:",u.error)}const a=performance.now()-n;this.events.emit("model:loaded",{model:o,loadTime:a}),this.renderLoopManager.requestRender();const c=((r=this.options.pathTracing)==null?void 0:r.enabled)??!1;return this.pathTracingService&&c&&(this.pathTracingService.reset(),this.pathTracingCompleteHandled=!1),X.ok(void 0)}catch(n){const o=n instanceof ce?n:new ce("Failed to load model",ue.MODEL_LOAD_FAILED,{originalError:n,source:e});return this.state=this.state.setError(o),this.events.emit("model:error",{error:o,url:typeof e=="string"?e:void 0}),X.err(o)}}startRenderLoop(){this.renderLoopManager.start(e=>{var u,d,h,l,v;if(this.disposed){this.renderLoopManager.stop();return}if(!this.state.isInitialized||this.state.status==="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=((u=this.options.pathTracing)==null?void 0:u.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=((h=this.pathTracingService)==null?void 0:h.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.state=this.state.updateRenderInfo({frameCount:this.frameCount,fps:Math.round(r),lastRenderTime:performance.now()-t}),this.lastFrameTime=t})}stopRenderLoop(){this.renderLoopManager.stop()}async renderFrame(){var u,d,h,l;const e=performance.now();if(!this.renderer||!this.scene||!this.camera){console.warn("[ViewerCore] Cannot render - components not initialized");return}if(this.isShowingScreenshot)return;this.state=this.state.startRendering();let t;const r=((u=this.pathTracingService)==null?void 0:u.isEnabled())||!1,n=((d=this.pathTracingService)==null?void 0:d.getSampleCount())||0,o=((h=this.options.pathTracing)==null?void 0:h.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.state}onStateChange(e){const t=r=>{this.state=r,e(r)};return this.stateChangeCallback=t,()=>{this.stateChangeCallback=void 0}}getEvents(){return this.events}getDomElement(){return this.renderer.getDomElement()}replaceWithScreenshot(){if(this.isShowingScreenshot)return;const e=this.renderer.getDomElement(),t=e.toDataURL("image/png"),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="auto",r.style.cursor="grab";const n=e.parentElement;if(n){e.style.display="none",n.appendChild(r),this.screenshotElement=r,this.isShowingScreenshot=!0;const o=()=>{this.restoreFromScreenshot()};r.addEventListener("mousedown",o),r.addEventListener("touchstart",o);const i=()=>{this.isShowingScreenshot&&this.restoreFromScreenshot()};window.addEventListener("resize",i),this.screenshotResizeHandler=i,this.screenshotElement&&this.screenshotElement.src?this.disposeSceneResources():console.warn("[ViewerCore] Screenshot capture failed, keeping scene resources")}}async restoreFromScreenshot(){var r;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.pathTracingService&&((r=this.options.pathTracing)!=null&&r.enabled)&&console.warn("[ViewerCore] Cannot recreate path tracing service - feature disabled"),this.serializedSceneState&&await Wi.restore(this.serializedSceneState,this.camera,this.controls,async n=>{const o=await this.loadModel(n);o.ok||console.error("[ViewerCore] Failed to reload model:",o.error)}),this.renderLoopManager.isRunning()||this.startRenderLoop(),this.renderLoopManager.requestRender())}disposeSceneResources(){var e;Yn.logMemoryUsage("Before disposal"),this.renderLoopManager.stop(),this.serializedSceneState=Wi.serialize(this.lastModelUrl,this.camera,this.controls,this.renderer.getDomElement()),this.pathTracingService,this.environmentService&&this.environmentService.dispose(),this.state.currentModel&&(this.scene.remove(this.state.currentModel),this.disposeObject(this.state.currentModel),this.state=new st().setInitialized()),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(),globalThis.gc&&((e=globalThis.gc)==null||e.call(globalThis)),Yn.logMemoryUsage("After disposal"),setTimeout(()=>{Yn.logMemoryUsage("After GC delay")},2e3)}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.disposed=!0,this.stopRenderLoop(),this.state.currentModel&&(this.scene.remove(this.state.currentModel),this.state.currentModel.dispose()),this.pathTracingService&&this.pathTracingService.dispose(),this.environmentService&&this.environmentService.dispose(),this.scene.clear(),this.controls.dispose(),this.renderer.dispose(),this.state=this.state.dispose(),this.events.removeAllListeners()}}class Nt{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 Nt(e)}static create(e=0,t=0,r=0){return new Nt(new C.Vector3(e,t,r))}}class We{constructor(e){this.object=e,this.positionAdapter=Nt.fromThreeVector(e.position),this.rotationAdapter=Nt.fromThreeVector(e.rotation),this.scaleAdapter=Nt.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()),X.ok(void 0)):X.err(new ce("Child must be a ThreeObject3DAdapter",ue.INVALID_PARAMETER))}catch(t){return X.err(new ce("Failed to add child object",ue.SCENE_OPERATION_FAILED,{originalError:t}))}}remove(e){try{return e instanceof We?(this.object.remove(e.getThreeObject()),X.ok(void 0)):X.err(new ce("Child must be a ThreeObject3DAdapter",ue.INVALID_PARAMETER))}catch(t){return X.err(new ce("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 C.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 C.Object3D)}}class Wt{constructor(e){this.scene=e||new C.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()),X.ok(void 0)):X.err(new ce("Object must be a ThreeObject3DAdapter",ue.INVALID_PARAMETER))}catch(t){return X.err(new ce("Failed to add object to scene",ue.SCENE_OPERATION_FAILED,{originalError:t}))}}remove(e){try{return e instanceof We?(this.scene.remove(e.getThreeObject()),X.ok(void 0)):X.err(new ce("Object must be a ThreeObject3DAdapter",ue.INVALID_PARAMETER))}catch(t){return X.err(new ce("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 C.Color?new Zn(this.scene.background):this.scene.background instanceof C.Texture?new dn(this.scene.background):null}set background(e){e instanceof Zn?this.scene.background=e.getThreeColor():e instanceof dn?this.scene.background=e.getThreeTexture():this.scene.background=null}get fog(){return this.scene.fog?new Yi(this.scene.fog):null}set fog(e){e instanceof Yi?this.scene.fog=e.getThreeFog():this.scene.fog=null}get environment(){return this.scene.environment?new dn(this.scene.environment):null}set environment(e){e instanceof dn?this.scene.environment=e.getThreeTexture():this.scene.environment=null}getInternalRenderer(){return this.scene}getThreeScene(){return this.scene}}class Zn{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 dn=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 Yi{constructor(e){this.fog=e}get color(){return new Zn(this.fog.color)}get near(){return this.fog.near||0}get far(){return this.fog.far||1e3}getThreeFog(){return this.fog}}class qn extends We{constructor(e){super(e),this.camera=e}get near(){return this.camera instanceof C.PerspectiveCamera||this.camera instanceof C.OrthographicCamera?this.camera.near:.1}set near(e){(this.camera instanceof C.PerspectiveCamera||this.camera instanceof C.OrthographicCamera)&&(this.camera.near=e)}get far(){return this.camera instanceof C.PerspectiveCamera||this.camera instanceof C.OrthographicCamera?this.camera.far:1e3}set far(e){(this.camera instanceof C.PerspectiveCamera||this.camera instanceof C.OrthographicCamera)&&(this.camera.far=e)}lookAt(e){e instanceof Nt?this.camera.lookAt(e.getThreeVector()):this.camera.lookAt(e.x,e.y,e.z)}updateProjectionMatrix(){(this.camera instanceof C.PerspectiveCamera||this.camera instanceof C.OrthographicCamera)&&this.camera.updateProjectionMatrix()}getWorldDirection(e){const t=new C.Vector3;this.camera.getWorldDirection(t),e.set(t.x,t.y,t.z)}getInternalRenderer(){return this.camera}getThreeCamera(){return this.camera}}class Kn extends qn{constructor(e){const t=e||new C.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 Kn(new C.PerspectiveCamera(e,t,r,n))}}class Ro{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 C.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:C.BasicShadowMap,pcf:C.PCFShadowMap,pcfsoft:C.PCFSoftShadowMap,vsm:C.VSMShadowMap};this.renderer.shadowMap.type=t[e.shadowMap.type]}if(e.toneMapping){const t={none:C.NoToneMapping,linear:C.LinearToneMapping,reinhard:C.ReinhardToneMapping,cineon:C.CineonToneMapping,aces:C.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=C.SRGBColorSpace,X.ok(void 0)}catch(t){return X.err(new ce("Failed to initialize renderer",ue.RENDERER_INIT_FAILED,{originalError:t,options:e}))}}render(e,t){if(!this.renderer)return X.err(new ce("Renderer not initialized",ue.RENDERER_NOT_INITIALIZED));try{if(!(e instanceof Wt))return X.err(new ce("Scene must be a ThreeSceneAdapter",ue.INVALID_PARAMETER));if(!(t instanceof qn))return X.err(new ce("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"),X.ok(void 0)):(this.renderer.render(r,n),X.ok(void 0))}catch(r){return X.err(new ce("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 Zi(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 Fo extends f.Loader{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new Bo(t)}),this.register(function(t){return new zo(t)}),this.register(function(t){return new qo(t)}),this.register(function(t){return new Ko(t)}),this.register(function(t){return new Xo(t)}),this.register(function(t){return new Uo(t)}),this.register(function(t){return new Vo(t)}),this.register(function(t){return new Go(t)}),this.register(function(t){return new jo(t)}),this.register(function(t){return new ko(t)}),this.register(function(t){return new Wo(t)}),this.register(function(t){return new Eo(t)}),this.register(function(t){return new Zo(t)}),this.register(function(t){return new Yo(t)}),this.register(function(t){return new Lo(t)}),this.register(function(t){return new $o(t)}),this.register(function(t){return new Qo(t)})}load(e,t,r,n){const o=this;let i;if(this.resourcePath!=="")i=this.resourcePath;else if(this.path!==""){const u=f.LoaderUtils.extractUrlBase(e);i=f.LoaderUtils.resolveURL(u,this.path)}else i=f.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const a=function(u){n?n(u):console.error(u),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(u){try{o.parse(u,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))===qi){try{i[fe.KHR_BINARY_GLTF]=new Jo(e)}catch(h){n&&n(h);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 u=new ha(o,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});u.fileLoader.setRequestHeader(this.requestHeader);for(let d=0;d<this.pluginCallbacks.length;d++){const h=this.pluginCallbacks[d](u);h.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),a[h.name]=h,i[h.name]=!0}if(o.extensionsUsed)for(let d=0;d<o.extensionsUsed.length;++d){const h=o.extensionsUsed[d],l=o.extensionsRequired||[];switch(h){case fe.KHR_MATERIALS_UNLIT:i[h]=new No;break;case fe.KHR_DRACO_MESH_COMPRESSION:i[h]=new Ho(o,this.dracoLoader);break;case fe.KHR_TEXTURE_TRANSFORM:i[h]=new ea;break;case fe.KHR_MESH_QUANTIZATION:i[h]=new ta;break;default:l.indexOf(h)>=0&&a[h]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+h+'".')}}u.setExtensions(i),u.setPlugins(a),u.parse(r,n)}parseAsync(e,t){const r=this;return new Promise(function(n,o){r.parse(e,t,n,o)})}}function Oo(){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 Lo{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 u;const d=new f.Color(16777215);c.color!==void 0&&d.setRGB(c.color[0],c.color[1],c.color[2],f.LinearSRGBColorSpace);const h=c.range!==void 0?c.range:0;switch(c.type){case"directional":u=new f.DirectionalLight(d),u.target.position.set(0,0,-1),u.add(u.target);break;case"point":u=new f.PointLight(d),u.distance=h;break;case"spot":u=new f.SpotLight(d),u.distance=h,c.spot=c.spot||{},c.spot.innerConeAngle=c.spot.innerConeAngle!==void 0?c.spot.innerConeAngle:0,c.spot.outerConeAngle=c.spot.outerConeAngle!==void 0?c.spot.outerConeAngle:Math.PI/4,u.angle=c.spot.outerConeAngle,u.penumbra=1-c.spot.innerConeAngle/c.spot.outerConeAngle,u.target.position.set(0,0,-1),u.add(u.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+c.type)}return u.position.set(0,0,0),u.decay=2,Mt(u,c),c.intensity!==void 0&&(u.intensity=c.intensity),u.name=t.createUniqueName(c.name||"light_"+e),n=Promise.resolve(u),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 No{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 ko{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 Bo{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 zo{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 Eo{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 Uo{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 Vo{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 Go{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 jo{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 Wo{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 Yo{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 Zo{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 qo{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 Ko{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 u=r.options.manager.getHandler(a.uri);u!==null&&(c=u)}return this.detectSupport().then(function(u){if(u)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 Xo{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 u=r.options.manager.getHandler(a.uri);u!==null&&(c=u)}return this.detectSupport().then(function(u){if(u)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 $o{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,u=n.byteLength||0,d=n.count,h=n.byteStride,l=new Uint8Array(a,c,u);return i.decodeGltfBufferAsync?i.decodeGltfBufferAsync(d,h,l,n.mode,n.filter).then(function(v){return v.buffer}):i.ready.then(function(){const v=new ArrayBuffer(d*h);return i.decodeGltfBuffer(new Uint8Array(v),d,h,l,n.mode,n.filter),v})})}else return null}}class Qo{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 u of n.primitives)if(u.mode!==ot.TRIANGLES&&u.mode!==ot.TRIANGLE_STRIP&&u.mode!==ot.TRIANGLE_FAN&&u.mode!==void 0)return null;const i=r.extensions[this.name].attributes,a=[],c={};for(const u in i)a.push(this.parser.getDependency("accessor",i[u]).then(d=>(c[u]=d,c[u])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(u=>{const d=u.pop(),h=d.isGroup?d.children:[d],l=u[0].count,v=[];for(const b of h){const T=new f.Matrix4,g=new f.Vector3,x=new f.Quaternion,w=new f.Vector3(1,1,1),S=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),S.setMatrixAt(A,T.compose(g,x,w));for(const A in c)if(A==="_COLOR_0"){const P=c[A];S.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(S,b),this.parser.assignFinalMaterial(S),v.push(S)}return d.isGroup?(d.clear(),d.add(...v),d):v[0]}))}}const qi="glTF",Br=12,Ki={JSON:1313821514,BIN:5130562};class Jo{constructor(e){this.name=fe.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,Br),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!==qi)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-Br,o=new DataView(e,Br);let i=0;for(;i<n;){const a=o.getUint32(i,!0);i+=4;const c=o.getUint32(i,!0);if(i+=4,c===Ki.JSON){const u=new Uint8Array(e,Br+i,a);this.content=r.decode(u)}else if(c===Ki.BIN){const u=Br+i;this.body=e.slice(u,u+a)}i+=a}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class Ho{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={},u={};for(const d in i){const h=$n[d]||d.toLowerCase();a[h]=i[d]}for(const d in e.attributes){const h=$n[d]||d.toLowerCase();if(i[d]!==void 0){const l=r.accessors[e.attributes[d]],v=ur[l.componentType];u[h]=v.name,c[h]=l.normalized===!0}}return t.getDependency("bufferView",o).then(function(d){return new Promise(function(h,l){n.decodeDracoFile(d,function(v){for(const b in v.attributes){const T=v.attributes[b],g=c[b];g!==void 0&&(T.normalized=g)}h(v)},a,u,f.LinearSRGBColorSpace,l)})})}}class ea{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 ta{constructor(){this.name=fe.KHR_MESH_QUANTIZATION}}class Xi 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,u=a*3,d=n-t,h=(r-t)/d,l=h*h,v=l*h,b=e*u,T=b-u,g=-2*v+3*l,x=v-l,w=1-g,S=x-l+h;for(let A=0;A!==a;A++){const P=i[T+A+a],D=i[T+A+c]*d,F=i[b+A+a],O=i[b+A]*d;o[A]=w*P+S*D+g*F+x*O}return o}}const ra=new f.Quaternion;class na extends Xi{interpolate_(e,t,r,n){const o=super.interpolate_(e,t,r,n);return ra.fromArray(o).normalize().toArray(o),o}}const ot={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},ur={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},$i={9728:f.NearestFilter,9729:f.LinearFilter,9984:f.NearestMipmapNearestFilter,9985:f.LinearMipmapNearestFilter,9986:f.NearestMipmapLinearFilter,9987:f.LinearMipmapLinearFilter},Qi={33071:f.ClampToEdgeWrapping,33648:f.MirroredRepeatWrapping,10497:f.RepeatWrapping},Xn={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},$n={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"},kt={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},ia={CUBICSPLINE:void 0,LINEAR:f.InterpolateLinear,STEP:f.InterpolateDiscrete},Qn={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function sa(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 Yt(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 oa(s,e,t){let r=!1,n=!1,o=!1;for(let u=0,d=e.length;u<d;u++){const h=e[u];if(h.POSITION!==void 0&&(r=!0),h.NORMAL!==void 0&&(n=!0),h.COLOR_0!==void 0&&(o=!0),r&&n&&o)break}if(!r&&!n&&!o)return Promise.resolve(s);const i=[],a=[],c=[];for(let u=0,d=e.length;u<d;u++){const h=e[u];if(r){const l=h.POSITION!==void 0?t.getDependency("accessor",h.POSITION):s.attributes.position;i.push(l)}if(n){const l=h.NORMAL!==void 0?t.getDependency("accessor",h.NORMAL):s.attributes.normal;a.push(l)}if(o){const l=h.COLOR_0!==void 0?t.getDependency("accessor",h.COLOR_0):s.attributes.color;c.push(l)}}return Promise.all([Promise.all(i),Promise.all(a),Promise.all(c)]).then(function(u){const d=u[0],h=u[1],l=u[2];return r&&(s.morphAttributes.position=d),n&&(s.morphAttributes.normal=h),o&&(s.morphAttributes.color=l),s.morphTargetsRelative=!0,s})}function aa(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 ca(s){let e;const t=s.extensions&&s.extensions[fe.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+Jn(t.attributes):e=s.indices+":"+Jn(s.attributes)+":"+s.mode,s.targets!==void 0)for(let r=0,n=s.targets.length;r<n;r++)e+=":"+Jn(s.targets[r]);return e}function Jn(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 Hn(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 la(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 ua=new f.Matrix4;class ha{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new Oo,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 Yt(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[u,d]of i.children.entries())o(d,a.children[u])};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=Xn[n.type],a=ur[n.componentType],c=n.normalized===!0,u=new a(n.count*i);return Promise.resolve(new f.BufferAttribute(u,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=Xn[n.type],u=ur[n.componentType],d=u.BYTES_PER_ELEMENT,h=d*c,l=n.byteOffset||0,v=n.bufferView!==void 0?r.bufferViews[n.bufferView].byteStride:void 0,b=n.normalized===!0;let T,g;if(v&&v!==h){const x=Math.floor(l/v),w="InterleavedBuffer:"+n.bufferView+":"+n.componentType+":"+x+":"+n.count;let S=t.cache.get(w);S||(T=new u(a,x*v,n.count*v/d),S=new f.InterleavedBuffer(T,v/d),t.cache.add(w,S)),g=new f.InterleavedBufferAttribute(S,c,l%v/d,b)}else a===null?T=new u(n.count*c):T=new u(a,l,n.count*c),g=new f.BufferAttribute(T,c,b);if(n.sparse!==void 0){const x=Xn.SCALAR,w=ur[n.sparse.indices.componentType],S=n.sparse.indices.byteOffset||0,A=n.sparse.values.byteOffset||0,P=new w(i[1],S,n.sparse.count*x),D=new u(i[2],A,n.sparse.count*c);a!==null&&(g=new f.BufferAttribute(g.array.slice(),g.itemSize,g.normalized));for(let F=0,O=P.length;F<O;F++){const L=P[F];if(g.setX(L,D[F*c]),c>=2&&g.setY(L,D[F*c+1]),c>=3&&g.setZ(L,D[F*c+2]),c>=4&&g.setW(L,D[F*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 u=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=$i[l.magFilter]||f.LinearFilter,d.minFilter=$i[l.minFilter]||f.LinearMipmapLinearFilter,d.wrapS=Qi[l.wrapS]||f.RepeatWrapping,d.wrapT=Qi[l.wrapT]||f.RepeatWrapping,n.associations.set(d,{textures:e}),d}).catch(function(){return null});return this.textureCache[c]=u,u}loadImageSource(e,t){const r=this,n=this.json,o=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(h=>h.clone());const i=n.images[e],a=self.URL||self.webkitURL;let c=i.uri||"",u=!1;if(i.bufferView!==void 0)c=r.getDependency("bufferView",i.bufferView).then(function(h){u=!0;const l=new Blob([h],{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(h){return new Promise(function(l,v){let b=l;t.isImageBitmapLoader===!0&&(b=function(T){const g=new f.Texture(T);g.needsUpdate=!0,l(g)}),t.load(f.LoaderUtils.resolveURL(h,o.path),b,void 0,v)})}).then(function(h){return u===!0&&a.revokeObjectURL(c),Mt(h,i),h.userData.mimeType=i.mimeType||la(i.uri),h}).catch(function(h){throw console.error("THREE.GLTFLoader: Couldn't load texture",c),h});return this.sourceCache[e]=d,d}assignTexture(e,t,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||{},u=[];if(c[fe.KHR_MATERIALS_UNLIT]){const h=n[fe.KHR_MATERIALS_UNLIT];i=h.getMaterialType(),u.push(h.extendParams(a,o,t))}else{const h=o.pbrMetallicRoughness||{};if(a.color=new f.Color(1,1,1),a.opacity=1,Array.isArray(h.baseColorFactor)){const l=h.baseColorFactor;a.color.setRGB(l[0],l[1],l[2],f.LinearSRGBColorSpace),a.opacity=l[3]}h.baseColorTexture!==void 0&&u.push(t.assignTexture(a,"map",h.baseColorTexture,f.SRGBColorSpace)),a.metalness=h.metallicFactor!==void 0?h.metallicFactor:1,a.roughness=h.roughnessFactor!==void 0?h.roughnessFactor:1,h.metallicRoughnessTexture!==void 0&&(u.push(t.assignTexture(a,"metalnessMap",h.metallicRoughnessTexture)),u.push(t.assignTexture(a,"roughnessMap",h.metallicRoughnessTexture))),i=this._invokeOne(function(l){return l.getMaterialType&&l.getMaterialType(e)}),u.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||Qn.OPAQUE;if(d===Qn.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,d===Qn.MASK&&(a.alphaTest=o.alphaCutoff!==void 0?o.alphaCutoff:.5)),o.normalTexture!==void 0&&i!==f.MeshBasicMaterial&&(u.push(t.assignTexture(a,"normalMap",o.normalTexture)),a.normalScale=new f.Vector2(1,1),o.normalTexture.scale!==void 0)){const h=o.normalTexture.scale;a.normalScale.set(h,h)}if(o.occlusionTexture!==void 0&&i!==f.MeshBasicMaterial&&(u.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 h=o.emissiveFactor;a.emissive=new f.Color().setRGB(h[0],h[1],h[2],f.LinearSRGBColorSpace)}return o.emissiveTexture!==void 0&&i!==f.MeshBasicMaterial&&u.push(t.assignTexture(a,"emissiveMap",o.emissiveTexture,f.SRGBColorSpace)),Promise.all(u).then(function(){const h=new i(a);return o.name&&(h.name=o.name),Mt(h,o),t.associations.set(h,{materials:e}),o.extensions&&Yt(n,h,o),h})}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 Ji(c,a,t)})}const i=[];for(let a=0,c=e.length;a<c;a++){const u=e[a],d=ca(u),h=n[d];if(h)i.push(h.promise);else{let l;u.extensions&&u.extensions[fe.KHR_DRACO_MESH_COMPRESSION]?l=o(u):l=Ji(new f.BufferGeometry,u,t),n[d]={primitive:u,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,u=i.length;c<u;c++){const d=i[c].material===void 0?sa(this.cache):this.getDependency("material",i[c].material);a.push(d)}return a.push(t.loadGeometries(i)),Promise.all(a).then(function(c){const u=c.slice(0,c.length-1),d=c[c.length-1],h=[];for(let v=0,b=d.length;v<b;v++){const T=d[v],g=i[v];let x;const w=u[v];if(g.mode===ot.TRIANGLES||g.mode===ot.TRIANGLE_STRIP||g.mode===ot.TRIANGLE_FAN||g.mode===void 0)x=o.isSkinnedMesh===!0?new f.SkinnedMesh(T,w):new f.Mesh(T,w),x.isSkinnedMesh===!0&&x.normalizeSkinWeights(),g.mode===ot.TRIANGLE_STRIP?x.geometry=Zi(x.geometry,f.TriangleStripDrawMode):g.mode===ot.TRIANGLE_FAN&&(x.geometry=Zi(x.geometry,f.TriangleFanDrawMode));else if(g.mode===ot.LINES)x=new f.LineSegments(T,w);else if(g.mode===ot.LINE_STRIP)x=new f.Line(T,w);else if(g.mode===ot.LINE_LOOP)x=new f.LineLoop(T,w);else if(g.mode===ot.POINTS)x=new f.Points(T,w);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+g.mode);Object.keys(x.geometry.morphAttributes).length>0&&aa(x,o),x.name=t.createUniqueName(o.name||"mesh_"+e),Mt(x,o),g.extensions&&Yt(n,x,g),t.assignFinalMaterial(x),h.push(x)}for(let v=0,b=h.length;v<b;v++)t.associations.set(h[v],{meshes:e,primitives:v});if(h.length===1)return o.extensions&&Yt(n,h[0],o),h[0];const l=new f.Group;o.extensions&&Yt(n,l,o),t.associations.set(l,{meshes:e});for(let v=0,b=h.length;v<b;v++)l.add(h[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 u=0,d=i.length;u<d;u++){const h=i[u];if(h){a.push(h);const l=new f.Matrix4;o!==null&&l.fromArray(o.array,u*16),c.push(l)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[u])}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=[],u=[],d=[];for(let h=0,l=n.channels.length;h<l;h++){const v=n.channels[h],b=n.samplers[v.sampler],T=v.target,g=T.node,x=n.parameters!==void 0?n.parameters[b.input]:b.input,w=n.parameters!==void 0?n.parameters[b.output]:b.output;T.node!==void 0&&(i.push(this.getDependency("node",g)),a.push(this.getDependency("accessor",x)),c.push(this.getDependency("accessor",w)),u.push(b),d.push(T))}return Promise.all([Promise.all(i),Promise.all(a),Promise.all(c),Promise.all(u),Promise.all(d)]).then(function(h){const l=h[0],v=h[1],b=h[2],T=h[3],g=h[4],x=[];for(let w=0,S=l.length;w<S;w++){const A=l[w],P=v[w],D=b[w],F=T[w],O=g[w];if(A===void 0)continue;A.updateMatrix&&A.updateMatrix();const L=r._createAnimationTracks(A,P,D,F,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,u=n.weights.length;c<u;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 u=0,d=a.length;u<d;u++)i.push(r.getDependency("node",a[u]));const c=n.skin===void 0?Promise.resolve(null):r.getDependency("skin",n.skin);return Promise.all([o,Promise.all(i),c]).then(function(u){const d=u[0],h=u[1],l=u[2];l!==null&&d.traverse(function(v){v.isSkinnedMesh&&v.bind(l,ua)});for(let v=0,b=h.length;v<b;v++)d.add(h[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(u){return u.createNodeMesh&&u.createNodeMesh(e)});return c&&a.push(c),o.camera!==void 0&&a.push(n.getDependency("camera",o.camera).then(function(u){return n._getNodeRef(n.cameraCache,o.camera,u)})),n._invokeAll(function(u){return u.createNodeAttachment&&u.createNodeAttachment(e)}).forEach(function(u){a.push(u)}),this.nodeCache[e]=Promise.all(a).then(function(u){let d;if(o.isBone===!0?d=new f.Bone:u.length>1?d=new f.Group:u.length===1?d=u[0]:d=new f.Object3D,d!==u[0])for(let h=0,l=u.length;h<l;h++)d.add(u[h]);if(o.name&&(d.userData.name=o.name,d.name=i),Mt(d,o),o.extensions&&Yt(r,d,o),o.matrix!==void 0){const h=new f.Matrix4;h.fromArray(o.matrix),d.applyMatrix4(h)}else o.translation!==void 0&&d.position.fromArray(o.translation),o.rotation!==void 0&&d.quaternion.fromArray(o.rotation),o.scale!==void 0&&d.scale.fromArray(o.scale);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&&Yt(t,o,r);const i=r.nodes||[],a=[];for(let c=0,u=i.length;c<u;c++)a.push(n.getDependency("node",i[c]));return Promise.all(a).then(function(c){for(let d=0,h=c.length;d<h;d++)o.add(c[d]);const u=d=>{const h=new Map;for(const[l,v]of n.associations)(l instanceof f.Material||l instanceof f.Texture)&&h.set(l,v);return d.traverse(l=>{const v=n.associations.get(l);v!=null&&h.set(l,v)}),h};return n.associations=u(o),o})}_createAnimationTracks(e,t,r,n,o){const i=[],a=e.name?e.name:e.uuid,c=[];kt[o.path]===kt.weights?e.traverse(function(l){l.morphTargetInfluences&&c.push(l.name?l.name:l.uuid)}):c.push(a);let u;switch(kt[o.path]){case kt.weights:u=f.NumberKeyframeTrack;break;case kt.rotation:u=f.QuaternionKeyframeTrack;break;case kt.position:case kt.scale:u=f.VectorKeyframeTrack;break;default:switch(r.itemSize){case 1:u=f.NumberKeyframeTrack;break;case 2:case 3:default:u=f.VectorKeyframeTrack;break}break}const d=n.interpolation!==void 0?ia[n.interpolation]:f.InterpolateLinear,h=this._getArrayFromAccessor(r);for(let l=0,v=c.length;l<v;l++){const b=new u(c[l]+"."+kt[o.path],t.array,h,d);n.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(b),i.push(b)}return i}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const r=Hn(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?na:Xi;return new n(this.times,this.values,this.getValueSize()/3,r)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function fa(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,u=a.max;if(c!==void 0&&u!==void 0){if(n.set(new f.Vector3(c[0],c[1],c[2]),new f.Vector3(u[0],u[1],u[2])),a.normalized){const d=Hn(ur[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 u=0,d=o.length;u<d;u++){const h=o[u];if(h.POSITION!==void 0){const l=t.json.accessors[h.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 T=Hn(ur[l.componentType]);c.multiplyScalar(T)}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 Ji(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=$n[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),fa(s,e,t),Promise.all(n).then(function(){return e.targets!==void 0?oa(s,e.targets,t):s})}class da{constructor(){this.loadingManager=new C.LoadingManager,this.loader=new Fo(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 C.PerspectiveCamera,c=i instanceof C.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(X.ok(n))},r=>{if(r.total>0){const n=r.loaded/r.total*100;console.log(`Loading: ${n.toFixed(0)}%`)}},r=>{t(X.err(new ce("Failed to load GLTF model",ue.MODEL_LOAD_FAILED,{url:e,originalError:r})))})})}catch(t){return X.err(new ce("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 C.VectorKeyframeTrack?"vector":e instanceof C.QuaternionKeyframeTrack?"quaternion":e instanceof C.NumberKeyframeTrack?"number":e instanceof C.BooleanKeyframeTrack?"boolean":"number"}}class Hi{static createLoader(e){var r;const t=(r=e.split(".").pop())==null?void 0:r.toLowerCase();switch(t){case"gltf":case"glb":return new da;default:throw new ce(`Unsupported file format: ${t}`,ue.UNSUPPORTED_FORMAT,{url:e,extension:t})}}}const es={type:"change"},ei={type:"start"},ts={type:"end"},pn=new f.Ray,rs=new f.Plane,pa=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},ti=1e-6;class ns 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=ga.bind(this),this._onPointerDown=ma.bind(this),this._onPointerUp=va.bind(this),this._onContextMenu=Sa.bind(this),this._onMouseWheel=xa.bind(this),this._onKeyDown=wa.bind(this),this._onTouchStart=_a.bind(this),this._onTouchMove=Ta.bind(this),this._onMouseDown=ya.bind(this),this._onMouseMove=ba.bind(this),this._interceptControlDown=Aa.bind(this),this._interceptControlUp=Ma.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(es),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 u=new f.Vector3(this._mouse.x,this._mouse.y,0);u.unproject(this.object),this.object.position.sub(u).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):(pn.origin.copy(this.object.position),pn.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(pn.direction))<pa?this.object.lookAt(this.target):(rs.setFromNormalAndCoplanarPoint(this.object.up,this.target),pn.intersectPlane(rs,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)>ti||8*(1-this._lastQuaternion.dot(this.object.quaternion))>ti||this._lastTargetPosition.distanceToSquared(this.target)>ti?(this.dispatchEvent(es),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 ma(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 ga(s){this.enabled!==!1&&(s.pointerType==="touch"?this._onTouchMove(s):this._onMouseMove(s))}function va(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(ts),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 ya(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(ei)}function ba(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 xa(s){this.enabled===!1||this.enableZoom===!1||this.state!==xe.NONE||(s.preventDefault(),this.dispatchEvent(ei),this._handleMouseWheel(this._customWheelEvent(s)),this.dispatchEvent(ts))}function wa(s){this.enabled===!1||this.enablePan===!1||this._handleKeyDown(s)}function _a(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(ei)}function Ta(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 Sa(s){this.enabled!==!1&&s.preventDefault()}function Aa(s){s.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function Ma(s){s.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}class Ia extends ns{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 is{constructor(e){this.controls=e,this.targetAdapter=Nt.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 ss extends is{constructor(e,t){const r=new ns(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 os extends is{constructor(e,t){const r=new Ia(e,t);super(r),r.screenSpacePanning=!0}get type(){return"map"}get screenSpacePanning(){return!0}set screenSpacePanning(e){}}const $r=class $r{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))}};$r.HEIGHT_RATIO=.075,$r.BEVEL_RATIO=.25,$r.GAP_FACTOR=1.05;let Zt=$r;class Ca{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 C.Shape,t=this.size+this.bevel,r=Math.PI*2/6;for(let u=0;u<6;u++){const d=t*Math.cos(u*r),h=t*Math.sin(u*r);u===0?e.moveTo(d,h):e.lineTo(d,h)}e.closePath();const n={depth:this.height,bevelEnabled:!0,bevelSize:this.bevel,bevelThickness:this.bevel,bevelSegments:128},o=new C.ExtrudeGeometry(e,n),i=new C.MeshPhysicalMaterial({color:new C.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 C.Color(16777215),envMapIntensity:1}),a=new C.Mesh(o,i);a.receiveShadow=!0;const c=new C.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 Pa{constructor(e,t,r){this.radius=e,this.tileSize=t,this.color=r}generateGrid(){const e=[],t=Zt.getGridSpacing(this.tileSize),r=t.width,n=t.height;for(let o=-this.radius;o<=this.radius;o++){const i=Math.max(-this.radius,-o-this.radius),a=Math.min(this.radius,-o+this.radius);for(let c=i;c<=a;c++){const u=r*(o+c/2),d=n*.75*c,h=Zt.getYPosition(this.tileSize),l=new Ca(new C.Vector3(u,h,d),this.tileSize,this.color);e.push(l)}}return e}addToScene(e){this.generateGrid().forEach(r=>{const n=r.createMesh();e.add(n)})}}class Da{addHelpers(e,t){try{if(!(e instanceof Wt))return X.err(new ce("Scene must be ThreeSceneAdapter",ue.INVALID_PARAMETER));const r=e.getThreeScene();if(t.grid){const n=r.userData;r.userData={...n,gridOptions:{enabled:!0,color:t.gridColor||"#AAAAAA"}}}if(t.axes){const n=t.axesSize||5,o=new C.AxesHelper(n);r.add(o)}return X.ok(void 0)}catch(r){return X.err(new ce("Failed to add helpers to scene",ue.SCENE_OPERATION_FAILED,{originalError:r,options:t}))}}addDynamicGrid(e,t,r=1.2){try{if(!(e instanceof Wt))return X.err(new ce("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 X.ok(void 0);const a=[];n.traverse(A=>{var P;(P=A.userData)!=null&&P.isHexGrid&&a.push(A)}),a.forEach(A=>n.remove(A));let c;t instanceof We||"getThreeObject"in t&&typeof t.getThreeObject=="function"?c=t.getThreeObject():c=t;const d=new C.Box3().setFromObject(c).getSize(new C.Vector3);console.log("Object size:",d);const l=1,b=Zt.getGridSpacing(l).width,T=Math.max(d.x,d.z)*r;let g=0,x=b;for(;x<T&&g<20;)g++,x+=2*b;T<b*.8?g=0:g<3&&T>b*2&&(g=3),console.log("Grid parameters:",{tileSize:l,gridRadius:g,requiredWidth:T,hexWidth:b,actualCoverage:(2*g+1)*b});const w=new Pa(g,l,i.color),S=new C.Group;return S.userData.isHexGrid=!0,w.generateGrid().forEach(A=>{const P=A.createMesh();S.add(P)}),n.add(S),X.ok(void 0)}catch(n){return X.err(new ce("Failed to add dynamic grid",ue.SCENE_OPERATION_FAILED,{originalError:n}))}}addLighting(e,t){try{if(!(e instanceof Wt))return X.err(new ce("Scene must be ThreeSceneAdapter",ue.INVALID_PARAMETER));const r=e.getThreeScene();if(t.ambient){const n=new C.Color(t.ambient.color||"#404040"),o=t.ambient.intensity??Math.PI,i=new C.AmbientLight(n,o);r.add(i)}if(t.hemisphere){const n=new C.Color(t.hemisphere.skyColor||"#ffffbb"),o=new C.Color(t.hemisphere.groundColor||"#080820"),i=t.hemisphere.intensity??1,a=new C.HemisphereLight(n,o,i);r.add(a)}if(t.directional){const n=new C.Color(t.directional.color||"#ffffff"),o=t.directional.intensity??Math.PI,i=new C.DirectionalLight(n,o);if(t.directional.position){const a=t.directional.position;if(a instanceof C.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 X.ok(void 0)}catch(r){return X.err(new ce("Failed to add lighting to scene",ue.SCENE_OPERATION_FAILED,{originalError:r,options:t}))}}createGradientBackground(e,t){try{if(!(e instanceof Wt))return X.err(new ce("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 X.err(new ce("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 C.CanvasTexture(n);return a.needsUpdate=!0,r.background=a,X.ok(void 0)}catch(r){return X.err(new ce("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 qn||"getThreeCamera"in t&&typeof t.getThreeCamera=="function"?o=t.getThreeCamera():o=t;let i;r instanceof ss||r instanceof os||"getThreeControls"in r&&typeof r.getThreeControls=="function"?i=r.getThreeControls():i=r;const a=new C.Box3().setFromObject(n),c=a.getCenter(new C.Vector3),u=a.getSize(new C.Vector3);console.log("Fitting camera to object:",{center:c,size:u,maxDimension:Math.max(u.x,u.y,u.z)});const d=Math.max(u.x,u.y,u.z);let h;"fov"in o?h=o.fov*(Math.PI/180):h=50*(Math.PI/180);let l=Math.abs(d/2/Math.tan(h/2));l*=2;const v=-Math.PI/4,b=Math.PI/8,T=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(T,g,x),o.lookAt(c),o.updateProjectionMatrix(),i&&i.target&&(i.target.copy(c),i.update()),console.log("Camera positioned at:",{x:T,y:g,z:x}),console.log("Looking at:",c),X.ok(void 0)}catch(n){return X.err(new ce("Failed to fit camera to object",ue.CAMERA_INIT_FAILED,{originalError:n}))}}}const as=0,Ra=1,cs=2,ls=2,ri=1.25,us=1,Bt=6*4+4+4,mn=65535,Fa=Math.pow(2,-24),ni=Symbol("SKIP_GENERATION");function hs(s){return s.index?s.index.count:s.attributes.position.count}function hr(s){return hs(s)/3}function fs(s,e=ArrayBuffer){return s>65535?new Uint32Array(new e(4*s)):new Uint16Array(new e(2*s))}function Oa(s,e){if(!s.index){const t=s.attributes.position.count,r=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=fs(t,r);s.setIndex(new f.BufferAttribute(n,1));for(let o=0;o<t;o++)n[o]=o}}function ds(s,e){const t=hr(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 ps(s,e){if(!s.groups||!s.groups.length)return ds(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 u=c.start/3,d=(c.start+c.count)/3;r.add(Math.max(o,u)),r.add(Math.min(i,d))}const a=Array.from(r.values()).sort((c,u)=>c-u);for(let c=0;c<a.length-1;c++){const u=a[c],d=a[c+1];t.push({offset:Math.floor(u),count:Math.floor(d-u)})}return t}function La(s,e){const t=hr(s),r=ps(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 ii(s,e,t,r,n){let o=1/0,i=1/0,a=1/0,c=-1/0,u=-1/0,d=-1/0,h=1/0,l=1/0,v=1/0,b=-1/0,T=-1/0,g=-1/0;for(let x=e*6,w=(e+t)*6;x<w;x+=6){const S=s[x+0],A=s[x+1],P=S-A,D=S+A;P<o&&(o=P),D>c&&(c=D),S<h&&(h=S),S>b&&(b=S);const F=s[x+2],O=s[x+3],L=F-O,E=F+O;L<i&&(i=L),E>u&&(u=E),F<l&&(l=F),F>T&&(T=F);const V=s[x+4],z=s[x+5],G=V-z,U=V+z;G<a&&(a=G),U>d&&(d=U),V<v&&(v=V),V>g&&(g=V)}r[0]=o,r[1]=i,r[2]=a,r[3]=c,r[4]=u,r[5]=d,n[0]=h,n[1]=l,n[2]=v,n[3]=b,n[4]=T,n[5]=g}function Na(s,e=null,t=null,r=null){const n=s.attributes.position,o=s.index?s.index.array:null,i=hr(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 u=n.array,d=n.offset||0;let h=3;n.isInterleavedBufferAttribute&&(h=n.data.stride);const l=["getX","getY","getZ"];for(let v=t;v<t+r;v++){const b=v*3,T=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*h+d,x=x*h+d,w=w*h+d);for(let S=0;S<3;S++){let A,P,D;a?(A=n[l[S]](g),P=n[l[S]](x),D=n[l[S]](w)):(A=u[g+S],P=u[x+S],D=u[w+S]);let F=A;P<F&&(F=P),D<F&&(F=D);let O=A;P>O&&(O=P),D>O&&(O=D);const L=(O-F)/2,E=S*2;c[T+E+0]=F+L,c[T+E+1]=L+(Math.abs(F)+L)*Fa}}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 ms(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 gs(s,e){e.set(s)}function vs(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 gn(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 zr(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 It=32,ka=(s,e)=>s.candidate-e.candidate,zt=new Array(It).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),vn=new Float32Array(6);function Ba(s,e,t,r,n,o){let i=-1,a=0;if(o===as)i=ms(e),i!==-1&&(a=(e[i]+e[i+3])/2);else if(o===Ra)i=ms(s),i!==-1&&(a=za(t,r,n,i));else if(o===cs){const c=zr(s);let u=ri*n;const d=r*6,h=(r+n)*6;for(let l=0;l<3;l++){const v=e[l],g=(e[l+3]-v)/It;if(n<It/4){const x=[...zt];x.length=n;let w=0;for(let A=d;A<h;A+=6,w++){const P=x[w];P.candidate=t[A+2*l],P.count=0;const{bounds:D,leftCacheBounds:F,rightCacheBounds:O}=P;for(let L=0;L<3;L++)O[L]=1/0,O[L+3]=-1/0,F[L]=1/0,F[L+3]=-1/0,D[L]=1/0,D[L+3]=-1/0;gn(A,t,D)}x.sort(ka);let S=n;for(let A=0;A<S;A++){const P=x[A];for(;A+1<S&&x[A+1].candidate===P.candidate;)x.splice(A+1,1),S--}for(let A=d;A<h;A+=6){const P=t[A+2*l];for(let D=0;D<S;D++){const F=x[D];P>=F.candidate?gn(A,t,F.rightCacheBounds):(gn(A,t,F.leftCacheBounds),F.count++)}}for(let A=0;A<S;A++){const P=x[A],D=P.count,F=n-P.count,O=P.leftCacheBounds,L=P.rightCacheBounds;let E=0;D!==0&&(E=zr(O)/c);let V=0;F!==0&&(V=zr(L)/c);const z=us+ri*(E*D+V*F);z<u&&(i=l,u=z,a=P.candidate)}}else{for(let S=0;S<It;S++){const A=zt[S];A.count=0,A.candidate=v+g+S*g;const P=A.bounds;for(let D=0;D<3;D++)P[D]=1/0,P[D+3]=-1/0}for(let S=d;S<h;S+=6){let D=~~((t[S+2*l]-v)/g);D>=It&&(D=It-1);const F=zt[D];F.count++,gn(S,t,F.bounds)}const x=zt[It-1];gs(x.bounds,x.rightCacheBounds);for(let S=It-2;S>=0;S--){const A=zt[S],P=zt[S+1];vs(A.bounds,P.rightCacheBounds,A.rightCacheBounds)}let w=0;for(let S=0;S<It-1;S++){const A=zt[S],P=A.count,D=A.bounds,O=zt[S+1].rightCacheBounds;P!==0&&(w===0?gs(D,vn):vs(D,vn,vn)),w+=P;let L=0,E=0;w!==0&&(L=zr(vn)/c);const V=n-w;V!==0&&(E=zr(O)/c);const z=us+ri*(L*w+E*V);z<u&&(i=l,u=z,a=A.candidate)}}}}else console.warn(`MeshBVH: Invalid build strategy value ${o} used.`);return{axis:i,pos:a}}function za(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 si{constructor(){this.boundingData=new Float32Array(6)}}function Ea(s,e,t,r,n,o){let i=r,a=r+n-1;const c=o.pos,u=o.axis*2;for(;;){for(;i<=a&&t[i*6+u]<c;)i++;for(;i<=a&&t[a*6+u]>=c;)a--;if(i<a){for(let d=0;d<3;d++){let h=e[i*3+d];e[i*3+d]=e[a*3+d],e[a*3+d]=h}for(let d=0;d<6;d++){let h=t[i*6+d];t[i*6+d]=t[a*6+d],t[a*6+d]=h}i++,a--}else return i}}function Ua(s,e,t,r,n,o){let i=r,a=r+n-1;const c=o.pos,u=o.axis*2;for(;;){for(;i<=a&&t[i*6+u]<c;)i++;for(;i<=a&&t[a*6+u]>=c;)a--;if(i<a){let d=s[i];s[i]=s[a],s[a]=d;for(let h=0;h<6;h++){let l=t[i*6+h];t[i*6+h]=t[a*6+h],t[a*6+h]=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 at(s){return s+8}function He(s,e){return e[s+6]}function oi(s,e){return e[s+7]}function kh(s){return s}let ys,Er,yn,bs;const Va=Math.pow(2,32);function ai(s){return"count"in s?1:1+ai(s.left)+ai(s.right)}function Ga(s,e,t){return ys=new Float32Array(t),Er=new Uint32Array(t),yn=new Uint16Array(t),bs=new Uint8Array(t),ci(s,e)}function ci(s,e){const t=s/4,r=s/2,n="count"in e,o=e.boundingData;for(let i=0;i<6;i++)ys[t+i]=o[i];if(n)if(e.buffer){const i=e.buffer;bs.set(new Uint8Array(i),s);for(let a=s,c=s+i.byteLength;a<c;a+=Bt){const u=a/2;Ye(u,yn)||(Er[a/4+6]+=t)}return s+i.byteLength}else{const i=e.offset,a=e.count;return Er[t+6]=i,yn[r+14]=a,yn[r+15]=mn,s+Bt}else{const i=e.left,a=e.right,c=e.splitAxis;let u;if(u=ci(s+Bt,i),u/4>Va)throw new Error("MeshBVH: Cannot store child pointer greater than 32 bits.");return Er[t+6]=u/4,u=ci(u,a),Er[t+7]=c,u}}function ja(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 Wa(s,e,t,r,n){const{maxDepth:o,verbose:i,maxLeafTris:a,strategy:c,onProgress:u,indirect:d}=n,h=s._indirectBuffer,l=s.geometry,v=l.index?l.index.array:null,b=d?Ua:Ea,T=hr(l),g=new Float32Array(6);let x=!1;const w=new si;return ii(e,t,r,w.boundingData,g),A(w,t,r,g),w;function S(P){u&&u(P/T)}function A(P,D,F,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))),F<=a||L>=o)return S(D+F),P.offset=D,P.count=F,P;const E=Ba(P.boundingData,O,e,D,F,c);if(E.axis===-1)return S(D+F),P.offset=D,P.count=F,P;const V=b(h,v,e,D,F,E);if(V===D||V===D+F)S(D+F),P.offset=D,P.count=F;else{P.splitAxis=E.axis;const z=new si,G=D,U=V-D;P.left=z,ii(e,G,U,z.boundingData,g),A(z,G,U,g,L+1);const H=new si,ne=V,ge=F-U;P.right=H,ii(e,ne,ge,H.boundingData,g),A(H,ne,ge,g,L+1)}return P}}function Ya(s,e){const t=s.geometry;e.indirect&&(s._indirectBuffer=ja(t,e.useSharedArrayBuffer),La(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||Oa(t,e);const r=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=Na(t),o=e.indirect?ds(t,e.range):ps(t,e.range);s._roots=o.map(i=>{const a=Wa(s,n,i.offset,i.count,e),c=ai(a),u=new r(Bt*c);return Ga(0,a,u),u})}class Ct{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}}Ct.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 u=0;u<=1;u++)for(let d=0;d<=1;d++){s.x=n.x*c+o.x*(1-c),s.y=n.y*u+o.y*(1-u),s.z=n.z*d+o.z*(1-d);const h=t.dot(s);i=Math.min(h,i),a=Math.max(h,a)}this.min=i,this.max=a}}();const Za=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,u=o.start,d=e;t.subVectors(a,u),s.subVectors(n.end,n.start),e.subVectors(o.end,o.start);const h=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=(h*l-b*v)/g:x=0,w=(h+x*l)/v,i.x=x,i.y=w}}(),li=function(){const s=new f.Vector2,e=new f.Vector3,t=new f.Vector3;return function(n,o,i,a){Za(n,o,s);let c=s.x,u=s.y;if(c>=0&&c<=1&&u>=0&&u<=1){n.at(c,i),o.at(u,a);return}else if(c>=0&&c<=1){u<0?o.at(0,a):o.at(1,a),n.closestPointToPoint(a,!0,i);return}else if(u>=0&&u<=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 h;u<0?h=o.start:h=o.end;const l=e,v=t;if(n.closestPointToPoint(h,!0,e),o.closestPointToPoint(d,!0,t),l.distanceToSquared(h)<=v.distanceToSquared(d)){i.copy(l),a.copy(h);return}else{i.copy(d),a.copy(v);return}}}}(),qa=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:u,b:d,c:h}=i;if(r.start=u,r.end=d,r.closestPointToPoint(c,!0,s).distanceTo(c)<=a||(r.start=u,r.end=h,r.closestPointToPoint(c,!0,s).distanceTo(c)<=a)||(r.start=d,r.end=h,r.closestPointToPoint(c,!0,s).distanceTo(c)<=a))return!0;const T=i.getPlane(t);if(Math.abs(T.distanceToPoint(c))<=a){const x=T.projectPoint(c,e);if(i.containsPoint(x))return!0}return!1}}(),Ka=1e-15;function ui(s){return Math.abs(s)<Ka}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 Ct),this.points=[this.a,this.b,this.c],this.sphere=new f.Sphere,this.plane=new f.Plane,this.needsUpdate=!0}intersectsSphere(e){return qa(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 u=o[1],d=i[1];u.subVectors(e,t),d.setFromPoints(u,n);const h=o[2],l=i[2];h.subVectors(t,r),l.setFromPoints(h,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,u=this.points;let d,h=1/0;for(let l=0;l<3;l++){const v=(l+1)%3;t.start.copy(u[l]),t.end.copy(u[v]),li(t,n,s,e),d=s.distanceToSquared(e),d<h&&(h=d,o&&o.copy(s),i&&i.copy(e))}return this.closestPointToPoint(a,s),d=a.distanceToSquared(s),d<h&&(h=d,o&&o.copy(s),i&&i.copy(a)),this.closestPointToPoint(c,s),d=c.distanceToSquared(s),d<h&&(h=d,o&&o.copy(s),i&&i.copy(c)),Math.sqrt(h)}}(),mt.prototype.intersectsTriangle=function(){const s=new mt,e=new Array(3),t=new Array(3),r=new Ct,n=new Ct,o=new f.Vector3,i=new f.Vector3,a=new f.Vector3,c=new f.Vector3,u=new f.Vector3,d=new f.Line3,h=new f.Line3,l=new f.Line3,v=new f.Vector3;function b(T,g,x){const w=T.points;let S=0,A=-1;for(let P=0;P<3;P++){const{start:D,end:F}=d;D.copy(w[P]),F.copy(w[(P+1)%3]),d.delta(i);const O=ui(g.distanceToPoint(D));if(ui(g.normal.dot(i))&&O){x.copy(d),S=2;break}const L=g.intersectLine(d,v);if(!L&&O&&v.copy(D),(L||O)&&!ui(v.distanceTo(F))){if(S<=1)(S===1?x.start:x.end).copy(v),O&&(A=S);else if(S>=2){(A===1?x.start:x.end).copy(v),S=2;break}if(S++,S===2&&A===-1)break}}return S}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 S=this.plane,A=g.plane;if(Math.abs(S.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],V=D[L];if(r.setFromPoints(V,t),E.isSeparated(r))return!1}const F=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=F[L],V=O[L];if(r.setFromPoints(V,e),E.isSeparated(r))return!1}for(let L=0;L<4;L++){const E=D[L];for(let V=0;V<4;V++){const z=O[V];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,h);if(P===1&&g.containsPoint(h.end))return x&&(x.start.copy(h.end),x.end.copy(h.end)),!0;if(P!==2)return!1;const D=b(g,S,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(h.delta(a),l.delta(c),a.dot(c)<0){let G=l.start;l.start=l.end,l.end=G}const F=h.start.dot(a),O=h.end.dot(a),L=l.start.dot(a),E=l.end.dot(a),V=O<L,z=F<E;return F!==E&&L!==O&&V===z?!1:(x&&(u.subVectors(h.start,l.start),u.dot(a)>0?x.start.copy(h.start):x.start.copy(l.start),u.subVectors(h.end,l.end),u.dot(a)<0?x.end.copy(h.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 u=a||c?r:null;if(this.intersectsTriangle(i,u))return(a||c)&&(a&&u.getCenter(a),c&&u.getCenter(c)),0;let d=1/0;for(let h=0;h<3;h++){let l;const v=t[h],b=i[v];this.closestPointToPoint(b,s),l=b.distanceToSquared(s),l<d&&(d=l,a&&a.copy(s),c&&c.copy(b));const T=this[v];i.closestPointToPoint(T,s),l=T.distanceToSquared(s),l<d&&(d=l,a&&a.copy(T),c&&c.copy(s))}for(let h=0;h<3;h++){const l=t[h],v=t[(h+1)%3];r.set(this[l],this[v]);for(let b=0;b<3;b++){const T=t[b],g=t[(b+1)%3];n.set(i[T],i[g]),li(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 Ze{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 Ct),this.alignedSatBounds=new Array(3).fill().map(()=>new Ct),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}}Ze.prototype.update=function(){return function(){const e=this.matrix,t=this.min,r=this.max,n=this.points;for(let u=0;u<=1;u++)for(let d=0;d<=1;d++)for(let h=0;h<=1;h++){const l=1*u|2*d|4*h,v=n[l];v.x=u?r.x:t.x,v.y=d?r.y:t.y,v.z=h?r.z:t.z,v.applyMatrix4(e)}const o=this.satBounds,i=this.satAxes,a=n[0];for(let u=0;u<3;u++){const d=i[u],h=o[u],l=1<<u,v=n[l];d.subVectors(a,v),h.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}}(),Ze.prototype.intersectsBox=function(){const s=new Ct;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 u=i[c],d=o[c];if(s.setFromBox(u,t),d.isSeparated(s))return!1}return!0}}(),Ze.prototype.intersectsTriangle=function(){const s=new mt,e=new Array(3),t=new Ct,r=new Ct,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 u=i.satBounds,d=i.satAxes,h=this.points;for(let l=0;l<3;l++){const v=u[l],b=d[l];if(t.setFromPoints(b,h),v.isSeparated(t))return!1}for(let l=0;l<3;l++){const v=c[l];for(let b=0;b<4;b++){const T=d[b];if(n.crossVectors(v,T),t.setFromPoints(n,e),r.setFromPoints(n,h),t.isSeparated(r))return!1}}return!0}}(),Ze.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}}(),Ze.prototype.distanceToPoint=function(){const s=new f.Vector3;return function(t){return this.closestPointToPoint(t,s),t.distanceTo(s)}}(),Ze.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,u=null){if(this.needsUpdate&&this.update(),this.intersectsBox(i))return(c||u)&&(i.getCenter(n),this.closestPointToPoint(n,r),i.closestPointToPoint(r,n),c&&c.copy(r),u&&u.copy(n)),0;const d=a*a,h=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(h,l);const w=x.distanceToSquared(n);if(w<b&&(b=w,c&&c.copy(x),u&&u.copy(n),w<d))return Math.sqrt(w)}let T=0;for(let g=0;g<3;g++)for(let x=0;x<=1;x++)for(let w=0;w<=1;w++){const S=(g+1)%3,A=(g+2)%3,P=x<<S|w<<A,D=1<<g|x<<S|w<<A,F=v[P],O=v[D];e[T].set(F,O);const E=s[g],V=s[S],z=s[A],G=t[T],U=G.start,H=G.end;U[E]=h[E],U[V]=x?h[V]:l[V],U[z]=w?h[z]:l[V],H[E]=l[E],H[V]=x?h[V]:l[V],H[z]=w?h[z]:l[V],T++}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:h.x,n.y=x?l.y:h.y,n.z=w?l.z:h.z,this.closestPointToPoint(n,r);const S=n.distanceToSquared(r);if(S<b&&(b=S,c&&c.copy(r),u&&u.copy(n),S<d))return Math.sqrt(S)}for(let g=0;g<12;g++){const x=e[g];for(let w=0;w<12;w++){const S=t[w];li(x,S,r,n);const A=r.distanceToSquared(n);if(A<b&&(b=A,c&&c.copy(r),u&&u.copy(n),A<d))return Math.sqrt(A)}}return Math.sqrt(b)}}();class hi{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 Xa extends hi{constructor(){super(()=>new mt)}}const ct=new Xa;class $a{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 $a;let Et,fr;const dr=[],bn=new hi(()=>new f.Box3);function Qa(s,e,t,r,n,o){Et=bn.getPrimitive(),fr=bn.getPrimitive(),dr.push(Et,fr),Me.setBuffer(s._roots[e]);const i=fi(0,s.geometry,t,r,n,o);Me.clearBuffer(),bn.releasePrimitive(Et),bn.releasePrimitive(fr),dr.pop(),dr.pop();const a=dr.length;return a>0&&(fr=dr[a-1],Et=dr[a-2]),i}function fi(s,e,t,r,n=null,o=0,i=0){const{float32Array:a,uint16Array:c,uint32Array:u}=Me;let d=s*2;if(Ye(d,c)){const l=Xe(s,u),v=Je(d,c);return Fe(s,a,Et),r(l,v,!1,i,o+s,Et)}else{let E=function(z){const{uint16Array:G,uint32Array:U}=Me;let H=z*2;for(;!Ye(H,G);)z=at(z),H=z*2;return Xe(z,U)},V=function(z){const{uint16Array:G,uint32Array:U}=Me;let H=z*2;for(;!Ye(H,G);)z=He(z,U),H=z*2;return Xe(z,U)+Je(H,G)};const l=at(s),v=He(s,u);let b=l,T=v,g,x,w,S;if(n&&(w=Et,S=fr,Fe(b,a,w),Fe(T,a,S),g=n(w),x=n(S),x<g)){b=v,T=l;const z=g;g=x,x=z,w=S}w||(w=Et,Fe(b,a,w));const A=Ye(b*2,c),P=t(w,A,g,i+1,o+b);let D;if(P===ls){const z=E(b),U=V(b)-z;D=r(z,U,!0,i+1,o+b,w)}else D=P&&fi(b,e,t,r,n,o,i+1);if(D)return!0;S=fr,Fe(T,a,S);const F=Ye(T*2,c),O=t(S,F,x,i+1,o+T);let L;if(O===ls){const z=E(T),U=V(T)-z;L=r(z,U,!0,i+1,o+T,S)}else L=O&&fi(T,e,t,r,n,o,i+1);return!!L}}const Ur=new f.Vector3,di=new f.Vector3;function Ja(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=>(Ur.copy(e).clamp(d.min,d.max),Ur.distanceToSquared(e)),intersectsBounds:(d,h,l)=>l<a&&l<i,intersectsTriangle:(d,h)=>{d.closestPointToPoint(e,Ur);const l=e.distanceToSquared(Ur);return l<a&&(di.copy(Ur),a=l,c=h),l<o}}),a===1/0)return null;const u=Math.sqrt(a);return t.point?t.point.copy(di):t.point=di.clone(),t.distance=u,t.faceIndex=c,t}const pr=new f.Vector3,mr=new f.Vector3,gr=new f.Vector3,xn=new f.Vector2,wn=new f.Vector2,_n=new f.Vector2,xs=new f.Vector3,ws=new f.Vector3,_s=new f.Vector3,Tn=new f.Vector3;function Ha(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 u=s.origin.distanceTo(n);return u<i||u>a?null:{distance:u,point:n.clone()}}function ec(s,e,t,r,n,o,i,a,c,u,d){pr.fromBufferAttribute(e,o),mr.fromBufferAttribute(e,i),gr.fromBufferAttribute(e,a);const h=Ha(s,pr,mr,gr,Tn,c,u,d);if(h){r&&(xn.fromBufferAttribute(r,o),wn.fromBufferAttribute(r,i),_n.fromBufferAttribute(r,a),h.uv=f.Triangle.getInterpolation(Tn,pr,mr,gr,xn,wn,_n,new f.Vector2)),n&&(xn.fromBufferAttribute(n,o),wn.fromBufferAttribute(n,i),_n.fromBufferAttribute(n,a),h.uv1=f.Triangle.getInterpolation(Tn,pr,mr,gr,xn,wn,_n,new f.Vector2)),t&&(xs.fromBufferAttribute(t,o),ws.fromBufferAttribute(t,i),_s.fromBufferAttribute(t,a),h.normal=f.Triangle.getInterpolation(Tn,pr,mr,gr,xs,ws,_s,new f.Vector3),h.normal.dot(s.direction)>0&&h.normal.multiplyScalar(-1));const l={a:o,b:i,c:a,normal:new f.Vector3,materialIndex:0};f.Triangle.getNormal(pr,mr,gr,l.normal),h.face=l,h.faceIndex=o}return h}function Sn(s,e,t,r,n,o,i){const a=r*3;let c=a+0,u=a+1,d=a+2;const h=s.index;s.index&&(c=h.getX(c),u=h.getX(u),d=h.getX(d));const{position:l,normal:v,uv:b,uv1:T}=s.attributes,g=ec(t,l,v,b,T,c,u,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,u=e+2;t&&(a=t.getX(a),c=t.getX(c),u=t.getX(u)),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(u),i.y=r.getY(u),i.z=r.getZ(u)}function tc(s,e,t,r,n,o,i,a){const{geometry:c,_indirectBuffer:u}=s;for(let d=r,h=r+n;d<h;d++)Sn(c,e,t,d,o,i,a)}function rc(s,e,t,r,n,o,i){const{geometry:a,_indirectBuffer:c}=s;let u=1/0,d=null;for(let h=r,l=r+n;h<l;h++){let v;v=Sn(a,e,t,h,null,o,i),v&&v.distance<u&&(d=v,u=v.distance)}return d}function nc(s,e,t,r,n,o,i){const{geometry:a}=t,{index:c}=a,u=a.attributes.position;for(let d=s,h=e+s;d<h;d++){let l;if(l=d,Oe(i,l*3,c,u),i.needsUpdate=!0,r(i,l,n,o))return!0}return!1}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,u=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),h(0,u),u+=o.byteLength;function h(l,v,b=!1){const T=l*2;if(a[T+15]===mn){const x=i[l+6],w=a[T+14];let S=1/0,A=1/0,P=1/0,D=-1/0,F=-1/0,O=-1/0;for(let L=3*x,E=3*(x+w);L<E;L++){let V=r[L];const z=n.getX(V),G=n.getY(V),U=n.getZ(V);z<S&&(S=z),z>D&&(D=z),G<A&&(A=G),G>F&&(F=G),U<P&&(P=U),U>O&&(O=U)}return c[l+0]!==S||c[l+1]!==A||c[l+2]!==P||c[l+3]!==D||c[l+4]!==F||c[l+5]!==O?(c[l+0]=S,c[l+1]=A,c[l+2]=P,c[l+3]=D,c[l+4]=F,c[l+5]=O,!0):!1}else{const x=l+8,w=i[l+6],S=x+v,A=w+v;let P=b,D=!1,F=!1;e?P||(D=e.has(S),F=e.has(A),P=!D&&!F):(D=!0,F=!0);const O=P||D,L=P||F;let E=!1;O&&(E=h(x,v,P));let V=!1;L&&(V=h(w,v,P));const z=E||V;if(z)for(let G=0;G<3;G++){const U=x+G,H=w+G,ne=c[U],ge=c[U+3],Pe=c[H],ve=c[H+3];c[l+G]=ne<Pe?ne:Pe,c[l+G+3]=ge>ve?ge:ve}return z}}}function Ut(s,e,t,r,n){let o,i,a,c,u,d;const h=1/t.direction.x,l=1/t.direction.y,v=1/t.direction.z,b=t.origin.x,T=t.origin.y,g=t.origin.z;let x=e[s],w=e[s+3],S=e[s+1],A=e[s+3+1],P=e[s+2],D=e[s+3+2];return h>=0?(o=(x-b)*h,i=(w-b)*h):(o=(w-b)*h,i=(x-b)*h),l>=0?(a=(S-T)*l,c=(A-T)*l):(a=(A-T)*l,c=(S-T)*l),o>c||a>i||((a>o||isNaN(o))&&(o=a),(c<i||isNaN(i))&&(i=c),v>=0?(u=(P-g)*v,d=(D-g)*v):(u=(D-g)*v,d=(P-g)*v),o>d||u>i)?!1:((u>o||o!==o)&&(o=u),(d<i||i!==i)&&(i=d),o<=n&&i>=r)}function sc(s,e,t,r,n,o,i,a){const{geometry:c,_indirectBuffer:u}=s;for(let d=r,h=r+n;d<h;d++){let l=u?u[d]:d;Sn(c,e,t,l,o,i,a)}}function oc(s,e,t,r,n,o,i){const{geometry:a,_indirectBuffer:c}=s;let u=1/0,d=null;for(let h=r,l=r+n;h<l;h++){let v;v=Sn(a,e,t,c?c[h]:h,null,o,i),v&&v.distance<u&&(d=v,u=v.distance)}return d}function ac(s,e,t,r,n,o,i){const{geometry:a}=t,{index:c}=a,u=a.attributes.position;for(let d=s,h=e+s;d<h;d++){let l;if(l=t.resolveTriangleIndex(d),Oe(i,l*3,c,u),i.needsUpdate=!0,r(i,l,n,o))return!0}return!1}function cc(s,e,t,r,n,o,i){Me.setBuffer(s._roots[e]),pi(0,s,t,r,n,o,i),Me.clearBuffer()}function pi(s,e,t,r,n,o,i){const{float32Array:a,uint16Array:c,uint32Array:u}=Me,d=s*2;if(Ye(d,c)){const l=Xe(s,u),v=Je(d,c);tc(e,t,r,l,v,n,o,i)}else{const l=at(s);Ut(l,a,r,o,i)&&pi(l,e,t,r,n,o,i);const v=He(s,u);Ut(v,a,r,o,i)&&pi(v,e,t,r,n,o,i)}}const lc=["x","y","z"];function uc(s,e,t,r,n,o){Me.setBuffer(s._roots[e]);const i=mi(0,s,t,r,n,o);return Me.clearBuffer(),i}function mi(s,e,t,r,n,o){const{float32Array:i,uint16Array:a,uint32Array:c}=Me;let u=s*2;if(Ye(u,a)){const h=Xe(s,c),l=Je(u,a);return rc(e,t,r,h,l,n,o)}else{const h=oi(s,c),l=lc[h],b=r.direction[l]>=0;let T,g;b?(T=at(s),g=He(s,c)):(T=He(s,c),g=at(s));const w=Ut(T,i,r,n,o)?mi(T,e,t,r,n,o):null;if(w){const P=w.point[l];if(b?P<=i[g+h]:P>=i[g+h+3])return w}const A=Ut(g,i,r,n,o)?mi(g,e,t,r,n,o):null;return w&&A?w.distance<=A.distance?w:A:w||A||null}}const An=new f.Box3,vr=new mt,yr=new mt,Vr=new f.Matrix4,Ts=new Ze,Mn=new Ze;function hc(s,e,t,r){Me.setBuffer(s._roots[e]);const n=gi(0,s,t,r);return Me.clearBuffer(),n}function gi(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(),Ts.set(t.boundingBox.min,t.boundingBox.max,r),n=Ts),Ye(c,i)){const d=e.geometry,h=d.index,l=d.attributes.position,v=t.index,b=t.attributes.position,T=Xe(s,a),g=Je(c,i);if(Vr.copy(r).invert(),t.boundsTree)return Fe(s,o,Mn),Mn.matrix.copy(Vr),Mn.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:w=>Mn.intersectsBox(w),intersectsTriangle:w=>{w.a.applyMatrix4(r),w.b.applyMatrix4(r),w.c.applyMatrix4(r),w.needsUpdate=!0;for(let S=T*3,A=(g+T)*3;S<A;S+=3)if(Oe(yr,S,h,l),yr.needsUpdate=!0,w.intersectsTriangle(yr))return!0;return!1}});for(let x=T*3,w=(g+T)*3;x<w;x+=3){Oe(vr,x,h,l),vr.a.applyMatrix4(Vr),vr.b.applyMatrix4(Vr),vr.c.applyMatrix4(Vr),vr.needsUpdate=!0;for(let S=0,A=v.count;S<A;S+=3)if(Oe(yr,S,v,b),yr.needsUpdate=!0,vr.intersectsTriangle(yr))return!0}}else{const d=s+8,h=a[s+6];return Fe(d,o,An),!!(n.intersectsBox(An)&&gi(d,e,t,r,n)||(Fe(h,o,An),n.intersectsBox(An)&&gi(h,e,t,r,n)))}}const In=new f.Matrix4,vi=new Ze,Gr=new Ze,fc=new f.Vector3,dc=new f.Vector3,pc=new f.Vector3,mc=new f.Vector3;function gc(s,e,t,r={},n={},o=0,i=1/0){e.boundingBox||e.computeBoundingBox(),vi.set(e.boundingBox.min,e.boundingBox.max,t),vi.needsUpdate=!0;const a=s.geometry,c=a.attributes.position,u=a.index,d=e.attributes.position,h=e.index,l=ct.getPrimitive(),v=ct.getPrimitive();let b=fc,T=dc,g=null,x=null;n&&(g=pc,x=mc);let w=1/0,S=null,A=null;return In.copy(t).invert(),Gr.matrix.copy(In),s.shapecast({boundsTraverseOrder:P=>vi.distanceToBox(P),intersectsBounds:(P,D,F)=>F<w&&F<i?(D&&(Gr.min.copy(P.min),Gr.max.copy(P.max),Gr.needsUpdate=!0),!0):!1,intersectsRange:(P,D)=>{if(e.boundsTree)return e.boundsTree.shapecast({boundsTraverseOrder:O=>Gr.distanceToBox(O),intersectsBounds:(O,L,E)=>E<w&&E<i,intersectsRange:(O,L)=>{for(let E=O,V=O+L;E<V;E++){Oe(v,3*E,h,d),v.a.applyMatrix4(t),v.b.applyMatrix4(t),v.c.applyMatrix4(t),v.needsUpdate=!0;for(let z=P,G=P+D;z<G;z++){Oe(l,3*z,u,c),l.needsUpdate=!0;const U=l.distanceToTriangle(v,b,g);if(U<w&&(T.copy(b),x&&x.copy(g),w=U,S=z,A=E),U<o)return!0}}}});{const F=hr(e);for(let O=0,L=F;O<L;O++){Oe(v,3*O,h,d),v.a.applyMatrix4(t),v.b.applyMatrix4(t),v.c.applyMatrix4(t),v.needsUpdate=!0;for(let E=P,V=P+D;E<V;E++){Oe(l,3*E,u,c),l.needsUpdate=!0;const z=l.distanceToTriangle(v,b,g);if(z<w&&(T.copy(b),x&&x.copy(g),w=z,S=E,A=O),z<o)return!0}}}}}),ct.releasePrimitive(l),ct.releasePrimitive(v),w===1/0?null:(r.point?r.point.copy(T):r.point=T.clone(),r.distance=w,r.faceIndex=S,n&&(n.point?n.point.copy(x):n.point=x.clone(),n.point.applyMatrix4(In),T.applyMatrix4(In),n.distance=T.sub(n.point).length(),n.faceIndex=A),r)}function vc(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,u=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),h(0,u),u+=o.byteLength;function h(l,v,b=!1){const T=l*2;if(a[T+15]===mn){const x=i[l+6],w=a[T+14];let S=1/0,A=1/0,P=1/0,D=-1/0,F=-1/0,O=-1/0;for(let L=x,E=x+w;L<E;L++){const V=3*s.resolveTriangleIndex(L);for(let z=0;z<3;z++){let G=V+z;G=r?r[G]:G;const U=n.getX(G),H=n.getY(G),ne=n.getZ(G);U<S&&(S=U),U>D&&(D=U),H<A&&(A=H),H>F&&(F=H),ne<P&&(P=ne),ne>O&&(O=ne)}}return c[l+0]!==S||c[l+1]!==A||c[l+2]!==P||c[l+3]!==D||c[l+4]!==F||c[l+5]!==O?(c[l+0]=S,c[l+1]=A,c[l+2]=P,c[l+3]=D,c[l+4]=F,c[l+5]=O,!0):!1}else{const x=l+8,w=i[l+6],S=x+v,A=w+v;let P=b,D=!1,F=!1;e?P||(D=e.has(S),F=e.has(A),P=!D&&!F):(D=!0,F=!0);const O=P||D,L=P||F;let E=!1;O&&(E=h(x,v,P));let V=!1;L&&(V=h(w,v,P));const z=E||V;if(z)for(let G=0;G<3;G++){const U=x+G,H=w+G,ne=c[U],ge=c[U+3],Pe=c[H],ve=c[H+3];c[l+G]=ne<Pe?ne:Pe,c[l+G+3]=ge>ve?ge:ve}return z}}}function yc(s,e,t,r,n,o,i){Me.setBuffer(s._roots[e]),yi(0,s,t,r,n,o,i),Me.clearBuffer()}function yi(s,e,t,r,n,o,i){const{float32Array:a,uint16Array:c,uint32Array:u}=Me,d=s*2;if(Ye(d,c)){const l=Xe(s,u),v=Je(d,c);sc(e,t,r,l,v,n,o,i)}else{const l=at(s);Ut(l,a,r,o,i)&&yi(l,e,t,r,n,o,i);const v=He(s,u);Ut(v,a,r,o,i)&&yi(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=bi(0,s,t,r,n,o);return Me.clearBuffer(),i}function bi(s,e,t,r,n,o){const{float32Array:i,uint16Array:a,uint32Array:c}=Me;let u=s*2;if(Ye(u,a)){const h=Xe(s,c),l=Je(u,a);return oc(e,t,r,h,l,n,o)}else{const h=oi(s,c),l=bc[h],b=r.direction[l]>=0;let T,g;b?(T=at(s),g=He(s,c)):(T=He(s,c),g=at(s));const w=Ut(T,i,r,n,o)?bi(T,e,t,r,n,o):null;if(w){const P=w.point[l];if(b?P<=i[g+h]:P>=i[g+h+3])return w}const A=Ut(g,i,r,n,o)?bi(g,e,t,r,n,o):null;return w&&A?w.distance<=A.distance?w:A:w||A||null}}const Cn=new f.Box3,br=new mt,xr=new mt,jr=new f.Matrix4,Ss=new Ze,Pn=new Ze;function wc(s,e,t,r){Me.setBuffer(s._roots[e]);const n=xi(0,s,t,r);return Me.clearBuffer(),n}function xi(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(),Ss.set(t.boundingBox.min,t.boundingBox.max,r),n=Ss),Ye(c,i)){const d=e.geometry,h=d.index,l=d.attributes.position,v=t.index,b=t.attributes.position,T=Xe(s,a),g=Je(c,i);if(jr.copy(r).invert(),t.boundsTree)return Fe(s,o,Pn),Pn.matrix.copy(jr),Pn.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:w=>Pn.intersectsBox(w),intersectsTriangle:w=>{w.a.applyMatrix4(r),w.b.applyMatrix4(r),w.c.applyMatrix4(r),w.needsUpdate=!0;for(let S=T,A=g+T;S<A;S++)if(Oe(xr,3*e.resolveTriangleIndex(S),h,l),xr.needsUpdate=!0,w.intersectsTriangle(xr))return!0;return!1}});for(let x=T,w=g+T;x<w;x++){const S=e.resolveTriangleIndex(x);Oe(br,3*S,h,l),br.a.applyMatrix4(jr),br.b.applyMatrix4(jr),br.c.applyMatrix4(jr),br.needsUpdate=!0;for(let A=0,P=v.count;A<P;A+=3)if(Oe(xr,A,v,b),xr.needsUpdate=!0,br.intersectsTriangle(xr))return!0}}else{const d=s+8,h=a[s+6];return Fe(d,o,Cn),!!(n.intersectsBox(Cn)&&xi(d,e,t,r,n)||(Fe(h,o,Cn),n.intersectsBox(Cn)&&xi(h,e,t,r,n)))}}const Dn=new f.Matrix4,wi=new Ze,Wr=new Ze,_c=new f.Vector3,Tc=new f.Vector3,Sc=new f.Vector3,Ac=new f.Vector3;function Mc(s,e,t,r={},n={},o=0,i=1/0){e.boundingBox||e.computeBoundingBox(),wi.set(e.boundingBox.min,e.boundingBox.max,t),wi.needsUpdate=!0;const a=s.geometry,c=a.attributes.position,u=a.index,d=e.attributes.position,h=e.index,l=ct.getPrimitive(),v=ct.getPrimitive();let b=_c,T=Tc,g=null,x=null;n&&(g=Sc,x=Ac);let w=1/0,S=null,A=null;return Dn.copy(t).invert(),Wr.matrix.copy(Dn),s.shapecast({boundsTraverseOrder:P=>wi.distanceToBox(P),intersectsBounds:(P,D,F)=>F<w&&F<i?(D&&(Wr.min.copy(P.min),Wr.max.copy(P.max),Wr.needsUpdate=!0),!0):!1,intersectsRange:(P,D)=>{if(e.boundsTree){const F=e.boundsTree;return F.shapecast({boundsTraverseOrder:O=>Wr.distanceToBox(O),intersectsBounds:(O,L,E)=>E<w&&E<i,intersectsRange:(O,L)=>{for(let E=O,V=O+L;E<V;E++){const z=F.resolveTriangleIndex(E);Oe(v,3*z,h,d),v.a.applyMatrix4(t),v.b.applyMatrix4(t),v.c.applyMatrix4(t),v.needsUpdate=!0;for(let G=P,U=P+D;G<U;G++){const H=s.resolveTriangleIndex(G);Oe(l,3*H,u,c),l.needsUpdate=!0;const ne=l.distanceToTriangle(v,b,g);if(ne<w&&(T.copy(b),x&&x.copy(g),w=ne,S=G,A=E),ne<o)return!0}}}})}else{const F=hr(e);for(let O=0,L=F;O<L;O++){Oe(v,3*O,h,d),v.a.applyMatrix4(t),v.b.applyMatrix4(t),v.c.applyMatrix4(t),v.needsUpdate=!0;for(let E=P,V=P+D;E<V;E++){const z=s.resolveTriangleIndex(E);Oe(l,3*z,u,c),l.needsUpdate=!0;const G=l.distanceToTriangle(v,b,g);if(G<w&&(T.copy(b),x&&x.copy(g),w=G,S=E,A=O),G<o)return!0}}}}}),ct.releasePrimitive(l),ct.releasePrimitive(v),w===1/0?null:(r.point?r.point.copy(T):r.point=T.clone(),r.distance=w,r.faceIndex=S,n&&(n.point?n.point.copy(x):n.point=x.clone(),n.point.applyMatrix4(Dn),T.applyMatrix4(Dn),n.distance=T.sub(n.point).length(),n.faceIndex=A),r)}function Ic(){return typeof SharedArrayBuffer<"u"}const Yr=new Me.constructor,Rn=new Me.constructor,Vt=new hi(()=>new f.Box3),wr=new f.Box3,_r=new f.Box3,_i=new f.Box3,Ti=new f.Box3;let Si=!1;function Cc(s,e,t,r){if(Si)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");Si=!0;const n=s._roots,o=e._roots;let i,a=0,c=0;const u=new f.Matrix4().copy(t).invert();for(let d=0,h=n.length;d<h;d++){Yr.setBuffer(n[d]),c=0;const l=Vt.getPrimitive();Fe(0,Yr.float32Array,l),l.applyMatrix4(u);for(let v=0,b=o.length;v<b&&(Rn.setBuffer(o[v]),i=gt(0,0,t,u,r,a,c,0,0,l),Rn.clearBuffer(),c+=o[v].length,!i);v++);if(Vt.releasePrimitive(l),Yr.clearBuffer(),a+=n[d].length,i)break}return Si=!1,i}function gt(s,e,t,r,n,o=0,i=0,a=0,c=0,u=null,d=!1){let h,l;d?(h=Rn,l=Yr):(h=Yr,l=Rn);const v=h.float32Array,b=h.uint32Array,T=h.uint16Array,g=l.float32Array,x=l.uint32Array,w=l.uint16Array,S=s*2,A=e*2,P=Ye(S,T),D=Ye(A,w);let F=!1;if(D&&P)d?F=n(Xe(e,x),Je(e*2,w),Xe(s,b),Je(s*2,T),c,i+e,a,o+s):F=n(Xe(s,b),Je(s*2,T),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=at(s),E=He(s,b);Fe(L,v,wr),Fe(E,v,_r);const V=O.intersectsBox(wr),z=O.intersectsBox(_r);F=V&&gt(e,L,r,t,n,i,o,c,a+1,O,!d)||z&&gt(e,E,r,t,n,i,o,c,a+1,O,!d),Vt.releasePrimitive(O)}else{const O=at(e),L=He(e,x);Fe(O,g,_i),Fe(L,g,Ti);const E=u.intersectsBox(_i),V=u.intersectsBox(Ti);if(E&&V)F=gt(s,O,t,r,n,o,i,a,c+1,u,d)||gt(s,L,t,r,n,o,i,a,c+1,u,d);else if(E)if(P)F=gt(s,O,t,r,n,o,i,a,c+1,u,d);else{const z=Vt.getPrimitive();z.copy(_i).applyMatrix4(t);const G=at(s),U=He(s,b);Fe(G,v,wr),Fe(U,v,_r);const H=z.intersectsBox(wr),ne=z.intersectsBox(_r);F=H&&gt(O,G,r,t,n,i,o,c,a+1,z,!d)||ne&&gt(O,U,r,t,n,i,o,c,a+1,z,!d),Vt.releasePrimitive(z)}else if(V)if(P)F=gt(s,L,t,r,n,o,i,a,c+1,u,d);else{const z=Vt.getPrimitive();z.copy(Ti).applyMatrix4(t);const G=at(s),U=He(s,b);Fe(G,v,wr),Fe(U,v,_r);const H=z.intersectsBox(wr),ne=z.intersectsBox(_r);F=H&&gt(L,G,r,t,n,i,o,c,a+1,z,!d)||ne&&gt(L,U,r,t,n,i,o,c,a+1,z,!d),Vt.releasePrimitive(z)}}return F}const Fn=new Ze,As=new f.Box3,Pc={strategy:as,maxDepth:40,maxLeafTris:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null};class Ai{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 Ai(t,{...r,[ni]:!0});if(a._roots=o,a._indirectBuffer=i||null,r.setIndex){const c=t.getIndex();if(c===null){const u=new f.BufferAttribute(e.index,1,!1);t.setIndex(u)}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({...Pc,[ni]:!1},t),t.useSharedArrayBuffer&&!Ic())throw new Error("MeshBVH: SharedArrayBuffer is not available.");this.geometry=e,this._roots=null,this._indirectBuffer=null,t[ni]||(Ya(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?vc:ic)(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 u=a*2,d=o[u+15]===mn;if(d){const h=n[a+6],l=o[u+14];e(c,d,new Float32Array(r,a*4,6),h,l)}else{const h=a+Bt/4,l=n[a+6],v=n[a+7];e(c,d,new Float32Array(r,a*4,6),v)||(i(h,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,u=Array.isArray(t),d=i.groups,h=c?t.side:t,l=this.indirect?yc:cc;for(let v=0,b=o.length;v<b;v++){const T=u?t[d[v].materialIndex].side:h,g=a.length;if(l(this,v,T,e,a,r,n),u){const x=d[v].materialIndex;for(let w=g,S=a.length;w<S;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 u=null;const d=i.groups,h=a?t.side:t,l=this.indirect?xc:uc;for(let v=0,b=o.length;v<b;v++){const T=c?t[d[v].materialIndex].side:h,g=l(this,v,T,e,r,n);g!=null&&(u==null||g.distance<u.distance)&&(u=g,c&&(g.face.materialIndex=d[v].materialIndex))}return u}intersectsGeometry(e,t){let r=!1;const n=this._roots,o=this.indirect?wc:hc;for(let i=0,a=n.length;i<a&&(r=o(this,i,e,t),!r);i++);return r}shapecast(e){const t=ct.getPrimitive(),r=this.indirect?ac:nc;let{boundsTraverseOrder:n,intersectsBounds:o,intersectsRange:i,intersectsTriangle:a}=e;if(i&&a){const h=i;i=(l,v,b,T,g)=>h(l,v,b,T,g)?!0:r(l,v,this,a,b,T,t)}else i||(a?i=(h,l,v,b)=>r(h,l,this,a,v,b,t):i=(h,l,v)=>v);let c=!1,u=0;const d=this._roots;for(let h=0,l=d.length;h<l;h++){const v=d[h];if(c=Qa(this,h,o,i,n,u),c)break;u+=v.byteLength}return ct.releasePrimitive(t),c}bvhcast(e,t,r){let{intersectsRanges:n,intersectsTriangles:o}=r;const i=ct.getPrimitive(),a=this.geometry.index,c=this.geometry.attributes.position,u=this.indirect?b=>{const T=this.resolveTriangleIndex(b);Oe(i,T*3,a,c)}:b=>{Oe(i,b*3,a,c)},d=ct.getPrimitive(),h=e.geometry.index,l=e.geometry.attributes.position,v=e.indirect?b=>{const T=e.resolveTriangleIndex(b);Oe(d,T*3,h,l)}:b=>{Oe(d,b*3,h,l)};if(o){const b=(T,g,x,w,S,A,P,D)=>{for(let F=x,O=x+w;F<O;F++){v(F),d.a.applyMatrix4(t),d.b.applyMatrix4(t),d.c.applyMatrix4(t),d.needsUpdate=!0;for(let L=T,E=T+g;L<E;L++)if(u(L),i.needsUpdate=!0,o(i,d,L,F,S,A,P,D))return!0}return!1};if(n){const T=n;n=function(g,x,w,S,A,P,D,F){return T(g,x,w,S,A,P,D,F)?!0:b(g,x,w,S,A,P,D,F)}}else n=b}return Cc(this,e,t,n)}intersectsBox(e,t){return Fn.set(e.min,e.max,t),Fn.needsUpdate=!0,this.shapecast({intersectsBounds:r=>Fn.intersectsBox(r),intersectsTriangle:r=>Fn.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?Mc:gc)(this,e,t,r,n,o,i)}closestPointToPoint(e,t={},r=0,n=1/0){return Ja(this,e,t,r,n)}getBoundingBox(e){return e.makeEmpty(),this._roots.forEach(r=>{Fe(0,new Float32Array(r),As),e.union(As)}),e}}function Dc(s){switch(s){case 1:return"R";case 2:return"RG";case 3:return"RGBA";case 4:return"RGBA"}throw new Error}function Rc(s){switch(s){case 1:return f.RedFormat;case 2:return f.RGFormat;case 3:return f.RGBAFormat;case 4:return f.RGBAFormat}}function Ms(s){switch(s){case 1:return f.RedIntegerFormat;case 2:return f.RGIntegerFormat;case 3:return f.RGBAIntegerFormat;case 4:return f.RGBAIntegerFormat}}class Is 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,u=c.BYTES_PER_ELEMENT;let d=this._forcedType,h=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,T,g=Dc(o);switch(d){case f.FloatType:b=1,v=Rc(o),a&&u===1?(T=c,g+="8",c===Uint8Array?l=f.UnsignedByteType:(l=f.ByteType,g+="_SNORM")):(T=Float32Array,g+="32F",l=f.FloatType);break;case f.IntType:g+=u*8+"I",b=a?Math.pow(2,c.BYTES_PER_ELEMENT*8-1):1,v=Ms(o),u===1?(T=Int8Array,l=f.ByteType):u===2?(T=Int16Array,l=f.ShortType):(T=Int32Array,l=f.IntType);break;case f.UnsignedIntType:g+=u*8+"UI",b=a?Math.pow(2,c.BYTES_PER_ELEMENT*8-1):1,v=Ms(o),u===1?(T=Uint8Array,l=f.UnsignedByteType):u===2?(T=Uint16Array,l=f.UnsignedShortType):(T=Uint32Array,l=f.UnsignedIntType);break}h===3&&(v===f.RGBAFormat||v===f.RGBAIntegerFormat)&&(h=4);const x=Math.ceil(Math.sqrt(i))||1,w=h*x*x,S=new T(w),A=e.normalized;e.normalized=!1;for(let P=0;P<i;P++){const D=h*P;S[D]=e.getX(P)/b,o>=2&&(S[D+1]=e.getY(P)/b),o>=3&&(S[D+2]=e.getZ(P)/b,h===4&&(S[D+3]=1)),o>=4&&(S[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=S,this.needsUpdate=!0,this.dispose(),e.itemSize=r,e.count=n}}class Cs extends Is{constructor(){super(),this._forcedType=f.UnsignedIntType}}class Ps extends Is{constructor(){super(),this._forcedType=f.FloatType}}class Fc{constructor(){this.index=new Cs,this.position=new Ps,this.bvhBounds=new f.DataTexture,this.bvhContents=new f.DataTexture,this._cachedIndexAttr=null,this.index.overrideItemSize=3}updateFrom(e){const{geometry:t}=e;if(Lc(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=fs(hs(t));this._cachedIndexAttr=new f.BufferAttribute(n,1,!1)}Oc(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 Oc(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 u=0;u<3;u++)r[a+u]=n?n[c+u]:c+u}}function Lc(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/Bt,u=2*Math.ceil(Math.sqrt(c/2)),d=new Float32Array(4*u*u),h=Math.ceil(Math.sqrt(c)),l=new Uint32Array(2*h*h);for(let v=0;v<c;v++){const b=v*Bt/4,T=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(T,o)){const x=Je(T,o),w=Xe(b,i),S=4294901760|x;l[v*2+0]=S,l[v*2+1]=w}else{const x=4*He(b,i)/Bt,w=oi(b,i);l[v*2+0]=w,l[v*2+1]=x}}e.image.data=d,e.image.width=u,e.image.height=u,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=h,t.image.height=h,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 Nc=`
30
+ <%s key={someKey} {...props} />`,Z,F,Y,F),lr[F+Z]=!0}}return m===r?an(T):on(T),T}}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 ce 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,ce)}static fromError(e,t,r){if(e instanceof ce)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 ce(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 X={ok(s){return{ok:!0,value:s}},err(s){return{ok:!1,error:s}},wrap(s){try{return X.ok(s())}catch(e){return X.err(e instanceof ce?e:new ce(String(e),ue.UNKNOWN,{originalError:e}))}}};class st{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 st({...this.data,isInitialized:!0,status:"idle"})}startLoading(){return new st({...this.data,status:"loading",loadProgress:0,error:null})}updateLoadProgress(e){return new st({...this.data,loadProgress:Math.min(Math.max(0,e),1)})}setLoaded(e){return new st({...this.data,status:"loaded",currentModel:e,loadProgress:1,error:null})}setError(e){return new st({...this.data,status:"error",error:e,loadProgress:0})}startRendering(){return new st({...this.data,status:"rendering"})}updateRenderInfo(e){return new st({...this.data,renderInfo:{...this.data.renderInfo,...e}})}dispose(){return new st({...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 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)}}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)}}function At(s){return s!==null&&typeof s=="object"&&"getInternalRenderer"in s&&typeof s.getInternalRenderer=="function"}class Oo{constructor(e){this.lastFrameTime=0,this.frameCount=0,this.screenshotElement=null,this.isShowingScreenshot=!1,this.pathTracingCompleteHandled=!1,this.disposed=!1,this.renderer=e.renderer,this.scene=e.scene,this.camera=e.camera,this.controls=e.controls,this.modelLoader=e.modelLoader,this.options=e.options,this.rendererOptions=e.rendererOptions,this.sceneSetupService=e.sceneSetupService,this.environmentService=e.environmentService,this.pathTracingService=e.pathTracingService,this.floorAlignmentService=e.floorAlignmentService,this.state=new st,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,u,d,h;try{const l=this.rendererOptions||{},v=this.renderer.initialize(l);if(!v.ok)return v;if(this.sceneSetupService){if(this.options.helpers){const b={grid:this.options.helpers.grid,axes:this.options.helpers.axes,gridColor:"#AAAAAA"},w=this.sceneSetupService.addHelpers(this.scene,b);w.ok||console.warn("Failed to add helpers:",w.error)}const _=this.options.lighting;if(_){const b={ambient:_.ambientLight?{color:String(_.ambientLight.color),intensity:_.ambientLight.intensity}:void 0,hemisphere:_.hemisphereLight?{skyColor:String(_.hemisphereLight.skyColor),groundColor:String(_.hemisphereLight.groundColor),intensity:_.hemisphereLight.intensity}:void 0,directional:_.directionalLight?{color:String(_.directionalLight.color),intensity:_.directionalLight.intensity,position:Array.isArray(_.directionalLight.position)?_.directionalLight.position:void 0,castShadow:_.directionalLight.castShadow,shadow:_.directionalLight.shadow}:void 0},w=this.sceneSetupService.addLighting(this.scene,b);w.ok||console.warn("Failed to add lighting:",w.error)}const g=(e=this.options.environment)==null?void 0:e.url;if(this.options.backgroundColor&&!g&&this.sceneSetupService){const b=this.sceneSetupService.createGradientBackground(this.scene,{topColor:String(this.options.backgroundColor),bottomColor:String(this.options.backgroundColor)});b.ok||console.warn("Failed to set background:",b.error)}}if(this.environmentService){const _=await this.environmentService.initialize({renderer:this.renderer,autoDispose:!0});_.ok||console.warn("Failed to initialize environment service:",_.error);const g=(t=this.options.environment)==null?void 0:t.url;if(g){const b=await this.environmentService.loadEnvironmentMap(g);b.ok?this.environmentService.applyToScene(this.scene,b.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:",b.error)}else if((i=this.options.helpers)!=null&&i.studioEnvironment){const b=this.environmentService.createStudioEnvironment();b.ok?this.environmentService.applyToScene(this.scene,b.value,{backgroundBlurriness:(a=this.options.environment)==null?void 0:a.backgroundBlurriness,backgroundIntensity:(c=this.options.environment)==null?void 0:c.backgroundIntensity,environmentIntensity:(u=this.options.environment)==null?void 0:u.environmentIntensity}):console.warn("Failed to create studio environment:",b.error)}}const x=((d=this.options.pathTracing)==null?void 0:d.enabled)??!1;if(this.pathTracingService&&x){const _=await this.pathTracingService.initialize({enabled:!0,renderer:this.renderer});_.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??x}),this.pathTracingService.events.on("pathtracing:paused",g=>{this.renderLoopManager.disableContinuousRendering(),this.options.staticScene||this.renderLoopManager.setAlwaysRender(!1),setTimeout(()=>{this.renderLoopManager.stop()},100)})):console.warn("Failed to initialize path tracing:",_.error)}if(this.state=this.state.setInitialized(),this.startRenderLoop(),!this.options.staticScene)this.renderLoopManager.setAlwaysRender(!0);else{const _=((h=this.options.pathTracing)==null?void 0:h.enabled)??!1;this.pathTracingService&&_&&this.renderLoopManager.enableContinuousRendering()}return this.renderLoopManager.requestRender(),X.ok(void 0)}catch(l){const v=new ce("Failed to initialize viewer",ue.INITIALIZATION_FAILED,{originalError:l});return this.state=this.state.setError(v),this.events.emit("error",{error:v}),X.err(v)}}async loadModel(e){var t,r;if(!this.state.canLoad())return X.err(new ce("Cannot load model in current state",ue.INVALID_STATE,{currentState:this.state.status,isInitialized:this.state.isInitialized}));try{this.state=this.state.startLoading();const n=performance.now();let o;if(typeof e=="string"){this.lastModelUrl=e;const u=await this.modelLoader.load(e);if(!u.ok)throw u.error;o=u.value.scene}else o=e;this.state.currentModel&&(this.scene.remove(this.state.currentModel),this.state.currentModel.dispose());const i=this.scene.add(o);if(!i.ok)throw i.error;if(this.floorAlignmentService){const u=this.floorAlignmentService.alignToFloor(o);u.ok||console.warn("Failed to align model to floor:",u.error)}if(o.traverse(u=>{"castShadow"in u&&"receiveShadow"in u&&(u.castShadow=!0,u.receiveShadow=!0)}),this.state=this.state.setLoaded(o),this.sceneSetupService){const u=this.sceneSetupService.addDynamicGrid(this.scene,o,2);u.ok||console.warn("Failed to add dynamic grid:",u.error)}if((t=this.options.camera)!=null&&t.autoFitToObject&&this.sceneSetupService){const u=this.sceneSetupService.fitCameraToObject(o,this.camera,this.controls);u.ok||console.warn("Failed to fit camera to object:",u.error)}const a=performance.now()-n;this.events.emit("model:loaded",{model:o,loadTime:a}),this.renderLoopManager.requestRender();const c=((r=this.options.pathTracing)==null?void 0:r.enabled)??!1;return this.pathTracingService&&c&&(this.pathTracingService.reset(),this.pathTracingCompleteHandled=!1),X.ok(void 0)}catch(n){const o=n instanceof ce?n:new ce("Failed to load model",ue.MODEL_LOAD_FAILED,{originalError:n,source:e});return this.state=this.state.setError(o),this.events.emit("model:error",{error:o,url:typeof e=="string"?e:void 0}),X.err(o)}}startRenderLoop(){this.renderLoopManager.start(e=>{var u,d,h,l,v;if(this.disposed){this.renderLoopManager.stop();return}if(!this.state.isInitialized||this.state.status==="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=((u=this.options.pathTracing)==null?void 0:u.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=((h=this.pathTracingService)==null?void 0:h.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.state=this.state.updateRenderInfo({frameCount:this.frameCount,fps:Math.round(r),lastRenderTime:performance.now()-t}),this.lastFrameTime=t})}stopRenderLoop(){this.renderLoopManager.stop()}async renderFrame(){var u,d,h,l;const e=performance.now();if(!this.renderer||!this.scene||!this.camera){console.warn("[ViewerCore] Cannot render - components not initialized");return}if(this.isShowingScreenshot)return;this.state=this.state.startRendering();let t;const r=((u=this.pathTracingService)==null?void 0:u.isEnabled())||!1,n=((d=this.pathTracingService)==null?void 0:d.getSampleCount())||0,o=((h=this.options.pathTracing)==null?void 0:h.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.state}onStateChange(e){const t=r=>{this.state=r,e(r)};return this.stateChangeCallback=t,()=>{this.stateChangeCallback=void 0}}getEvents(){return this.events}getDomElement(){return this.renderer.getDomElement()}replaceWithScreenshot(){if(this.isShowingScreenshot)return;const e=this.renderer.getDomElement(),t=e.toDataURL("image/png"),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="auto",r.style.cursor="grab";const n=e.parentElement;if(n){e.style.display="none",n.appendChild(r),this.screenshotElement=r,this.isShowingScreenshot=!0;const o=()=>{this.restoreFromScreenshot()};r.addEventListener("mousedown",o),r.addEventListener("touchstart",o);const i=()=>{this.isShowingScreenshot&&this.restoreFromScreenshot()};window.addEventListener("resize",i),this.screenshotResizeHandler=i,this.screenshotElement&&this.screenshotElement.src?this.disposeSceneResources():console.warn("[ViewerCore] Screenshot capture failed, keeping scene resources")}}async restoreFromScreenshot(){var r;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.pathTracingService&&((r=this.options.pathTracing)!=null&&r.enabled)&&console.warn("[ViewerCore] Cannot recreate path tracing service - feature disabled"),this.serializedSceneState&&await Zi.restore(this.serializedSceneState,this.camera,this.controls,async n=>{const o=await this.loadModel(n);o.ok||console.error("[ViewerCore] Failed to reload model:",o.error)}),this.renderLoopManager.isRunning()||this.startRenderLoop(),this.renderLoopManager.requestRender())}disposeSceneResources(){var e;Zn.logMemoryUsage("Before disposal"),this.renderLoopManager.stop(),this.serializedSceneState=Zi.serialize(this.lastModelUrl,this.camera,this.controls,this.renderer.getDomElement()),this.pathTracingService,this.environmentService&&this.environmentService.dispose(),this.state.currentModel&&(this.scene.remove(this.state.currentModel),this.disposeObject(this.state.currentModel),this.state=new st().setInitialized()),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(),globalThis.gc&&((e=globalThis.gc)==null||e.call(globalThis)),Zn.logMemoryUsage("After disposal"),setTimeout(()=>{Zn.logMemoryUsage("After GC delay")},2e3)}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.disposed=!0,this.stopRenderLoop(),this.state.currentModel&&(this.scene.remove(this.state.currentModel),this.state.currentModel.dispose()),this.pathTracingService&&this.pathTracingService.dispose(),this.environmentService&&this.environmentService.dispose(),this.scene.clear(),this.controls.dispose(),this.renderer.dispose(),this.state=this.state.dispose(),this.events.removeAllListeners()}}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()),X.ok(void 0)):X.err(new ce("Child must be a ThreeObject3DAdapter",ue.INVALID_PARAMETER))}catch(t){return X.err(new ce("Failed to add child object",ue.SCENE_OPERATION_FAILED,{originalError:t}))}}remove(e){try{return e instanceof We?(this.object.remove(e.getThreeObject()),X.ok(void 0)):X.err(new ce("Child must be a ThreeObject3DAdapter",ue.INVALID_PARAMETER))}catch(t){return X.err(new ce("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()),X.ok(void 0)):X.err(new ce("Object must be a ThreeObject3DAdapter",ue.INVALID_PARAMETER))}catch(t){return X.err(new ce("Failed to add object to scene",ue.SCENE_OPERATION_FAILED,{originalError:t}))}}remove(e){try{return e instanceof We?(this.scene.remove(e.getThreeObject()),X.ok(void 0)):X.err(new ce("Object must be a ThreeObject3DAdapter",ue.INVALID_PARAMETER))}catch(t){return X.err(new ce("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 Lo{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,X.ok(void 0)}catch(t){return X.err(new ce("Failed to initialize renderer",ue.RENDERER_INIT_FAILED,{originalError:t,options:e}))}}render(e,t){if(!this.renderer)return X.err(new ce("Renderer not initialized",ue.RENDERER_NOT_INITIALIZED));try{if(!(e instanceof Yt))return X.err(new ce("Scene must be a ThreeSceneAdapter",ue.INVALID_PARAMETER));if(!(t instanceof Xn))return X.err(new ce("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"),X.ok(void 0)):(this.renderer.render(r,n),X.ok(void 0))}catch(r){return X.err(new ce("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 No extends f.Loader{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new Uo(t)}),this.register(function(t){return new Go(t)}),this.register(function(t){return new $o(t)}),this.register(function(t){return new Qo(t)}),this.register(function(t){return new Jo(t)}),this.register(function(t){return new jo(t)}),this.register(function(t){return new Wo(t)}),this.register(function(t){return new Yo(t)}),this.register(function(t){return new qo(t)}),this.register(function(t){return new Eo(t)}),this.register(function(t){return new Zo(t)}),this.register(function(t){return new Vo(t)}),this.register(function(t){return new Xo(t)}),this.register(function(t){return new Ko(t)}),this.register(function(t){return new Bo(t)}),this.register(function(t){return new Ho(t)}),this.register(function(t){return new ea(t)})}load(e,t,r,n){const o=this;let i;if(this.resourcePath!=="")i=this.resourcePath;else if(this.path!==""){const u=f.LoaderUtils.extractUrlBase(e);i=f.LoaderUtils.resolveURL(u,this.path)}else i=f.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const a=function(u){n?n(u):console.error(u),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(u){try{o.parse(u,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 ta(e)}catch(h){n&&n(h);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 u=new pa(o,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});u.fileLoader.setRequestHeader(this.requestHeader);for(let d=0;d<this.pluginCallbacks.length;d++){const h=this.pluginCallbacks[d](u);h.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),a[h.name]=h,i[h.name]=!0}if(o.extensionsUsed)for(let d=0;d<o.extensionsUsed.length;++d){const h=o.extensionsUsed[d],l=o.extensionsRequired||[];switch(h){case fe.KHR_MATERIALS_UNLIT:i[h]=new zo;break;case fe.KHR_DRACO_MESH_COMPRESSION:i[h]=new ra(o,this.dracoLoader);break;case fe.KHR_TEXTURE_TRANSFORM:i[h]=new na;break;case fe.KHR_MESH_QUANTIZATION:i[h]=new ia;break;default:l.indexOf(h)>=0&&a[h]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+h+'".')}}u.setExtensions(i),u.setPlugins(a),u.parse(r,n)}parseAsync(e,t){const r=this;return new Promise(function(n,o){r.parse(e,t,n,o)})}}function ko(){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 Bo{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 u;const d=new f.Color(16777215);c.color!==void 0&&d.setRGB(c.color[0],c.color[1],c.color[2],f.LinearSRGBColorSpace);const h=c.range!==void 0?c.range:0;switch(c.type){case"directional":u=new f.DirectionalLight(d),u.target.position.set(0,0,-1),u.add(u.target);break;case"point":u=new f.PointLight(d),u.distance=h;break;case"spot":u=new f.SpotLight(d),u.distance=h,c.spot=c.spot||{},c.spot.innerConeAngle=c.spot.innerConeAngle!==void 0?c.spot.innerConeAngle:0,c.spot.outerConeAngle=c.spot.outerConeAngle!==void 0?c.spot.outerConeAngle:Math.PI/4,u.angle=c.spot.outerConeAngle,u.penumbra=1-c.spot.innerConeAngle/c.spot.outerConeAngle,u.target.position.set(0,0,-1),u.add(u.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+c.type)}return u.position.set(0,0,0),u.decay=2,Mt(u,c),c.intensity!==void 0&&(u.intensity=c.intensity),u.name=t.createUniqueName(c.name||"light_"+e),n=Promise.resolve(u),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 zo{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 Eo{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 Uo{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 Go{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 Vo{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 jo{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 Wo{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 Yo{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 Zo{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 Ko{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 Xo{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 $o{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 Qo{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 u=r.options.manager.getHandler(a.uri);u!==null&&(c=u)}return this.detectSupport().then(function(u){if(u)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 Jo{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 u=r.options.manager.getHandler(a.uri);u!==null&&(c=u)}return this.detectSupport().then(function(u){if(u)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 Ho{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,u=n.byteLength||0,d=n.count,h=n.byteStride,l=new Uint8Array(a,c,u);return i.decodeGltfBufferAsync?i.decodeGltfBufferAsync(d,h,l,n.mode,n.filter).then(function(v){return v.buffer}):i.ready.then(function(){const v=new ArrayBuffer(d*h);return i.decodeGltfBuffer(new Uint8Array(v),d,h,l,n.mode,n.filter),v})})}else return null}}class ea{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 u of n.primitives)if(u.mode!==ot.TRIANGLES&&u.mode!==ot.TRIANGLE_STRIP&&u.mode!==ot.TRIANGLE_FAN&&u.mode!==void 0)return null;const i=r.extensions[this.name].attributes,a=[],c={};for(const u in i)a.push(this.parser.getDependency("accessor",i[u]).then(d=>(c[u]=d,c[u])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(u=>{const d=u.pop(),h=d.isGroup?d.children:[d],l=u[0].count,v=[];for(const x of h){const _=new f.Matrix4,g=new f.Vector3,b=new f.Quaternion,w=new f.Vector3(1,1,1),S=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),S.setMatrixAt(A,_.compose(g,b,w));for(const A in c)if(A==="_COLOR_0"){const P=c[A];S.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(S,x),this.parser.assignFinalMaterial(S),v.push(S)}return d.isGroup?(d.clear(),d.add(...v),d):v[0]}))}}const $i="glTF",zr=12,Qi={JSON:1313821514,BIN:5130562};class ta{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 u=new Uint8Array(e,zr+i,a);this.content=r.decode(u)}else if(c===Qi.BIN){const u=zr+i;this.body=e.slice(u,u+a)}i+=a}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class ra{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={},u={};for(const d in i){const h=Jn[d]||d.toLowerCase();a[h]=i[d]}for(const d in e.attributes){const h=Jn[d]||d.toLowerCase();if(i[d]!==void 0){const l=r.accessors[e.attributes[d]],v=hr[l.componentType];u[h]=v.name,c[h]=l.normalized===!0}}return t.getDependency("bufferView",o).then(function(d){return new Promise(function(h,l){n.decodeDracoFile(d,function(v){for(const x in v.attributes){const _=v.attributes[x],g=c[x];g!==void 0&&(_.normalized=g)}h(v)},a,u,f.LinearSRGBColorSpace,l)})})}}class na{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 ia{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,u=a*3,d=n-t,h=(r-t)/d,l=h*h,v=l*h,x=e*u,_=x-u,g=-2*v+3*l,b=v-l,w=1-g,S=b-l+h;for(let A=0;A!==a;A++){const P=i[_+A+a],D=i[_+A+c]*d,R=i[x+A+a],O=i[x+A]*d;o[A]=w*P+S*D+g*R+b*O}return o}}const sa=new f.Quaternion;class oa extends Ji{interpolate_(e,t,r,n){const o=super.interpolate_(e,t,r,n);return sa.fromArray(o).normalize().toArray(o),o}}const ot={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"},aa={CUBICSPLINE:void 0,LINEAR:f.InterpolateLinear,STEP:f.InterpolateDiscrete},Hn={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function ca(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 la(s,e,t){let r=!1,n=!1,o=!1;for(let u=0,d=e.length;u<d;u++){const h=e[u];if(h.POSITION!==void 0&&(r=!0),h.NORMAL!==void 0&&(n=!0),h.COLOR_0!==void 0&&(o=!0),r&&n&&o)break}if(!r&&!n&&!o)return Promise.resolve(s);const i=[],a=[],c=[];for(let u=0,d=e.length;u<d;u++){const h=e[u];if(r){const l=h.POSITION!==void 0?t.getDependency("accessor",h.POSITION):s.attributes.position;i.push(l)}if(n){const l=h.NORMAL!==void 0?t.getDependency("accessor",h.NORMAL):s.attributes.normal;a.push(l)}if(o){const l=h.COLOR_0!==void 0?t.getDependency("accessor",h.COLOR_0):s.attributes.color;c.push(l)}}return Promise.all([Promise.all(i),Promise.all(a),Promise.all(c)]).then(function(u){const d=u[0],h=u[1],l=u[2];return r&&(s.morphAttributes.position=d),n&&(s.morphAttributes.normal=h),o&&(s.morphAttributes.color=l),s.morphTargetsRelative=!0,s})}function ua(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 ha(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 fa(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 da=new f.Matrix4;class pa{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new ko,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[u,d]of i.children.entries())o(d,a.children[u])};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,u=new a(n.count*i);return Promise.resolve(new f.BufferAttribute(u,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],u=hr[n.componentType],d=u.BYTES_PER_ELEMENT,h=d*c,l=n.byteOffset||0,v=n.bufferView!==void 0?r.bufferViews[n.bufferView].byteStride:void 0,x=n.normalized===!0;let _,g;if(v&&v!==h){const b=Math.floor(l/v),w="InterleavedBuffer:"+n.bufferView+":"+n.componentType+":"+b+":"+n.count;let S=t.cache.get(w);S||(_=new u(a,b*v,n.count*v/d),S=new f.InterleavedBuffer(_,v/d),t.cache.add(w,S)),g=new f.InterleavedBufferAttribute(S,c,l%v/d,x)}else a===null?_=new u(n.count*c):_=new u(a,l,n.count*c),g=new f.BufferAttribute(_,c,x);if(n.sparse!==void 0){const b=Qn.SCALAR,w=hr[n.sparse.indices.componentType],S=n.sparse.indices.byteOffset||0,A=n.sparse.values.byteOffset||0,P=new w(i[1],S,n.sparse.count*b),D=new u(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 u=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]=u,u}loadImageSource(e,t){const r=this,n=this.json,o=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(h=>h.clone());const i=n.images[e],a=self.URL||self.webkitURL;let c=i.uri||"",u=!1;if(i.bufferView!==void 0)c=r.getDependency("bufferView",i.bufferView).then(function(h){u=!0;const l=new Blob([h],{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(h){return new Promise(function(l,v){let x=l;t.isImageBitmapLoader===!0&&(x=function(_){const g=new f.Texture(_);g.needsUpdate=!0,l(g)}),t.load(f.LoaderUtils.resolveURL(h,o.path),x,void 0,v)})}).then(function(h){return u===!0&&a.revokeObjectURL(c),Mt(h,i),h.userData.mimeType=i.mimeType||fa(i.uri),h}).catch(function(h){throw console.error("THREE.GLTFLoader: Couldn't load texture",c),h});return this.sourceCache[e]=d,d}assignTexture(e,t,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||{},u=[];if(c[fe.KHR_MATERIALS_UNLIT]){const h=n[fe.KHR_MATERIALS_UNLIT];i=h.getMaterialType(),u.push(h.extendParams(a,o,t))}else{const h=o.pbrMetallicRoughness||{};if(a.color=new f.Color(1,1,1),a.opacity=1,Array.isArray(h.baseColorFactor)){const l=h.baseColorFactor;a.color.setRGB(l[0],l[1],l[2],f.LinearSRGBColorSpace),a.opacity=l[3]}h.baseColorTexture!==void 0&&u.push(t.assignTexture(a,"map",h.baseColorTexture,f.SRGBColorSpace)),a.metalness=h.metallicFactor!==void 0?h.metallicFactor:1,a.roughness=h.roughnessFactor!==void 0?h.roughnessFactor:1,h.metallicRoughnessTexture!==void 0&&(u.push(t.assignTexture(a,"metalnessMap",h.metallicRoughnessTexture)),u.push(t.assignTexture(a,"roughnessMap",h.metallicRoughnessTexture))),i=this._invokeOne(function(l){return l.getMaterialType&&l.getMaterialType(e)}),u.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&&(u.push(t.assignTexture(a,"normalMap",o.normalTexture)),a.normalScale=new f.Vector2(1,1),o.normalTexture.scale!==void 0)){const h=o.normalTexture.scale;a.normalScale.set(h,h)}if(o.occlusionTexture!==void 0&&i!==f.MeshBasicMaterial&&(u.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 h=o.emissiveFactor;a.emissive=new f.Color().setRGB(h[0],h[1],h[2],f.LinearSRGBColorSpace)}return o.emissiveTexture!==void 0&&i!==f.MeshBasicMaterial&&u.push(t.assignTexture(a,"emissiveMap",o.emissiveTexture,f.SRGBColorSpace)),Promise.all(u).then(function(){const h=new i(a);return o.name&&(h.name=o.name),Mt(h,o),t.associations.set(h,{materials:e}),o.extensions&&qt(n,h,o),h})}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 u=e[a],d=ha(u),h=n[d];if(h)i.push(h.promise);else{let l;u.extensions&&u.extensions[fe.KHR_DRACO_MESH_COMPRESSION]?l=o(u):l=ts(new f.BufferGeometry,u,t),n[d]={primitive:u,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,u=i.length;c<u;c++){const d=i[c].material===void 0?ca(this.cache):this.getDependency("material",i[c].material);a.push(d)}return a.push(t.loadGeometries(i)),Promise.all(a).then(function(c){const u=c.slice(0,c.length-1),d=c[c.length-1],h=[];for(let v=0,x=d.length;v<x;v++){const _=d[v],g=i[v];let b;const w=u[v];if(g.mode===ot.TRIANGLES||g.mode===ot.TRIANGLE_STRIP||g.mode===ot.TRIANGLE_FAN||g.mode===void 0)b=o.isSkinnedMesh===!0?new f.SkinnedMesh(_,w):new f.Mesh(_,w),b.isSkinnedMesh===!0&&b.normalizeSkinWeights(),g.mode===ot.TRIANGLE_STRIP?b.geometry=Xi(b.geometry,f.TriangleStripDrawMode):g.mode===ot.TRIANGLE_FAN&&(b.geometry=Xi(b.geometry,f.TriangleFanDrawMode));else if(g.mode===ot.LINES)b=new f.LineSegments(_,w);else if(g.mode===ot.LINE_STRIP)b=new f.Line(_,w);else if(g.mode===ot.LINE_LOOP)b=new f.LineLoop(_,w);else if(g.mode===ot.POINTS)b=new f.Points(_,w);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+g.mode);Object.keys(b.geometry.morphAttributes).length>0&&ua(b,o),b.name=t.createUniqueName(o.name||"mesh_"+e),Mt(b,o),g.extensions&&qt(n,b,g),t.assignFinalMaterial(b),h.push(b)}for(let v=0,x=h.length;v<x;v++)t.associations.set(h[v],{meshes:e,primitives:v});if(h.length===1)return o.extensions&&qt(n,h[0],o),h[0];const l=new f.Group;o.extensions&&qt(n,l,o),t.associations.set(l,{meshes:e});for(let v=0,x=h.length;v<x;v++)l.add(h[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 u=0,d=i.length;u<d;u++){const h=i[u];if(h){a.push(h);const l=new f.Matrix4;o!==null&&l.fromArray(o.array,u*16),c.push(l)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[u])}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=[],u=[],d=[];for(let h=0,l=n.channels.length;h<l;h++){const v=n.channels[h],x=n.samplers[v.sampler],_=v.target,g=_.node,b=n.parameters!==void 0?n.parameters[x.input]:x.input,w=n.parameters!==void 0?n.parameters[x.output]:x.output;_.node!==void 0&&(i.push(this.getDependency("node",g)),a.push(this.getDependency("accessor",b)),c.push(this.getDependency("accessor",w)),u.push(x),d.push(_))}return Promise.all([Promise.all(i),Promise.all(a),Promise.all(c),Promise.all(u),Promise.all(d)]).then(function(h){const l=h[0],v=h[1],x=h[2],_=h[3],g=h[4],b=[];for(let w=0,S=l.length;w<S;w++){const A=l[w],P=v[w],D=x[w],R=_[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,u=n.weights.length;c<u;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 u=0,d=a.length;u<d;u++)i.push(r.getDependency("node",a[u]));const c=n.skin===void 0?Promise.resolve(null):r.getDependency("skin",n.skin);return Promise.all([o,Promise.all(i),c]).then(function(u){const d=u[0],h=u[1],l=u[2];l!==null&&d.traverse(function(v){v.isSkinnedMesh&&v.bind(l,da)});for(let v=0,x=h.length;v<x;v++)d.add(h[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(u){return u.createNodeMesh&&u.createNodeMesh(e)});return c&&a.push(c),o.camera!==void 0&&a.push(n.getDependency("camera",o.camera).then(function(u){return n._getNodeRef(n.cameraCache,o.camera,u)})),n._invokeAll(function(u){return u.createNodeAttachment&&u.createNodeAttachment(e)}).forEach(function(u){a.push(u)}),this.nodeCache[e]=Promise.all(a).then(function(u){let d;if(o.isBone===!0?d=new f.Bone:u.length>1?d=new f.Group:u.length===1?d=u[0]:d=new f.Object3D,d!==u[0])for(let h=0,l=u.length;h<l;h++)d.add(u[h]);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 h=new f.Matrix4;h.fromArray(o.matrix),d.applyMatrix4(h)}else o.translation!==void 0&&d.position.fromArray(o.translation),o.rotation!==void 0&&d.quaternion.fromArray(o.rotation),o.scale!==void 0&&d.scale.fromArray(o.scale);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,u=i.length;c<u;c++)a.push(n.getDependency("node",i[c]));return Promise.all(a).then(function(c){for(let d=0,h=c.length;d<h;d++)o.add(c[d]);const u=d=>{const h=new Map;for(const[l,v]of n.associations)(l instanceof f.Material||l instanceof f.Texture)&&h.set(l,v);return d.traverse(l=>{const v=n.associations.get(l);v!=null&&h.set(l,v)}),h};return n.associations=u(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 u;switch(Bt[o.path]){case Bt.weights:u=f.NumberKeyframeTrack;break;case Bt.rotation:u=f.QuaternionKeyframeTrack;break;case Bt.position:case Bt.scale:u=f.VectorKeyframeTrack;break;default:switch(r.itemSize){case 1:u=f.NumberKeyframeTrack;break;case 2:case 3:default:u=f.VectorKeyframeTrack;break}break}const d=n.interpolation!==void 0?aa[n.interpolation]:f.InterpolateLinear,h=this._getArrayFromAccessor(r);for(let l=0,v=c.length;l<v;l++){const x=new u(c[l]+"."+Bt[o.path],t.array,h,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?oa:Ji;return new n(this.times,this.values,this.getValueSize()/3,r)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function ma(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,u=a.max;if(c!==void 0&&u!==void 0){if(n.set(new f.Vector3(c[0],c[1],c[2]),new f.Vector3(u[0],u[1],u[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 u=0,d=o.length;u<d;u++){const h=o[u];if(h.POSITION!==void 0){const l=t.json.accessors[h.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 _=ti(hr[l.componentType]);c.multiplyScalar(_)}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),ma(s,e,t),Promise.all(n).then(function(){return e.targets!==void 0?la(s,e.targets,t):s})}class ga{constructor(){this.loadingManager=new M.LoadingManager,this.loader=new No(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(X.ok(n))},r=>{if(r.total>0){const n=r.loaded/r.total*100;console.log(`Loading: ${n.toFixed(0)}%`)}},r=>{t(X.err(new ce("Failed to load GLTF model",ue.MODEL_LOAD_FAILED,{url:e,originalError:r})))})})}catch(t){return X.err(new ce("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 ga;default:throw new ce(`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,va=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=xa.bind(this),this._onPointerDown=ya.bind(this),this._onPointerUp=ba.bind(this),this._onContextMenu=Ia.bind(this),this._onMouseWheel=Ta.bind(this),this._onKeyDown=Sa.bind(this),this._onTouchStart=Aa.bind(this),this._onTouchMove=Ma.bind(this),this._onMouseDown=wa.bind(this),this._onMouseMove=_a.bind(this),this._interceptControlDown=Ca.bind(this),this._interceptControlUp=Pa.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 u=new f.Vector3(this._mouse.x,this._mouse.y,0);u.unproject(this.object),this.object.position.sub(u).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))<va?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 ya(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 xa(s){this.enabled!==!1&&(s.pointerType==="touch"?this._onTouchMove(s):this._onMouseMove(s))}function ba(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 wa(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 _a(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 Ta(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 Sa(s){this.enabled===!1||this.enablePan===!1||this._handleKeyDown(s)}function Aa(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 Ma(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 Ia(s){this.enabled!==!1&&s.preventDefault()}function Ca(s){s.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function Pa(s){s.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}class Da 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 Da(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 Ra{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 Fa{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),u=n*2;for(let h=-r;h<=r;h++){const l=Math.max(-r,-h-r),v=Math.min(r,-h+r);for(let x=l;x<=v;x++){const _=c*(h+x/2),g=u*.75*x,b=[],w=Math.PI*2/6;for(let P=0;P<=6;P++){const D=P*w+Math.PI/6,R=_+n*Math.cos(D),O=g+n*Math.sin(D);b.push(new M.Vector3(R,0,O))}const S=new M.BufferGeometry().setFromPoints(b),A=new M.Line(S,a);t.add(A)}}return t}dispose(){}}class Oa{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 u=0;u<6;u++){const d=t*Math.cos(u*r),h=t*Math.sin(u*r);u===0?e.moveTo(d,h):e.lineTo(d,h)}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 La{constructor(){this.name="Hexagonal Glass Grid"}createGrid(e){var u,d;const t=new M.Group,r=((u=e.styleOptions)==null?void 0:u.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 h=-r;h<=r;h++){const l=Math.max(-r,-h-r),v=Math.min(r,-h+r);for(let x=l;x<=v;x++){const _=a*(h+x/2),g=c*.75*x,b=Zt.getYPosition(n),S=new Oa(new M.Vector3(_,b,g),n,o).createMesh();t.add(S)}}return t}dispose(){}}class Na{constructor(){this.name="Stone Tile Grid",this.textureLoader=new M.TextureLoader,this.loadedTextures=new Map}createGrid(e){var v,x,_,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,u=((x=e.styleOptions)==null?void 0:x.bevelSize)||c*.2,d=((_=e.styleOptions)==null?void 0:_.randomHeight)||!1,h=((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 S=(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:u,bevelThickness:u,bevelSegments:2},L=new M.ExtrudeGeometry(D,O);L.rotateX(-Math.PI/2);const E=new M.Mesh(L,l);E.position.set(S,-P/2,A),E.castShadow=!0,E.receiveShadow=!0,h&&(E.rotation.y=Math.floor(Math.random()*4)*(Math.PI/2)),t.add(E)}return t}createStoneMaterial(e){var i,a,c,u,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 h=this.loadTexture(e.styleOptions.texture);h&&(o.map=h,h.wrapS=h.wrapT=M.RepeatWrapping,h.repeat.set(1,1))}if((u=e.styleOptions)!=null&&u.normalMap){const h=this.loadTexture(e.styleOptions.normalMap);h&&(o.normalMap=h,h.wrapS=h.wrapT=M.RepeatWrapping,h.repeat.set(1,1))}if((d=e.styleOptions)!=null&&d.roughnessMap){const h=this.loadTexture(e.styleOptions.roughnessMap);h&&(o.roughnessMap=h,h.wrapS=h.wrapT=M.RepeatWrapping,h.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 Ra],[It.HEXAGONAL_WIRE,new Fa],[It.HEXAGONAL_GLASS,new La],[It.STONE_TILES,new Na]]);let gn=ji;class ka{addHelpers(e,t){try{if(!(e instanceof Yt))return X.err(new ce("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,u=o.divisions||10,d={size:c,divisions:u,color:i.color,opacity:i.opacity,styleOptions:{hexRadius:Math.floor(u/2),tileSize:1,...i.styleOptions}},h=gn.createGrid(a,d);h.userData.isGrid=!0,h.userData.isDefaultGrid=!0,r.add(h)}}if(t.axes){const n=t.axesSize||5,o=new M.AxesHelper(n);r.add(o)}return X.ok(void 0)}catch(r){return X.err(new ce("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 X.err(new ce("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 X.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,_=Math.max(d.x,d.z)*r;let g=0,b=x;for(;b<_&&g<20;)g++,b+=2*x;_<x*.8?g=0:g<3&&_>x*2&&(g=3),console.log("Grid parameters:",{tileSize:l,gridRadius:g,requiredWidth:_,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),X.ok(void 0)}catch(n){return X.err(new ce("Failed to add dynamic grid",ue.SCENE_OPERATION_FAILED,{originalError:n}))}}addLighting(e,t){try{if(!(e instanceof Yt))return X.err(new ce("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 X.ok(void 0)}catch(r){return X.err(new ce("Failed to add lighting to scene",ue.SCENE_OPERATION_FAILED,{originalError:r,options:t}))}}createGradientBackground(e,t){try{if(!(e instanceof Yt))return X.err(new ce("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 X.err(new ce("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,X.ok(void 0)}catch(r){return X.err(new ce("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),u=a.getSize(new M.Vector3);console.log("Fitting camera to object:",{center:c,size:u,maxDimension:Math.max(u.x,u.y,u.z)});const d=Math.max(u.x,u.y,u.z);let h;"fov"in o?h=o.fov*(Math.PI/180):h=50*(Math.PI/180);let l=Math.abs(d/2/Math.tan(h/2));l*=2;const v=-Math.PI/4,x=Math.PI/8,_=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(_,g,b),o.lookAt(c),o.updateProjectionMatrix(),i&&i.target&&(i.target.copy(c),i.update()),console.log("Camera positioned at:",{x:_,y:g,z:b}),console.log("Looking at:",c),X.ok(void 0)}catch(n){return X.err(new ce("Failed to fit camera to object",ue.CAMERA_INIT_FAILED,{originalError:n}))}}}const us=0,Ba=1,hs=2,fs=2,ii=1.25,ds=1,zt=6*4+4+4,vn=65535,za=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 Ea(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 u=c.start/3,d=(c.start+c.count)/3;r.add(Math.max(o,u)),r.add(Math.min(i,d))}const a=Array.from(r.values()).sort((c,u)=>c-u);for(let c=0;c<a.length-1;c++){const u=a[c],d=a[c+1];t.push({offset:Math.floor(u),count:Math.floor(d-u)})}return t}function Ua(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,u=-1/0,d=-1/0,h=1/0,l=1/0,v=1/0,x=-1/0,_=-1/0,g=-1/0;for(let b=e*6,w=(e+t)*6;b<w;b+=6){const S=s[b+0],A=s[b+1],P=S-A,D=S+A;P<o&&(o=P),D>c&&(c=D),S<h&&(h=S),S>x&&(x=S);const R=s[b+2],O=s[b+3],L=R-O,E=R+O;L<i&&(i=L),E>u&&(u=E),R<l&&(l=R),R>_&&(_=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]=u,r[5]=d,n[0]=h,n[1]=l,n[2]=v,n[3]=x,n[4]=_,n[5]=g}function Ga(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 u=n.array,d=n.offset||0;let h=3;n.isInterleavedBufferAttribute&&(h=n.data.stride);const l=["getX","getY","getZ"];for(let v=t;v<t+r;v++){const x=v*3,_=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*h+d,b=b*h+d,w=w*h+d);for(let S=0;S<3;S++){let A,P,D;a?(A=n[l[S]](g),P=n[l[S]](b),D=n[l[S]](w)):(A=u[g+S],P=u[b+S],D=u[w+S]);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=S*2;c[_+E+0]=R+L,c[_+E+1]=L+(Math.abs(R)+L)*za}}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,Va=(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 ja(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===Ba)i=ys(s),i!==-1&&(a=Wa(t,r,n,i));else if(o===hs){const c=Er(s);let u=ii*n;const d=r*6,h=(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<h;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(Va);let S=n;for(let A=0;A<S;A++){const P=b[A];for(;A+1<S&&b[A+1].candidate===P.candidate;)b.splice(A+1,1),S--}for(let A=d;A<h;A+=6){const P=t[A+2*l];for(let D=0;D<S;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<S;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<u&&(i=l,u=z,a=P.candidate)}}else{for(let S=0;S<Ct;S++){const A=Et[S];A.count=0,A.candidate=v+g+S*g;const P=A.bounds;for(let D=0;D<3;D++)P[D]=1/0,P[D+3]=-1/0}for(let S=d;S<h;S+=6){let D=~~((t[S+2*l]-v)/g);D>=Ct&&(D=Ct-1);const R=Et[D];R.count++,yn(S,t,R.bounds)}const b=Et[Ct-1];xs(b.bounds,b.rightCacheBounds);for(let S=Ct-2;S>=0;S--){const A=Et[S],P=Et[S+1];bs(A.bounds,P.rightCacheBounds,A.rightCacheBounds)}let w=0;for(let S=0;S<Ct-1;S++){const A=Et[S],P=A.count,D=A.bounds,O=Et[S+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<u&&(i=l,u=z,a=A.candidate)}}}}else console.warn(`MeshBVH: Invalid build strategy value ${o} used.`);return{axis:i,pos:a}}function Wa(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 Ya(s,e,t,r,n,o){let i=r,a=r+n-1;const c=o.pos,u=o.axis*2;for(;;){for(;i<=a&&t[i*6+u]<c;)i++;for(;i<=a&&t[a*6+u]>=c;)a--;if(i<a){for(let d=0;d<3;d++){let h=e[i*3+d];e[i*3+d]=e[a*3+d],e[a*3+d]=h}for(let d=0;d<6;d++){let h=t[i*6+d];t[i*6+d]=t[a*6+d],t[a*6+d]=h}i++,a--}else return i}}function qa(s,e,t,r,n,o){let i=r,a=r+n-1;const c=o.pos,u=o.axis*2;for(;;){for(;i<=a&&t[i*6+u]<c;)i++;for(;i<=a&&t[a*6+u]>=c;)a--;if(i<a){let d=s[i];s[i]=s[a],s[a]=d;for(let h=0;h<6;h++){let l=t[i*6+h];t[i*6+h]=t[a*6+h],t[a*6+h]=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 at(s){return s+8}function He(s,e){return e[s+6]}function ci(s,e){return e[s+7]}function Vh(s){return s}let ws,Ur,bn,_s;const Za=Math.pow(2,32);function li(s){return"count"in s?1:1+li(s.left)+li(s.right)}function Ka(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 u=a/2;Ye(u,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 u;if(u=ui(s+zt,i),u/4>Za)throw new Error("MeshBVH: Cannot store child pointer greater than 32 bits.");return Ur[t+6]=u/4,u=ui(u,a),Ur[t+7]=c,u}}function Xa(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 $a(s,e,t,r,n){const{maxDepth:o,verbose:i,maxLeafTris:a,strategy:c,onProgress:u,indirect:d}=n,h=s._indirectBuffer,l=s.geometry,v=l.index?l.index.array:null,x=d?qa:Ya,_=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 S(P){u&&u(P/_)}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 S(D+R),P.offset=D,P.count=R,P;const E=ja(P.boundingData,O,e,D,R,c);if(E.axis===-1)return S(D+R),P.offset=D,P.count=R,P;const G=x(h,v,e,D,R,E);if(G===D||G===D+R)S(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 Qa(s,e){const t=s.geometry;e.indirect&&(s._indirectBuffer=Xa(t,e.useSharedArrayBuffer),Ua(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||Ea(t,e);const r=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=Ga(t),o=e.indirect?gs(t,e.range):vs(t,e.range);s._roots=o.map(i=>{const a=$a(s,n,i.offset,i.count,e),c=li(a),u=new r(zt*c);return Ka(0,a,u),u})}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 u=0;u<=1;u++)for(let d=0;d<=1;d++){s.x=n.x*c+o.x*(1-c),s.y=n.y*u+o.y*(1-u),s.z=n.z*d+o.z*(1-d);const h=t.dot(s);i=Math.min(h,i),a=Math.max(h,a)}this.min=i,this.max=a}}();const Ja=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,u=o.start,d=e;t.subVectors(a,u),s.subVectors(n.end,n.start),e.subVectors(o.end,o.start);const h=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=(h*l-x*v)/g:b=0,w=(h+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){Ja(n,o,s);let c=s.x,u=s.y;if(c>=0&&c<=1&&u>=0&&u<=1){n.at(c,i),o.at(u,a);return}else if(c>=0&&c<=1){u<0?o.at(0,a):o.at(1,a),n.closestPointToPoint(a,!0,i);return}else if(u>=0&&u<=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 h;u<0?h=o.start:h=o.end;const l=e,v=t;if(n.closestPointToPoint(h,!0,e),o.closestPointToPoint(d,!0,t),l.distanceToSquared(h)<=v.distanceToSquared(d)){i.copy(l),a.copy(h);return}else{i.copy(d),a.copy(v);return}}}}(),Ha=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:u,b:d,c:h}=i;if(r.start=u,r.end=d,r.closestPointToPoint(c,!0,s).distanceTo(c)<=a||(r.start=u,r.end=h,r.closestPointToPoint(c,!0,s).distanceTo(c)<=a)||(r.start=d,r.end=h,r.closestPointToPoint(c,!0,s).distanceTo(c)<=a))return!0;const _=i.getPlane(t);if(Math.abs(_.distanceToPoint(c))<=a){const b=_.projectPoint(c,e);if(i.containsPoint(b))return!0}return!1}}(),ec=1e-15;function fi(s){return Math.abs(s)<ec}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 Ha(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 u=o[1],d=i[1];u.subVectors(e,t),d.setFromPoints(u,n);const h=o[2],l=i[2];h.subVectors(t,r),l.setFromPoints(h,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,u=this.points;let d,h=1/0;for(let l=0;l<3;l++){const v=(l+1)%3;t.start.copy(u[l]),t.end.copy(u[v]),hi(t,n,s,e),d=s.distanceToSquared(e),d<h&&(h=d,o&&o.copy(s),i&&i.copy(e))}return this.closestPointToPoint(a,s),d=a.distanceToSquared(s),d<h&&(h=d,o&&o.copy(s),i&&i.copy(a)),this.closestPointToPoint(c,s),d=c.distanceToSquared(s),d<h&&(h=d,o&&o.copy(s),i&&i.copy(c)),Math.sqrt(h)}}(),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,u=new f.Vector3,d=new f.Line3,h=new f.Line3,l=new f.Line3,v=new f.Vector3;function x(_,g,b){const w=_.points;let S=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),S=2;break}const L=g.intersectLine(d,v);if(!L&&O&&v.copy(D),(L||O)&&!fi(v.distanceTo(R))){if(S<=1)(S===1?b.start:b.end).copy(v),O&&(A=S);else if(S>=2){(A===1?b.start:b.end).copy(v),S=2;break}if(S++,S===2&&A===-1)break}}return S}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 S=this.plane,A=g.plane;if(Math.abs(S.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,h);if(P===1&&g.containsPoint(h.end))return b&&(b.start.copy(h.end),b.end.copy(h.end)),!0;if(P!==2)return!1;const D=x(g,S,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(h.delta(a),l.delta(c),a.dot(c)<0){let V=l.start;l.start=l.end,l.end=V}const R=h.start.dot(a),O=h.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&&(u.subVectors(h.start,l.start),u.dot(a)>0?b.start.copy(h.start):b.start.copy(l.start),u.subVectors(h.end,l.end),u.dot(a)<0?b.end.copy(h.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 u=a||c?r:null;if(this.intersectsTriangle(i,u))return(a||c)&&(a&&u.getCenter(a),c&&u.getCenter(c)),0;let d=1/0;for(let h=0;h<3;h++){let l;const v=t[h],x=i[v];this.closestPointToPoint(x,s),l=x.distanceToSquared(s),l<d&&(d=l,a&&a.copy(s),c&&c.copy(x));const _=this[v];i.closestPointToPoint(_,s),l=_.distanceToSquared(s),l<d&&(d=l,a&&a.copy(_),c&&c.copy(s))}for(let h=0;h<3;h++){const l=t[h],v=t[(h+1)%3];r.set(this[l],this[v]);for(let x=0;x<3;x++){const _=t[x],g=t[(x+1)%3];n.set(i[_],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 u=0;u<=1;u++)for(let d=0;d<=1;d++)for(let h=0;h<=1;h++){const l=1*u|2*d|4*h,v=n[l];v.x=u?r.x:t.x,v.y=d?r.y:t.y,v.z=h?r.z:t.z,v.applyMatrix4(e)}const o=this.satBounds,i=this.satAxes,a=n[0];for(let u=0;u<3;u++){const d=i[u],h=o[u],l=1<<u,v=n[l];d.subVectors(a,v),h.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 u=i[c],d=o[c];if(s.setFromBox(u,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 u=i.satBounds,d=i.satAxes,h=this.points;for(let l=0;l<3;l++){const v=u[l],x=d[l];if(t.setFromPoints(x,h),v.isSeparated(t))return!1}for(let l=0;l<3;l++){const v=c[l];for(let x=0;x<4;x++){const _=d[x];if(n.crossVectors(v,_),t.setFromPoints(n,e),r.setFromPoints(n,h),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,u=null){if(this.needsUpdate&&this.update(),this.intersectsBox(i))return(c||u)&&(i.getCenter(n),this.closestPointToPoint(n,r),i.closestPointToPoint(r,n),c&&c.copy(r),u&&u.copy(n)),0;const d=a*a,h=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(h,l);const w=b.distanceToSquared(n);if(w<x&&(x=w,c&&c.copy(b),u&&u.copy(n),w<d))return Math.sqrt(w)}let _=0;for(let g=0;g<3;g++)for(let b=0;b<=1;b++)for(let w=0;w<=1;w++){const S=(g+1)%3,A=(g+2)%3,P=b<<S|w<<A,D=1<<g|b<<S|w<<A,R=v[P],O=v[D];e[_].set(R,O);const E=s[g],G=s[S],z=s[A],V=t[_],U=V.start,H=V.end;U[E]=h[E],U[G]=b?h[G]:l[G],U[z]=w?h[z]:l[G],H[E]=l[E],H[G]=b?h[G]:l[G],H[z]=w?h[z]:l[G],_++}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:h.x,n.y=b?l.y:h.y,n.z=w?l.z:h.z,this.closestPointToPoint(n,r);const S=n.distanceToSquared(r);if(S<x&&(x=S,c&&c.copy(r),u&&u.copy(n),S<d))return Math.sqrt(S)}for(let g=0;g<12;g++){const b=e[g];for(let w=0;w<12;w++){const S=t[w];hi(b,S,r,n);const A=r.distanceToSquared(n);if(A<x&&(x=A,c&&c.copy(r),u&&u.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 tc extends di{constructor(){super(()=>new mt)}}const ct=new tc;class rc{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 rc;let Ut,dr;const pr=[],wn=new di(()=>new f.Box3);function nc(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:u}=Me;let d=s*2;if(Ye(d,c)){const l=Xe(s,u),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=at(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=at(s),v=He(s,u);let x=l,_=v,g,b,w,S;if(n&&(w=Ut,S=dr,Fe(x,a,w),Fe(_,a,S),g=n(w),b=n(S),b<g)){x=v,_=l;const z=g;g=b,b=z,w=S}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;S=dr,Fe(_,a,S);const R=Ye(_*2,c),O=t(S,R,b,i+1,o+_);let L;if(O===fs){const z=E(_),U=G(_)-z;L=r(z,U,!0,i+1,o+_,S)}else L=O&&pi(_,e,t,r,n,o,i+1);return!!L}}const Gr=new f.Vector3,mi=new f.Vector3;function ic(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,h,l)=>l<a&&l<i,intersectsTriangle:(d,h)=>{d.closestPointToPoint(e,Gr);const l=e.distanceToSquared(Gr);return l<a&&(mi.copy(Gr),a=l,c=h),l<o}}),a===1/0)return null;const u=Math.sqrt(a);return t.point?t.point.copy(mi):t.point=mi.clone(),t.distance=u,t.faceIndex=c,t}const mr=new f.Vector3,gr=new f.Vector3,vr=new f.Vector3,_n=new f.Vector2,Tn=new f.Vector2,Sn=new f.Vector2,Ts=new f.Vector3,Ss=new f.Vector3,As=new f.Vector3,An=new f.Vector3;function sc(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 u=s.origin.distanceTo(n);return u<i||u>a?null:{distance:u,point:n.clone()}}function oc(s,e,t,r,n,o,i,a,c,u,d){mr.fromBufferAttribute(e,o),gr.fromBufferAttribute(e,i),vr.fromBufferAttribute(e,a);const h=sc(s,mr,gr,vr,An,c,u,d);if(h){r&&(_n.fromBufferAttribute(r,o),Tn.fromBufferAttribute(r,i),Sn.fromBufferAttribute(r,a),h.uv=f.Triangle.getInterpolation(An,mr,gr,vr,_n,Tn,Sn,new f.Vector2)),n&&(_n.fromBufferAttribute(n,o),Tn.fromBufferAttribute(n,i),Sn.fromBufferAttribute(n,a),h.uv1=f.Triangle.getInterpolation(An,mr,gr,vr,_n,Tn,Sn,new f.Vector2)),t&&(Ts.fromBufferAttribute(t,o),Ss.fromBufferAttribute(t,i),As.fromBufferAttribute(t,a),h.normal=f.Triangle.getInterpolation(An,mr,gr,vr,Ts,Ss,As,new f.Vector3),h.normal.dot(s.direction)>0&&h.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),h.face=l,h.faceIndex=o}return h}function Mn(s,e,t,r,n,o,i){const a=r*3;let c=a+0,u=a+1,d=a+2;const h=s.index;s.index&&(c=h.getX(c),u=h.getX(u),d=h.getX(d));const{position:l,normal:v,uv:x,uv1:_}=s.attributes,g=oc(t,l,v,x,_,c,u,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,u=e+2;t&&(a=t.getX(a),c=t.getX(c),u=t.getX(u)),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(u),i.y=r.getY(u),i.z=r.getZ(u)}function ac(s,e,t,r,n,o,i,a){const{geometry:c,_indirectBuffer:u}=s;for(let d=r,h=r+n;d<h;d++)Mn(c,e,t,d,o,i,a)}function cc(s,e,t,r,n,o,i){const{geometry:a,_indirectBuffer:c}=s;let u=1/0,d=null;for(let h=r,l=r+n;h<l;h++){let v;v=Mn(a,e,t,h,null,o,i),v&&v.distance<u&&(d=v,u=v.distance)}return d}function lc(s,e,t,r,n,o,i){const{geometry:a}=t,{index:c}=a,u=a.attributes.position;for(let d=s,h=e+s;d<h;d++){let l;if(l=d,Oe(i,l*3,c,u),i.needsUpdate=!0,r(i,l,n,o))return!0}return!1}function uc(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,u=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),h(0,u),u+=o.byteLength;function h(l,v,x=!1){const _=l*2;if(a[_+15]===vn){const b=i[l+6],w=a[_+14];let S=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<S&&(S=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]!==S||c[l+1]!==A||c[l+2]!==P||c[l+3]!==D||c[l+4]!==R||c[l+5]!==O?(c[l+0]=S,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],S=b+v,A=w+v;let P=x,D=!1,R=!1;e?P||(D=e.has(S),R=e.has(A),P=!D&&!R):(D=!0,R=!0);const O=P||D,L=P||R;let E=!1;O&&(E=h(b,v,P));let G=!1;L&&(G=h(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,u,d;const h=1/t.direction.x,l=1/t.direction.y,v=1/t.direction.z,x=t.origin.x,_=t.origin.y,g=t.origin.z;let b=e[s],w=e[s+3],S=e[s+1],A=e[s+3+1],P=e[s+2],D=e[s+3+2];return h>=0?(o=(b-x)*h,i=(w-x)*h):(o=(w-x)*h,i=(b-x)*h),l>=0?(a=(S-_)*l,c=(A-_)*l):(a=(A-_)*l,c=(S-_)*l),o>c||a>i||((a>o||isNaN(o))&&(o=a),(c<i||isNaN(i))&&(i=c),v>=0?(u=(P-g)*v,d=(D-g)*v):(u=(D-g)*v,d=(P-g)*v),o>d||u>i)?!1:((u>o||o!==o)&&(o=u),(d<i||i!==i)&&(i=d),o<=n&&i>=r)}function hc(s,e,t,r,n,o,i,a){const{geometry:c,_indirectBuffer:u}=s;for(let d=r,h=r+n;d<h;d++){let l=u?u[d]:d;Mn(c,e,t,l,o,i,a)}}function fc(s,e,t,r,n,o,i){const{geometry:a,_indirectBuffer:c}=s;let u=1/0,d=null;for(let h=r,l=r+n;h<l;h++){let v;v=Mn(a,e,t,c?c[h]:h,null,o,i),v&&v.distance<u&&(d=v,u=v.distance)}return d}function dc(s,e,t,r,n,o,i){const{geometry:a}=t,{index:c}=a,u=a.attributes.position;for(let d=s,h=e+s;d<h;d++){let l;if(l=t.resolveTriangleIndex(d),Oe(i,l*3,c,u),i.needsUpdate=!0,r(i,l,n,o))return!0}return!1}function pc(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:u}=Me,d=s*2;if(Ye(d,c)){const l=Xe(s,u),v=Je(d,c);ac(e,t,r,l,v,n,o,i)}else{const l=at(s);Gt(l,a,r,o,i)&&gi(l,e,t,r,n,o,i);const v=He(s,u);Gt(v,a,r,o,i)&&gi(v,e,t,r,n,o,i)}}const mc=["x","y","z"];function gc(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 u=s*2;if(Ye(u,a)){const h=Xe(s,c),l=Je(u,a);return cc(e,t,r,h,l,n,o)}else{const h=ci(s,c),l=mc[h],x=r.direction[l]>=0;let _,g;x?(_=at(s),g=He(s,c)):(_=He(s,c),g=at(s));const w=Gt(_,i,r,n,o)?vi(_,e,t,r,n,o):null;if(w){const P=w.point[l];if(x?P<=i[g+h]:P>=i[g+h+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 vc(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,h=d.index,l=d.attributes.position,v=t.index,x=t.attributes.position,_=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 S=_*3,A=(g+_)*3;S<A;S+=3)if(Oe(xr,S,h,l),xr.needsUpdate=!0,w.intersectsTriangle(xr))return!0;return!1}});for(let b=_*3,w=(g+_)*3;b<w;b+=3){Oe(yr,b,h,l),yr.a.applyMatrix4(Vr),yr.b.applyMatrix4(Vr),yr.c.applyMatrix4(Vr),yr.needsUpdate=!0;for(let S=0,A=v.count;S<A;S+=3)if(Oe(xr,S,v,x),xr.needsUpdate=!0,yr.intersectsTriangle(xr))return!0}}else{const d=s+8,h=a[s+6];return Fe(d,o,In),!!(n.intersectsBox(In)&&yi(d,e,t,r,n)||(Fe(h,o,In),n.intersectsBox(In)&&yi(h,e,t,r,n)))}}const Pn=new f.Matrix4,xi=new qe,jr=new qe,yc=new f.Vector3,xc=new f.Vector3,bc=new f.Vector3,wc=new f.Vector3;function _c(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,u=a.index,d=e.attributes.position,h=e.index,l=ct.getPrimitive(),v=ct.getPrimitive();let x=yc,_=xc,g=null,b=null;n&&(g=bc,b=wc);let w=1/0,S=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,h,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,u,c),l.needsUpdate=!0;const U=l.distanceToTriangle(v,x,g);if(U<w&&(_.copy(x),b&&b.copy(g),w=U,S=z,A=E),U<o)return!0}}}});{const R=fr(e);for(let O=0,L=R;O<L;O++){Oe(v,3*O,h,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,u,c),l.needsUpdate=!0;const z=l.distanceToTriangle(v,x,g);if(z<w&&(_.copy(x),b&&b.copy(g),w=z,S=E,A=O),z<o)return!0}}}}}),ct.releasePrimitive(l),ct.releasePrimitive(v),w===1/0?null:(r.point?r.point.copy(_):r.point=_.clone(),r.distance=w,r.faceIndex=S,n&&(n.point?n.point.copy(b):n.point=b.clone(),n.point.applyMatrix4(Pn),_.applyMatrix4(Pn),n.distance=_.sub(n.point).length(),n.faceIndex=A),r)}function Tc(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,u=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),h(0,u),u+=o.byteLength;function h(l,v,x=!1){const _=l*2;if(a[_+15]===vn){const b=i[l+6],w=a[_+14];let S=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<S&&(S=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]!==S||c[l+1]!==A||c[l+2]!==P||c[l+3]!==D||c[l+4]!==R||c[l+5]!==O?(c[l+0]=S,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],S=b+v,A=w+v;let P=x,D=!1,R=!1;e?P||(D=e.has(S),R=e.has(A),P=!D&&!R):(D=!0,R=!0);const O=P||D,L=P||R;let E=!1;O&&(E=h(b,v,P));let G=!1;L&&(G=h(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 Sc(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:u}=Me,d=s*2;if(Ye(d,c)){const l=Xe(s,u),v=Je(d,c);hc(e,t,r,l,v,n,o,i)}else{const l=at(s);Gt(l,a,r,o,i)&&bi(l,e,t,r,n,o,i);const v=He(s,u);Gt(v,a,r,o,i)&&bi(v,e,t,r,n,o,i)}}const Ac=["x","y","z"];function Mc(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 u=s*2;if(Ye(u,a)){const h=Xe(s,c),l=Je(u,a);return fc(e,t,r,h,l,n,o)}else{const h=ci(s,c),l=Ac[h],x=r.direction[l]>=0;let _,g;x?(_=at(s),g=He(s,c)):(_=He(s,c),g=at(s));const w=Gt(_,i,r,n,o)?wi(_,e,t,r,n,o):null;if(w){const P=w.point[l];if(x?P<=i[g+h]:P>=i[g+h+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 Ic(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,h=d.index,l=d.attributes.position,v=t.index,x=t.attributes.position,_=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 S=_,A=g+_;S<A;S++)if(Oe(wr,3*e.resolveTriangleIndex(S),h,l),wr.needsUpdate=!0,w.intersectsTriangle(wr))return!0;return!1}});for(let b=_,w=g+_;b<w;b++){const S=e.resolveTriangleIndex(b);Oe(br,3*S,h,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,h=a[s+6];return Fe(d,o,Dn),!!(n.intersectsBox(Dn)&&_i(d,e,t,r,n)||(Fe(h,o,Dn),n.intersectsBox(Dn)&&_i(h,e,t,r,n)))}}const Fn=new f.Matrix4,Ti=new qe,Yr=new qe,Cc=new f.Vector3,Pc=new f.Vector3,Dc=new f.Vector3,Rc=new f.Vector3;function Fc(s,e,t,r={},n={},o=0,i=1/0){e.boundingBox||e.computeBoundingBox(),Ti.set(e.boundingBox.min,e.boundingBox.max,t),Ti.needsUpdate=!0;const a=s.geometry,c=a.attributes.position,u=a.index,d=e.attributes.position,h=e.index,l=ct.getPrimitive(),v=ct.getPrimitive();let x=Cc,_=Pc,g=null,b=null;n&&(g=Dc,b=Rc);let w=1/0,S=null,A=null;return Fn.copy(t).invert(),Yr.matrix.copy(Fn),s.shapecast({boundsTraverseOrder:P=>Ti.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,h,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,u,c),l.needsUpdate=!0;const ne=l.distanceToTriangle(v,x,g);if(ne<w&&(_.copy(x),b&&b.copy(g),w=ne,S=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,h,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,u,c),l.needsUpdate=!0;const V=l.distanceToTriangle(v,x,g);if(V<w&&(_.copy(x),b&&b.copy(g),w=V,S=E,A=O),V<o)return!0}}}}}),ct.releasePrimitive(l),ct.releasePrimitive(v),w===1/0?null:(r.point?r.point.copy(_):r.point=_.clone(),r.distance=w,r.faceIndex=S,n&&(n.point?n.point.copy(b):n.point=b.clone(),n.point.applyMatrix4(Fn),_.applyMatrix4(Fn),n.distance=_.sub(n.point).length(),n.faceIndex=A),r)}function Oc(){return typeof SharedArrayBuffer<"u"}const qr=new Me.constructor,On=new Me.constructor,Vt=new di(()=>new f.Box3),_r=new f.Box3,Tr=new f.Box3,Si=new f.Box3,Ai=new f.Box3;let Mi=!1;function Lc(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 u=new f.Matrix4().copy(t).invert();for(let d=0,h=n.length;d<h;d++){qr.setBuffer(n[d]),c=0;const l=Vt.getPrimitive();Fe(0,qr.float32Array,l),l.applyMatrix4(u);for(let v=0,x=o.length;v<x&&(On.setBuffer(o[v]),i=gt(0,0,t,u,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,u=null,d=!1){let h,l;d?(h=On,l=qr):(h=qr,l=On);const v=h.float32Array,x=h.uint32Array,_=h.uint16Array,g=l.float32Array,b=l.uint32Array,w=l.uint16Array,S=s*2,A=e*2,P=Ye(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,_),c,i+e,a,o+s):R=n(Xe(s,x),Je(s*2,_),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=at(s),E=He(s,x);Fe(L,v,_r),Fe(E,v,Tr);const G=O.intersectsBox(_r),z=O.intersectsBox(Tr);R=G&&gt(e,L,r,t,n,i,o,c,a+1,O,!d)||z&&gt(e,E,r,t,n,i,o,c,a+1,O,!d),Vt.releasePrimitive(O)}else{const O=at(e),L=He(e,b);Fe(O,g,Si),Fe(L,g,Ai);const E=u.intersectsBox(Si),G=u.intersectsBox(Ai);if(E&&G)R=gt(s,O,t,r,n,o,i,a,c+1,u,d)||gt(s,L,t,r,n,o,i,a,c+1,u,d);else if(E)if(P)R=gt(s,O,t,r,n,o,i,a,c+1,u,d);else{const z=Vt.getPrimitive();z.copy(Si).applyMatrix4(t);const V=at(s),U=He(s,x);Fe(V,v,_r),Fe(U,v,Tr);const H=z.intersectsBox(_r),ne=z.intersectsBox(Tr);R=H&&gt(O,V,r,t,n,i,o,c,a+1,z,!d)||ne&&gt(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,u,d);else{const z=Vt.getPrimitive();z.copy(Ai).applyMatrix4(t);const V=at(s),U=He(s,x);Fe(V,v,_r),Fe(U,v,Tr);const H=z.intersectsBox(_r),ne=z.intersectsBox(Tr);R=H&&gt(L,V,r,t,n,i,o,c,a+1,z,!d)||ne&&gt(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,Nc={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 u=new f.BufferAttribute(e.index,1,!1);t.setIndex(u)}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({...Nc,[si]:!1},t),t.useSharedArrayBuffer&&!Oc())throw new Error("MeshBVH: SharedArrayBuffer is not available.");this.geometry=e,this._roots=null,this._indirectBuffer=null,t[si]||(Qa(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?Tc:uc)(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 u=a*2,d=o[u+15]===vn;if(d){const h=n[a+6],l=o[u+14];e(c,d,new Float32Array(r,a*4,6),h,l)}else{const h=a+zt/4,l=n[a+6],v=n[a+7];e(c,d,new Float32Array(r,a*4,6),v)||(i(h,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,u=Array.isArray(t),d=i.groups,h=c?t.side:t,l=this.indirect?Sc:pc;for(let v=0,x=o.length;v<x;v++){const _=u?t[d[v].materialIndex].side:h,g=a.length;if(l(this,v,_,e,a,r,n),u){const b=d[v].materialIndex;for(let w=g,S=a.length;w<S;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 u=null;const d=i.groups,h=a?t.side:t,l=this.indirect?Mc:gc;for(let v=0,x=o.length;v<x;v++){const _=c?t[d[v].materialIndex].side:h,g=l(this,v,_,e,r,n);g!=null&&(u==null||g.distance<u.distance)&&(u=g,c&&(g.face.materialIndex=d[v].materialIndex))}return u}intersectsGeometry(e,t){let r=!1;const n=this._roots,o=this.indirect?Ic:vc;for(let i=0,a=n.length;i<a&&(r=o(this,i,e,t),!r);i++);return r}shapecast(e){const t=ct.getPrimitive(),r=this.indirect?dc:lc;let{boundsTraverseOrder:n,intersectsBounds:o,intersectsRange:i,intersectsTriangle:a}=e;if(i&&a){const h=i;i=(l,v,x,_,g)=>h(l,v,x,_,g)?!0:r(l,v,this,a,x,_,t)}else i||(a?i=(h,l,v,x)=>r(h,l,this,a,v,x,t):i=(h,l,v)=>v);let c=!1,u=0;const d=this._roots;for(let h=0,l=d.length;h<l;h++){const v=d[h];if(c=nc(this,h,o,i,n,u),c)break;u+=v.byteLength}return ct.releasePrimitive(t),c}bvhcast(e,t,r){let{intersectsRanges:n,intersectsTriangles:o}=r;const i=ct.getPrimitive(),a=this.geometry.index,c=this.geometry.attributes.position,u=this.indirect?x=>{const _=this.resolveTriangleIndex(x);Oe(i,_*3,a,c)}:x=>{Oe(i,x*3,a,c)},d=ct.getPrimitive(),h=e.geometry.index,l=e.geometry.attributes.position,v=e.indirect?x=>{const _=e.resolveTriangleIndex(x);Oe(d,_*3,h,l)}:x=>{Oe(d,x*3,h,l)};if(o){const x=(_,g,b,w,S,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=_,E=_+g;L<E;L++)if(u(L),i.needsUpdate=!0,o(i,d,L,R,S,A,P,D))return!0}return!1};if(n){const _=n;n=function(g,b,w,S,A,P,D,R){return _(g,b,w,S,A,P,D,R)?!0:x(g,b,w,S,A,P,D,R)}}else n=x}return Lc(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?Fc:_c)(this,e,t,r,n,o,i)}closestPointToPoint(e,t={},r=0,n=1/0){return ic(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 kc(s){switch(s){case 1:return"R";case 2:return"RG";case 3:return"RGBA";case 4:return"RGBA"}throw new Error}function Bc(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,u=c.BYTES_PER_ELEMENT;let d=this._forcedType,h=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,_,g=kc(o);switch(d){case f.FloatType:x=1,v=Bc(o),a&&u===1?(_=c,g+="8",c===Uint8Array?l=f.UnsignedByteType:(l=f.ByteType,g+="_SNORM")):(_=Float32Array,g+="32F",l=f.FloatType);break;case f.IntType:g+=u*8+"I",x=a?Math.pow(2,c.BYTES_PER_ELEMENT*8-1):1,v=Ps(o),u===1?(_=Int8Array,l=f.ByteType):u===2?(_=Int16Array,l=f.ShortType):(_=Int32Array,l=f.IntType);break;case f.UnsignedIntType:g+=u*8+"UI",x=a?Math.pow(2,c.BYTES_PER_ELEMENT*8-1):1,v=Ps(o),u===1?(_=Uint8Array,l=f.UnsignedByteType):u===2?(_=Uint16Array,l=f.UnsignedShortType):(_=Uint32Array,l=f.UnsignedIntType);break}h===3&&(v===f.RGBAFormat||v===f.RGBAIntegerFormat)&&(h=4);const b=Math.ceil(Math.sqrt(i))||1,w=h*b*b,S=new _(w),A=e.normalized;e.normalized=!1;for(let P=0;P<i;P++){const D=h*P;S[D]=e.getX(P)/x,o>=2&&(S[D+1]=e.getY(P)/x),o>=3&&(S[D+2]=e.getZ(P)/x,h===4&&(S[D+3]=1)),o>=4&&(S[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=S,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 zc{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(Uc(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)}Ec(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 Ec(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 u=0;u<3;u++)r[a+u]=n?n[c+u]:c+u}}function Uc(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,u=2*Math.ceil(Math.sqrt(c/2)),d=new Float32Array(4*u*u),h=Math.ceil(Math.sqrt(c)),l=new Uint32Array(2*h*h);for(let v=0;v<c;v++){const x=v*zt/4,_=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(_,o)){const b=Je(_,o),w=Xe(x,i),S=4294901760|b;l[v*2+0]=S,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=u,e.image.height=u,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=h,t.image.height=h,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 Gc=`
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
- `,kc=`
112
+ `,Vc=`
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
- `,Bc=`
316
+ `,jc=`
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 Ds(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 zc(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 Ec(s){let e=0;for(let t=0,r=s.length;t<r;t++)e+=s[t].getIndex().count;return e}function Uc(s){let e=0;for(let t=0,r=s.length;t<r;t++)e+=s[t].getAttribute("position").count;return e}function Vc(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 Gc(s,e={},t=new f.BufferGeometry){const{useGroups:r=!1,forceUpdate:n=!1,skipAssigningAttributes:o=[],overwriteIndex:i=!0}=e;zc(s);const a=s[0].index!==null,c=a?Ec(s):-1,u=Uc(s);if(Vc(t,c,u),r){let h=0;for(let l=0,v=s.length;l<v;l++){const b=s[l];let T;a?T=b.getIndex().count:T=b.getAttribute("position").count,t.addGroup(h,T,l),h+=T}}if(a){let h=!1;if(t.index||(t.setIndex(new f.BufferAttribute(new Uint32Array(c),1,!1)),h=!0),h||i){let l=0,v=0;const b=t.getIndex();for(let T=0,g=s.length;T<g;T++){const x=s[T],w=x.getIndex();if(!(!n&&!h&&o[T]))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 h=0,l=d.length;h<l;h++){let v=!1;const b=d[h];if(!t.getAttribute(b)){const x=s[0].getAttribute(b);t.setAttribute(b,Zr(x,u)),v=!0}let T=0;const g=t.getAttribute(b);for(let x=0,w=s.length;x<w;x++){const S=s[x],A=!n&&!v&&o[x],P=S.getAttribute(b);A||Ds(P,g,T),T+=P.count}}}function jc(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 u=c.array;for(let d=0;d<a.length;d++){const h=a[d],l=h.start,v=h.count,b=Math.min(v,i-l),T=Array.isArray(e)?e[h.materialIndex]:e,g=t.indexOf(T);for(let x=0;x<b;x++){let w=l+x;r&&(w=r.getX(w)),u[w]=g}}}function Wc(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 Mi(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 Rs(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 Fs(s){const e=s.skeleton;return e?(e.boneTexture||e.computeBoneTexture(),`${Mi(e.boneTexture.image.data.buffer)}_${e.boneTexture.uuid}`):null}class Yc{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=Rs(t),this.primitiveCount=r,this.skeletonHash=Fs(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===Rs(t)&&this.skeletonHash===Fs(e)&&this.primitiveCount===r)}}const qt=new f.Vector3,Kt=new f.Vector3,Xt=new f.Vector3,Os=new f.Vector4,On=new f.Vector3,Ii=new f.Vector3,Ls=new f.Vector4,Ns=new f.Vector4,Ln=new f.Matrix4,ks=new f.Matrix4;function Bs(s,e,t){const r=s.skeleton,n=s.geometry,o=r.bones,i=r.boneInverses;Ls.fromBufferAttribute(n.attributes.skinIndex,e),Ns.fromBufferAttribute(n.attributes.skinWeight,e),Ln.elements.fill(0);for(let a=0;a<4;a++){const c=Ns.getComponent(a);if(c!==0){const u=Ls.getComponent(a);ks.multiplyMatrices(o[u].matrixWorld,i[u]),Zc(Ln,ks,c)}}return Ln.multiply(s.bindMatrix).premultiply(s.bindMatrixInverse),t.transformDirection(Ln),t}function Ci(s,e,t,r,n){On.set(0,0,0);for(let o=0,i=s.length;o<i;o++){const a=e[o],c=s[o];a!==0&&(Ii.fromBufferAttribute(c,r),t?On.addScaledVector(Ii,a):On.addScaledVector(Ii.sub(n),a))}n.add(On)}function Zc(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 qc(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 u=n.getComponent(i,c),d=n.getComponent(i+2,c);n.setComponent(i,c,d),n.setComponent(i+2,c,u)}}return s}function Kc(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 u=a.position,d=o?a.normal:null,h=i?a.tangent:null,l=r.morphAttributes.position,v=r.morphAttributes.normal,b=r.morphAttributes.tangent,T=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,S=a.position.count;w<S;w++)qt.fromBufferAttribute(u,w),d&&Kt.fromBufferAttribute(d,w),h&&(Os.fromBufferAttribute(h,w),Xt.fromBufferAttribute(h,w)),g&&(l&&Ci(l,g,T,w,qt),v&&Ci(v,g,T,w,Kt),b&&Ci(b,g,T,w,Xt)),s.isSkinnedMesh&&(s.applyBoneTransform(w,qt),d&&Bs(s,w,Kt),h&&Bs(s,w,Xt)),n&&qt.applyMatrix4(s.matrixWorld),c.position.setXYZ(w,qt.x,qt.y,qt.z),d&&(n&&Kt.applyNormalMatrix(x),c.normal.setXYZ(w,Kt.x,Kt.y,Kt.z)),h&&(n&&Xt.transformDirection(s.matrixWorld),c.tangent.setXYZW(w,Xt.x,Xt.y,Xt.z,Os.w));for(const w in e.attributes){const S=e.attributes[w];S==="position"||S==="tangent"||S==="normal"||!(S in a)||(c[S]||t.setAttribute(S,Zr(a[S])),Tr(a[S],c[S]),Ds(a[S],c[S]))}return s.matrixWorld.determinant()<0&&qc(t),t}class Xc extends f.BufferGeometry{constructor(){super(),this.version=0,this.hash=null,this._diff=new Yc}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)?(Kc(e,t,this),r.updateFrom(e),this.version++,this.hash=`${this.uuid}_${this.version}`,!0):!1}}const Pi=0,zs=1,Es=2;function $c(s,e){for(let t=0,r=s.length;t<r;t++)s[t].traverseVisible(o=>{o.isMesh&&e(o)})}function Qc(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 Jc(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 Gc(s,t,e);for(const r in e.attributes)e.attributes[r].needsUpdate=!0}class Hc{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 $c(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 u=e.get(c);(!u||!u.isCompatible(a,this.attributes))&&(u&&u.dispose(),u=new Xc,e.set(c,u)),u.updateFrom(a,n)&&this.generateMissingAttributes&&Wc(u,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=[],u=o.get(e)||[];this._updateIntermediateGeometries();let d=!1;i.length!==u.length&&(d=!0);for(let l=0,v=i.length;l<v;l++){const b=i[l],T=n.get(b.uuid);c.push(T);const g=u[l];!g||g.uuid!==T.uuid?(a.push(!1),d=!0):g.version!==T.version?a.push(!1):a.push(!0)}Jc(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 h=Pi;return d?h=Es:a.includes(!1)&&(h=zs),{changeType:h,materials:Qc(i),geometry:e}}}function el(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 tl(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 rl{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 Hc(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(h=>{h.traverse(l=>{l.isSkinnedMesh&&l.skeleton&&l.skeleton.update()})});const i=t.generate(r),a=i.materials,c=el(a),{lights:u,iesTextures:d}=tl(o);if(i.changeType!==Pi&&jc(r,a,a),this.generateBVH){if(this.bvh instanceof Promise)throw new Error("PathTracingSceneGenerator: BVH is already building asynchronously.");if(i.changeType===Es){const h={strategy:cs,maxLeafTris:1,indirect:!0,onProgress:e,...this.bvhOptions};this._buildAsync?this.bvh=this._bvhWorker.generate(r,h):this.bvh=new Ai(r,h)}else i.changeType===zs&&this.bvh.refit()}return{bvhChanged:i.changeType!==Pi,bvh:this.bvh,lights:u,iesTextures:d,geometry:r,materials:a,textures:c,objects:o}}}const nl=new f.OrthographicCamera(-1,1,1,-1,0,1);class il 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 sl=new il;class Sr{constructor(e){this._mesh=new f.Mesh(sl,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,nl)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class Di 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 ol extends Di{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 Sr(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 Wc(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 Yc(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 Zc(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 Kc(s,e={},t=new f.BufferGeometry){const{useGroups:r=!1,forceUpdate:n=!1,skipAssigningAttributes:o=[],overwriteIndex:i=!0}=e;Wc(s);const a=s[0].index!==null,c=a?Yc(s):-1,u=qc(s);if(Zc(t,c,u),r){let h=0;for(let l=0,v=s.length;l<v;l++){const x=s[l];let _;a?_=x.getIndex().count:_=x.getAttribute("position").count,t.addGroup(h,_,l),h+=_}}if(a){let h=!1;if(t.index||(t.setIndex(new f.BufferAttribute(new Uint32Array(c),1,!1)),h=!0),h||i){let l=0,v=0;const x=t.getIndex();for(let _=0,g=s.length;_<g;_++){const b=s[_],w=b.getIndex();if(!(!n&&!h&&o[_]))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 h=0,l=d.length;h<l;h++){let v=!1;const x=d[h];if(!t.getAttribute(x)){const b=s[0].getAttribute(x);t.setAttribute(x,Zr(b,u)),v=!0}let _=0;const g=t.getAttribute(x);for(let b=0,w=s.length;b<w;b++){const S=s[b],A=!n&&!v&&o[b],P=S.getAttribute(x);A||Os(P,g,_),_+=P.count}}}function Xc(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 u=c.array;for(let d=0;d<a.length;d++){const h=a[d],l=h.start,v=h.count,x=Math.min(v,i-l),_=Array.isArray(e)?e[h.materialIndex]:e,g=t.indexOf(_);for(let b=0;b<x;b++){let w=l+b;r&&(w=r.getX(w)),u[w]=g}}}function $c(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 Qc{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 u=Bs.getComponent(a);Es.multiplyMatrices(o[u].matrixWorld,i[u]),Jc(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 Jc(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 Hc(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 u=n.getComponent(i,c),d=n.getComponent(i+2,c);n.setComponent(i,c,d),n.setComponent(i+2,c,u)}}return s}function el(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)),Sr(r.index,t.index),Sr(a.position,c.position),o&&Sr(a.normal,c.normal),i&&Sr(a.tangent,c.tangent);const u=a.position,d=o?a.normal:null,h=i?a.tangent:null,l=r.morphAttributes.position,v=r.morphAttributes.normal,x=r.morphAttributes.tangent,_=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,S=a.position.count;w<S;w++)Kt.fromBufferAttribute(u,w),d&&Xt.fromBufferAttribute(d,w),h&&(ks.fromBufferAttribute(h,w),$t.fromBufferAttribute(h,w)),g&&(l&&Di(l,g,_,w,Kt),v&&Di(v,g,_,w,Xt),x&&Di(x,g,_,w,$t)),s.isSkinnedMesh&&(s.applyBoneTransform(w,Kt),d&&Us(s,w,Xt),h&&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)),h&&(n&&$t.transformDirection(s.matrixWorld),c.tangent.setXYZW(w,$t.x,$t.y,$t.z,ks.w));for(const w in e.attributes){const S=e.attributes[w];S==="position"||S==="tangent"||S==="normal"||!(S in a)||(c[S]||t.setAttribute(S,Zr(a[S])),Sr(a[S],c[S]),Os(a[S],c[S]))}return s.matrixWorld.determinant()<0&&Hc(t),t}class tl extends f.BufferGeometry{constructor(){super(),this.version=0,this.hash=null,this._diff=new Qc}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&&!Sr(i,a))return!1}return!0}updateFrom(e,t){const r=this._diff;return r.didChange(e)?(el(e,t,this),r.updateFrom(e),this.version++,this.hash=`${this.uuid}_${this.version}`,!0):!1}}const Ri=0,Gs=1,Vs=2;function rl(s,e){for(let t=0,r=s.length;t<r;t++)s[t].traverseVisible(o=>{o.isMesh&&e(o)})}function nl(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 il(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 Kc(s,t,e);for(const r in e.attributes)e.attributes[r].needsUpdate=!0}class sl{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 rl(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 u=e.get(c);(!u||!u.isCompatible(a,this.attributes))&&(u&&u.dispose(),u=new tl,e.set(c,u)),u.updateFrom(a,n)&&this.generateMissingAttributes&&$c(u,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=[],u=o.get(e)||[];this._updateIntermediateGeometries();let d=!1;i.length!==u.length&&(d=!0);for(let l=0,v=i.length;l<v;l++){const x=i[l],_=n.get(x.uuid);c.push(_);const g=u[l];!g||g.uuid!==_.uuid?(a.push(!1),d=!0):g.version!==_.version?a.push(!1):a.push(!0)}il(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 h=Ri;return d?h=Vs:a.includes(!1)&&(h=Gs),{changeType:h,materials:nl(i),geometry:e}}}function ol(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 al(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 cl{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 sl(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(h=>{h.traverse(l=>{l.isSkinnedMesh&&l.skeleton&&l.skeleton.update()})});const i=t.generate(r),a=i.materials,c=ol(a),{lights:u,iesTextures:d}=al(o);if(i.changeType!==Ri&&Xc(r,a,a),this.generateBVH){if(this.bvh instanceof Promise)throw new Error("PathTracingSceneGenerator: BVH is already building asynchronously.");if(i.changeType===Vs){const h={strategy:hs,maxLeafTris:1,indirect:!0,onProgress:e,...this.bvhOptions};this._buildAsync?this.bvh=this._bvhWorker.generate(r,h):this.bvh=new Ii(r,h)}else i.changeType===Gs&&this.bvh.refit()}return{bvhChanged:i.changeType!==Ri,bvh:this.bvh,lights:u,iesTextures:d,geometry:r,materials:a,textures:c,objects:o}}}const ll=new f.OrthographicCamera(-1,1,1,-1,0,1);class ul 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 hl=new ul;class Ar{constructor(e){this._mesh=new f.Mesh(hl,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,ll)}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 fl 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
 
@@ -360,7 +360,7 @@ struct BVH {
360
360
 
361
361
  }
362
362
 
363
- }`}),this.setValues(e)}}function Nn(s=1){let e="uint";return s>1&&(e="uvec"+s),`
363
+ }`}),this.setValues(e)}}function Bn(s=1){let e="uint";return s>1&&(e="uvec"+s),`
364
364
  ${e} sobolReverseBits( ${e} x ) {
365
365
 
366
366
  x = ( ( ( x & 0xaaaaaaaau ) >> 1 ) | ( ( x & 0x55555555u ) << 1 ) );
@@ -395,7 +395,7 @@ struct BVH {
395
395
  return x;
396
396
 
397
397
  }
398
- `}function kn(s=1){let e="uint",t="float",r="",n=".r",o="1u";return s>1&&(e="uvec"+s,t="vec"+s,r=s+"",s===2?(n=".rg",o="uvec2( 1u, 2u )"):s===3?(n=".rgb",o="uvec3( 1u, 2u, 3u )"):(n="",o="uvec4( 1u, 2u, 3u, 4u )")),`
398
+ `}function zn(s=1){let e="uint",t="float",r="",n=".r",o="1u";return s>1&&(e="uvec"+s,t="vec"+s,r=s+"",s===2?(n=".rg",o="uvec2( 1u, 2u )"):s===3?(n=".rgb",o="uvec3( 1u, 2u, 3u )"):(n="",o="uvec4( 1u, 2u, 3u, 4u )")),`
399
399
 
400
400
  ${t} sobol${r}( int effect ) {
401
401
 
@@ -413,16 +413,16 @@ struct BVH {
413
413
  return SOBOL_FACTOR * ${t}( result >> 8 );
414
414
 
415
415
  }
416
- `}const Us=`
416
+ `}const js=`
417
417
 
418
418
  // Utils
419
419
  const float SOBOL_FACTOR = 1.0 / 16777216.0;
420
420
  const uint SOBOL_MAX_POINTS = 256u * 256u;
421
421
 
422
- ${Nn(1)}
423
- ${Nn(2)}
424
- ${Nn(3)}
425
- ${Nn(4)}
422
+ ${Bn(1)}
423
+ ${Bn(2)}
424
+ ${Bn(3)}
425
+ ${Bn(4)}
426
426
 
427
427
  uint sobolHash( uint x ) {
428
428
 
@@ -436,7 +436,7 @@ struct BVH {
436
436
 
437
437
  }
438
438
 
439
- `,al=`
439
+ `,dl=`
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
- `,cl=`
517
+ `,pl=`
518
518
 
519
519
  // Seeds
520
520
  uniform sampler2D sobolTexture;
@@ -552,12 +552,12 @@ struct BVH {
552
552
 
553
553
  }
554
554
 
555
- ${kn(1)}
556
- ${kn(2)}
557
- ${kn(3)}
558
- ${kn(4)}
555
+ ${zn(1)}
556
+ ${zn(2)}
557
+ ${zn(3)}
558
+ ${zn(4)}
559
559
 
560
- `;class ll extends Di{constructor(){super({blending:f.NoBlending,uniforms:{resolution:{value:new f.Vector2}},vertexShader:`
560
+ `;class ml extends Fi{constructor(){super({blending:f.NoBlending,uniforms:{resolution:{value:new f.Vector2}},vertexShader:`
561
561
 
562
562
  varying vec2 vUv;
563
563
  void main() {
@@ -568,8 +568,8 @@ struct BVH {
568
568
  }
569
569
  `,fragmentShader:`
570
570
 
571
- ${Us}
572
- ${al}
571
+ ${js}
572
+ ${dl}
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 ul{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 Sr(new ll);return o.material.resolution.set(t,t),o.render(e),e.setRenderTarget(n),o.dispose(),r}}class hl 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 fl{constructor(){this.bokehSize=0,this.apertureBlades=0,this.apertureRotation=0,this.focusDistance=10,this.anamorphicRatio=1}updateFrom(e){e instanceof hl?(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 Ri(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 Vs(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 dl(s,e,t){return .2126*s+.7152*e+.0722*t}function pl(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,u=o.length;c<u;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 u=0;u<r;u++){const d=n-c-1,h=4*(c*r+u),l=4*(d*r+u);i[l+0]=a[h+0],i[l+1]=a[h+1],i[l+2]=a[h+2],i[l+3]=a[h+3]}t.flipY=!1,t.image.data=i}return t}class ml{constructor(){const e=new f.DataTexture(Ri(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(Ri(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(Ri(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=pl(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),u=new Float32Array(n);let d=0,h=0;for(let g=0;g<n;g++){let x=0;for(let w=0;w<r;w++){const S=g*r+w,A=f.DataUtils.fromHalfFloat(o[4*S+0]),P=f.DataUtils.fromHalfFloat(o[4*S+1]),D=f.DataUtils.fromHalfFloat(o[4*S+2]),F=dl(A,P,D);x+=F,d+=F,i[S]=F,a[S]=x}if(x!==0)for(let w=g*r,S=g*r+r;w<S;w++)i[w]/=x,a[w]/=x;h+=x,c[g]=x,u[g]=h}if(h!==0)for(let g=0,x=c.length;g<x;g++)c[g]/=h,u[g]/=h;const l=new Uint16Array(n),v=new Uint16Array(r*n);for(let g=0;g<n;g++){const x=(g+1)/n,w=Vs(u,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,S=(x+1)/r,A=Vs(a,S,g*r,r);v[w]=f.DataUtils.toHalfFloat((A+.5)/r)}this.dispose();const{marginalWeights:b,conditionalWeights:T}=this;b.image={width:n,height:1,data:l},b.needsUpdate=!0,T.image={width:r,height:n,data:v},T.needsUpdate=!0,this.totalSum=d,this.map=t}}const Fi=6,gl=0,vl=1,yl=2,bl=3,xl=4,vt=new f.Vector3,$e=new f.Vector3,Gs=new f.Matrix4,Ar=new f.Quaternion,js=new f.Vector3,Mr=new f.Vector3,wl=new f.Vector3(0,1,0);class _l{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*Fi,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,u=e.length;c<u;c++){const d=e[c],h=c*Fi*4;let l=0;for(let b=0;b<Fi*4;b++)i[h+b]=0;d.getWorldPosition($e),i[h+l++]=$e.x,i[h+l++]=$e.y,i[h+l++]=$e.z;let v=gl;if(d.isRectAreaLight&&d.isCircular?v=vl:d.isSpotLight?v=yl:d.isDirectionalLight?v=bl:d.isPointLight&&(v=xl),i[h+l++]=v,i[h+l++]=d.color.r,i[h+l++]=d.color.g,i[h+l++]=d.color.b,i[h+l++]=d.intensity,d.getWorldQuaternion(Ar),d.isRectAreaLight)vt.set(d.width,0,0).applyQuaternion(Ar),i[h+l++]=vt.x,i[h+l++]=vt.y,i[h+l++]=vt.z,l++,$e.set(0,d.height,0).applyQuaternion(Ar),i[h+l++]=$e.x,i[h+l++]=$e.y,i[h+l++]=$e.z,i[h+l++]=vt.cross($e).length()*(d.isCircular?Math.PI/4:1);else if(d.isSpotLight){const b=d.radius||0;js.setFromMatrixPosition(d.matrixWorld),Mr.setFromMatrixPosition(d.target.matrixWorld),Gs.lookAt(js,Mr,wl),Ar.setFromRotationMatrix(Gs),vt.set(1,0,0).applyQuaternion(Ar),i[h+l++]=vt.x,i[h+l++]=vt.y,i[h+l++]=vt.z,l++,$e.set(0,1,0).applyQuaternion(Ar),i[h+l++]=$e.x,i[h+l++]=$e.y,i[h+l++]=$e.z,i[h+l++]=Math.PI*b*b,i[h+l++]=b,i[h+l++]=d.decay,i[h+l++]=d.distance,i[h+l++]=Math.cos(d.angle),i[h+l++]=Math.cos(d.angle*(1-d.penumbra)),i[h+l++]=d.iesMap?t.indexOf(d.iesMap):-1}else if(d.isPointLight){const b=vt.setFromMatrixPosition(d.matrixWorld);i[h+l++]=b.x,i[h+l++]=b.y,i[h+l++]=b.z,l++,l+=4,l+=1,i[h+l++]=d.decay,i[h+l++]=d.distance}else if(d.isDirectionalLight){const b=vt.setFromMatrixPosition(d.matrixWorld),T=$e.setFromMatrixPosition(d.target.matrixWorld);Mr.subVectors(b,T).normalize(),i[h+l++]=Mr.x,i[h+l++]=Mr.y,i[h+l++]=Mr.z}}this.count=e.length;const a=Mi(i.buffer);return this.hash!==a?(this.hash=a,r.needsUpdate=!0,!0):!1}}function Ws(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 u=4*c,d=e*c;for(let h=0;h<r;h++)t[n+u+h]=e>=h+1?s[d+h]/a:0}}class Tl 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 h=t.itemSize;h===3&&(h=4),Ws(r.image.data,h,c,4,d),this.dispose(),this.needsUpdate=!0}setAttributes(e){const t=e[0].count,r=e.length;for(let h=0,l=r;h<l;h++)if(e[h].count!==t)throw new Error("FloatAttributeTextureArray: All attributes must have the same item count.");const n=this._textures;for(;n.length<r;){const h=new Ps;n.push(h)}for(;n.length>r;)n.pop();for(let h=0,l=r;h<l;h++)n[h].updateFrom(e[h]);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:u,height:d}=a;for(let h=0,l=r;h<l;h++){const v=n[h],T=u*d*4*h;let g=e[h].itemSize;g===3&&(g=4),Ws(v.image.data,g,c,4,T)}this.dispose(),this.needsUpdate=!0}}class Sl extends Tl{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 Oi(s,e){return s.uuid<e.uuid?1:s.uuid>e.uuid?-1:0}function Li(s){return`${s.source.uuid}:${s.colorSpace}`}function Al(s){const e=new Set,t=[];for(let r=0,n=s.length;r<n;r++){const o=s[r],i=Li(o);e.has(i)||(e.add(i),t.push(o))}return t}function Ml(s){const e=s.map(r=>r.iesMap||null).filter(r=>r),t=new Set(e);return Array.from(t).sort(Oi)}function Il(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 Al(t).sort(Oi)}function Cl(s){const e=[];return s.traverse(t=>{t.visible&&(t.isRectAreaLight||t.isSpotLight||t.isPointLight||t.isDirectionalLight)&&e.push(t)}),e.sort(Oi)}const Ys=45,Zs=Ys*4;class Pl{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 Dl 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 Pl}updateFrom(e,t){function r(b,T,g=-1){if(T in b&&b[T]){const x=Li(b[T]);return h[x]}else return g}function n(b,T,g){return T in b?b[T]:g}function o(b,T,g,x){const w=b[T]&&b[T].isTexture?b[T]:null;if(w){w.matrixAutoUpdate&&w.updateMatrix();const S=w.matrix.elements;let A=0;g[x+A++]=S[0],g[x+A++]=S[3],g[x+A++]=S[6],A++,g[x+A++]=S[1],g[x+A++]=S[4],g[x+A++]=S[7],A++}return 8}let i=0;const a=e.length*Ys,c=Math.ceil(Math.sqrt(a))||1,{image:u,features:d}=this,h={};for(let b=0,T=t.length;b<T;b++)h[Li(t[b])]=b;u.width!==c&&(this.dispose(),u.data=new Float32Array(c*c*4),u.width=c,u.height=c);const l=u.data;d.reset();for(let b=0,T=e.length;b<T;b++){const g=e[b];if(g.isFogVolumeMaterial){d.setUsed("FOG");for(let S=0;S<Zs;S++)l[i+S]=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+=Zs;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=Mi(l.buffer);return this.hash!==v?(this.hash=v,this.needsUpdate=!0,!0):!1}}const qs=new f.Color;function Rl(s){return s?`${s.uuid}:${s.version}`:null}function Fl(s,e){for(const t in e)t in s&&(s[t]=e[t])}class Ks 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),Fl(this.texture,n),this.texture.setTextures=(...i)=>{this.setTextures(...i)},this.hashes=[null];const o=new Sr(new Ol);this.fsQuad=o}setTextures(e,t,r=this.width,n=this.height){const o=e.getRenderTarget(),i=e.toneMapping,a=e.getClearAlpha();e.getClearColor(qs);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 u=this.fsQuad,d=this.hashes;let h=!1;for(let l=0,v=c;l<v;l++){const b=t[l],T=Rl(b);b&&(d[l]!==T||b.isWebGLRenderTarget)&&(b.matrixAutoUpdate=!1,b.matrix.identity(),u.material.map=b,e.setRenderTarget(this,l),u.render(e),b.updateMatrix(),b.matrixAutoUpdate=!0,d[l]=T,h=!0)}return u.material.map=null,e.setClearColor(qs,a),e.setRenderTarget(o),e.toneMapping=i,h}dispose(){super.dispose(),this.fsQuad.dispose()}}class Ol 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 gl{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 ml);return o.material.resolution.set(t,t),o.render(e),e.setRenderTarget(n),o.dispose(),r}}class vl 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 yl{constructor(){this.bokehSize=0,this.apertureBlades=0,this.apertureRotation=0,this.focusDistance=10,this.anamorphicRatio=1}updateFrom(e){e instanceof vl?(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 xl(s,e,t){return .2126*s+.7152*e+.0722*t}function bl(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,u=o.length;c<u;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 u=0;u<r;u++){const d=n-c-1,h=4*(c*r+u),l=4*(d*r+u);i[l+0]=a[h+0],i[l+1]=a[h+1],i[l+2]=a[h+2],i[l+3]=a[h+3]}t.flipY=!1,t.image.data=i}return t}class wl{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=bl(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),u=new Float32Array(n);let d=0,h=0;for(let g=0;g<n;g++){let b=0;for(let w=0;w<r;w++){const S=g*r+w,A=f.DataUtils.fromHalfFloat(o[4*S+0]),P=f.DataUtils.fromHalfFloat(o[4*S+1]),D=f.DataUtils.fromHalfFloat(o[4*S+2]),R=xl(A,P,D);b+=R,d+=R,i[S]=R,a[S]=b}if(b!==0)for(let w=g*r,S=g*r+r;w<S;w++)i[w]/=b,a[w]/=b;h+=b,c[g]=b,u[g]=h}if(h!==0)for(let g=0,b=c.length;g<b;g++)c[g]/=h,u[g]/=h;const l=new Uint16Array(n),v=new Uint16Array(r*n);for(let g=0;g<n;g++){const b=(g+1)/n,w=Ws(u,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,S=(b+1)/r,A=Ws(a,S,g*r,r);v[w]=f.DataUtils.toHalfFloat((A+.5)/r)}this.dispose();const{marginalWeights:x,conditionalWeights:_}=this;x.image={width:n,height:1,data:l},x.needsUpdate=!0,_.image={width:r,height:n,data:v},_.needsUpdate=!0,this.totalSum=d,this.map=t}}const Li=6,_l=0,Tl=1,Sl=2,Al=3,Ml=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,Il=new f.Vector3(0,1,0);class Cl{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,u=e.length;c<u;c++){const d=e[c],h=c*Li*4;let l=0;for(let x=0;x<Li*4;x++)i[h+x]=0;d.getWorldPosition($e),i[h+l++]=$e.x,i[h+l++]=$e.y,i[h+l++]=$e.z;let v=_l;if(d.isRectAreaLight&&d.isCircular?v=Tl:d.isSpotLight?v=Sl:d.isDirectionalLight?v=Al:d.isPointLight&&(v=Ml),i[h+l++]=v,i[h+l++]=d.color.r,i[h+l++]=d.color.g,i[h+l++]=d.color.b,i[h+l++]=d.intensity,d.getWorldQuaternion(Mr),d.isRectAreaLight)vt.set(d.width,0,0).applyQuaternion(Mr),i[h+l++]=vt.x,i[h+l++]=vt.y,i[h+l++]=vt.z,l++,$e.set(0,d.height,0).applyQuaternion(Mr),i[h+l++]=$e.x,i[h+l++]=$e.y,i[h+l++]=$e.z,i[h+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,Il),Mr.setFromRotationMatrix(Ys),vt.set(1,0,0).applyQuaternion(Mr),i[h+l++]=vt.x,i[h+l++]=vt.y,i[h+l++]=vt.z,l++,$e.set(0,1,0).applyQuaternion(Mr),i[h+l++]=$e.x,i[h+l++]=$e.y,i[h+l++]=$e.z,i[h+l++]=Math.PI*x*x,i[h+l++]=x,i[h+l++]=d.decay,i[h+l++]=d.distance,i[h+l++]=Math.cos(d.angle),i[h+l++]=Math.cos(d.angle*(1-d.penumbra)),i[h+l++]=d.iesMap?t.indexOf(d.iesMap):-1}else if(d.isPointLight){const x=vt.setFromMatrixPosition(d.matrixWorld);i[h+l++]=x.x,i[h+l++]=x.y,i[h+l++]=x.z,l++,l+=4,l+=1,i[h+l++]=d.decay,i[h+l++]=d.distance}else if(d.isDirectionalLight){const x=vt.setFromMatrixPosition(d.matrixWorld),_=$e.setFromMatrixPosition(d.target.matrixWorld);Ir.subVectors(x,_).normalize(),i[h+l++]=Ir.x,i[h+l++]=Ir.y,i[h+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 u=4*c,d=e*c;for(let h=0;h<r;h++)t[n+u+h]=e>=h+1?s[d+h]/a:0}}class Pl 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 h=t.itemSize;h===3&&(h=4),Zs(r.image.data,h,c,4,d),this.dispose(),this.needsUpdate=!0}setAttributes(e){const t=e[0].count,r=e.length;for(let h=0,l=r;h<l;h++)if(e[h].count!==t)throw new Error("FloatAttributeTextureArray: All attributes must have the same item count.");const n=this._textures;for(;n.length<r;){const h=new Fs;n.push(h)}for(;n.length>r;)n.pop();for(let h=0,l=r;h<l;h++)n[h].updateFrom(e[h]);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:u,height:d}=a;for(let h=0,l=r;h<l;h++){const v=n[h],_=u*d*4*h;let g=e[h].itemSize;g===3&&(g=4),Zs(v.image.data,g,c,4,_)}this.dispose(),this.needsUpdate=!0}}class Dl extends Pl{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 Rl(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 Fl(s){const e=s.map(r=>r.iesMap||null).filter(r=>r),t=new Set(e);return Array.from(t).sort(Ni)}function Ol(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 Rl(t).sort(Ni)}function Ll(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 Nl{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 kl 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 Nl}updateFrom(e,t){function r(x,_,g=-1){if(_ in x&&x[_]){const b=ki(x[_]);return h[b]}else return g}function n(x,_,g){return _ in x?x[_]:g}function o(x,_,g,b){const w=x[_]&&x[_].isTexture?x[_]:null;if(w){w.matrixAutoUpdate&&w.updateMatrix();const S=w.matrix.elements;let A=0;g[b+A++]=S[0],g[b+A++]=S[3],g[b+A++]=S[6],A++,g[b+A++]=S[1],g[b+A++]=S[4],g[b+A++]=S[7],A++}return 8}let i=0;const a=e.length*Ks,c=Math.ceil(Math.sqrt(a))||1,{image:u,features:d}=this,h={};for(let x=0,_=t.length;x<_;x++)h[ki(t[x])]=x;u.width!==c&&(this.dispose(),u.data=new Float32Array(c*c*4),u.width=c,u.height=c);const l=u.data;d.reset();for(let x=0,_=e.length;x<_;x++){const g=e[x];if(g.isFogVolumeMaterial){d.setUsed("FOG");for(let S=0;S<Xs;S++)l[i+S]=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 Bl(s){return s?`${s.uuid}:${s.version}`:null}function zl(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),zl(this.texture,n),this.texture.setTextures=(...i)=>{this.setTextures(...i)},this.hashes=[null];const o=new Ar(new El);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 u=this.fsQuad,d=this.hashes;let h=!1;for(let l=0,v=c;l<v;l++){const x=t[l],_=Bl(x);x&&(d[l]!==_||x.isWebGLRenderTarget)&&(x.matrixAutoUpdate=!1,x.matrix.identity(),u.material.map=x,e.setRenderTarget(this,l),u.render(e),x.updateMatrix(),x.matrixAutoUpdate=!0,d[l]=_,h=!0)}return u.material.map=null,e.setClearColor($s,a),e.setRenderTarget(o),e.toneMapping=i,h}dispose(){super.dispose(),this.fsQuad.dispose()}}class El 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 Ll(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 Nl{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&&(Ll(o,r),this.reshuffle());let c=o[i++];for(let u=0;u<t;u++)a[u]=(c%e+r())/e,c=Math.floor(c/e);return a}}}class kl{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 u=new Nl(e,c,r);u.samples=new Float32Array(o.buffer,a,u.samples.length),a+=u.samples.length*4,i.push(u)}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 Bl{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 zl 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 Bl,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 kl(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 El(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 Ul(s,e){s.fill(0);for(let t=0;t<e;t++)s[t]=1}class Xs{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,u=i*i+a*a;n[c]=Math.E**(-u/(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 u=-a;u<=a;u++)for(let d=-a;d<=a;d++){const h=(a+d)*c+u+a,l=i[h];let v=e+u;v=v<0?n+v:v%n;let b=t+d;b=b<0?n+b:b%n;const T=b*n+v;o[T]+=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 Vl{constructor(){this.random=Math.random,this.sigma=1.5,this.size=64,this.majorityPointsRatio=.1,this.samples=new Xs(1),this.savedSamples=new Xs(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;Ul(a,i),El(a,this.random);for(let h=0,l=a.length;h<l;h++)a[h]===1&&e.addPointIndex(h);for(;;){const h=e.findCluster();e.removePointIndex(h);const l=e.findVoid();if(h===l){e.addPointIndex(h);break}e.addPointIndex(l)}const c=new Uint32Array(o*o);t.copy(e);let u;for(u=e.count-1;u>=0;){const h=e.findCluster();e.removePointIndex(h),c[h]=u,u--}const d=o*o;for(u=t.count;u<d/2;){const h=t.findVoid();t.addPointIndex(h),c[h]=u,u++}for(t.invert();u<d;){const h=t.findCluster();t.removePointIndex(h),c[h]=u,u++}return{data:c,maxValue:d}}}function Gl(s){return s>=3?4:s}function jl(s){switch(s){case 1:return f.RedFormat;case 2:return f.RGFormat;default:return f.RGBAFormat}}class Wl 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 Vl;r.channels=e,r.size=t;const n=Gl(e),o=jl(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 u=r.generate(),d=u.data,h=u.maxValue;for(let l=0,v=d.length;l<v;l++){const b=d[l]/h;i[l*n+a]=b}}this.needsUpdate=!0}}const Yl=`
598
+ `})}}function Ul(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 Gl{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&&(Ul(o,r),this.reshuffle());let c=o[i++];for(let u=0;u<t;u++)a[u]=(c%e+r())/e,c=Math.floor(c/e);return a}}}class Vl{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 u=new Gl(e,c,r);u.samples=new Float32Array(o.buffer,a,u.samples.length),a+=u.samples.length*4,i.push(u)}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 jl{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 Wl 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 jl,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 Vl(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 Yl(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,u=i*i+a*a;n[c]=Math.E**(-u/(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 u=-a;u<=a;u++)for(let d=-a;d<=a;d++){const h=(a+d)*c+u+a,l=i[h];let v=e+u;v=v<0?n+v:v%n;let x=t+d;x=x<0?n+x:x%n;const _=x*n+v;o[_]+=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 Zl{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),Yl(a,this.random);for(let h=0,l=a.length;h<l;h++)a[h]===1&&e.addPointIndex(h);for(;;){const h=e.findCluster();e.removePointIndex(h);const l=e.findVoid();if(h===l){e.addPointIndex(h);break}e.addPointIndex(l)}const c=new Uint32Array(o*o);t.copy(e);let u;for(u=e.count-1;u>=0;){const h=e.findCluster();e.removePointIndex(h),c[h]=u,u--}const d=o*o;for(u=t.count;u<d/2;){const h=t.findVoid();t.addPointIndex(h),c[h]=u,u++}for(t.invert();u<d;){const h=t.findCluster();t.removePointIndex(h),c[h]=u,u++}return{data:c,maxValue:d}}}function Kl(s){return s>=3?4:s}function Xl(s){switch(s){case 1:return f.RedFormat;case 2:return f.RGFormat;default:return f.RGBAFormat}}class $l 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 Zl;r.channels=e,r.size=t;const n=Kl(e),o=Xl(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 u=r.generate(),d=u.data,h=u.maxValue;for(let l=0,v=d.length;l<v;l++){const x=d[l]/h;i[l*n+a]=x}}this.needsUpdate=!0}}const Ql=`
599
599
 
600
600
  struct PhysicalCamera {
601
601
 
@@ -607,7 +607,7 @@ struct BVH {
607
607
 
608
608
  };
609
609
 
610
- `,Zl=`
610
+ `,Jl=`
611
611
 
612
612
  struct EquirectHdrInfo {
613
613
 
@@ -619,7 +619,7 @@ struct BVH {
619
619
 
620
620
  };
621
621
 
622
- `,ql=`
622
+ `,Hl=`
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
- `,Kl=`
708
+ `,eu=`
709
709
 
710
710
  struct Material {
711
711
 
@@ -912,7 +912,7 @@ struct BVH {
912
912
 
913
913
  }
914
914
 
915
- `,Xl=`
915
+ `,tu=`
916
916
 
917
917
  struct SurfaceRecord {
918
918
 
@@ -974,7 +974,7 @@ struct BVH {
974
974
  vec3 color;
975
975
  };
976
976
 
977
- `,$l=`
977
+ `,ru=`
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
- `,Ql=`
1044
+ `,nu=`
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
- `,Jl=`
1259
+ `,iu=`
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
- `,Hl=`
1344
+ `,su=`
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
- `,eu=`
1447
+ `,ou=`
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
- `,tu=`
1527
+ `,au=`
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
- `,ru=`
1588
+ `,cu=`
1589
1589
 
1590
1590
  // add texel fetch functions for texture arrays
1591
1591
  vec4 texelFetch1D( sampler2DArray tex, int layer, uint index ) {
@@ -1608,7 +1608,7 @@ struct BVH {
1608
1608
 
1609
1609
  }
1610
1610
 
1611
- `,$s=`
1611
+ `,Hs=`
1612
1612
 
1613
1613
  // TODO: possibly this should be renamed something related to material or path tracing logic
1614
1614
 
@@ -1723,7 +1723,7 @@ struct BVH {
1723
1723
  return x < 0.5 ? sqrt( 2.0 * x ) - 1.0 : 1.0 - sqrt( 2.0 - ( 2.0 * x ) );
1724
1724
 
1725
1725
  }
1726
- `,Qs=`
1726
+ `,eo=`
1727
1727
 
1728
1728
  // https://www.shadertoy.com/view/wltcRS
1729
1729
  uvec4 WHITE_NOISE_SEED;
@@ -1779,7 +1779,7 @@ struct BVH {
1779
1779
  return vec4( WHITE_NOISE_SEED ) / float( 0xffffffffu );
1780
1780
 
1781
1781
  }
1782
- `,nu=`
1782
+ `,lu=`
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
- `,iu=`
1831
+ `,uu=`
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
- `,su=`
2269
+ `,hu=`
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
- `,ou=`
2290
+ `,fu=`
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
- `,au=`
2391
+ `,du=`
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
- `,cu=`
2525
+ `,pu=`
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 ) {
@@ -2619,7 +2619,7 @@ struct BVH {
2619
2619
 
2620
2620
  }
2621
2621
 
2622
- `,lu=`
2622
+ `,mu=`
2623
2623
 
2624
2624
  #ifndef FOG_CHECK_ITERATIONS
2625
2625
  #define FOG_CHECK_ITERATIONS 30
@@ -2680,7 +2680,7 @@ bool bvhIntersectFogVolumeHit(
2680
2680
 
2681
2681
  }
2682
2682
 
2683
- `,uu=`
2683
+ `,gu=`
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
- `,hu=`
2860
+ `,vu=`
2861
2861
 
2862
2862
  vec3 ndcToRayOrigin( vec2 coord ) {
2863
2863
 
@@ -2940,7 +2940,7 @@ bool bvhIntersectFogVolumeHit(
2940
2940
 
2941
2941
  }
2942
2942
 
2943
- `,fu=`
2943
+ `,yu=`
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
- `,du=`
3039
+ `,xu=`
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
- `,pu=`
3361
+ `,bu=`
3362
3362
 
3363
3363
  struct Ray {
3364
3364
 
@@ -3407,7 +3407,7 @@ bool bvhIntersectFogVolumeHit(
3407
3407
 
3408
3408
  }
3409
3409
 
3410
- `,mu=`
3410
+ `,wu=`
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 gu extends Di{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 fl},cameraWorldMatrix:{value:new f.Matrix4},invProjectionMatrix:{value:new f.Matrix4},bvh:{value:new Fc},attributesArray:{value:new Sl},materialIndexAttribute:{value:new Cs},materials:{value:new Dl},textures:{value:new Ks().texture},lights:{value:new _l},iesProfiles:{value:new Ks(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 zl},stratifiedOffsetTexture:{value:new Wl(64,1)}},vertexShader:`
3457
+ `;class _u 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 yl},cameraWorldMatrix:{value:new f.Matrix4},invProjectionMatrix:{value:new f.Matrix4},bvh:{value:new zc},attributesArray:{value:new Dl},materialIndexAttribute:{value:new Rs},materials:{value:new kl},textures:{value:new Qs().texture},lights:{value:new Cl},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 wl},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 Wl},stratifiedOffsetTexture:{value:new $l(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
- ${Nc}
3482
- ${Bc}
3483
- ${kc}
3481
+ ${Gc}
3482
+ ${jc}
3483
+ ${Vc}
3484
3484
 
3485
3485
  // uniform structs
3486
- ${Yl}
3487
- ${ql}
3488
- ${Zl}
3489
- ${Kl}
3490
- ${Xl}
3486
+ ${Ql}
3487
+ ${Hl}
3488
+ ${Jl}
3489
+ ${eu}
3490
+ ${tu}
3491
3491
 
3492
3492
  // random
3493
3493
  #if RANDOM_TYPE == 2 // Stratified List
3494
3494
 
3495
- ${nu}
3495
+ ${lu}
3496
3496
 
3497
3497
  #elif RANDOM_TYPE == 1 // Sobol
3498
3498
 
3499
- ${Qs}
3500
- ${Us}
3501
- ${cl}
3499
+ ${eo}
3500
+ ${js}
3501
+ ${pl}
3502
3502
 
3503
3503
  #define rand(v) sobol(v)
3504
3504
  #define rand2(v) sobol2(v)
@@ -3507,7 +3507,7 @@ bool bvhIntersectFogVolumeHit(
3507
3507
 
3508
3508
  #else // PCG
3509
3509
 
3510
- ${Qs}
3510
+ ${eo}
3511
3511
 
3512
3512
  // Using the sobol functions seems to break the the compiler on MacOS
3513
3513
  // - specifically the "sobolReverseBits" function.
@@ -3523,11 +3523,11 @@ bool bvhIntersectFogVolumeHit(
3523
3523
  #endif
3524
3524
 
3525
3525
  // common
3526
- ${ru}
3527
- ${Hl}
3528
- ${$s}
3529
- ${eu}
3530
- ${tu}
3526
+ ${cu}
3527
+ ${su}
3528
+ ${Hs}
3529
+ ${ou}
3530
+ ${au}
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
- ${Jl}
3587
- ${$l}
3588
- ${Ql}
3589
-
3590
- ${lu}
3591
- ${ou}
3592
- ${cu}
3593
- ${au}
3594
- ${su}
3595
3586
  ${iu}
3587
+ ${ru}
3588
+ ${nu}
3589
+
3590
+ ${mu}
3591
+ ${fu}
3592
+ ${pu}
3593
+ ${du}
3594
+ ${hu}
3595
+ ${uu}
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
- ${pu}
3628
- ${hu}
3629
- ${mu}
3630
- ${uu}
3631
- ${fu}
3632
- ${du}
3627
+ ${bu}
3628
+ ${vu}
3629
+ ${wu}
3630
+ ${gu}
3631
+ ${yu}
3632
+ ${xu}
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*vu(){const{_renderer:s,_fsQuad:e,_blendQuad:t,_primaryTarget:r,_blendTargets:n,_sobolTarget:o,_subframe:i,alpha:a,material:c}=this,u=new f.Vector4,d=new f.Vector4,h=t.material;let[l,v]=n;for(;;){a?(h.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[b,T,g,x]=i,w=r.width,S=r.height;c.resolution.set(w*g,S*x),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,F=Math.ceil(w*g),O=Math.ceil(S*x),L=Math.floor(b*w),E=Math.floor(T*S),V=Math.ceil(F/A),z=Math.ceil(O/P);for(let G=0;G<P;G++)for(let U=0;U<A;U++){const H=s.getRenderTarget(),ne=s.autoClear,ge=s.getScissorTest();s.getScissor(u),s.getViewport(d);let Pe=U,ve=G;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*V,E+ye*z,Math.min(V,F-Pe*V),Math.min(z,O-ye*z)),r.viewport.set(L,E,F,O),s.setRenderTarget(r),s.setScissorTest(!0),s.autoClear=!1,e.render(s),s.setViewport(d),s.setScissor(u),s.setScissorTest(ge),s.setRenderTarget(H),s.autoClear=ne,a&&(h.target1=l.texture,h.target2=r.texture,s.setRenderTarget(v),t.render(s),s.setRenderTarget(H)),this.samples+=1/D,U===A-1&&G===P-1&&(this.samples=Math.round(this.samples)),yield}[l,v]=[v,l]}}const Js=new f.Color;class Hs{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 Sr(new gu),this._blendQuad=new Sr(new ol),this._task=null,this._currentTile=0,this._compilePromise=null,this._sobolTarget=new ul().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(Js),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(Js,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=vu.call(this)),this._task.next())}}const $t=new f.Vector2,eo=new f.Vector2,Bn=new f.Spherical,zn=new f.Color;class yu 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++){eo.set(t,r),$t.set(n/t,o/r),$t.x-=.5,$t.y=1-$t.y,Bn.theta=$t.x*2*Math.PI,Bn.phi=$t.y*Math.PI,Bn.radius=1,this.generationCallback(Bn,$t,eo,zn);const a=4*(o*t+n);e[a+0]=zn.r,e[a+1]=zn.g,e[a+2]=zn.b,e[a+3]=1}}copy(e){return super.copy(e),this.generationCallback=e.generationCallback,this}}const to=new f.Vector3;class bu extends yu{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)=>{to.setFromSpherical(t);const i=to.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 xu 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:`
3924
+ `}),this.setValues(e)}}function*Tu(){const{_renderer:s,_fsQuad:e,_blendQuad:t,_primaryTarget:r,_blendTargets:n,_sobolTarget:o,_subframe:i,alpha:a,material:c}=this,u=new f.Vector4,d=new f.Vector4,h=t.material;let[l,v]=n;for(;;){a?(h.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,_,g,b]=i,w=r.width,S=r.height;c.resolution.set(w*g,S*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(S*b),L=Math.floor(x*w),E=Math.floor(_*S),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(u),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(u),s.setScissorTest(ge),s.setRenderTarget(H),s.autoClear=ne,a&&(h.target1=l.texture,h.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 _u),this._blendQuad=new Ar(new fl),this._task=null,this._currentTile=0,this._compilePromise=null,this._sobolTarget=new gl().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=Tu.call(this)),this._task.next())}}const Qt=new f.Vector2,no=new f.Vector2,En=new f.Spherical,Un=new f.Color;class Su 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 Au extends Su{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 Mu 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 wu extends f.ShaderMaterial{constructor(){super({uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:`
3981
+ `}),this.setValues(e)}}class Iu extends f.ShaderMaterial{constructor(){super({uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:`
3982
3982
  varying vec2 vUv;
3983
3983
  void main() {
3984
3984
 
@@ -3995,7 +3995,7 @@ bool bvhIntersectFogVolumeHit(
3995
3995
  #include <common>
3996
3996
  #include <cube_uv_reflection_fragment>
3997
3997
 
3998
- ${$s}
3998
+ ${Hs}
3999
3999
 
4000
4000
  void main() {
4001
4001
 
@@ -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 ro{constructor(e){this._renderer=e,this._quad=new Sr(new wu)}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,u=Math.log2(c)-2,d=1/c,h=1/(3*Math.max(Math.pow(2,u),7*16));i.material.defines.CUBEUV_MAX_MIP=`${u}.0`,i.material.defines.CUBEUV_TEXEL_WIDTH=h,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),T=new Float32Array(t*r*4);o.readRenderTargetPixels(a,0,0,t,r,T),a.dispose();for(let x=0,w=T.length;x<w;x++)b[x]=f.DataUtils.toHalfFloat(T[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 _u(s){return s.extensions.get("EXT_float_blend")}const Ir=new f.Vector2;class Tu{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 rl,this._pathTracer=new Hs(e),this._queueReset=!1,this._clock=new f.Clock,this._compilePromise=null,this._lowResPathTracer=new Hs(e),this._lowResPathTracer.tiles.set(1,1),this._quad=new Sr(new xu({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=Il(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=Cl(e),o=Ml(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 bu(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 ro(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 ro(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 u=this._pathTracer.material;return a&&(u.bvh.updateFrom(i),u.attributesArray.updateFrom(o.attributes.normal,o.attributes.tangent,o.attributes.uv,o.attributes.color),u.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||!_u(r),e.alpha=t.alpha,this.renderToCanvas){const c=this._renderer,u=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<u||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(Ir);const e=Math.floor(this.renderScale*Ir.x),t=Math.floor(this.renderScale*Ir.y);if(this._pathTracer.getSize(Ir),Ir.x!==e||Ir.y!==t){const r=this.lowResScale;this._pathTracer.setSize(e,t),this._lowResPathTracer.setSize(Math.floor(e*r),Math.floor(t*r))}}}}function no(s){return typeof s=="object"&&s!==null&&"getInternalRenderer"in s&&typeof s.getInternalRenderer=="function"}let Su=0;const io=new Set;class Au{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 fn,this.instanceId=++Su,io.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 C.DataTexture(i,r.width,r.height,C.RGBAFormat,C.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()?X.ok(void 0):X.err(new ce("Path tracing is not supported in this environment",ue.PATH_TRACING_INIT_FAILED,{reason:"WebGL2 or required extensions not available"}))}catch(t){return X.err(new ce("Failed to initialize path tracing",ue.PATH_TRACING_INIT_FAILED,{originalError:t}))}}createPathTracer(){if(this.disposed)return X.err(new ce("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 X.err(new ce("Renderer not ready, will retry",ue.RENDERER_NOT_INITIALIZED));t++}return e?(this.pathTracer=new Tu(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!==C.ACESFilmicToneMapping&&(e.toneMapping=C.ACESFilmicToneMapping,e.toneMappingExposure=1.5),e.autoClear=!1,e.setRenderTarget(null),X.ok(void 0)):X.err(new ce("Three.js renderer not available",ue.RENDERER_NOT_INITIALIZED))}catch(e){return X.err(new ce("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 X.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),X.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&&no(e)&&(o=e.getInternalRenderer()),t&&no(t)&&(i=t.getInternalRenderer()),!o||!i)return X.err(new ce("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===C.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 u=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=h=>{d()},a.image.complete&&d()}),this.pathTracer&&this.pathTracer.setScene(o,i),this.sceneInitialized=!0,o.environment=u}catch(d){throw o.environment=u,d}}else if(((n=o.environment)==null?void 0:n.mapping)===C.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(u){console.warn("Failed to update lights for path tracing:",u)}const a=this.renderer.render(e,t);if(!a.ok)return a;const c=At(this.renderer)?this.renderer.getInternalRenderer():null;if(c){const u=c.autoClear,d=c.getRenderTarget();c.autoClear=!1,this.pathTracer&&this.pathTracer.renderSample(),c.autoClear=u,c.setRenderTarget(d)}else throw new Error("Three.js renderer not available");if(this.sampleCount++,this.sampleCount===this.settings.samples){const u=At(this.renderer)?this.renderer.getInternalRenderer():null;if(u&&this.pathTracer)try{const d=u.autoClear;u.autoClear=!0,u.setRenderTarget(null),u.clear(!0,!0,!0);const h=this.pathTracer.copyQuad;h&&typeof h.render=="function"?h.render(u):(u.autoClear=!1,this.pathTracer.renderSample());const l=u.domElement,v=l.toDataURL("image/png");this.pausedFrameBase64=v,this.createImageOverlay(l,v),u.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),X.ok(void 0)}}else return this.renderer.render(e,t);return X.ok(void 0)}catch(o){return X.err(new ce("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,io.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 Iu)}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,u=Math.log2(c)-2,d=1/c,h=1/(3*Math.max(Math.pow(2,u),7*16));i.material.defines.CUBEUV_MAX_MIP=`${u}.0`,i.material.defines.CUBEUV_TEXEL_WIDTH=h,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),_=new Float32Array(t*r*4);o.readRenderTargetPixels(a,0,0,t,r,_),a.dispose();for(let b=0,w=_.length;b<w;b++)x[b]=f.DataUtils.toHalfFloat(_[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 Cu(s){return s.extensions.get("EXT_float_blend")}const Cr=new f.Vector2;class Pu{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 cl,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 Mu({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=Ol(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=Ll(e),o=Fl(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 Au(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 u=this._pathTracer.material;return a&&(u.bvh.updateFrom(i),u.attributesArray.updateFrom(o.attributes.normal,o.attributes.tangent,o.attributes.uv,o.attributes.color),u.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||!Cu(r),e.alpha=t.alpha,this.renderToCanvas){const c=this._renderer,u=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<u||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 Du=0;const ao=new Set;class Ru{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=++Du,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()?X.ok(void 0):X.err(new ce("Path tracing is not supported in this environment",ue.PATH_TRACING_INIT_FAILED,{reason:"WebGL2 or required extensions not available"}))}catch(t){return X.err(new ce("Failed to initialize path tracing",ue.PATH_TRACING_INIT_FAILED,{originalError:t}))}}createPathTracer(){if(this.disposed)return X.err(new ce("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 X.err(new ce("Renderer not ready, will retry",ue.RENDERER_NOT_INITIALIZED));t++}return e?(this.pathTracer=new Pu(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),X.ok(void 0)):X.err(new ce("Three.js renderer not available",ue.RENDERER_NOT_INITIALIZED))}catch(e){return X.err(new ce("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 X.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),X.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 X.err(new ce("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 u=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=h=>{d()},a.image.complete&&d()}),this.pathTracer&&this.pathTracer.setScene(o,i),this.sceneInitialized=!0,o.environment=u}catch(d){throw o.environment=u,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(u){console.warn("Failed to update lights for path tracing:",u)}const a=this.renderer.render(e,t);if(!a.ok)return a;const c=At(this.renderer)?this.renderer.getInternalRenderer():null;if(c){const u=c.autoClear,d=c.getRenderTarget();c.autoClear=!1,this.pathTracer&&this.pathTracer.renderSample(),c.autoClear=u,c.setRenderTarget(d)}else throw new Error("Three.js renderer not available");if(this.sampleCount++,this.sampleCount===this.settings.samples){const u=At(this.renderer)?this.renderer.getInternalRenderer():null;if(u&&this.pathTracer)try{const d=u.autoClear;u.autoClear=!0,u.setRenderTarget(null),u.clear(!0,!0,!0);const h=this.pathTracer.copyQuad;h&&typeof h.render=="function"?h.render(u):(u.autoClear=!1,this.pathTracer.renderSample());const l=u.domElement,v=l.toDataURL("image/png");this.pausedFrameBase64=v,this.createImageOverlay(l,v),u.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),X.ok(void 0)}}else return this.renderer.render(e,t);return X.ok(void 0)}catch(o){return X.err(new ce("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 lt=Uint8Array,Cr=Uint16Array,Mu=Int32Array,so=new lt([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]),oo=new lt([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]),Iu=new lt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ao=function(s,e){for(var t=new Cr(31),r=0;r<31;++r)t[r]=e+=1<<s[r-1];for(var n=new Mu(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}},co=ao(so,2),lo=co.b,Cu=co.r;lo[28]=258,Cu[258]=28;for(var Pu=ao(oo,0),Du=Pu.b,Ni=new Cr(32768),Ie=0;Ie<32768;++Ie){var Gt=(Ie&43690)>>1|(Ie&21845)<<1;Gt=(Gt&52428)>>2|(Gt&13107)<<2,Gt=(Gt&61680)>>4|(Gt&3855)<<4,Ni[Ie]=((Gt&65280)>>8|(Gt&255)<<8)>>1}for(var qr=function(s,e,t){for(var r=s.length,n=0,o=new Cr(e);n<r;++n)s[n]&&++o[s[n]-1];var i=new Cr(e);for(n=1;n<e;++n)i[n]=i[n-1]+o[n-1]<<1;var a;if(t){a=new Cr(1<<e);var c=15-e;for(n=0;n<r;++n)if(s[n])for(var u=n<<4|s[n],d=e-s[n],h=i[s[n]-1]++<<d,l=h|(1<<d)-1;h<=l;++h)a[Ni[h]>>c]=u}else for(a=new Cr(r),n=0;n<r;++n)s[n]&&(a[n]=Ni[i[s[n]-1]++]>>15-s[n]);return a},Kr=new lt(288),Ie=0;Ie<144;++Ie)Kr[Ie]=8;for(var Ie=144;Ie<256;++Ie)Kr[Ie]=9;for(var Ie=256;Ie<280;++Ie)Kr[Ie]=7;for(var Ie=280;Ie<288;++Ie)Kr[Ie]=8;for(var uo=new lt(32),Ie=0;Ie<32;++Ie)uo[Ie]=5;var Ru=qr(Kr,9,1),Fu=qr(uo,5,1),ki=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},Bi=function(s,e){var t=e/8|0;return(s[t]|s[t+1]<<8|s[t+2]<<16)>>(e&7)},Ou=function(s){return(s+7)/8|0},Lu=function(s,e,t){return(t==null||t>s.length)&&(t=s.length),new lt(s.subarray(e,t))},Nu=["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||Nu[s]);if(r.code=s,Error.captureStackTrace&&Error.captureStackTrace(r,bt),!t)throw r;return r},ku=function(s,e,t,r){var n=s.length,o=0;if(!n||e.f&&!e.l)return t||new lt(0);var i=!t,a=i||e.i!=2,c=e.i;i&&(t=new lt(n*3));var u=function(Pt){var _t=t.length;if(Pt>_t){var Dt=new lt(Math.max(_t*2,Pt));Dt.set(t),t=Dt}},d=e.f||0,h=e.p||0,l=e.b||0,v=e.l,b=e.d,T=e.m,g=e.n,x=n*8;do{if(!v){d=yt(s,h,1);var w=yt(s,h+1,3);if(h+=3,w)if(w==1)v=Ru,b=Fu,T=9,g=5;else if(w==2){var D=yt(s,h,31)+257,F=yt(s,h+10,15)+4,O=D+yt(s,h+5,31)+1;h+=14;for(var L=new lt(O),E=new lt(19),V=0;V<F;++V)E[Iu[V]]=yt(s,h+V*3,7);h+=F*3;for(var z=ki(E),G=(1<<z)-1,U=qr(E,z,1),V=0;V<O;){var H=U[yt(s,h,G)];h+=H&15;var S=H>>4;if(S<16)L[V++]=S;else{var ne=0,ge=0;for(S==16?(ge=3+yt(s,h,3),h+=2,ne=L[V-1]):S==17?(ge=3+yt(s,h,7),h+=3):S==18&&(ge=11+yt(s,h,127),h+=7);ge--;)L[V++]=ne}}var Pe=L.subarray(0,D),ve=L.subarray(D);T=ki(Pe),g=ki(ve),v=qr(Pe,T,1),b=qr(ve,g,1)}else bt(1);else{var S=Ou(h)+4,A=s[S-4]|s[S-3]<<8,P=S+A;if(P>n){c&&bt(0);break}a&&u(l+A),t.set(s.subarray(S,P),l),e.b=l+=A,e.p=h=P*8,e.f=d;continue}if(h>x){c&&bt(0);break}}a&&u(l+131072);for(var ye=(1<<T)-1,Ue=(1<<g)-1,_e=h;;_e=h){var ne=v[Bi(s,h)&ye],Se=ne>>4;if(h+=ne&15,h>x){c&&bt(0);break}if(ne||bt(2),Se<256)t[l++]=Se;else if(Se==256){_e=h,v=null;break}else{var et=Se-254;if(Se>264){var V=Se-257,ut=so[V];et=yt(s,h,(1<<ut)-1)+lo[V],h+=ut}var de=b[Bi(s,h)&Ue],ze=de>>4;de||bt(3),h+=de&15;var ve=Du[ze];if(ze>3){var ut=oo[ze];ve+=Bi(s,h)&(1<<ut)-1,h+=ut}if(h>x){c&&bt(0);break}a&&u(l+131072);var ke=l+et;if(l<ve){var ht=o-ve,tt=Math.min(ve,ke);for(ht+l<0&&bt(3);l<tt;++l)t[l]=r[ht+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=T,e.d=b,e.n=g)}while(!d);return l!=t.length&&i?Lu(t,0,l):t.subarray(0,l)},Bu=new lt(0),zu=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 En(s,e){return ku(s.subarray(zu(s),-4),{i:2},e,e)}var Eu=typeof TextDecoder<"u"&&new TextDecoder,Uu=0;try{Eu.decode(Bu,{stream:!0}),Uu=1}catch{}class Vu 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 M=_-1;for(;_<65536;)y[_++]=0;return M}function V(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 G(p,y,_,M,k){for(;_<p;)y=y<<8|Or(M,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 M=y+U[_]>>1;U[_]=y,y=M}for(let _=0;_<65537;++_){const M=p[_];M>0&&(p[_]=M|U[M]++<<6)}}function ne(p,y,_,M,k,R){const B=y;let q=0,Y=0;for(;M<=k;M++){if(B.value-y.value>_)return!1;G(6,q,Y,p,B);const j=z.l;if(q=z.c,Y=z.lc,R[M]=j,j==63){if(B.value-y.value>_)throw new Error("Something wrong with hufUnpackEncTable");G(8,q,Y,p,B);let W=z.l+6;if(q=z.c,Y=z.lc,M+W>k+1)throw new Error("Something wrong with hufUnpackEncTable");for(;W--;)R[M++]=0;M--}else if(j>=59){let W=j-59+2;if(M+W>k+1)throw new Error("Something wrong with hufUnpackEncTable");for(;W--;)R[M++]=0;M--}}H(R)}function ge(p){return p&63}function Pe(p){return p>>6}function ve(p,y,_,M){for(;y<=_;y++){const k=Pe(p[y]),R=ge(p[y]);if(k>>R)throw new Error("Invalid table entry");if(R>14){const B=M[k>>R-14];if(B.len)throw new Error("Invalid table entry");if(B.lit++,B.p){const q=B.p;B.p=new Array(B.lit);for(let Y=0;Y<B.lit-1;++Y)B.p[Y]=q[Y]}else B.p=new Array(1);B.p[B.lit-1]=y}else if(R){let B=0;for(let q=1<<14-R;q>0;q--){const Y=M[(k<<14-R)+B];if(Y.len||Y.p)throw new Error("Invalid table entry");Y.len=R,Y.lit=y,B++}}}return!0}const ye={c:0,lc:0};function Ue(p,y,_,M){p=p<<8|Or(_,M),y+=8,ye.c=p,ye.lc=y}const _e={c:0,lc:0};function Se(p,y,_,M,k,R,B,q,Y){if(p==y){M<8&&(Ue(_,M,k,R),_=ye.c,M=ye.lc),M-=8;let j=_>>M;if(j=new Uint8Array([j])[0],q.value+j>Y)return!1;const W=B[q.value-1];for(;j-- >0;)B[q.value++]=W}else if(q.value<Y)B[q.value++]=p;else return!1;_e.c=_,_e.lc=M}function et(p){return p&65535}function ut(p){const y=et(p);return y>32767?y-65536:y}const de={a:0,b:0};function ze(p,y){const _=ut(p),k=ut(y),R=_+(k&1)+(k>>1),B=R,q=R-k;de.a=B,de.b=q}function ke(p,y){const _=et(p),M=et(y),k=_-(M>>1)&65535,R=M+k-32768&65535;de.a=R,de.b=k}function ht(p,y,_,M,k,R,B){const q=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+R*(k-W),ee=R*j,le=R*W,te=M*j,se=M*W;let he,Te,Re,it;for(;J<=re;J+=le){let Ce=J;const me=J+M*(_-W);for(;Ce<=me;Ce+=se){const Be=Ce+te,pt=Ce+ee,Ee=pt+te;q?(ze(p[Ce+y],p[pt+y]),he=de.a,Re=de.b,ze(p[Be+y],p[Ee+y]),Te=de.a,it=de.b,ze(he,Te),p[Ce+y]=de.a,p[Be+y]=de.b,ze(Re,it),p[pt+y]=de.a,p[Ee+y]=de.b):(ke(p[Ce+y],p[pt+y]),he=de.a,Re=de.b,ke(p[Be+y],p[Ee+y]),Te=de.a,it=de.b,ke(he,Te),p[Ce+y]=de.a,p[Be+y]=de.b,ke(Re,it),p[pt+y]=de.a,p[Ee+y]=de.b)}if(_&j){const Be=Ce+ee;q?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+M*(_-W);for(;Ce<=me;Ce+=se){const Be=Ce+te;q?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,_,M,k,R,B,q,Y){let j=0,W=0;const J=B,re=Math.trunc(M.value+(k+7)/8);for(;M.value<re;)for(Ue(j,W,_,M),j=ye.c,W=ye.lc;W>=14;){const le=j>>W-14&16383,te=y[le];if(te.len)W-=te.len,Se(te.lit,R,j,W,_,M,q,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&&M.value<re;)Ue(j,W,_,M),j=ye.c,W=ye.lc;if(W>=he&&Pe(p[te.p[se]])==(j>>W-he&(1<<he)-1)){W-=he,Se(te.p[se],R,j,W,_,M,q,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,Se(le.lit,R,j,W,_,M,q,Y,J),j=_e.c,W=_e.lc;else throw new Error("hufDecode issues")}return!0}function Pt(p,y,_,M,k,R){const B={value:0},q=_.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);V(re);const ee=M-(_.value-q);if(ne(p,_,ee,Y,j,J),W>8*(M-(_.value-q)))throw new Error("Something wrong with hufUncompress");ve(J,Y,j,re),tt(J,re,p,_,W,j,R,k,B)}function _t(p,y,_){for(let M=0;M<_;++M)y[M]=p[y[M]]}function Dt(p){for(let y=1;y<p.length;y++){const _=p[y-1]+p[y]-128;p[y]=_}}function Rr(p,y){let _=0,M=Math.floor((p.length+1)/2),k=0;const R=p.length-1;for(;!(k>R||(y[k++]=p[_++],k>R));)y[k++]=p[M++]}function ft(p){let y=p.byteLength;const _=new Array;let M=0;const k=new DataView(p);for(;y>0;){const R=k.getInt8(M++);if(R<0){const B=-R;y-=B+1;for(let q=0;q<B;q++)_.push(k.getUint8(M++))}else{const B=R;y-=2;const q=k.getUint8(M++);for(let Y=0;Y<B+1;Y++)_.push(q)}}return _}function rt(p,y,_,M,k,R){let B=new DataView(R.buffer);const q=_[p.idx[0]].width,Y=_[p.idx[0]].height,j=3,W=Math.floor(q/8),J=Math.ceil(q/8),re=Math.ceil(Y/8),ee=q-(J-1)*8,le=Y-(re-1)*8,te={value:0},se=new Array(j),he=new Array(j),Te=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),Te[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 pt=8;for(let be=0;be<J;++be){be==J-1&&(pt=ee);for(let Ae=0;Ae<j;++Ae)Te[Ae].fill(0),Te[Ae][0]=k[se[Ae]++],Qt(te,M,Te[Ae]),Jt(Te[Ae],he[Ae]),xt(he[Ae]);Qr(he);for(let Ae=0;Ae<j;++Ae)Jr(he[Ae],Re[Ae],be*64)}let Ee=0;for(let be=0;be<j;++be){const Ae=_[p.idx[be]].type;for(let Lt=8*me;Lt<8*me+Be;++Lt){Ee=it[be][Lt];for(let un=0;un<W;++un){const St=un*64+(Lt&7)*8;B.setUint16(Ee+0*2*Ae,Re[be][St+0],!0),B.setUint16(Ee+1*2*Ae,Re[be][St+1],!0),B.setUint16(Ee+2*2*Ae,Re[be][St+2],!0),B.setUint16(Ee+3*2*Ae,Re[be][St+3],!0),B.setUint16(Ee+4*2*Ae,Re[be][St+4],!0),B.setUint16(Ee+5*2*Ae,Re[be][St+5],!0),B.setUint16(Ee+6*2*Ae,Re[be][St+6],!0),B.setUint16(Ee+7*2*Ae,Re[be][St+7],!0),Ee+=8*2*Ae}}if(W!=J)for(let Lt=8*me;Lt<8*me+Be;++Lt){const un=it[be][Lt]+8*W*2*Ae,St=W*64+(Lt&7)*8;for(let Wn=0;Wn<pt;++Wn)B.setUint16(un+Wn*2*Ae,Re[be][St+Wn],!0)}}}const Ce=new Uint16Array(q);B=new DataView(R.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 pt=0;pt<Y;++pt){const Ee=it[me][pt];for(let be=0;be<q;++be)Ce[be]=B.getUint16(Ee+be*2*Be,!0);for(let be=0;be<q;++be)B.setFloat32(Ee+be*2*Be,K(Ce[be]),!0)}}}function Qt(p,y,_){let M,k=1;for(;k<64;)M=y[p.value],M==65280?k=64:M>>8==255?k+=M&255:(_[k]=M,k++),p.value++}function Jt(p,y){y[0]=K(p[0]),y[1]=K(p[1]),y[2]=K(p[5]),y[3]=K(p[6]),y[4]=K(p[14]),y[5]=K(p[15]),y[6]=K(p[27]),y[7]=K(p[28]),y[8]=K(p[2]),y[9]=K(p[4]),y[10]=K(p[7]),y[11]=K(p[13]),y[12]=K(p[16]),y[13]=K(p[26]),y[14]=K(p[29]),y[15]=K(p[42]),y[16]=K(p[3]),y[17]=K(p[8]),y[18]=K(p[12]),y[19]=K(p[17]),y[20]=K(p[25]),y[21]=K(p[30]),y[22]=K(p[41]),y[23]=K(p[43]),y[24]=K(p[9]),y[25]=K(p[11]),y[26]=K(p[18]),y[27]=K(p[24]),y[28]=K(p[31]),y[29]=K(p[40]),y[30]=K(p[44]),y[31]=K(p[53]),y[32]=K(p[10]),y[33]=K(p[19]),y[34]=K(p[23]),y[35]=K(p[32]),y[36]=K(p[39]),y[37]=K(p[45]),y[38]=K(p[52]),y[39]=K(p[54]),y[40]=K(p[20]),y[41]=K(p[22]),y[42]=K(p[33]),y[43]=K(p[38]),y[44]=K(p[46]),y[45]=K(p[51]),y[46]=K(p[55]),y[47]=K(p[60]),y[48]=K(p[21]),y[49]=K(p[34]),y[50]=K(p[37]),y[51]=K(p[47]),y[52]=K(p[50]),y[53]=K(p[56]),y[54]=K(p[59]),y[55]=K(p[61]),y[56]=K(p[35]),y[57]=K(p[36]),y[58]=K(p[48]),y[59]=K(p[49]),y[60]=K(p[57]),y[61]=K(p[58]),y[62]=K(p[62]),y[63]=K(p[63])}function xt(p){const y=.5*Math.cos(.7853975),_=.5*Math.cos(3.14159/16),M=.5*Math.cos(3.14159/8),k=.5*Math.cos(3*3.14159/16),R=.5*Math.cos(5*3.14159/16),B=.5*Math.cos(3*3.14159/8),q=.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]=M*p[ee+2],Y[1]=B*p[ee+2],Y[2]=M*p[ee+6],Y[3]=B*p[ee+6],j[0]=_*p[ee+1]+k*p[ee+3]+R*p[ee+5]+q*p[ee+7],j[1]=k*p[ee+1]-q*p[ee+3]-_*p[ee+5]-R*p[ee+7],j[2]=R*p[ee+1]-_*p[ee+3]+q*p[ee+5]+k*p[ee+7],j[3]=q*p[ee+1]-R*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]=M*p[16+re],Y[1]=B*p[16+re],Y[2]=M*p[48+re],Y[3]=B*p[48+re],j[0]=_*p[8+re]+k*p[24+re]+R*p[40+re]+q*p[56+re],j[1]=k*p[8+re]-q*p[24+re]-_*p[40+re]-R*p[56+re],j[2]=R*p[8+re]-_*p[24+re]+q*p[40+re]+k*p[56+re],j[3]=q*p[8+re]-R*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 Qr(p){for(let y=0;y<64;++y){const _=p[0][y],M=p[1][y],k=p[2][y];p[0][y]=_+1.5747*k,p[1][y]=_-.1873*M-.4682*k,p[2][y]=_+1.8556*M}}function Jr(p,y,_){for(let M=0;M<64;++M)y[_+M]=f.DataUtils.toHalfFloat(Rt(p[M]))}function Rt(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 Ht(p){return new DataView(p.array.buffer,p.offset.value,p.size)}function Hr(p){const y=p.viewer.buffer.slice(p.offset.value,p.offset.value+p.size),_=new Uint8Array(ft(y)),M=new Uint8Array(_.length);return Dt(_),Rr(_,M),new DataView(M.buffer)}function Ft(p){const y=p.array.slice(p.offset.value,p.offset.value+p.size),_=En(y),M=new Uint8Array(_.length);return Dt(_),Rr(_,M),new DataView(M.buffer)}function er(p){const y=p.viewer,_={value:p.offset.value},M=new Uint16Array(p.columns*p.lines*(p.inputChannels.length*p.type)),k=new Uint8Array(8192);let R=0;const B=new Array(p.inputChannels.length);for(let le=0,te=p.inputChannels.length;le<te;le++)B[le]={},B[le].start=R,B[le].end=B[le].start,B[le].nx=p.columns,B[le].ny=p.lines,B[le].size=p.type,R+=B[le].nx*B[le].ny*B[le].size;const q=nt(y,_),Y=nt(y,_);if(Y>=8192)throw new Error("Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(q<=Y)for(let le=0;le<Y-q+1;le++)k[le+q]=dt(y,_);const j=new Uint16Array(65536),W=E(k,j),J=je(y,_);Pt(p.array,y,_,J,M,R);for(let le=0;le<p.inputChannels.length;++le){const te=B[le];for(let se=0;se<B[le].size;++se)ht(M,te.start+se,te.nx,te.size,te.ny,te.nx*te.size,W)}_t(j,M,R);let re=0;const ee=new Uint8Array(M.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,Te=new Uint8Array(M.buffer,se.end*2,he*2);ee.set(Te,re),re+=he*2,se.end+=he}return new DataView(ee.buffer)}function tr(p){const y=p.array.slice(p.offset.value,p.offset.value+p.size),_=En(y),M=p.inputChannels.length*p.lines*p.columns*p.totalBytes,k=new ArrayBuffer(M),R=new DataView(k);let B=0,q=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,R.setUint16(q,J,!0),q+=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,R.setUint32(q,J,!0),q+=4}break}}return R}function Fr(p){const y=p.viewer,_={value:p.offset.value},M=new Uint8Array(p.columns*p.lines*(p.inputChannels.length*p.type*2)),k={version:Ve(y,_),unknownUncompressedSize:Ve(y,_),unknownCompressedSize:Ve(y,_),acCompressedSize:Ve(y,_),dcCompressedSize:Ve(y,_),rleCompressedSize:Ve(y,_),rleUncompressedSize:Ve(y,_),rleRawSize:Ve(y,_),totalAcUncompressedCount:Ve(y,_),totalDcUncompressedCount:Ve(y,_),acCompression:Ve(y,_)};if(k.version<2)throw new Error("EXRLoader.parse: "+Q.compression+" version "+k.version+" is unsupported");const R=new Array;let B=nt(y,_)-2;for(;B>0;){const te=Tt(y.buffer,_),se=dt(y,_),he=se>>2&3,Te=(se>>4)-1,Re=new Int8Array([Te])[0],it=dt(y,_);R.push({name:te,index:Re,type:it,compression:he}),B-=te.length+3}const q=Q.channels,Y=new Array(p.inputChannels.length);for(let te=0;te<p.inputChannels.length;++te){const se=Y[te]={},he=q[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<R.length;++he){const Te=R[he];se.name==Te.name&&(se.compression=Te.compression,Te.index>=0&&(j.idx[Te.index]=te),se.offset=te)}}let W,J,re;if(k.acCompressedSize>0)switch(k.acCompression){case 0:W=new Uint16Array(k.totalAcUncompressedCount),Pt(p.array,y,_,k.acCompressedSize,W,k.totalAcUncompressedCount);break;case 1:const te=p.array.slice(_.value,_.value+k.totalAcUncompressedCount),se=En(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(Ft(te).buffer),_.value+=k.dcCompressedSize}if(k.rleRawSize>0){const te=p.array.slice(_.value,_.value+k.rleCompressedSize),se=En(te);re=ft(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,M);for(let te=0;te<Y.length;++te){const se=Y[te];if(!se.decoded)switch(se.compression){case 2:let he=0,Te=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)M[it++]=re[Te+me*se.width*se.height];Te++}he++}break;case 1:default:throw new Error("EXRLoader.parse: unsupported channel compression")}}return new DataView(M.buffer)}function Tt(p,y){const _=new Uint8Array(p);let M=0;for(;_[y.value+M]!=0;)M+=1;const k=new TextDecoder().decode(_.slice(y.value,y.value+M));return y.value=y.value+M+1,k}function rr(p,y,_){const M=new TextDecoder().decode(new Uint8Array(p).slice(y.value,y.value+_));return y.value=y.value+_,M}function en(p,y){const _=Ge(p,y),M=je(p,y);return[_,M]}function tn(p,y){const _=je(p,y),M=je(p,y);return[_,M]}function Ge(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 Or(p,y){const _=p[y.value];return y.value=y.value+1,_}function dt(p,y){const _=p.getUint8(y.value);return y.value=y.value+1,_}const Ve=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 nr(p,y){return f.DataUtils.toHalfFloat(De(p,y))}function K(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 Ot(p,y){return K(nt(p,y))}function ir(p,y,_,M){const k=_.value,R=[];for(;_.value<k+M-1;){const B=Tt(y,_),q=Ge(p,_),Y=dt(p,_);_.value+=3;const j=Ge(p,_),W=Ge(p,_);R.push({name:B,pixelType:q,pLinear:Y,xSampling:j,ySampling:W})}return _.value+=1,R}function rn(p,y){const _=De(p,y),M=De(p,y),k=De(p,y),R=De(p,y),B=De(p,y),q=De(p,y),Y=De(p,y),j=De(p,y);return{redX:_,redY:M,greenX:k,greenY:R,blueX:B,blueY:q,whiteX:Y,whiteY:j}}function sr(p,y){const _=["NO_COMPRESSION","RLE_COMPRESSION","ZIPS_COMPRESSION","ZIP_COMPRESSION","PIZ_COMPRESSION","PXR24_COMPRESSION","B44_COMPRESSION","B44A_COMPRESSION","DWAA_COMPRESSION","DWAB_COMPRESSION"],M=dt(p,y);return _[M]}function nn(p,y){const _=Ge(p,y),M=Ge(p,y),k=Ge(p,y),R=Ge(p,y);return{xMin:_,yMin:M,xMax:k,yMax:R}}function or(p,y){const _=["INCREASING_Y","DECREASING_Y","RANDOM_Y"],M=dt(p,y);return _[M]}function ar(p,y){const _=["ENVMAP_LATLONG","ENVMAP_CUBE"],M=dt(p,y);return _[M]}function sn(p,y){const _=["ONE_LEVEL","MIPMAP_LEVELS","RIPMAP_LEVELS"],M=["ROUND_DOWN","ROUND_UP"],k=je(p,y),R=je(p,y),B=dt(p,y);return{xSize:k,ySize:R,levelMode:_[B&15],roundingMode:M[B>>4]}}function on(p,y){const _=De(p,y),M=De(p,y);return[_,M]}function cr(p,y){const _=De(p,y),M=De(p,y),k=De(p,y);return[_,M,k]}function lr(p,y,_,M,k){if(M==="string"||M==="stringvector"||M==="iccProfile")return rr(y,_,k);if(M==="chlist")return ir(p,y,_,k);if(M==="chromaticities")return rn(p,_);if(M==="compression")return sr(p,_);if(M==="box2i")return nn(p,_);if(M==="envmap")return ar(p,_);if(M==="tiledesc")return sn(p,_);if(M==="lineOrder")return or(p,_);if(M==="float")return De(p,_);if(M==="v2f")return on(p,_);if(M==="v3f")return cr(p,_);if(M==="int")return Ge(p,_);if(M==="rational")return en(p,_);if(M==="timecode")return tn(p,_);if(M==="preview")return _.value+=k,"skipped";_.value+=k}function an(p,y){const _=Math.log2(p);return y=="ROUND_DOWN"?Math.floor(_):Math.ceil(_)}function cn(p,y,_){let M=0;switch(p.levelMode){case"ONE_LEVEL":M=1;break;case"MIPMAP_LEVELS":M=an(Math.max(y,_),p.roundingMode)+1;break;case"RIPMAP_LEVELS":throw new Error("THREE.EXRLoader: RIPMAP_LEVELS tiles currently unsupported.")}return M}function Lr(p,y,_,M){const k=new Array(p);for(let R=0;R<p;R++){const B=1<<R;let q=y/B|0;M=="ROUND_UP"&&q*B<y&&(q+=1);const Y=Math.max(q,1);k[R]=(Y+_-1)/_|0}return k}function ln(){const p=this,y=p.offset,_={value:0};for(let M=0;M<p.tileCount;M++){const k=Ge(p.viewer,y),R=Ge(p.viewer,y);y.value+=8,p.size=je(p.viewer,y);const B=k*p.blockWidth,q=R*p.blockHeight;p.columns=B+p.blockWidth>p.width?p.width-B:p.blockWidth,p.lines=q+p.blockHeight>p.height?p.height-q:p.blockHeight;const Y=p.columns*p.totalBytes,W=p.size<p.lines*Y?p.uncompress(p):Ht(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+q+J))*p.outLineWidth;for(let Te=0;Te<p.columns;Te++){const Re=he+(Te+B)*p.outputChannels+se;p.byteArray[Re]=p.getter(W,_)}}}}}function m(){const p=this,y=p.offset,_={value:0};for(let M=0;M<p.height/p.blockHeight;M++){const k=Ge(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 R=p.columns*p.totalBytes,q=p.size<p.lines*R?p.uncompress(p):Ht(p);y.value+=p.size;for(let Y=0;Y<p.blockHeight;Y++){const j=M*p.blockHeight,W=Y+p.scanOrder(j);if(W>=p.height)continue;const J=Y*R,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 Te=re+he*p.outputChannels+se;p.byteArray[Te]=p.getter(q,_)}}}}}}function I(p,y,_){const M={};if(p.getUint32(0,!0)!=20000630)throw new Error("THREE.EXRLoader: Provided file doesn't appear to be in OpenEXR format.");M.version=p.getUint8(4);const k=p.getUint8(5);M.spec={singleTile:!!(k&2),longName:!!(k&4),deepFormat:!!(k&8),multiPart:!!(k&16)},_.value=8;let R=!0;for(;R;){const B=Tt(y,_);if(B==0)R=!1;else{const q=Tt(y,_),Y=je(p,_),j=lr(p,y,_,q,Y);j===void 0?console.warn(`THREE.EXRLoader: Skipped unknown header attribute type '${q}'.`):M[B]=j}}if((k&-7)!=0)throw console.error("THREE.EXRHeader:",M),new Error("THREE.EXRLoader: Provided file is currently unsupported.");return M}function N(p,y,_,M,k){const R={size:0,viewer:y,array:_,offset:M,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":R.blockHeight=1,R.uncompress=Ht;break;case"RLE_COMPRESSION":R.blockHeight=1,R.uncompress=Hr;break;case"ZIPS_COMPRESSION":R.blockHeight=1,R.uncompress=Ft;break;case"ZIP_COMPRESSION":R.blockHeight=16,R.uncompress=Ft;break;case"PIZ_COMPRESSION":R.blockHeight=32,R.uncompress=er;break;case"PXR24_COMPRESSION":R.blockHeight=16,R.uncompress=tr;break;case"DWAA_COMPRESSION":R.blockHeight=32,R.uncompress=Fr;break;case"DWAB_COMPRESSION":R.blockHeight=256,R.uncompress=Fr;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,R.type=W.pixelType}let q=!1;if(B.R&&B.G&&B.B)q=!B.A,R.outputChannels=4,R.decodeChannels={R:0,G:1,B:2,A:3};else if(B.Y)R.outputChannels=1,R.decodeChannels={Y:0};else throw new Error("EXRLoader.parse: file contains unsupported data channels.");if(R.type==1)switch(k){case f.FloatType:R.getter=Ot;break;case f.HalfFloatType:R.getter=nt;break}else if(R.type==2)switch(k){case f.FloatType:R.getter=De;break;case f.HalfFloatType:R.getter=nr}else throw new Error("EXRLoader.parse: unsupported pixelType "+R.type+" for "+p.compression+".");R.columns=R.width;const Y=R.width*R.height*R.outputChannels;switch(k){case f.FloatType:R.byteArray=new Float32Array(Y),q&&R.byteArray.fill(1,0,Y);break;case f.HalfFloatType:R.byteArray=new Uint16Array(Y),q&&R.byteArray.fill(15360,0,Y);break;default:console.error("THREE.EXRLoader: unsupported type: ",k);break}let j=0;for(const W of p.channels)R.decodeChannels[W.name]!==void 0&&(R.channelByteOffsets[W.name]=j),j+=W.pixelType*2;if(R.totalBytes=j,R.outLineWidth=R.width*R.outputChannels,p.lineOrder==="INCREASING_Y"?R.scanOrder=W=>W:R.scanOrder=W=>R.height-1-W,R.outputChannels==4?(R.format=f.RGBAFormat,R.colorSpace=f.LinearSRGBColorSpace):(R.format=f.RedFormat,R.colorSpace=f.NoColorSpace),p.spec.singleTile){R.blockHeight=p.tiles.ySize,R.blockWidth=p.tiles.xSize;const W=cn(p.tiles,R.width,R.height),J=Lr(W,R.width,p.tiles.xSize,p.tiles.roundingMode),re=Lr(W,R.height,p.tiles.ySize,p.tiles.roundingMode);R.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++)Ve(y,M);R.decode=ln.bind(R)}else{R.blockWidth=R.width;const W=Math.ceil(R.height/R.blockHeight);for(let J=0;J<W;J++)Ve(y,M);R.decode=m.bind(R)}return R}const Z={value:0},ie=new DataView(e),oe=new Uint8Array(e),Q=I(ie,e,Z),$=N(Q,ie,oe,Z,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 Gu 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
- `,h=function(O,L,E){L=L||1024;let z=O.pos,G=-1,U=0,H="",ne=String.fromCharCode.apply(null,new Uint16Array(O.subarray(z,z+128)));for(;0>(G=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<G?(O.pos+=U+G+1,H+ne.slice(0,G)):!1},l=function(O){const L=/^#\?(\S+)/,E=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,V=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,z=/^\s*FORMAT=(\S+)\s*$/,G=/^\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=h(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+`
4011
+ */var lt=Uint8Array,Pr=Uint16Array,Fu=Int32Array,co=new lt([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 lt([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]),Ou=new lt([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 Fu(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,Lu=ho.r;fo[28]=258,Lu[258]=28;for(var Nu=uo(lo,0),ku=Nu.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 u=n<<4|s[n],d=e-s[n],h=i[s[n]-1]++<<d,l=h|(1<<d)-1;h<=l;++h)a[Bi[h]>>c]=u}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 lt(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 lt(32),Ie=0;Ie<32;++Ie)po[Ie]=5;var Bu=Kr(Xr,9,1),zu=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)},Eu=function(s){return(s+7)/8|0},Uu=function(s,e,t){return(t==null||t>s.length)&&(t=s.length),new lt(s.subarray(e,t))},Gu=["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||Gu[s]);if(r.code=s,Error.captureStackTrace&&Error.captureStackTrace(r,xt),!t)throw r;return r},Vu=function(s,e,t,r){var n=s.length,o=0;if(!n||e.f&&!e.l)return t||new lt(0);var i=!t,a=i||e.i!=2,c=e.i;i&&(t=new lt(n*3));var u=function(Dt){var _t=t.length;if(Dt>_t){var Rt=new lt(Math.max(_t*2,Dt));Rt.set(t),t=Rt}},d=e.f||0,h=e.p||0,l=e.b||0,v=e.l,x=e.d,_=e.m,g=e.n,b=n*8;do{if(!v){d=yt(s,h,1);var w=yt(s,h+1,3);if(h+=3,w)if(w==1)v=Bu,x=zu,_=9,g=5;else if(w==2){var D=yt(s,h,31)+257,R=yt(s,h+10,15)+4,O=D+yt(s,h+5,31)+1;h+=14;for(var L=new lt(O),E=new lt(19),G=0;G<R;++G)E[Ou[G]]=yt(s,h+G*3,7);h+=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,h,V)];h+=H&15;var S=H>>4;if(S<16)L[G++]=S;else{var ne=0,ge=0;for(S==16?(ge=3+yt(s,h,3),h+=2,ne=L[G-1]):S==17?(ge=3+yt(s,h,7),h+=3):S==18&&(ge=11+yt(s,h,127),h+=7);ge--;)L[G++]=ne}}var Pe=L.subarray(0,D),ve=L.subarray(D);_=zi(Pe),g=zi(ve),v=Kr(Pe,_,1),x=Kr(ve,g,1)}else xt(1);else{var S=Eu(h)+4,A=s[S-4]|s[S-3]<<8,P=S+A;if(P>n){c&&xt(0);break}a&&u(l+A),t.set(s.subarray(S,P),l),e.b=l+=A,e.p=h=P*8,e.f=d;continue}if(h>b){c&&xt(0);break}}a&&u(l+131072);for(var ye=(1<<_)-1,Ue=(1<<g)-1,_e=h;;_e=h){var ne=v[Ei(s,h)&ye],Se=ne>>4;if(h+=ne&15,h>b){c&&xt(0);break}if(ne||xt(2),Se<256)t[l++]=Se;else if(Se==256){_e=h,v=null;break}else{var et=Se-254;if(Se>264){var G=Se-257,ut=co[G];et=yt(s,h,(1<<ut)-1)+fo[G],h+=ut}var de=x[Ei(s,h)&Ue],ze=de>>4;de||xt(3),h+=de&15;var ve=ku[ze];if(ze>3){var ut=lo[ze];ve+=Ei(s,h)&(1<<ut)-1,h+=ut}if(h>b){c&&xt(0);break}a&&u(l+131072);var ke=l+et;if(l<ve){var ht=o-ve,tt=Math.min(ve,ke);for(ht+l<0&&xt(3);l<tt;++l)t[l]=r[ht+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=_,e.d=x,e.n=g)}while(!d);return l!=t.length&&i?Uu(t,0,l):t.subarray(0,l)},ju=new lt(0),Wu=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 Vu(s.subarray(Wu(s),-4),{i:2},e,e)}var Yu=typeof TextDecoder<"u"&&new TextDecoder,qu=0;try{Yu.decode(ju,{stream:!0}),qu=1}catch{}class Zu 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 T=0;for(let k=0;k<65536;++k)(k==0||p[k>>3]&1<<(k&7))&&(y[T++]=k);const I=T-1;for(;T<65536;)y[T++]=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,T,I,k){for(;T<p;)y=y<<8|Lr(I,k),T+=8;T-=p,z.l=y>>T&(1<<p)-1,z.c=y,z.lc=T}const U=new Array(59);function H(p){for(let T=0;T<=58;++T)U[T]=0;for(let T=0;T<65537;++T)U[p[T]]+=1;let y=0;for(let T=58;T>0;--T){const I=y+U[T]>>1;U[T]=y,y=I}for(let T=0;T<65537;++T){const I=p[T];I>0&&(p[T]=I|U[I]++<<6)}}function ne(p,y,T,I,k,F){const B=y;let Z=0,Y=0;for(;I<=k;I++){if(B.value-y.value>T)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>T)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,T,I){for(;y<=T;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,T,I){p=p<<8|Lr(T,I),y+=8,ye.c=p,ye.lc=y}const _e={c:0,lc:0};function Se(p,y,T,I,k,F,B,Z,Y){if(p==y){I<8&&(Ue(T,I,k,F),T=ye.c,I=ye.lc),I-=8;let j=T>>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=T,_e.lc=I}function et(p){return p&65535}function ut(p){const y=et(p);return y>32767?y-65536:y}const de={a:0,b:0};function ze(p,y){const T=ut(p),k=ut(y),F=T+(k&1)+(k>>1),B=F,Z=F-k;de.a=B,de.b=Z}function ke(p,y){const T=et(p),I=et(y),k=T-(I>>1)&65535,F=I+k-32768&65535;de.a=F,de.b=k}function ht(p,y,T,I,k,F,B){const Z=B<16384,Y=T>k?k:T;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,Te,Re,it;for(;J<=re;J+=le){let Ce=J;const me=J+I*(T-W);for(;Ce<=me;Ce+=se){const Be=Ce+te,pt=Ce+ee,Ee=pt+te;Z?(ze(p[Ce+y],p[pt+y]),he=de.a,Re=de.b,ze(p[Be+y],p[Ee+y]),Te=de.a,it=de.b,ze(he,Te),p[Ce+y]=de.a,p[Be+y]=de.b,ze(Re,it),p[pt+y]=de.a,p[Ee+y]=de.b):(ke(p[Ce+y],p[pt+y]),he=de.a,Re=de.b,ke(p[Be+y],p[Ee+y]),Te=de.a,it=de.b,ke(he,Te),p[Ce+y]=de.a,p[Be+y]=de.b,ke(Re,it),p[pt+y]=de.a,p[Ee+y]=de.b)}if(T&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*(T-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,T,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,T,I),j=ye.c,W=ye.lc;W>=14;){const le=j>>W-14&16383,te=y[le];if(te.len)W-=te.len,Se(te.lit,F,j,W,T,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,T,I),j=ye.c,W=ye.lc;if(W>=he&&Pe(p[te.p[se]])==(j>>W-he&(1<<he)-1)){W-=he,Se(te.p[se],F,j,W,T,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,Se(le.lit,F,j,W,T,I,Z,Y,J),j=_e.c,W=_e.lc;else throw new Error("hufDecode issues")}return!0}function Dt(p,y,T,I,k,F){const B={value:0},Z=T.value,Y=je(y,T),j=je(y,T);T.value+=4;const W=je(y,T);if(T.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-(T.value-Z);if(ne(p,T,ee,Y,j,J),W>8*(I-(T.value-Z)))throw new Error("Something wrong with hufUncompress");ve(J,Y,j,re),tt(J,re,p,T,W,j,F,k,B)}function _t(p,y,T){for(let I=0;I<T;++I)y[I]=p[y[I]]}function Rt(p){for(let y=1;y<p.length;y++){const T=p[y-1]+p[y]-128;p[y]=T}}function Fr(p,y){let T=0,I=Math.floor((p.length+1)/2),k=0;const F=p.length-1;for(;!(k>F||(y[k++]=p[T++],k>F));)y[k++]=p[I++]}function ft(p){let y=p.byteLength;const T=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++)T.push(k.getUint8(I++))}else{const B=F;y-=2;const Z=k.getUint8(I++);for(let Y=0;Y<B+1;Y++)T.push(Z)}}return T}function rt(p,y,T,I,k,F){let B=new DataView(F.buffer);const Z=T[p.idx[0]].width,Y=T[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),Te=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),Te[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 pt=8;for(let xe=0;xe<J;++xe){xe==J-1&&(pt=ee);for(let Ae=0;Ae<j;++Ae)Te[Ae].fill(0),Te[Ae][0]=k[se[Ae]++],Jt(te,I,Te[Ae]),Ht(Te[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=T[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 St=hn*64+(Nt&7)*8;B.setUint16(Ee+0*2*Ae,Re[xe][St+0],!0),B.setUint16(Ee+1*2*Ae,Re[xe][St+1],!0),B.setUint16(Ee+2*2*Ae,Re[xe][St+2],!0),B.setUint16(Ee+3*2*Ae,Re[xe][St+3],!0),B.setUint16(Ee+4*2*Ae,Re[xe][St+4],!0),B.setUint16(Ee+5*2*Ae,Re[xe][St+5],!0),B.setUint16(Ee+6*2*Ae,Re[xe][St+6],!0),B.setUint16(Ee+7*2*Ae,Re[xe][St+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,St=W*64+(Nt&7)*8;for(let qn=0;qn<pt;++qn)B.setUint16(hn+qn*2*Ae,Re[xe][St+qn],!0)}}}const Ce=new Uint16Array(Z);B=new DataView(F.buffer);for(let me=0;me<j;++me){T[p.idx[me]].decoded=!0;const Be=T[p.idx[me]].type;if(T[me].type==2)for(let pt=0;pt<Y;++pt){const Ee=it[me][pt];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,K(Ce[xe]),!0)}}}function Jt(p,y,T){let I,k=1;for(;k<64;)I=y[p.value],I==65280?k=64:I>>8==255?k+=I&255:(T[k]=I,k++),p.value++}function Ht(p,y){y[0]=K(p[0]),y[1]=K(p[1]),y[2]=K(p[5]),y[3]=K(p[6]),y[4]=K(p[14]),y[5]=K(p[15]),y[6]=K(p[27]),y[7]=K(p[28]),y[8]=K(p[2]),y[9]=K(p[4]),y[10]=K(p[7]),y[11]=K(p[13]),y[12]=K(p[16]),y[13]=K(p[26]),y[14]=K(p[29]),y[15]=K(p[42]),y[16]=K(p[3]),y[17]=K(p[8]),y[18]=K(p[12]),y[19]=K(p[17]),y[20]=K(p[25]),y[21]=K(p[30]),y[22]=K(p[41]),y[23]=K(p[43]),y[24]=K(p[9]),y[25]=K(p[11]),y[26]=K(p[18]),y[27]=K(p[24]),y[28]=K(p[31]),y[29]=K(p[40]),y[30]=K(p[44]),y[31]=K(p[53]),y[32]=K(p[10]),y[33]=K(p[19]),y[34]=K(p[23]),y[35]=K(p[32]),y[36]=K(p[39]),y[37]=K(p[45]),y[38]=K(p[52]),y[39]=K(p[54]),y[40]=K(p[20]),y[41]=K(p[22]),y[42]=K(p[33]),y[43]=K(p[38]),y[44]=K(p[46]),y[45]=K(p[51]),y[46]=K(p[55]),y[47]=K(p[60]),y[48]=K(p[21]),y[49]=K(p[34]),y[50]=K(p[37]),y[51]=K(p[47]),y[52]=K(p[50]),y[53]=K(p[56]),y[54]=K(p[59]),y[55]=K(p[61]),y[56]=K(p[35]),y[57]=K(p[36]),y[58]=K(p[48]),y[59]=K(p[49]),y[60]=K(p[57]),y[61]=K(p[58]),y[62]=K(p[62]),y[63]=K(p[63])}function bt(p){const y=.5*Math.cos(.7853975),T=.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]=T*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]-T*p[ee+5]-F*p[ee+7],j[2]=F*p[ee+1]-T*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]-T*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]=T*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]-T*p[40+re]-F*p[56+re],j[2]=F*p[8+re]-T*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]-T*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 T=p[0][y],I=p[1][y],k=p[2][y];p[0][y]=T+1.5747*k,p[1][y]=T-.1873*I-.4682*k,p[2][y]=T+1.8556*I}}function Hr(p,y,T){for(let I=0;I<64;++I)y[T+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),T=new Uint8Array(ft(y)),I=new Uint8Array(T.length);return Rt(T),Fr(T,I),new DataView(I.buffer)}function Ot(p){const y=p.array.slice(p.offset.value,p.offset.value+p.size),T=Gn(y),I=new Uint8Array(T.length);return Rt(T),Fr(T,I),new DataView(I.buffer)}function tr(p){const y=p.viewer,T={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,T),Y=nt(y,T);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]=dt(y,T);const j=new Uint16Array(65536),W=E(k,j),J=je(y,T);Dt(p.array,y,T,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)ht(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,Te=new Uint8Array(I.buffer,se.end*2,he*2);ee.set(Te,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),T=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=T[Y[0]++]<<8|T[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=T[Y[0]++]<<24|T[Y[1]++]<<16|T[Y[2]++]<<8;J+=le,F.setUint32(Z,J,!0),Z+=4}break}}return F}function Or(p){const y=p.viewer,T={value:p.offset.value},I=new Uint8Array(p.columns*p.lines*(p.inputChannels.length*p.type*2)),k={version:Ge(y,T),unknownUncompressedSize:Ge(y,T),unknownCompressedSize:Ge(y,T),acCompressedSize:Ge(y,T),dcCompressedSize:Ge(y,T),rleCompressedSize:Ge(y,T),rleUncompressedSize:Ge(y,T),rleRawSize:Ge(y,T),totalAcUncompressedCount:Ge(y,T),totalDcUncompressedCount:Ge(y,T),acCompression:Ge(y,T)};if(k.version<2)throw new Error("EXRLoader.parse: "+Q.compression+" version "+k.version+" is unsupported");const F=new Array;let B=nt(y,T)-2;for(;B>0;){const te=Tt(y.buffer,T),se=dt(y,T),he=se>>2&3,Te=(se>>4)-1,Re=new Int8Array([Te])[0],it=dt(y,T);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 Te=F[he];se.name==Te.name&&(se.compression=Te.compression,Te.index>=0&&(j.idx[Te.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,T,k.acCompressedSize,W,k.totalAcUncompressedCount);break;case 1:const te=p.array.slice(T.value,T.value+k.totalAcUncompressedCount),se=Gn(te);W=new Uint16Array(se.buffer),T.value+=k.totalAcUncompressedCount;break}if(k.dcCompressedSize>0){const te={array:p.array,offset:T,size:k.dcCompressedSize};J=new Uint16Array(Ot(te).buffer),T.value+=k.dcCompressedSize}if(k.rleRawSize>0){const te=p.array.slice(T.value,T.value+k.rleCompressedSize),se=Gn(te);re=ft(se.buffer),T.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,Te=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[Te+me*se.width*se.height];Te++}he++}break;case 1:default:throw new Error("EXRLoader.parse: unsupported channel compression")}}return new DataView(I.buffer)}function Tt(p,y){const T=new Uint8Array(p);let I=0;for(;T[y.value+I]!=0;)I+=1;const k=new TextDecoder().decode(T.slice(y.value,y.value+I));return y.value=y.value+I+1,k}function nr(p,y,T){const I=new TextDecoder().decode(new Uint8Array(p).slice(y.value,y.value+T));return y.value=y.value+T,I}function tn(p,y){const T=Ve(p,y),I=je(p,y);return[T,I]}function rn(p,y){const T=je(p,y),I=je(p,y);return[T,I]}function Ve(p,y){const T=p.getInt32(y.value,!0);return y.value=y.value+4,T}function je(p,y){const T=p.getUint32(y.value,!0);return y.value=y.value+4,T}function Lr(p,y){const T=p[y.value];return y.value=y.value+1,T}function dt(p,y){const T=p.getUint8(y.value);return y.value=y.value+1,T}const Ge=function(p,y){let T;return"getBigInt64"in DataView.prototype?T=Number(p.getBigInt64(y.value,!0)):T=p.getUint32(y.value+4,!0)+Number(p.getUint32(y.value,!0)<<32),y.value+=8,T};function De(p,y){const T=p.getFloat32(y.value,!0);return y.value+=4,T}function ir(p,y){return f.DataUtils.toHalfFloat(De(p,y))}function K(p){const y=(p&31744)>>10,T=p&1023;return(p>>15?-1:1)*(y?y===31?T?NaN:1/0:Math.pow(2,y-15)*(1+T/1024):6103515625e-14*(T/1024))}function nt(p,y){const T=p.getUint16(y.value,!0);return y.value+=2,T}function Lt(p,y){return K(nt(p,y))}function sr(p,y,T,I){const k=T.value,F=[];for(;T.value<k+I-1;){const B=Tt(y,T),Z=Ve(p,T),Y=dt(p,T);T.value+=3;const j=Ve(p,T),W=Ve(p,T);F.push({name:B,pixelType:Z,pLinear:Y,xSampling:j,ySampling:W})}return T.value+=1,F}function nn(p,y){const T=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:T,redY:I,greenX:k,greenY:F,blueX:B,blueY:Z,whiteX:Y,whiteY:j}}function or(p,y){const T=["NO_COMPRESSION","RLE_COMPRESSION","ZIPS_COMPRESSION","ZIP_COMPRESSION","PIZ_COMPRESSION","PXR24_COMPRESSION","B44_COMPRESSION","B44A_COMPRESSION","DWAA_COMPRESSION","DWAB_COMPRESSION"],I=dt(p,y);return T[I]}function sn(p,y){const T=Ve(p,y),I=Ve(p,y),k=Ve(p,y),F=Ve(p,y);return{xMin:T,yMin:I,xMax:k,yMax:F}}function ar(p,y){const T=["INCREASING_Y","DECREASING_Y","RANDOM_Y"],I=dt(p,y);return T[I]}function cr(p,y){const T=["ENVMAP_LATLONG","ENVMAP_CUBE"],I=dt(p,y);return T[I]}function on(p,y){const T=["ONE_LEVEL","MIPMAP_LEVELS","RIPMAP_LEVELS"],I=["ROUND_DOWN","ROUND_UP"],k=je(p,y),F=je(p,y),B=dt(p,y);return{xSize:k,ySize:F,levelMode:T[B&15],roundingMode:I[B>>4]}}function an(p,y){const T=De(p,y),I=De(p,y);return[T,I]}function lr(p,y){const T=De(p,y),I=De(p,y),k=De(p,y);return[T,I,k]}function ur(p,y,T,I,k){if(I==="string"||I==="stringvector"||I==="iccProfile")return nr(y,T,k);if(I==="chlist")return sr(p,y,T,k);if(I==="chromaticities")return nn(p,T);if(I==="compression")return or(p,T);if(I==="box2i")return sn(p,T);if(I==="envmap")return cr(p,T);if(I==="tiledesc")return on(p,T);if(I==="lineOrder")return ar(p,T);if(I==="float")return De(p,T);if(I==="v2f")return an(p,T);if(I==="v3f")return lr(p,T);if(I==="int")return Ve(p,T);if(I==="rational")return tn(p,T);if(I==="timecode")return rn(p,T);if(I==="preview")return T.value+=k,"skipped";T.value+=k}function cn(p,y){const T=Math.log2(p);return y=="ROUND_DOWN"?Math.floor(T):Math.ceil(T)}function ln(p,y,T){let I=0;switch(p.levelMode){case"ONE_LEVEL":I=1;break;case"MIPMAP_LEVELS":I=cn(Math.max(y,T),p.roundingMode)+1;break;case"RIPMAP_LEVELS":throw new Error("THREE.EXRLoader: RIPMAP_LEVELS tiles currently unsupported.")}return I}function Nr(p,y,T,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+T-1)/T|0}return k}function un(){const p=this,y=p.offset,T={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;T.value=re+te;const he=(p.height-(1+Z+J))*p.outLineWidth;for(let Te=0;Te<p.columns;Te++){const Re=he+(Te+B)*p.outputChannels+se;p.byteArray[Re]=p.getter(W,T)}}}}}function m(){const p=this,y=p.offset,T={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){T.value=J+te;for(let he=0;he<p.columns;he++){const Te=re+he*p.outputChannels+se;p.byteArray[Te]=p.getter(Z,T)}}}}}}function C(p,y,T){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)},T.value=8;let F=!0;for(;F;){const B=Tt(y,T);if(B==0)F=!1;else{const Z=Tt(y,T),Y=je(p,T),j=ur(p,y,T,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,T,I,k){const F={size:0,viewer:y,array:T,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),oe=new Uint8Array(e),Q=C(ie,e,q),$=N(Q,ie,oe,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 Ku 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
+ `,h=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=h(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=h(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(V))&&(U.exposure=parseFloat(ne[1])),(ne=H.match(z))&&(U.valid|=2,U.format=ne[1]),(ne=H.match(G))&&(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 V=L;if(V<8||V>32767||O[0]!==2||O[1]!==2||O[2]&128)return new Uint8Array(O);V!==(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 G=0,U=0;const H=4*V,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])!=V)&&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 Se=O[U++];for(let et=0;et<ye;et++)ge[ve++]=Se}else ge.set(O.subarray(U,U+ye),ve),ve+=ye,U+=ye}const Ue=V;for(let _e=0;_e<Ue;_e++){let Se=0;z[G]=ge[_e+Se],Se+=V,z[G+1]=ge[_e+Se],Se+=V,z[G+2]=ge[_e+Se],Se+=V,z[G+3]=ge[_e+Se],G+=4}Pe--}return z},b=function(O,L,E,V){const z=O[L+3],G=Math.pow(2,z-128)/255;E[V+0]=O[L+0]*G,E[V+1]=O[L+1]*G,E[V+2]=O[L+2]*G,E[V+3]=1},T=function(O,L,E,V){const z=O[L+3],G=Math.pow(2,z-128)/255;E[V+0]=f.DataUtils.toHalfFloat(Math.min(O[L+0]*G,65504)),E[V+1]=f.DataUtils.toHalfFloat(Math.min(O[L+1]*G,65504)),E[V+2]=f.DataUtils.toHalfFloat(Math.min(O[L+2]*G,65504)),E[V+3]=f.DataUtils.toHalfFloat(1)},g=new Uint8Array(e);g.pos=0;const x=l(g),w=x.width,S=x.height,A=v(g.subarray(g.pos),w,S);let P,D,F;switch(this.type){case f.FloatType:F=A.length/4;const O=new Float32Array(F*4);for(let E=0;E<F;E++)b(A,E*4,O,E*4);P=O,D=f.FloatType;break;case f.HalfFloatType:F=A.length/4;const L=new Uint16Array(F*4);for(let E=0;E<F;E++)T(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:S,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 ju 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 u=new f.Mesh(e,r);u.position.set(-2.017,.018,6.124),u.rotation.set(0,.333,0),u.scale.set(2.002,4.566,2.064),this.add(u);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 h=new f.Mesh(e,r);h.position.set(-2.193,-.369,-5.547),h.rotation.set(0,.516,0),h.scale.set(3.875,3.487,2.986),this.add(h);const l=new f.Mesh(e,Pr(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,Pr(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,Pr(17));b.position.set(14.904,12.198,-1.832),b.scale.set(.15,4.265,6.331),this.add(b);const T=new f.Mesh(e,Pr(43));T.position.set(-.462,8.89,14.52),T.scale.set(4.38,5.441,.088),this.add(T);const g=new f.Mesh(e,Pr(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,Pr(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 Pr(s){const e=new f.MeshBasicMaterial;return e.color.setScalar(s),e}class Wu{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 C.WebGLRenderer&&(n=i)}}return n?(this.pmremGenerator=new C.PMREMGenerator(n),this.pmremGenerator.compileEquirectangularShader(),X.ok(void 0)):X.err(new ce("Could not access Three.js renderer",ue.INITIALIZATION_FAILED))}catch(r){return X.err(new ce("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 X.ok(new Dr(i));const a=(t=e.split(".").pop())==null?void 0:t.toLowerCase();let c;switch(a){case"hdr":c=new Gu;break;case"exr":c=new Vu;break;case"jpg":case"jpeg":case"png":c=new C.TextureLoader;break;default:return X.err(new ce(`Unsupported environment map format: ${a}`,ue.UNSUPPORTED_FORMAT,{url:e,extension:a}))}const u=await new Promise((d,h)=>{c.load(e,l=>{var v,b,T,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:(T=l.image)!=null&&T.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=>h(l))});if(this.pmremGenerator){u.mapping=C.EquirectangularReflectionMapping;const d=this.pmremGenerator.fromEquirectangular(u).texture;return this.loadedTextures.set(e,d),this.loadedTextures.set(e+"_original",u),console.log("[ThreeEnvironmentService] Stored original texture for path tracing:",{url:e+"_original",format:u.format,mapping:u.mapping,hasImage:!!u.image,imageComplete:(r=u.image)==null?void 0:r.complete,imageNaturalWidth:(n=u.image)==null?void 0:n.naturalWidth,imageNaturalHeight:(o=u.image)==null?void 0:o.naturalHeight}),X.ok(new Dr(d))}return this.loadedTextures.set(e,u),X.ok(new Dr(u))}catch(i){return X.err(new ce("Failed to load environment map",ue.TEXTURE_LOAD_FAILED,{url:e,originalError:i}))}}applyToScene(e,t){try{if(!(e instanceof Wt))return X.err(new ce("Scene must be ThreeSceneAdapter",ue.INVALID_PARAMETER));if(!(t instanceof Dr))return X.err(new ce("Texture must be ThreeTextureAdapter",ue.INVALID_PARAMETER));const r=e.getThreeScene(),n=t.getThreeTexture();if(r.environment=n,n.mapping===C.CubeUVReflectionMapping){const i=Array.from(this.loadedTextures.entries()).find(([a,c])=>a.endsWith("_original")&&c.mapping===C.EquirectangularReflectionMapping);i&&(r.__originalEnvironmentTexture=i[1])}else n.mapping===C.EquirectangularReflectionMapping&&(r.__originalEnvironmentTexture=n);if(n.mapping===C.EquirectangularReflectionMapping)r.background=n;else if(n.mapping===C.CubeUVReflectionMapping){const i=Array.from(this.loadedTextures.entries()).find(([a,c])=>a.endsWith("_original")&&c.mapping===C.EquirectangularReflectionMapping);i?r.background=i[1]:r.background=n}else r.background=n;return X.ok(void 0)}catch(r){return X.err(new ce("Failed to apply environment to scene",ue.SCENE_OPERATION_FAILED,{originalError:r}))}}getOriginalEnvironmentTexture(e){const t=this.loadedTextures.get(e+"_original");return t?new Dr(t):null}createStudioEnvironment(e={}){try{if(!this.pmremGenerator)return X.err(new ce("Environment service not initialized",ue.INITIALIZATION_FAILED));const t=new ju,r=this.pmremGenerator.fromScene(t).texture;return t.dispose(),X.ok(new Dr(r))}catch(t){return X.err(new ce("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 Dr{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 Yu{constructor(e){this.object=e,this.boundingBox=new C.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 C.Vector3;return t>0?r.y=-e:r.y=0,r}applyOffset(e){this.object.position.add(e)}}class Zu{alignToFloor(e){try{let t=null;return"getThreeObject"in e&&typeof e.getThreeObject=="function"?t=e.getThreeObject():e instanceof C.Object3D&&(t=e),t?(new Yu(t).alignToFloor(),X.ok(void 0)):X.err(new ce("Could not get Three.js object for floor alignment",ue.INVALID_PARAMETER))}catch(t){return X.err(new ce("Failed to align object to floor",ue.OPERATION_FAILED,{originalError:t}))}}}var Un=(s=>(s.MapControls="MapControls",s.OrbitControls="OrbitControls",s))(Un||{});class qu{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===C.BasicShadowMap)return"basic";if(e===C.PCFShadowMap)return"pcf";if(e===C.PCFSoftShadowMap)return"pcfsoft";if(e===C.VSMShadowMap)return"vsm"}return typeof e=="string"?e:void 0}static convertToneMappingType(e){if(typeof e=="number"){if(e===C.NoToneMapping)return"none";if(e===C.LinearToneMapping)return"linear";if(e===C.ReinhardToneMapping)return"reinhard";if(e===C.CineonToneMapping)return"cineon";if(e===C.ACESFilmicToneMapping)return"aces"}return typeof e=="string"?e:"aces"}}class Ku{static createViewer(e,t){var T;const r=new Ro(e),n=new Wt,o=this.createCamera(t),i=this.createControls(o.getThreeCamera(),e,t),a=new Xu().createDefaultLoader(),c=new Da,u=new Wu;let d;(((T=t.pathTracing)==null?void 0:T.enabled)??!1)&&(d=new Au);const l=new Zu,v=qu.convertRendererOptions(t.renderer||{}),b={renderer:r,scene:n,camera:o,controls:i,modelLoader:a,options:t,rendererOptions:v,sceneSetupService:c,environmentService:u,pathTracingService:d,floorAlignmentService:l};return new Do(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,u=Kn.create(n,1,o,i);return a&&u.position.set(a[0],a[1],a[2]),c&&u.lookAt({x:c[0],y:c[1],z:c[2],set:()=>{},copy:()=>{},add:()=>{},multiply:()=>{},normalize:()=>{},length:()=>0}),u}static createControls(e,t,r){const n=r.controls||{},o=n.type||Un.OrbitControls;let i;o===Un.MapControls?i=new os(e,t):i=new ss(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||{},u=c.target||c.cameraTarget;return u&&i.target&&(i.target.set(u[0],u[1],u[2]),i.update()),i}}class Xu extends Hi{createDefaultLoader(){return Hi.createLoader("model.glb")}}const ho={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:{url:"https://dl.polyhaven.org/file/ph-assets/HDRIs/extra/Tonemapped%20JPG/industrial_sunset_puresky.jpg"},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:Un.OrbitControls,enabled:!0,enableDamping:!0,dampingFactor:.25,enableZoom:!0,enableRotate:!0,enablePan:!0},helpers:{grid:!0,axes:!1,stats:!1,gizmo:!1,studioEnvironment:!0}};function $u(s){const e=ae.useRef(s),t=ae.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 ae.useMemo(()=>{e.current=s},[t,s]),e.current}function Qu(s,e){const t=ae.useRef(null),[r,n]=ae.useState(new st),[o,i]=ae.useState(!1),a=$u(e);ae.useEffect(()=>{var l;if(!s.current||t.current)return;const u={...ho,...a};console.log("[useViewerCore] Creating viewer with options:",{pathTracingEnabled:(l=u.pathTracing)==null?void 0:l.enabled,staticScene:u.staticScene,pathTracing:u.pathTracing});const d=Ku.createViewer(s.current,u);t.current=d;const h=d.onStateChange(v=>{n(v)});return d.initialize().then(v=>{v.ok?i(!0):console.error("Failed to initialize viewer:",v.error)}),()=>{h(),d.dispose(),t.current=null,i(!1)}},[s,a]);const c=ae.useRef({width:0,height:0});return ae.useEffect(()=>{if(!t.current||!s.current)return;let u=null;const d=v=>{if(s.current&&t.current){const b=s.current.parentElement||s.current;let{clientWidth:T,clientHeight:g}=b;if(v&&v[0]){const{width:x,height:w}=v[0].contentRect;T=Math.floor(x),g=Math.floor(w)}if(c.current.width===T&&c.current.height===g)return;u!==null&&cancelAnimationFrame(u),u=requestAnimationFrame(()=>{t.current&&s.current&&(t.current.resize(T,g),c.current={width:T,height:g})})}};d();const h=()=>d();window.addEventListener("resize",h);let l=null;return typeof ResizeObserver<"u"&&s.current.parentElement&&(l=new ResizeObserver(d),l.observe(s.current.parentElement)),()=>{window.removeEventListener("resize",h),l==null||l.disconnect(),u!==null&&cancelAnimationFrame(u)}},[o,s]),{viewer:t.current,state:r,isInitialized:o}}function Ju(s,e){const t=ae.useRef(e);t.current=e,ae.useEffect(()=>{if(!s)return;const r=s.getEvents(),n=[];return Object.keys(e).forEach(o=>{if(e[o]){const a=c=>{const u=t.current[o];u&&u(c)};r.on(o,a),n.push(()=>r.off(o,a))}}),()=>{n.forEach(o=>o())}},[s])}const fo=ae.createContext(null);function Hu({viewer:s,canvasRef:e,children:t}){return qe.jsx(fo.Provider,{value:{viewer:s,canvasRef:e},children:t})}function eh(){const s=ae.useContext(fo);if(!s)throw new Error("useViewerContext must be used within ViewerProvider");return s}function th(){const{canvasRef:s}=eh();return qe.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 zi={exports:{}},Xr={};/**
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 Se=O[U++];for(let et=0;et<ye;et++)ge[ve++]=Se}else ge.set(O.subarray(U,U+ye),ve),ve+=ye,U+=ye}const Ue=G;for(let _e=0;_e<Ue;_e++){let Se=0;z[V]=ge[_e+Se],Se+=G,z[V+1]=ge[_e+Se],Se+=G,z[V+2]=ge[_e+Se],Se+=G,z[V+3]=ge[_e+Se],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},_=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,S=b.height,A=v(g.subarray(g.pos),w,S);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++)_(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:S,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 Xu 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 u=new f.Mesh(e,r);u.position.set(-2.017,.018,6.124),u.rotation.set(0,.333,0),u.scale.set(2.002,4.566,2.064),this.add(u);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 h=new f.Mesh(e,r);h.position.set(-2.193,-.369,-5.547),h.rotation.set(0,.516,0),h.scale.set(3.875,3.487,2.986),this.add(h);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 _=new f.Mesh(e,Dr(43));_.position.set(-.462,8.89,14.52),_.scale.set(4.38,5.441,.088),this.add(_);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 $u{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(),X.ok(void 0)):X.err(new ce("Could not access Three.js renderer",ue.INITIALIZATION_FAILED))}catch(r){return X.err(new ce("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 X.ok(new Rr(i));const a=(t=e.split(".").pop())==null?void 0:t.toLowerCase();let c;switch(a){case"hdr":c=new Ku;break;case"exr":c=new Zu;break;case"jpg":case"jpeg":case"png":c=new M.TextureLoader;break;default:return X.err(new ce(`Unsupported environment map format: ${a}`,ue.UNSUPPORTED_FORMAT,{url:e,extension:a}))}const u=await new Promise((d,h)=>{c.load(e,l=>{var v,x,_,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:(_=l.image)!=null&&_.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=>h(l))});if(this.pmremGenerator){u.mapping=M.EquirectangularReflectionMapping;const d=this.pmremGenerator.fromEquirectangular(u).texture;return this.loadedTextures.set(e,d),this.loadedTextures.set(e+"_original",u),console.log("[ThreeEnvironmentService] Stored original texture for path tracing:",{url:e+"_original",format:u.format,mapping:u.mapping,hasImage:!!u.image,imageComplete:(r=u.image)==null?void 0:r.complete,imageNaturalWidth:(n=u.image)==null?void 0:n.naturalWidth,imageNaturalHeight:(o=u.image)==null?void 0:o.naturalHeight}),X.ok(new Rr(d))}return this.loadedTextures.set(e,u),X.ok(new Rr(u))}catch(i){return X.err(new ce("Failed to load environment map",ue.TEXTURE_LOAD_FAILED,{url:e,originalError:i}))}}applyToScene(e,t,r){try{if(!(e instanceof Yt))return X.err(new ce("Scene must be ThreeSceneAdapter",ue.INVALID_PARAMETER));if(!(t instanceof Rr))return X.err(new ce("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,u])=>c.endsWith("_original")&&u.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,u])=>c.endsWith("_original")&&u.mapping===M.EquirectangularReflectionMapping);a?n.background=a[1]:n.background=o}else n.background=o;return X.ok(void 0)}catch(n){return X.err(new ce("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 X.err(new ce("Environment service not initialized",ue.INITIALIZATION_FAILED));const t=new Xu,r=this.pmremGenerator.fromScene(t).texture;return t.dispose(),X.ok(new Rr(r))}catch(t){return X.err(new ce("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 Qu{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 Ju{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 Qu(t).alignToFloor(),X.ok(void 0)):X.err(new ce("Could not get Three.js object for floor alignment",ue.INVALID_PARAMETER))}catch(t){return X.err(new ce("Failed to align object to floor",ue.OPERATION_FAILED,{originalError:t}))}}}var Vn=(s=>(s.MapControls="MapControls",s.OrbitControls="OrbitControls",s))(Vn||{});class Hu{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 eh{static createViewer(e,t){var _;const r=new Lo(e),n=new Yt,o=this.createCamera(t),i=this.createControls(o.getThreeCamera(),e,t),a=new th().createDefaultLoader(),c=new ka,u=new $u;let d;(((_=t.pathTracing)==null?void 0:_.enabled)??!1)&&(d=new Ru);const l=new Ju,v=Hu.convertRendererOptions(t.renderer||{}),x={renderer:r,scene:n,camera:o,controls:i,modelLoader:a,options:t,rendererOptions:v,sceneSetupService:c,environmentService:u,pathTracingService:d,floorAlignmentService:l};return new Oo(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,u=$n.create(n,1,o,i);return a&&u.position.set(a[0],a[1],a[2]),c&&u.lookAt({x:c[0],y:c[1],z:c[2],set:()=>{},copy:()=>{},add:()=>{},multiply:()=>{},normalize:()=>{},length:()=>0}),u}static createControls(e,t,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||{},u=c.target||c.cameraTarget;return u&&i.target&&(i.target.set(u[0],u[1],u[2]),i.update()),i}}class th 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}};function rh(s){const e=ae.useRef(s),t=ae.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 ae.useMemo(()=>{e.current=s},[t,s]),e.current}function nh(s,e){const t=ae.useRef(null),[r,n]=ae.useState(new st),[o,i]=ae.useState(!1),a=rh(e);ae.useEffect(()=>{var l;if(!s.current||t.current)return;const u={...mo,...a};console.log("[useViewerCore] Creating viewer with options:",{pathTracingEnabled:(l=u.pathTracing)==null?void 0:l.enabled,staticScene:u.staticScene,pathTracing:u.pathTracing});const d=eh.createViewer(s.current,u);t.current=d;const h=d.onStateChange(v=>{n(v)});return d.initialize().then(v=>{v.ok?i(!0):console.error("Failed to initialize viewer:",v.error)}),()=>{h(),d.dispose(),t.current=null,i(!1)}},[s,a]);const c=ae.useRef({width:0,height:0});return ae.useEffect(()=>{if(!t.current||!s.current)return;let u=null;const d=v=>{if(s.current&&t.current){const x=s.current.parentElement||s.current;let{clientWidth:_,clientHeight:g}=x;if(v&&v[0]){const{width:b,height:w}=v[0].contentRect;_=Math.floor(b),g=Math.floor(w)}if(c.current.width===_&&c.current.height===g)return;u!==null&&cancelAnimationFrame(u),u=requestAnimationFrame(()=>{t.current&&s.current&&(t.current.resize(_,g),c.current={width:_,height:g})})}};d();const h=()=>d();window.addEventListener("resize",h);let l=null;return typeof ResizeObserver<"u"&&s.current.parentElement&&(l=new ResizeObserver(d),l.observe(s.current.parentElement)),()=>{window.removeEventListener("resize",h),l==null||l.disconnect(),u!==null&&cancelAnimationFrame(u)}},[o,s]),{viewer:t.current,state:r,isInitialized:o}}function ih(s,e){const t=ae.useRef(e);t.current=e,ae.useEffect(()=>{if(!s)return;const r=s.getEvents(),n=[];return Object.keys(e).forEach(o=>{if(e[o]){const a=c=>{const u=t.current[o];u&&u(c)};r.on(o,a),n.push(()=>r.off(o,a))}}),()=>{n.forEach(o=>o())}},[s])}const go=ae.createContext(null);function sh({viewer:s,canvasRef:e,children:t}){return Ze.jsx(go.Provider,{value:{viewer:s,canvasRef:e},children:t})}function oh(){const s=ae.useContext(go);if(!s)throw new Error("useViewerContext must be used within ViewerProvider");return s}function ah(){const{canvasRef:s}=oh();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 po;function rh(){if(po)return Xr;po=1;var s=ae,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,u){var d,h={},l=null,v=null;u!==void 0&&(l=""+u),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)&&(h[d]=c[d]);if(a&&a.defaultProps)for(d in c=a.defaultProps,c)h[d]===void 0&&(h[d]=c[d]);return{$$typeof:e,type:a,key:l,ref:v,props:h,_owner:n.current}}return Xr.Fragment=t,Xr.jsx=i,Xr.jsxs=i,Xr}var Vn={};/**
4023
+ */var vo;function ch(){if(vo)return $r;vo=1;var s=ae,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,u){var d,h={},l=null,v=null;u!==void 0&&(l=""+u),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)&&(h[d]=c[d]);if(a&&a.defaultProps)for(d in c=a.defaultProps,c)h[d]===void 0&&(h[d]=c[d]);return{$$typeof:e,type:a,key:l,ref:v,props:h,_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,17 +4028,17 @@ 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 mo;function nh(){return mo||(mo=1,process.env.NODE_ENV!=="production"&&function(){var s=ae,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"),u=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),h=Symbol.for("react.memo"),l=Symbol.for("react.lazy"),v=Symbol.for("react.offscreen"),b=Symbol.iterator,T="@@iterator";function g(m){if(m===null||typeof m!="object")return null;var I=b&&m[b]||m[T];return typeof I=="function"?I:null}var x=s.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function w(m){{for(var I=arguments.length,N=new Array(I>1?I-1:0),Z=1;Z<I;Z++)N[Z-1]=arguments[Z];S("error",m,N)}}function S(m,I,N){{var Z=x.ReactDebugCurrentFrame,ie=Z.getStackAddendum();ie!==""&&(I+="%s",N=N.concat([ie]));var oe=N.map(function(Q){return String(Q)});oe.unshift("Warning: "+I),Function.prototype.apply.call(console[m],console,oe)}}var A=!1,P=!1,D=!1,F=!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===u||m===d||F||m===v||A||P||D||typeof m=="object"&&m!==null&&(m.$$typeof===l||m.$$typeof===h||m.$$typeof===i||m.$$typeof===a||m.$$typeof===c||m.$$typeof===L||m.getModuleId!==void 0))}function V(m,I,N){var Z=m.displayName;if(Z)return Z;var ie=I.displayName||I.name||"";return ie!==""?N+"("+ie+")":N}function z(m){return m.displayName||"Context"}function G(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 u:return"Suspense";case d:return"SuspenseList"}if(typeof m=="object")switch(m.$$typeof){case a:var I=m;return z(I)+".Consumer";case i:var N=m;return z(N._context)+".Provider";case c:return V(m,m.render,"ForwardRef");case h:var Z=m.displayName||null;return Z!==null?Z:G(m.type)||"Memo";case l:{var ie=m,oe=ie._payload,Q=ie._init;try{return G(Q(oe))}catch{return null}}}return null}var U=Object.assign,H=0,ne,ge,Pe,ve,ye,Ue,_e;function Se(){}Se.__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:Se,writable:!0};Object.defineProperties(console,{info:m,log:m,warn:m,error:m,group:m,groupCollapsed:m,groupEnd:m})}H++}}function ut(){{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=x.ReactCurrentDispatcher,ze;function ke(m,I,N){{if(ze===void 0)try{throw Error()}catch(ie){var Z=ie.stack.trim().match(/\n( *(at )?)/);ze=Z&&Z[1]||""}return`
4032
- `+ze+m}}var ht=!1,tt;{var Pt=typeof WeakMap=="function"?WeakMap:Map;tt=new Pt}function _t(m,I){if(!m||ht)return"";{var N=tt.get(m);if(N!==void 0)return N}var Z;ht=!0;var ie=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var oe;oe=de.current,de.current=null,et();try{if(I){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){Z=B}Reflect.construct(m,[],Q)}else{try{Q.call()}catch(B){Z=B}m.call(Q.prototype)}}else{try{throw Error()}catch(B){Z=B}m()}}catch(B){if(B&&Z&&typeof B.stack=="string"){for(var $=B.stack.split(`
4033
- `),p=Z.stack.split(`
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 M=`
4035
- `+$[y].replace(" at new "," at ");return m.displayName&&M.includes("<anonymous>")&&(M=M.replace("<anonymous>",m.displayName)),typeof m=="function"&&tt.set(m,M),M}while(y>=1&&_>=0);break}}}finally{ht=!1,de.current=oe,ut(),Error.prepareStackTrace=ie}var k=m?m.displayName||m.name:"",R=k?ke(k):"";return typeof m=="function"&&tt.set(m,R),R}function Dt(m,I,N){return _t(m,!1)}function Rr(m){var I=m.prototype;return!!(I&&I.isReactComponent)}function ft(m,I,N){if(m==null)return"";if(typeof m=="function")return _t(m,Rr(m));if(typeof m=="string")return ke(m);switch(m){case u:return ke("Suspense");case d:return ke("SuspenseList")}if(typeof m=="object")switch(m.$$typeof){case c:return Dt(m.render);case h:return ft(m.type,I,N);case l:{var Z=m,ie=Z._payload,oe=Z._init;try{return ft(oe(ie),I,N)}catch{}}}return""}var rt=Object.prototype.hasOwnProperty,Qt={},Jt=x.ReactDebugCurrentFrame;function xt(m){if(m){var I=m._owner,N=ft(m.type,m._source,I?I.type:null);Jt.setExtraStackFrame(N)}else Jt.setExtraStackFrame(null)}function Qr(m,I,N,Z,ie){{var oe=Function.call.bind(rt);for(var Q in m)if(oe(m,Q)){var $=void 0;try{if(typeof m[Q]!="function"){var p=Error((Z||"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](I,Q,Z,N,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(y){$=y}$&&!($ instanceof Error)&&(xt(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).",Z||"React class",N,Q,typeof $),xt(null)),$ instanceof Error&&!($.message in Qt)&&(Qt[$.message]=!0,xt(ie),w("Failed %s type: %s",N,$.message),xt(null))}}}var Jr=Array.isArray;function Rt(m){return Jr(m)}function Ht(m){{var I=typeof Symbol=="function"&&Symbol.toStringTag,N=I&&m[Symbol.toStringTag]||m.constructor.name||"Object";return N}}function Hr(m){try{return Ft(m),!1}catch{return!0}}function Ft(m){return""+m}function er(m){if(Hr(m))return w("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",Ht(m)),Ft(m)}var tr=x.ReactCurrentOwner,Fr={key:!0,ref:!0,__self:!0,__source:!0},Tt,rr;function en(m){if(rt.call(m,"ref")){var I=Object.getOwnPropertyDescriptor(m,"ref").get;if(I&&I.isReactWarning)return!1}return m.ref!==void 0}function tn(m){if(rt.call(m,"key")){var I=Object.getOwnPropertyDescriptor(m,"key").get;if(I&&I.isReactWarning)return!1}return m.key!==void 0}function Ge(m,I){typeof m.ref=="string"&&tr.current}function je(m,I){{var N=function(){Tt||(Tt=!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)",I))};N.isReactWarning=!0,Object.defineProperty(m,"key",{get:N,configurable:!0})}}function Or(m,I){{var N=function(){rr||(rr=!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)",I))};N.isReactWarning=!0,Object.defineProperty(m,"ref",{get:N,configurable:!0})}}var dt=function(m,I,N,Z,ie,oe,Q){var $={$$typeof:e,type:m,key:I,ref:N,props:Q,_owner:oe};return $._store={},Object.defineProperty($._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty($,"_self",{configurable:!1,enumerable:!1,writable:!1,value:Z}),Object.defineProperty($,"_source",{configurable:!1,enumerable:!1,writable:!1,value:ie}),Object.freeze&&(Object.freeze($.props),Object.freeze($)),$};function Ve(m,I,N,Z,ie){{var oe,Q={},$=null,p=null;N!==void 0&&(er(N),$=""+N),tn(I)&&(er(I.key),$=""+I.key),en(I)&&(p=I.ref,Ge(I,ie));for(oe in I)rt.call(I,oe)&&!Fr.hasOwnProperty(oe)&&(Q[oe]=I[oe]);if(m&&m.defaultProps){var y=m.defaultProps;for(oe in y)Q[oe]===void 0&&(Q[oe]=y[oe])}if($||p){var _=typeof m=="function"?m.displayName||m.name||"Unknown":m;$&&je(Q,_),p&&Or(Q,_)}return dt(m,$,p,ie,Z,tr.current,Q)}}var De=x.ReactCurrentOwner,nr=x.ReactDebugCurrentFrame;function K(m){if(m){var I=m._owner,N=ft(m.type,m._source,I?I.type:null);nr.setExtraStackFrame(N)}else nr.setExtraStackFrame(null)}var nt;nt=!1;function Ot(m){return typeof m=="object"&&m!==null&&m.$$typeof===e}function ir(){{if(De.current){var m=G(De.current.type);if(m)return`
4031
+ */var yo;function lh(){return yo||(yo=1,process.env.NODE_ENV!=="production"&&function(){var s=ae,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"),u=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),h=Symbol.for("react.memo"),l=Symbol.for("react.lazy"),v=Symbol.for("react.offscreen"),x=Symbol.iterator,_="@@iterator";function g(m){if(m===null||typeof m!="object")return null;var C=x&&m[x]||m[_];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];S("error",m,N)}}function S(m,C,N){{var q=b.ReactDebugCurrentFrame,ie=q.getStackAddendum();ie!==""&&(C+="%s",N=N.concat([ie]));var oe=N.map(function(Q){return String(Q)});oe.unshift("Warning: "+C),Function.prototype.apply.call(console[m],console,oe)}}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===u||m===d||R||m===v||A||P||D||typeof m=="object"&&m!==null&&(m.$$typeof===l||m.$$typeof===h||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 u: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 h:var q=m.displayName||null;return q!==null?q:V(m.type)||"Memo";case l:{var ie=m,oe=ie._payload,Q=ie._init;try{return V(Q(oe))}catch{return null}}}return null}var U=Object.assign,H=0,ne,ge,Pe,ve,ye,Ue,_e;function Se(){}Se.__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:Se,writable:!0};Object.defineProperties(console,{info:m,log:m,warn:m,error:m,group:m,groupCollapsed:m,groupEnd:m})}H++}}function ut(){{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
+ `+ze+m}}var ht=!1,tt;{var Dt=typeof WeakMap=="function"?WeakMap:Map;tt=new Dt}function _t(m,C){if(!m||ht)return"";{var N=tt.get(m);if(N!==void 0)return N}var q;ht=!0;var ie=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var oe;oe=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
+ `),p=q.stack.split(`
4034
+ `),y=$.length-1,T=p.length-1;y>=1&&T>=0&&$[y]!==p[T];)T--;for(;y>=1&&T>=0;y--,T--)if($[y]!==p[T]){if(y!==1||T!==1)do if(y--,T--,T<0||$[y]!==p[T]){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&&T>=0);break}}}finally{ht=!1,de.current=oe,ut(),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 ft(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 u:return ke("Suspense");case d:return ke("SuspenseList")}if(typeof m=="object")switch(m.$$typeof){case c:return Rt(m.render);case h:return ft(m.type,C,N);case l:{var q=m,ie=q._payload,oe=q._init;try{return ft(oe(ie),C,N)}catch{}}}return""}var rt=Object.prototype.hasOwnProperty,Jt={},Ht=b.ReactDebugCurrentFrame;function bt(m){if(m){var C=m._owner,N=ft(m.type,m._source,C?C.type:null);Ht.setExtraStackFrame(N)}else Ht.setExtraStackFrame(null)}function Jr(m,C,N,q,ie){{var oe=Function.call.bind(rt);for(var Q in m)if(oe(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},Tt,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(){Tt||(Tt=!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 dt=function(m,C,N,q,ie,oe,Q){var $={$$typeof:e,type:m,key:C,ref:N,props:Q,_owner:oe};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 oe,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(oe in C)rt.call(C,oe)&&!Or.hasOwnProperty(oe)&&(Q[oe]=C[oe]);if(m&&m.defaultProps){var y=m.defaultProps;for(oe in y)Q[oe]===void 0&&(Q[oe]=y[oe])}if($||p){var T=typeof m=="function"?m.displayName||m.name||"Unknown":m;$&&je(Q,T),p&&Lr(Q,T)}return dt(m,$,p,ie,q,rr.current,Q)}}var De=b.ReactCurrentOwner,ir=b.ReactDebugCurrentFrame;function K(m){if(m){var C=m._owner,N=ft(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
- Check the render method of \``+m+"`."}return""}}function rn(m){return""}var sr={};function nn(m){{var I=ir();if(!I){var N=typeof m=="string"?m:m.displayName||m.name;N&&(I=`
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
 
4039
- Check the top-level render call using <`+N+">.")}return I}}function or(m,I){{if(!m._store||m._store.validated||m.key!=null)return;m._store.validated=!0;var N=nn(I);if(sr[N])return;sr[N]=!0;var Z="";m&&m._owner&&m._owner!==De.current&&(Z=" It was passed a child from "+G(m._owner.type)+"."),K(m),w('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',N,Z),K(null)}}function ar(m,I){{if(typeof m!="object")return;if(Rt(m))for(var N=0;N<m.length;N++){var Z=m[N];Ot(Z)&&or(Z,I)}else if(Ot(m))m._store&&(m._store.validated=!0);else if(m){var ie=g(m);if(typeof ie=="function"&&ie!==m.entries)for(var oe=ie.call(m),Q;!(Q=oe.next()).done;)Ot(Q.value)&&or(Q.value,I)}}}function sn(m){{var I=m.type;if(I==null||typeof I=="string")return;var N;if(typeof I=="function")N=I.propTypes;else if(typeof I=="object"&&(I.$$typeof===c||I.$$typeof===h))N=I.propTypes;else return;if(N){var Z=G(I);Qr(N,m.props,"prop",Z,m)}else if(I.PropTypes!==void 0&&!nt){nt=!0;var ie=G(I);w("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",ie||"Unknown")}typeof I.getDefaultProps=="function"&&!I.getDefaultProps.isReactClassApproved&&w("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function on(m){{for(var I=Object.keys(m.props),N=0;N<I.length;N++){var Z=I[N];if(Z!=="children"&&Z!=="key"){K(m),w("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",Z),K(null);break}}m.ref!==null&&(K(m),w("Invalid attribute `ref` supplied to `React.Fragment`."),K(null))}}var cr={};function lr(m,I,N,Z,ie,oe){{var Q=E(m);if(!Q){var $="";(m===void 0||typeof m=="object"&&m!==null&&Object.keys(m).length===0)&&($+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var p=rn();p?$+=p:$+=ir();var y;m===null?y="null":Rt(m)?y="array":m!==void 0&&m.$$typeof===e?(y="<"+(G(m.type)||"Unknown")+" />",$=" Did you accidentally export a JSX literal instead of a component?"):y=typeof m,w("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",y,$)}var _=Ve(m,I,N,ie,oe);if(_==null)return _;if(Q){var M=I.children;if(M!==void 0)if(Z)if(Rt(M)){for(var k=0;k<M.length;k++)ar(M[k],m);Object.freeze&&Object.freeze(M)}else w("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else ar(M,m)}if(rt.call(I,"key")){var R=G(m),B=Object.keys(I).filter(function(j){return j!=="key"}),q=B.length>0?"{key: someKey, "+B.join(": ..., ")+": ...}":"{key: someKey}";if(!cr[R+q]){var Y=B.length>0?"{"+B.join(": ..., ")+": ...}":"{}";w(`A props object containing a "key" prop is being spread into JSX:
4039
+ Check the top-level render call using <`+N+">.")}return C}}function ar(m,C){{if(!m._store||m._store.validated||m.key!=null)return;m._store.validated=!0;var N=sn(C);if(or[N])return;or[N]=!0;var q="";m&&m._owner&&m._owner!==De.current&&(q=" It was passed a child from "+V(m._owner.type)+"."),K(m),w('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',N,q),K(null)}}function cr(m,C){{if(typeof m!="object")return;if(Ft(m))for(var N=0;N<m.length;N++){var q=m[N];Lt(q)&&ar(q,C)}else if(Lt(m))m._store&&(m._store.validated=!0);else if(m){var ie=g(m);if(typeof ie=="function"&&ie!==m.entries)for(var oe=ie.call(m),Q;!(Q=oe.next()).done;)Lt(Q.value)&&ar(Q.value,C)}}}function on(m){{var C=m.type;if(C==null||typeof C=="string")return;var N;if(typeof C=="function")N=C.propTypes;else if(typeof C=="object"&&(C.$$typeof===c||C.$$typeof===h))N=C.propTypes;else return;if(N){var q=V(C);Jr(N,m.props,"prop",q,m)}else if(C.PropTypes!==void 0&&!nt){nt=!0;var ie=V(C);w("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",ie||"Unknown")}typeof C.getDefaultProps=="function"&&!C.getDefaultProps.isReactClassApproved&&w("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function an(m){{for(var C=Object.keys(m.props),N=0;N<C.length;N++){var q=C[N];if(q!=="children"&&q!=="key"){K(m),w("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",q),K(null);break}}m.ref!==null&&(K(m),w("Invalid attribute `ref` supplied to `React.Fragment`."),K(null))}}var lr={};function ur(m,C,N,q,ie,oe){{var Q=E(m);if(!Q){var $="";(m===void 0||typeof m=="object"&&m!==null&&Object.keys(m).length===0)&&($+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var p=nn();p?$+=p:$+=sr();var y;m===null?y="null":Ft(m)?y="array":m!==void 0&&m.$$typeof===e?(y="<"+(V(m.type)||"Unknown")+" />",$=" Did you accidentally export a JSX literal instead of a component?"):y=typeof m,w("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",y,$)}var T=Ge(m,C,N,ie,oe);if(T==null)return T;if(Q){var I=C.children;if(I!==void 0)if(q)if(Ft(I)){for(var k=0;k<I.length;k++)cr(I[k],m);Object.freeze&&Object.freeze(I)}else w("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else cr(I,m)}if(rt.call(C,"key")){var F=V(m),B=Object.keys(C).filter(function(j){return j!=="key"}),Z=B.length>0?"{key: someKey, "+B.join(": ..., ")+": ...}":"{key: someKey}";if(!lr[F+Z]){var Y=B.length>0?"{"+B.join(": ..., ")+": ...}":"{}";w(`A props object containing a "key" prop is being spread into JSX:
4040
4040
  let props = %s;
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} />`,q,R,Y,R),cr[R+q]=!0}}return m===r?on(_):sn(_),_}}function an(m,I,N){return lr(m,I,N,!0)}function cn(m,I,N){return lr(m,I,N,!1)}var Lr=cn,ln=an;Vn.Fragment=r,Vn.jsx=Lr,Vn.jsxs=ln}()),Vn}process.env.NODE_ENV==="production"?zi.exports=rh():zi.exports=nh();var ih=zi.exports;const sh=(s,e,t,r,n,o)=>{const i=performance.now(),a=()=>{const c=performance.now()-i,u=Math.min(c/n,1);s.position.lerpVectors(t,r,u),e==null||e.update(),o(),u<1&&requestAnimationFrame(a)};requestAnimationFrame(a)},go=(s,e)=>{s.quaternion.copy(e.quaternion);const t=new C.Vector3(0,0,-1).applyQuaternion(s.quaternion).normalize();s.position.copy(t.multiplyScalar(-8)),s.lookAt(new C.Vector3(0,0,0)),s.updateMatrixWorld(!0)},oh=(s,e,t)=>{const r=t.target.clone(),n=s.position.clone().sub(r).length(),o=new C.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()},ah=()=>{try{const s=document.createElement("canvas");return!!(window.WebGLRenderingContext&&(s.getContext("webgl")||s.getContext("experimental-webgl")))}catch{return!1}},ch=()=>ah()?new C.WebGLRenderer({alpha:!0,antialias:!1}):(console.error("WebGL is not supported in this environment."),null),vo={type:"change"},Ei={type:"start"},yo={type:"end"},Gn=new f.Ray,bo=new f.Plane,lh=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},Ui=1e-6;class uh 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=fh.bind(this),this._onPointerDown=hh.bind(this),this._onPointerUp=dh.bind(this),this._onContextMenu=xh.bind(this),this._onMouseWheel=gh.bind(this),this._onKeyDown=vh.bind(this),this._onTouchStart=yh.bind(this),this._onTouchMove=bh.bind(this),this._onMouseDown=ph.bind(this),this._onMouseMove=mh.bind(this),this._interceptControlDown=wh.bind(this),this._interceptControlUp=_h.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(vo),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 u=new f.Vector3(this._mouse.x,this._mouse.y,0);u.unproject(this.object),this.object.position.sub(u).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):(Gn.origin.copy(this.object.position),Gn.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Gn.direction))<lh?this.object.lookAt(this.target):(bo.setFromNormalAndCoplanarPoint(this.object.up,this.target),Gn.intersectPlane(bo,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)>Ui||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Ui||this._lastTargetPosition.distanceToSquared(this.target)>Ui?(this.dispatchEvent(vo),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 hh(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 fh(s){this.enabled!==!1&&(s.pointerType==="touch"?this._onTouchMove(s):this._onMouseMove(s))}function dh(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(yo),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 ph(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(Ei)}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 gh(s){this.enabled===!1||this.enableZoom===!1||this.state!==we.NONE||(s.preventDefault(),this.dispatchEvent(Ei),this._handleMouseWheel(this._customWheelEvent(s)),this.dispatchEvent(yo))}function vh(s){this.enabled===!1||this.enablePan===!1||this._handleKeyDown(s)}function yh(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(Ei)}function bh(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 xh(s){this.enabled!==!1&&s.preventDefault()}function wh(s){s.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function _h(s){s.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}const Th=s=>{const e=new C.AmbientLight(16777215,1);s.add(e);const t=new C.DirectionalLight(16777215,1);t.position.set(5,10,5),s.add(t);const r=new C.DirectionalLight(16777215,1);r.position.set(-5,-10,5),s.add(r);const n=new C.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 jt=(s=>(s.FRONT="FRONT",s.BACK="BACK",s.RIGHT="RIGHT",s.LEFT="LEFT",s.TOP="TOP",s.BOTTOM="BOTTOM",s))(jt||{});new C.Vector3(0,1,0);class Sh{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 C.CanvasTexture(t);return n.needsUpdate=!0,n}}class jn{static createWireframe([e,t,r]){const n=new C.BoxGeometry(e,t,r),o=new C.EdgesGeometry(n),i=new C.LineBasicMaterial({color:pe.LINE_COLOR}),a=new C.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 C.BoxGeometry(o.x,o.y,o.z),a=new C.MeshStandardMaterial({color:pe.EDGE_COLOR}),c=new C.Mesh(i,a);return c.position.copy(e),c.name=`Edge Box ${r}`,c}static createCornerCube(e,t){const r=new C.BoxGeometry(pe.EDGE_SECTION_SIZE,pe.EDGE_SECTION_SIZE,pe.EDGE_SECTION_SIZE),n=new C.MeshStandardMaterial({color:pe.CORNER_COLOR}),o=new C.Mesh(r,n);return o.position.copy(e),o.name=`Corner Cube ${t}`,o}static createFace(e,t,r){const n=new C.Group,o=new C.BoxGeometry(pe.CUBE_SIZE-pe.EDGE_SECTION_SIZE,pe.CUBE_SIZE-pe.EDGE_SECTION_SIZE,pe.FACE_THICKNESS),i=new C.MeshStandardMaterial({color:pe.FACE_COLOR}),a=new C.Mesh(o,i);a.name=`Face Box ${r}`,n.add(a);const c=new C.PlaneGeometry(pe.CUBE_SIZE-pe.EDGE_SECTION_SIZE,pe.CUBE_SIZE-pe.EDGE_SECTION_SIZE),u=new C.MeshStandardMaterial({map:Sh.createTextTexture(r),transparent:!0,depthWrite:!1}),d=new C.Mesh(c,u);return d.position.set(0,0,pe.FACE_THICKNESS/2+.01),n.add(d),n.position.copy(e),n.rotation.copy(t),n}}const Ah=(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 C.CanvasTexture(t),o=new C.SpriteMaterial({map:n}),i=new C.Sprite(o);return i.scale.set(.5,.5,.5),i};class Mh{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 jt.BACK:return new C.Euler(0,Math.PI,0);case jt.RIGHT:return new C.Euler(0,-Math.PI/2,0);case jt.LEFT:return new C.Euler(0,Math.PI/2,0);case jt.TOP:return new C.Euler(Math.PI/2,0,0);case jt.BOTTOM:return new C.Euler(-Math.PI/2,0,0);case jt.FRONT:default:return new C.Euler(0,0,0)}}createWireframe(){const e=pe.CUBE_SIZE+pe.EDGE_SECTION_SIZE,t=jn.createWireframe([e,e,e]);return t.userData.gizmoCube=this,t}createEdgeBox(e,t,r){const n=jn.createEdgeBox(e,t,r);return n.userData.gizmoCube=this,n}createCornerCube(e,t){const r=jn.createCornerCube(e,t);return r.userData.gizmoCube=this,r}createFace(e,t,r){const n=jn.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 C.Vector3(0,t,-t)},{axis:"x",pos:new C.Vector3(0,t,t)},{axis:"x",pos:new C.Vector3(0,-t,-t)},{axis:"x",pos:new C.Vector3(0,-t,t)},{axis:"y",pos:new C.Vector3(t,0,-t)},{axis:"y",pos:new C.Vector3(t,0,t)},{axis:"y",pos:new C.Vector3(-t,0,-t)},{axis:"y",pos:new C.Vector3(-t,0,t)},{axis:"z",pos:new C.Vector3(t,t,0)},{axis:"z",pos:new C.Vector3(t,-t,0)},{axis:"z",pos:new C.Vector3(-t,t,0)},{axis:"z",pos:new C.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 C.Vector3(-t,-t,-t),new C.Vector3(-t,-t,t),new C.Vector3(-t,t,-t),new C.Vector3(-t,t,t),new C.Vector3(t,-t,-t),new C.Vector3(t,-t,t),new C.Vector3(t,t,-t),new C.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 C.Vector3(0,0,t),rotation:new C.Euler(0,0,0),label:"FRONT"},{pos:new C.Vector3(0,0,-t),rotation:new C.Euler(0,Math.PI,0),label:"BACK"},{pos:new C.Vector3(t,0,0),rotation:new C.Euler(0,Math.PI/2,0),label:"RIGHT"},{pos:new C.Vector3(-t,0,0),rotation:new C.Euler(0,-Math.PI/2,0),label:"LEFT"},{pos:new C.Vector3(0,t,0),rotation:new C.Euler(-Math.PI/2,0,0),label:"TOP"},{pos:new C.Vector3(0,-t,0),rotation:new C.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 C.Group,u=i/2,d=new C.CylinderGeometry(u,u,n,32),h=new C.MeshBasicMaterial({color:t}),l=new C.Mesh(d,h);if(l.position.copy(o).add(r.clone().multiplyScalar(n/2)),!r.equals(new C.Vector3(0,1,0))){const b=new C.Vector3(0,1,0).cross(r).normalize(),T=Math.acos(new C.Vector3(0,1,0).dot(r));l.setRotationFromAxisAngle(b,T)}c.add(l);const v=Ah(a,t);return v.position.copy(o).add(r.clone().multiplyScalar(n+.1)),c.add(v),c}createCoordinateAxes(){const e=new C.Group,t=pe.CUBE_SIZE,r=pe.EDGE_SECTION_SIZE,n=-1.075,o=a=>{const c=new C.Vector3(1,1,1);return new C.Vector3(a,a,a).add(c.clone().normalize().negate().multiplyScalar(.04))},i=t+1.25*r;return[{color:16711680,direction:new C.Vector3(1,0,0),length:i,origin:o(n),lineWidth:.04,label:"X"},{color:65280,direction:new C.Vector3(0,1,0),length:i,origin:o(n),lineWidth:.04,label:"Y"},{color:255,direction:new C.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 C.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 C.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 C.Vector3;e=this.hoveredObject.getWorldPosition(e).clone();const t=new C.Vector3(0,0,0),r=e.sub(t).normalize();this.hoveredObject.userData.vectorToCube=r}}}class Ih{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 uh(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 Mh({initialFace:((e=this.options)==null?void 0:e.initialFace)??jt.FRONT}).create();t&&this.gizmoScene.add(t),Th(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 Ch=(s,e)=>{let t;return function(...r){t||(s.apply(this,r),t=!0,setTimeout(()=>t=!1,e))}};function xo(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 wo(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 Ph(s,e){const t=s==null?void 0:s.userData.gizmoCube;if(s&&t){t.handleClick();const r=t.vectorToCube;r&&e(r)}}const Dh=25,Rh=200;function Fh({gizmoRenderer:s,gizmoScene:e,gizmoCamera:t,alignCameraWithVector:r,gizmoControlRef:n}){const o=ae.useRef(null),i=ae.useRef(null),a=ae.useRef(new C.Raycaster).current,c=ae.useRef(new C.Vector2).current,u=ae.useCallback(Ch(l=>{if(!n.current||!s)return;xo(l,s,c);const v=wo(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/Dh),[n,s,t,e,a,c]),d=ae.useCallback(l=>{o.current=Date.now(),i.current={x:l.clientX,y:l.clientY}},[]),h=ae.useCallback(l=>{if((o.current?Date.now()-o.current:0)<Rh){xo(l,s,c);const v=wo(c,t,e,a);Ph(v,r)}o.current=null,i.current=null},[r,s,t,e,a,c]);return{onMouseDown:d,onMouseMove:u,onMouseUp:h}}const Oh=({camera:s,controls:e,className:t,render:r,options:n})=>{const o=ae.useRef(null),i=ae.useRef(new C.Scene).current,[a]=ae.useState(()=>ch()),c=30,u=1,d=.1,h=10,l=new C.PerspectiveCamera(c,u,d,h),v=ae.useRef(l).current,b=ae.useRef(null),T=ae.useCallback(()=>{a&&(r(),a.render(i,v))},[r,a,i,v]),g=ae.useCallback(A=>{if(!s||!e)return;const P=s.position.length(),D=A.clone().multiplyScalar(P);sh(s,e,s.position.clone(),D,400,T),s.lookAt(new C.Vector3(0,0,0)),s.up.set(0,1,0),e.target.set(0,0,0)},[s,e,T]),{onMouseDown:x,onMouseMove:w,onMouseUp:S}=Fh({gizmoRenderer:a,gizmoScene:i,gizmoCamera:v,alignCameraWithVector:g,gizmoControlRef:b});return ae.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:T},F={syncGizmoCameraWithMain:go,syncMainCameraWithGizmo:oh};return b.current=new Ih({gizmoParams:P,mainParams:D,syncFunctions:F,options:n}),A.addEventListener("mousedown",x),A.addEventListener("mousemove",w),A.addEventListener("mouseup",S),()=>{b.current&&(b.current.dispose(),b.current=null),A.removeEventListener("mousedown",x),A.removeEventListener("mousemove",w),A.removeEventListener("mouseup",S)}},[s,e,T,w,x,S]),ae.useEffect(()=>{s&&(go(v,s),T())},[s,T]),ih.jsx("div",{className:t?`${t}`:"gizmo-default",ref:o})},Lh=({camera:s,controls:e,render:t,placement:r="top-right",size:n=128})=>{const o=ae.useRef(null);if(ae.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 qe.jsx("div",{ref:o,className:"viewer-gizmo-container",children:qe.jsx(Oh,{camera:s,controls:i,render:t})})};class Nh extends ae.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:qe.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:qe.jsxs("div",{children:[qe.jsx("h3",{children:"Error Loading 3D Viewer"}),qe.jsx("p",{children:((e=this.state.error)==null?void 0:e.message)||"An unexpected error occurred"})]})}):this.props.children}}class _o{static toThreeObject(e){if("getThreeObject"in e&&typeof e.getThreeObject=="function")return e.getThreeObject();if(e instanceof C.Object3D)return e;const t=new C.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 C.Camera?e:new C.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 To=ae.forwardRef(({object:s,options:e={}},t)=>{var A,P;const r=ae.useRef(null),{viewer:n,isInitialized:o}=Qu(r,e),i=ae.useRef(new fn),a=ae.useRef(void 0),c=ae.useMemo(()=>{if(typeof s=="string")return s;if(s)return`object-${s.uuid||"no-uuid"}`},[s]);ae.useMemo(()=>{a.current=s},[c,s]),ae.useEffect(()=>{if(!n||!o||!a.current)return;const D=typeof a.current=="string"?a.current:new We(a.current);n.loadModel(D).then(F=>{F.ok||console.error("Failed to load model:",F.error)})},[n,o,c]);const u=ae.useMemo(()=>({"model:loaded":D=>i.current.emit("model:loaded",_o.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",_o.convertControlsChange(D)),error:D=>i.current.emit("error",D)}),[]);Ju(n,u);const d=ae.useCallback(D=>{if(D&&typeof D=="object"){const F=D;if(typeof F.getThreeScene=="function")return F.getThreeScene()}return null},[]),h=ae.useCallback(D=>{if(D&&typeof D=="object"){const F=D;if(typeof F.getThreeCamera=="function")return F.getThreeCamera()}return null},[]),l=ae.useCallback(D=>{if(D&&typeof D=="object"){const F=D;if(typeof F.getThreeRenderer=="function")return F.getThreeRenderer()}return null},[]),v=ae.useCallback(D=>{if(D&&typeof D=="object"){const F=D;if(typeof F.getThreeControls=="function")return F.getThreeControls()}return null},[]),b=n?h(n.camera):null,T=n?v(n.controls):null,g=n?l(n.renderer):null,x=ae.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,S=typeof((P=e.helpers)==null?void 0:P.gizmo)=="object"?e.helpers.gizmo:{};return ae.useImperativeHandle(t,()=>({scene:n?d(n.scene):null,camera:b,renderer:g,controls:T,events:i.current}),[n,b,g,T,d]),qe.jsx(Nh,{children:qe.jsx(Hu,{viewer:n,canvasRef:r,children:qe.jsxs("div",{style:{position:"relative",width:"100%",height:"100%"},children:[qe.jsx(th,{}),w&&o&&b&&T&&qe.jsx(Lh,{camera:b,controls:T,render:x,placement:S.placement,size:S.size})]})})})});To.displayName="SimpleViewer";const So=ae.forwardRef((s,e)=>qe.jsx(To,{ref:e,...s}));So.displayName="SimpleViewer",wt.SimpleViewer=So,wt.TypedEventEmitter=fn,wt.defaultOptions=ho,Object.defineProperty(wt,Symbol.toStringTag,{value:"Module"})});
4044
+ <%s key={someKey} {...props} />`,Z,F,Y,F),lr[F+Z]=!0}}return m===r?an(T):on(T),T}}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=ch():Ui.exports=lh();var uh=Ui.exports;const hh=(s,e,t,r,n,o)=>{const i=performance.now(),a=()=>{const c=performance.now()-i,u=Math.min(c/n,1);s.position.lerpVectors(t,r,u),e==null||e.update(),o(),u<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)},fh=(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()},dh=()=>{try{const s=document.createElement("canvas");return!!(window.WebGLRenderingContext&&(s.getContext("webgl")||s.getContext("experimental-webgl")))}catch{return!1}},ph=()=>dh()?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,mh=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 gh 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=yh.bind(this),this._onPointerDown=vh.bind(this),this._onPointerUp=xh.bind(this),this._onContextMenu=Mh.bind(this),this._onMouseWheel=_h.bind(this),this._onKeyDown=Th.bind(this),this._onTouchStart=Sh.bind(this),this._onTouchMove=Ah.bind(this),this._onMouseDown=bh.bind(this),this._onMouseMove=wh.bind(this),this._interceptControlDown=Ih.bind(this),this._interceptControlUp=Ch.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 u=new f.Vector3(this._mouse.x,this._mouse.y,0);u.unproject(this.object),this.object.position.sub(u).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))<mh?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 vh(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 yh(s){this.enabled!==!1&&(s.pointerType==="touch"?this._onTouchMove(s):this._onMouseMove(s))}function xh(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 bh(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 wh(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 _h(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 Th(s){this.enabled===!1||this.enablePan===!1||this._handleKeyDown(s)}function Sh(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 Ah(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 Mh(s){this.enabled!==!1&&s.preventDefault()}function Ih(s){s.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function Ch(s){s.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}const Ph=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 Dh{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),u=new M.MeshStandardMaterial({map:Dh.createTextTexture(r),transparent:!0,depthWrite:!1}),d=new M.Mesh(c,u);return d.position.set(0,0,pe.FACE_THICKNESS/2+.01),n.add(d),n.position.copy(e),n.rotation.copy(t),n}}const Rh=(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 Fh{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,u=i/2,d=new M.CylinderGeometry(u,u,n,32),h=new M.MeshBasicMaterial({color:t}),l=new M.Mesh(d,h);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(),_=Math.acos(new M.Vector3(0,1,0).dot(r));l.setRotationFromAxisAngle(x,_)}c.add(l);const v=Rh(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 Oh{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 gh(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 Fh({initialFace:((e=this.options)==null?void 0:e.initialFace)??Wt.FRONT}).create();t&&this.gizmoScene.add(t),Ph(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 Lh=(s,e)=>{let t;return function(...r){t||(s.apply(this,r),t=!0,setTimeout(()=>t=!1,e))}};function To(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 So(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 Nh(s,e){const t=s==null?void 0:s.userData.gizmoCube;if(s&&t){t.handleClick();const r=t.vectorToCube;r&&e(r)}}const kh=25,Bh=200;function zh({gizmoRenderer:s,gizmoScene:e,gizmoCamera:t,alignCameraWithVector:r,gizmoControlRef:n}){const o=ae.useRef(null),i=ae.useRef(null),a=ae.useRef(new M.Raycaster).current,c=ae.useRef(new M.Vector2).current,u=ae.useCallback(Lh(l=>{if(!n.current||!s)return;To(l,s,c);const v=So(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/kh),[n,s,t,e,a,c]),d=ae.useCallback(l=>{o.current=Date.now(),i.current={x:l.clientX,y:l.clientY}},[]),h=ae.useCallback(l=>{if((o.current?Date.now()-o.current:0)<Bh){To(l,s,c);const v=So(c,t,e,a);Nh(v,r)}o.current=null,i.current=null},[r,s,t,e,a,c]);return{onMouseDown:d,onMouseMove:u,onMouseUp:h}}const Eh=({camera:s,controls:e,className:t,render:r,options:n})=>{const o=ae.useRef(null),i=ae.useRef(new M.Scene).current,[a]=ae.useState(()=>ph()),c=30,u=1,d=.1,h=10,l=new M.PerspectiveCamera(c,u,d,h),v=ae.useRef(l).current,x=ae.useRef(null),_=ae.useCallback(()=>{a&&(r(),a.render(i,v))},[r,a,i,v]),g=ae.useCallback(A=>{if(!s||!e)return;const P=s.position.length(),D=A.clone().multiplyScalar(P);hh(s,e,s.position.clone(),D,400,_),s.lookAt(new M.Vector3(0,0,0)),s.up.set(0,1,0),e.target.set(0,0,0)},[s,e,_]),{onMouseDown:b,onMouseMove:w,onMouseUp:S}=zh({gizmoRenderer:a,gizmoScene:i,gizmoCamera:v,alignCameraWithVector:g,gizmoControlRef:x});return ae.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:_},R={syncGizmoCameraWithMain:xo,syncMainCameraWithGizmo:fh};return x.current=new Oh({gizmoParams:P,mainParams:D,syncFunctions:R,options:n}),A.addEventListener("mousedown",b),A.addEventListener("mousemove",w),A.addEventListener("mouseup",S),()=>{x.current&&(x.current.dispose(),x.current=null),A.removeEventListener("mousedown",b),A.removeEventListener("mousemove",w),A.removeEventListener("mouseup",S)}},[s,e,_,w,b,S]),ae.useEffect(()=>{s&&(xo(v,s),_())},[s,_]),uh.jsx("div",{className:t?`${t}`:"gizmo-default",ref:o})},Uh=({camera:s,controls:e,render:t,placement:r="top-right",size:n=128})=>{const o=ae.useRef(null);if(ae.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(Eh,{camera:s,controls:i,render:t})})};class Gh extends ae.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=ae.forwardRef(({object:s,options:e={}},t)=>{var A,P;const r=ae.useRef(null),{viewer:n,isInitialized:o}=nh(r,e),i=ae.useRef(new dn),a=ae.useRef(void 0),c=ae.useMemo(()=>{if(typeof s=="string")return s;if(s)return`object-${s.uuid||"no-uuid"}`},[s]);ae.useMemo(()=>{a.current=s},[c,s]),ae.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 u=ae.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)}),[]);ih(n,u);const d=ae.useCallback(D=>{if(D&&typeof D=="object"){const R=D;if(typeof R.getThreeScene=="function")return R.getThreeScene()}return null},[]),h=ae.useCallback(D=>{if(D&&typeof D=="object"){const R=D;if(typeof R.getThreeCamera=="function")return R.getThreeCamera()}return null},[]),l=ae.useCallback(D=>{if(D&&typeof D=="object"){const R=D;if(typeof R.getThreeRenderer=="function")return R.getThreeRenderer()}return null},[]),v=ae.useCallback(D=>{if(D&&typeof D=="object"){const R=D;if(typeof R.getThreeControls=="function")return R.getThreeControls()}return null},[]),x=n?h(n.camera):null,_=n?v(n.controls):null,g=n?l(n.renderer):null,b=ae.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,S=typeof((P=e.helpers)==null?void 0:P.gizmo)=="object"?e.helpers.gizmo:{};return ae.useImperativeHandle(t,()=>({scene:n?d(n.scene):null,camera:x,renderer:g,controls:_,events:i.current}),[n,x,g,_,d]),Ze.jsx(Gh,{children:Ze.jsx(sh,{viewer:n,canvasRef:r,children:Ze.jsxs("div",{style:{position:"relative",width:"100%",height:"100%"},children:[Ze.jsx(ah,{}),w&&o&&x&&_&&Ze.jsx(Uh,{camera:x,controls:_,render:b,placement:S.placement,size:S.size})]})})})});Mo.displayName="SimpleViewer";const Io=ae.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"})});